Documentation
¶
Overview ¶
Package expr reads and evaluates the OpenJD EXPR extension's expression language.
The package is a self-contained leaf with respect to internal/openjd itself: the only intra-openjd import is internal/openjd/intrange, a leaf shared between the two (see the intrange bullet below), not internal/openjd proper. The dependency with internal/openjd proper still runs the other way — it will import expr once template integration lands — so expr can be tested with no template machinery present.
Usage ¶
e, err := expr.Parse("Param.Frame * 2")
v, err := e.Eval(expr.MapSymbols{"Param.Frame": expr.Int(21)}, expr.TAny)
// v.String() == "42"
Parse reports syntax errors; Eval reports evaluation errors. Both return an *Error carrying a byte offset into the source, rendered as a line and column, so a template author can see which part of an expression failed.
This is a SUBSET of EXPR ¶
This package implements the spec's full type system: a recursive Type with all sixteen type codes (the Recommended Library Interface's Type Codes table — section 1.2.1 itself lists twelve rows and omits any, noreturn and the type variables), automatic coercion between them (section 1.2.3), and static type checking against placeholders for values that do not exist yet (section 1.3.1's unresolved[T]) — "Param.Frame + 1" type-checks to unresolved[int] before any parameter has a value, and "Param.Name + 5" is rejected as a type error the same way, with Param.Name declared but still unbound. Every literal form — including list literals — dotted names and the full ten-level operator grammar are implemented on top of that type system. The rest of the extension is not implemented, and several of the remaining omissions look like bugs when tried by hand. They are not:
"1 + 2.5" now evaluates to 3.5, and "1 < 2.5" to true: section 2.1.1's int-to-float promotion is implemented, and an operator is selected by trying an exact-type match first and a promoting one second. But promotion only ever uses a conversion that cannot fail on any value — int-to-float, path-to-string, range_expr-to-string, range_expr-to-list[int] — never one that can, such as string-to-int. That is why "'a' + 1" is still an ERROR rather than "a1": section 1.2.3's single-scalar catch-all conversion applies when a context (a target type, a coercion) demands a specific type and is prepared for the value not to fit, not when the language itself is choosing which operator overload to run on the caller's behalf. "true + true" is an error for the same reason: no shape accepts (bool, bool), and bool has no promoting route into one that does.
Equality and ordering diverge in how far they reach across types. Section 1.2.5 defines equality for every pair of types, so "5 == 5.0" is true and "'5' == 5" is false — equality never fails, it just isn't always true — and a list or range_expr value follows the same cross-type rule: "[1, 2] == [1.0, 2.0]" is true, and a range_expr compares equal to the list of integers it expands to. Section 2.1.4 permits ordering to cross only two named compatible pairs, int/float and string/path; every other cross-type comparison is an ERROR, so "5 < 'a'" fails with "unsupported operand types" even though "5 == 'a'" evaluates fine (to false). List ordering (lexicographic, section 1.2.5) reaches across element types by exactly those same two compatible pairs, applied ELEMENTWISE: "[1] < [1.0]" is false, not an error, and so is "[[1]] < [[1.0]]" one level down, while "['a'] < [1]" stays an "unsupported operand types" error because string/int is not one of the pairs. That composes section 1.2.5 (list ordering is elementwise, and says nothing about the elements' types) with section 2.1.4 (an ordering operator's operands "may differ for compatible pairs"); it was an error here until this wave, and the error was an artifact of the list ordering shape's single shared type variable rather than a reading of the spec. The unification happens during shape matching (shape.go's orderingUnified), so both operands are coerced to the common element type BEFORE any element is compared. Ordering also reaches the empty list, in either operand position and at any nesting depth: section 1.2.6 rule 6 makes list[nulltype] convertible to list[T] for any T, so "[] < [1]" is true, "[1] < []" is false, and "[[]] < [[1]]" and "[[1]] < [[]]" answer the same way one level down. The empty literal's binding of the shared element-type variable is provisional rather than pinning (shape.go's emptyListBinding), and the exception is applied in BOTH directions — an empty binding meeting a real argument, and a real binding meeting an empty argument — which is what makes the orders agree. Only the first of those two directions existed at first, which is exactly why the nested case worked one way and errored the other.
List literals, subscripts and slices are implemented, and list[T] has real values — "[1, 2, 3]" parses and evaluates. A literal with no target type infers its element type from its own elements per section 1.2.6's unification rules; a list[T] target instead coerces every element to T directly. "x[0]" and "x[1:3]" work on a list, a string or a range_expr (sections 2.1.7 and 2.1.8) — subscript is bounds-checked and errors out of range, while slice clamps like Python. Both also work on a UNION of those, which matters because this package manufactures such a union itself: slicing a range_expr whose length is not yet known is typed "range_expr | list[int]", and section 1.3.1's unknown-condition rule types a conditional as the union of both branches. Every member is indexed and the results combined, so "Param.Range[:][0]" is an int and "([1, 2] if Param.Flag else [3.0])[0]" a float; the operation is rejected only when some member genuinely cannot be indexed. list[T] also has its own operators: concatenation ("+"), repetition ("*" by an int, section 2.1.3) and membership ("in"/"not in") — and, as of this wave, list comprehensions (section 1.3.7) too; see the comprehension bullet below for what that does and does not cover. Subscript and slice have NO differential coverage against the OpenJD reference implementation (make test-expr-oracle), though: verified directly against it under every target tried (int, list[int], float, string, and even a matching type), the reference mis-infers a subscript's or slice's own static result type whenever ANY target type is supplied at all, and is correct only with none — a bug in the reference, not here (see the root-cause-B entries in test/oracle/baseline.txt, which baseline all 22 such corpus cases as a known reference defect). So subscript and slice are checked by this package's own tests and the conformance fixtures only.
List comprehensions (section 1.3.7) are complete, parse and eval: "[x for x in [1, 2, 3] if x > 1]" evaluates. The loop variable's binding follows the section's own shadowing rule — "a loop variable that shadows an existing binding is an error" — checked against the CALLER's symbol table (comp.go's evalListComp), on top of the parser's own <UserIdentifier> casing rule that already keeps a loop variable from colliding with a spec-defined symbol like Param. The shadowing check is only as precise as the caller's table: this package carries no scope information of its own, so a caller that binds a name which is not actually IN SCOPE at this particular expression will produce a false rejection. CORRECTION: an earlier revision of this paragraph said real scope tracking "is sub-project E's, where template integration threads an actual scope through" and gave "a 'let' bound somewhere else in the template" as the standing example of a false rejection. Sub-project E has now done that: internal/openjd's checkTemplateExpressions threads a per-position table built from section 3.6.2's scope model, so that specific false-rejection risk is closed for that caller — a step's own "let" is visible in its own script but not a sibling step's, and the table handed to this package's comprehension check reflects exactly that at each expression position (internal/openjd/exprcheck_let_test.go pins it, section by section). The general caveat above still holds for ANY caller, this package included: it carries no scope information of its own, so it can only ever be as precise as whatever table it is handed. The iterable and the filter are both parsed at the OR level (parser.go's parseOr), not the full <ConditionalExpr> section 1.1.2's own grammar names for them, because that grammar is ambiguous there: parseConditional consumes a bare "if" expecting an "else" to follow it, so "[x for x in y if c]" would fail hunting for one. A conditional in either position therefore needs parentheses — "[x for x in (a if b else c)]" — which is exactly how Python resolves the same ambiguity (comp_for and comp_if both take an or_test, not a full conditional). A STRING IS DELIBERATELY NOT ITERABLE: the spec never defines iterating one, and section 2.1.2 already gives "in" over a string a different meaning, a substring test, so "[c for c in 'abc']" is a "cannot be iterated" error rather than a list of characters. A UNION iterable follows the same every-member rule a subscript and a slice already apply to a union receiver: it is iterable only when EVERY member is, with the members' element types unified per section 1.2.6. That keeps "range_expr | list[int]" — the union this package manufactures itself for a slice of a range_expr whose length is not yet known — iterable as int, while "list[int] | nulltype" and "range_expr | list[string]" are both rejected rather than silently typed as their list member. An EMPTY iterable produces "[]" with the element expression never evaluated, and therefore never type-checked: "[Bogus for i in Param.Empty]" is "[]", not an unknown-symbol error. That is deliberate rather than a gap — the spec requires no static check of a body that never runs, and the reference implementation answers identically. Rejected outright, each with its own parser error: a second "for" clause and a second "if" filter (Python's multi-generator and multi-filter forms) and a generator expression ("(x for x in y)"). A dict or set comprehension ("{k: k for k in y}", "{x for x in y}") is rejected earlier still, IN THE LEXER — "{" is not a token this grammar defines at all, so there is no parser production to reject it in; it never reaches one. The comprehension is a SECOND way to do unbounded total work in a single expression, alongside B2's nested-repetition growth: nesting one comprehension inside another's element expression multiplies the inner work by the outer iteration count at every level, the same shape of growth "[[0]*10000000]*10" already had. checkElementCount (limits.go's maxElements) bounds one comprehension's own RESULT, not the cumulative work of producing every nested level along the way; the CUMULATIVE work is what section 1.3.10's operation-bounded evaluation was for, and sub-project E1 landed it: runComp (comp.go) charges rule 2 for every element the comprehension iterates, at EVERY nesting level, so the multiplied work now spends against the same operation budget as the rest of the expression, one charge per level per iteration, and the limit fires before the multiplication runs away (TestOperationLimit_CatchesANestedComprehension, the fixture-shaped regression test for exactly this construct). See the BOUNDED EVALUATION bullet below for the two limits themselves.
Function, method and property calls now PARSE AND RESOLVE — "len([1])", "[1,2].upper()" and "Param.Name.stem" no longer fail as unsupported syntax — and the registry they resolve through, functionShapes (funcs.go, assembled by its own mergeFuncs), now holds 80 entries: sub-project C1's four groups — general conversions (len, bool, string, int, float, list, range_expr — funcsconv.go), validation (fail, the same file, its own RFC 0006 category despite living beside the conversions in one Go source file), math (abs, min, max, sum, floor, ceil, round — funcsmath.go), and list functions (range, flatten, sorted, reversed, unique, any, all — funcslist.go) — sub-project C2's string library, across four files: case transforms and classification (upper, lower, capitalize, title, isdigit, isalpha, isalnum, isspace, isupper, islower, isascii — funcsstrcase.go), trim, affix and search/replace (strip, lstrip, rstrip, removeprefix, removesuffix, startswith, endswith, count, find, rfind, index, rindex, replace — funcsstrfind.go), split, rsplit and join (funcsstrsplit.go) and padding (ljust, rjust, center, zfill — funcsstrpad.go) — sub-project C3's two hard-grammar families across four more files: regular expressions (re_match, re_search, re_findall, re_sub, re_escape, re_split — funcsre.go, behind its own translated dialect in repattern.go — see the regex bullet below) and repr_* (repr_sh, repr_cmd, repr_pwsh — funcsreprshell.go — and repr_py, repr_json — funcsreprdata.go — see the repr_* bullet below) — and sub-project C4's path engine, all of it in funcspath.go over the three-flavor pure-path engine in pathval.go: construction and predicates (path, as_posix, is_absolute), the six properties, which are registered under their __property_*__ spellings and so are six of the 80 (__property_name__, __property_stem__, __property_suffix__, __property_suffixes__, __property_parent__, __property_parts__), the with_* family and the relative pair (with_name, with_stem, with_suffix, is_relative_to, relative_to), and with_number, whose substitution scanner lives in pathnumber.go. Section 2.1.5's "/" and "+" path operators ship in the same wave but are operator-table rows (ops.go), not registry entries, so they are not among the 80 — see the path bullet below for all of it. The eightieth entry is sub-project D's apply_path_mapping, which is registered from its own pathMappingFuncs group beside the engine it wraps (pathmapping.go) rather than from C4's pathFuncs, because it is the one function in the registry that reads SESSION state — the path-mapping rules WithPathMapping threads through evalCtx — see the path-mapping bullet below.
WITH IT, SECTION 2.2's ROUGHLY 100-FUNCTION LIBRARY IS ENTIRELY REGISTERED: no library name is left unregistered, in any sub-project. An unknown call still fails at RUNTIME with "unknown function", a real diagnostic rather than a parse error — "no_such_function('/mnt/share')" reports `unknown function "no_such_function"`, not a syntax error, verified directly, exactly as every library name did before C1.
THAT WORKED EXAMPLE DELIBERATELY NAMES SOMETHING THAT IS NOT, AND WILL NEVER BE, A LIBRARY FUNCTION. Every earlier revision pointed it at a real name from a sub-project that had not shipped yet, and every one went stale when that sub-project shipped — FOUR times: re_match until C2, repr_* until C3, with_suffix until C4, and apply_path_mapping until this wave. Each time the example began demonstrating a DIFFERENT mechanism under the same prose: "with_suffix('/foo/bar.txt', '.png')" reports `no signature of "with_suffix" accepts (string, string)`, and "apply_path_mapping('/mnt/share')" now returns the path "/mnt/share" outright (both verified directly) — overload selection and a clean evaluation, not the unknown-function lookup the paragraph is about, which is exactly the misreading a stale example invites. There is no unregistered library name left to re-point it at a fifth time, and it must not be re-pointed at a real one: a name nothing registers is the only spelling of this example that cannot go stale. (Not every call reaches the registry at all: a dunder callee like "__add__(1, 2)" is rejected before lookup with "is a specification naming convention and is not directly callable", and a callee whose whole dotted name resolves to a symbol — "Param.Name()" when Param.Name is bound — fails "Param.Name is not a function".)
THREE of C2's rulings look like bugs when tried by hand, and are not. RFC 0006 defines none of the three, so each is adjudicated here and recorded in test/oracle/baseline.txt where it diverges from the reference.
isdigit() is ASCII-ONLY, so isdigit('٣') is false — verified directly, and it matches the reference, preserving the guard-then-convert idiom: under a Unicode definition isdigit('٣') would be true while int('٣') still fails. isalnum() then COMPOSES from isalpha and isdigit, which DIVERGES from the reference: sqi answers isalnum('٣') false, since isalpha('٣') and isdigit('٣') are both false, while the reference answers isalnum('٣') true on that same input — a self-contradiction RFC 0006 gives no basis to follow, so the reference's own inconsistency, not agreement with it, is the adjudication (recorded in test/oracle/baseline.txt).
capitalize('fine day') is "FIne day", not "Fine day" — verified directly, and the reference agrees, so this is NOT a baselined divergence. upper() and lower() apply FULL Unicode case mapping via golang.org/x/text/cases, which expands the fi ligature to two uppercase letters, and capitalize is RFC 0006's "Capitalize first character, lowercase rest" read literally, so the first rune is uppercased rather than titlecased. Python answers "Fine day" only because it titlecases the first character instead.
title() breaks words on isalnum's OWN predicate, so title('a_b c') is "A_B C" (an underscore separates two words) while title('a1b c') is "A1b C" (a digit does not) — both verified directly. Using the reference's Unicode notion of a word boundary while isalnum stays ASCII-only would put two conflicting definitions of "alphanumeric" in one file, so title('²x y') is the one baselined divergence that ruling produces (test/oracle/baseline.txt).
Uniform function call syntax (section 1.3.3) makes "x.f(a)" resolve through the same callFunction as "f(x, a)", with the receiver prepended to the argument list — EXCEPT that section 1.2.4 suppresses implicit coercion on a method receiver specifically, a call-site property this package does implement (callFunction's methodStyle), and C1's own registry is now the first place a caller can observe it directly with no test-only function involved: round's single-argument row is declared over TFloat alone, so "round(3)" resolves in FUNCTION position by promoting the int argument to float (returning the int 3, since that row's own return type is int), while "Param.N.round()" with Param.N bound to that same int FAILS — "no signature of \"round\" accepts (int)" — because the receiver never gets the promotion the argument position received, verified directly against both call forms. TestReceiverCoercionRestriction (call_internal_test.go) now targets the SHIPPED startswith from funcsstrfind.go rather than a synthetic function it registers itself — the spec's own worked example is startswith(path, string), which exercises the restriction by COERCION: the receiver must fail to coerce into a (string, string) signature for the restriction to be observable at all. C1 had to register one because it shipped no (string, string) overload for a path receiver to be refused by; C2's string library supplies one, so a path receiver now genuinely fails to match it. One further exception already exists in the shipped registry: [].len() and len([]) both resolve and both return 0 (TestLen_EmptyListReceiver) — not because the receiver restriction was relaxed, but because there is nothing for it to restrict. list[T]'s receiver-position binding of the unbound element variable T to nulltype (the empty literal's own type) converts no value at all; section 1.2.4 suppresses a COERCION on the receiver, and binding a type variable is not one. That restriction is applied to a PROPERTY receiver as well (resolve.go's evalProperty passes methodStyle), which is an adjudication and not an inherited detail: section 1.3.3 defines "x.p" as method syntax over "__property_p__", and section 1.2.4 suppresses coercion on the receiver of a method call, so a property's receiver is not coerced either. It is consequential for the path engine's properties (C4's) rather than academic — it decides, for a "__property_stem__(path)", that "Param.S.stem" on a STRING parameter is an error instead of a silent string-to-path conversion. The reference implementation agrees, checked directly: "'/a/b.txt'.stem" reports "'stem' property is not available for string. Available for: path". TestPropertyReceiverCoercionRestriction pins it with a path receiver against a "(string)" property signature registered locally by the test — C1 registers no properties at all — which is the only receiver type where the flag is observable in the first place: every other type that reaches a string parameter does so by a conversion overload selection would refuse anyway, so the test would pass with the restriction switched off. Property syntax (section 1.3.3) is sugar for a call to __property_p__, dispatched through the same registry, so a property access to a name NOTHING has registered fails through the identical unknown-function mechanism — but NOT with the identical message: it is deliberately reworded to "unknown property" (resolve.go's evalProperty) so that a genuine runtime error inside a property that DOES exist is never relabeled as a missing one. "Param.Name.nosuchprop" (Param.Name bound to a string) reports `unknown property "nosuchprop" on string`, not `unknown function "__property_nosuchprop__"`. "Param.Name.stem" on that same string receiver is the OTHER branch, and went stale exactly the way the with_suffix worked example above warned a path-family example would: it named the "unknown property" wording until C4's Task 6 registered __property_stem__ for real, and now verified directly, it instead reports `no signature of "__property_stem__" accepts (string)` — the receiver-restriction message two paragraphs up, not this one, because the property is no longer unknown. A dotted name that reaches a method or property call is split by LONGEST-PREFIX resolution against the caller's own symbol table (resolve.go's resolveName): "Param.Name.upper()" tries "Param.Name.upper" as a bound symbol first, then "Param.Name", stopping at the first prefix the caller's table actually binds. This package hardcodes no namespaces of its own — the caller's table is authoritative, exactly as it is for the comprehension shadowing check above — so a caller that binds both "a.b" and "a.b.c" gets "a.b.c" resolved to the SYMBOL rather than to a property "c" of "a.b". Nothing of the ~100-function library is left unregistered, sub-project D's apply_path_mapping having been the last of it; the type-variable codes (CodeVarT and friends) and the matcher's binding of them already live here in shape.go, and C1's own list[varT] rows — len(), bool(), string()'s list row, and flatten(), sorted(), reversed() and unique() from the list-function group — are the first functions to bind that variable for a genuinely polymorphic signature.
FIVE of C3's rulings look like bugs when tried by hand, and are not. RFC 0006 defines none of them precisely enough to settle by reading alone, so each was verified directly against Go's regexp package, Python's re module and the reference implementation, and is recorded here and in test/oracle/baseline.txt where it diverges from the reference.
The accepted regex dialect is NARROWER than the reference's. RFC 0006 defines the dialect as "the intersection of Python's re module and Rust's regex crate", and sqi enforces that STATED RULE rather than merely the spec's own explicit list of rejected constructs, so re_search('3', r'\p{Nd}'), re_search('ab', r'(?<n>a)b') and re_search('a', r'[[:alpha:]]') are all rejected — verified directly — even though the reference accepts all three. Checked against real Python's re module directly, not just against the spec text: it rejects \p{Nd} ("bad escape \p") and (?<n>a) ("unknown extension ?<n") outright, matching sqi, but it does not reject [[:alpha:]] at all — it reads the whole bracket expression LITERALLY, as a class holding the characters '[', ':', 'a', 'l', 'p', 'h' followed by a literal ']', so "a" alone does not match it and "a]" does. That is a different rejection from sqi's (sqi refuses to compile the pattern at all; Python compiles it into something that matches almost nothing anyone intended), which is exactly why RFC 0006 excludes POSIX classes from the intersection rather than leaving them to either engine's own reading.
\W and \S inside a NEGATED character class are rejected — a STATED COMPLIANCE GAP, not an oversight: re_search('a!', r'[^\Wa]') errors with "\W inside a negated character class needs set subtraction, which Go's engine cannot express", verified directly, because "not a word character, minus 'a'" is set subtraction and RE2 (which backs Go's regexp, and the reference's own engine) has no operator for it — the reference itself does not reject this pattern, but silently returns null (no match) for every input, which is not a well-formed reading of the dialect either; see test/oracle/baseline.txt. Inside a POSITIVE class the same shorthand works, by REWRITING the class into an alternation rather than emitting it in place — re_search('a!', r'[\Wa]') matches, verified directly — and a class may hold any number of \W/\S occurrences this way, each distinct shorthand becoming its own alternation branch (scanClass, classNeedsAlternation).
\d, \w and \s are UNICODE, not Go's ASCII-only defaults — every pattern is translated by translatePattern (repattern.go) before it ever reaches Go's engine, and that translation is what makes them Unicode: verified directly, re_search('٣', '\d') matches the Arabic-Indic digit ٣, which Go's own \d does not.
repr_sh and repr_py follow the PYTHON FUNCTIONS RFC 0006 names them after — shlex.quote and repr respectively — which produce different TEXT from the reference implementation for the same input, verified directly: repr_sh("it's") is 'it'"'"'s' here (shlex.quote's close-quote/literal-quote/reopen-quote splice) and "it's" there (a different, but shell-safe, quoting strategy); repr_py("it's") is "it's" here (Python repr()'s own quote-switching rule: prefer a single quote, switch to double when the string holds a single quote and no double) and 'it\'s' there (always single-quote, escape instead of switching). repr_sh's difference is TEXTUAL ONLY — both forms are shell-equivalent and safe, unlike a hypothetical quoting bug, which is why this file lives apart from the serialization functions next door (funcsreprshell.go's own comment). Both divergences are baselined in test/oracle/baseline.txt as the reference's own bug: RFC 0006 names the Python function, and sqi's output is what that function actually produces.
repr_json does NOT share writeJSONValue, string()'s list-rendering helper (funcsconv.go) — string(list) and repr_json genuinely differ on non-ASCII input, in the reference too, verified directly against both: string(['café']) is ["café"] (non-ASCII left literal, matching the reference exactly) while repr_json('café') is "caf\u00e9" (ASCII-only output with a generic four-hex-digit escape, matching Python's json.dumps default ensure_ascii behavior, which the reference also matches). RFC 0006 calls string()'s list row "the JSON string representation" with no ensure_ascii qualification and separately names repr_json after json.dumps, whose DEFAULT is ensure_ascii=True — two different specified behaviors landing in two different functions on purpose, not a missed opportunity to share code.
flatten()'s row ORDER is load-bearing — listFuncs (funcslist.go) is the first table in the package where it is. "flatten([[1],[2]])" matches BOTH its nested row (list[list[T]] -> list[T]) and its flat row (list[T] -> list[T]) at cost 0, since [[1],[2]] is simultaneously a list[list[int]] (T = int) and a list[list[int]] read as list[T] with T = list[int]; matchShapesExactFirst breaks an exact-cost tie to the EARLIEST registered shape, not by any property of the argument. The nested row is listed first for exactly that reason: reversing the two would make flatten() the identity on every argument, silently, with no type error to catch it.
path and range_expr exist as types — TPath and TRangeExpr participate in Type, coercion and cross-type equality, and a declared parameter can be typed as either. path has no literal syntax of its own, but a value IS produced by evaluation: string -> path is section 1.2.3's own coercion rule, so Eval(src, syms, expr.TPath) returns a path value for any expression that evaluates to a string. path now has semantics of its own on top of that — its three flavors, its URI awareness, its properties and functions, and section 2.1.5's "/" and "+" — all delivered by sub-project C4 and described in the path-engine bullet below. RFC 0006 puts the whole family in the function library, which is why C4 owns it and D does not; D is narrower than that split once suggested: apply_path_mapping, the Param/RawParam split, and mapping into typed parameter values — the first of those has now shipped, and has the path-mapping bullet below to itself. range_expr, by contrast, still has no operator of its own beyond what coercion gives it for free. The range_expr -> list[int] conversion (section 1.2.3) is fully implemented — coercing a range_expr value to a list[int] target expands it — and so is section 1.2.5's list/range_expr cross-type equality rule, both exercised above. What coercion gives a range_expr OPERAND for free is deliberately narrow, and the narrowing is an adjudication rather than a gap: section 1.2.3's range_expr -> string rule reaches a string PARAMETER only for the operators whose own tables name a range_expr row, which is "+" alone — sections 2.1.2 and 2.1.3 write those rows out explicitly, and would not need to if the coercion fired on its own during overload selection. So "Param.Range + '!'" still concatenates as text, while "Param.Range * 2" and "'1' in Param.Range" are "unsupported operand types" errors rather than the string repetition "1-101-10" and the substring test over "1-10" they used to be. The reference implementation rejects both as well.
range_expr has real values, and sub-project C1's range_expr() function (funcsconv.go) is now the language's own way to construct one — the first since "nothing coerces to it, and nothing constructs it" was written. range_expr(string) parses the spec's <IntRangeExpr> grammar (via internal/openjd/intrange, the same leaf internal/openjd itself uses) and keeps the source text verbatim rather than canonicalizing it; range_expr(list[int]) sorts and de-duplicates its input, then builds the canonical string through canonicalRange (rangeexpr.go) — the same function this package already used internally to derive a range_expr from a SLICE of one (slice.go's sliceRangeExpr). Sub-project E's CHUNK[INT] symbol remains a second, still-unimplemented way to get one. Because a bare expression can now construct a range_expr with no symbol table, it also has DIFFERENTIAL coverage for the first time (make test-expr-oracle, corpus.txt's range_expr(...) cases) — which is what surfaced a canonicalization gap rather than closing the topic outright: range_expr(string) keeps "1-10:2" as entered, while the reference reports the canonical "1-9:2" (the end corrected to the last value the step actually produces), and the same gap resurfaces wherever that string is read back out — string(range_expr(...)) and range_expr as an operand of "+". range_expr(list[int]) itself is NOT part of the gap: canonicalRange agrees with the reference on every list-constructed case in the corpus. All of it is baselined in test/oracle/baseline.txt as a known gap, deferred to sub-project E along with the rest of section 1.3.4's pass-through requirements.
THE PATH ENGINE (sub-project C4) is complete: three flavors, every path property and function RFC 0006 defines, and section 2.1.5's "/" and "+" operators. apply_path_mapping was the one name it left out, and sub-project D has since registered it — it has the PATH MAPPING bullet below to itself, because its source matching is deliberately NOT this engine's path equality. A path value here is PURE — no filesystem is touched, nothing is resolved or stat'ed — and it is NORMALIZED BY CONSTRUCTION, because Value.Path re-parses its text. That is what makes RFC 0006 line 767's own guarantee, path(p.parts) == p, hold for every shape, and it is why "/" and "+" re-normalize their results where the reference implementation stores the joined text raw.
path_format is an EVALUATION option (WithPathFormat, eval.go), not a property of the host, and its default here is POSIX — which differs from the specification's own default of host-native, deliberately. sqi parses templates SERVER-SIDE, so a host-derived default would let one template expand into different tasks depending on which machine submitted it; the spec itself names POSIX as what TEMPLATE scope wants, "to ensure consistent behavior regardless of the submission machine's OS", and template parsing is exactly that scope. PathNative exists and resolves to the running GOOS, but nothing in sqi selects it yet — sub-project E does, for host contexts. Verified with no option at all: path('C:/a') renders "C:/a" and its is_absolute() is false (a drive letter means nothing to POSIX), while WithPathFormat(PathWindows) gives "C:\a" and true.
A URI IS NOT A FLAVOR. It is detected from the text under every path_format, by the spec's own scheme grammar, and a URI NORMALIZES NOTHING: consecutive slashes, "." segments and a trailing slash all survive, because a URI path component is an opaque identifier and "a//b" and "a/b" may name different objects in a store. Verified: path('s3://bucket/a//b/./c') renders back verbatim under both filesystem flavors, and its parts are ["s3://bucket", "a", "", "b", ".", "c"] — the empty component and the "." are real components, where a POSIX or Windows path would have collapsed both.
"+" NOW RETURNS A PATH where it used to return a string. Before this wave a path operand simply coerced to string and the (string, string) row answered; RFC 0006's section 2.1.5 table declares __add__(path, string) with a path return, so "path('/a/b') + 'c'" is the path "/a/bc", verified. path + path reaches that same row through section 1.2.3's path -> string coercion at cost 1, beating the (string, string) row at cost 2, so it is typed path too — the reference types it string, and the divergence is baselined. A caller that wanted the old string result must ask for one (a string target, or string()).
THE RULINGS BELOW look like bugs when tried by hand and are not. (The heading used to give a count, and no reading of what follows ever produced it: named rulings and a "smaller divergences" block are two different lists, and the number could only ever be right for one of them.) Each was adjudicated against third_party/openjd-specifications/ and, where it diverges from the reference, recorded case by case in test/oracle/baseline.txt — that file, not this comment, is the place to check an individual row.
PATH COMPARISON IS BYTE-EXACT AND CASE-SENSITIVE FOR EVERY FLAVOR, WINDOWS INCLUDED. path('C:/A') == path('c:/a') is FALSE here under WithPathFormat(PathWindows); CPython's PureWindowsPath casefolds and answers True (measured). The specification is silent, and the reference agrees with sqi. This was raised twice during the sub-project and kept both times, for the same reason path_format defaults to POSIX: an expression evaluated server-side must not answer differently because of a host convention, and a case-folding equality would make two templates that differ only in the case of a path literal expand into the same tasks on one flavor and different tasks on another. Determinism and host-independence outrank imitating one platform's filesystem.
as_posix IS FLAVOR-AWARE: it replaces the FLAVOR'S OWN separator with "/", so it is the IDENTITY under POSIX and on a URI, and a "\" -> "/" rewrite only under Windows. path('/renders/shot_a\b.exr').as_posix() is therefore unchanged, verified. The unconditional backslash rewrite it replaced was refuted by this engine's own values rather than by a preference between readings: under POSIX a backslash is an ordinary filename character, so that same path's parts are ["/", "renders", "shot_a\b.exr"] and its name is "shot_a\b.exr", while as_posix answered "/renders/shot_a/b.exr" — a different path with different parts. It also rewrote a URI object key ("s3://bucket/a\b" to the DIFFERENT key "s3://bucket/a/b"), contradicting the "a URI NORMALIZES NOTHING" rule three paragraphs up. CPython settles the direction: PurePath.as_posix() is str(self).replace(self.parser.sep, '/'), and RFC 0006 line 857 names as_posix among the functions that "match Python's pathlib API" — the same clause that settles stem/suffix below. The reference agrees with the OLD behavior and has the identical contradiction (its parts keep the backslash too), so this is a baselined divergence, argued case by case in test/oracle/baseline.txt.
with_number REPLACES THE LAST MATCH, per RFC 0006 line 822 — "searches the filename stem from the end for these patterns and replaces the last match". A match is one bounded run of ONE placeholder kind (a printf specifier, a '#' run, a digit run), not everything from where a run starts to the end of the stem, so "##a3" holds TWO candidates and only the digits are replaced: with_number('##a3', 7) is "##a7", verified. The reference lets a '#' run swallow the remainder of the stem and answers "07", DESTROYING the literal "a" the caller wrote — a defect against its own specification's wording, not a second reading of it. Do not change sqi to match it; corpus.txt deliberately also carries the rows where the two agree, so an overcorrection fails there rather than trading one set of answers for another silently.
stem, suffix AND suffixes FOLLOW CURRENT CPython pathlib, which rewrote them to strip the whole LEADING DOT RUN before splitting (and therefore to treat a TRAILING dot as a suffix); the reference implements the older rule, which guarded only a single leading dot. So path('a.').stem is "a" with suffix "." and suffixes ["."], and path('/a/..b').stem is "..b" with no suffix — all verified here, and measured directly against CPython. The same splitStemSuffix backs with_stem, with_suffix and with_number, so the rule reaches those too. THE VERSION BOUNDARY: 3.12 still has the old rule and 3.14 has the new one, measured on python3.12 and python3.14 side by side; 3.13 was not installed and was NOT tested, so the boundary is somewhere in (3.12, 3.14] and this comment does not name a single version. RFC 0006 says "matches Python pathlib.PurePath behavior" and links the CURRENT documentation, which is what settles it in favor of the current rule rather than the reference's.
A TRAILING EMPTY COMPONENT ON THE BASE of relative_to/is_relative_to is CONSUMED. Section 2.1.5 rules that "a trailing slash on the left operand is consumed by the join (matching pathlib behavior)", and the base of these two functions is an operand of exactly that kind, so an operator-written prefix like "s3://renders/" must match the objects under it. Parsing, meanwhile, PRESERVES an empty component verbatim (Expression-Language lines 754-755) — the URI rule above. Those two rules are both right and together they produce a COHERENCE ARTIFACT worth stating outright, because it looks like a bug: path('s3://b//') == path('s3://b') is FALSE (their parts differ: ["s3://b", "", ""] against ["s3://b"]), and yet each IS relative to the other and relative_to returns "." in BOTH directions — all four verified. Equality compares the parsed values; relative_to consumes a boundary run on the base before comparing. The reference consumes the same run everywhere the receiver has something after the base, and then does not consume it in the self case, which makes its answers internally inconsistent rather than differently ruled.
THE REFERENCE'S PATH FAMILY IS POSIX-ONLY, so it cannot adjudicate the Windows flavor at all: it accepts a backslash as a replacement name, and never switches on a drive even for a drive-looking receiver like "C:/a/b" (both measured). Every Windows expectation in this engine is therefore pinned by this package's own unit tests against CPython's PureWindowsPath, NOT by make test-expr-oracle, and the corpus carries no Windows-flavor case at all. URI behavior IS oracle-measurable, because a URI is detected under the reference's POSIX format too, and the corpus covers it heavily.
THREE SMALLER DIVERGENCES, each deliberate, each recorded beside the code that produces it rather than only here:
The "\\?\UNC\" extended-length prefix is NOT parsed. pathlib gives that one literal prefix its own start-at-offset-8 parsing, splitting a further server+share out of what follows, so "\\?\UNC\srv\share\x" is ONE opaque root plus "x" to Python; here it runs through the ordinary offset-2 UNC algorithm and comes out with root "\\?\UNC\" and "srv", "share", "x" as ordinary components — a different split, not merely a different rendering, and the only extended-length or device shape known to diverge (a plain "\\?\a\b" or "\\.\a\b" agrees with CPython, measured both ways). Reserved device NAMES ("NUL", "CON") are not special-cased either, and neither are they by pathlib's PURE paths. See parseWindows.
path('//srv/share/x') / '//srv/share' ANCHORS here, giving "\\srv\share\", where CPython keeps the parent's "x" and answers "\\srv\share\x" (measured). sqi is arguably the more spec-faithful side: section 2.1.5 says an absolute right operand replaces the left entirely, and "//srv/share" is_absolute() is true in both engines. The mechanical cause is that splitRootWindows also ports pathlib's root-SYNTHESIS heuristic, which ntpath.splitroot does not have, so a complete server+share pair carries a root here and the join's anchor arm fires. See pathJoin.
path('C:') + '//b' YIELDS A URI, "C://b", with parts ["C://b"] and is_absolute() true, under every path_format including Windows — because the spec's own scheme grammar, ^[a-zA-Z][a-zA-Z0-9+.-]*://, accepts a ONE-LETTER scheme (a star, not a plus) and URI detection runs before any flavor is consulted. Special-casing a single-letter scheme so a drive wins would be sqi inventing a rule the specification does not have, on a shape no real template produces. See splitURI.
PATH MAPPING (sub-project D) ships apply_path_mapping, the last name the RFC 0006 library was missing, over a prefix-mapping engine local to this package (pathmapping.go's mapPath). It is registered FLAT — always resolvable, in every scope — from its own pathMappingFuncs group rather than from C4's pathFuncs, because it is the only function in the registry that reads session state: the rules WithPathMapping (eval.go) threads through evalCtx.
WITH NO RULES IT PASSES ITS INPUT THROUGH, NORMALIZED AS A PATH VALUE IN THE EVALUATION'S FLAVOR: apply_path_mapping('/mnt/share') evaluates with no option at all to the path "/mnt/share" (verified directly). "Passthrough" names the MAPPING outcome — no rule rewrote the text — not a verbatim string return: the result is always re-parsed by boundedPath in ec.pathFormat, so apply_path_mapping('/a//b/') is the path "/a/b" and apply_path_mapping('/a/b') under WithPathFormat(PathWindows) is "\a\b" (both verified). That normalization is required rather than incidental — the vendored fixture expr2.3.2--apply-path-mapping's output_windows line for its POSIX_UNMAPPED case expects a slash-shaped input that matched no rule to come back with Windows separators, which only happens because the passthrough is re-parsed. That is not a placeholder — it is the specified behavior when nothing matches — and it is what every current caller gets, because nothing in sqi passes WithPathMapping yet. Sub-project E is what will. Rules are tried in order of DECREASING SourcePath length and the first match wins, so the more specific rule wins whatever order the caller listed them in: with "/a" -> "/short" listed BEFORE "/a/b" -> "/long", apply_path_mapping('/a/b/c') is "/long/c" (verified).
A WINDOWS SOURCE MATCHES CASE-INSENSITIVELY AND SEPARATOR-INSENSITIVELY, which is DELIBERATELY NOT C4's path equality. Path EQUALITY (==) and relative_to/is_relative_to compare components byte-exactly and case-SENSITIVELY on every flavor including Windows (the path bullet above explains why: determinism for a server-side expansion). Those are the operations the contrast is with, and the claim is deliberately not widened to "everything else in the package": the / operator already case-folds, because pathJoin (pathval.go) compares the two operands' DRIVES with strings.EqualFold, as ntpath.join does — so path('C:/a') / 'c:b' keeps the parent and gives "c:\a\b", where path('C:/a') / 'd:b' discards it and gives "d:b" (both verified under WithPathFormat(PathWindows)). That fold predates D and is the only case-insensitive comparison C4's path engine makes — pathJoin's drive test is the package's only strings.EqualFold outside pathmapping.go. Source MATCHING is a different operation from path EQUALITY, and the two answers genuinely disagree on the same pair of paths: a WINDOWS rule whose SourcePath is `C:\studio` maps 'c:/STUDIO/project/scene.ma', while path('C:/Studio') == path('c:/studio') is FALSE and is_relative_to(path('C:/Studio/a'), path('c:/studio')) is FALSE, both under WithPathFormat(PathWindows) — all three verified directly. The insensitivity is confined to the rule comparator (applyFileRule passes strings.EqualFold to relativeParts, which is otherwise the SAME function is_relative_to uses); a POSIX rule does not casefold, so a "/Projects" rule leaves '/projects/a.exr' untouched (verified).
ITS PARAMETER IS A STRING AND ITS RESULT IS A PATH, which makes the section 1.2.4 receiver restriction visible in a new place: the result chains, so apply_path_mapping('/projects/shot01/out.exr').stem is "out", but a PATH receiver is refused — path('/projects/a').apply_path_mapping() reports `no signature of "apply_path_mapping" accepts (path)`, because a method receiver is not coerced. Both are pinned by TestApplyPathMapping_ResultChainsButAPathReceiverIsRefused. Two calls therefore do not compose directly; ask for a string in between.
IT HAS NO ORACLE COVERAGE, and cannot get any through the current harness: scripts/expr-oracle.py calls the reference's evaluate_expression(src, target_type=...), whose only two knobs are the source text and the target type, so there is no channel for session mapping rules and none of test/oracle/corpus.txt's cases name this function. Everything above is pinned by unit tests in this package alone, the same position C4's Windows semantics are in.
Those unit tests are NOT all invented, which is the one thing that distinguishes this function's position from C4's. The conformance suite ships three fixtures written against apply_path_mapping itself — EXPR/jobs/expr2.3.2--apply-path-mapping.test.yaml and its --uri-source-path-mapping-posix and --uri-source-path-mapping-windows siblings — carrying 31 hand-authored expected strings across their expected.output/output_posix/output_windows blocks, rules and all. The scored harness never reads them: collectTemplateFixtures (test/conformance/suite_test.go) keeps only the job_templates and env_templates kinds, and the EXPR path reads exprSuiteDir — "EXPR/job_templates" — alone, since EXPR/jobs needs a real session and a python subprocess. They are therefore transcribed into TestApplyPathMapping_VendoredFixtureExpectations (35 assertions — the four flavor-independent ones run under both formats), which is specification-authored ground truth rather than sqi's own reading, and is the only external check this function has.
SQI NOW CARRIES TWO PATH-MAPPING IMPLEMENTATIONS, and that is by design rather than an oversight left to be found later. internal/worker/pathmap does a strings.ReplaceAll SUBSTRING swap anywhere in a command string; this engine matches a PREFIX on component boundaries and rebuilds the remainder in the destination flavor. They serve different jobs, and this leaf package cannot import that one anyway. Reconciling them is possible future work, not D's.
HOST-CONTEXT ENFORCEMENT IS NOT HERE. RFC 0006 makes apply_path_mapping valid only in host-context (@fmtstring[host]) scopes and an error anywhere else, and this package has no scope model to enforce that with — sub-project E does. The cost is recorded rather than hidden: registering the function turned EXPR/job_templates/7.3--apply-path-mapping-in-job-name.invalid.yaml and its -in-timeout sibling from passing to failing (conformance 145 -> 143), because both were only ever rejected by "unknown function" and not by the placement rule they actually violate. Both are baselined in test/conformance/baseline-expr.txt with that reason (that file was deleted by sub-project H2; read it in git), and burn down when E can reject them for the right one.
BOUNDED EVALUATION (sub-project E1) delivers the specification's two configurable resource limits — section 1.3.9's memory-bounded evaluation and section 1.3.10's operation-bounded evaluation — both in this wave, both through meter.go.
TWO OPTIONS, ON BY DEFAULT, NO UNLIMITED MODE. WithMemoryLimit(bytes) bounds the live memory, in bytes, that one evaluation's values hold at once; it defaults to 100,000,000. WithOperationLimit(ops) bounds the number of section 1.3.10 operations one evaluation may perform; it defaults to 10,000,000 (eval.go). Both apply with NO option passed at all — a caller that forgets the option is not left unbounded, which mattered because the conformance harness's EXPR-only scoring path (conformance.RunExprCase, since deleted by sub-project H2) evaluated with no options, and the two expr1.3.10 conformance fixtures below only burn down if a no-option evaluation is already bounded. There is no unlimited escape hatch: a non-positive value to either option is a caller error, reported by Eval (verified directly: WithMemoryLimit(0) and WithOperationLimit(-1) both fail with "... must be positive, got ...").
THE FLOOR RELATIONSHIP. limits.go's five hard, non-configurable bounds — maxElements, maxStringBytes, maxParseDepth, maxEvalDepth and maxSourceBytes, all described above — sit UNDERNEATH these two configurable ones and are not raised by them: raising WithMemoryLimit does not raise what one operation may allocate. Evaluating "'a' * 20000000" under WithMemoryLimit(1_000_000_000) — a budget ten times the string it would produce — still fails, and on the SAME error as with no option at all: "col 5: the result is too large: repeating 1 elements 20000000 times exceeds the limit of 10000000", with errors.Is(err, errTooLarge) true and errors.Is(err, errMemoryLimit) false (both measured directly). checkRepeat's maxStringBytes ceiling (limits.go) is checked before any WithMemoryLimit accounting ever sees the string.
LIMITS ARE PER-Eval, NOT PER-TEMPLATE. Each call to Expression.Eval (and Eval, EvalWithMetrics, EvalForBalanceCheck, which route through it) starts a fresh meter with its own budget; nothing here accumulates a running total across multiple expressions evaluated for one template. Whether a template-wide, cumulative budget across every expression it contains is also needed is deliberately NOT decided here — that question belongs to whichever of sub-projects E2-E4 first has template integration to ask it against.
THE UNRESOLVED-OPERAND RULING. A dispatched call whose argument is still unresolved — the type-check path taken before a parameter is bound to a value — charges section 1.3.10 rule 1 only, the single operation for the call itself (call.go's callFunction, plus three mirroring sites in ops.go — binary, unary and the fast-path equality check — four unresolved-operand charge sites in all). Rules 2 and 3 do not apply: the call was dispatched, but no list was iterated and no string was processed, because nothing downstream of the unresolved operand actually ran. This ruling has no counterpart to probe against the reference implementation, which has no comparable unresolved-operand evaluation path.
RULE 2'S ENUMERATION IS OPEN, AND THE TWO SPECIFICATION DOCUMENTS DISAGREE ABOUT IT. This is settled here, once, because sub-project E1 did not notice the disagreement and let each task decide it by whichever document that task happened to open — leaving the package citing two mutually exclusive readings, both citations literally accurate. The divergence is real and it is in the specification, not in a misreading of it:
wiki/2026-02-Expression-Language.md lines 1080-1087 introduces rule 2's function list with "such as" — an OPEN enumeration. rfcs/0005-expression-language.md lines 1173-1182 introduces the same list with "This applies to:" — read literally, a CLOSED one.
THE RULING IS OPEN, on four grounds. (1) The wiki page is THE SPECIFICATION for this package (see the closing note at the bottom of this file); RFC 0005 is the proposal that produced it, and where the two disagree the specification governs — the same precedence this package already applies to the reference implementation. (2) BOTH documents state the same operative sentence first — "When a function or the evaluator iterates through every element of a list, the number of elements is added to the operation count" — and both introduce rule 3's parallel list with "and similar", openly, in the RFC too. A closed rule 2 beside an open rule 3 in one document, on two rules of identical construction, is not a reading either document argues for. (3) A closed reading makes rule 2's own words "or the evaluator" INOPERATIVE for anything unnamed: no evaluator-performed iteration except the list comprehension is in the enumeration, and the comprehension is listed separately precisely BECAUSE the evaluator, not a function, performs it — so the general clause must reach further than the list, or it says nothing. (4) A closed reading defeats the rule's stated purpose. It was not a theoretical preference: five constructs that do O(receiver) work were charged a flat 1 under it, and "len([range_expr('1-1000000')[0] for x in range(500)])" ran 1.8 seconds for 2,002 counted operations, scaling to roughly half an hour while staying under a fifth of the default budget. Charging them (see the bullet below) closes that.
WHAT THE OPEN READING DOES NOT LICENSE. It is not a mandate to charge everything: the question each row still answers is whether the work is element-count-dominated or byte-scan-dominated, and whether the implementation PROVABLY does that work. split() stays uncharged for rule 2 because its work is byte-dominated; "not", unary minus and unary plus stay uncharged because they touch no list and no string at all; min/max's fixed-arity 2- and 3-argument overloads stay uncharged because they take no list-typed parameter. "Unnamed by the enumeration" is not a reason to charge nothing, and "named by the enumeration" is not required to charge — that is the whole content of the ruling.
FIVE CONSTRUCTS THAT DID O(receiver) WORK FOR A FLAT 1, NOW CHARGED. The closed reading's cost was concrete and was found by a whole-branch review measuring this checkout, not by argument. Each of these expands or decodes its whole receiver inside a single call, and each was charged 1 while the SLICE form of the identical expression was charged correctly:
subscript of a string receiver (list.go's evalIndex) — indexValue does []rune(recv.AsStr()), decoding every byte of the receiver to find rune boundaries. Now charges rule 3 on the receiver, before the decode. A 500,000-byte receiver went from 1 to 1,954. subscript of a range_expr receiver (same) — indexValue calls rangeInts, which fully expands. Now charges rule 2 on the receiver's element count, from rangeExprCount (arithmetic for a single sub-range, a bounded expansion for two or more). A 1,000,000-element receiver went from 1 to 1,000,001. "in"/"not in" with a range_expr container (ops.go) — containsRangeInt calls rangeInts. Now Cost{ArgElements: {1}}, index 1 being the container, matching the string and list rows beside it. min() and max() over a range_expr (funcsmath.go) — both bodies are byte-identical rangeInts calls, and sum()'s range_expr row one table over ALREADY charged Cost{ArgElements: {0}} for the same body. Now both charge it too, which also removes an inconsistency inside one file.
A SUBSCRIPT OF A LIST STAYS AT A FLAT 1, deliberately: AsList returns the backing slice with no copy (value.go), so a list subscript genuinely touches one element and iterates nothing. The receiver-kind split is the same one slice.go's sliceValue already established and the same asymmetry the implementations themselves have.
LIST ORDERING NOW CHARGES ITS WALK, like list equality. "[...] < [...]" and "[...] == [...]" run the SAME compareLists/valuesEqual walk over the same operands, and only equality was charged, on the sole ground that rule 2 names "list/range equality comparisons" by token and does not name ordering. Under the open reading that distinction does not survive — the general sentence is satisfied either way, and the measured consequence was a 1,666x discrepancy: a 20,000-int list compared 2,000 times completed at 6,002 operations under "<" while the identical "==" expression tripped the 10,000,000 limit. orderingShapes' list/list row now declares Cost{ArgElements: {0}}, charging the LEFT operand exactly as applyBinary's equality path does. The four scalar ordering rows still charge rule 1 only; they iterate nothing.
THE COUNTING RULINGS. sqi's operation counter and the reference's diverge on 247 corpus cases, each adjudicated and recorded in test/oracle/baseline-ops.txt, grouped under roughly twenty root-cause families (its own "# ── " section headers enumerate them; that file, not this comment, is where to check one entry). Most of the 247 are the reference over-counting by a flat +1 on operators RFC 0005's own AST-transformation table routes around section 1.3.10 rule 1 entirely rather than through a genuine function call — ordering, equality, "not", "and"/"or", the ternary, "in"/"not in" — adjudicated as the reference's own bug rather than a gap here. A second class is sqi charging where the reference does not (join()'s byte charge, string(list)'s and the repr_* family's per-element charge, unique()'s per-comparison charge — see below) or the reverse (round(x, ndigits>0), min/max's fixed 2- and 3-arg rows) — each argued from the RFC 0006 text in that file's own section for it.
THE SECTION 1.3.10 WORKED EXAMPLE'S OWN ARITHMETIC IS WRONG. The specification states 'a' * 100000 costs 393 operations; the correct total is 392: ceil(100000/256) is 391 (256*390 = 99840, leaving 160), plus 1 for the repetition call itself. Measured directly — EvalWithMetrics("'a' * 100000", nil, TString) reports 392, not 393 — and the reference implementation agrees with 392. The RULE (meter.go's ceilDiv256) is right; only the specification's own addition is off, and meter.go records the correction beside the function so a reader checking it against the spec does not conclude it has an off-by-one.
Value.String() AND string(list) AGREE ON QUOTING AND ESCAPING FOR EVERY CASE EXERCISED — not universally. Before this wave, Value.String() rendered a list's string elements unquoted while string()'s JSON row quoted them (see the float-passthrough bullet above); that quoting gap closed in this wave, and the two were then measured to also agree byte-for-byte on ESCAPING for every case tried: an embedded double quote, non-ASCII, angle brackets and an ampersand, a newline, a backslash, tab, backspace, formfeed, carriage return, an emoji, U+2028/U+2029, and the empty string (TestValueString_VersusStringFunction). That is the full extent of the claim, and it must not be read as universal agreement: the two are INDEPENDENT implementations — Value.String() quotes a list's string elements with strconv.Quote (value.go), string()'s list row encodes with encoding/json and SetEscapeHTML(false) (funcsconv.go's writeJSONValue) — and a direct probe of the two encoders against each other, outside the set above, finds real divergences: on the C0 controls U+0000, U+0001 and U+001B, strconv.Quote emits its own hex-escape form where the JSON encoder emits a \u00XX escape; on vertical tab (U+000B), Quote emits its own short escape where JSON emits \u000b; on DEL (U+007F), Quote escapes it where JSON leaves it literal; and on invalid UTF-8, Quote preserves the raw bytes where JSON substitutes U+FFFD — all four measured directly against both functions and pinned as regression tests, not just measured once (TestValueString_DivergesFromStringFunctionOutsideMeasuredSet). Do not widen the agreement claim past the set it was measured on.
unique() CHARGES PER COMPARISON, NOT PER ELEMENT — and the reason is a prediction that measurement overturned, not a preference. C1 predicted section 1.3.10's operation limit would already catch uniqueList's O(n^2) scan through its old registry-level Cost{ArgElements: {0}} charge, which prices only the INPUT length. It did not: unique(range(20000)) completed in roughly 4 seconds with no error under that charge, running on the order of 4*10^8 real valuesEqual comparisons while only 20,001 operations were ever counted against the 10-million default limit. uniqueList (funcslist.go) is now an FnCtx function charging one operation per valuesEqual comparison, and the charge fires BEFORE the comparison it prices, so the limit stops the quadratic work while it is in progress rather than billing for it, unbounded, after the fact (TestUnique_IsBoundedByTheOperationLimit).
THE TOP-LEVEL COERCION IS METERED. coerceTop (eval.go), which every public entry point — Expression.Eval, Eval, EvalWithMetrics, EvalForBalanceCheck — runs on the whole expression's result, releases the pre-coercion value and allocates the coerced result with WithMemoryLimit's bound checked, at all four entry points. Before this wave's final fix round it ran OUTSIDE the metered region: coerceList (coerce.go) can turn a small live range_expr into an arbitrarily large list[int], and with the top-level coercion unmetered that materialization was bounded only by the fixed maxElements floor (10,000,000 elements, roughly 640MB at 64 bytes a value), with WithMemoryLimit never consulted at all on that path.
THE FENCE IS LIFTED, WITH A RESIDUAL STATED RATHER THAN THE PROBLEM DECLARED GONE. Every earlier wave's version of this comment said this package must not be handed untrusted expressions until sub-project E; sub-project E1 is what changes that, demonstrated by running TestOperationLimit_*, TestMemoryLimit_* and TestUnique_IsBoundedByTheOperationLimit, all passing. Three things this does NOT mean: the fixed floor (limits.go) still bounds what a single operation may allocate, unchanged by either configurable limit; maxParseDepth and maxSourceBytes still guard PARSING, a phase no evaluation-time budget can reach at all, so what a hostile expression may spend before a single operation charge exists to stop it is whatever those two hard bounds allow and nothing narrower; and limits are per-Eval, so a template with many expressions gets many independent budgets, one per expression evaluated — a cumulative per-template budget, if one turns out to be needed, is sub-project E2's or E4's question.
NONE OF IT BOUNDS PARSING, AND FOR A LONG TIME NOTHING DID. Every limit named in this bullet — the two configurable ones, the floor beneath them, the template-wide budget internal/openjd layers on top (E4c) and the deadline below — is consulted from exactly two places, meter.charge and meter.reserve, and both of those run during EVALUATION. Parse ran first and unwatched: tokenize built the entire token slice and the parser the entire tree before any of the above existed to be spent. maxParseDepth was no help, because it bounds recursive-descent STACK FRAMES and a flat left-associative chain is read in a loop. Measured, with EXPR supported and the walk live: one 4,000,001-byte "1+1+1+…" expression parsed SUCCESSFULLY in 544 ms, holding 427.6 MB of live heap and churning 1,403.3 MB; through the submission path a 4 MiB request body — what POST /api/v1/jobs accepts, anonymously when auth is off — cost ~765 MB of peak heap per in-flight request, and six concurrent requests reached 4,582 MB. An already-expired deadline changed nothing: the parse finished before anything read the clock. maxSourceBytes (limits.go, 10,000 bytes, checked at the top of Parse before tokenize) is what closes it — the one bound in this package that applies BEFORE evaluation begins, and therefore the only one that can. It is a 4xx verdict, not a 503: a source that is too long is a deterministic property of the template, so it reaches a caller as an ordinary parse error (a ValidationError through internal/openjd) rather than through ErrDeadlineExceeded.
THE WALL-CLOCK DEADLINE, A BOUND OF A DIFFERENT SHAPE ENTIRELY (WithDeadline, sub-project H1). This paragraph used to open "A FIFTH BOUND"; the ordinal is dropped rather than corrected to a sixth, because it counted limits.go's floor, which has since grown by one and may again. Everything above bounds WORK — bytes held, operations performed, elements built, nesting depth. None of them bounds TIME, and they cannot: section 1.3.10 prices 256 bytes at one operation, so '("x" * 900000).title()' spends ~7,000 of a 10,000 operation budget while costing ~57 ms of CPU, and a request that stays inside every budget above still measures in minutes. WithDeadline(t) sets an absolute wall-clock instant after which evaluation stops. The zero time — the default — means no deadline and reads no clock.
THREE WAYS IT DIFFERS FROM EVERY OTHER BOUND HERE, and each one matters to a caller:
(1) IT IS WALL-CLOCK, therefore NON-DETERMINISTIC. The same template on the same input breaches it on a loaded host and not on an idle one. Every other bound in this section is a function of the expression alone.
(2) IT IS PER-REQUEST, NOT PER-Eval. The option takes an absolute time rather than a duration precisely so that one deadline spans the many evaluations a template walk performs — a per-evaluation duration would let each of hundreds of positions spend the whole allowance, which is the opposite of a bound. That is also why meter.charge checks it on the FIRST charge of every evaluation and not only on the interval: a template built entirely from cheap expressions must still stop, and each of those expressions gets a fresh meter.
(3) A BREACH MEANS THE SERVER GAVE UP, NOT THAT THE TEMPLATE IS INVALID. Every other bound here is a verdict about the expression, and a caller is right to reject the submission (422). ErrDeadlineExceeded is exported, and distinct from every budget error, so that a caller can tell the two apart STRUCTURALLY (errors.Is) rather than by reading a message, and report it as a transient server condition (503).
PRECEDENCE, WHEN A SINGLE CHARGE BREACHES BOTH: the operation limit wins. meter.charge checks it first, deliberately — the deterministic verdict is the more useful and the more honest one, and reporting an over-budget template as a transient server condition would invite a client to retry something that can never succeed (TestDeadline_OperationLimitBeatsTheDeadline). meter.reserve orders the two the same way.
IT IS A BACKSTOP, NOT A BUDGET, AND ITS GRANULARITY IS COARSE. The clock is SAMPLED — on the first charge and every deadlineCheckInterval (1024) charges thereafter — because charge is the hot path of every expression and a time.Now() on each call taxes evaluations that are nowhere near a deadline. So the guarantee is "the deadline plus at most one evaluation's remaining operation budget", not "the deadline": up to 1023 further charge calls may run, each of them potentially a bulk operation, and the call count is held to the operation budget only because a charge that prices bulk work adds at least one operation to it. meter.reserve narrows the worst of that window by checking unconditionally, with the count in hand, immediately before each large materialization — so the single biggest construction inside the window never starts rather than being caught after it completes. What remains is not closed here and should not be described as if it were.
A union target that names a value's own type exactly now admits it unchanged, list types included: Eval("[1.0, 2.0]", nil, expr.UnionOf(expr.ListOf(expr.TFloat), expr.ListOf(expr.TInt))) returns the list rather than failing with "list[float] cannot be coerced to list[float] | list[int]". An earlier revision of this comment recorded that as a known gap; it is closed (coerce.go's directUnionMember). Note the shape of the check, because the two are easy to conflate: coercible() answers "does an implicit CONVERSION rule carry this TYPE to the target", which is a different question from "may this exact VALUE, of a type the target already names, pass through unchanged" — so for list (and every other non-null) type, the already-a-member carve-out lives in coerce() as directUnionMember, comparing whole types rather than type codes, since a code-only test cannot tell a list[int] from a list[string] inside a union; coercible() itself still has no such shortcut for them, and correctly reports FALSE for e.g. coercible(list[float], "list[float] | list[int]") — that pair has no conversion rule between them, direct membership is directUnionMember's question, not coercible()'s.
nulltype is the one exception, and by construction, not by extending this carve-out to it: coercible(nulltype, to) now reports TRUE whenever `to` admits null (bfa4cf3, coerce.go), because for null specifically "the target already admits it" and "coercible" collapse into the same question — there is no separate null-to-something conversion rule to ask about, only whether the target's union names null at all. coercible(nulltype, "string?") is true precisely because the target admits it; TestCoercible's "nulltype reaches a target that names null via optional sugar" and "...via a bare nulltype union member" rows pin this, alongside the negative boundary ("...does not reach a union that does not name null") proving the rule still checks target membership rather than admitting null everywhere.
A hard, fixed bound (limits.go's maxElements and maxStringBytes, both 10,000,000) applies to any list, string or range_expr this package produces, whether by repetition ("'x' * 3", "[0] * 3") or by concatenation ("'a' + 'b'", "[1] + [2]"). Both producers are checked on both types; string concatenation was the one gap, and a chain of individually-legal repetitions walked 18x past the bound through it. A THIRD bound, maxParseDepth (500), applies before any value exists: the parser's recursive descent is depth-limited, because exhausting the Go stack is a runtime.throw that recover() cannot catch — a 200,000-deep list literal killed the process outright rather than returning an error. "Depth-limited" means every recursion CYCLE in the descent is counted, which is a stronger claim than guarding the entry production and was not true when it was first written: parsePower reads its exponent through parseUnary, and parseUnary falls back through to parsePower, a loop that passed no guard at all, so "2**2**2**…" a million operators long still killed the process. It is counted now (parser.go's enter carries the full enumeration). A FOURTH bound, maxEvalDepth (10,000), does the same for EVALUATION, which the parse guard cannot cover: a left-associative run like "true or true or …" or "1 + 1 + …" is built by a loop, so it costs the parser no recursion at all and passes maxParseDepth however long it is, while the left-deep tree it produces is then walked recursively by evalNode — which overflowed the stack for real between 400,000 and 500,000 operators. A FIFTH bound, maxSourceBytes (10,000 bytes), applies EARLIER THAN ANY of them — at the top of Parse, before tokenize reads a byte — because the four above between them still left the whole PARSE unmetered: a single 4 MB flat chain parsed successfully in 544 ms while holding 427.6 MB of live heap, passing maxParseDepth untouched for the reason the fourth bound's paragraph just gave, and reaching maxEvalDepth only after every one of those bytes had been tokenized and turned into nodes. It bounds source LENGTH rather than node count on purpose; see limits.go for why, and for the headroom over real templates (the largest expression in any vendored fixture, sample or preset is 99 bytes). None of the five is the spec's own configurable memory and operation limits (sections 1.3.9 and 1.3.10) — those are a SEPARATE mechanism, covered in the BOUNDED EVALUATION bullet below, and this paragraph's historical claim that this package must not be handed untrusted expressions before they exist is corrected there rather than restated here: sub-project E1 delivered them, on by default, and that fence is now lifted, with a residual stated precisely in that bullet rather than the problem being declared gone outright. What the five bounds here still do, unchanged: stop one operation from allocating unbounded memory, stop the parser and the evaluator from overflowing the stack, and stop one expression's SOURCE from being large enough that merely reading it costs hundreds of megabytes — a narrower job than the configurable limits below, which stop a pathological expression from doing unbounded TOTAL work across many operations. The one remaining walk over a parsed tree — ast.go's walk, which Expression.Names uses — needs no bound at all any more: it is ITERATIVE, with an explicit stack, so its Go stack depth is constant however deep the tree is. It was recursive, and it was the last unbounded recursion here: 10,000,000 chained operators killed the process with "fatal error: stack overflow", measured. A bound would have been the wrong fix — Names returns []string with no error channel, and a tree that already parsed cannot fail to be walked — so the hazard was removed rather than converted into an error.
A float LITERAL in expression source does not preserve the text it was parsed from — "1.100" evaluates to a value that renders as "1.1", not "1.100". Value.String is a rendering for diagnostics and tests, not section 1.3.4's pass-through, and no producer sets the literal path's carry; this half of the gap is unchanged from sub-project A. Sub-project C1 gives Value the mechanism this needs but does not use it here: an optional rendered form (value.go's fs field, exported construction via FloatText), first set only by round(x, ndigits) for a positive ndigits because RFC 0006 requires round(3.5, 2) to render "3.50" — a form no float64 carries on its own (TestRound_CarryIsRoundOnlyAndDoesNotPropagate). Sub-project E2 added a second producer for the OTHER half of section 1.3.4 — a FLOAT JOB PARAMETER's submitted text, which sqi has verbatim because parameters are stored as map[string]string: phase 2's concreteJobParamValue (internal/openjd/exprcheck.go) now binds it with FloatText, so Param.<name> for a submitted "3.500" carries that text and Value.String reports it. SUBSTITUTION — reading the carry back out into rendered template output — was unimplemented on both halves and is now sub-project E4a's: internal/worker/fmtres renders phase-3 values onto a real command line, and pins that a submitted "3.500" arrives as 3.500 through both plain substitution and repr_py. The same underlying Value.String gap USED TO show up for a list too, before this wave: Value.String rendered a list's string elements unquoted ("[a, b]"), while string()'s JSON row (funcsconv.go) quoted them ("[\"a\", \"b\"]") — confirmed directly against the reference, not just inferred, since RFC 0006 calls that conversion's list row "the JSON string representation" rather than a diagnostic rendering. Sub-project E1 closed the Value.String() half of that gap: it now quotes a list's string elements too, and the BOUNDED EVALUATION bullet below states, narrowly and from a direct measurement rather than from prediction, exactly how far the two renderings agree once both quote — do not restate that claim here, and read it there rather than assume the two are now interchangeable. What is NOT closed is the pass-through this paragraph opened with: Value.String() remains a rendering for diagnostics and tests, not section 1.3.4's digit-for-digit float pass-through, which still needs the original submitted string and still belongs to whichever later sub-project first has template integration to source it from.
Nothing here touches a job template. Parsing a template, binding its parameters, and interpolating an expression's result back into template text are all outside this package; it evaluates expression text handed to it directly.
Section 1.1.5's escape table is narrower than its own opening claim that "all Python escape sequences are supported": \a, \b, \f, \v, \0, octal escapes and a backslash-newline line continuation are absent from the table, so this package keeps them verbatim, backslash included, rather than decoding them — "'\a'" evaluates to the two characters "\a". This is a deliberate reading of the table over the prose, not a deferral to a later sub-project.
A target type propagates into a sub-expression from exactly four node kinds, and nowhere else — a rule not answerable from outside the package, so it is spelled out here rather than left to be inferred from eval.go:
Cond, the chosen branch (or both, under an unknown condition) forwards the target
Logical ("and"/"or"), both operands forwards the target
ListLit, each element (through listElemTarget) forwards the target
ListComp, the element expression (through listElemTarget) forwards the target
ListComp, its iterable; its filter always TAny; always TBool
Unary / Binary / Compare, all operands always TAny instead
Index / Slice, the receiver being indexed or sliced always TAny instead
Index's own index; Slice's start/stop/step always TInt instead
Call, its receiver and every argument always TAny instead
Access, the receiver being accessed always TAny instead
The four "forwards" rows compute a value that literally IS one of the sub-expression's values, so the caller's target applies to it directly — ListComp's element expression joins ListLit's for the same reason: each of a comprehension's produced elements IS the element expression's value, one per iteration, exactly as each of a literal's elements is. Everything else COMPUTES a new value from its operands, so forwarding the target would leak context across an operator or call boundary — a string target reaching into "Param.Count + 1" would concatenate its operands into "11" rather than add them — and a subscript's own index or a slice's bound is fixed at TInt regardless of the target because that position must already be an int no matter what the whole expression is being coerced to. A call's return type is fixed by the signature callFunction selects, not by the caller's target, so a target reaching into an argument would let the CALLER'S context change which overload the callee resolves to.
COMPILED REGULAR EXPRESSIONS ARE CACHED FOR THE LIFETIME OF ONE EVALUATION, and for that lifetime only (recache.go). Before it, every re_match/re_search/re_findall/re_sub/re_split invocation ran translatePattern's full byte scan and regexp.Compile again, so a pattern inside a comprehension was compiled once PER ELEMENT while section 1.3.10 charged it roughly one operation plus ceil(len/256) — under-priced by about three orders of magnitude, and on the WORKER there is no wall-clock deadline to backstop it at all. Measured on the machine this was written on, '[s for s in Param.Files if re_match(s, r"shot\d+\.exr") != null]' over 10,000 elements: 30.4 ms and 48.6 MB before, 12.0 ms and 13.1 MB after (380,097 allocations against 70,062).
IT CHANGES NO RESULT AND NO COUNT. Section 1.3.10's charges are applied by callShape (ops.go) around the whole call, before Fn or FnCtx runs, so a cached compile is charged exactly what an uncached one is — the differential oracle's operation-count dimension is unmoved. A failing pattern is cached too, and its error value is returned unchanged on every hit, so an invalid pattern in a comprehension is rejected once with the message it always had.
IT IS CAPPED AT maxCachedPatterns ENTRIES, and the cap is the load- bearing part rather than a tidy-up. A pattern is an arbitrary string from a submitted template, not necessarily a literal, so "[re_match(s, s) for s in Param.Files]" presents one DISTINCT pattern per element; an uncapped map would retain one compiled program per element and turn a comprehension into a memory amplifier. Past the cap the cache stops storing — nothing is evicted and the map never grows again — so what it retains is a constant, not a function of the input. Being per-evaluation is what makes that bound hold across requests, and is also why the cache needs no eviction policy and no lock.
This package imports internal/openjd/intrange for range_expr's own grammar, section 3.4.1.1.1's <IntRangeExpr>. internal/openjd expands the identical grammar for a different purpose — a step's task parameter space — with its own pre-existing divergences from both this package and the spec: it orders values first-seen rather than increasing, rejects a range whose start exceeds its end where the spec yields a single value, and rejects a negative step the spec permits. Both callers share intrange's Range type but use different entry points (Parse here, ParseWithPolicy there) precisely because they disagree about what to accept — see the intrange package doc for the full comparison.
Test coverage, as of this writing: the OpenJD conformance suite's EXPR/job_templates group is 145/209 passing, 64 fixtures baselined (make test-conformance). It went DOWN in sub-project D, from 145/209 with 64 baselined to 143/209 with 66 baselined, and that was the one direction this number was allowed to move without being a defect: registering apply_path_mapping made 7.3--apply-path-mapping-in-job-name.invalid.yaml and its -in-timeout sibling evaluate cleanly, and both were only ever rejected by "unknown function" rather than by the placement rule they actually violate. Both are STILL baselined, waiting on sub-project E's scope-aware evaluation to reject them for the right reason — see the PATH MAPPING bullet above, which states the same 145 -> 143 and must keep stating it. The score is back at 145/209 with 64 baselined AS OF sub-project E1, but NOT because D's regression reversed: E1's Task 9 landed the section 1.3.10 operation counter and burned down a completely DIFFERENT pair of long-baselined entries, expr1.3.10--operation-limit-exceeded and expr1.3.10--string-operation-limit-exceeded (present in the baseline since C1 and C2 respectively, for the mirror-image reason: both used to be rejected only by an "unknown function" error before range() and .upper() were registered, then wrongly evaluated to completion once those landed, and now correctly exceed the operation limit instead). The two apply_path_mapping placement fixtures are UNCHANGED by E1 and remain baselined; the arithmetic landing on the same total (145/209, 64 baselined) both before D and after E1's Task 9 is a coincidence of magnitude — D ADDED two baseline entries, E1's Task 9 REMOVED two different ones, and the counts happen to net to the same score — not a reversal or a same-composition round trip. test/conformance/baseline-expr.txt's own header records this history in full, including the note that predicted the E1 outcome before it landed (the file was deleted by sub-project H2; read it in git). D therefore has NO protected-fixtures test of the kind every wave below has, because it is the mirror image of one: those tests exist where registering a family turned accidental "unknown function" passes into real rejections that must not silently become acceptances, whereas here registration turned two accidental passes into acceptances outright, which no assertion can protect and only scope-aware evaluation can fix. The score includes the ten .invalid fixtures TestConformance_B3ProtectedFixtures asserts by name — a construct this comment describes as rejected, such as the comprehension shadowing check or a parser/lexer rejection of a form Python allows, genuinely does reject it — the sixteen TestConformance_C1ProtectedFixtures protects: sub-project C1's own conversion and math functions correctly REJECTING an invalid argument (an empty list or path into bool(), an unrecognized string into bool(), an empty list to min/max, an unrepresentable float-to-int, NaN and infinity into float(), an empty string or list into range_expr()) — the seven TestConformance_C2ProtectedFixtures protects: sub-project C2's own string functions correctly REJECTING an invalid argument (an empty substring into count/find/replace, an empty separator into split/rsplit, a missing substring into index/rindex), now that registering the 31 string functions removed the accidental "unknown function" rejection those same fixtures used to pass under — each must be rejected by REAL argument validation instead, so that swap (one starting to pass for the wrong reason while another silently regresses) cannot hide inside an unchanged aggregate score either — and the sixteen TestConformance_C3ProtectedFixtures protects: sub-project C3's own regex scanner and re_sub replacement check correctly REJECTING an unsupported construct (an empty pattern, \z, lookahead, lookbehind, a named backreference, and re_sub's four group-reference spellings) for the RIGHT reason now — the pattern scanner or the replacement check, not "unknown function" — rather than merely failing to parse as before C3 — and the four TestConformance_C4ProtectedFixtures protects, all .invalid and all of which passed before C4 for the wrong reason ("unknown function", because path() itself was unregistered): relative_to's own errNotRelative, with_number's own errPaddingTooWide, section 1.2.4's receiver restriction refusing to coerce a path receiver into a string method, and C1's bool() path row. Note what that test can and cannot promise — it asserts the fixture is still REJECTED, not which mechanism rejected it, so an entry pins a specific check only where no second mechanism rejects the same input; its own docstring says so, and all four were verified to have none. C3 also CLEARED one fixture outright, 3.6--let-bindings.yaml, which needed only functions already registered by that point (len, sum, string, repr_py). Its sibling 3.6--let-host-context-symbols.yaml is STILL baselined, but no longer for the reason an earlier revision of this comment gave: it does not fail for want of the "/" path operator any more (C4 shipped that), it fails because this scoring path binds a "let" name untyped, so "repr_sh(out)" reports `no signature of "repr_sh" accepts (unresolved)` — measured. That is the scope-blindness class the baseline file's own header describes, and it burns down in sub-project E, not here. The differential oracle test's VALUE dimension has 927/1057 cases agreeing with the reference implementation, 130 baselined divergences (make test-expr-oracle) — up from B3's 135/169, then C1's 279/321 now that C1's 22 functions had their own corpus cases, C2's 407/469 once its 31 string functions had theirs, C3's 473/551 with its regex and repr_* functions, C4's path family (test/oracle/corpus.txt), which is where most of the growth in the value count came from, and E1's Task 13, which retired 31 value baselines by closing the Value.String() list-quoting gap described in the float-passthrough bullet above and the BOUNDED EVALUATION bullet below (891/1052 with 161 baselined, unmoved by sub-project D, to 922/1052 with 130 baselined; E1's final review then added five range_expr membership and subscript cases, all agreeing, for 927/1057 with the same 130). Sub-project D itself moved neither number and was the first wave that could not: the corpus contains no apply_path_mapping case and cannot contain one, because the harness passes the reference only a source string and a target type, with no channel for session mapping rules — see the PATH MAPPING bullet above. Sub-project E1 also added a SECOND oracle dimension the tracker had never carried before: OPERATION COUNTS. EvalWithMetrics (meter.go) and the reference's own evaluate_with_metrics are compared on every case whose value already agrees — a case with a value divergence is already reported once and is not double-counted here — and land at 680/927 agreeing, 247 baselined divergences, recorded and adjudicated family by family in test/oracle/baseline-ops.txt (roughly twenty root-cause families; see the BOUNDED EVALUATION bullet's COUNTING RULINGS paragraph for the shape of them). The path corpus is large and its divergences are the reference's, argued family by family in the C4 section of test/oracle/baseline.txt (its non-normalizing "/" and "+", its flavor-blind as_posix, its pre-current-pathlib stem/suffix split, its with_number hash-swallow, its inconsistent trailing-slash consumption on a relative_to base, and its treatment of a bare "scheme://" as a wildcard authority). The baselined entries include the range_expr(string) canonicalization gap described above and one round() case: sqi returns int for round(x, ndigits) when ndigits <= 0, per RFC 0006's own signature table, while the reference returns a FLOAT — round(1234.5, -1) is "1230 : int" here and "1230.0 : float" there. The specification outranks the reference (it is Beta, 0.x, breaking changes permitted in minor bumps), so this is adjudicated as the reference's bug and recorded in test/oracle/baseline.txt, not fixed here to match it. Also included are the list-of-strings rendering gap (Value.String, not string()) recurring through flatten, sorted and unique, split and rsplit, C3's own regex functions (re_search, re_match, re_findall, re_split all return list[string] or list[list[string]]) and now C4's list-valued path properties (parts, suffixes) — the corpus wraps those in join() wherever it means to compare the VALUES rather than that rendering; two of C2's own rulings argued above — isalnum's composition (isalnum('٣')) and title's ASCII-only word boundary (title('²x y')) — while capitalize's ligature expansion is NOT baselined, since the reference agrees with it outright; and three of C3's own rulings argued above — the intersection-rule refusals (\p{Nd}, (?<n>a), [[:alpha:]]), the [^\W...] set-subtraction gap, and repr_sh/repr_py's textual differences from the reference — while \d/\w/\s's Unicode semantics are NOT baselined, since they are exactly what the oracle is checking agreement on, and repr_json's non-ASCII escaping is NOT baselined either, since the reference matches it exactly. C4 adds the same shape: its rulings above are baselined where they diverge, while case-SENSITIVE path comparison is NOT — the reference agrees with sqi there, and it is CPython's PureWindowsPath that disagrees with both, which the oracle cannot see at all because the reference's path family is POSIX-only. Most baselined divergences are the reference's own bugs, adjudicated against the spec text and recorded one by one in test/oracle/baseline.txt — that file, not this comment, is the place to check any individual ruling.
Anything unimplemented FAILS rather than silently misbehaving, with one deliberate exception: the escape sequences named above pass through verbatim instead of erroring or being decoded. The grammar is EXPR's own rather than borrowed from a Python parser precisely so that the failure runs in that direction: a borrowed parser would accept syntax this package cannot evaluate.
Extending it ¶
Two shapes carry the weight and should not be reshaped:
- Type is a code plus its type parameters (Params), built through normalizing constructors — UnionOf, ListOf, UnresolvedOf and the rest — rather than as struct literals, so that two types meaning the same thing always have the same shape and Equal is sufficient everywhere downstream. Value carries a Type rather than inferring one from which payload field is set; an unresolved value carries no payload at all, which is what makes a typed-but-valueless result possible.
- Operator behavior is an ordered list of Shapes per operator (shape.go, ops.go), not a switch or a map keyed on operand types — a Type containing a slice cannot be a map key at all. Each Shape declares the types it takes AND the type it returns, which is what lets a missing operand value still produce a typed result. New signatures are new Shape entries; a candidate list with no admissible match is still reported as "unsupported operand types", the same single mechanism sub-project A used for its narrower same-type-only dispatch.
The specification is the OpenJD wiki page "Expression Language [Extension: EXPR]", pinned in the third_party/openjd-specifications submodule. Section numbers cited in this package's comments refer to it.
Index ¶
- Variables
- func EvalForBalanceCheck(src string, target Type) (live, resultSize int64, err error)
- func LineCol(src string, offset int) (line, col int)
- func SizeOf(v Value) int64
- type Access
- type Binary
- type BoolLit
- type Call
- type Code
- type Compare
- type Cond
- type Cost
- type Error
- type Expression
- func (e *Expression) CalledFunctions() []string
- func (e *Expression) CallsAny(names map[string]struct{}) bool
- func (e *Expression) Eval(syms Symbols, target Type, opts ...Option) (Value, error)
- func (e *Expression) Names() []string
- func (e *Expression) Root() Node
- func (e *Expression) Source() string
- type FloatLit
- type Index
- type IntLit
- type ListComp
- type ListLit
- type Logical
- type MapSymbols
- type Name
- type Node
- type NullLit
- type Op
- type Option
- type PathFormat
- type PathMapRule
- type PathMapSourceFormat
- type Shape
- type Slice
- type StringLit
- type Symbols
- type Type
- type Unary
- type Value
- func Bool(b bool) Value
- func Coerce(v Value, target Type) (Value, error)
- func Eval(src string, syms Symbols, target Type, opts ...Option) (Value, error)
- func EvalWithMetrics(src string, syms Symbols, target Type, opts ...Option) (Value, int64, error)
- func Float(f float64) Value
- func FloatText(f float64, text string) Value
- func Int(i int64) Value
- func List(elem Type, vals []Value) Value
- func Null() Value
- func Path(text string, f PathFormat) Value
- func RangeExpr(text string) (Value, error)
- func String(s string) Value
- func Unresolved(constraint Type) Value
- func ValueFromText(t Type, raw string, pathFlavor PathFormat) Value
- func (v Value) AsBool() bool
- func (v Value) AsFloat() float64
- func (v Value) AsInt() int64
- func (v Value) AsList() []Value
- func (v Value) AsRangeExpr() string
- func (v Value) AsStr() string
- func (v Value) Equal(o Value) bool
- func (v Value) IsNull() bool
- func (v Value) IsUnresolved() bool
- func (v Value) String() string
Constants ¶
This section is empty.
Variables ¶
var ( TNull = Type{Code: CodeNull} TBool = Type{Code: CodeBool} TInt = Type{Code: CodeInt} TFloat = Type{Code: CodeFloat} TString = Type{Code: CodeString} TPath = Type{Code: CodePath} TRangeExpr = Type{Code: CodeRangeExpr} TAny = Type{Code: CodeAny} TNoReturn = Type{Code: CodeNoReturn} )
The predeclared types that take no parameters.
var ErrDeadlineExceeded = errors.New("expr: evaluation deadline exceeded")
ErrDeadlineExceeded reports that an evaluation stopped because its wall-clock deadline passed.
It is EXPORTED and distinct from every budget error on purpose. A budget error means the template asked for more than it is allowed and is therefore invalid; this means the server gave up, and the same template might well succeed on an idle machine. Callers that turn errors into HTTP status codes must be able to tell those apart structurally rather than by reading a message — see internal/api's submission handler, which maps this to 503 and every budget error to 422.
The wrapped message adds HOW FAR PAST the deadline the check landed and nothing else ("... exceeded by 1.2s"). It must keep adding information rather than restating this sentence: %w concatenates the two, and an earlier revision rendered as "expr: evaluation deadline exceeded: evaluation exceeded its wall-clock deadline", which a 503 body would have shown verbatim.
Functions ¶
func EvalForBalanceCheck ¶
EvalForBalanceCheck evaluates src and reports the live memory remaining afterward alongside the result's own size. The two must be equal: after a top-level evaluation nothing but the result is live.
It exists for the differential oracle, which asserts the identity over the whole corpus rather than over hand-picked cases. That breadth is the point: a release bug in one rarely-exercised function is exactly what a written-out test set misses. It routes through coerceTop exactly like every other public entry point, so the invariant covers the top-level coercion too -- without that, this instrument would be structurally blind to a leak or a missing bound check in exactly the region WithMemoryLimit most needs to reach (see coerceTop's own doc comment).
WHAT THE CORPUS-WIDE SWEEP DOES NOT REACH, stated because "over the whole corpus" reads broader than it delivers: this function takes no Symbols and passes MapSymbols(nil), and test/oracle/corpus.txt contains NO SYMBOL REFERENCES AT ALL. So no corpus case ever produces an unresolved value, and the sweep touches none of the roughly thirteen release sites on the unresolved paths (evalIndex's and evalSlice's unresolved branches, sliceComponent, condResult, applyBinary's and callFunction's unresolved-operand returns, and their siblings) and no symbol-backed receiver. That is a COVERAGE gap, not a known correctness one: the final whole-branch review probed 67 symbol-bearing and unresolved-path expressions by hand and every one balanced exactly. Closing it properly needs a corpus that binds symbols, which is sub-project E's to add when template integration gives it a reason to.
func LineCol ¶
LineCol converts a byte offset into 1-based line and column numbers. Columns are counted in runes, not bytes, so a caret placed at the returned column lands under the intended character. An out-of-range offset is clamped to the start or end of src rather than reported as an error: a bad offset must never turn a real diagnostic into a panic.
func SizeOf ¶
SizeOf reports the section 1.3.9 size, in bytes, that this package charges for holding v live -- the same figure [meter.alloc] adds to an evaluation's memory budget.
It exists for callers that RETAIN values across evaluations, which the per-Eval meter by construction cannot bound: each Eval starts with a fresh budget, so a caller that keeps N results alive is exposed to N times the per-Eval limit no matter how tight that limit is. internal/worker/fmtres' let: evaluator is the case this was added for (an EXPR let: block binds up to 50 values into one symbol table and holds them for the whole task); the server-side checker discards every result, which is exactly why a per-Eval cap sufficed there.
The figure is implementation-defined by section 1.3.9's own admission ("try to match the actual memory usage of each value as closely as practical"), so treat it as a budgeting unit, not as a Go heap measurement.
Types ¶
type Access ¶
Access is a property access, "X.Attr" (spec section 1.3.3, where a property p resolves to the function __property_p__).
It is produced ONLY when the receiver is not a Name — "[1,2].len" or "(x).y". A dotted name keeps all its segments inside one Name node, and resolution splits it, so "Param.File.stem" produces no Access.
type Binary ¶
Binary is an arithmetic, string or comparison operation whose behavior comes from the dispatch table in ops.go.
type Call ¶
Call is a call, "Callee(Args...)" (spec section 1.3.3).
Callee carries the un-split callee: a Name whose segments resolution walks, or an Access whose X is the receiver. Which of those it is decides whether section 1.2.4's receiver coercion restriction applies, so the distinction must survive parsing rather than being desugared away here.
type Code ¶
type Code int
Code is the base of a Type: which type constructor it is, independent of any type parameters. The Recommended Library Interface's Type Codes table lists all sixteen codes this discriminates between; section 1.2.1 itself lists only the twelve the language surfaces to a template author, omitting any, noreturn and the type variables, which exist only in a function signature.
const ( CodeNull Code = iota // nulltype CodeBool CodeInt CodeFloat CodeString CodePath CodeRangeExpr CodeList // Params[0] is the element type CodeUnion // Params are the members CodeUnresolved // Params[0] is the constraint CodeAny CodeNoReturn CodeVarT // type variables: function signatures only, never a concrete value CodeVarT1 CodeVarT2 CodeVarT3 )
The type codes. Params carries the type parameters each one takes: none for the scalars, an element type for CodeList, the members for CodeUnion, and the constraint for CodeUnresolved.
type Compare ¶
type Compare struct {
// Offset is the byte offset of the FIRST comparison operator in the
// chain. It is what Pos() returns and is unrelated to which link, if any,
// fails during evaluation — see OpOffsets for that.
Offset int
Ops []Op
Operands []Node
OpOffsets []int
}
Compare is a comparison chain (spec section 1.3.6). "1 < 2 < 3" holds three operands and two operators; len(Operands) is always len(Ops)+1. Chains are one node rather than nested Binary nodes because each intermediate value must be evaluated exactly once.
OpOffsets holds the byte offset of each operator in Ops, in order, so len(OpOffsets) is always len(Ops) too: OpOffsets[i] is where Ops[i] sits in the source, letting the evaluator blame the specific link in the chain that failed rather than the chain's first operator.
type Cost ¶
type Cost struct {
// ArgElements are parameter indices charged by element count (rule 2:
// "when a function or the evaluator iterates through every element of a
// list, the number of elements is added").
ArgElements []int
// ArgBytes are parameter indices charged by ceil(len/256) (rule 3: "when a
// function processes a string or path value, the length of the value
// divided by 256, rounded up, is added").
ArgBytes []int
// ResultElements charges the element count of the value PRODUCED. Rule 2
// covers generators as well as consumers: range(1000) iterates a list it
// created rather than one it was given.
ResultElements bool
// ResultBytes charges the byte length of the value PRODUCED, for a function
// whose work scales with what it built rather than with what it read.
ResultBytes bool
}
Cost declares a Shape's section 1.3.10 rule-2 and rule-3 charges.
The single per-call operation of rule 1 is charged by callShape for EVERY shape and is deliberately not declared here: making it declarative would let a forgotten entry silently un-count a call, which is the one charge that can never legitimately be zero.
The zero value charges nothing beyond that call, which is correct for the functions section 1.3.10 explicitly exempts -- "simple lookups like len() that do not process the string content".
type Error ¶
type Error struct {
// Msg describes what went wrong, without any position prefix.
Msg string
// Offset is the byte offset into Src where the problem starts.
Offset int
// Src is the expression source the offset refers to.
Src string
// contains filtered or unexported fields
}
Error is a syntax or evaluation error in an expression. It carries the byte offset in the source text at which the problem was found, together with the source itself, so the rendered message can name a line and column.
The spec requires errors to point at the failing part of an expression, so offsets are recorded on tokens by the lexer, carried onto tree nodes by the parser, and used by the evaluator to blame the operator that failed rather than the start of the expression.
type Expression ¶
type Expression struct {
// contains filtered or unexported fields
}
Expression is a parsed expression, ready to evaluate.
func Parse ¶
func Parse(src string) (*Expression, error)
Parse reads an expression and returns its tree, or an *Error naming the position at which the source stopped making sense.
The grammar implemented here is EXPR's, not Python's. Anything outside it — bitwise operators, dict and set literals, assignment, and the rest of section 1.1's exclusion list — is rejected. That direction is deliberate: a reader borrowed from a full Python parser would silently ACCEPT syntax this package cannot evaluate, whereas anything unimplemented here fails to parse. The FIRST thing it does is bound the source's length (limits.go's maxSourceBytes). That check has to come before tokenize, not after it and not inside the parser: every other bound this package and its callers have — the section 1.3.9/1.3.10 budgets, the template-wide budget, the operator limits, the wall-clock deadline — is metered during EVALUATION, so until this check runs nothing at all is watching. See maxSourceBytes for what one unbounded parse measured.
func (*Expression) CalledFunctions ¶
func (e *Expression) CalledFunctions() []string
CalledFunctions returns the external set of function and method names this expression calls, sorted and de-duplicated. It is the counterpart to Names: where Names collects the SYMBOL a callee's leading segments name, this collects the trailing segment that names the function or method itself (section 1.3.3). "len(x)" yields "len"; "Param.Name.upper()" yields "upper"; "s.apply_path_mapping()" yields "apply_path_mapping".
It is EXTERNAL in the same sense Names is, and for the same reason: a comprehension loop variable called directly is bound by section 1.3.7, not by the function registry, so "[x() for x in Param.L]" yields the empty set rather than {"x"}. The exclusion is deliberately NARROW — it applies only to a SINGLE-SEGMENT callee, where the called name IS the bound identifier. In "[x.foo() for x in Param.L]" the called name is the method "foo", which the loop variable x does not shadow, so "foo" is reported; and the binding ends with its comprehension, so "[x for x in Param.L] + [x()]" reports {"x"} again. (Names diverges from the reference implementation on that last point and explains why above; the same reading applies here.)
Its stated use is sub-project E's: spotting a host-context call (notably apply_path_mapping) in a submission-time scope, which E rejects. This package enforces no such rule itself — see pathMappingFuncs.
func (*Expression) CallsAny ¶
func (e *Expression) CallsAny(names map[string]struct{}) bool
CallsAny reports whether the expression calls any of the named functions or methods — the MEMBERSHIP question CalledFunctions is otherwise used to answer, without building the answer.
It applies exactly CalledFunctions's collection rule, node for node: the same callee positions, the same trailing-segment rule for a dotted callee, the same Access arm for a parenthesized receiver, and the same narrow section 1.3.7 exclusion of a single-segment callee a comprehension binds. Read that doc comment for the adjudication of each; this one restates none of it, precisely so the two cannot drift apart in the telling. CalledFunctions is the enumeration, this is the predicate, and they agree by construction — which is pinned by TestCalledFunctions, whose every case asserts both.
It exists because the only consumer is a predicate. internal/openjd's checker asks "does this call a host-only function?" once per expression on the submission path, against a set with a single member (apply_path_mapping), and CalledFunctions answered it by walking the whole tree into a de-duplicating map, allocating a slice, and sorting it. This walks with early termination — it stops at the first match — and allocates nothing but the walk stack.
An empty or nil set is false without walking anything.
func (*Expression) Eval ¶
Eval evaluates the parsed expression against syms, coercing the result to target. syms may be nil for an expression that references no symbols; pass TAny as the target to accept the expression's natural result type.
The target guides implicit coercion (section 1.3.1). It applies HERE, at the boundary, and inside operator dispatch when a shape is matched. It propagates into a sub-expression from exactly four node kinds and no others — the package doc's forwarding table is the single statement of which, and of why each row is what it is; do not restate it here, and consult it rather than this comment when the question is whether some position takes a target. Section 1.3.1 leaves the question open, and the table's governing rule is that a node forwards only when its result literally IS a sub-expression's value: propagating a string target into "Param.Count + 1" would concatenate its operands into "11" rather than adding them, and section 1.3.2's own example of "Count: {{ len(myList) }}" yielding "Count: 5" describes evaluating naturally and converting afterward.
func (*Expression) Names ¶
func (e *Expression) Names() []string
Names returns every EXTERNAL dotted value reference the expression makes — for example {"Param.Frame", "Task.Param.Chunk"} — sorted and deduplicated.
This is the spec's accessed_symbols set, which the Recommended Library Interface defines as "the external symbols referenced by the expression as full dotted paths including properties" — so "Param.File.stem" is collected whole, trailing property and all. Callers use it to decide which symbols an expression needs before evaluating it; sub-project E uses it to scope-check a template's expressions without binding values.
Two kinds of identifier are therefore NOT names, and are excluded rather than reported:
- A FUNCTION OR METHOD NAME. The spec keeps those in a separate called_functions set, so the trailing segment of a call's callee is dropped: "len(Param.Items)" collects {"Param.Items"} and "Param.Name.upper()" collects {"Param.Name"}, not {"len"} and {"Param.Name.upper"}. The spec's called_functions set is CalledFunctions below, added by sub-project D; it collects exactly the segment this one drops.
- A COMPREHENSION LOOP VARIABLE, and anything rooted at one. Section 1.3.7 binds it inside the comprehension, so it is not external: "[x for x in Param.Items]" collects {"Param.Items"} and "[x.stem for x in Param.Files]" collects {"Param.Files"}. The binding covers the element expression and the filter but NOT the iterable, which is evaluated before the variable exists — "[x for x in x]" does collect the iterable's own external {"x"}.
Both exclusions matter to the only consumer this set has: a scope check of the form "every name here must be in scope" would otherwise reject every comprehension and every plain function call in the language. Every case above was verified against the reference implementation, which answers identically.
It does NOT answer identically once the binding ends. A loop variable is bound to its own comprehension and no further, so a later mention is external again: "[x for x in Param.A] + [x]" collects {"Param.A", "x"}, where the reference collects {"Param.A"} alone, as if the name were removed from the whole expression. The spec is on this side — section 1.3.7 binds the variable inside the comprehension, and the Recommended Library Interface asks for the EXTERNAL symbols — so the divergence is deliberate. It is also the safer direction: a scope check sees the free "x" here and would miss it under the reference's answer.
One narrowing remains, and it is safe in that direction: a property chain whose receiver is not a bare name — "(Param.File).stem", where the parentheses make the parser build an Access rather than one Name — collects the receiver "Param.File" alone, where the reference collects "Param.File.stem". A scope check sees a name that IS in scope either way.
func (*Expression) Source ¶
func (e *Expression) Source() string
Source returns the text this expression was parsed from.
type Index ¶
type Index struct {
// Offset is the byte offset of the "[", so an out-of-bounds error blames
// the subscript rather than the start of the expression.
Offset int
X, Idx Node
}
Index is a subscript, "X[Idx]" (spec section 2.1.7).
type ListComp ¶
type ListComp struct {
// Offset is the byte offset of the opening "[".
Offset int
Elem Node
// Var is the loop variable, which section 1.3.7 requires to be a
// <UserIdentifier> so it cannot shadow a spec-defined symbol like Param.
Var string
// VarOffset is where Var sits in the source, so a shadowing error blames
// the variable rather than the opening bracket.
VarOffset int
Iter Node
Cond Node
}
ListComp is a list comprehension (spec section 1.3.7): "[" Elem "for" Var "in" Iter ("if" Cond)? "]".
Cond is nil when the comprehension has no filter. Section 1.3.7 permits exactly one filter and no second "for" — Python's multi-generator form is rejected by the parser, not represented here.
type ListLit ¶
ListLit is a list literal (spec section 1.1.2). Elems is empty for "[]", whose type is list[nulltype] (section 1.2.6).
type Logical ¶
Logical is "and" or "or" (spec section 2.1.6). These are not in the dispatch table: they short-circuit and return one of their operands rather than a bool, so they cannot be expressed as a Shape with a fixed return type.
type MapSymbols ¶
MapSymbols is a Symbols backed by a map keyed on fully qualified dotted names, for example {"Param.Frame": Int(7)}. A nil MapSymbols is a valid empty table.
type Name ¶
Name is a dotted value reference such as Param.Foo or Task.Param.Frame. Parts holds the dot-separated segments in order and is never empty.
type Node ¶
type Node interface {
// Pos returns the byte offset in the source where this node begins.
Pos() int
// contains filtered or unexported methods
}
Node is one node in a parsed expression tree.
Every node records the byte offset in the source it came from, so an evaluation error can blame the operator that failed rather than the start of the expression. For an operation node the offset is the operator's own.
type NullLit ¶
type NullLit struct {
Offset int
}
NullLit is None or null (spec sections 1.1.1 and 1.1.4).
type Op ¶
type Op int
Op identifies an operator. The same value names an operator in the tree and keys the dispatch tables in ops.go, so there is one operator vocabulary rather than two that can drift.
type Option ¶
type Option func(*evalCtx)
Option configures one evaluation.
It is variadic so that existing three-argument calls keep compiling, and so sub-project E can add the section 1.3.9 and 1.3.10 limits through the same channel rather than changing the signature a second time.
func WithClock ¶
WithClock replaces the clock the deadline check reads. It exists for tests, which advance a fake clock rather than sleeping. Production never calls it; nil means time.Now.
func WithDeadline ¶
WithDeadline sets an absolute wall-clock deadline for this evaluation.
The zero time — the default — means no deadline, and costs nothing: the meter short-circuits before reading any clock.
It is deliberately ABSOLUTE rather than a duration, so one deadline can span a whole request. An accepted template's expressions are walked twice (phase 1 in ValidateWithOptions, phase 2 in checkExpressionsAtSubmit) across many evaluations, and a per-evaluation duration would let each one spend the full allowance.
func WithMemoryLimit ¶
WithMemoryLimit bounds the LIVE memory, in bytes, of the values one evaluation holds at once (section 1.3.9). It defaults to 100,000,000.
There is no unlimited mode: a non-positive limit is a caller error, reported by Eval. A value that reads like "off" must not BE off in a package reachable from POST /api/v1/jobs. Tests wanting effectively-unbounded evaluation pass a large number.
Note that limits.go's fixed bounds sit UNDERNEATH this one and are not configurable, so raising this limit does not raise what a single operation may allocate: "'a' * 20000000" still fails on maxStringBytes with errTooLarge, not on errMemoryLimit.
func WithOperationLimit ¶
WithOperationLimit bounds the number of operations one evaluation may perform (section 1.3.10). It defaults to 10,000,000. A non-positive limit is a caller error, for the same reason WithMemoryLimit's is.
func WithPathFormat ¶
func WithPathFormat(f PathFormat) Option
WithPathFormat selects the path semantics for this evaluation.
func WithPathMapping ¶
func WithPathMapping(rules []PathMapRule) Option
WithPathMapping supplies the session's path-mapping rules to apply_path_mapping. Absent, apply_path_mapping passes its input through, NORMALIZED as a path value in the evaluation's flavor — passthrough means "no rule rewrote it", not "the text is returned verbatim", so '/a//b/' still comes back as the path "/a/b". Sub-project E injects the rules per host-context scope; before E, no production caller sets this, so apply_path_mapping is passthrough everywhere it is currently reached.
type PathFormat ¶
type PathFormat int
PathFormat selects the semantics the path type uses during evaluation.
The specification makes this an evaluator setting rather than a property of the host, and that distinction is load-bearing here: sqi parses templates server-side, so deriving it from the running machine would let one template expand into different tasks depending on which OS submitted it.
const ( // PathPOSIX is Python's PurePosixPath. It is the DEFAULT, which differs // from the specification's own default of host-native on purpose — the // spec itself names POSIX as what TEMPLATE scope wants, "to ensure // consistent behavior regardless of the submission machine's OS", and // template parsing is exactly that scope. PathPOSIX PathFormat = iota // PathWindows is Python's PureWindowsPath. PathWindows // PathNative is the specification's own default: the host's semantics. // Nothing in sqi selects it yet; sub-project E does, for host contexts. PathNative )
type PathMapRule ¶
type PathMapRule struct {
SourceFormat PathMapSourceFormat
SourcePath string
DestinationPath string
}
PathMapRule is one source→destination path-mapping rule. It mirrors the OpenJD pathmapping-1.0 schema but is independent of internal/worker/protocol, which this leaf package cannot import; sub-project E translates a protocol.PathMapRule into this type at the injection boundary.
type PathMapSourceFormat ¶
type PathMapSourceFormat int
PathMapSourceFormat is the format of a path-mapping rule's SourcePath, the OpenJD pathmapping-1.0 "source_path_format" enum (URI is the EXPR extension's addition).
const ( // PathMapPOSIX matches SourcePath using POSIX path semantics. PathMapPOSIX PathMapSourceFormat = iota // PathMapWindows matches SourcePath using Windows path semantics // (case-insensitive, separator-insensitive — see applyFileRule). PathMapWindows // PathMapURI matches SourcePath by string prefix on a "/" path-segment // boundary, with no path normalization — see applyURIRule. PathMapURI )
type Shape ¶
type Shape struct {
// Params are the declared parameter types, one per argument.
Params []Type
// Ret is the declared result type. It may be a union: the spec's own
// __pow__(int, int) -> float | int is one.
Ret Type
// RetOf, when set, computes the declared result from the match's variable
// bindings INSTEAD of substituting them into Ret.
//
// It exists for a result type that is a UNIFICATION of the operands rather
// than a copy of one of them. List concatenation is the case: its two
// element variables are independent (they must be, or "[1] + [2.0]" would
// not match at all), so no substitution into Ret can say what section
// 2.1.3's "common type" of the two is — "[] + list[int]" reads the LEFT
// variable and answers list[nulltype], and "list[int] + []" answers
// list[int], for the same concatenation. concatLists computes the real
// answer from the VALUES, which is no help on the path where there are no
// values; this is that same computation over types.
RetOf func(b bindings) Type
// Fn computes the result. It is called only with arguments that matched
// Params, so it may use the payload accessors without checking.
Fn func(args []Value) (Value, error)
// FnCtx is Fn for the few implementations that need the evaluation's
// settings rather than only their arguments.
//
// The rule for which rows use it is not a tally, it is a question: does
// this row need something the evaluation holds that its arguments cannot
// give it? Two answers so far, and they are unrelated to each other.
//
// The first is the path FLAVOR. All three of path()'s rows must choose one
// at construction time — path(string), path(list[string]) and
// path(list[nulltype]) — because constructing a path is the only operation
// that ever has to decide; every other path operation reads the flavor off
// its receiver.
//
// The second is the COMPILED-PATTERN CACHE (recache.go), which every
// re_ row that compiles a pattern reaches through ec.re. That one is a
// speed property and nothing else: the cache changes no result, no error
// and no section 1.3.10 charge, since callShape applies every charge around
// the call before Fn or FnCtx runs.
//
// Adding a parameter to Fn instead would have changed every OTHER row,
// which needs neither; RetOf is the existing precedent for an optional
// alternative field.
//
// A Shape sets Fn or FnCtx, never both.
FnCtx func(ec evalCtx, args []Value) (Value, error)
// Promote narrows which conversions this shape's parameters will accept to
// admit an argument of a different type. The zero value accepts every
// lossless conversion coerce.go allows, which is right for most operators
// and wrong for ordering — see promotion.
Promote promotion
// Cost declares this signature's section 1.3.10 charges beyond the single
// per-call operation. See Cost.
Cost Cost
}
Shape is one accepted signature of an operator or function: the types it takes, the type it gives back, and the code that computes it.
Sub-project A dispatched on a map keyed by operand kind. Two facts retired that. A Type contains a slice, so it cannot be a Go map key at all. And a map entry does not record what it returns, which makes it impossible to answer "what would this produce?" for an operand that has no value — the question at the center of the spec's static type checking. A declared Ret answers it without executing anything.
Params and Ret may contain type variables (CodeVarT and friends), bound at match time and substituted into Ret afterward, so that a signature like __getitem__(list[T], int) -> T returns the element type. Sub-project C registers its function library into this same structure.
type Slice ¶
type Slice struct {
// Offset is the byte offset of the "[".
Offset int
X Node
Start Node
Stop Node
Step Node
}
Slice is a slice, "X[Start:Stop:Step]" (spec sections 1.3.8 and 2.1.8).
An ABSENT component is nil, which is distinct from an explicit one: section 1.3.8 defaults start to 0 or to the end and stop to the length or to -length-1, depending on the SIGN OF THE STEP, so a zero value could not carry the distinction.
type Symbols ¶
type Symbols interface {
// Lookup returns the value bound to a fully qualified dotted name, and
// whether it is bound at all.
Lookup(name string) (Value, bool)
}
Symbols resolves the dotted names an expression references — Param.Frame, Task.Param.Chunk, Session.WorkingDirectory and the like.
The package deliberately hardcodes no namespaces: the caller decides what is in scope, exactly as fmtstring.Scope does for base-spec format strings.
type Type ¶
type Type struct {
// Code is which type constructor this is. Always meaningful.
Code Code
// Params are the type parameters, whose meaning depends on Code. Empty for
// the scalars.
Params []Type
}
Type is a type in the expression language: a code plus its type parameters.
Because Params is a slice, Type is NOT comparable — "==" on two Types is a compile error and a struct containing a Type cannot be a Go map key. Use Equal. That single fact is why operator dispatch is a list of shapes (shape.go) rather than the map keyed on kinds that sub-project A used.
Construct Types through the constructors below rather than as literals: they normalize, and everything downstream relies on structural equality being sufficient, which only holds for normalized types.
func JobParamTypes ¶
JobParamTypes maps a declared OpenJD job-parameter type ("STRING", "PATH", "INT", "FLOAT", "LIST[PATH]", ...) to the expression types of Param.<name> and RawParam.<name>, per section 1.2.2's job-parameter table.
PATH and LIST[PATH] are the two rows where the raw form differs from the resolved form, because the raw value may be a path for another operating system that cannot be parsed locally: Param.<name> is a path (or list of paths), RawParam.<name> stays a string (or list of strings). Every other declared type binds Param and RawParam to the SAME type. That rule is stated in as many words by Template Schemas §7.3.1's value-reference table — "This is the same as RawParam.<ParamName> for all parameter types except PATH" (wiki/2023-09-Template-Schemas.md:1991) — NOT by Expression-Language §1.2.2, which an earlier revision of this comment cited for it; the substance was right and the citation was wrong. §1.2.2's own contribution is the type table above plus the PATH prose ("Param.<name> has type path with path mapping rules applied, while RawParam.<name> has type string containing the original unmapped value"). So an INT job parameter's RawParam.<name> is int, not string. Do not special-case RawParam to string uniformly; that would contradict the specification for every non-PATH type.
An unrecognized spelling floors to "any" rather than leaving the name unbound — an unbound name would make a valid template fail as "unknown symbol", which is worse than typing it loosely.
This is the single, shared definition of the mapping. internal/openjd's phase-1/phase-2 symbol-table builder (exprcheck.go's jobParamTypes) and the worker's phase-3 builder (internal/worker/fmtres/exprsyms.go) both call this function rather than each keeping their own copy. internal/openjd itself cannot be imported by the worker binary — it pulls in internal/store, which the worker must never depend on — so the mapping lives here, in the one package both sides already import (internal/openjd/expr imports only internal/openjd/intrange). A second, independently maintained copy of this table is exactly the drift EXPR sub-project E4a's design spec section 3.1 warns a worker-side symbol table must not introduce.
func ListOf ¶
ListOf builds a list type. An unresolved element type hoists outward — a list of unresolved elements is an unresolved list — which keeps unresolved as the outermost constructor, the canonical form the ExprType section requires.
Section 1.2.1's constraints on the element type (no third level of nesting, no optional element) are enforced by ParseType, where untrusted text enters. Internal callers pass programmer-controlled types, so an error return here would add an unfailing check to every call site.
func OptionalOf ¶
OptionalOf builds the type of a value that may also be null. The spec has no separate optional code: "int?" is exactly the union of int and nulltype, and UnionOf's normalization means applying this twice changes nothing.
func ParseType ¶
ParseType reads a type in the notation String produces: "int", "list[string]", "int?", "int | string", "unresolved[int]".
This is where untrusted text becomes a Type — declared parameter types arrive as strings — so it is also where section 1.2.1's constraints on a list's element type are enforced.
func TaskParamType ¶
TaskParamType maps a declared OpenJD task-parameter type per section 1.2.2's task table. CHUNK[INT] is range_expr, NOT list[int], so that a frame range need not be expanded. Task.Param.<name> and Task.RawParam.<name> share this same type for every declared task- parameter type, including PATH. §1.2.2's task table gives ONE expression type per declared type, with no Param/RawParam split at all; the value-versus-type distinction comes from Template Schemas' own task- parameter definitions, which describe Task.Param.<name> as "the value of the parameter with relevant path mapping rules applied to it" and Task.RawParam.<name> as "the value of the parameter as it was defined, with no path mapping rules applied" (wiki/2023-09-Template-Schemas.md:1246-1247). An earlier revision of this comment attributed those two quotes to §1.2.2, which does not contain them. It is a VALUE difference, not a type difference; both remain path.
An unrecognized spelling floors to "any", for the same reason JobParamTypes does. See that function's doc comment for why this mapping is shared rather than duplicated per caller.
func UnionOf ¶
UnionOf builds a union type, applying every normalization rule the ExprType section requires: nested unions flatten, noreturn collapses to nothing, any absorbs everything, duplicates are removed, members sort with nulltype last, a single member unwraps, and an unresolved member hoists to wrap the whole union.
Normalizing here rather than at each use site is what makes Equal sufficient downstream. Dispatch, coercion and the conformance path all rely on two types that mean the same thing having the same shape.
func UnresolvedOf ¶
UnresolvedOf builds the type of a value whose type is known but whose value is not, per the spec's static-type-checking model. Nested unresolved types flatten, so unresolved is idempotent.
The value-level counterpart is Unresolved, which builds a Value; the -Of suffix on the type constructors keeps the two apart.
type Value ¶
type Value struct {
// Type is the value's type. Always set.
Type Type
// contains filtered or unexported fields
}
Value is an evaluated expression result.
Type is always meaningful. The payload fields are valid only for their corresponding type code, and reading the wrong one panics. An unresolved value — a placeholder whose type is known but whose value is not — carries NO payload at all, which is the case the type-tag-separate-from-payload shape exists to make possible.
Because Type contains a slice, Value is NOT comparable: use Equal, not "==".
func Coerce ¶
Coerce converts v to target per section 1.2.3's implicit type coercion -- the very same conversion an evaluation's own target type applies to its result, exported so a caller that has ALREADY evaluated can convert once more without re-parsing and re-evaluating the source.
It exists for one caller, and the reason is structural rather than convenient. internal/openjd's task-parameter range resolver (resolve.go's evalRangeExprField) must evaluate a whole-field range expression against exactly the type section 1.3.12 gives that field -- "int | string | range_expr | list[int]" for an INT parameter -- because anything else would make its accept/reject verdict differ from the checker's, which is the drift the whole wave exists to prevent. But those four union members mean DIFFERENT things downstream: an int or a string becomes range TEXT, while a range_expr or a list becomes the range's VALUES. So the resolver evaluates against the union, then converts the range_expr arm -- and only that arm -- into list[int].
Doing that second step through this function reuses section 1.2.3's own range_expr -> list[int] rule (coerceList's rangeInts call, which expands in increasing, de-duplicated order per section 3.4.1.1.1). The alternative would be a second, independent implementation of "take the integers out of a range_expr" living in internal/openjd, whose ordering policy could drift from this package's -- and internal/openjd already has a deliberately DIFFERENT <IntRangeExpr> policy (first-seen order, no negative step, no start > end), so "drift" there is not hypothetical, it is the default outcome of writing the expansion twice.
Errors carry no position, exactly as coerce's do: the caller is expected to attach whatever position it has.
func Eval ¶
Eval parses and evaluates src in one step. Prefer Parse plus Expression.Eval when the same expression is evaluated more than once.
func EvalWithMetrics ¶
EvalWithMetrics evaluates src and reports the section 1.3.10 operation count alongside the result, mirroring the reference implementation's ParsedExpression.evaluate_with_metrics. It exists for the differential oracle (test/oracle), which cannot read a package-private counter.
It reports operations only. Section 1.3.9's memory figure is deliberately not exposed: value sizing is implementation-defined, so a differential comparison of it could only be suppressed, never adjudicated.
func FloatText ¶
FloatText returns a float value that renders as text instead of through the default float formatting.
It exists for section 1.3.4: a FLOAT job parameter submitted as "3.500" must keep that exact text rather than the canonical "3.5". sqi stores submitted parameters as map[string]string, so the original text is available verbatim wherever a concrete value is bound from it — internal/openjd/exprcheck.go's concreteJobParamValue is that call site today. See the fs field's comment for the invariants this carry keeps — including the repr_* exception to "no operation propagates it".
CONTRACT the caller must uphold, unchecked at runtime: text must be a textual representation of f, e.g. the exact source strconv.ParseFloat(text, 64) produced f from -- as concreteJobParamValue's call does, parsing raw into f and then passing that SAME raw back as text. Nothing here verifies this. A mismatched pair (say, FloatText(3.5, "9000")) builds a Value whose NUMBER is 3.5 -- what Equal, arithmetic, and every other operation compare and compute with -- but whose TEXT is "9000" -- what String() (and therefore repr_py/repr_json/repr_pwsh) reports. The two would silently disagree for as long as the value's fs form is read instead of computed.
func List ¶
List returns a list value with the given element type and elements.
The element type is passed explicitly rather than inferred from vals because an EMPTY list still has one: "[]" is list[nulltype] (section 1.2.6), and section 1.2.6's inference rules can also give a list an element type no element has exactly — [1, 2.0] is list[float] after its elements are coerced.
func Path ¶
func Path(text string, f PathFormat) Value
Path returns a path value with the given flavor, normalized on the way in.
func RangeExpr ¶
RangeExpr returns a range_expr value from its text, which must satisfy the base specification's <IntRangeExpr> grammar (2023-09 Template Schemas, section 3.4.1.1.1).
The TEXT is what the value carries; the integers are expanded only when an operation needs them. That is the point of section 1.2.2 giving CHUNK[INT] the type range_expr rather than list[int] — a frame range need not be expanded to be passed around — and it is what lets range_expr -> string (section 1.2.3) answer without materializing anything.
This constructor is also what the language's own range_expr(string) function calls (sub-project C1, funcsconv.go) — the first way an expression can produce a range_expr with no symbol table involved. The CHUNK[INT] symbol remains sub-project E's, still-unimplemented, second way to get one. A caller's symbol table binding a name to a value built by calling this function directly is the third.
func Unresolved ¶
Unresolved returns a placeholder for a value that is not yet known but whose type satisfies the given constraint.
This is the mechanism the spec's static type checking is built on: an expression is evaluated with placeholders in the symbol table, operations propagate the type, and a type error surfaces without any value existing. It is safe because the language is side-effect free.
The type constructor with the -Of suffix, UnresolvedOf, builds the Type; this builds the Value.
func ValueFromText ¶
func ValueFromText(t Type, raw string, pathFlavor PathFormat) Value
ValueFromText converts a parameter's submitted raw text into a concrete Value of type t. It returns Unresolved(t) in two distinct situations, which are easy to conflate:
PARSE FAILURE, for a type this function does make concrete. INT and FLOAT go concrete when raw parses and fall back to Unresolved(t) when it does not: this function is not a validator, so a value that fails to parse here is reported as still-unknown rather than causing a panic or a lie about what was bound. Validating a submitted value against its declared type happens upstream, before this is called. STRING and PATH always go concrete — every string parses as either.
BY CONSTRUCTION, for a type this function never makes concrete at all. As of EXPR sub-project F1 there is NO SUCH TYPE LEFT. Bool and list were the two: this paragraph used to read "F MUST add its cases here when that lands, or its own parameters will silently never resolve past a placeholder in phase 3", and F1 added them. The instruction is kept rather than deleted because the hazard it names is real and permanent for any type added later — an unhandled type reaches the default branch and returns Unresolved(t), which is a LEGITIMATE phase-1 result, so nothing errors and nothing logs; the parameter simply never resolves. TestValueFromText_ResolvesTheF1Types guards it by asserting CONCRETENESS rather than correctness, and any future type must join that table. This is the one place the mapping lives now that phase 2 and phase 3 share it (see JobParamTypes' doc comment).
range_expr (CodeRangeExpr) IS made concrete, via RangeExpr(raw) with the same parse-failure-falls-back-to-Unresolved rule as INT/FLOAT. CHUNK[INT] task parameters (declared today, not deferred to F) are the producer: internal/openjd/expand.go stores a CHUNK[INT] task parameter's value as a range-expression string like "1-5", and unlike a job parameter's declared type (which internal/openjd's JobParamType enum limits to STRING/PATH/INT/FLOAT — nothing can construct a RANGE_EXPR- typed job parameter that passes validation), this case IS reachable in production, from Task.Param.<chunked-name> in the worker's phase-3 table. Phase 2 cannot observe this case: internal/openjd's bindTaskParamSymbols binds every Task.Param./Task.RawParam. entry as Unresolved(t) directly and never calls this function for task parameters at all (task parameters are per-task, not per-template — see that function's own doc comment) — verified by reading it, not assumed.
pathFlavor selects the flavor for a CodePath result, so callers evaluating in different contexts get a Path value that matches their own evaluation's flavor rather than a fixed one: internal/openjd hardcodes PathPOSIX here for submission-time job-parameter binding (a known, pre-existing gap — nothing server-side sets a PathFormat other than the default), while the worker's phase-3 table (a genuine host context) uses PathNative.
The CodeFloat case binds raw as the value's rendered form (FloatText), per section 1.3.4: submitting "3.500" to a FLOAT parameter must preserve that exact text, not the canonical "3.5" strconv.ParseFloat's companion FormatFloat would produce. Callers that store submitted parameters as plain strings (both internal/openjd and the worker do) already have the original text in raw — no separate capture is needed.
func (Value) AsRangeExpr ¶
AsRangeExpr returns the range expression text. It panics if v is not a range_expr.
func (Value) AsStr ¶
AsStr returns the string payload. It panics if v is not a string.
Named AsStr rather than AsString because String is the fmt.Stringer rendering; two methods one letter apart would be a standing trap.
func (Value) Equal ¶
Equal reports whether two values have the same type and the same payload.
Value is not comparable with "==" because Type contains a slice, so this is the only way to compare two values for identity. It is NOT the language's "==" operator: section 1.2.5 makes that cross-type, so 5 == 5.0 is true there while Int(5).Equal(Float(5)) is false here.
func (Value) IsUnresolved ¶
IsUnresolved reports whether v is a placeholder rather than a known value.
func (Value) String ¶
String renders the value as text.
Floats use the shortest representation that round-trips, with a ".0" added when the result would otherwise look like an integer, so a float never renders indistinguishably from an int. Null renders as "null" and booleans as "true"/"false" — the JSON/YAML spellings, matching the aliases in spec section 1.1.4 and the string(nulltype) -> "null" rule in section 2.2.1.
This is a rendering for diagnostics and tests. The definitive form used when interpolating a value back into a template is sub-project E's to fix, and section 1.3.4's float pass-through rule belongs to it.
Source Files
¶
- ast.go
- call.go
- coerce.go
- comp.go
- doc.go
- errors.go
- eval.go
- funcs.go
- funcsconv.go
- funcslist.go
- funcsmath.go
- funcspath.go
- funcsre.go
- funcsreprdata.go
- funcsreprshell.go
- funcsstrcase.go
- funcsstrfind.go
- funcsstrpad.go
- funcsstrsplit.go
- lexer.go
- limits.go
- list.go
- meter.go
- ops.go
- paramtypes.go
- parser.go
- pathmapping.go
- pathnumber.go
- pathval.go
- rangeexpr.go
- recache.go
- repattern.go
- resolve.go
- shape.go
- slice.go
- token.go
- type.go
- unicodename.go
- value.go