diff --git a/.github/release-paths.txt b/.github/release-paths.txt index e13b682..7e5ce5e 100644 --- a/.github/release-paths.txt +++ b/.github/release-paths.txt @@ -10,6 +10,8 @@ frontend/package-lock.json frontend/vite.config.ts frontend/tsconfig.json src/intellisense.ts +src/expression-catalog.ts +src/expression-language.ts scripts/build_release.py # The pure ParameterIndex engine is now imported by the shipped variant editor. diff --git a/Paramood/bridge/protocol.py b/Paramood/bridge/protocol.py index 320b265..f17ca3c 100644 --- a/Paramood/bridge/protocol.py +++ b/Paramood/bridge/protocol.py @@ -1,5 +1,11 @@ """Small transport-independent request validation layer.""" +from ..core.expressions import ( + ExpressionError, + LocalEvaluationUnsupported, + NondeterministicExpression, +) + class BridgeError(Exception): def __init__(self, code, message): @@ -58,6 +64,20 @@ def dispatch(adapter, message): 'error': {'code': exc.code, 'message': str(exc)}, 'documentId': adapter.document_id, } + except ExpressionError as exc: + code = ( + 'NONDETERMINISTIC_EXPRESSION' + if isinstance(exc, NondeterministicExpression) + else 'LOCAL_EVALUATION_UNSUPPORTED' + if isinstance(exc, LocalEvaluationUnsupported) + else 'INVALID_EXPRESSION' + ) + return { + 'requestId': request_id, + 'ok': False, + 'error': {'code': code, 'message': str(exc)}, + 'documentId': adapter.document_id, + } except Exception as exc: return { 'requestId': request_id, diff --git a/Paramood/core/builtins.py b/Paramood/core/builtins.py new file mode 100644 index 0000000..5d558e9 --- /dev/null +++ b/Paramood/core/builtins.py @@ -0,0 +1,11 @@ +"""Fusion's canonical expression metadata. No Autodesk imports are allowed here.""" + +import json +from pathlib import Path + +CATALOG = json.loads( + Path(__file__).with_name('expression_catalog.json').read_text(encoding='utf-8') +) +FUNCTIONS = {item['name']: item for item in CATALOG['functions']} +CONSTANT_NAMES = {item['name'] for item in CATALOG['constants']} +UNIT_NAMES = set(CATALOG['units']) diff --git a/Paramood/core/expression_catalog.json b/Paramood/core/expression_catalog.json new file mode 100644 index 0000000..262c116 --- /dev/null +++ b/Paramood/core/expression_catalog.json @@ -0,0 +1,644 @@ +{ + "functions": [ + { + "name": "sin", + "category": "Trigonometry", + "description": "Returns the sine of an angle.", + "signature": "sin(angle)", + "arguments": [ + { + "name": "angle", + "description": "Angle to evaluate.", + "type": "angle", + "dimension": "angle" + } + ], + "arity": 1, + "returns": "unitless", + "example": "sin(30 deg)", + "restriction": "Use explicit deg or rad units. Bare arguments use Fusion angle preferences." + }, + { + "name": "cos", + "category": "Trigonometry", + "description": "Returns the cosine of an angle.", + "signature": "cos(angle)", + "arguments": [ + { + "name": "angle", + "description": "Angle to evaluate.", + "type": "angle", + "dimension": "angle" + } + ], + "arity": 1, + "returns": "unitless", + "example": "cos(30 deg)", + "restriction": "Use explicit deg or rad units. Bare arguments use Fusion angle preferences." + }, + { + "name": "tan", + "category": "Trigonometry", + "description": "Returns the tangent of an angle.", + "signature": "tan(angle)", + "arguments": [ + { + "name": "angle", + "description": "Angle to evaluate.", + "type": "angle", + "dimension": "angle" + } + ], + "arity": 1, + "returns": "unitless", + "example": "tan(30 deg)", + "restriction": "Use explicit deg or rad units. Bare arguments use Fusion angle preferences." + }, + { + "name": "sinh", + "category": "Trigonometry", + "description": "Returns the hyperbolic sine of an angle.", + "signature": "sinh(angle)", + "arguments": [ + { + "name": "angle", + "description": "Angle to evaluate.", + "type": "angle", + "dimension": "angle" + } + ], + "arity": 1, + "returns": "unitless", + "example": "sinh(30 deg)", + "restriction": "Use explicit deg or rad units. Bare arguments use Fusion angle preferences." + }, + { + "name": "cosh", + "category": "Trigonometry", + "description": "Returns the hyperbolic cosine of an angle.", + "signature": "cosh(angle)", + "arguments": [ + { + "name": "angle", + "description": "Angle to evaluate.", + "type": "angle", + "dimension": "angle" + } + ], + "arity": 1, + "returns": "unitless", + "example": "cosh(30 deg)", + "restriction": "Use explicit deg or rad units. Bare arguments use Fusion angle preferences." + }, + { + "name": "tanh", + "category": "Trigonometry", + "description": "Returns the hyperbolic tangent of an angle.", + "signature": "tanh(angle)", + "arguments": [ + { + "name": "angle", + "description": "Angle to evaluate.", + "type": "angle", + "dimension": "angle" + } + ], + "arity": 1, + "returns": "unitless", + "example": "tanh(30 deg)", + "restriction": "Use explicit deg or rad units. Bare arguments use Fusion angle preferences." + }, + { + "name": "asin", + "category": "Trigonometry", + "description": "Returns the inverse sine as an angle.", + "signature": "asin(value)", + "arguments": [ + { + "name": "value", + "description": "Unitless input value.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "angle", + "example": "asin(0.5)", + "restriction": "-1 <= value <= 1." + }, + { + "name": "acos", + "category": "Trigonometry", + "description": "Returns the inverse cosine as an angle.", + "signature": "acos(value)", + "arguments": [ + { + "name": "value", + "description": "Unitless input value.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "angle", + "example": "acos(0.5)", + "restriction": "-1 <= value <= 1." + }, + { + "name": "atan", + "category": "Trigonometry", + "description": "Returns the inverse tangent as an angle.", + "signature": "atan(value)", + "arguments": [ + { + "name": "value", + "description": "Unitless input value.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "angle", + "example": "atan(1)", + "restriction": "" + }, + { + "name": "asinh", + "category": "Trigonometry", + "description": "Returns the inverse hyperbolic sine as an angle.", + "signature": "asinh(value)", + "arguments": [ + { + "name": "value", + "description": "Unitless input value.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "angle", + "example": "asinh(1)", + "restriction": "" + }, + { + "name": "acosh", + "category": "Trigonometry", + "description": "Returns the inverse hyperbolic cosine as an angle.", + "signature": "acosh(value)", + "arguments": [ + { + "name": "value", + "description": "Unitless input value.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "angle", + "example": "acosh(2)", + "restriction": "value >= 1." + }, + { + "name": "atanh", + "category": "Trigonometry", + "description": "Returns the inverse hyperbolic tangent as an angle.", + "signature": "atanh(value)", + "arguments": [ + { + "name": "value", + "description": "Unitless input value.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "angle", + "example": "atanh(0.5)", + "restriction": "-1 < value < 1." + }, + { + "name": "sqrt", + "category": "Mathematics", + "description": "Returns the square root.", + "signature": "sqrt(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "numeric", + "dimension": "numeric" + } + ], + "arity": 1, + "returns": "square root of input dimension", + "example": "sqrt(4)", + "restriction": "The input must be nonnegative; dimension powers must admit a square root." + }, + { + "name": "abs", + "category": "Mathematics", + "description": "Returns the absolute value.", + "signature": "abs(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "numeric", + "dimension": "numeric" + } + ], + "arity": 1, + "returns": "same as input", + "example": "abs(-5 mm)", + "restriction": "" + }, + { + "name": "floor", + "category": "Mathematics", + "description": "Rounds down to the nearest integer.", + "signature": "floor(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "unitless", + "example": "floor(-1.5)", + "restriction": "" + }, + { + "name": "ceil", + "category": "Mathematics", + "description": "Rounds up to the nearest integer.", + "signature": "ceil(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "unitless", + "example": "ceil(1.5)", + "restriction": "" + }, + { + "name": "round", + "category": "Mathematics", + "description": "Rounds to the nearest integer.", + "signature": "round(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "unitless", + "example": "round(-1.5)", + "restriction": "Halfway values round away from zero." + }, + { + "name": "sign", + "category": "Mathematics", + "description": "Returns 1 for positive input and 0 otherwise.", + "signature": "sign(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "unitless", + "example": "sign(-2)", + "restriction": "Fusion sign is not the mathematical -1/0/1 signum." + }, + { + "name": "exp", + "category": "Mathematics", + "description": "Returns e raised to the input power.", + "signature": "exp(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "unitless", + "example": "exp(2)", + "restriction": "The result must be finite." + }, + { + "name": "ln", + "category": "Mathematics", + "description": "Returns the natural logarithm.", + "signature": "ln(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "unitless", + "example": "ln(E)", + "restriction": "value > 0." + }, + { + "name": "log", + "category": "Mathematics", + "description": "Returns the base-10 logarithm.", + "signature": "log(value)", + "arguments": [ + { + "name": "value", + "description": "Value to evaluate.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 1, + "returns": "unitless", + "example": "log(100)", + "restriction": "value > 0." + }, + { + "name": "min", + "category": "Mathematics", + "description": "Returns the smaller of two values.", + "signature": "min(first; second)", + "arguments": [ + { + "name": "first", + "description": "First value.", + "type": "numeric", + "dimension": "numeric" + }, + { + "name": "second", + "description": "Second value, with the same dimension.", + "type": "same as first", + "dimension": "same as first" + } + ], + "arity": 2, + "returns": "same as input", + "example": "min(2 mm; 3 mm)", + "restriction": "Exactly two arguments; dimensions must match." + }, + { + "name": "max", + "category": "Mathematics", + "description": "Returns the larger of two values.", + "signature": "max(first; second)", + "arguments": [ + { + "name": "first", + "description": "First value.", + "type": "numeric", + "dimension": "numeric" + }, + { + "name": "second", + "description": "Second value, with the same dimension.", + "type": "same as first", + "dimension": "same as first" + } + ], + "arity": 2, + "returns": "same as input", + "example": "max(2 mm; 3 mm)", + "restriction": "Exactly two arguments; dimensions must match." + }, + { + "name": "pow", + "category": "Mathematics", + "description": "Raises a base to the specified exponent.", + "signature": "pow(base; exponent)", + "arguments": [ + { + "name": "base", + "description": "Base value.", + "type": "numeric", + "dimension": "numeric" + }, + { + "name": "exponent", + "description": "Exponent value.", + "type": "unitless", + "dimension": "unitless" + } + ], + "arity": 2, + "returns": "base dimension raised to exponent", + "example": "pow(2; 3)", + "restriction": "Fusion rounds decimal powers at the eighth decimal place. The result must be real and finite." + }, + { + "name": "random", + "category": "Mathematics", + "description": "Returns a nondeterministic unitless random value.", + "signature": "random()", + "arguments": [], + "arity": 0, + "returns": "unitless", + "example": "random()", + "restriction": "Changes when evaluated. Exact preview and batch application are unavailable; Quick Calculator uses native Fusion evaluation." + }, + { + "name": "if", + "category": "Logic", + "description": "Returns one of two expressions according to a logical condition.", + "signature": "if(condition; whenTrue; whenFalse)", + "arguments": [ + { + "name": "condition", + "description": "Logical test using comparisons, and, or, or not.", + "type": "boolean", + "dimension": "boolean" + }, + { + "name": "whenTrue", + "description": "Value when the test is true.", + "type": "any", + "dimension": "any" + }, + { + "name": "whenFalse", + "description": "Value when the test is false, with the same dimension and type.", + "type": "same as whenTrue", + "dimension": "same as whenTrue" + } + ], + "arity": 3, + "returns": "same as branches", + "example": "if(2 mm < 3 mm; 10 mm; 20 mm)", + "restriction": "Three arguments; both branches must have matching types and dimensions." + } + ], + "constants": [ + { + "name": "PI", + "description": "Ratio of circumference to diameter.", + "value": 3.141592653589793, + "unit": "", + "dimension": "unitless", + "example": "2 * PI * 5 mm" + }, + { + "name": "E", + "description": "Euler's number, the base of natural logarithms.", + "value": 2.718281828459045, + "unit": "", + "dimension": "unitless", + "example": "ln(E)" + }, + { + "name": "Gravity", + "description": "Standard gravitational acceleration at Earth's surface.", + "value": 980.665, + "unit": "cm/s^2", + "dimension": "length / time^2", + "example": "Gravity / (1 mm / s^2)" + }, + { + "name": "SpeedOfLight", + "description": "Speed of light in vacuum.", + "value": 29979245800, + "unit": "cm/s", + "dimension": "length / time", + "example": "SpeedOfLight / (1 mm / s)" + } + ], + "units": [ + "rad", + "deg", + "grad", + "rpm", + "acre", + "circular_mil", + "farad", + "coulomb", + "S", + "mho", + "dol", + "A", + "J", + "erg", + "calorie", + "Btu", + "V", + "ccs", + "cis", + "cfm", + "cmh", + "gpm", + "lph", + "N", + "dyne", + "lbforce", + "ounceforce", + "tonforce", + "Hz", + "lx", + "H", + "mm", + "cm", + "m", + "hm", + "micron", + "in", + "ft", + "yd", + "mi", + "nauticalMile", + "mil", + "cd", + "EV", + "lm", + "Wb", + "maxwell", + "T", + "gamma", + "gauss", + "oersted", + "g", + "kg", + "slug", + "lbmass", + "ouncemass", + "tonmass", + "pcs", + "W", + "hp", + "Pa", + "psi", + "psf", + "ksi", + "bar", + "atm", + "inH2O", + "ftH2O", + "mH2O", + "mmHg", + "inHg", + "ohm", + "sr", + "mps", + "fps", + "mph", + "knots", + "mmpm", + "mpm", + "inpm", + "ftpm", + "mole", + "K", + "C", + "F", + "R", + "s", + "min", + "hr", + "poise", + "l", + "gal", + "qt", + "pt", + "cup", + "fl_oz" + ], + "operators": [ + "+", + "-", + "*", + "/", + "%", + "^", + ">", + "<", + ">=", + "<=", + "==", + "<>", + "and", + "or", + "not" + ] +} diff --git a/Paramood/core/expressions.py b/Paramood/core/expressions.py index 7435928..741af8d 100644 --- a/Paramood/core/expressions.py +++ b/Paramood/core/expressions.py @@ -11,10 +11,13 @@ import re from dataclasses import dataclass from typing import ClassVar, Mapping, Tuple +from itertools import zip_longest + +from .builtins import FUNCTIONS, CONSTANT_NAMES, UNIT_NAMES from .text import decode_literal, map_code, normalize_literals, segments, split_definitions -Dimension = Tuple[int, int] # powers of length and angle +Dimension = Tuple[int, ...] # powers of length, angle, and optional time SCALAR = (0, 0) LENGTH = (1, 0) ANGLE = (0, 1) @@ -30,14 +33,25 @@ 'deg': (math.pi / 180, ANGLE), 'rad': (1.0, ANGLE), 'n': (1.0, SCALAR), + 'hm': (100000.0, LENGTH), + 'micron': (0.001, LENGTH), + 'yd': (914.4, LENGTH), + 'mi': (1609344.0, LENGTH), + 'nauticalMile': (1852000.0, LENGTH), + 'mil': (0.0254, LENGTH), + 'grad': (math.pi / 200, ANGLE), + 's': (1.0, (0, 0, 1)), + 'min': (60.0, (0, 0, 1)), + 'hr': (3600.0, (0, 0, 1)), } +_UNIT_PATTERN = '|'.join(re.escape(u) for u in sorted(UNIT_NAMES | {'n'}, key=len, reverse=True)) _LITERAL = re.compile( - r'(? 2 and result[-1] == 0: + result.pop() + return tuple(result) + + +def dimension_unit(dimension, length_unit='mm'): + """Serialize length/angle/time dimensions without inferring physical types.""" + if len(dimension) > 3: + raise LocalEvaluationUnsupported('Unsupported physical dimension') + numerator, denominator = [], [] + for unit, power in zip((length_unit, 'rad', 's'), dimension): + if power: + magnitude = abs(power) + part = unit if magnitude == 1 else unit + '^' + str(magnitude) + (numerator if power > 0 else denominator).append(part) + top = '*'.join(numerator) + return (top or '1') + '/' + '/'.join(denominator) if denominator else top + + def _assignment(item: str) -> tuple[str, str, str]: parts = item.split('=', 1) if len(parts) != 2 or not parts[1].strip(): @@ -119,8 +162,26 @@ def _tree(expression: str) -> ast.Expression: raise ExpressionError('Reserved internal identifier') def code(raw): + if ',' in raw: + raise ExpressionError('Separate function arguments with a semicolon (;)') + if '!=' in raw or '**' in raw: + raise ExpressionError('Use Fusion operators <> and ^') raw = re.sub(r'\bif\s*\(', '__if__(', raw).replace(';', ',') - return _LITERAL.sub(lambda m: '__unit__(' + m.group(1) + ',"' + m.group(2) + '")', raw) + raw = raw.replace('<>', '!=').replace('^', '**') + # A postfix unit power applies to the unit, not the coefficient: 4 mm^2. + raw = re.sub( + _LITERAL.pattern + r'\s*\*\*\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)', + lambda m: '(' + m.group(1) + '*__unit__(1,"' + m.group(2) + '")**(' + m.group(3) + '))', + raw, + ) + if re.search(r'\b(' + _UNIT_PATTERN + r')\s*\*\*\s*[A-Za-z_(]', raw): + raise LocalEvaluationUnsupported('Use pow() for nonliteral unit exponents') + raw = _LITERAL.sub(lambda m: '__unit__(' + m.group(1) + ',"' + m.group(2) + '")', raw) + return re.sub( + r'(?<=[\w)])\s+(' + _UNIT_PATTERN + r')\b(?!\s*\()', + lambda m: '*__unit__(1,"' + m.group(1) + '")', + raw, + ) source = ''.join( repr(decode_literal(raw)) if literal else code(raw) for literal, raw in segments(expression) @@ -133,14 +194,80 @@ def code(raw): def _dependencies(tree: ast.Expression) -> set[str]: names = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)} - return names - _FUNCTIONS - {'__unit__'} + calls = { + n.func.id + for n in ast.walk(tree) + if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) + } + return names - calls - CONSTANT_NAMES - set(UNITS) - {'n'} def evaluate( - expression: str, parameters: Mapping[str, Quantity | TextValue] + expression: str, + parameters: Mapping[str, Quantity | TextValue], + native_function=None, + allow_nondeterministic=False, ) -> Quantity | TextValue: """Evaluate supported operations, rejecting unknown units/functions and dimensions.""" + if len(expression) > 10000: + raise ExpressionError('Expression is too long') tree = _tree(normalize_expression(expression, parameters)) + if sum(1 for _ in ast.walk(tree)) > 2000: + raise ExpressionError('Expression is too complex') + for call in ast.walk(tree): + if ( + isinstance(call, ast.Call) + and isinstance(call.func, ast.Name) + and call.func.id in FUNCTIONS + ): + if len(call.args) != FUNCTIONS[call.func.id]['arity'] or call.keywords: + raise ExpressionError('Invalid function arguments') + # Reject random even in an unselected conditional branch: recompute is unstable. + if not allow_nondeterministic and any( + isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == 'random' + for n in ast.walk(tree) + ): + raise NondeterministicExpression( + 'random() has no stable preview. Use Quick Calculator for a native sample.' + ) + + def logical(node): + if isinstance(node, ast.BoolOp) and isinstance(node.op, (ast.And, ast.Or)): + values = [logical(value) for value in node.values] + return all(values) if isinstance(node.op, ast.And) else any(values) + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): + return not logical(node.operand) + if isinstance(node, ast.Compare) and len(node.ops) == 1: + a, b = calc(node.left), calc(node.comparators[0]) + if a.dimension != b.dimension: + raise ExpressionError('Incompatible conditional types') + comparisons = { + ast.Lt: lambda: a.value < b.value, + ast.LtE: lambda: a.value <= b.value, + ast.Gt: lambda: a.value > b.value, + ast.GtE: lambda: a.value >= b.value, + ast.Eq: lambda: a.value == b.value, + ast.NotEq: lambda: a.value != b.value, + } + compare = comparisons.get(type(node.ops[0])) + if compare: + return compare() + raise ExpressionError('Unsupported conditional expression') + + def power(a, b): + if b.dimension != SCALAR: + raise ExpressionError('Exponent must be dimensionless') + exponent = b.value + if abs(exponent) > 10000: + raise ExpressionError('Exponent is too large') + dim = [round(d * exponent, 8) for d in a.dimension] + if any(not math.isclose(d, round(d), abs_tol=1e-8) for d in dim): + raise LocalEvaluationUnsupported( + 'Fractional resulting dimensions require native Fusion evaluation' + ) + if a.value < 0 and exponent != int(exponent): + raise ExpressionError('Power must have a real result') + return Quantity(math.pow(a.value, exponent), _dimension(round(d) for d in dim)) def calc(node: ast.AST) -> Quantity | TextValue: if isinstance(node, ast.Constant) and isinstance(node.value, str): @@ -149,6 +276,21 @@ def calc(node: ast.AST) -> Quantity | TextValue: return Quantity(float(node.value)) if isinstance(node, ast.Name): if node.id not in parameters: + constants = { + 'PI': Quantity(math.pi), + 'E': Quantity(math.e), + 'Gravity': Quantity(9806.65, (1, 0, -2)), + 'SpeedOfLight': Quantity(299792458000.0, (1, 0, -1)), + } + if node.id in constants: + return constants[node.id] + if node.id in UNITS: + factor, dimension = UNITS[node.id] + return Quantity(factor, dimension) + if node.id in UNIT_NAMES: + raise LocalEvaluationUnsupported( + 'Unit requires native Fusion evaluation: ' + node.id + ) raise ExpressionError('Unknown parameter: ' + node.id) value = parameters[node.id] if isinstance(value, TextValue) and len(value.value) > MAX_TEXT_LENGTH: @@ -160,7 +302,7 @@ def calc(node: ast.AST) -> Quantity | TextValue: raise ExpressionError('Text cannot be used in numeric operations') return Quantity(q.value if isinstance(node.op, ast.UAdd) else -q.value, q.dimension) if isinstance(node, ast.BinOp) and isinstance( - node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div) + node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.Mod) ): a, b = calc(node.left), calc(node.right) if isinstance(a, TextValue) or isinstance(b, TextValue): @@ -173,6 +315,14 @@ def calc(node: ast.AST) -> Quantity | TextValue: raise ExpressionError('Text result exceeds 65536 characters') return TextValue(a.value + b.value) raise ExpressionError('Cannot mix text and numeric values') + if isinstance(node.op, ast.Pow): + return power(a, b) + if isinstance(node.op, ast.Mod): + if a.dimension != b.dimension: + raise ExpressionError('Incompatible dimensions') + if b.value == 0: + raise ExpressionError('Division by zero') + return Quantity(math.fmod(a.value, b.value), a.dimension) if isinstance(node.op, (ast.Add, ast.Sub)): if a.dimension != b.dimension: raise ExpressionError('Incompatible dimensions') @@ -181,34 +331,20 @@ def calc(node: ast.AST) -> Quantity | TextValue: a.dimension, ) sign = 1 if isinstance(node.op, ast.Mult) else -1 - dim = tuple(x + sign * y for x, y in zip(a.dimension, b.dimension)) + dim = _dimension( + x + sign * y for x, y in zip_longest(a.dimension, b.dimension, fillvalue=0) + ) if sign == -1 and b.value == 0: raise ExpressionError('Division by zero') return Quantity(a.value * b.value if sign == 1 else a.value / b.value, dim) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and not node.keywords: name = node.func.id if name == '__if__' and len(node.args) == 3: - condition = node.args[0] - if not isinstance(condition, ast.Compare) or len(condition.ops) != 1: - raise ExpressionError('Unsupported conditional expression') - left, right = calc(condition.left), calc(condition.comparators[0]) - if left.dimension != right.dimension: - raise ExpressionError('Incompatible conditional types') - comparisons = { - ast.Lt: lambda a, b: a < b, - ast.LtE: lambda a, b: a <= b, - ast.Gt: lambda a, b: a > b, - ast.GtE: lambda a, b: a >= b, - ast.Eq: lambda a, b: a == b, - ast.NotEq: lambda a, b: a != b, - } - compare = comparisons.get(type(condition.ops[0])) - if compare is None: - raise ExpressionError('Unsupported comparison') + condition = logical(node.args[0]) yes, no = calc(node.args[1]), calc(node.args[2]) if yes.dimension != no.dimension: raise ExpressionError('Conditional branches must have the same type') - return yes if compare(left.value, right.value) else no + return yes if condition else no if ( name == '__unit__' and len(node.args) == 2 @@ -216,20 +352,28 @@ def calc(node: ast.AST) -> Quantity | TextValue: ): unit = node.args[1].value if unit not in UNITS: - raise ExpressionError('Unsupported unit') + raise LocalEvaluationUnsupported( + 'Unit requires native Fusion evaluation: ' + str(unit) + ) q = calc(node.args[0]) if q.dimension != SCALAR: raise ExpressionError('Unit requires a dimensionless number') factor, dim = UNITS[unit] return Quantity(q.value * factor, dim) if name not in _FUNCTIONS: - raise ExpressionError('Unsupported function: ' + name) + raise ExpressionError('Unknown function: ' + name) args = [calc(arg) for arg in node.args] if any(isinstance(arg, TextValue) for arg in args): raise ExpressionError('Numeric functions cannot use text') - if not args or (name not in {'min', 'max'} and len(args) != 1): + if len(args) != FUNCTIONS.get(name, {}).get('arity'): raise ExpressionError('Invalid function arguments') + if name == 'random': + if native_function and allow_nondeterministic: + return native_function(name, args, SCALAR) + raise NondeterministicExpression('random() requires native Fusion evaluation') q = args[0] + if name == 'pow': + return power(q, args[1]) if name in {'min', 'max'}: if any(a.dimension != q.dimension for a in args): raise ExpressionError('Incompatible dimensions') @@ -237,24 +381,34 @@ def calc(node: ast.AST) -> Quantity | TextValue: if name == 'sqrt': if any(d % 2 for d in q.dimension) or q.value < 0: raise ExpressionError('Invalid sqrt dimension or value') - return Quantity(math.sqrt(q.value), tuple(d // 2 for d in q.dimension)) - if name in {'sin', 'cos', 'tan'}: + return Quantity(math.sqrt(q.value), _dimension(d // 2 for d in q.dimension)) + if name in {'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh'}: + if q.dimension == SCALAR: + if native_function: + return native_function(name, args, SCALAR) + raise LocalEvaluationUnsupported( + 'Bare trigonometric arguments require Fusion angle preferences' + ) if q.dimension != ANGLE: raise ExpressionError('Trigonometric functions require an angle') return Quantity(getattr(math, name)(q.value)) - if name in {'floor', 'ceil', 'round'} and q.dimension != SCALAR: + if name == 'abs': + return Quantity(abs(q.value), q.dimension) + if q.dimension != SCALAR: raise ExpressionError('Function requires a dimensionless value') - return Quantity( - getattr(math, name)(q.value) - if name in {'floor', 'ceil'} - else (round(q.value) if name == 'round' else abs(q.value)), - q.dimension, - ) + if name in {'asin', 'acos', 'atan', 'asinh', 'acosh', 'atanh'}: + return Quantity(getattr(math, name)(q.value), ANGLE) + if name == 'round': + return Quantity(math.copysign(math.floor(abs(q.value) + 0.5), q.value)) + if name == 'sign': + return Quantity(float(q.value > 0)) + method = {'ln': 'log', 'log': 'log10'}.get(name, name) + return Quantity(getattr(math, method)(q.value)) raise ExpressionError('Unsupported expression') try: result = calc(tree.body) - except (OverflowError, ValueError) as exc: + except (OverflowError, ValueError, ZeroDivisionError, RecursionError) as exc: if isinstance(exc, ExpressionError): raise raise ExpressionError('Invalid numerical result') from exc @@ -266,7 +420,11 @@ def calc(node: ast.AST) -> Quantity | TextValue: def _increment_unit( - expression: str, raw: Mapping[str, str], existing: Mapping[str, Quantity], default_unit: str + expression: str, + raw: Mapping[str, str], + existing: Mapping[str, Quantity], + default_unit: str, + native_function=None, ) -> str: """Infer the unit of a previously declared parameter for a bare increment.""" values = {name: value for name, value in existing.items() if name not in raw} @@ -282,12 +440,12 @@ def resolve(name: str) -> None: active.add(name) for dep in _dependencies(_tree(raw[name])): resolve(dep) - values[name] = evaluate(raw[name], values) + values[name] = evaluate(raw[name], values, native_function) active.remove(name) for dependency in _dependencies(_tree(expression)): resolve(dependency) - dimension = evaluate(expression, values).dimension + dimension = evaluate(expression, values, native_function).dimension if dimension == SCALAR: return '' if dimension == LENGTH: @@ -303,6 +461,7 @@ def _fold_assignments( original_exprs: Mapping[str, str], units: Mapping[str, str], default_unit: str, + native_function=None, ) -> dict[str, str]: """Fold sequential updates into one expression per parameter, without self references.""" entries = [_assignment(item) for item in split_definitions(text)] @@ -324,7 +483,7 @@ def numeric_literal(name: str, expression: str) -> str: initial[name] = numeric_literal(name, expression) raw: dict[str, str] = {} for name, operator, expression in entries: - if name in _FUNCTIONS or name in {'__unit__', 'this'}: + if name in _FUNCTIONS or name in CONSTANT_NAMES or name in {'__unit__', 'this'}: raise ExpressionError('Duplicate or reserved parameter: ' + name) expression = normalize_expression(expression, known) dependencies = _dependencies(_tree(expression)) @@ -356,11 +515,13 @@ def numeric_literal(name: str, expression: str) -> str: return raw -def plan_batch(text: str, existing: Mapping[str, Quantity], default_unit: str) -> list[Operation]: +def plan_batch( + text: str, existing: Mapping[str, Quantity], default_unit: str, native_function=None +) -> list[Operation]: """Validate the complete batch before returning dependency-ordered operations.""" if default_unit not in UNITS or UNITS[default_unit][1] != LENGTH: raise ExpressionError('Unsupported project length unit') - raw = _fold_assignments(text, existing, {}, {}, default_unit) + raw = _fold_assignments(text, existing, {}, {}, default_unit, native_function) trees = {name: _tree(expr) for name, expr in raw.items()} deps = {name: _dependencies(tree) for name, tree in trees.items()} ordered: list[str] = [] @@ -391,7 +552,7 @@ def visit(name: str) -> None: expr = raw[name] if _NUMERIC.fullmatch(expr): expr += ' ' + default_unit - value = evaluate(expr, values) + value = evaluate(expr, values, native_function) if isinstance(value, TextValue): text_size += len(value.value) if text_size > MAX_BATCH_TEXT_LENGTH: @@ -503,7 +664,7 @@ class ParameterSnapshot: def plan_batch_snapshot( - text: str, snapshot: Mapping[str, ParameterSnapshot], default_unit: str + text: str, snapshot: Mapping[str, ParameterSnapshot], default_unit: str, native_function=None ) -> list[Operation]: """Conservatively project a batch through a complete dependency snapshot. @@ -573,7 +734,7 @@ def plan_batch_snapshot( if not original_graph[name] <= item.dependencies <= closure[name]: raise ExpressionError('Mismatched snapshot dependencies: ' + name) for name, expr in original_exprs.items(): - actual = evaluate(expr, original_values) + actual = evaluate(expr, original_values, native_function) expected = snapshot[name].quantity same_value = ( actual.value == expected.value @@ -589,6 +750,7 @@ def plan_batch_snapshot( original_exprs, {name: item.unit for name, item in snapshot.items()}, default_unit, + native_function, ) graph = dict(original_graph) graph.update({name: _dependencies(_tree(expr)) for name, expr in raw.items()}) @@ -618,7 +780,7 @@ def visit(name: str) -> None: for name in ordered: if name in raw: expr = raw[name] - value = evaluate(expr, values) + value = evaluate(expr, values, native_function) if value.dimension not in (SCALAR, LENGTH, ANGLE, TEXT): raise ExpressionError('Unsupported resulting dimension') if name in snapshot and snapshot[name].quantity.dimension != value.dimension: @@ -646,7 +808,7 @@ def visit(name: str) -> None: ) ) else: - value = evaluate(original_exprs[name], values) + value = evaluate(original_exprs[name], values, native_function) if value.dimension != snapshot[name].quantity.dimension: raise ExpressionError('Dependent parameter dimension changed: ' + name) values[name] = value diff --git a/Paramood/fusion/adapter.py b/Paramood/fusion/adapter.py index db8708c..6d08b53 100644 --- a/Paramood/fusion/adapter.py +++ b/Paramood/fusion/adapter.py @@ -11,6 +11,7 @@ from ..core.expressions import ( ANGLE, + ExpressionError, LENGTH, SCALAR, TextValue, @@ -18,6 +19,7 @@ ParameterSnapshot, Quantity, dependency_closure, + dimension_unit, evaluate, normalize_expression, plan_batch, @@ -445,11 +447,17 @@ def _plan(self, text): name: item for name, item in snapshot.items() if name not in isolated } ops = plan_batch_snapshot( - text, planned_snapshot, design.fusionUnitsManager.defaultLengthUnits + text, + planned_snapshot, + design.fusionUnitsManager.defaultLengthUnits, + self._native_function(design), ) else: ops = plan_batch( - text, self._quantities(design), design.fusionUnitsManager.defaultLengthUnits + text, + self._quantities(design), + design.fusionUnitsManager.defaultLengthUnits, + self._native_function(design), ) for op in ops: if op.status != 'New': @@ -514,6 +522,25 @@ def _execute_new_batch(self, design, ops): self._verify_value(created, op) return {'created': created_names, 'updated': updated_names} + def _native_function(self, design): + """Evaluate preference-sensitive calls only on an explicit bridge request.""" + + def evaluate_call(name, arguments, dimension): + # This callback currently handles unitless arguments and unitless results. + # It never creates temporary parameters or changes the active document. + if dimension != SCALAR or any(arg.dimension != SCALAR for arg in arguments): + raise ExpressionError('Unsupported native function dimension') + expression = name + '(' + ';'.join(format(arg.value, '.17g') for arg in arguments) + ')' + manager = design.fusionUnitsManager + if not manager.isValidExpression(expression, ''): + raise ExpressionError('Fusion cannot validate function: ' + name) + value = manager.evaluateExpression(expression, '') + if not math.isfinite(value): + raise ExpressionError('Fusion returned a non-finite result') + return Quantity(value, dimension) + + return evaluate_call + def _verify_value(self, parameter, op): unit = parameter.unit if isinstance(op.quantity, TextValue): @@ -850,16 +877,19 @@ def request(self, action, payload): raise BridgeError('BAD_REQUEST', 'Expression is missing or too long.') quantities = self._quantities(design) expression = normalize_expression(expression, quantities) - quantity = evaluate(expression, quantities) + quantity = evaluate( + expression, quantities, self._native_function(design), allow_nondeterministic=True + ) if isinstance(quantity, TextValue): return {'value': quantity.value, 'unit': 'Text', 'formatted': quantity.value} unit = { LENGTH: design.fusionUnitsManager.defaultLengthUnits, ANGLE: 'deg', SCALAR: '', - }.get(quantity.dimension) - if unit is None: - raise BridgeError('UNSUPPORTED', 'This result dimension is not supported yet.') + }.get( + quantity.dimension, + dimension_unit(quantity.dimension, design.fusionUnitsManager.defaultLengthUnits), + ) manager = design.fusionUnitsManager if not manager.isValidExpression(expression, unit): raise BridgeError('INVALID_EXPRESSION', 'Fusion cannot validate this expression.') @@ -868,7 +898,7 @@ def request(self, action, payload): display_value = ( value if not unit - else manager.convert(value, 'cm' if quantity.dimension == LENGTH else 'rad', unit) + else manager.convert(value, dimension_unit(quantity.dimension, 'cm'), unit) ) return {'value': display_value, 'unit': unit, 'formatted': formatted} if action == 'cleanup.analyze': diff --git a/README.md b/README.md index 796af11..4d052cd 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ This overview describes the v1.5.0 source. The [Releases page](https://github.co | --- | --- | | **Quick input** | One field for calculations and parameter assignments. Expressions without `=` are evaluated; assignments open a preview and require an explicit **Apply parameters** action. | | **Batch parameters** | Create and update parameters from semicolon-separated definitions, preserving formula references. | -| **IntelliSense** | CodeMirror completion for parameter names, nested virtual paths, and keyboard navigation. | +| **IntelliSense** | CodeMirror completion for parameters, virtual paths, all 26 Fusion functions and four constants; nested Signature Help, active arguments, and conservative diagnostics. [Expression reference](docs/EXPRESSION_REFERENCE.md). | | **Parameter browser** | A collapsible, hierarchical list of named parameters and Fusion-generated model parameters, with displayed values and units. | | **Inline editing** | Click a value to edit with IntelliSense. Press **Enter** to validate and apply or **Escape** to cancel. | | **Naming and dependencies** | Click an editable parameter name to rename it. A model value such as `20 (d_min)` shows its expression; driven sketch dimensions are displayed in parentheses and are read-only. | diff --git a/docs/EXPRESSION_ACCEPTANCE.md b/docs/EXPRESSION_ACCEPTANCE.md new file mode 100644 index 0000000..6ff7188 --- /dev/null +++ b/docs/EXPRESSION_ACCEPTANCE.md @@ -0,0 +1,34 @@ +# Expression IntelliSense acceptance + +Date: 2026-11-08. Native platform: macOS, Autodesk Fusion 2706.1.17. + +## Native numerical and adapter checks + +An isolated copy of the new modules ran on Fusion's main thread in a dedicated temporary design. Existing user documents were preserved and the original document was restored afterward. + +- Catalog-driven batch Preview produced no model writes; Apply created 29 parameters: examples for all 25 deterministic functions and all four constants. +- All 25 function results matched the local planner within `1e-9` relative/absolute tolerance, after converting Fusion's internal cm to the planner's mm where required. +- Existing-parameter update, relative addition, `this`, virtual paths, and a dependent conditional parameter passed. +- Quick Calculator evaluated all 25 deterministic function examples, two preference-sensitive bare trigonometric calls through the native fallback, one native `random()` sample, and both physical constants as derived calculator quantities. +- Stable random-dependent Preview was rejected with `NONDETERMINISTIC_EXPRESSION`. +- A local F3D export was reopened through Fusion's archive importer: all 31 parameters retained units and values; the saved variant retained its identity. This is a native archive round trip, not a cloud Save test. + +The native script used actual `FusionUnitsManager`, `UserParameters`, `Design.modifyParameters`, export/import, and the new Fusion adapter. These checks were not mock tests. Windows Fusion and cloud document save/reopen were not exercised. + +## Native palette checks + +The production frontend from an installed test ZIP was loaded in an isolated 361-pixel-wide Fusion Palette with the new adapter and a temporary document. The installed user add-in was not stopped or restarted. + +- Selecting `pow` inserted parentheses and placed the cursor inside. +- Typing `probe=pow(2; max(` displayed the nested `max(first; second)` signature. After `3; `, `second` was emphasized. Closing `max` restored `pow(base; exponent)` with `exponent` emphasized; closing `pow` hid Signature Help. +- Dark-theme text contrast and narrow-width wrapping were visually checked after correcting a native-only tooltip styling conflict. +- Incomplete calls produced no automatic native Preview requests after the draft guard was added. +- The completed expression previewed as `16`, and clicking Apply created the actual Fusion parameter with value `16`. +- Inline editing to `PI * 2` displayed the constant color and committed the value `6.283185307179586`; this value was read back through the Fusion API. +- The test palette and test document were closed, and the original document was restored. + +Full add-in stop/restart, Windows UI, light-theme native rendering, and cloud Save were not tested. The previously reported restart crash is outside this change. + +## Automated validation + +Local macOS checks passed: 379 Python tests plus 22 subtests, 160 frontend tests, and 47 standalone IntelliSense tests. Ruff 0.17.3 formatting/lint, Prettier, ESLint, TypeScript, Vite production build, Python compilation, deterministic ZIP tests, embedded catalog checks, and the stable release archive contract passed. CI is evaluated separately on the PR and on the merge commit. diff --git a/docs/EXPRESSION_REFERENCE.md b/docs/EXPRESSION_REFERENCE.md new file mode 100644 index 0000000..538cef5 --- /dev/null +++ b/docs/EXPRESSION_REFERENCE.md @@ -0,0 +1,423 @@ +# Fusion expression reference + +Paramood uses the case-sensitive Autodesk Fusion expression language. This reference and the editor share the metadata in `Paramood/core/expression_catalog.json`. + +## Functions + +Arguments are separated with **semicolons**, never commas. Functions insert parentheses and place the cursor inside; existing opening parentheses are reused. + +### `sin(angle)` + +Returns the sine of an angle. + +Category: Trigonometry. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `angle` | angle | Angle to evaluate. | + +Example: `sin(30 deg)`. + +Use explicit deg or rad units. Bare arguments use Fusion angle preferences. + +### `cos(angle)` + +Returns the cosine of an angle. + +Category: Trigonometry. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `angle` | angle | Angle to evaluate. | + +Example: `cos(30 deg)`. + +Use explicit deg or rad units. Bare arguments use Fusion angle preferences. + +### `tan(angle)` + +Returns the tangent of an angle. + +Category: Trigonometry. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `angle` | angle | Angle to evaluate. | + +Example: `tan(30 deg)`. + +Use explicit deg or rad units. Bare arguments use Fusion angle preferences. + +### `sinh(angle)` + +Returns the hyperbolic sine of an angle. + +Category: Trigonometry. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `angle` | angle | Angle to evaluate. | + +Example: `sinh(30 deg)`. + +Use explicit deg or rad units. Bare arguments use Fusion angle preferences. + +### `cosh(angle)` + +Returns the hyperbolic cosine of an angle. + +Category: Trigonometry. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `angle` | angle | Angle to evaluate. | + +Example: `cosh(30 deg)`. + +Use explicit deg or rad units. Bare arguments use Fusion angle preferences. + +### `tanh(angle)` + +Returns the hyperbolic tangent of an angle. + +Category: Trigonometry. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `angle` | angle | Angle to evaluate. | + +Example: `tanh(30 deg)`. + +Use explicit deg or rad units. Bare arguments use Fusion angle preferences. + +### `asin(value)` + +Returns the inverse sine as an angle. + +Category: Trigonometry. Returns: angle. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Unitless input value. | + +Example: `asin(0.5)`. + +-1 <= value <= 1. + +### `acos(value)` + +Returns the inverse cosine as an angle. + +Category: Trigonometry. Returns: angle. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Unitless input value. | + +Example: `acos(0.5)`. + +-1 <= value <= 1. + +### `atan(value)` + +Returns the inverse tangent as an angle. + +Category: Trigonometry. Returns: angle. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Unitless input value. | + +Example: `atan(1)`. + +### `asinh(value)` + +Returns the inverse hyperbolic sine as an angle. + +Category: Trigonometry. Returns: angle. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Unitless input value. | + +Example: `asinh(1)`. + +### `acosh(value)` + +Returns the inverse hyperbolic cosine as an angle. + +Category: Trigonometry. Returns: angle. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Unitless input value. | + +Example: `acosh(2)`. + +value >= 1. + +### `atanh(value)` + +Returns the inverse hyperbolic tangent as an angle. + +Category: Trigonometry. Returns: angle. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Unitless input value. | + +Example: `atanh(0.5)`. + +-1 < value < 1. + +### `sqrt(value)` + +Returns the square root. + +Category: Mathematics. Returns: square root of input dimension. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | numeric | Value to evaluate. | + +Example: `sqrt(4)`. + +The input must be nonnegative; dimension powers must admit a square root. + +### `abs(value)` + +Returns the absolute value. + +Category: Mathematics. Returns: same as input. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | numeric | Value to evaluate. | + +Example: `abs(-5 mm)`. + +### `floor(value)` + +Rounds down to the nearest integer. + +Category: Mathematics. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Value to evaluate. | + +Example: `floor(-1.5)`. + +### `ceil(value)` + +Rounds up to the nearest integer. + +Category: Mathematics. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Value to evaluate. | + +Example: `ceil(1.5)`. + +### `round(value)` + +Rounds to the nearest integer. + +Category: Mathematics. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Value to evaluate. | + +Example: `round(-1.5)`. + +Halfway values round away from zero. + +### `sign(value)` + +Returns 1 for positive input and 0 otherwise. + +Category: Mathematics. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Value to evaluate. | + +Example: `sign(-2)`. + +Fusion sign is not the mathematical -1/0/1 signum. + +### `exp(value)` + +Returns e raised to the input power. + +Category: Mathematics. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Value to evaluate. | + +Example: `exp(2)`. + +The result must be finite. + +### `ln(value)` + +Returns the natural logarithm. + +Category: Mathematics. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Value to evaluate. | + +Example: `ln(E)`. + +value > 0. + +### `log(value)` + +Returns the base-10 logarithm. + +Category: Mathematics. Returns: unitless. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `value` | unitless | Value to evaluate. | + +Example: `log(100)`. + +value > 0. + +### `min(first; second)` + +Returns the smaller of two values. + +Category: Mathematics. Returns: same as input. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `first` | numeric | First value. | +| `second` | same as first | Second value, with the same dimension. | + +Example: `min(2 mm; 3 mm)`. + +Exactly two arguments; dimensions must match. + +### `max(first; second)` + +Returns the larger of two values. + +Category: Mathematics. Returns: same as input. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `first` | numeric | First value. | +| `second` | same as first | Second value, with the same dimension. | + +Example: `max(2 mm; 3 mm)`. + +Exactly two arguments; dimensions must match. + +### `pow(base; exponent)` + +Raises a base to the specified exponent. + +Category: Mathematics. Returns: base dimension raised to exponent. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `base` | numeric | Base value. | +| `exponent` | unitless | Exponent value. | + +Example: `pow(2; 3)`. + +Fusion rounds decimal powers at the eighth decimal place. The result must be real and finite. + +### `random()` + +Returns a nondeterministic unitless random value. + +Category: Mathematics. Returns: unitless. + +Example: `random()`. + +Changes when evaluated. Exact preview and batch application are unavailable; Quick Calculator uses native Fusion evaluation. + +### `if(condition; whenTrue; whenFalse)` + +Returns one of two expressions according to a logical condition. + +Category: Logic. Returns: same as branches. + +| Argument | Type / dimension | Description | +| --- | --- | --- | +| `condition` | boolean | Logical test using comparisons, and, or, or not. | +| `whenTrue` | any | Value when the test is true. | +| `whenFalse` | same as whenTrue | Value when the test is false, with the same dimension and type. | + +Example: `if(2 mm < 3 mm; 10 mm; 20 mm)`. + +Three arguments; both branches must have matching types and dimensions. + +## Constants + +Names are case-sensitive. Constants are values, not callable functions. Their dedicated color distinguishes them from parameters and functions. + +| Name | Value | Unit / dimension | Example | +| --- | --- | --- | --- | +| `PI` | 3.141592653589793 | unitless | `2 * PI * 5 mm` | +| `E` | 2.718281828459045 | unitless | `ln(E)` | +| `Gravity` | 980.665 | cm/s^2 | `Gravity / (1 mm / s^2)` | +| `SpeedOfLight` | 29979245800 | cm/s | `SpeedOfLight / (1 mm / s)` | + +## Operators + +Arithmetic: `+`, `-`, `*`, `/`, `%`, `^`. Exponentiation is right-associative and precedes unary minus: `-2^2` is `-4`; `2^3^2` is `512`. Modulo follows the dividend sign: `-7 % 3` is `-1`. + +Inside `if` conditions: `>`, `<`, `>=`, `<=`, `==`, `<>`, `and`, `or`, `not`. Use parentheses to group logical expressions. Python-style `!=` and `**` are not Fusion operators. + +## Units and dimensions + +The editor recognizes these abbreviations from the Autodesk unit reference: + +`rad`, `deg`, `grad`, `rpm`, `acre`, `circular_mil`, `farad`, `coulomb`, `S`, `mho`, `dol`, `A`, `J`, `erg`, `calorie`, `Btu`, `V`, `ccs`, `cis`, `cfm`, `cmh`, `gpm`, `lph`, `N`, `dyne`, `lbforce`, `ounceforce`, `tonforce`, `Hz`, `lx`, `H`, `mm`, `cm`, `m`, `hm`, `micron`, `in`, `ft`, `yd`, `mi`, `nauticalMile`, `mil`, `cd`, `EV`, `lm`, `Wb`, `maxwell`, `T`, `gamma`, `gauss`, `oersted`, `g`, `kg`, `slug`, `lbmass`, `ouncemass`, `tonmass`, `pcs`, `W`, `hp`, `Pa`, `psi`, `psf`, `ksi`, `bar`, `atm`, `inH2O`, `ftH2O`, `mH2O`, `mmHg`, `inHg`, `ohm`, `sr`, `mps`, `fps`, `mph`, `knots`, `mmpm`, `mpm`, `inpm`, `ftpm`, `mole`, `K`, `C`, `F`, `R`, `s`, `min`, `hr`, `poise`, `l`, `gal`, `qt`, `pt`, `cup`, `fl_oz`. + +The local planner supports all documented length units (`mm`, `cm`, `m`, `hm`, `micron`, `in`, `ft`, `yd`, `mi`, `nauticalMile`, `mil`), angle units (`deg`, `rad`, `grad`), unitless values, and text. Time units (`s`, `min`, `hr`) and the physical constants can participate in intermediate expressions. For example, `Gravity / (1 mm / s^2)` returns the unitless value `9806.65`. Quick Calculator can also display derived length/angle/time quantities such as `Gravity` and `SpeedOfLight`. Final batch outputs remain length, angle, unitless, or text; mass, temperature, other physical quantities, and fractional resulting dimensions require further planner support. Recognizing a Fusion unit in the editor does not assert local support for every physical quantity. + +`n` is a Paramood-only suffix for a unitless numeric literal, such as `count=5n`; it is removed before sending the expression to Fusion. Use explicit units for trigonometric arguments. Bare angle arguments use native Fusion preferences on an explicit Preview or Calculate request; no Fusion API calls occur while typing. + +## Signature Help and diagnostics + +Typing `(` opens the function signature. The current argument is emphasized; `;` advances it. Nested calls, grouped expressions, cursor movement, and editing existing formulas update the signature. Closing a nested call restores the outer signature. Descriptions, argument dimensions, restrictions, return types, and examples fit a narrow palette and scroll when necessary. + +Confirmed errors receive a wavy underline and an English explanation on hover: unknown calls and completed parameter references, unknown unit abbreviations, wrong argument counts, clearly incompatible argument dimensions, commas, invalid operators, extra closing parentheses, and calling a constant. Missing trailing arguments, opening parentheses, strings, and identifier prefixes are treated as unfinished input. Dimension diagnostics intentionally cover only expressions whose types can be established locally; Preview and Apply remain the authoritative full validation steps. An unclosed opening parenthesis is reported by Preview rather than while typing. + +## Safety and native validation + +The planner preserves dependencies and rejects cycles, invalid arithmetic, incompatible parameter types, stale previews, and unsupported syntax. Unsupported local evaluation is returned as `LOCAL_EVALUATION_UNSUPPORTED`, distinct from `INVALID_EXPRESSION`. Preference-dependent bare trigonometric calls have a narrow read-only native fallback on explicit requests. Unsupported physical units and ambiguous dimensions fail closed without creating temporary parameters or claiming a result. + +`random()` is offered with its nondeterministic restriction. Quick Calculator evaluates a fresh native sample. A stable batch Preview or Apply is rejected with `NONDETERMINISTIC_EXPRESSION`, even if the call occurs in an unselected branch. Existing random-dependent snapshots cannot be certified as stable. No arbitrary local random sample is ever treated as a verified preview. + +Fusion validates each numeric expression again before mutation and the adapter compares the resulting value with the plan. Local safety limits are 10,000 expression characters, 2,000 AST nodes, and absolute exponents up to 10,000. Both conditional branches must have compatible types and be evaluable; an unused invalid branch is not silently accepted. + +## Keyboard shortcuts + +| Key | Action | +| --- | --- | +| Ctrl+Space | Open completion explicitly | +| Up / Down | Select a completion | +| Tab / Enter | Accept the selected completion | +| Escape | Close completion; cancel an inline edit when completion is closed | +| Enter without completion | Submit the expression / preview | +| Shift+Enter | Insert a line break in multiline editors | + +## Sources and verification + +- [Autodesk Parameters reference](https://help.autodesk.com/cloudhelp/ENU/Fusion-Model/files/GUID-76272551-3275-46C4-AE4D-10D58B408C20.htm) +- [Autodesk Unit types](https://help.autodesk.com/cloudhelp/ENU/Fusion-Model/files/DSN-REF-PARAMETERS-UNITS.htm) +- [FusionUnitsManager](https://autodeskfusion360.github.io/FusionAPIReference/Fusion_API_Documentation/files/FusionUnitsManager.htm) +- [CodeMirror tooltip API](https://codemirror.net/docs/ref/#view.showTooltip) + +The Autodesk reference contains loose type descriptions for `sign` and `exp`; Paramood documents their observed numeric behavior. `sign(-2)=0`, `sign(0)=0`, halfway rounding away from zero, two-argument min/max, and angle-valued inverse hyperbolic functions were checked in Fusion 2706.1.17 on macOS. See [native acceptance evidence](EXPRESSION_ACCEPTANCE.md). diff --git a/docs/INTELLISENSE.md b/docs/INTELLISENSE.md index df8c057..7aacfb4 100644 --- a/docs/INTELLISENSE.md +++ b/docs/INTELLISENSE.md @@ -33,3 +33,7 @@ The variant search accepts one existing-parameter assignment such as `box.width= Run root `npm test` for the standalone index and `npm test --prefix frontend` for palette integration tests. These automated checks do not establish native Fusion or Windows behavior. [Russian details](INTELLISENSE.ru.md) + +## Fusion builtins and Signature Help + +All 26 documented Fusion functions and four mathematical/physical constants have shared metadata, descriptions, examples, argument signatures, completion, and dedicated highlighting. Signature Help tracks nested calls and the active argument without querying Fusion while typing. Confirmed syntax and simple dimension errors are underlined; unfinished input stays editable. See the [full expression reference](EXPRESSION_REFERENCE.md) for functions, constants, units, shortcuts, and planner restrictions. diff --git a/docs/releases/1.6.0.md b/docs/releases/1.6.0.md new file mode 100644 index 0000000..ee78c04 --- /dev/null +++ b/docs/releases/1.6.0.md @@ -0,0 +1,20 @@ +## Paramood 1.6.0 + +### Expression IntelliSense + +- Complete all 26 documented Fusion functions and `PI`, `E`, `Gravity`, and `SpeedOfLight` from one typed metadata catalog shared with the Python planner. +- Show English descriptions, signatures, argument types, return dimensions, restrictions, and examples. Reuse existing parentheses and place the cursor inside the call. +- Add nested Signature Help with active-argument emphasis, cursor tracking, and a readable, scrolling tooltip in narrow Fusion palettes. +- Distinguish functions, constants, parameters, batch declarations, units, strings, numbers, operators, unknown names, and confirmed errors. Preserve parameter hierarchies, model dimensions, inline edits, and batch context after function argument separators. +- Diagnose unknown calls, wrong argument counts, simple dimension mismatches, commas, invalid operators, extra closing parentheses, and calling constants. Defer automatic native validation for incomplete calls and known identifier prefixes. +- Extend local evaluation with inverse/hyperbolic functions, logarithms, exponentials, powers, modulo, constants, time intermediates, comparisons, and logical conditions. Match Fusion's two-argument min/max, positive-only sign, and rounding halfway away from zero. Use native Fusion preferences for bare trigonometric arguments. +- Evaluate `random()` through native Quick Calculator. Reject random-dependent stable Preview/Apply explicitly; distinguish unsupported local evaluation from invalid expressions. +- Add the English [expression reference](https://github.com/4FusionLab/Paramood/blob/main/docs/EXPRESSION_REFERENCE.md) with functions, constants, units, shortcuts, and limitations. + +### Validation and limits + +Catalog-driven Python, IntelliSense, and CodeMirror integration tests accompany existing regressions. Ruff, Prettier, ESLint, TypeScript/Vite, deterministic ZIP, embedded catalog, and SHA-256 checks are required by CI. + +Native macOS Fusion 2706.1.17: 29 catalog-example parameters created, 25 deterministic function results compared, 30 calculator calls, relative updates, dependencies, virtual paths, and stable-random rejection passed. A local F3D round trip preserved 31 parameters and a saved variant. The installed test ZIP's frontend was visually checked in a 361-pixel Fusion Palette: nested/active signatures, dark-theme contrast, completion insertion, actual Apply (`16`), and inline constant editing (`2 * PI`) passed. Original user documents were preserved. + +Final batch quantities remain length, angle, unitless, or text. Other physical units and fractional dimensions remain explicit local-planner limitations. Dimension diagnostics intentionally cover only locally provable cases. Windows Fusion, light-theme native UI, cloud Save, and full add-in stop/restart were not tested; the previously reported restart crash is not claimed fixed. See the [acceptance record](https://github.com/4FusionLab/Paramood/blob/main/docs/EXPRESSION_ACCEPTANCE.md). diff --git a/frontend/src/editor.test.tsx b/frontend/src/editor.test.tsx index 70e1c33..4ae5aad 100644 --- a/frontend/src/editor.test.tsx +++ b/frontend/src/editor.test.tsx @@ -521,3 +521,108 @@ it('completes Cyrillic hierarchical parameter names', () => { ); expect(result?.options.map((option) => option.label)).toContain('ширина'); }); + +import { fusionFunctions, fusionConstants } from '../../src/expression-catalog'; +import { expressionSignatureHelp } from './expression-codemirror'; + +describe('Fusion builtin editor integration', () => { + it.each(fusionFunctions)( + 'completes, inserts and highlights $name from the shared catalog', + (fn) => { + const text = `probe=${fn.name.slice(0, 2)}`; + const { view } = mount({ text }); + const result = completions(new CompletionContext(view.state, text.length, true), [], true)!; + const completion = result.options.find((c) => c.label === fn.name)!; + expect(completion.detail).toBe(fn.signature); + expect(completion.info).toContain(fn.description); + expect(typeof completion.apply).toBe('function'); + const apply = completion.apply; + if (typeof apply === 'function') act(() => apply(view, completion, result.from, text.length)); + expect(view.state.doc.toString()).toBe(`probe=${fn.name}()`); + expect(view.state.selection.main.head).toBe(`probe=${fn.name}(`.length); + expect(host.querySelector('.token-function')?.textContent).toBe(fn.name); + const tooltip = view.state.field(expressionSignatureHelp)[0]; + expect(tooltip.create(view).dom.textContent).toContain(fn.description); + expect(tooltip.create(view).dom.textContent).toContain(fn.example); + }, + ); + it.each(fusionConstants)( + 'completes and highlights $name without making it an inline parameter', + (constant) => { + const text = `probe=${constant.name}`; + const { view } = mount({ text }); + const result = completions(new CompletionContext(view.state, text.length, true), [], true)!; + const option = result.options.find((c) => c.label === constant.name)!; + expect(option.type).toBe('constant'); + expect(option.info).toContain(constant.description); + expect(host.querySelector('.token-constant')?.textContent).toBe(constant.name); + }, + ); + it.each(['pow(2; 3)', 'pow (2; 3)'])('reuses the existing parenthesis in %s', (input) => { + const { view } = mount({ text: `probe=${input}` }); + const from = 6, + to = 9; + const result = completions(new CompletionContext(view.state, to, true), [], true)!; + const completion = result.options.find((c) => c.label === 'pow')!; + const apply = completion.apply; + if (typeof apply === 'function') act(() => apply(view, completion, from, to)); + expect(view.state.doc.toString()).toBe(`probe=${input}`); + expect(view.state.selection.main.head).toBe(view.state.doc.toString().indexOf('(') + 1); + }); + it('keeps expression context after a semicolon inside a nested batch call', () => { + const text = 'probe=pow(2; ma'; + const options = completions( + new CompletionContext(EditorState.create({ doc: text }), text.length, false), + [], + true, + )!; + expect(options.options.map((c) => c.label)).toContain('max'); + }); + it.each(['po', 'probe=po'])( + 'suppresses builtins in assignment targets and strings: %s', + (text) => { + const pos = text.indexOf('=') < 0 ? text.length : 2; + const options = completions( + new CompletionContext(EditorState.create({ doc: text }), pos, true), + [], + true, + ); + expect(options?.options.some((c) => c.type === 'function')).toBe(false); + const quoted = 'probe="pow'; + expect( + completions( + new CompletionContext(EditorState.create({ doc: quoted }), quoted.length, true), + [], + true, + ), + ).toBeNull(); + }, + ); + it('updates nested signature help and active arguments when the cursor moves', () => { + const text = 'probe=pow(2; max(3; 4))'; + const { view } = mount({ text }); + const tooltipAt = (pos: number) => { + act(() => view.dispatch({ selection: { anchor: pos } })); + return view.state.field(expressionSignatureHelp)[0]?.create(view).dom; + }; + let dom = tooltipAt(text.indexOf('4'))!; + expect(dom.querySelector('.expression-signature-label')?.textContent).toBe( + 'max(first; second)', + ); + expect(dom.querySelector('strong')?.textContent).toBe('second'); + dom = tooltipAt(text.length - 1)!; + expect(dom.querySelector('strong')?.textContent).toBe('exponent'); + expect(tooltipAt(text.length)).toBeUndefined(); + }); + it('marks confirmed diagnostic ranges and preserves scientific notation', () => { + mount({ text: 'probe=pow(2, 3) + 1e-3' }); + expect( + Array.from(host.querySelectorAll('.token-error')).some((token) => + token.getAttribute('title')?.includes('semicolon'), + ), + ).toBe(true); + expect(Array.from(host.querySelectorAll('.token-number')).map((n) => n.textContent)).toContain( + '1e-3', + ); + }); +}); diff --git a/frontend/src/editor.tsx b/frontend/src/editor.tsx index 577a977..dac24fe 100644 --- a/frontend/src/editor.tsx +++ b/frontend/src/editor.tsx @@ -24,8 +24,18 @@ import { import type { Parameter } from './bridge'; import { inString } from './expression-syntax'; -const functions = ['sqrt', 'sin', 'cos', 'tan', 'abs', 'floor', 'ceil', 'round', 'min', 'max']; -const units = ['mm', 'cm', 'm', 'in', 'ft', 'deg', 'rad', 'n']; +import { + functionByName, + constantByName, + fusionUnits, + fusionOperators, +} from '../../src/expression-catalog'; +import { builtinCompletions, expressionSignatureHelp } from './expression-codemirror'; +import { + expressionTokens, + expressionDiagnostics, + statementStart, +} from '../../src/expression-language'; function declaredNames(text: string): string[] { return Array.from( text.matchAll( @@ -57,7 +67,7 @@ export function completions( if (word.from === word.to && !context.explicit && !path) return null; if (!path && /^\d/.test(word.text)) return null; const showModelDimensions = !path && /^d$/i.test(word.text); - const left = text.slice(0, context.pos).split(/[;\n]/).pop() ?? ''; + const left = text.slice(statementStart(text, context.pos), context.pos); const nameContext = batch && !left.includes('='); const target = batch && !nameContext ? assignmentTarget(left) : !batch ? currentTarget : undefined; @@ -139,19 +149,9 @@ export function completions( options.push({ label: name, type: 'variable', detail: 'In this batch' }); if (nameContext) return { from: word.from, options: [...objectOptions, ...options] }; if (targetExists) options.push({ label: 'this', type: 'variable', detail: 'Current value' }); - for (const name of functions) - options.push({ - label: name, - type: 'function', - detail: 'Function', - apply(view, _completion, from, to) { - view.dispatch({ - changes: { from, to, insert: `${name}()` }, - selection: { anchor: from + name.length + 1 }, - }); - }, - }); - for (const unit of units) options.push({ label: unit, type: 'keyword', detail: 'Unit' }); + options.push( + ...builtinCompletions().filter((item) => !parameters.some((p) => p.name === item.label)), + ); return { from: word.from, options: [...objectOptions, ...options] }; } interface Props { @@ -180,32 +180,45 @@ function highlighting( const text = view.state.doc.toString(); const declared = new Set(declaredNames(text)); const known = new Set(parameters().map((p) => p.name)); - const token = - /'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|[A-Za-zА-Яа-яЁё_][A-Za-zА-Яа-яЁё_0-9]*(?:\.[A-Za-zА-Яа-яЁё0-9]+)*|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+*/^=;()-]/g; - for (const match of text.matchAll(token)) { - const value = match[0], - from = match.index!, - rest = text.slice(from + value.length); + const diagnostics = expressionDiagnostics( + text, + new Map(parameters().map((p) => [p.name, p.unit])), + batch(), + ); + for (const token of expressionTokens(text)) { + const value = token.value, + from = token.from, + rest = text.slice(token.to); let kind = 'operator'; if (value.startsWith("'") || value.startsWith('"')) kind = 'string'; else if (/^\d|^\./.test(value)) kind = 'number'; else if (/^[A-Za-zА-Яа-яЁё_]/.test(value)) { - const left = text.slice(0, from).split(/[;\n]/).pop() ?? ''; + const left = text.slice(statementStart(text, from), from); const current = batch() ? assignmentTarget(left) : currentTarget(); - if (functions.includes(value) && /^\s*\(/.test(rest)) kind = 'function'; - else if (units.includes(value)) kind = 'unit'; + if (known.has(value.replace(/\./g, '_'))) kind = 'parameter'; + else if (functionByName.has(value) && /^\s*\(/.test(rest)) kind = 'function'; + else if (constantByName.has(value)) kind = 'constant'; + else if (fusionOperators.includes(value)) kind = 'operator'; + else if (fusionUnits.includes(value)) kind = 'unit'; else if ( value === 'this' && current && (known.has(current) || declaredNames(text.slice(0, from - left.length)).includes(current)) ) kind = 'parameter'; - else if (known.has(value.replace(/\./g, '_'))) kind = 'parameter'; else if (declared.has(value.replace(/\./g, '_')) || (batch() && /^\s*=/.test(rest))) kind = 'new'; else kind = 'unknown'; } - ranges.push(Decoration.mark({ class: `token-${kind}` }).range(from, from + value.length)); + const diagnostic = diagnostics.find((d) => d.from === from); + ranges.push( + Decoration.mark({ + class: `token-${kind}${diagnostic ? ' token-error' : ''}`, + attributes: diagnostic + ? { title: diagnostic.message, 'aria-label': diagnostic.message } + : {}, + }).range(from, from + value.length), + ); } return Decoration.set(ranges); } @@ -244,6 +257,7 @@ export function ExpressionEditor(props: Props) { ] : []), history(), + expressionSignatureHelp, highlighting( () => latest.current.parameters, () => !!latest.current.batch, diff --git a/frontend/src/expression-codemirror.ts b/frontend/src/expression-codemirror.ts new file mode 100644 index 0000000..8e5de7b --- /dev/null +++ b/frontend/src/expression-codemirror.ts @@ -0,0 +1,98 @@ +import type { Completion } from '@codemirror/autocomplete'; +import { pickedCompletion } from '@codemirror/autocomplete'; +import { StateField } from '@codemirror/state'; +import { showTooltip, type Tooltip } from '@codemirror/view'; +import { + fusionFunctions, + fusionConstants, + fusionUnits, + fusionOperators, + functionInfo, +} from '../../src/expression-catalog.ts'; +import { signatureContext } from '../../src/expression-language.ts'; + +export function builtinCompletions(): Completion[] { + return [ + ...fusionFunctions.map((f): Completion => ({ + label: f.name, + type: 'function', + detail: f.signature, + info: functionInfo(f), + apply(view, completion, from, to) { + const following = view.state.sliceDoc(to).match(/^\s*\(/); + const insert = f.name + (following ? '' : '()'); + view.dispatch({ + changes: { from, to, insert }, + selection: { anchor: from + f.name.length + (following ? following[0].length : 1) }, + annotations: pickedCompletion.of(completion), + }); + }, + })), + ...fusionConstants.map((c): Completion => ({ + label: c.name, + type: 'constant', + detail: `${c.value} ${c.unit || 'unitless'}`, + info: `${c.description}\nDimension: ${c.dimension}. Case-sensitive.\nExample: ${c.example}`, + })), + ...fusionOperators + .filter((operator) => /^[a-z]+$/.test(operator)) + .map((label): Completion => ({ label, type: 'keyword', detail: 'Logical operator' })), + ...fusionUnits.map((label): Completion => ({ + label, + type: 'keyword', + detail: label === 'n' ? 'Paramood unitless suffix' : 'Fusion unit', + })), + ]; +} +export const expressionSignatureHelp = StateField.define({ + create: (state) => signatureTooltips(state.doc.toString(), state.selection.main.head), + update(value, tr) { + return tr.docChanged || tr.selection + ? signatureTooltips(tr.state.doc.toString(), tr.state.selection.main.head) + : value; + }, + provide: (field) => showTooltip.computeN([field], (state) => state.field(field)), +}); +function signatureTooltips(text: string, pos: number): readonly Tooltip[] { + const context = signatureContext(text, pos); + if (!context) return []; + return [ + { + pos, + above: true, + create: () => { + const dom = document.createElement('div'); + dom.className = 'expression-signature'; + const signature = document.createElement('div'); + signature.className = 'expression-signature-label'; + signature.append(context.fn.name + '('); + context.fn.arguments.forEach((arg, i) => { + if (i) signature.append('; '); + const span = document.createElement(i === context.argument ? 'strong' : 'span'); + span.textContent = arg.name; + if (i === context.argument) span.className = 'expression-active-argument'; + signature.append(span); + }); + signature.append(')'); + dom.append(signature); + const description = document.createElement('div'); + description.textContent = context.fn.description; + dom.append(description); + context.fn.arguments.forEach((arg, i) => { + const row = document.createElement('div'); + row.textContent = `${arg.name}: ${arg.type} — ${arg.description}`; + if (i === context.argument) row.className = 'expression-active-argument'; + dom.append(row); + }); + const returns = document.createElement('div'); + returns.textContent = `Returns: ${context.fn.returns}. ${context.fn.restriction}`; + dom.append(returns); + const example = document.createElement('div'); + example.textContent = `Example: ${context.fn.example}`; + dom.append(example); + dom.setAttribute('role', 'note'); + return { dom }; + }, + }, + ]; +} diff --git a/frontend/src/inline-edit.ts b/frontend/src/inline-edit.ts index 19c315c..6e87df1 100644 --- a/frontend/src/inline-edit.ts +++ b/frontend/src/inline-edit.ts @@ -1,28 +1,16 @@ +import { fusionFunctions, fusionConstants, fusionUnits } from '../../src/expression-catalog'; import type { Parameter } from './bridge'; import { hasAssignment, hasDefinitionSeparator } from './expression-syntax'; const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; -const reserved = new Set([ - 'this', - 'mm', - 'cm', - 'm', - 'in', - 'ft', - 'deg', - 'rad', - 'n', - 'sqrt', - 'sin', - 'cos', - 'tan', - 'abs', - 'floor', - 'ceil', - 'round', - 'min', - 'max', -]); +const reserved = new Set( + [ + 'this', + ...fusionFunctions.map((f) => f.name), + ...fusionConstants.map((c) => c.name), + ...fusionUnits, + ].map((name) => name.toLowerCase()), +); export function prepareInlineEdit(parameter: Parameter, input: string, parameters: Parameter[]) { const expression = input.trim(); diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 8d280f3..35ab2f1 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -1,3 +1,4 @@ +import { incompleteExpression } from '../../src/expression-language'; import { render, type ComponentChildren } from 'preact'; import { useEffect, useRef, useState } from 'preact/hooks'; import { Calculator, Copy, History, ListTree, PanelBottom, X } from 'lucide-preact'; @@ -203,7 +204,17 @@ export function App() { const gen = ++previewGen.current; setPreview(null); setPreviewError(''); - if (!available || !text.trim() || !assignment || !model?.documentId) return; + if ( + !available || + !text.trim() || + !assignment || + !model?.documentId || + incompleteExpression( + text, + model.parameters.flatMap((p) => [p.name, p.name.replace(/_/g, '.')]), + ) + ) + return; const id = model.documentId; const timer = window.setTimeout(() => { void request('parameters.preview', { text }, id) @@ -224,7 +235,17 @@ export function App() { const gen = ++calcGen.current; setResult(null); setCalcError(''); - if (!available || !expression.trim() || assignment || !model?.documentId) return; + if ( + !available || + !expression.trim() || + assignment || + !model?.documentId || + incompleteExpression( + expression, + model.parameters.flatMap((p) => [p.name, p.name.replace(/_/g, '.')]), + ) + ) + return; const id = model.documentId; const timer = window.setTimeout(() => { void request('calculator.evaluate', { expression }, id) diff --git a/frontend/src/palettes.test.tsx b/frontend/src/palettes.test.tsx index bc755b8..fb8dfbc 100644 --- a/frontend/src/palettes.test.tsx +++ b/frontend/src/palettes.test.tsx @@ -846,3 +846,26 @@ it('automatically dismisses a success toast after 3.5 seconds', async () => { else Reflect.deleteProperty(navigator, 'clipboard'); } }); + +it('waits for complete function calls before native Preview or Calculate requests', async () => { + const calls = mount('#parameters'); + await vi.waitFor(() => expect(host.textContent).toContain('Design')); + const editor = EditorView.findFromDOM(host.querySelector('.cm-content')!)!; + for (const text of ['probe=po', 'probe=pow()', 'pow(2;']) { + act(() => editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: text } })); + await new Promise((resolve) => setTimeout(resolve, 350)); + expect( + calls.some( + (call) => call.action === 'parameters.preview' || call.action === 'calculator.evaluate', + ), + ).toBe(false); + } + act(() => + editor.dispatch({ + changes: { from: 0, to: editor.state.doc.length, insert: 'probe=pow(2;3)' }, + }), + ); + await vi.waitFor(() => + expect(calls.some((call) => call.action === 'parameters.preview')).toBe(true), + ); +}); diff --git a/frontend/src/style.css b/frontend/src/style.css index 655d109..50f06a4 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -379,7 +379,7 @@ kbd { color: var(--muted); } .token-unknown { - text-decoration: underline wavy var(--error); + text-decoration: underline dotted var(--muted); text-underline-offset: 2px; } @media (prefers-color-scheme: dark) { @@ -1169,3 +1169,36 @@ kbd { .token-string { color: #b07828; } + +.token-constant { + color: #8b5ac7; + font-weight: 600; +} +.token-error { + text-decoration: underline wavy #d54b4b; + text-underline-offset: 3px; +} +.cm-tooltip.expression-signature { + color: var(--text); + background: var(--surface); + border: 1px solid var(--border); + max-width: min(340px, calc(100vw - 24px)); + max-height: 230px; + overflow: auto; + padding: 7px 9px; + white-space: normal; + overflow-wrap: anywhere; + font-size: 11px; + line-height: 1.4; +} +.expression-signature-label { + font-family: monospace; + margin-bottom: 4px; +} +.expression-active-argument { + font-weight: 700; + color: #2d83c4; +} +.expression-signature > div + div { + margin-top: 4px; +} diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json index fb225a6..6c2be8f 100644 --- a/frontend/tsconfig.json +++ b/frontend/tsconfig.json @@ -1,10 +1,12 @@ { "compilerOptions": { "target": "ES2020", - "lib": ["ES2020", "DOM"], + "lib": ["ES2022", "DOM"], "module": "ESNext", "moduleResolution": "bundler", "strict": true, + "resolveJsonModule": true, + "allowImportingTsExtensions": true, "jsx": "react-jsx", "jsxImportSource": "preact", "skipLibCheck": true, diff --git a/scripts/build_release.py b/scripts/build_release.py index 0b00ee1..b940496 100644 --- a/scripts/build_release.py +++ b/scripts/build_release.py @@ -32,6 +32,9 @@ def build(output_dir: Path, version_override: str = None) -> Path: if '__pycache__' not in path.parts: relative = path.relative_to(SOURCE).as_posix() files['Paramood/' + relative] = path.read_bytes() + files['Paramood/core/expression_catalog.json'] = ( + SOURCE / 'core' / 'expression_catalog.json' + ).read_bytes() files['Paramood/LICENSE'] = (ROOT / 'LICENSE').read_bytes() files['Paramood/THIRD_PARTY_NOTICES.txt'] = (ROOT / 'THIRD_PARTY_NOTICES.txt').read_bytes() manifest['version'] = version diff --git a/src/codemirror.ts b/src/codemirror.ts index 5a2bcc6..cf5e610 100644 --- a/src/codemirror.ts +++ b/src/codemirror.ts @@ -2,9 +2,17 @@ import { autocompletion, pickedCompletion, startCompletion } from '@codemirror/autocomplete'; import type { Completion, CompletionSource } from '@codemirror/autocomplete'; import type { Extension } from '@codemirror/state'; +import { + builtinCompletions, + expressionSignatureHelp, +} from '../frontend/src/expression-codemirror.ts'; +import { statementStart } from './expression-language.ts'; import { ParameterIndex, suggestCompletions } from './intellisense.js'; -export function parameterCompletionSource(getIndex: () => ParameterIndex): CompletionSource { +export function parameterCompletionSource( + getIndex: () => ParameterIndex, + batch = false, +): CompletionSource { return (context) => { const result = suggestCompletions( context.state.doc.toString(), @@ -12,49 +20,63 @@ export function parameterCompletionSource(getIndex: () => ParameterIndex): Compl getIndex(), context.explicit, ); - if (!result || !result.options.length) return null; + if (!result) return null; + const text = context.state.doc.toString(); + const start = statementStart(text, context.pos); + const before = text.slice(start, context.pos); + const nameContext = + !before.includes('=') && (batch || /(?=])=(?!=)/.test(text.slice(start))); + const memberContext = text[result.from - 1] === '.'; return { from: result.from, to: result.to, - options: result.options.map((symbol) => { - const isNamespace = symbol.kind === 'namespace'; - const completion: Completion = { - label: symbol.label, - type: isNamespace ? 'namespace' : 'variable', - boost: isNamespace - ? 90 - : symbol.path === symbol.nativeName && symbol.label.includes('_') - ? -40 - : 10, - detail: isNamespace - ? 'Object' - : [ - symbol.nativeName, - symbol.unit, - symbol.value == null ? undefined : String(symbol.value), - ] - .filter(Boolean) - .join(' · '), - info: symbol.comment, - }; - if (isNamespace) { - completion.apply = (view, option, from, to) => { - view.dispatch({ - changes: { from, to, insert: symbol.label + '.' }, - annotations: pickedCompletion.of(option), - }); - startCompletion(view); + options: [ + ...result.options.map((symbol) => { + const isNamespace = symbol.kind === 'namespace'; + const completion: Completion = { + label: symbol.label, + type: isNamespace ? 'namespace' : 'variable', + boost: isNamespace + ? 90 + : symbol.path === symbol.nativeName && symbol.label.includes('_') + ? -40 + : 10, + detail: isNamespace + ? 'Object' + : [ + symbol.nativeName, + symbol.unit, + symbol.value == null ? undefined : String(symbol.value), + ] + .filter(Boolean) + .join(' · '), + info: symbol.comment, }; - } - return completion; - }), + if (isNamespace) { + completion.apply = (view, option, from, to) => { + view.dispatch({ + changes: { from, to, insert: symbol.label + '.' }, + annotations: pickedCompletion.of(option), + }); + startCompletion(view); + }; + } + return completion; + }), + ...(!nameContext && !memberContext + ? builtinCompletions().filter((item) => !getIndex().nativeName(item.label)) + : []), + ], }; }; } /** Add this extension to Paramood's future CodeMirror expression editor. */ -export function parameterAutocomplete(getIndex: () => ParameterIndex): Extension { - return autocompletion({ - override: [parameterCompletionSource(getIndex)], - activateOnTyping: true, - }); +export function parameterAutocomplete(getIndex: () => ParameterIndex, batch = false): Extension { + return [ + expressionSignatureHelp, + autocompletion({ + override: [parameterCompletionSource(getIndex, batch)], + activateOnTyping: true, + }), + ]; } diff --git a/src/expression-catalog.ts b/src/expression-catalog.ts new file mode 100644 index 0000000..a11cf45 --- /dev/null +++ b/src/expression-catalog.ts @@ -0,0 +1,28 @@ +/** Fusion expression metadata shared by completion, highlighting and signature help. */ +import catalog from '../Paramood/core/expression_catalog.json' with { type: 'json' }; +export interface FunctionArgument { + name: string; + description: string; + type: string; + dimension: string; +} +export interface FusionFunction { + name: string; + category: string; + description: string; + signature: string; + arguments: FunctionArgument[]; + arity: number; + returns: string; + example: string; + restriction: string; +} +export const fusionFunctions: readonly FusionFunction[] = catalog.functions; +export const fusionConstants = catalog.constants; +export const fusionUnits: readonly string[] = [...catalog.units, 'n']; +export const fusionOperators = catalog.operators; +export const functionByName = new Map(fusionFunctions.map((f) => [f.name, f])); +export const constantByName = new Map(fusionConstants.map((c) => [c.name, c])); +export function functionInfo(f: FusionFunction): string { + return `${f.description}\n${f.arguments.map((a) => `${a.name}: ${a.type} — ${a.description}`).join('\n')}\nReturns: ${f.returns}. ${f.restriction}\nExample: ${f.example}`; +} diff --git a/src/expression-language.ts b/src/expression-language.ts new file mode 100644 index 0000000..1cc859a --- /dev/null +++ b/src/expression-language.ts @@ -0,0 +1,278 @@ +import { + constantByName, + functionByName, + fusionOperators, + fusionUnits, +} from './expression-catalog.ts'; + +export interface ExpressionToken { + value: string; + from: number; + to: number; + kind: 'identifier' | 'number' | 'string' | 'operator'; +} +/** One lexer for incomplete editor text, including scientific notation and escaped strings. */ +export function expressionTokens(text: string): ExpressionToken[] { + const pattern = + /'(?:\\.|[^'\\])*'?|"(?:\\.|[^"\\])*"?|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[A-Za-zА-Яа-яЁё_µ°][A-Za-zА-Яа-яЁё_0-9µ°]*(?:\.[A-Za-zА-Яа-яЁё0-9_]+)*|>=|<=|==|<>|!=|[^\s]/g; + return Array.from(text.matchAll(pattern), (m) => ({ + value: m[0], + from: m.index!, + to: m.index! + m[0].length, + kind: /^['"]/.test(m[0]) + ? 'string' + : /^(?:\d|\.\d)/.test(m[0]) + ? 'number' + : /^[A-Za-zА-Яа-яЁё_µ°]/.test(m[0]) + ? 'identifier' + : 'operator', + })); +} +export function statementStart(text: string, pos: number): number { + let depth = 0, + start = 0; + for (const t of expressionTokens(text.slice(0, pos))) { + if (t.kind === 'string') continue; + if (t.value === '(') depth++; + if (t.value === ')') depth = Math.max(0, depth - 1); + if (t.value === ';' && depth === 0) start = t.to; + // Newlines only separate definitions outside function calls. + if (depth === 0) { + const nextLine = text.slice(t.to, pos).match(/^\s*\n/); + if (nextLine) start = t.to + nextLine[0].length; + } + } + return start; +} +export function signatureContext(text: string, pos: number) { + const tokens = expressionTokens(text.slice(0, pos)); + const last = tokens.at(-1); + if (last?.kind === 'string' && !/^(['"])(?:\\.|(?!\1).)*\1$/s.test(last.value)) return null; + const stack: { name: string; from: number; argument: number }[] = []; + for (let i = 0; i < tokens.length; i++) { + const t = tokens[i]; + if (t.value === '(') + stack.push({ + name: tokens[i - 1]?.kind === 'identifier' ? tokens[i - 1].value : '', + from: t.from, + argument: 0, + }); + else if (t.value === ')') stack.pop(); + else if (t.value === ';' && stack.length) stack[stack.length - 1].argument++; + } + const call = [...stack].reverse().find((frame) => frame.name); + const fn = call && functionByName.get(call.name); + return fn && call ? { fn, from: call.from, argument: call.argument } : null; +} +export interface ExpressionDiagnostic { + from: number; + to: number; + message: string; + code: string; +} +/** Diagnose only proven errors. Missing trailing tokens remain a normal editing state. */ +export function expressionDiagnostics( + text: string, + known: ReadonlyMap, + batch = false, +): ExpressionDiagnostic[] { + const tokens = expressionTokens(text), + result: ExpressionDiagnostic[] = []; + const targets = new Set(); + if (batch) + for (let i = 0; i < tokens.length; i++) + if ( + tokens[i + 1]?.value === '=' || + (['+', '-', '*', '/'].includes(tokens[i + 1]?.value) && tokens[i + 2]?.value === '=') + ) + targets.add(tokens[i].value.replace(/\./g, '_')); + const error = (t: ExpressionToken, code: string, message: string) => + result.push({ from: t.from, to: t.to, code, message }); + const stack: { token: ExpressionToken; name: string; count: number; start: number }[] = []; + for (let i = 0; i < tokens.length; i++) { + const t = tokens[i], + next = tokens[i + 1]; + if (t.value === '(') { + const previous = tokens[i - 1]; + stack.push({ + token: t, + name: previous?.kind === 'identifier' ? previous.value : '', + count: 0, + start: i + 1, + }); + } else if (t.value === ')') { + const call = stack.pop(); + if (!call) { + error(t, 'parenthesis', 'Unexpected closing parenthesis.'); + continue; + } + const fn = functionByName.get(call.name); + if (fn) { + const count = i === call.start ? 0 : call.count + 1; + if (count !== fn.arity && count !== 0) + error( + call.token, + 'arity', + `${fn.name} expects ${fn.arity} argument${fn.arity === 1 ? '' : 's'}; received ${count}.`, + ); + // Infer simple arguments only. Composite expressions are validated by Fusion at Preview. + const args: ExpressionToken[][] = [[]]; + let depth = 0; + for (const a of tokens.slice(call.start, i)) { + if (a.value === '(') depth++; + if (a.value === ')') depth--; + if (a.value === ';' && !depth) args.push([]); + else args.at(-1)!.push(a); + } + const dimensions = args.map((a) => simpleDimension(a, known)); + fn.arguments.forEach((arg, n) => { + const dim = dimensions[n]; + if ( + dim && + ((arg.type === 'unitless' && dim !== 'unitless') || + (arg.type === 'angle' && !['angle', 'unitless'].includes(dim))) + ) + error(args[n][0], 'dimension', `${arg.name} requires ${arg.type}.`); + }); + if ( + ['min', 'max'].includes(fn.name) && + dimensions[0] && + dimensions[1] && + dimensions[0] !== dimensions[1] + ) + error(call.token, 'dimension', 'Arguments must have matching dimensions.'); + if (fn.name === 'if' && dimensions[1] && dimensions[2] && dimensions[1] !== dimensions[2]) + error( + call.token, + 'dimension', + 'Conditional branches must have matching types and dimensions.', + ); + } + } else if (t.value === ';' && stack.length) stack.at(-1)!.count++; + else if (t.value === ',' && stack.length) + error(t, 'separator', 'Separate function arguments with a semicolon (;).'); + else if (t.value === '!=') error(t, 'operator', 'Use <> for not equal.'); + if (t.kind !== 'identifier') continue; + const native = t.value.replace(/\./g, '_'); + const isTarget = + next?.value === '=' || + (next && ['+', '-', '*', '/'].includes(next.value) && tokens[i + 2]?.value === '='); + if (isTarget && batch) { + if (constantByName.has(t.value) || functionByName.has(t.value)) + error(t, 'reserved', 'This name is reserved by Fusion.'); + continue; + } + if (next?.value === '(') { + if (constantByName.has(t.value)) + error(t, 'constant', `${t.value} is a constant and cannot be called.`); + else if (!functionByName.has(t.value) && !['not'].includes(t.value)) + error(t, 'function', `Unknown function: ${t.value}.`); + continue; + } + if ( + known.has(native) || + targets.has(native) || + constantByName.has(t.value) || + fusionUnits.includes(t.value) || + fusionOperators.includes(t.value) || + t.value === 'this' + ) + continue; + // The final identifier may still be a prefix the user is typing. + if (i === tokens.length - 1 && t.to === text.length) continue; + error( + t, + tokens[i - 1]?.kind === 'number' ? 'unit' : 'parameter', + tokens[i - 1]?.kind === 'number' + ? `Unknown unit: ${t.value}.` + : `Unknown parameter: ${t.value}.`, + ); + } + return result; +} +function simpleDimension( + tokens: ExpressionToken[], + known: ReadonlyMap, +): string | undefined { + const t = tokens.filter((t) => !['+', '-'].includes(t.value)); + if (t.length === 1) { + if (t[0].kind === 'number') return 'unitless'; + if (t[0].kind === 'string') return 'text'; + return ( + constantByName.get(t[0].value)?.dimension ?? + unitDimension(known.get(t[0].value.replace(/\./g, '_'))) + ); + } + if (t.length === 2 && t[0].kind === 'number') return unitDimension(t[1].value); + return undefined; +} +function unitDimension(unit?: string): string | undefined { + if (unit === '' || unit === 'n') return 'unitless'; + if (unit && ['deg', 'rad', 'grad'].includes(unit)) return 'angle'; + if ( + unit && + ['mm', 'cm', 'm', 'hm', 'micron', 'in', 'ft', 'yd', 'mi', 'nauticalMile', 'mil'].includes(unit) + ) + return 'length'; + if (unit === 'Text') return 'text'; + return undefined; +} + +/** Avoid native validation while a user is still assembling a call or token. */ +export function incompleteExpression(text: string, knownNames: readonly string[] = []): boolean { + const tokens = expressionTokens(text); + const last = tokens.at(-1); + if (!last) return true; + if ( + last.kind === 'identifier' && + knownNames.some((name) => name !== last.value && name.startsWith(last.value)) + ) + return true; + if (last.kind === 'string' && !/^(['"])(?:\\.|(?!\1).)*\1$/s.test(last.value)) return true; + let depth = 0; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.value === '(') { + depth++; + const fn = functionByName.get(tokens[i - 1]?.value); + if (fn?.arity && tokens[i + 1]?.value === ')') return true; + } + if (token.value === ')') { + if (tokens[i - 1]?.value === ';') return true; + depth--; + } + } + if ( + depth > 0 || + [ + '=', + '+', + '-', + '*', + '/', + '^', + '%', + ';', + '<', + '>', + '<=', + '>=', + '==', + '<>', + 'and', + 'or', + 'not', + ].includes(last.value) + ) + return true; + if ( + last.kind === 'identifier' && + last.to === text.length && + (Array.from(functionByName.keys()).some((name) => name.startsWith(last.value)) || + Array.from(constantByName.keys()).some( + (name) => name !== last.value && name.startsWith(last.value), + )) + ) + return true; + return false; +} diff --git a/tests/integration/test_batch_adapter.py b/tests/integration/test_batch_adapter.py index 5c96728..ae612a6 100644 --- a/tests/integration/test_batch_adapter.py +++ b/tests/integration/test_batch_adapter.py @@ -51,7 +51,7 @@ def __init__(self, params): def isValidExpression(self, expression, unit): self.params.log.append(('validate', expression, unit)) - return expression != 'min(1,2)' + return expression != 'min(1;2)' def formatUnits(self, unit): raise RuntimeError('not a unit') @@ -96,7 +96,7 @@ def test_batch_created_in_dependency_order_and_validated_immediately(adapter_mod def test_later_fusion_rejection_propagates_as_error_for_command_abort(adapter_module): adapter, params = make_adapter(adapter_module) - text = 'a=15;b=min(1,2)' + text = 'a=15;b=min(1;2)' design = adapter._design() ops = adapter_module.plan_batch(text, {}, 'mm') with pytest.raises(adapter_module.BridgeError) as error: @@ -187,7 +187,7 @@ def test_direct_batch_reports_confirmed_changes_after_later_failure(adapter_modu adapter, params = make_adapter(adapter_module) adapter.in_command = False adapter.in_direct_apply = True - text = 'width=15;height=min(1,2)' + text = 'width=15;height=min(1;2)' preview = adapter.request('parameters.preview', {'text': text}) with pytest.raises(adapter_module.BridgeError) as error: adapter.request( diff --git a/tests/integration/test_release_package.py b/tests/integration/test_release_package.py index 91d0023..5e62aed 100644 --- a/tests/integration/test_release_package.py +++ b/tests/integration/test_release_package.py @@ -22,6 +22,9 @@ def test_release_package_is_self_contained_and_reproducible(tmp_path): assert 'Paramood/Paramood.py' in names assert 'Paramood/Paramood.manifest' in names assert 'Paramood/core/expressions.py' in names + assert 'Paramood/core/expression_catalog.json' in names + catalog = json.loads(archive.read('Paramood/core/expression_catalog.json')) + assert len(catalog['functions']) == 26 and len(catalog['constants']) == 4 assert 'Paramood/frontend/dist/index.html' in names assert any( name.startswith('Paramood/frontend/dist/assets/') and name.endswith('.js') diff --git a/tests/intellisense.test.mjs b/tests/intellisense.test.mjs index 3332b4c..5cc56d7 100644 --- a/tests/intellisense.test.mjs +++ b/tests/intellisense.test.mjs @@ -129,3 +129,71 @@ test('supports Cyrillic hierarchical names in completion and expressions', () => assert.equal(suggestCompletions('корпус.ш', 8, index).options[0].label, 'ширина'); assert.equal(compileExpression('корпус.ширина', index).expression, 'корпус_ширина'); }); + +// Catalog-driven coverage makes newly documented builtins part of the contract. +const { fusionFunctions, fusionConstants } = await import('../src/expression-catalog.ts'); +const { expressionTokens, signatureContext, expressionDiagnostics, statementStart } = + await import('../src/expression-language.ts'); +for (const f of fusionFunctions) { + test(`Fusion catalog and signature: ${f.name}`, () => { + assert.equal(f.arity, f.arguments.length); + assert.equal(f.signature, `${f.name}(${f.arguments.map((a) => a.name).join('; ')})`); + assert.ok(f.description && f.example && f.returns); + const text = `${f.name}(`; + assert.equal(signatureContext(text, text.length)?.fn.name, f.name); + assert.equal(signatureContext(text, text.length)?.argument, 0); + assert.deepEqual(expressionDiagnostics(f.example, new Map()), []); + }); +} +for (const c of fusionConstants) { + test(`Fusion constant: ${c.name}`, () => { + assert.ok(c.description && c.example && c.dimension); + assert.ok(Number.isFinite(c.value)); + assert.equal(expressionTokens(c.name)[0].kind, 'identifier'); + assert.deepEqual(expressionDiagnostics(c.example, new Map()), []); + }); +} +test('nested signatures follow the nearest open call and skip grouping and strings', () => { + const text = 'pow(2; max(3; 4))'; + assert.equal(signatureContext(text, text.indexOf('3'))?.fn.name, 'max'); + assert.equal(signatureContext(text, text.indexOf('4'))?.argument, 1); + assert.equal(signatureContext(text, text.length - 1)?.fn.name, 'pow'); + assert.equal(signatureContext(text, text.length), null); + assert.equal(signatureContext('if(1<2; "a;b', 12), null); + assert.equal(signatureContext('pow((2+3', 8)?.fn.name, 'pow'); + assert.equal(signatureContext('if(1<2; "a;b"; ', 15)?.argument, 2); +}); +test('semicolons inside calls are not batch separators', () => { + const text = 'first=2; second=pow(2; max(3; '; + assert.equal(statementStart(text, text.length), 8); +}); +test('diagnostics are conservative about incomplete input and precise about completed errors', () => { + for (const text of ['pow(', 'pow(2;', 'somePrefix', 'sin(3', '1e-3', 'if(1<2; "unterminated']) + assert.deepEqual(expressionDiagnostics(text, new Map()), [], text); + for (const [text, code] of [ + ['unknown(2)', 'function'], + ['pow(2)', 'arity'], + ['sin(2 mm)', 'dimension'], + ['min(2 mm; 3 deg)', 'dimension'], + ['missing + 1', 'parameter'], + ['2 wrongUnit + 1', 'unit'], + ['pow(2,3)', 'separator'], + [')', 'parenthesis'], + ['PI()', 'constant'], + ['1 != 2', 'operator'], + ['if(1<2;1 mm;2 deg)', 'dimension'], + ]) + assert.ok( + expressionDiagnostics(text, new Map()).some((d) => d.code === code), + text, + ); + assert.deepEqual(expressionDiagnostics('box.size=2; width=box.size*2', new Map(), true), []); +}); + +const { incompleteExpression } = await import('../src/expression-language.ts'); +test('native preview waits for complete expressions', () => { + for (const input of ['probe=po', 'probe=pow()', 'pow(', 'pow(2;)', '1 +', 'if(1<2; "draft']) + assert.equal(incompleteExpression(input), true, input); + for (const input of ['probe=pow(2;3)', 'random()', 'PI', 'min(1;2)', '2+3']) + assert.equal(incompleteExpression(input), false, input); +}); diff --git a/tests/test_release_paths.py b/tests/test_release_paths.py index 46450bc..1e4a3fd 100644 --- a/tests/test_release_paths.py +++ b/tests/test_release_paths.py @@ -32,6 +32,9 @@ def test_shipped_runtime_inputs_trigger_release(self): 'frontend/package-lock.json', 'frontend/vite.config.ts', 'src/intellisense.ts', + 'src/expression-catalog.ts', + 'src/expression-language.ts', + 'Paramood/core/expression_catalog.json', 'scripts/build_release.py', ): with self.subTest(path=path): diff --git a/tests/unit/test_core.py b/tests/unit/test_core.py index fc6fcfa..dd06897 100644 --- a/tests/unit/test_core.py +++ b/tests/unit/test_core.py @@ -205,12 +205,12 @@ def test_snapshot_plan_uses_recalculated_value_before_division(): assert operations[-1].quantity.value == 0.5 -def test_snapshot_plan_rejects_unsupported_existing_expression(): +def test_snapshot_plan_supports_existing_power_expression(): from Paramood.core.expressions import ParameterSnapshot, plan_batch_snapshot snapshot = {'a': ParameterSnapshot('2^3', '', Quantity(8), set())} - with pytest.raises(ExpressionError): - plan_batch_snapshot('x=2', snapshot, 'mm') + operations = plan_batch_snapshot('x=a*2', snapshot, 'mm') + assert operations[0].quantity.value == 16 def test_snapshot_plan_numeric_existing_expression_uses_its_unit(): diff --git a/tests/unit/test_expression_builtins.py b/tests/unit/test_expression_builtins.py new file mode 100644 index 0000000..525903e --- /dev/null +++ b/tests/unit/test_expression_builtins.py @@ -0,0 +1,173 @@ +import math + +import pytest + +from Paramood.core.builtins import CATALOG, FUNCTIONS +from Paramood.core.expressions import ( + ANGLE, + LENGTH, + SCALAR, + ExpressionError, + LocalEvaluationUnsupported, + NondeterministicExpression, + Quantity, + ParameterSnapshot, + evaluate, + plan_batch, + plan_batch_snapshot, +) + + +@pytest.mark.parametrize('function', CATALOG['functions'], ids=lambda f: f['name']) +def test_every_catalog_function(function): + assert function['arity'] == len(function['arguments']) + assert ( + function['signature'] + == function['name'] + '(' + '; '.join(a['name'] for a in function['arguments']) + ')' + ) + assert ( + function['category'] + and function['description'] + and function['returns'] + and function['example'] + ) + for arg in function['arguments']: + assert arg['name'] and arg['type'] and arg['dimension'] and arg['description'] + if function['name'] == 'random': + with pytest.raises(NondeterministicExpression): + evaluate(function['example'], {}) + else: + result = evaluate(function['example'], {}) + assert math.isfinite(result.value) + # Both creation and snapshot update planners must recognize each builtin. + created = plan_batch('probe=' + function['example'], {}, 'mm')[0] + snapshot = { + 'probe': ParameterSnapshot(created.expression, created.unit, created.quantity, set()) + } + updated = plan_batch_snapshot('probe=' + function['example'], snapshot, 'mm')[0] + assert updated.quantity == created.quantity + + +@pytest.mark.parametrize('constant', CATALOG['constants'], ids=lambda c: c['name']) +def test_every_catalog_constant(constant): + result = evaluate(constant['name'], {}) + assert math.isfinite(result.value) + assert math.isfinite(evaluate(constant['example'], {}).value) + with pytest.raises(ExpressionError, match='reserved'): + plan_batch(constant['name'] + '=2', {}, 'mm') + with pytest.raises(ExpressionError, match='Unknown'): + evaluate(constant['name'].lower(), {}) + + +@pytest.mark.parametrize( + ('expression', 'value', 'dimension'), + [ + ('round(2.5)', 3, SCALAR), + ('round(-2.5)', -3, SCALAR), + ('sign(-2)', 0, SCALAR), + ('sign(0)', 0, SCALAR), + ('sign(2)', 1, SCALAR), + ('log(100)', 2, SCALAR), + ('ln(E)', 1, SCALAR), + ('-2^2', -4, SCALAR), + ('2^3^2', 512, SCALAR), + ('-7 % 3', -1, SCALAR), + ('7 % -3', 1, SCALAR), + ('pow(4 mm^2; 0.5)', 2, LENGTH), + ('sqrt(4 mm^2)', 2, LENGTH), + ('2/4 mm', 0.5, (-1, 0)), + ('sin(PI/4 * 1 rad)', math.sqrt(0.5), SCALAR), + ('Gravity / (1 mm/s^2)', 9806.65, SCALAR), + ('SpeedOfLight / (1 mm/s)', 299792458000, SCALAR), + ('if((1<2) and not(3<>3); 10 mm; 20 mm)', 10, LENGTH), + ('if((1>2) or (2>=2); 3; 4)', 3, SCALAR), + ('if(1==2; 3; if(1<=2; 4; 5))', 4, SCALAR), + ('asinh(1)', math.asinh(1), ANGLE), + ('atanh(0)', 0, ANGLE), + ], +) +def test_fusion_numeric_semantics(expression, value, dimension): + result = evaluate(expression, {}) + assert result.dimension == dimension + assert result.value == pytest.approx(value) + + +@pytest.mark.parametrize( + 'expression', + [ + 'min(1;2;3)', + 'max(1)', + 'pow(2)', + 'sin(1 mm)', + 'ln(-1)', + 'log(0)', + 'asin(2)', + 'acos(-2)', + 'acosh(.5)', + 'atanh(1)', + 'sqrt(-1)', + 'pow(-2;.5)', + 'pow(2;1 mm)', + 'exp(10000)', + '1%0', + 'min(1 mm;2 deg)', + 'if(1<2;1 mm;2 deg)', + 'pow(2,3)', + 'unknown(1)', + 'PI()', + 'pi', + '1e-3+e', + '1!=2', + '2**3', + '__import__("os")', + '(1).__class__', + '2^10001', + ], +) +def test_invalid_expression_rejected(expression): + with pytest.raises(ExpressionError): + evaluate(expression, {}) + + +@pytest.mark.parametrize('expression', ['random()', 'if(1<2;2;random())']) +def test_random_never_becomes_a_stable_plan(expression): + for planner in (plan_batch, plan_batch_snapshot): + with pytest.raises(NondeterministicExpression): + planner('probe=' + expression, {}, 'mm') + + +def test_unsupported_is_distinct_from_invalid_and_native_fallback_is_narrow(): + with pytest.raises(LocalEvaluationUnsupported): + evaluate('sin(30)', {}) + calls = [] + + def native(name, args, dimension): + calls.append((name, args, dimension)) + return Quantity(0.5) + + assert evaluate('sin(30)', {}, native).value == 0.5 + assert calls == [('sin', [Quantity(30)], SCALAR)] + assert evaluate('random()', {}, native, allow_nondeterministic=True).value == 0.5 + with pytest.raises(LocalEvaluationUnsupported): + evaluate('1 kg', {}) + + +def test_unitless_parameter_and_scientific_notation_are_not_constants(): + assert evaluate('1e-3 + E', {}).value == pytest.approx(0.001 + math.e) + assert evaluate('2', {'E': Quantity(999)}).value == 2 + assert len(FUNCTIONS) == len(CATALOG['functions']) + + +@pytest.mark.parametrize('function', CATALOG['functions'], ids=lambda f: f['name']) +def test_catalog_function_wrong_argument_count(function): + expression = function['name'] + '(' + ';'.join('1' for _ in range(function['arity'] + 1)) + ')' + with pytest.raises(ExpressionError, match='arguments'): + evaluate(expression, {}) + + +def test_derived_dimension_units_for_calculator(): + from Paramood.core.expressions import dimension_unit + + assert dimension_unit(evaluate('Gravity', {}).dimension) == 'mm/s^2' + assert dimension_unit(evaluate('SpeedOfLight', {}).dimension, 'cm') == 'cm/s' + assert dimension_unit(SCALAR) == ''