Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/workflows/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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.

Expand Down
23 changes: 13 additions & 10 deletions src/specify_cli/workflows/expressions/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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})*"


Expand Down Expand Up @@ -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
"""
Expand Down Expand Up @@ -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))
Expand Down
54 changes: 41 additions & 13 deletions src/specify_cli/workflows/expressions/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,38 +16,66 @@
# 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-]+$")


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


Expand Down
194 changes: 184 additions & 10 deletions tests/test_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading