T0002 — Parser and AST
Part of the roadmap. Phase 1 · wave 2 · size M.
- Depends on: T0001
- Parallel with: T0006, T0019
- Conformance groups:
comments,testPrecedence(parse level) - Background: ADR-0002
Goal
A Pratt/recursive-descent parser that produces the AST from design notes.
Scope
src/parser/ast.ts: node types with spans, where literals keep their raw text.src/parser/precedence.tsandparser.ts:- the binding-power table
- postfix
.and[] - prefix
+and- is/aswith greedy type specifiers- function calls and argument lists
- quantity literals (number + string, or number + calendar keyword)
{}- keyword-identifiers (
as,contains,in,is) - a nesting-depth limit
- An internal
parse()and a test-only AST printer (S-expressions) for compact structural assertions. - Syntax errors that name the expected token.
Design notes
Binding powers
These follow N1 §6.8 and the ANTLR grammar. All binary operators are left-associative.
| Binding power | Operators | Kind |
|---|---|---|
| 13 (highest) | . invocation | postfix |
| 12 | [ ] indexer | postfix |
| 11 | unary +, - | prefix |
| 10 | *, /, div, mod | infix |
| 9 | +, -, & | infix |
| 8 | is, as (right side is a type specifier) | infix |
| 7 | ` | ` |
| 6 | <, >, <=, >= | infix |
| 5 | =, ~, !=, !~ | infix |
| 4 | in, contains | infix |
| 3 | and | infix |
| 2 | or, xor | infix |
| 1 | implies | infix |
Rules worth calling out:
- Unary minus binds looser than
., so-1.convertsToInteger()parses as-(1.convertsToInteger()), as in the N1 §6.8 example. The AST stays faithful to this; the compiler folds-<number literal>into a negative literal. is/asread a qualified identifier greedily.x as Quantity.unitnames the typeQuantity.unit, so authors must write(x as Quantity).unit. This matches the ANTLR grammar. A dot before a function call or$this/$index/$totalcannot belong to the type name and starts an invocation on the type-operation expression:x as T.f()callsfonx as T, andx as T.$thistargetsx as T.- The function forms
is(T),as(T)andofType(T)parse their argument as an expression. The compiler then reads it as a type specifier: an identifier or a chain of member accesses. NUMBERfollowed by aSTRINGor a calendar keyword becomes aQuantityliteral.{}is the empty literal.as,contains,inandisare accepted where an identifier is expected, as in'abc'.contains('b').- A leading identifier is parsed as a plain
Identifier. Whether it names a type (such asPatient) or a path is decided later (T0018: navigation rules). - Nesting limit: a maximum depth (default 1,000) prevents stack overflows on hostile input.
- The parser stops at the first error. Error recovery for editor use may come later.
AST
The AST is a discriminated union. Every node has span: { start: number; end: number }.
type ExpressionNode =| LiteralNode // { kind: 'Literal', type: 'Boolean' | 'String' | 'Integer' | 'Decimal' | 'Date' | 'DateTime' | 'Time' | 'Quantity' | 'Empty', raw: string, unit?: string }| IdentifierNode // { kind: 'Identifier', name, delimited } — root-level member or type name| MemberNode // { kind: 'Member', target, name, delimited } — a.b| FunctionCallNode // { kind: 'FunctionCall', target | null, name, args }| IndexerNode // { kind: 'Indexer', target, index }| UnaryNode // { kind: 'Unary', op: '+' | '-', operand }| BinaryNode // { kind: 'Binary', op, left, right }| TypeOperationNode // { kind: 'TypeOperation', op: 'is' | 'as', operand, type: TypeSpecifierNode }| VariableNode // { kind: 'Variable', name } — %name| ThisNode | IndexNode | TotalNode; // $this, $index, $total
Literal nodes keep the raw source text. The compiler converts it with the value modules. This keeps the parser independent of the Decimal and date/time implementations, so they can be built in parallel, and it preserves decimal precision (1.0 vs 1). Literal values that are well-formed but invalid (@2015-02-30, @T14:34:28Z) are handled by the compiler at evaluation time; see T0008: invalid literal values.
The official N1 grammar invocation rule also permits expr.$this, expr.$index and expr.$total. Those nodes have target: ExpressionNode | null, like FunctionCallNode; the bare forms have a null target. This represents syntax only; T0008/T0018 decide evaluation semantics.
parse(expression, { maxDepth? }) stays internal until T0025. Depth is the depth of the expression tree, counting the root and each parenthesized group as a level; the default and maximum permitted setting is 1,000, and callers may lower it. Invalid settings and excess nesting raise syntax/nesting-limit. Each step of a member, call, index, type-operation or left-associative operator chain nests the chain before it one level deeper, so a chain cannot build a tree deeper than the limit either (#107).
The AST type name is TypeSpecifierNode, distinct from types/TypeSpecifier (#54). It carries kind: 'TypeSpecifier', a span, and identifiers: readonly string[] preserving decoded identifiers as written (without resolving namespaces or changing case). The compiler adapts these with typeSpecifierFromIdentifiers(). String literals additionally retain the lexer's decoded value; quantity literals retain the decoded unit and the raw numeric number text. raw always keeps untouched literal source spelling, even when parentheses widen span; value and unit are decoded, with no case or unit normalization. Grouping expands the enclosed node's span to include parentheses without introducing another AST kind.
The AST is part of the public API (parse()), but its shape is not frozen before 1.0.
Acceptance criteria
-
Each adjacent pair of precedence levels has a test, as does left-associativity and the N1 §6.8 example
-7.combine(3).x as Quantity.unitparses as a type specifier. -
Every in-scope
<expression>intests-fhir-r4.xmlandtests-fhir-r5.xmlwithoutinvalid="syntax"parses, and every in-scopeinvalid="syntax"one throwsFhirPathSyntaxError. Exceptions, each listed in the PR:- out-of-scope groups (
documentFunctions,cdaTests) - expressions that use phase-2 syntax (
Lliterals, instance selectors) - the R5
htmlTest01expressiontext.div.htmlChecks(), which violates the identifier grammar becausedivis reserved. It must throw; the correctedtext.`div`.htmlChecks()form must parse. See spec notes. - suite labels that do not describe a grammar error. For example,
testSection13marks the well-formed callBundle.section('http://loinc.org', '11450-4', 1)assyntax, although the problem is the arity of an extension function. These go intospec-notes.md. The parser stays purely syntactic and does not check functions.
The XML files come from T0022's vendored fixtures; if T0022 has not landed yet, copy the two files into the test folder temporarily.
- out-of-scope groups (
-
No imports from
values/; literal conversion is the compiler's job (T0008). -
Line coverage of
parser/is at least 95%.