diff --git a/docs/workflows/expressions.md b/docs/workflows/expressions.md index 3269e910f1..da80beaecc 100644 --- a/docs/workflows/expressions.md +++ b/docs/workflows/expressions.md @@ -53,6 +53,11 @@ handler, so resume is at-least-once. This is a dedicated expression language, not full Jinja2 or Python. +Numeric literals accept scientific notation such as `1e3` and `-2E-3`. +A list from a named value can be indexed repeatedly, including with negative +indices, as in `{{ inputs.matrix[0][-1] }}`. A chain raises `IndexError` for an +out-of-range index and `TypeError` for indexing a non-list value. + ## Filters | Filter | Example | Behavior | diff --git a/src/specify_cli/workflows/expressions/engine.py b/src/specify_cli/workflows/expressions/engine.py index 88ae8c3760..53ab9972fc 100644 --- a/src/specify_cli/workflows/expressions/engine.py +++ b/src/specify_cli/workflows/expressions/engine.py @@ -157,7 +157,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)*)(?:[eE][+-]?\d(?:_?\d)*)?/ %import common.WS %ignore WS """ @@ -201,7 +201,7 @@ 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)) + return ("lit", float(text) if "." in text or "e" in text.lower() else 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..1aacfd569b 100644 --- a/src/specify_cli/workflows/expressions/namespace.py +++ b/src/specify_cli/workflows/expressions/namespace.py @@ -16,7 +16,7 @@ # 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+(?:\]\[-?\d+)*)\]$") _PLAIN_SEGMENT = re.compile(r"^[\w-]+$") @@ -24,24 +24,28 @@ 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 repeated list indices, including negative + indices. An invalid single index retains the legacy ``None`` result. """ parts = path.split(".") current = obj for part in parts: - # Handle list indexing: name[0], name[-1] idx_match = _INDEXED_SEGMENT.match(part) if idx_match: - key, idx = idx_match.group(1), int(idx_match.group(2)) - if isinstance(current, dict): - current = current.get(key) - else: + key, suffix = idx_match.groups() + if not isinstance(current, dict): return None - if isinstance(current, list) and -len(current) <= idx < len(current): + current = current.get(key) + indexes = suffix.split("][") + for index in indexes: + idx = int(index) + if len(indexes) == 1 and ( + not isinstance(current, list) or not -len(current) <= idx < len(current) + ): + return None + if not isinstance(current, list): + raise TypeError(f"Cannot index a non-list value in {part!r}") current = current[idx] - else: - return None elif isinstance(current, dict): current = current.get(part) else: diff --git a/src/specify_cli/workflows/step/shell/__init__.py b/src/specify_cli/workflows/step/shell/__init__.py index 968f65a914..ca0fa73a75 100644 --- a/src/specify_cli/workflows/step/shell/__init__.py +++ b/src/specify_cli/workflows/step/shell/__init__.py @@ -92,7 +92,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: for name, template in config.get("env", {}).items(): try: value = evaluate_expression(template, context) - except ValueError as exc: + except (ValueError, IndexError, TypeError) as exc: return StepResult( status=StepStatus.FAILED, error=f"Shell step {config.get('id', '?')!r}: env {name!r}: {exc}", diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 56baaa7b16..dfef2cdd72 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -506,6 +506,34 @@ def test_list_literal_followed_by_index_is_not_misparsed_as_one_literal(self): assert evaluate_expression("{{ [[1, 2], 3] }}", ctx) == [[1, 2], 3] assert evaluate_expression("{{ ['a]', 'b'] }}", ctx) == ["a]", "b"] + def test_exponent_literals_and_chained_list_indexes(self): + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.expressions import evaluate_expression + + context = StepContext(inputs={"matrix": [[10, 20], [30, 40]], "label": "1e3"}) + assert evaluate_expression("{{ -2E+3 }}", context) == -2000.0 + assert evaluate_expression("{{ inputs.matrix[-1][0] }}", context) == 30 + assert evaluate_expression("{{ inputs.matrix[-1][1] < 1e2 }}", context) is True + assert evaluate_expression("{{ inputs.label == 1e3 }}", context) is False + assert evaluate_expression("{{ inputs.matrix[9] }}", context) is None + + @pytest.mark.parametrize( + ("expression", "error"), + [ + ("{{ inputs.matrix[0][5] }}", IndexError), + ("{{ inputs.scalar[0][1] }}", TypeError), + ("{{ inputs .matrix }}", ValueError), + ("{{ inputs. matrix }}", ValueError), + ], + ) + def test_invalid_index_chains_and_path_syntax_raise(self, expression, error): + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.expressions import evaluate_expression + + context = StepContext(inputs={"matrix": [[10]], "scalar": "text"}) + with pytest.raises(error): + evaluate_expression(expression, context) + def test_operator_splitting_is_quote_aware(self): from specify_cli.workflows.expressions import ( evaluate_condition, @@ -1802,11 +1830,7 @@ 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. - """ + """A point or exponent makes a float; signs and digit separators are allowed.""" from specify_cli.workflows.expressions import evaluate_expression from specify_cli.workflows.base import StepContext @@ -1822,13 +1846,12 @@ def test_number_literal_forms(self): assert evaluate_expression("{{ [.5, +1] }}", ctx) == [0.5, 1] 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 fail parsing instead of returning data.""" 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_", "1e+", "5..", "."): with pytest.raises(ValueError, match="invalid expression"): evaluate_expression("{{ " + text + " }}", StepContext(inputs={})) diff --git a/tests/unit/test_condition_expression_block.py b/tests/unit/test_condition_expression_block.py index e4d3e2934e..79756e0bf3 100644 --- a/tests/unit/test_condition_expression_block.py +++ b/tests/unit/test_condition_expression_block.py @@ -771,7 +771,7 @@ 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), # Round 7: an operand one level down, which the single-term gate never saw. ("inputs.a === inputs.b", True), ("bogus", True), @@ -827,12 +827,7 @@ 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), ("'one'", True), ('"one"', True), # Two literals, not one: the evaluator requires the opening quote's match to @@ -861,7 +856,6 @@ def test_literal_handling_comes_from_the_evaluator(condition, resolvable): # to None however the index is written. "inputs[0]", "steps[1]", - "1e3", "'a' 'b'", ], ) diff --git a/tests/workflows/test_shell_step.py b/tests/workflows/test_shell_step.py index d34faa215f..656ceb58c0 100644 --- a/tests/workflows/test_shell_step.py +++ b/tests/workflows/test_shell_step.py @@ -301,6 +301,45 @@ def unexpected_run(*args, **kwargs): assert "upper" in result.error +@pytest.mark.parametrize( + ("data", "diagnostic"), [([[0]], "out of range"), ([0], "Cannot index a non-list value")], + ids=["index-error", "type-error"], +) +@pytest.mark.parametrize("continue_on_error", [False, True], ids=["halt", "continue"]) +def test_chained_env_index_failure_respects_continue_on_error( + project_dir, data, diagnostic, continue_on_error, +): + seed = _python_run(project_dir, f"print({json.dumps(data)!r})") + definition = WorkflowDefinition.from_string(yaml.safe_dump({ + "schema_version": "1.0", + "workflow": {"id": "chained-env-index", "name": "Chained Env Index", "version": "1.0.0"}, + "steps": [ + {"id": "seed", "type": "shell", "run": seed, "output_format": "json"}, + { + "id": "invalid", "type": "shell", "strict": True, + "run": "echo should-not-run", + "env": {"VALUE": "{{ steps.seed.output.data[0][1] }}"}, + "continue_on_error": continue_on_error, + }, + {"id": "after", "type": "shell", "run": "echo after"}, + ], + })) + engine = WorkflowEngine(project_dir) + assert engine.validate(definition) == [] + state = engine.execute(definition) + failure = state.step_results["invalid"] + assert failure["status"] == "failed" + assert "env 'VALUE'" in failure["error"] + assert diagnostic in failure["error"] + assert failure["output"]["stdout"] == "" + if continue_on_error: + assert state.status == RunStatus.COMPLETED + assert state.step_results["after"]["status"] == "completed" + else: + assert state.status == RunStatus.FAILED + assert "after" not in state.step_results + + @pytest.mark.skipif(os.name != "posix", reason="POSIX process environment encoding") @pytest.mark.parametrize("value", ["\ud800", "\udc00"]) @pytest.mark.parametrize("template", ["literal", "{{ inputs.value }}", "value={{ inputs.value }}"])