|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// #4812 — `parseCelToAst` is the canonical parse-to-AST entry: the ONE answer in |
| 4 | +// this repo to "what parses". These tests pin it against `celEngine.compile`, |
| 5 | +// which is the entry the runtime actually uses, in both directions — what both |
| 6 | +// accept, what both reject, and the one asymmetry that is deliberate. |
| 7 | +// |
| 8 | +// They also pin the two things a consumer silently opts out of by building its |
| 9 | +// own `new Environment(...)` instead: the #3306 nullable-ternary rewrite, and |
| 10 | +// `DEFAULT_LIMITS`. `@objectstack/lint`'s null-guard pass did exactly that until |
| 11 | +// #4812 — and it was the *bounds* it diverged on, so a bare-env comparison is |
| 12 | +// asserted here rather than described. |
| 13 | + |
| 14 | +import { Environment } from '@marcbachmann/cel-js'; |
| 15 | +import { describe, expect, it } from 'vitest'; |
| 16 | + |
| 17 | +import { celEngine, parseCelToAst, DEFAULT_LIMITS } from './cel-engine'; |
| 18 | + |
| 19 | +/** |
| 20 | + * A bare cel-js environment — byte-for-byte the one `validate-null-guards.ts` |
| 21 | + * built for itself before #4812, and the shape any consumer naturally reaches |
| 22 | + * for. Its only difference from the canonical env is what it does NOT carry: |
| 23 | + * no `limits`, no stdlib, no rewrite. |
| 24 | + */ |
| 25 | +const bareEnv = new Environment({ unlistedVariablesAreDyn: true, enableOptionalTypes: true }); |
| 26 | +const bareParses = (source: string): boolean => { |
| 27 | + try { |
| 28 | + bareEnv.parse(source); |
| 29 | + return true; |
| 30 | + } catch { |
| 31 | + return false; |
| 32 | + } |
| 33 | +}; |
| 34 | + |
| 35 | +/** Sources the platform accepts — drawn from the shapes this package's own suites use. */ |
| 36 | +const ACCEPTED = [ |
| 37 | + 'record.amount > 1000', |
| 38 | + 'record.end_date < record.start_date', |
| 39 | + 'record.start_date != null && record.end_date != null && record.end_date < record.start_date', |
| 40 | + 'has(record.start_date) && record.start_date < record.end_date', |
| 41 | + '"manager" in os.user.positions', |
| 42 | + 'record.rating >= 4', |
| 43 | + 'record.end_date <= daysFromNow(60)', |
| 44 | + 'daysBetween(record.start_date, record.end_date) + 1', |
| 45 | + 'record.budget == null || record.budget > 100', |
| 46 | + '!isBlank(record.owner) && record.owner != record.creator', |
| 47 | + 'record.status == "open" ? record.amount * 0.1 : null', |
| 48 | + 'true ? 5 : null', |
| 49 | + 'size(record.items) > 0', |
| 50 | + '[1, 2, 3].all(x, x > 0)', |
| 51 | + 'record.?owner.orValue("none") == "none"', |
| 52 | +]; |
| 53 | + |
| 54 | +/** Sources the platform rejects at PARSE — syntax faults, in both entries. */ |
| 55 | +const SYNTAX_REJECTED = [ |
| 56 | + 'record.budget >', |
| 57 | + 'record.a $$ 1', |
| 58 | + 'record.a ?? 3', // cel-js 8 has no `??` |
| 59 | + '((record.a)', |
| 60 | +]; |
| 61 | + |
| 62 | +/** |
| 63 | + * The comparable content of a cel-js AST: `op` plus `args`, recursively. |
| 64 | + * |
| 65 | + * A raw deep-equal cannot be used here. `compile()` runs cel-js's `check()`, |
| 66 | + * which decorates every node IN PLACE with an entire evaluation plan — measured |
| 67 | + * on `record.amount > 1000`, the root gains `left`, `right`, `candidates`, |
| 68 | + * `handle` (a bound function), `rightStaticType` and `checkedType`, and |
| 69 | + * `candidates.registry` points back at the Environment, so the decorated tree is |
| 70 | + * circular. `parseCelToAst` is parse-only and carries none of it. |
| 71 | + * |
| 72 | + * `op` + `args` is also exactly the surface every AST consumer in this repo |
| 73 | + * walks (`lowerCelAst`, `collectCelRootIdentifiers`, lint's null-guard pass), so |
| 74 | + * equality on this projection is the claim that matters: the two entries hand a |
| 75 | + * consumer the same tree. |
| 76 | + */ |
| 77 | +function shapeOf(value: unknown): unknown { |
| 78 | + if (Array.isArray(value)) return value.map(shapeOf); |
| 79 | + if (value && typeof value === 'object' && typeof (value as { op?: unknown }).op === 'string') { |
| 80 | + return { op: (value as { op: string }).op, args: shapeOf((value as { args: unknown }).args) }; |
| 81 | + } |
| 82 | + // Leaves: identifier / member / function-name strings and literal values |
| 83 | + // (including the BigInts cel-js produces for `int`). |
| 84 | + return value; |
| 85 | +} |
| 86 | + |
| 87 | +/** Sources that parse but do NOT type-check — the deliberate asymmetry. */ |
| 88 | +const PARSES_BUT_FAILS_CHECK = [ |
| 89 | + '1 + "x"', |
| 90 | + 'NOPE(record.a) > 1', |
| 91 | + 'record.a.NOPE()', |
| 92 | +]; |
| 93 | + |
| 94 | +/** Over the platform's bounds — the divergence a bare env does not see. */ |
| 95 | +const OVER_BOUNDS: Record<string, string> = { |
| 96 | + maxAstNodes: Array.from({ length: 300 }, (_, i) => `record.f${i}`).join(' + '), |
| 97 | + maxDepth: '('.repeat(60) + 'record.a' + ')'.repeat(60), |
| 98 | + maxListElements: `[${Array.from({ length: 200 }, (_, i) => i).join(',')}].size() > 0`, |
| 99 | +}; |
| 100 | + |
| 101 | +describe('parseCelToAst — parity with celEngine.compile (#4812)', () => { |
| 102 | + it.each(ACCEPTED)('returns the SAME ast compile() returns: %s', (source) => { |
| 103 | + const compiled = celEngine.compile(source); |
| 104 | + expect(compiled.ok).toBe(true); |
| 105 | + const ast = parseCelToAst(source); |
| 106 | + expect(ast).not.toBeNull(); |
| 107 | + // `compile()` builds a FRESH env per call; `parseCelToAst` memoizes one. |
| 108 | + // Deep equality here is what pins that memo as equivalent — if the two ever |
| 109 | + // drift (a rewrite applied on one side, a limit on the other), this fails. |
| 110 | + expect(shapeOf(ast)).toEqual( |
| 111 | + shapeOf(compiled.ok ? compiled.value : undefined), |
| 112 | + ); |
| 113 | + }); |
| 114 | + |
| 115 | + it.each(SYNTAX_REJECTED)('rejects exactly what compile() rejects at parse: %s', (source) => { |
| 116 | + // The parity claim is the accept/reject verdict itself. `compile`'s error |
| 117 | + // *classification* is asserted separately below — cel-js does not phrase |
| 118 | + // every syntax fault the same way, and `classifyError` reads the phrasing. |
| 119 | + expect(parseCelToAst(source)).toBeNull(); |
| 120 | + expect(celEngine.compile(source).ok).toBe(false); |
| 121 | + }); |
| 122 | + |
| 123 | + it('yields a plain parse tree, while compile() yields a type-ANNOTATED one', () => { |
| 124 | + // The concrete difference between "parse" and "parse + check", pinned so the |
| 125 | + // two entries are not mistaken for interchangeable. A consumer walking |
| 126 | + // `.op`/`.args` sees the same tree from either; only `compile()` has run the |
| 127 | + // type checker over it. |
| 128 | + const source = 'record.amount > 1000'; |
| 129 | + const compiled = celEngine.compile(source); |
| 130 | + expect(compiled.ok).toBe(true); |
| 131 | + expect(compiled.ok && (compiled.value as { checkedType?: unknown }).checkedType).toBeDefined(); |
| 132 | + expect((parseCelToAst(source) as unknown as { checkedType?: unknown }).checkedType).toBeUndefined(); |
| 133 | + }); |
| 134 | + |
| 135 | + it('classifies the common syntax fault as `parse`', () => { |
| 136 | + const compiled = celEngine.compile('record.budget >'); |
| 137 | + expect(compiled.ok).toBe(false); |
| 138 | + if (!compiled.ok) expect(compiled.error.kind).toBe('parse'); |
| 139 | + // NOT asserted for `((record.a)`: cel-js phrases an unbalanced delimiter as |
| 140 | + // `Expected RPAREN, got EOF`, which `classifyError`'s |
| 141 | + // /parse|unexpected|syntax/i does not match, so a genuine syntax fault is |
| 142 | + // reported to the author as `runtime`. Pre-existing, out of scope for #4812, |
| 143 | + // filed separately — asserting it here would enshrine it. |
| 144 | + }); |
| 145 | + |
| 146 | + it.each(PARSES_BUT_FAILS_CHECK)( |
| 147 | + 'still yields an AST for a source that parses but fails check(): %s', |
| 148 | + (source) => { |
| 149 | + // The asymmetry is deliberate and load-bearing: `parseCelToAst` is parse |
| 150 | + // ONLY, `compile()` is parse + check. A consumer analysing an AST (the |
| 151 | + // null-guard pass, the pushdown compiler) must not be denied one just |
| 152 | + // because cel-js cannot type an expression over `dyn` operands — and a |
| 153 | + // caller who wants the type verdict asks `compile()`. Asserted so that |
| 154 | + // nobody "tightens" this entry into a second compile(). |
| 155 | + expect(parseCelToAst(source)).not.toBeNull(); |
| 156 | + const compiled = celEngine.compile(source); |
| 157 | + expect(compiled.ok).toBe(false); |
| 158 | + if (!compiled.ok) expect(compiled.error.kind).toBe('type'); |
| 159 | + }, |
| 160 | + ); |
| 161 | + |
| 162 | + it('never throws, and answers null for an empty source', () => { |
| 163 | + expect(parseCelToAst('')).toBeNull(); |
| 164 | + expect(parseCelToAst(' ')).toBeNull(); |
| 165 | + expect(parseCelToAst(undefined as unknown as string)).toBeNull(); |
| 166 | + expect(parseCelToAst(null as unknown as string)).toBeNull(); |
| 167 | + }); |
| 168 | +}); |
| 169 | + |
| 170 | +describe('parseCelToAst — carries the #3306 nullable-ternary rewrite', () => { |
| 171 | + // `true ? 5 : null` is the specimen: it PARSES in any env, but cel-js's |
| 172 | + // ternary unifier rejects it at check ("Ternary branches must have the same |
| 173 | + // type, got 'int' and 'null'"), so without the rewrite the blessed |
| 174 | + // `guard ? value : null` shape does not compile. The rewrite wraps the |
| 175 | + // non-null branch in `dyn(...)`, which is what makes it legal — and it is the |
| 176 | + // AST the runtime executes. An entry that skipped the rewrite would hand a |
| 177 | + // consumer a DIFFERENT tree from the one the platform runs. |
| 178 | + it('wraps the non-null branch in dyn(...), matching what the runtime executes', () => { |
| 179 | + const ast = parseCelToAst('true ? 5 : null') as unknown as { |
| 180 | + op: string; |
| 181 | + args: [unknown, { op: string; args: [string, unknown[]] }, unknown]; |
| 182 | + }; |
| 183 | + expect(ast).not.toBeNull(); |
| 184 | + expect(ast.op).toBe('?:'); |
| 185 | + expect(ast.args[1].op).toBe('call'); |
| 186 | + expect(ast.args[1].args[0]).toBe('dyn'); |
| 187 | + }); |
| 188 | + |
| 189 | + it('agrees with compile() on the rewritten shape, which only compile() could evaluate', () => { |
| 190 | + const source = 'record.status == "open" ? record.amount * 0.1 : null'; |
| 191 | + const compiled = celEngine.compile(source); |
| 192 | + expect(compiled.ok).toBe(true); |
| 193 | + expect(shapeOf(parseCelToAst(source))).toEqual( |
| 194 | + shapeOf(compiled.ok ? compiled.value : undefined), |
| 195 | + ); |
| 196 | + }); |
| 197 | + |
| 198 | + it('cannot change WHETHER a source parses — only the AST it yields', () => { |
| 199 | + // Stated as a test because it is the fact that makes #4812's originally |
| 200 | + // suspected hole ("formula rewrites something bare cel-js cannot parse, so |
| 201 | + // lint silently skips it") impossible by construction: the rewrite parses |
| 202 | + // the source FIRST and returns it unchanged on failure. Every source below |
| 203 | + // therefore gets the same accept/reject verdict from both entries. |
| 204 | + for (const source of [...ACCEPTED, ...PARSES_BUT_FAILS_CHECK]) { |
| 205 | + expect(bareParses(source)).toBe(true); |
| 206 | + expect(parseCelToAst(source)).not.toBeNull(); |
| 207 | + } |
| 208 | + for (const source of SYNTAX_REJECTED) { |
| 209 | + expect(bareParses(source)).toBe(false); |
| 210 | + expect(parseCelToAst(source)).toBeNull(); |
| 211 | + } |
| 212 | + }); |
| 213 | +}); |
| 214 | + |
| 215 | +describe('parseCelToAst — carries the platform bounds (the real #4812 divergence)', () => { |
| 216 | + it.each(Object.entries(OVER_BOUNDS))( |
| 217 | + 'refuses a source over %s, which a bare env happily parses', |
| 218 | + (_limit, source) => { |
| 219 | + // This is the measured divergence, in the direction it actually runs: a |
| 220 | + // consumer with its own limitless env parses — and then reasons about — a |
| 221 | + // predicate the platform rejects outright. Both halves asserted, so the |
| 222 | + // test states the divergence rather than merely benefiting from its fix. |
| 223 | + expect(bareParses(source)).toBe(true); |
| 224 | + expect(parseCelToAst(source)).toBeNull(); |
| 225 | + |
| 226 | + const compiled = celEngine.compile(source); |
| 227 | + expect(compiled.ok).toBe(false); |
| 228 | + if (!compiled.ok) { |
| 229 | + expect(compiled.error.kind).toBe('bounds'); |
| 230 | + expect(compiled.error.message).toMatch(/Exceeded max/i); |
| 231 | + } |
| 232 | + }, |
| 233 | + ); |
| 234 | + |
| 235 | + it('pins the bounds the entry enforces to DEFAULT_LIMITS', () => { |
| 236 | + // If DEFAULT_LIMITS moves, the fixtures above must move with it; this |
| 237 | + // assertion is the tripwire that says so out loud. |
| 238 | + expect(DEFAULT_LIMITS.maxAstNodes).toBe(256); |
| 239 | + expect(DEFAULT_LIMITS.maxDepth).toBe(32); |
| 240 | + expect(DEFAULT_LIMITS.maxListElements).toBe(64); |
| 241 | + }); |
| 242 | +}); |
0 commit comments