diff --git a/docs/workflows/expressions.md b/docs/workflows/expressions.md index 3269e910f1..670a7e7f9e 100644 --- a/docs/workflows/expressions.md +++ b/docs/workflows/expressions.md @@ -44,8 +44,8 @@ handler, so resume is at-least-once. | Form | Example | | --- | --- | -| Dot-path lookup | `{{ inputs.name }}`, `{{ steps.test.output.exit_code }}` | -| Literals | Strings, numbers, `true`, `false`, `none`/`null`, and lists such as `[1, 2]` | +| Dot-path lookup | `{{ inputs.name }}`, `{{ steps.test.output.exit_code }}`, `{{ steps.plan.output.matrix[0][1] }}` | +| Literals | Strings, numbers (including exponent literals such as `1e3`), `true`, `false`, `none`/`null`, and lists such as `[1, 2]` | | Comparisons | `==`, `!=`, `>`, `<`, `>=`, `<=` | | Boolean logic | `and`, `or`, `not` | | Membership | `in`, `not in` | @@ -93,7 +93,9 @@ Notes on the newer filters: Operators bind from loosest to tightest as `or`, `and`, `not`, then the comparisons. All comparisons (`==`, `!=`, `>`, `<`, `>=`, `<=`, `in`, `not in`) share one level and are evaluated left to right; none has priority over another. `{{ a == b > 0 }}` therefore means `{{ (a == b) > 0 }}`. To combine comparisons, use parentheses or `and`/`or`. -The body of every `{{ }}` block must be a valid expression. Text that is not one, such as prose (`{{ some text }}`), a key with characters other than letters, digits, `_` and `-` (`{{ inputs.weird:key }}`), or arithmetic (`{{ count + 1 }}`), raises a `ValueError` naming the offending token. Numbers may be written as `5`, `-5`, `+5`, `1_000`, `0.5`, `.5`, `5.`, or `1.5e3`. +The body of every `{{ }}` block must be a valid expression. Text that is not one, such as prose (`{{ some text }}`), a key with characters other than letters, digits, `_` and `-` (`{{ inputs.weird:key }}`), or arithmetic (`{{ count + 1 }}`), raises a `ValueError` naming the offending token. Numbers may be written as `5`, `-5`, `+5`, `1_000`, `0.5`, `.5`, `5.`, `1.5e3`, `1e3`, `-2e+3`, or `5e-2`. Exponent literals evaluate to `float`; malformed exponent forms such as `1e` or `1e3.5` raise `ValueError`. During comparisons, integer-mantissa exponent strings without a decimal point (such as `"1e3"`) remain strings and are not converted to numbers, whereas decimal-mantissa exponent strings containing `.` (such as `"1.0e3"` or `"1.5e3"`) are coerced to `float` when compared with a number or numeric string. + +Path segments support integer list indexing, including negative indices and chained indexing (for example, `{{ steps.plan.output.matrix[0][1] }}`, `{{ steps.plan.output.matrix[-1][-2] }}`, or `{{ item[0][1] }}`). Malformed index syntax (such as `matrix[0][]` or `matrix[0][a]`) raises `ValueError`. For chained indexing, an out-of-range index raises `IndexError` and indexing a non-list value raises `TypeError` instead of returning `None`. > **Compatibility:** Earlier releases could resolve an expression such as `{{ inputs.weird:key }}` when the key existed; this expression now fails at runtime. Rename keys you control (for example, `weird:key` to `weird_key`) and update their references. Quoted-key lookup is not supported. Workflow validation may not detect these expressions before execution. diff --git a/src/specify_cli/workflows/expressions/engine.py b/src/specify_cli/workflows/expressions/engine.py index 88ae8c3760..375552479c 100644 --- a/src/specify_cli/workflows/expressions/engine.py +++ b/src/specify_cli/workflows/expressions/engine.py @@ -86,13 +86,14 @@ def _path_terminal_pattern(plain_pattern: str, indexed_pattern: str) -> str: """The ``PATH`` regex, built from the namespace's own segment definitions. ``_PLAIN_SEGMENT`` (``^[\\w-]+$``) and ``_INDEXED_SEGMENT`` - (``^([\\w-]+)\\[(-?\\d+)\\]$``) are stripped of their anchors and combined: - every segment is a plain or an indexed one. The *first* segment excludes a - leading digit (so ``123`` keeps lexing as a number) and the reserved word - operators (``and``, ``or``, ``not``, ``in``, so they never lex as a path - where an operand is expected); that is the only difference from the - namespace pattern, and it is why this derivation reads the pattern instead - of re-describing the shape. + (``^([\\w-]+)((?:\\[-?\\d+\\])+)$``) are stripped of their anchors and + combined: every segment is a plain or an indexed one. The *first* segment + excludes a leading digit or hyphen (so ``123`` keeps lexing as a number + and ``1[0]`` does not silently resolve as a path) and the reserved word + operators (``and``, ``or``, ``not``, ``in``, so neither ``and`` nor + ``and[0]`` ever lexes as a path where an operand is expected); that is the + only difference from the namespace pattern, and it is why this derivation + reads the pattern instead of re-describing the shape. ``_INDEXED_SEGMENT`` is read through ``namespace`` at call time, so the parser cache below rebuilds when it is widened -- the drift guard @@ -101,7 +102,7 @@ def _path_terminal_pattern(plain_pattern: str, indexed_pattern: str) -> str: plain = plain_pattern.strip("^$") indexed = indexed_pattern.strip("^$") later = f"(?:{indexed}|{plain})" - first = f"(?:{indexed}|(?!(?:and|or|not|in)(?![\\w-]))[^\\W\\d]{plain[:-1]}*)" + first = f"(?!(?:and|or|not|in)(?![\\w-]))(?=[^\\W\\d])(?:{indexed}|{plain})" return f"{first}(?:\\.{later})*" @@ -157,7 +158,7 @@ def _grammar(path_pattern: str) -> str: FILTER_NAME: /[A-Za-z_][\w-]*/ PATH: /""" + path_pattern + r"""/ STRING: /'[^']*'/ | /"[^"]*"/ -NUMBER: /[+-]?(?:(?:\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|\d(?:_?\d)*)/ +NUMBER: /[+-]?(?:(?:\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|\.\d(?:_?\d)*)|\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?/ %import common.WS %ignore WS """ @@ -201,7 +202,9 @@ def string(self, token: Token) -> tuple[str, str]: def number(self, token: Token) -> tuple[str, Any]: text = str(token) - return ("lit", float(text) if "." in text else int(text)) + if "." in text or "e" in text or "E" in text: + return ("lit", float(text)) + return ("lit", int(text)) def path(self, token: Token) -> tuple[str, str]: return ("path", str(token)) diff --git a/src/specify_cli/workflows/expressions/namespace.py b/src/specify_cli/workflows/expressions/namespace.py index 596c45fb39..aba3e23f58 100644 --- a/src/specify_cli/workflows/expressions/namespace.py +++ b/src/specify_cli/workflows/expressions/namespace.py @@ -16,7 +16,8 @@ # against it, and the condition gate below reuses it rather than describing the # same shape a second time, so widening what indexing accepts cannot leave the # evaluator and the gate disagreeing. -_INDEXED_SEGMENT = re.compile(r"^([\w-]+)\[(-?\d+)\]$") +_INDEXED_SEGMENT = re.compile(r"^([\w-]+)((?:\[-?\d+\])+)$") +_INDEX_BRACKET = re.compile(r"\[([^\]]+)\]") _PLAIN_SEGMENT = re.compile(r"^[\w-]+$") @@ -24,30 +25,57 @@ def _resolve_dot_path(obj: Any, path: str) -> Any: """Resolve a dotted path like ``steps.specify.output.file`` against *obj*. - Supports dict key access and list indexing, including the negative form - Python and Jinja2 both accept (e.g., ``task_list[0]``, ``task_list[-1]``). + Supports dict key access and single or chained list indexing, including the + negative form Python and Jinja2 both accept (e.g., ``task_list[0]``, + ``task_list[-1]``, ``matrix[0][1]``). + + For chained indexing (two or more bracketed indices on one segment), + invalid access raises ``IndexError`` for out-of-range list indices and + ``TypeError`` when the target is not a list, rather than silently + returning ``None``. """ parts = path.split(".") current = obj for part in parts: - # Handle list indexing: name[0], name[-1] + # Handle single or chained list indexing: name[0], name[-1], matrix[0][1] idx_match = _INDEXED_SEGMENT.match(part) if idx_match: - key, idx = idx_match.group(1), int(idx_match.group(2)) + key = idx_match.group(1) if isinstance(current, dict): current = current.get(key) else: - return None - if isinstance(current, list) and -len(current) <= idx < len(current): - current = current[idx] - else: - return None + current = None + raw_indices = idx_match.group(2) + indices = ( + _INDEX_BRACKET.findall(raw_indices) + if raw_indices.startswith("[") + else [raw_indices] + ) + chained = len(indices) > 1 + for raw_idx in indices: + idx = int(raw_idx) + if not isinstance(current, list): + if chained: + raise TypeError( + f"cannot index {type(current).__name__} in '{path}': " + "chained indexing requires a list" + ) + current = None + break + if -len(current) <= idx < len(current): + current = current[idx] + elif chained: + raise IndexError( + f"list index {idx} out of range in '{path}' " + f"(length {len(current)})" + ) + else: + current = None + break elif isinstance(current, dict): current = current.get(part) else: - return None - if current is None: - return None + current = None return current diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 56baaa7b16..ebd2b9a161 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -1802,36 +1802,210 @@ def test_comparisons_share_one_level_and_group_left_to_right(self): ) is True def test_number_literal_forms(self): - """Every number form the former engine read through ``int()``/``float()``. - - A ``.`` makes a float (exponents need one too, as before); a sign and - digit-group underscores are allowed. - """ + """Integer, decimal, and exponent-form numeric literals evaluate with + matching Python types; signs and digit-group underscores are allowed.""" from specify_cli.workflows.expressions import evaluate_expression from specify_cli.workflows.base import StepContext - ctx = StepContext(inputs={"ratio": 0.7}) + ctx = StepContext(inputs={"ratio": 0.7, "n": 5}) for text, expected in [ ("5", 5), ("-5", -5), ("+5", 5), ("1_000", 1000), ("0.5", 0.5), (".5", 0.5), ("-.5", -0.5), ("5.", 5.0), ("1.5e3", 1500.0), (".5E-1", 0.05), ("1_000.5", 1000.5), + ("1e3", 1000.0), ("1E3", 1000.0), ("+1e3", 1000.0), + ("-2e+3", -2000.0), ("5e-2", 0.05), ("1_000e2", 100000.0), ]: result = evaluate_expression("{{ " + text + " }}", ctx) assert result == expected and type(result) is type(expected), text assert evaluate_expression("{{ inputs.ratio > .5 }}", ctx) is True - assert evaluate_expression("{{ [.5, +1] }}", ctx) == [0.5, 1] + assert evaluate_expression("{{ inputs.n < 1e3 }}", ctx) is True + assert evaluate_expression("{{ [.5, +1, 1e3] }}", ctx) == [0.5, 1, 1000.0] def test_malformed_number_literals_are_refused(self): - """Forms ``int()``/``float()`` refuse (or, for ``1e3``, the former engine - never read as a number) do not lex as one either.""" + """Malformed numeric literals (including incomplete or malformed + exponents) raise ``ValueError`` instead of falling through.""" import pytest from specify_cli.workflows.expressions import evaluate_expression from specify_cli.workflows.base import StepContext - for text in ("1__0", "1_", "1e3", "5..", "."): + for text in ( + "1__0", "1_", "5..", ".", + "1e", "1E", "1e+", "1e-", "1e3e4", "1e3.5", "1e_3", "1_e3", "1e3_", + ): with pytest.raises(ValueError, match="invalid expression"): evaluate_expression("{{ " + text + " }}", StepContext(inputs={})) + def test_exponent_strings_are_not_implicitly_coerced_in_comparisons(self): + """Integer-mantissa exponent strings stay strings during comparisons + rather than being implicitly converted to floats, while existing + decimal-mantissa float coercion and exponent numeric literals remain + unchanged.""" + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.expressions import ( + evaluate_condition, + evaluate_expression, + ) + + ctx = StepContext( + inputs={ + "s": "1e3", + "upper": "2E3", + "small": "5e-2", + "neg": "-1e2", + "dec_eq": "1.0e3", + "dec_gt": "1.5e3", + "n": 1000, + } + ) + # Integer-mantissa exponent strings do not implicitly coerce to numbers. + assert evaluate_expression("{{ inputs.s == 1000 }}", ctx) is False + assert evaluate_expression("{{ inputs.s == 1e3 }}", ctx) is False + assert evaluate_expression("{{ inputs.s != 1000 }}", ctx) is True + assert evaluate_expression("{{ inputs.s != 1e3 }}", ctx) is True + assert evaluate_expression("{{ inputs.s == '1000' }}", ctx) is False + assert evaluate_expression("{{ inputs.s == '1e3' }}", ctx) is True + assert evaluate_condition("{{ inputs.s > 100 }}", ctx) is False + assert evaluate_condition("{{ inputs.s < 100 }}", ctx) is False + assert evaluate_condition("{{ inputs.small < 0.1 }}", ctx) is False + assert evaluate_condition("{{ inputs.neg < 0 }}", ctx) is False + # String-to-string ordering stays lexicographic ("1e3" < "2e1", "2E3" < "900"). + assert evaluate_expression("{{ inputs.s > '2e1' }}", ctx) is False + assert evaluate_expression("{{ inputs.upper > '900' }}", ctx) is False + # Decimal-mantissa exponent strings keep existing float() coercion. + assert evaluate_expression("{{ inputs.dec_eq == 1000 }}", ctx) is True + assert evaluate_expression("{{ inputs.dec_eq == 1e3 }}", ctx) is True + assert evaluate_expression("{{ inputs.dec_eq == '1000' }}", ctx) is True + assert evaluate_condition("{{ inputs.dec_gt > 100 }}", ctx) is True + assert evaluate_expression("{{ inputs.dec_eq == inputs.s }}", ctx) is False + # Exponent numeric literals still compare numerically. + assert evaluate_expression("{{ 1e3 == 1000 }}", ctx) is True + assert evaluate_expression("{{ 1e3 > 100 }}", ctx) is True + assert evaluate_expression("{{ inputs.n == 1e3 }}", ctx) is True + assert evaluate_expression("{{ 5e-2 < 0.1 }}", ctx) is True + + def test_chained_list_indexing_and_expected_errors(self): + """Chained list indices resolve across nested lists (including negative + indices) and dot segments; invalid chained access raises IndexError or + TypeError instead of returning None, and invalid syntax raises ValueError.""" + import pytest + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.expressions import ( + evaluate_condition, + evaluate_expression, + ) + from specify_cli.workflows.step.if_then import IfThenStep + + ctx = StepContext( + inputs={ + "name": "it's", + "a": "x", + "b": True, + "scalar": 42, + "empty": [], + "rows": [None, {"k": "v"}], + }, + steps={ + "plan": { + "output": { + "matrix": [["a", "b"], ["c", "d"]], + "cube": [[[{"label": "ok"}]]], + "null_cell": [[None]], + "falsy_cells": [[False, 0, ""]], + } + } + }, + item=[["first", "second"], ["third", "fourth"]], + ) + assert evaluate_expression("{{ steps.plan.output.matrix[0][1] }}", ctx) == "b" + assert evaluate_expression("{{ steps.plan.output.matrix[-1][-2] }}", ctx) == "c" + assert evaluate_expression("{{ steps.plan.output.matrix[0][-1] }}", ctx) == "b" + assert evaluate_expression("{{ steps.plan.output.matrix[-2][0] }}", ctx) == "a" + assert ( + evaluate_expression("{{ steps.plan.output.cube[0][0][0].label }}", ctx) + == "ok" + ) + assert ( + evaluate_expression("{{ steps.plan.output.cube[-1][-1][-1].label }}", ctx) + == "ok" + ) + assert evaluate_expression("{{ steps.plan.output.null_cell[0][0] }}", ctx) is None + assert evaluate_expression("{{ steps.plan.output.falsy_cells[0][0] }}", ctx) is False + assert evaluate_expression("{{ steps.plan.output.falsy_cells[0][1] }}", ctx) == 0 + assert evaluate_expression("{{ steps.plan.output.falsy_cells[0][2] }}", ctx) == "" + assert evaluate_expression("{{ item[0][1] }}", ctx) == "second" + assert evaluate_expression("{{ item[-1][0] }}", ctx) == "third" + assert evaluate_expression("{{ item[-1][-1] }}", ctx) == "fourth" + assert evaluate_condition("{{ steps.plan.output.matrix[0][1] == 'b' }}", ctx) is True + # Short-circuit boolean guards prevent evaluating an invalid chained index. + assert evaluate_condition("{{ false and steps.plan.output.matrix[0][9] }}", ctx) is False + assert evaluate_condition("{{ true or steps.plan.output.matrix[0][9] }}", ctx) is True + + # Out-of-range chained indices raise IndexError instead of returning None. + for bad_index in ( + "steps.plan.output.matrix[0][9]", + "steps.plan.output.matrix[0][-9]", + "steps.plan.output.matrix[9][0]", + "steps.plan.output.matrix[-9][0]", + "inputs.empty[0][0]", + "item[0][9]", + "item[-9][0]", + ): + with pytest.raises(IndexError, match="out of range"): + evaluate_expression("{{ " + bad_index + " }}", ctx) + # Conditions and workflow branches surface the error instead of picking the wrong branch. + with pytest.raises(IndexError, match="out of range"): + evaluate_condition("{{ steps.plan.output.matrix[0][9] != 'b' }}", ctx) + with pytest.raises(IndexError, match="out of range"): + IfThenStep().execute( + { + "id": "branch", + "condition": "{{ steps.plan.output.matrix[0][9] == 'b' }}", + "then": [], + "else": [], + }, + ctx, + ) + with pytest.raises(IndexError, match="out of range"): + evaluate_expression("cell={{ steps.plan.output.matrix[0][9] }}", ctx) + + # Chained indexing into non-list values raises TypeError instead of returning None. + for bad_target in ( + "steps.plan.output.matrix[0][1][0]", + "steps.plan.output.null_cell[0][0][0]", + "steps.plan.output.missing[0][1]", + "steps.missing.output.matrix[0][1]", + "inputs.scalar[0][1]", + "inputs.rows[0][0]", + "inputs.rows[1][0]", + "inputs[0][1]", + ): + with pytest.raises(TypeError, match="chained indexing requires a list"): + evaluate_expression("{{ " + bad_target + " }}", ctx) + with pytest.raises(TypeError, match="chained indexing requires a list"): + evaluate_expression("{{ item[0][1] }}", StepContext()) + + # Malformed index syntax and digit-/keyword-led indexing raise ValueError. + for bad in ( + "steps.plan.output.matrix[0][]", + "steps.plan.output.matrix[0][a]", + "steps.plan.output.matrix[0][1.5]", + "1[0]", + "and[0]", + "or[0]", + "in[0]", + r"'it\'s'", + r"inputs.name == 'it\'s'", + ): + with pytest.raises(ValueError, match="invalid expression"): + evaluate_expression("{{ " + bad + " }}", ctx) + # `not` before a list literal without a space negates the list literal + # rather than lexing as a path named `not[0]`. + assert evaluate_expression("{{ not[0] }}", ctx) is False + assert evaluate_expression("{{ not[] }}", ctx) is True + # Word operators adjacent to quotes still parse and evaluate cleanly. + assert evaluate_condition("{{ inputs.a=='x'and inputs.b }}", ctx) is True + assert evaluate_condition("{{ 'x'in inputs.a }}", ctx) is True + def test_integer_conversion_error_is_reported_as_invalid_expression(self): """The integer conversion limit is reported as an expression error.""" import sys diff --git a/tests/unit/test_condition_expression_block.py b/tests/unit/test_condition_expression_block.py index e4d3e2934e..72c3bde866 100644 --- a/tests/unit/test_condition_expression_block.py +++ b/tests/unit/test_condition_expression_block.py @@ -771,7 +771,8 @@ def test_the_probe_reports_what_the_evaluator_reports(): # _resolve_dot_path keys on [w-]+, so a key literally named "2bad" resolves. ("inputs.2bad", False), ("inputs.tags[foo]", True), - ("inputs.matrix[0][1]", True), + ("inputs.matrix[0][1]", False), + ("inputs.matrix[0][foo]", True), # Round 7: an operand one level down, which the single-term gate never saw. ("inputs.a === inputs.b", True), ("bogus", True), @@ -827,12 +828,13 @@ def test_filter_wiring_errors_are_still_rejections(condition): ("42", True), ("3.14", True), ("-7", True), - # `1e3` has no "." so the evaluator calls int() on it, which fails; it then - # falls through to a path lookup and resolves to None. The gate used to - # decide this for itself with a float() test that accepted `1e3`, and the - # correction turned a truthy condition false. Now the evaluator reaches the - # dot-path resolution with `1e3` and reports it, so the two cannot disagree. - ("1e3", False), + ("1e3", True), + ("1e", False), + ("steps.plan.output.matrix[0][1]", True), + ("item[0][1]", True), + ("inputs[0][1]", False), + ("1[0]", False), + ("and[0]", False), ("'one'", True), ('"one"', True), # Two literals, not one: the evaluator requires the opening quote's match to @@ -857,11 +859,15 @@ def test_literal_handling_comes_from_the_evaluator(condition, resolvable): @pytest.mark.parametrize( "condition", [ - # `_build_namespace` hands back mappings, so an indexed root always resolves - # to None however the index is written. + # `_build_namespace` hands back mappings, so an indexed mapping root + # never resolves to a list (single indexing yields None; chained + # indexing raises TypeError). "inputs[0]", + "inputs[0][1]", "steps[1]", - "1e3", + "1e", + "1[0]", + "and[0]", "'a' 'b'", ], ) @@ -985,6 +991,25 @@ def test_indexing_an_always_mapping_root_still_loses_the_correction(condition): assert evaluate_condition("{{ " + condition + " }}", ctx) is False +@pytest.mark.parametrize( + "condition", ["inputs[0][1]", "steps[1][0]", "fan_in[0][0]", "context[0][0]"] +) +def test_chained_indexing_an_always_mapping_root_loses_correction_and_raises(condition): + """Chained indexing on an always-mapping root withholds correction and raises TypeError.""" + ctx = StepContext(inputs={"a": 1}, item=[["x", "y"]]) + assert CORRECTION_OFFERED not in format_condition_remediation(condition) + with pytest.raises(TypeError, match="chained indexing requires a list"): + evaluate_condition("{{ " + condition + " }}", ctx) + + +@pytest.mark.parametrize("condition", ["item[0][1] == 'y'", "item[-1][-2] == 'x'"]) +def test_chained_indexed_item_root_keeps_the_correction(condition): + """Chained indexing on a nested list ``item`` keeps the correction and evaluates.""" + ctx = StepContext(inputs={"a": 1}, item=[["x", "y"]]) + assert CORRECTION_OFFERED in format_condition_remediation(condition) + assert evaluate_condition("{{ " + condition + " }}", ctx) is True + + # --- what the leaf walk rests on ----------------------------------------------