T0001 — Lexer
Part of the roadmap. Phase 1 · wave 1 · size M.
- Depends on: T0000
- Parallel with: T0003, T0004, T0005, T0022
- Conformance groups:
comments(with T0002) - Background: ADR-0002
Goal
Turn an expression string into tokens with exact source spans, as described in the design notes below.
Scope
src/lexer/: token kinds (token.ts), the lexer (lexer.ts), character-code constants (char-codes.ts), and a line table for line/column lookup (line-table.ts).- Identifiers, delimited identifiers, strings with all escapes, numbers (including the
1.toString()rule), date/time literals (@2015,@2015-02-04T14:34:28+09:00,@2015T,@T14:30:14.559), symbols and operators,$this/$index/$total, and%followed by an identifier, a delimited identifier or a string. The double-quoted%"…"form is accepted for compatibility. - Comments and whitespace, plus an
includeTriviaoption. - Error codes
syntax/unterminated-string,syntax/unterminated-comment,syntax/invalid-escape,syntax/unexpected-characterandsyntax/invalid-date-literal(shape only). A timezone on aTIMEliteral (@T14:34:28Z) is accepted as part of the token; the compiler rejects it at evaluation (T0008).
Design notes
The lexer is hand-written (ADR-0002). It makes one pass over the UTF-16 string, switching on character codes; the hot path has no regular expressions.
-
Tokens carry
kind,startandendoffsets, and avalue(see token API). Line and column are computed lazily from a line table, only when an error is formatted. -
Trivia: whitespace,
//line comments and/* */block comments are skipped. AnincludeTriviaoption keeps them for tooling. -
Identifiers: simple identifiers (
[A-Za-z_][A-Za-z0-9_]*) and delimited identifiers in backticks, which support the same escapes as strings (N1 §8.6). -
Keywords are lexed as identifiers, and the parser decides what they mean. This is because
as,contains,inandisare also legal identifiers, whilediv,mod,andand the others are reserved (N1 §8.5). Calendar unit keywords (year,months, …) work the same way. -
Strings: single quotes, with escapes
\',\",`,\,\/,\f,\n,\r,\tand\uXXXX(N1 §4.1.2). Any other escape issyntax/invalid-escape. N1 says the backslash of an unknown sequence is ignored, but the suite rejects'\u+041', and Callis follows the suite (spec notes). An escaped surrogate must be part of a pair, as 3.0.0 requires (spec notes). Unescaped line breaks are allowed, as in the grammar. -
Numbers:
[0-9]+('.'[0-9]+)?. Leading zeros are allowed. A.that is not followed by a digit ends the number, so1.toString()lexes as1,.,toString. TheLsuffix forLong(phase 2) is anticipated. -
Date/time literals: the
@forms from the grammar (DATE,DATETIMEincluding@2015T,TIMEas@T…). The lexer checks only the shape. It also tolerates a timezone on aTIMEliteral (@T14:34:28Z), which the grammar does not allow, so that the literal can fail at evaluation as the suite expects (see T0008: invalid literal values). Range checks (month 13, Feb 30) happen when the compiler builds the literal value. Like the grammar's tokens, a literal is the longest prefix with a valid shape, so@2015-1is@2015,-,1. A literal directly followed by a digit or:(@2015-01-01T14:3) issyntax/invalid-date-literal(spec notes). -
Symbols:
( ) [ ] { } . , = != ~ !~ < <= > >= + - * / | &, and$this,$indexand$total.%starts an environment variable token. -
Environment variable names: after
%come an identifier, a delimited identifier, or a string (%'us-zip', allowed for backwards compatibility per N1 §9). The double-quoted form%"vs-name"that appears on the FHIR pages is accepted as a documented compatibility extension.%and the name form oneEnvironmentVariabletoken, with nothing between them (spec notes). -
Errors: each raises
FhirPathSyntaxErrorwith a span.Problem Code Unterminated string, delimited identifier or quoted variable name syntax/unterminated-stringUnterminated /*commentsyntax/unterminated-commentInvalid escape, or an unpaired escaped surrogate syntax/invalid-escapeUnexpected character, !without=or~,$withoutthis,indexortotal,%without a namesyntax/unexpected-characterMalformed date/time literal syntax/invalid-date-literal
Token API
The parser (T0002) uses this interface. All of it is internal to @callis/core.
// token.tstype SymbolKind = '(' | ')' | '[' | ']' | '{' | '}' | '.' | ',' | '=' | '!=' | '~' | '!~'| '<' | '<=' | '>' | '>=' | '+' | '-' | '*' | '/' | '|' | '&';type TriviaKind = 'Whitespace' | 'LineComment' | 'BlockComment'; // only with includeTriviatype TokenKind = 'Identifier' | 'DelimitedIdentifier' | 'String' | 'Number'| 'Date' | 'DateTime' | 'Time' | 'EnvironmentVariable' | '$this' | '$index' | '$total'| SymbolKind | TriviaKind | 'EOF';interface Token {readonly kind: TokenKind;readonly start: number; // UTF-16 offset, inclusivereadonly end: number; // UTF-16 offset, exclusivereadonly value: string;}// lexer.tsfunction tokenize(expression: string, options?: { includeTrivia?: boolean }): readonly Token[];// line-table.tsclass LineTable {constructor(source: string);readonly lineCount: number;locate(offset: number): { line: number; column: number }; // 1-basedspan(start: number, end?: number): SourceSpan;}
tokenize()returns every token at once and always ends with anEOFtoken atexpression.length. The parser can look ahead as far as it needs. Because the whole expression is lexed first, a lexical error is reported even when a parse error comes earlier in the text.valueis the decoded text forStringandDelimitedIdentifier(quotes removed, escapes decoded) and the decoded name forEnvironmentVariable(%ucum,%`ucum`,%'ucum'and%"ucum"all have the valueucum). ForEOFit is empty. For every other kind it is the source text, for example1.50or@2015-02-04, so literals keep their raw text. For aStringliteral, the raw text isexpression.slice(token.start, token.end)and the decoded text isvalue; the AST should keep the decoded text, so the compiler does not decode escapes a second time.- Keywords, including
true,false, the operatorsand,div, … and the calendar units, areIdentifiertokens. To reject%trueor other reserved words after%, the parser can check whether the character after%is a letter or_. - With
includeTrivia, the tokens cover the expression without gaps; joining their source text rebuilds it. LineTableuses the same line breaks asspanFromOffsets(\n,\r\nor a lone\r).
Acceptance criteria
- Every token kind is produced with correct
start/end. Errors report correct line and column. - All examples in N1 §8 and all escapes in N1 §4.1.2 have table-driven tests.
- Edge cases are covered:
1.toString(),1.5,`div`, unterminated/*,@2015-01-01T,@T14, timezoneZand±hh:mm. - A fuzz test (random strings) never crashes; it only produces tokens or
FhirPathSyntaxError. - Line coverage of
lexer/is at least 95%.