Specification notes
How Callis reads the FHIRPath specification where the text is ambiguous, silent, or disagrees with the HL7 test suite. Each entry gives the spec link, the affected tests and the decision. Entries are added in the same PR as the code (AGENTS.md).
Decimal
Precision and rounding of division
- Spec: N1 §4.1.4 asks for at least 28 digits with 8 decimal places; N1 §6.6.2 does not say how many digits a quotient keeps or how it is rounded.
- Tests:
testDivide1–testDivide7,testComment6(2 / 2is the decimal1),testEquivalent11,testNEquality22. - Decision: the quotient is rounded half away from zero to 28 significant digits, or to 8 digits after the decimal point if that keeps more, and trailing zeros are then removed. So
1 / 3is0.3333333333333333333333333333,4 / 2is2and1 / 2is0.5. Half away from zero matchesround()(3.0.0). Negative integer powers use the same division (T0004).
round() never adds digits
- Spec: N1
roundand 3.0.0roundsay the precision is "the decimal place at which the rounding will occur", but not what happens when the input has fewer decimal places. - Tests:
testRound1,testRound2(not affected either way). - Decision:
round(n)rounds half away from zero tondecimal places, and a value that already has at mostndecimal places is returned unchanged:1.5.round(3)is1.5, not1.500. Padding would claim precision the value does not have, and it would letx.round(2147483647)allocate a huge number.
Rounding in decimal equivalence
- Spec: N1 §6.1.2 compares "values rounded to the precision of the least precise operand" and ignores trailing zeros when determining precision, but does not name the rounding mode.
- Tests:
testEquivalent8–testEquivalent13,testNotEquivalent8–testNotEquivalent13. - Decision: both values are rounded half away from zero, as
round()does. A consequence of ignoring trailing zeros is that1.04 ~ 1.0istrue:1.0counts as precision 0.
Results that cannot be represented are empty
- Spec: 3.0.0 §6.6 makes arithmetic overflow and underflow empty;
powerandsqrtare empty when the result "cannot be represented". - Tests:
testPower3,testSqrt2. - Decision: the Decimal kernels for
sqrt,exp,ln,logandpowerreturn empty forNaN, infinite results and results that underflow to zero although the exact value is not zero. Results beyond the size of a Decimal are empty too. For a whole exponent the bound applies to the exact power|base|^|exponent|; for a negative exponent that is the denominator, so2.power(-40000)is empty although 28 digits of it would fit. The scale counts, so0.1.power(10001)and1.0.power(100000)are empty. Where 3.0.0 asks for an error instead of empty (for examplelog()of a non-positive number), the function layer (T0016) raises it.
Size of a Decimal
- Spec: N1 §4.1.4 asks for at least 28 digits with 8 decimal places and lets implementations support more. 3.0.0 §6.6 makes arithmetic overflow and underflow empty. Neither sets an upper limit.
- Tests: none in the suite come near the bound.
- Decision (owner, #47, 2026-11-04): a Decimal's coefficient has at most 10,000 digits and its scale is at most 10,000. An operation whose exact result is beyond that (
+,-,*,/,div,power,ln,log) is overflow or underflow and gives empty. So1e9999 + 1e-10000, which needs 20,000 digits, is empty, and repeated squaring ends in empty instead of an error. Division keeps its 28 significant digits and its 8 digits after the point rather than rounding to fit. So1 / 3e9980is empty, and so is a quotient from about1e9992up that is not exact within fewer digits (1e9995 / 3). Text beyond the bound does not parse, sotoDecimal()gives empty. A Decimal literal beyond the bound is a valid token with no Decimal value. It is an invalid literal value: it raiseseval/invalid-literalwhen evaluated, like@2015-02-30(owner, #69, 2026-11-05; T0008).
Math functions
The math functions (N1 §5.7, T0016) are thin: the numbers come from the Decimal kernels (see Decimal) and the functions add singleton evaluation, the implicit Integer → Decimal conversion and the Integer range.
The result of power() is a Decimal
- Spec: N1
powersays the result is an Integer when both operands are Integers. 3.0.0powersays it is always a Decimal, "because raising an Integer to a negative power (such as -1) produces a Decimal result", and shows2.power(3) // 8 (as a decimal). - Tests:
testPower1,testPower2,testPower3,testPowerEmpty–testPowerEmpty3(R5). Equality does not tell an Integer from a Decimal, so no suite test depends on it. - Decision: follow 3.0.0 (ADR-0001):
power()always returns a Decimal, so2.power(3)is the Decimal8and2.power(-1)is0.5. The alternative, an Integer for non-negative whole exponents, would make the type of the result depend on the value of the exponent.round()follows the same 3.0.0 line:1.round()is the Decimal1.
log() of zero or a negative number is an error, ln() is empty
- Spec: 3.0.0
logsays that an input or a base of 0 or less ends the evaluation with an error. N1 has no such sentence, and neither version says anything aboutln()of such a number or about base 1. - Tests:
testLog1,testLog2,testLogEmpty–testLogEmpty3(R5),testLn1,testLn2. - Decision:
log()raiseseval/invalid-argumentfor an input or a base of zero or less, as 3.0.0 asks and as Results that cannot be represented are empty announces. An empty input or an empty base is checked first, so(-1).log({})is empty.ln()has no such sentence and falls under "cannot be represented", so0.ln()and(-1).ln()are empty. Base 1 has no logarithm either, and gives empty, like division by zero.
Integer results outside the Integer range are empty
- Spec: 3.0.0 §6.6 makes overflow and underflow empty.
ceiling(),floor()andtruncate()return an Integer, andabs()returns the type of its input, but a Decimal can hold a whole number beyond the 32-bit Integer range. - Tests: none in the suite.
- Decision: the result is empty when it is not an Integer:
3000000000.5.floor()and(-2147483648).abs()are empty, like the Integer overflow of+and*. The input ofceiling(),floor()andtruncate()may be an Integer, which is returned as it is.
round() with an empty or a negative precision
- Spec: N1
roundrequires a precision of 0 or more, "or the evaluation will end and signal an error". It does not say what an empty precision (1.5.round({})) gives;log()andpower()say that an empty argument gives an empty result. - Tests:
testRound1,testRound2,testRoundEmpty(R5). - Decision: a precision that is left out is 0; an empty precision gives an empty result, as for
log()andpower(). A negative precision raiseseval/invalid-argumenteven when the input is empty, because the argument is wrong whatever the input. A precision that is not an Integer (2.5.round(1.5)) raiseseval/type-mismatch.
ceiling(), floor(), round() and truncate() of a Quantity
- Spec: N1 lists
Quantityonly forabs(). 3.0.0 also letsceiling(),floor()andtruncate()take a Quantity: "the result is a Quantity with the same units and the value (Decimal) set to the integer result calculated".round()gives "a Quantity with the same units". - Tests: none in the suite;
testAbs3coversabs(). - Decision: follow 3.0.0 (ADR-0001, #176): the four functions keep the unit, so
(5.5 'mg').ceiling()is6 'mg'and(5.55 'mg').round(1)is5.6 'mg'. The value stays a Decimal, as the value of every Quantity is (N1 §4.1.8):ceiling(),floor()andtruncate()give the whole number without digits after the point ((5.0 'mg').floor()is5 'mg'), andround()rounds it like any Decimal. Since that value is not an Integer, the Integer range does not apply:(3000000000.5 'mg').floor()is3000000000 'mg', while3000000000.5.floor()is empty (Integer results outside the Integer range are empty). The other math functions still raiseeval/type-mismatchfor a Quantity.
Lexer
Unknown escape sequences are syntax errors
- Spec: N1 §4.1.2 lists the escapes
\',\",`,\r,\n,\t,\f,\and\uXXXX, and says that "if a `` is used at the beginning of a non-escape sequence, it will be ignored":'\p'is'p','\u005'is'u005', and'\'is''. 3.0.0 repeats the rule. The grammar'sESCrule also allows\/; the N1 grammar lacks\", which the 3.0.0 grammar adds. - Suite:
testLiteralUnicodeInvalidexpects'\u+041'to be a syntax error, which contradicts the rule.testLiteralStringEscapesuses\'as an escaped quote, which contradicts'\'being''. - Decision: follow the suite and T0001. The escapes listed above and
\/are recognized; any other sequence that starts with `` raisessyntax/invalid-escape, and'\'is an unterminated string. This applies to strings, delimited identifiers and quoted environment variable names. The owner confirmed this on 2026-11-04. (T0001)
Escaped surrogates must form a pair
- Spec: 3.0.0 §String:
\uXXXXescapes are UTF-16 code units, and an escaped surrogate "must be paired with a corresponding high or low surrogate to form a valid Unicode scalar value". N1 says nothing about it. - Suite: no tests.
- Decision: an escaped high surrogate that is not followed by a low surrogate, or an escaped low surrogate that does not follow a high surrogate, raises
syntax/invalid-escape. The other half of the pair may be escaped or not. Unescaped characters are not checked. (T0001)
A time zone on a Time literal is read by the lexer
- Spec: N1 §4.1.6 says Time values have no time zone, and the grammar's
TIMEtoken has no offset. - Suite:
testLiteralTimeUTC(@T14:34:28Z.is(Time)) andtestLiteralTimeTimezoneOffset(@T14:34:28+10:00.is(Time)) are labelledinvalid="execution", notsyntax. - Decision: follow the suite. The lexer reads
Zor±hh:mmas part of the Time token, and the compiler raiseseval/invalid-literalwhen the literal is evaluated (T0008: invalid literal values). (T0001)
Date and time literals end at the longest valid shape
- Spec: the
DATE,DATETIMEandTIMEtokens of the grammar. An ANTLR lexer takes the longest input that matches a token. - Suite:
testLiteralDateTimeSecond(@2015-02-04T14:34:28.is(DateTime)),testLiteralTimeMillisecondand the othertestLiteral*tests need a.without a digit after it to end the literal. - Decision: the lexer takes the same longest match, so
@2015-1lexes as@2015,-,1, and@T14:30+01as@T14:30,+,01. When a literal is directly followed by a digit or a:, as in@2015-01-01T14:3or@20150, the lexer raisessyntax/invalid-date-literalfor the whole malformed literal. The grammar cannot accept such input either, so this changes only the error, not which expressions are valid. (T0001)
Environment variables are single tokens
- Spec: N1 §9 calls an environment variable "a token introduced by a %", whose name is an identifier, a delimited identifier, or (for backwards compatibility) a string. The grammar's
externalConstantis a parser rule, which would allow whitespace after the%. The FHIR pages (R4, R5) write the names in double quotes:%"vs-[name]",%"ext-[name]". - Suite:
testVariables3(%ucum),testVariables4(%`vs-administrative-gender`) andtestExtension2(%`ext-patient-birthTime`). - Decision:
%and its name form oneEnvironmentVariabletoken, so nothing may come between them (% ucumis an error). The double-quoted form is accepted as a compatibility extension, with the same escapes as strings. A"anywhere else is an unexpected character. The owner confirmed this on 2026-11-04. (T0001)
Types
Type names are case-sensitive, and qualified names do not fall back
- Spec: N1 §10.1 Models
- Tests:
testType5,testType11–testType14,testType22 - Decision: Type names and namespaces are matched exactly. An unqualified name is looked up in the model namespace, then in
System, so with the FHIR modelbooleanisFHIR.booleanandBooleanisSystem.Boolean;Patient.active.is(Boolean)is false. A qualified name is looked up in its own namespace only:System.PatientandFHIR.Booleando not resolve. - Consequence: with the FHIR model, the unqualified
QuantityisFHIR.Quantity, so5 'mg' is Quantityis false (the literal is aSystem.Quantity) and5 'mg' is System.Quantityis true. The suite writesSystem.Quantitywhen it tests literals (testDecimalLiteralIsNotQuantity). Without a model,QuantityisSystem.Quantity. - Code:
resolveTypeSpecifier()inpackages/core/src/types/type-specifier.ts(T0003).
Unresolved type specifiers are execution errors
- Spec: N1
isandasrequire an error when the target identifier does not resolve. The permanent 3.0.0isandasretain that rule; 3.0.0ofTypelikewise requires a type identifier that resolves. Type safety permits implementation choices about compile-time versus runtime checks. - Pinned tests: both R4 and R5 at
cb4eac4classifytestFHIRPathAsFunction23(Patient.gender.as(string1)) and24(Patient.gender.ofType(string1)) asinvalid="execution".testType22(Patient.is(System.Patient).not()) instead expects true. These are all phase-1 tests under the runner's per-test classifier; the surrounding group's reflection tests are STU. R5's description explicitly permits a resolution error forSystem.Patient; R4 lacks that description but has the same positive assertion. - Decision: an unresolved type is an execution error (
FhirPathEvaluationError,eval/unknown-type) foris/asand their function forms and forofType(). Resolution is still performed once during compilation; an unresolved result compiles to a closure that raises at the evaluated use site, before matching or empty-input handling. Constant folding must preserve this timing. Unreached lazy branches do not raise it. Analysis can emit asemantic/unknown-typewarning, including in strict mode, without preventing compilation. This agrees with the execution-error fixtures and closure architecture. - No namespace exemption:
System.Patient,FHIR.Booleanwith a FHIR model, unknown namespaces and unknown unqualified names with a model all error. A known namespace does not define all possible type names. Resolved nonmatching targets still give false/empty under the ordinary operator rules. The separate model-less unqualified extension below is the only resource-name fallback. - Narrow suite exception: follow the normative error rule rather than making
System.Patienta special always-false target. Under ADR-0011, onlytestType22is registered, for R4 and R5, intools/conformance/src/exceptions.tswith this heading as its note, since the conformance runner evaluates with a model (T0018). The vendored tests are unchanged, and the exception is reported as skipped, not passed.testFHIRPathAsFunction23/24remain ordinary phase-1 tests expecting execution errors, and pass. - Ownership: T0008 implements target handling and adds the evaluation error code; T0042 reuses it for
ofType()(it moved there from T0012 when T0012 was narrowed towhere), T0018 integrates model types and the named exception, T0024 preserves error timing in diagnostics. T0003's pure resolver and System/model subtype helpers remain unchanged. This resolves the planning choice in #58, not its future implementation.
is on empty input is false
- Spec: N1 §6.3.1 ends the rule for
iswith "In all other cases this operator returns the empty collection", which includes empty input. 3.0.0 changes that sentence to "In all other cases this operator returns false." Theis()function follows the operator. - Tests: R4 and R5
testPolymorphismIsA3evaluateObservation.issued is instantonobservation-example, which has noissued, and expect empty, as N1 says; they are exceptions. Unit tests:{} is Integerinpackages/core/test/evaluate.test.ts. - Decision (owner, #148, 2026-11-11): follow 3.0.0 where the test suite disagrees with it (ADR-0001), as T0008 already does.
isandis()on empty input arefalsewhen the target resolves:{} is Integerisfalse, so({} is Integer).not()istrue. An unresolved target still raiseseval/unknown-typeon empty input (above), more than one item still raiseseval/singleton-expected, andasandofType()on empty input stay empty. - Code:
isType()inpackages/core/src/runtime/type-target.ts(T0008); the exceptions intools/conformance/src/exceptions.ts.
Resource type names without a model
- Spec: N1 models and 3.0.0 type specifiers assume known types; they do not define Callis's plain-JSON model-less mode. The T0003 model principles already give resources a name through
resourceType. - Tests: no official model-less fixture defines this behavior. The matcher's tests are in
runtime/type-target.test.tsandtest/evaluate.test.ts(T0008), and T0042 adds theofType()cases such asBundle.entry.resource.ofType(Patient). Between them they cover exact matching, invalid qualifiers, System precedence, empty/multiple input, and inherited or invalidresourceType. T0018 covers model-present exclusion. - Decision: only without a model, an unqualified name that does not resolve to System is a resource-name target. It matches input objects with an own string
resourceTypeexactly equal to the name (case-sensitive), never primitives, inherited properties or missing/non-string values. It needs no FHIR registry or input-dependent type discovery; the pure resolver still returnsundefined. A name absent from the data, including a typo, is a valid nonmatching resource-name target, so singletonisgives false andas/ofType()give empty. This loss of typo detection is intentional and confined to this mode. - Limits: no inheritance is inferred, so a Patient does not match
ResourceorDomainResource. System targets take precedence, and qualified unresolved names (System.Patient,FHIR.Patientwithout a model,Foo.Patient) raiseeval/unknown-type. With a model, never use this fallback even if an individual node lacks a model type: the provider decides its model type. Existing FHIR primitive rules, includingofType()'s mapped-System support, remain unchanged. - Cardinality: for a valid target use 3.0.0's empty
isresult (false; above), emptyas/ofType()results, and singleton errors for multi-itemis/as. Unknown qualified targets still error on empty input, as above. Input shape never turns an unresolved target into a mismatch. - Ownership: T0008 builds the runtime matcher and shares the own-property exact-name rule with the model-less root identifier; T0042 reuses it for
ofType(), T0018 disables it when a model is supplied, and T0024 recognizes these valid model-less targets (#59). T0008 and T0018 implemented the runtime contracts and theofType()function (T0042) reuses them; the analyzer (T0024) still has to. None of this changes the pure type helpers.
Every type is a System.Any, including model types
- Spec: N1 §4.1 Literals calls
System.Any"an ultimate root type"; 3.0.0's reflection section defines it as the base type of the primitives. - Tests: none in the suite.
- Decision:
is System.Any(andas,ofType()) is true for every type, System or model. - Code:
isOfType()inpackages/core/src/types/type-test.ts(T0003).
FHIR primitives in is, as and ofType()
- Spec: R5 §2.1.9.1.2; N1 §6.3, §5.2.4
- Tests:
testType11–testType14,testFHIRPathIsFunction1–10,testFHIRPathAsFunction11–22 - Decision:
isdoes not treat a FHIR primitive as the System type it converts to:Patient.active.is(System.Boolean)is false. R5 lifts this restriction forofType()only, soasbehaves likeis, andPatient.name.given.ofType(System.String)keeps the given names.- All three accept subtypes through the model's inheritance, as N1 says for each of them.
Patient.gender.is(string)is true becausecodederives fromstring. - The suite marks
testFHIRPathAsFunction11(Patient.gender.as(string)) andtestFHIRPathAsFunction16(Patient.gender.ofType(string)) as contested and expects them to be empty. Callis follows the spec and returns the code. Both are registered as exceptions for R4 and R5 intools/conformance/src/exceptions.ts, since the conformance runner evaluates with a model (T0018, #111);testFHIRPathAsFunction11left the baseline that way.
- Code:
isOfType()andmatchesOfType()inpackages/core/src/types/type-test.ts(T0003).
FHIR.date maps to System.Date
- Spec: the mapping table in R5 §2.1.9.1.2 maps
FHIR.datetoSystem.DateTime. - Tests:
testExtractBirthDateexpectsbirthDateto have output typedate. - Decision:
FHIR.datemaps toSystem.Date, as the suite and the other major implementations do.dateTimeandinstantmap toSystem.DateTime. The R6 draft6.0.0-snapshot1corrects its table toSystem.Date(FHIR-55637 in the page's change notes), so this decision agrees with it. - Consequence:
Patient.birthDate.ofType(System.Date)keeps the birth date andPatient.birthDate.ofType(System.DateTime)is empty, although R5's table suggests the opposite.ofType()filters by type and does not apply the implicitDate → DateTimeconversion. - Code: the
ModelProvider.getSystemType()contract inpackages/core/src/model/model-provider.ts(T0003); the generated models implement it (T0019).
The id of a resource is an id, the id of any other element a string
- Spec: the published definitions of R4
Resource.id(typeid) and R4Element.id(typestring); R5 and R6 giveResource.idthe same type.ElementDefinition.basenames the one element that defines an inherited element, and a snapshot holds the base's element unless the differential changes it. - Tests:
testContainedId(R4) expectscontained.idto have the output typeid. It already passed with R5. - Source: the System-typed
idelements in the pinned packages carry their FHIR type instructuredefinition-fhir-type, and the sources disagree with the published definitions and with themselves:- R4 4.0.1 gives
Resource.idthe typestring, in both its snapshot and its differential, and so do the 147 resources that inherit it. - R5 5.0.0 is right for
Resource.idand its 161 copies, but gives 46 datatypes (Address.id,Age.id, …) the typeidalthough they inheritElement.id, astring. - R6 6.0.0-snapshot1 is right for
Resource.idand 7 resources, but gives the 116 others (Patient.id, …) the typestring. Element.id(string) andExtension.url(uri) agree with their published definitions in all three, and so does every other element typed this way.
- R4 4.0.1 gives
- Decision:
- The generator reads the FHIR type of an inherited element from the element that defines it, through
base.path, not from its own snapshot copy. An element that its differential redefines keeps its own type. - The one defining element that contradicts its published type, R4
Resource.id, is corrected by an entry in the release table intools/model-gen/src/cli.ts. An entry names the value it replaces. Generation fails when the source no longer carries that value, or when nothing uses the entry, so changing the pin means reviewing it.
- The generator reads the FHIR type of an inherited element from the element that defines it, through
- Consequence: in the R4, R5 and R6 models every resource's
idis anidand every otheridastring, soPatient.id is idandcontained.id is idare true, andAddress.id is stringis true. Against the earlier output, 148 R4 resources and 116 R6 resources change fromstringtoid, and 46 R5 datatypes fromidtostring. - Code:
generateModel()intools/model-gen/src/generate.tsand the corrections intools/model-gen/src/cli.ts(T0019).
Collections and evaluation
Singleton evaluation uses implicit conversions only
- Spec: N1 §4.5 says a single item is used if it "can be converted to the expected input type"; 3.0.0 says "implicitly converted".
- Tests: none specific.
- Decision: Only the implicit conversions of N1 §5.5 apply. A single
'5'where an Integer is expected is an error, not5; where a Boolean is expected it istrue(step 2). - Error codes: the spec only says that evaluation "will signal an error". More than one item raises
eval/singleton-expected; a single item that does not convert raiseseval/type-mismatch, because its type is the problem andfirst()would not help. The owner decided this on 2026-11-05. - Code:
singleton()inpackages/core/src/runtime/singleton.ts(T0003).
Integer literals outside the 32-bit range
- Spec: N1 §4.1 makes
Integera 32-bit signed integer, but the grammar'sNUMBERtoken has no size limit, and N1 does not say what an Integer literal beyond the range means. FHIRPath 3.0.0 addsLongliterals with anLsuffix (STU, T0028). - Tests:
testLiteralIntegerMax(2147483647, valid); none beyond the range. - Decision: an Integer literal outside -2,147,483,648 to 2,147,483,647 is an invalid literal value: it compiles, and raises
eval/invalid-literalwhen it is evaluated, like@2015-02-30(T0008: invalid literal values). It does not silently become a Decimal or a Long. A sign written directly before the literal is part of its value, so-2147483648is valid although2147483648alone is not. Any further+or-follows the ordinary Integer rules, so-(-2147483648)overflows to empty, exactly as-%idoes when%iis the smallest Integer. - Code:
constantOf()andmaterialize()inpackages/core/src/compiler/literal.ts.
Function arguments are evaluated with the focus of the call
- Spec: N1 §5 says how a function evaluates an expression parameter for each input item, but not what the focus of an ordinary argument is.
- Tests: none specific;
testCombineandtestUnionrely on it, for examplename.select(use.union(given)). - Decision: a value argument is evaluated with the same focus and iteration variables as the call itself, not with the call's input. In
name.select(use.union(given)),givenis evaluated on each name, as in the HL7 Java engine. Lambda arguments are evaluated per item (where,select) or once for the whole input (iif, below), as the function decides. - Code:
evaluateArgs()andbindLambda()inpackages/core/src/compiler/lambda.ts.
Frame variables after a dot
- Spec: the N1 grammar allows
$this,$indexand$totalas an invocation after a dot (name.$this) but gives that form no meaning. - Tests: none.
- Decision: the expression before the dot is evaluated, so its errors surface, and the result is the frame variable, as if it were written alone.
name.select(given.$index)is the index of each name. - Code:
compileFrameVariable()inpackages/core/src/compiler/compile.ts.
Navigation
Implemented in packages/core/src/runtime/navigation.ts (T0008 without a model, T0018 with one).
Root identifiers with a model
- Spec: N1 §10.1 and R5 §2.1.9.1: a path may start with the type of the root node, and
Patient.nameon an input that is not a Patient is empty. Neither says how an identifier that is both a type name and an element name is read. - Tests:
testSimpleWithContext,testSimpleBackTick1,testEscapedIdentifierUnicode;testSimpleWithWrongContextexpects a semantic error in strict mode (T0024). - Decision: with a model, a leading identifier names a type when the model has a resource, complex or backbone type of that name. The result is each focus item whose model type is that type or a subtype of it (
DomainResource.containedon a Patient), and empty for the other items. The data'sresourceTypeis never consulted, so an object the model does not know (resourceType: "Foo") matches no type name, andFoo.nameis an ordinary path. A primitive type name is always an element name, because FHIR's primitives share their spelling with elements (id,code,date,url); so is any name the model does not know. Without a model the model-less rule applies: the identifier matches the item's ownresourceTypeexactly. (T0018)
The input type at evaluation
- Spec: an expression is evaluated on a focus whose type comes from the model and the data (N1 §10.1, R5 §2.1.9.1.2). Neither says how a host declares the type of an input that does not name it, such as a data type evaluated on its own for an invariant. The HL7 suite's
contextTypeattribute declares the focus type for static checks only. - Tests: every suite test with a
contextTypeselects its focus with acontextexpression, so the focus is already a typed node and keeps its type; their results do not change.static-analysis.test.tsevaluates every suite test whose input is a resource again with theresourceTyperemoved and the type given asinputType, and compares the results. It also compares data types on their own with the same element inside a resource. Both suites agree excepttestConformsTo1andtestMultipleResolve(last point below).public-model-options.test.tsruns the rules with R4, R5 and R6. - Decision: by the owner's decision on #224 (2026-11-21), evaluation uses the
inputTypeoption, so that it agrees with analysis:- With one type name (a name given twice counts once), an input that does not name its type takes that type. That is an object without an own
resourceTypethatModelProvider.getRootType()does not recognize, when the type is a resource, complex or backbone type, and a JSON string, number or boolean, when it is a primitive type. Its FHIR primitives, choice elements and extensions are then navigated as in a resource, andis,asandofType()see the type. Each item of an array input is typed the same way. A value of the other shape, such as an object withinputType: 'string'or a string with'Period', stays untyped. - An input that names its own type keeps it. An own
resourceTypenames one even when the model does not know it, so{ resourceType: 'Foo' }stays untyped. If the data's type is neither aninputTypetype nor a subtype of one, as for an Observation withinputType: 'Patient', the two conflict. Analysis never sees the input, andevaluate()returns values only, so nothing reports the conflict; evaluation goes on with the data's type. A warning at evaluation is #232. Raisingeval/invalid-argumentinstead was the alternative the owner did not choose. - With several type names the input stays untyped, as before: nothing in the data says which type it has.
inputTypeneeds a model, so evaluation without one is unchanged. - Only the input is typed. A node or value class passed as the input (internal API) keeps its own type, and neither the variables nor the
resourceandrootResourceoptions are typed byinputType. - Where FHIR needs a resource, a resource is still recognized by its own
resourceType.%resourceand%rootResourcedefault to the input itself when it has none,resolve()finds the container of a contained resource and the Bundle around a reference by theirresourceType, and host hooks receive the JSON as it is. So on a resource whoseresourceTypeis removed,testMultipleResolveno longer finds the contained resources and the suite's fakeconformsTohook intestConformsTo1no longer knows the type (#233).
- With one type name (a name given twice counts once), an input that does not name its type takes that type. That is an object without an own
- Code:
toInputCollection()inpackages/core/src/runtime/navigation.ts,declaredInputType()inpackages/core/src/api/compile.ts.
Choice elements written with a type suffix
- Spec: R5 §2.1.9.1.1: a choice element is addressed by its name without
[x], andObservation.valueQuantityis not valid FHIRPath. ADR-0012 keeps the suffix form as an opt-in for compatibility. - Tests:
testPolymorphismA,testPolymorphicsA,testPolymorphicsCandtestPolymorphicsD(mode="lenient/polymorphics");testPolymorphismBandtestPolymorphicsBexpect a semantic error (T0024). - Decision:
Observation.valuegives the onevalue[x]that is present, typed by its JSON key (valueQuantityis aQuantity,valueStringastring), with its_value[x]extensions for a primitive. The suffix form is not an element: at runtime it is empty, like any element the type does not have, and static analysis will report it. Withlenient: { choiceSuffix: true },Observation.valueQuantitygives the value only when its type isQuantity, sovalueStringon the same observation is empty; the node is still namedvalue. Without a model the suffix form is an ordinary JSON key. (T0018)
Typed primitives that do not parse
- Spec: R5 §2.1.9.1.2 maps FHIR primitives to System types; it does not say what a value that is not valid for its type is.
- Tests: none in the suite;
node-value.test.ts. - Decision: a FHIR primitive whose JSON value is not valid for its type (a
datewritten asnot a dateor with a time, abooleanwritten as"true", a fraction where anintegeris declared) keeps the plain JSON mapping of its value (String,Decimal, …) instead of raising an error: FHIRPath navigates the data it is given and does not validate it. Its model type is unchanged, sois dateis still true. A FHIRQuantitywithout a UCUMsystemandcodestays a complex value. (T0018)
Children without a model
- Spec: N1 §5.8 lists the "immediate child nodes"; plain JSON has no element definitions.
- Tests: none in the suite;
navigation.test.ts. The functions themselves are T0017. - Decision: with a model, the children of a typed node are its elements in definition order, with the
_nameextensions folded into their primitives, and the children of a FHIR primitive are itsidandextension. Without a model, or for a node the model does not know, the children are the own JSON properties in document order, exceptresourceType, which names the type rather than holding data, and keys starting with_, which hold the extensions of a primitive and are not elements themselves. (T0018)
Order of descendants()
- Spec: N1 §5.8.2 calls
descendants()a shorthand forrepeat(children()), and N1 §3.1 leaves the order of both functions undefined.repeat()only adds items that are new by=. - Tests:
testRepeat3andtestRepeat4(counts),testDistinct2andtestDistinct3; none depends on the order or on duplicate values. - Decision:
descendants()lists the nodes in document order: each node comes right before its own descendants, depth first, as XPath's descendant axis does. With a model, the order of each node's children is the definition order of children without a model. Every node is listed once and equal values are kept, so twogivennames with the same text are both descendants; deduplicating by=would drop one. The HL7 Java engine and fhirpath.js do not deduplicate either, but list the nodes level by level. The walk follows the data rather than the model's types, so it ends on a recursive element such asQuestionnaire.item.item, and it keeps its own stack, so deep input cannot overflow the call stack. It does not detect cycles: JSON input is a tree, but a JavaScript object graph with a cycle, which only a host can pass, has no end, and the walk runs until memory runs out. The evaluation limits and the cancellation signal will bound it (#186). - Code:
descendantsFunctioninpackages/core/src/functions/tree.ts(T0017).
trace() names and projections
- Spec: N1 §5.9.1 adds the input, or its projection, to "the diagnostic log" and returns the input unchanged. Its example,
contained.where(criteria).trace('unmatched', id).empty(), traces theidof each item. It does not say how the log reaches the host, or what an empty or non-Stringnamedoes. - Tests:
testTrace1,testTrace2, andtrace()insidetestSkip3,testSplit3andtestPrecedence6. - Decision:
- The log is the
tracehook of the evaluation (T0021: host hooks); without one,trace()only returns its input. The hook gets the name, the traced values converted like the evaluation's results (output,decimalOutput), and the span of the call, in evaluation order, also for empty input. - The projection is evaluated for each input item, with that item as
$thisand its$index, asselect()does, and the results are traced as one collection, as the spec example needs. The HL7 Java engine evaluates it once instead, like its other arguments, with the$thiswhere the call is written rather than the input oftrace()(funcTrace()inFHIRPathEngine.java, hapifhir/org.hl7.fhir.core); the suite cannot tell the two apart, because it only counts the returned input. The projection is evaluated whether or not there is a hook, so adding a hook never changes a result or an error. nameis a String parameter with singleton evaluation: more than one item raiseseval/singleton-expected, a non-Stringeval/type-mismatch. An emptynametraces under the name'': empty propagation would make the result empty, andtrace()never changes its input.- The hook is a host boundary (ADR-0004):
evaluateAsync()waits for a promise it returns before going on, andevaluate()raiseseval/async-in-syncfor one, like every other hook of T0021 (#185).
- The log is the
- Code:
traceFunctioninpackages/core/src/functions/utility.ts, andtraceSink()inpackages/core/src/api/compile.ts(T0017).
Equality and ordering
Implemented in packages/core/src/runtime/ (equality.ts, comparison.ts, operands.ts; T0009).
Model-less date convenience
- Spec: none. This is a Callis extension. N1 §5.5 has no implicit String → date/time conversion, and N1 §6.1.1 and §6.2 need operands of the same type. Without a model, plain JSON has no date type, so
birthDate = @1974-12-25would always be false (T0003, #55). - Tests: no suite test covers model-less input. Direct tests in
operands.test.ts. - Decision: only when no model is supplied, a string from untyped input data is read as a date/time when the other operand of
=,!=,~,!~,<,<=,>or>=is one, in either operand order:- Eligible: an input node with no model type whose JSON value is a string. String literals and computed strings never are, and neither is any node when a model is supplied, even if the model does not know the node's type.
- Against a Date or DateTime, text without a
Tis parsed as a Date (parseDate()) and text with one as a DateTime (parseDateTime()); against a Time, as a Time (parseTime()). The usual temporal rules follow: partial precision, Date → DateTime, offsets and the evaluation's default offset. SobirthDate < @2000is true, and=between the input text1974-12and@1974-12-25is empty. - Text that does not parse stays a String:
=givesfalseand<raiseseval/type-mismatch, as for any String against a date. It never raiseseval/invalid-literal. Two input strings compare as strings. - The node is not changed and nothing is cached on it, so later String operations on it are unaffected.
Equivalent collections pair their items one to one
- Spec: N1 §6.1.2 says "each item must be equivalent" and that the comparison "is not order dependent", but not whether one item may match several. Equivalence is not transitive: decimals round to the less precise operand, so
1 ~ 1.2and1 ~ 1.4are true but1.2 ~ 1.4is false. - Tests:
testEquivalent20,testEquivalent21,testEquivalent23,testEquivalent24and theirtestNotEquivalentcounterparts. - Decision: two collections are equivalent when they have the same length and some ordering of one is pairwise equivalent to the other, so each item is used once.
(1 | 1 | 2) ~ (1 | 2 | 2)is false, and(1 | 1.2) ~ (1.2 | 1.4)is true even though pairing1with the first equivalent item (1.2) would leave1.2and1.4.
Complex values without a model
- Spec: N1 §6.1.1 and §6.1.2 compare complex types by "all child properties", recursively, but plain JSON has no type definition that lists them.
- Tests:
testEquality25–27,testEquivalent19–21(with the FHIR model; FHIR equivalence refines~for FHIR types). - Decision: the child properties are what model-less navigation sees: own properties only, arrays flattened, and
null, an empty array and a missing property all mean "no value". The order of the properties does not matter. Each child collection is compared with=(repeating items in order) or~(in any order), so child strings compare exactly or case-insensitively and child numbers by value. Two input strings are never read as dates. - With a model: two typed nodes of the same model type compare by their elements instead of their JSON keys, so a choice element compares by its one value, a FHIR
dateby the date rules, and_nameextensions and keys that are not elements are ignored. Typed nodes of different model types are not equal and not equivalent, as N1 requires operands of the same type: aPatientand aPractitionerwith the sameiddiffer, so|keeps both. A node the model does not know keeps the JSON rules, also against a typed node. FHIR Quantities without a UCUM code have their own rule, and~on FHIR types follows FHIR equivalence. (T0018)
Existence
Implemented in packages/core/src/functions/existence.ts (T0011, T0041). How exists() evaluates its criteria is under Operators.
all() stops at the first item that does not match
- Spec: N1 all and 3.0.0 return true "if all return true", but do not say whether the criteria of later items are evaluated once one is not true.
- Tests:
stops at the first item that does not match, without evaluating later itemsand the internal sync, promise, custom-thenable and cross-realm cases inpackages/core/src/functions/existence.test.ts; the pinnedtestAllgroup has no later-error case. - Decision:
all()mirrorsexists(). It evaluates the criteria in input order, with the canonical Boolean rule, and stops at the first item whose criterion does not match (false or empty), returning false. Later criteria are not evaluated, including errors they would have raised; a criterion reached before that still propagates its error. Empty input returns true without evaluating the criterion. - Code:
findItem()inpackages/core/src/functions/existence.ts.
allTrue() and the like take only Booleans
- Spec: N1 allTrue, anyTrue, allFalse and anyFalse "take a collection of Boolean values", as 3.0.0 does, but neither says what an item of another type does.
- Tests:
allTrue, anyTrue, allFalse and anyFalseinpackages/core/src/functions/existence.test.tsandexistence functions on typed nodesinpackages/core/test/generated-models.test.ts; the pinnedtestAllgroup projects Booleans only. - Decision: every input item must be a Boolean: a System Boolean or a FHIR
boolean. Any other item raiseseval/type-mismatch, wherever it is and whatever the other items are, sotrue.combine('a').anyTrue()is an error and the error never depends on which item decides the result. Items are not converted astoBoolean()would convert them, and the singleton rule that counts a single non-Boolean as true applies where one Boolean is expected, not to the items of a collection. A FHIRbooleanthat holds only extensions has no value and is left out, as singleton evaluation treats it as empty. - Code:
booleansOf()inpackages/core/src/functions/existence.ts.
distinct() and isDistinct()
- Spec: N1 distinct compares items with
=and says the order "is not guaranteed to be preserved"; isDistinct is "shorthand for"X.count() = X.distinct().count(). N1 does not say which of equal items remains, or what an undetermined comparison means. 3.0.0 distinct and isDistinct clarify the second: "Items are considered to be equal when the equals (=) operator returns true (i.e. false and empty both indicate that the items are distinct)". 3.0.0 also lets either of two equal quantities remain. - Tests: R5
testDistinct30–35expect the last of equal items, in input order:'a'.combine('b').combine('a').distinct()is'b', 'a'. R5testDistinct29andtestDistinct36expect empty fromisDistinct()anddistinct()for@2020.combine(@2020-01-01), where 3.0.0 givestrueand both dates; they are exceptions. The R4 copy has no such tests. Unit tests:distinct and isDistinctinpackages/core/src/functions/existence.test.ts, and thedistinct()cases ofexistence functions on typed nodesinpackages/core/test/generated-models.test.ts. - Decision (owner, 2026-11-10): follow 3.0.0 where the test suite disagrees with it (ADR-0001).
- Two items are equal only when
=is true; false and empty both mean they are distinct. So@2020.combine(@2020-01-01).distinct()is both dates andisDistinct()istrue. The same holds for quantities whose units cannot be related, and for complex values whose children cannot be compared, such as twoPeriods whose starts differ in precision. An element that holds only extensions, such as a FHIR primitive with only a data-absent-reason, has no value: it is never equal to another item, including another such element. - An undetermined pair never hides an equal one:
1.combine(1).combine(@2020).combine(@2020-01).isDistinct()isfalse.isDistinct()is never empty, anddistinct()is empty only for empty input. distinct()keeps the last of equal items, at its position, and returns the input items themselves, so object identity and model types survive. With no repeats it returns the input.- This is the rule of
|,intersect(),exclude(),subsetOf()andsupersetOf()(below) and ofrepeat(), for which an undetermined comparison is not equality either.
- Two items are equal only when
- Code:
laterRepeats()inpackages/core/src/functions/existence.ts; the exceptions intools/conformance/src/exceptions.ts.
Filtering and projection
Implemented in packages/core/src/functions/filtering.ts (T0012, T0042). How where() reads its criteria is under Operators; how ofType() resolves and matches types is under Types.
repeat()
- Spec: N1 repeat repeats the projection "as long as the projection yields new items (as determined by the
=operator)" and leaves the order undefined. 3.0.0 describes it as a queue: the input items first, then every projected item that is not in the output yet, where "false and empty both indicate that the values are not equal". It says that$indexis "undefined and not set" in the projection, that implementations "SHOULD include safety mechanisms to prevent infinite loops", and that they may end the evaluation with an error. - Tests:
testRepeat1,testRepeat2andtestRepeat5(counts and a constant projection);repeat through the public synchronous API,the repeat() limit,repeat() and the cancellation signaland the async cases inpackages/core/src/functions/filtering.test.ts;finds an element that holds only extensions once, in sync and async modeinpackages/core/test/generated-models.test.ts;isSameNodeinpackages/core/src/runtime/node-value.test.ts. - Decision:
- The order is 3.0.0's queue, so breadth first:
Questionnaire.repeat(item)lists the top-level items, then their items, and so on. The input items are in the result only when the projection gives them. - An item is new unless
=is true for an item of the result, or it is the same input node as one: the same object, or the same element of the input reached again (Patient.active.repeat(%resource.active)). Undetermined comparisons, such as@2020and@2020-01, are new, as for|, and equal items in different JSON objects are added once.=on an element that holds only extensions is empty, so without the node checkPatient.active.repeat($this)on such an element would add it again and again until the limit; with it, the element is found once. Two such elements are still two items, also when they share one JSON object. - The projection is evaluated for one item at a time, with the item as its focus and
$this.$indexis not set, so it stays that of the call, as foriif()(empty at the top level). - The cancellation signal of T0021 is checked before each item is projected, so an abort during a long walk raises
eval/aborted, also when every projection answers synchronously. - One
repeat()call produces at mostlimits.maxRepeatItemsitems, 5,000 by default; one more raiseseval/limit-exceeded. A projection that navigates data ends on its own, but one that makes new values, such as'x'.repeat($this & 'x'), never would. Each new item is compared with every item already found, so deduplicating thousands of complex items already takes seconds (#190); a higher default would let a runaway projection run longer without helping real data. The internallimitsevaluation option changes it; the public API exposes it with T0038.
- The order is 3.0.0's queue, so breadth first:
- Code:
repeatProjection()inpackages/core/src/functions/filtering.ts;isSameNode()inpackages/core/src/runtime/node-value.ts;DEFAULT_LIMITSinpackages/core/src/api/compile.ts.
Subsetting and combining
Implemented in packages/core/src/functions/subsetting.ts and combining.ts (T0013).
skip() and take() with an empty count
- Spec: N1 §5.3.6 gives the input back for a
numof zero or less, and §5.3.7 gives empty for anumof zero or less. Neither says what an emptynumdoes, or what anumthat is not an Integer does. - Tests:
testSkip7,testSkip8,testTake8andtestTake9("skip()with an empty count returns empty");testSkip5andtestSkip6for the counts of zero or less. - Decision: an empty
numgives empty, forskip()as well as fortake(), before the rule for counts of zero or less is considered, so(0 | 1 | 2).skip({})is empty and not the input.numgoes through singleton evaluation whether or not the input is empty, as the arguments of the string functions do: more than one item raiseseval/singleton-expected, and a single item that is not an Integer ('1',1.5,1.0,true) raiseseval/type-mismatch, because nothing converts to Integer implicitly. So an error never depends on the data. - Code:
skipFunctionandtakeFunctioninpackages/core/src/functions/subsetting.ts.
intersect() and exclude() with undetermined equality
- Spec: N1 §5.3.8 and §5.3.9 take "the elements that are in both collections" and "that are not in the other collection". N1 §6.1.1 lets
=be empty, for example for date/times of different precision, andunion()says it uses="to determine equality". None of them says what an empty comparison means for membership. - Tests:
testIntersect1–4andtestExclude1–4; none compares values whose equality is undetermined. - Decision: an item is in the other collection only when
=istruefor one of its items. An undetermined comparison does not establish equality, as in the|operator (T0010):@2020-01.intersect(@2020)is empty,@2020-01.exclude(@2020)keeps@2020-01, and@2020-01.union(@2020)has both items.intersect()andexclude()compare with the same kernel as|,inandcontains, so they inherit the model-less date convenience and the rule that typed nodes of different model types are never equal. - Code:
includesEqual()inpackages/core/src/functions/subsetting.ts.
The order and the items of intersect(), union() and combine()
- Spec: N1 §5.3.8 says the order of
intersect()is "not guaranteed to be preserved", and §5.4.1 and §5.4.2 say there is "no expectation of order" in the result ofunion()andcombine().intersect()andunion()eliminate duplicates, so the spec does not say which of two equal items remains. It callsa.union(b)"synonymous witha | b". - Tests:
testIntersect4,testUnion2,testUnion8andtestUnion13(counts only);testCombine2andtestCombine3expect the given names before the family names, the ordercombine()keeps. ThepreserveOrderargument ofcombine()is STU (T0027). - Decision: the results have an order that never varies:
intersect()lists each item once, in the order of the input; the item is the input's, not the equal one of the argument.union()is the|operator: the items of the input, then the new items of the argument, each at its first position. Of equal items the first remains, so a node of the input keeps its model type and its model-less date provenance.combine()lists the input, then the argument, keeping every duplicate. The signature takes the one argumentotheruntil T0027 adds the optionalpreserveOrder.exclude()keeps the order and the duplicates of the input, as the spec requires.
- Code:
intersectFunctioninpackages/core/src/functions/subsetting.ts;unionFunctionandcombineFunctioninpackages/core/src/functions/combining.ts.
Strings
String equivalence
- Spec: N1 string equivalence, clarified in 3.0.0
- Tests:
testEquivalent5–7,testNotEquivalent5–7 - Decision: Two strings are equivalent when they are equal after this normalization:
- Every character with the Unicode
White_Spaceproperty becomes a space, as 3.0.0 specifies. Runs of whitespace are not collapsed and the ends are not trimmed (3.0.0 says so explicitly), so'a b' ~ 'a b'is false. U+FEFF, which JavaScript's\smatches, is not whitespace. - Case is folded without locale rules by converting to upper case and then to lower case. This approximates Unicode full case folding:
'Straße' ~ 'STRASSE'and'σ' ~ 'ς'are true, and Turkish dotted and dotless i get no special treatment. The spec asks to ignore case "and locale" but names no algorithm. - No Unicode normalization (NFC/NFD) is applied, because the spec does not ask for it: a precomposed
éis not equivalent toefollowed by a combining accent.
- Every character with the Unicode
- Code:
normalizeStringForEquivalence()inpackages/core/src/values/string.ts(T0003).
String ordering is by code point
- Spec: N1 §6.2: "String ordering is strictly lexical and is based on the Unicode value of the individual characters."
- Tests: none in the suite.
- Decision: strings are ordered by Unicode code point. JavaScript's
<compares UTF-16 code units, which puts characters above U+FFFF (surrogate pairs) before U+E000–U+FFFF; Callis corrects for that, so'\uFFFF' < '\u{10000}'is true. No locale collation is used. - Code:
compareStrings()inpackages/core/src/values/string.ts(T0003).
Characters are Unicode scalar values
- Spec: N1 §5.6 does not say what a "character" is. 3.0.0 measures
indexOf(),substring(),length()andtoChars()in characters, "Unicode scalar values", and its examples count a surrogate pair as one ('a🔥b'.indexOf('b')is2) and a combining accent as one more ('é'.length()is2). - Tests: none in the suite.
testMatchesUnicodeCharactersis commented out in the XML. - Decision: follow 3.0.0 and count code points, not UTF-16 code units.
indexOf(),substring(),length()andtoChars()convert between characters and JavaScript's code units, andtoChars()never splits a surrogate pair. Grapheme clusters are not used, as 3.0.0 says. - Strings that are not well-formed: an expression cannot write a lone surrogate (the lexer rejects it), but input data can hold one. Each lone surrogate counts as one character, and a search never matches half of a surrogate pair:
'🔥'.startsWith('\uD83D')is false, and'🔥'.replace('\uD83D', 'x')is'🔥'. This applies toindexOf(),startsWith(),endsWith(),contains()andreplace(). - Case:
upper()andlower()use JavaScript'stoUpperCase()andtoLowerCase(), the Unicode default case mapping with no locale, so'ß'.upper()is'SS'(as in string equivalence). - Code:
packages/core/src/functions/characters.ts(T0015).
Regular expressions use JavaScript's dialect
- Spec: N1 §5.6.9–10 ask for expressions that are case-sensitive, in "single line" mode, with Unicode characters, and do not prescribe a dialect; they only recommend the PCRE flavor.
- Tests:
testMatchesCaseSensitive1–2,testMatchesSingleLineMode1,testMatchesWithinUrl1–4,testReplaceMatches1–7. - Decision:
matches()andreplaceMatches()useRegExpwith theuandsflags. Theuflag reads the text as characters and allows\p{…}. Thesflag is "single line" mode, astestMatchesSingleLineMode1shows:.also matches a line terminator.^and$match only at the ends of the string, somatches()finds the expression anywhere in the input and'^…$'matches all of it (testMatchesWithinUrl2–3). Lines are not special; themflag is a 3.0.0 addition (T0029). A pattern is compiled on every call, so no state is kept between evaluations. - Differences from PCRE that a user can run into:
\d,\w,\sand\bfollow JavaScript (\dand\ware ASCII only,\sis Unicode); theuflag allows an escape only for a syntax character, so-outside a character class and_are errors; there are no inline flags ((?i)), possessive quantifiers, atomic groups,\A,\Zor(?P<name>…)(a named group is(?<name>…)). - Error code: a pattern that is not valid raises
eval/invalid-argument. There is no new error code: the argument is the problem. - Not covered: a pattern can take exponential time on some input (catastrophic backtracking), as in every backtracking engine. The architecture documents this, and the
regexhook of T0021 lets a host plug in a safe engine: every pattern is compiled bycompileRegex(), which calls the hook with the pattern and the flagssuwhen there is one, and the dialect is then the host's. - Errors: the message says why a pattern is not valid but does not repeat the pattern, because a pattern can be computed from input data and errors never include input data (architecture).
- Code:
packages/core/src/functions/regex.ts(T0015).
The substitution of replaceMatches()
- Spec: N1 §5.6.10: "The substitution may refer to identified match groups in the regular expression", with the example
'${day}-${month}-${year}'for named groups. It does not say how a reference is written beyond the example. (The N1 example callsreplace(…); it meansreplaceMatches(…).) - Tests: none in the suite uses a group.
- Decision: the substitution is expanded by Callis, so it does not depend on
String.prototype.replace. It accepts the spec's${name}and${n}(${0}is the whole match) and JavaScript's replacement patterns:$1–$99,$<name>,$&,$`,$'and$$. A group that took no part in the match is the empty string. As in JavaScript,$nwithout a groupnis plain text, so'costs $5'is safe; use$$for a dollar sign before{or a digit. A${…}reference to a group the pattern does not have raiseseval/invalid-argument, like Java does; it is raised when a match is replaced, so a text with no match never raises it. Supporting both forms now means no expression changes meaning when one of them is added later. - Code:
expandSubstitution()inpackages/core/src/functions/regex.ts(T0015).
An empty pattern in replace() and replaceMatches()
- Spec: N1 §5.6.8 says an empty
patternsurrounds every character with the substitution ('abc'.replace('', 'x')is'xaxbxcx').replaceMatches()says nothing about an emptyregex. - Tests:
testReplace2('abc'.replace('', 'x')is'xaxbxcx') andtestReplaceMatches2('abc'.replaceMatches('', 'x')is'abc'). - Decision: follow both tests.
replace()treats the pattern as text, so the empty string occurs before every character and at the end;''.replace('', 'x')is'x'.replaceMatches()returns the input unchanged for an emptyregex, although the regular expression''matches everywhere. Any other expression that can match nothing, such asx*, replaces its empty matches as the engine finds them:'abc'.replaceMatches('x*', '-')is'-a-b-c-', and with theuflag a match never falls inside a surrogate pair.
substring() and the checks on string functions
- Spec: N1 §5.6.2 says "If
startlies outside the length of the string, the function returns empty"; 3.0.0 adds "outside, or equal to", and that alengthof zero or less gives''. N1 §5.6 says the functions "operate on collections with a single item" and signal an error for more than one item "or an item that is not a String". The specs do not say whether an invalid argument is an error when the input is empty. - Tests:
testSubstring4–5,testSubstring9,testSubstring13–18,testStartsWithNonString1,testEndsWithNonString1,testContainsNonString1. - Decision:
- A
startat the end of the string is outside it:'abc'.substring(3)and''.substring(0)are empty (3.0.0).startis checked beforelength:'abc'.substring(-1, -1)and'abc'.substring(3, 0)are empty, while'abc'.substring(2, 0)is''. - The input and every argument go through singleton evaluation whether or not another one is empty.
{}.startsWith(1)raiseseval/type-mismatchand'a'.substring(0 | 1)raiseseval/singleton-expected, so an error does not depend on the data. Only after that is an empty input or argument an empty result. A String argument is a String only:'abc'.substring('1')and'abc'.substring(1.5)are errors, since nothing converts to Integer implicitly. - The
NonStringtests (Appointment.identifier.startsWith('rand')) areinvalid="semantic". The error is found during evaluation, so the runner reports them as "detected late" (Semantic errors found during evaluation) until T0024. - An argument is evaluated with the focus of the call (Function arguments), which is why
testSubstring10aandtestStartsWith12aare errors:length()there is the length of the root resource.
- A
Date, DateTime and Time
Implemented in packages/core/src/values/datetime/ (T0005).
A value without a timezone offset is UTC
- Spec: N1 Date/Time equality leaves the default offset for values without one to the implementation.
- Tests:
testEquality23(@2012-04-15T15:00:00Z = @2012-04-15T10:00:00) andtestNEquality17(the same with!=) expect empty. The suite notes that the result "could be impacted by the timezone of the engine running the test". - Decision: The owner chose UTC as the default (ADR-0012). The value without an offset is read as 10:00Z, so the results are
falseandtrue, and these two tests fail. No fixed default offset gives empty; that would need a policy where a missing offset is unknown (anywhere within ±14:00). The owner kept UTC (#50), so both tests are conformance exceptions in the R4 and R5 reports (tools/conformance/src/exceptions.ts).
Partial values across timezone offsets
- Spec: N1 §6.2 compares "the values at each precision … respecting timezone offsets". It does not say how to normalize a value that is coarser than its offset (an hour-precision value at
+05:30), or a Date compared with a DateTime that has an offset. - Tests: none in the suite.
- Decision: Each value stands for the span of time its precision covers, in UTC:
@2018-03is all of March, at the default offset. Spans that do not overlap are ordered, identical spans are equal, and anything else is empty. Seconds and milliseconds count as one precision, so a value with seconds is a single millisecond. For values that line up with their own precision, this is exactly the component-by-component rule. It also settles the edge cases:@2015-02-04T10+05:30 = @2015-02-04T04:30Zis empty, and@2012-04-15 = @2012-04-15T01:00+10:00isfalseat UTC (that instant is on 14 April in UTC) but empty at a default offset of+10:00.
Fractional seconds in equivalence
- Spec: N1 Date/Time equivalence compares seconds and milliseconds "with decimal equivalence semantics", which would round to the less precise operand. Its own example says
@2012-01-01T10:30:31.1 ~ @2012-01-01T10:30:31isfalse. - Tests:
testEquivalent18,testNotEquivalent18. - Decision: Follow the example and the tests: seconds are compared exactly, as for equality.
@T10:30:31 ~ @T10:30:31.0is stilltrue, because seconds and milliseconds count as one precision.
A time on a partial date
- Spec: The grammar defines
DATETIMEas'@' DATEFORMAT 'T' (TIMEFORMAT TIMEZONEOFFSETFORMAT?)?, which also matches@2015T10:00and@2015-02T10. - Tests: none.
- Decision: Such a literal is not a date and time (ISO 8601 needs a full date before a time), so it is an invalid literal value, like
@2015-02-30: the parser returns nothing and the compiler raiseseval/invalid-literalat evaluation (T0008). The string forms fortoDateTime()and FHIRdateTimereject it too.
Leap seconds
- Spec: FHIR's
dateTime,instantandtimepatterns allow the second60. FHIRPath's own ranges stop at:59(N1 §4.1.6, §4.1.7). - Tests: none.
- Decision: leap seconds are not supported (ADR-0006). A value with the second
60, such as2015-12-31T23:59:60Z, does not parse, sotoDateTime()gives empty for it, and arithmetic and comparison never meet one.
Quoted calendar keywords in arithmetic
- Spec: 3.0.0 Date/Time Arithmetic lists the calendar keywords unquoted and the UCUM units quoted.
- Tests:
testMinus5(@1974-12-25 - 1 'month'is@1974-11-25), labelled "Contested". - Decision: Follow the suite: a quoted calendar keyword (
'month','days') works like the keyword. Of the time units, only'a'and'mo'raise an error.
Fractions in date/time arithmetic
- Spec: 3.0.0 Date/Time Arithmetic applies the fraction of a quantity "only … for second or millisecond precisions". For partial values it converts the quantity to the value's precision, "truncating any decimal fraction".
- Tests:
testPlusDate2andtestPlusDate4(7.7 daysadds 7 days),testPlusDate19(0.1 's'adds 100 ms). - Decision:
- The precision in the first rule is the quantity's unit. Above seconds the fraction is dropped before anything else, so
@T10:00 + 1.5 hoursis@T11:00, not@T11:30. - Seconds keep their fraction down to milliseconds, and anything finer is dropped (
1.5 'ms'adds 1 ms). - The result is then converted to the value's precision and truncated toward zero. A value with second precision ignores a fraction of a second (
@T10:00:00 + 0.5 secondsis@T10:00:00), and@2014 - 23 monthsis@2013. - Weeks follow the first rule too: the fraction is dropped before the weeks become days, so
1.5 weeksadds 7 days, not 10. Reading "multiply by 7, then calculate in days" as 10.5 days, truncated to 10, is also defensible; Callis treats weeks like every other unit above seconds.
- The precision in the first rule is the quantity's unit. Above seconds the fraction is dropped before anything else, so
- R4 suite: the R4 copy of the suite (
tests-fhir-r4.xml) still expectstestPlusDate19to ignore the fraction (@1973-12-25T00:00:00.000+10:00 + 0.1 's'unchanged). Callis follows the R5 copy, which is the source of truth and matches 3.0.0, so the R4testPlusDate19is a conformance exception (tools/conformance/src/exceptions.ts, #51). The R5 test runs as usual. - Warning: 3.0.0 also says "Implementers SHOULD produce a warning when decimal fractions are ignored". The owner decided on 2026-11-11 that Callis warns statically, for fractions written in the expression, and not at runtime for now (#52). T0024 added the warning:
isFractionIgnored(amount, unit, precision)invalues/datetime/arithmetic.tstells when the rules above drop part of the amount. It only computes, so the arithmetic kernels stay pure, and a static and a runtime check can share it.- The static warning is the
Diagnosticsemantic/fraction-ignored, severitywarning, fromanalyze()and attached to aFhirPathSemanticErrorthatcompile()throws for another reason, for+and-whose right operand is a quantity literal (possibly behind-) and whose left operand the analyzer knows to be a Date, DateTime or Time: a literal, a function such astoday(), or an element with a model (birthDate + 7.7 dayswithinputType: 'Patient'). A literal on the left gives its precision, so@2014 + 23 monthswarns; otherwiseisFractionIgnored()checks only the quantity, which is all that analysis knows. A choice element that may be a Period gives no warning, and neither does a quantity from the data or a computed one. - A computed quantity gets no runtime warning for now. That would need a host hook in
EvaluationHooks(T0021), which has onlytracetoday, and a code, both public API.isFractionIgnored()stays internal for such a later hook, which would call it where the operator is evaluated (runtime/arithmetic.ts), which has the value and the quantity. - A warning never changes the result, in strict mode too: the fraction is ignored as described above.
- A unit the kernel rejects (
@2020 + 1 'mg','a','mo'), or one the value cannot take (@2020-01-01 + 1 hour), is reported like any other operator type mismatch (below): a warning, and an error in strict mode.
String forms accepted by toDateTime() and toTime()
- Spec: N1 §5.5 gives the formats
YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mmandhh:mm:ss.fff(+|-)hh:mm, and accepts partial values. - Tests:
testLiteralYearToDateTime…testLiteralTZToDateTime. - Decision: Partial values are accepted to the same precisions as literals, including the hour alone (
'2015-02-04T14','14'). A timezone on a time string is rejected, because Time values have none (N1 §4.1.6); the offset in thetoTime()format is read as a slip in the text. Fractional seconds beyond milliseconds are truncated, as for FHIRinstantvalues.
Writing a zero offset
- Spec: N1 toString() shows offsets as
(+|-)hh:mm, and N1 §4.1.7 allowsZas a synonym for+00:00. - Decision:
toString()writes a zero offset asZ, whether the input hadZ,+00:00or-00:00. Both forms are valid FHIR.
Conformance suite
How the conformance runner (T0022, tools/conformance) reads the attributes of the HL7 test suite. The test schema is vendored as tools/conformance/fixtures/r5/testSchema.xsd.
Semantic errors found during evaluation
- Spec: N1 §11 lets an implementation check types at compile time or at run time.
- Tests: every
invalid="semantic"test, for exampletestDollarOrderNotAllowed,isEffectOnLogic3Baseand theisSemanticChecksgroup. - Decision: a
FhirPathSemanticErrorpasses. AFhirPathEvaluationErroralso passes, and the report counts it as "detected late", so the gap to static analysis (T0024) stays visible.
ordered and checkOrderedFunctions
- Spec: N1 §3.1 says the order of
children()anddescendants()is undefined, and that implementations may report an error for an order-dependent operation on such a collection.testSchema.xsddocumentsorderedas "check order of results". - Tests:
testDollarOrderNotAllowedexpects a semantic error forPatient.children().skip(1). R4 marks itcheckOrderedFunctions="true"and R5ordered="true"; both copies aremode="strict". - Decision:
orderedonly controls how outputs are compared: in order, or as a multiset whenordered="false".checkOrderedFunctionsis not passed to the engine. The test is in strict mode, sostrictis the signal, as in the HL7 Java runner, which ignores the attribute. Strict mode reports an order-dependent operation on a collection whose order is undefined (T0024, #72): the result ofchildren()anddescendants(), and everything derived from it item by item (where(),select(),distinct(),ofType(),trace(),tail(),skip(),take(),extension(),resolve(), a union with it), is unordered, andfirst(),last(),tail(),skip(),take()and the indexer on it aresemantic/unordered-collectionerrors. A result thatcount(),single(),exists()or a selection of one item gives is ordered again. Withoutstrictnothing is reported, and evaluation lists the children in the model's definition order as before (children without a model).
Static analysis of every test
- Spec: N1 §11 leaves compile-time checking to the implementation; the suite's
invalid="semantic"tests and itscontextTypeattribute assume a check against the type of the focus. - Tests:
testSimpleFail,testSimpleWithWrongContext,testPolymorphismB,testPolymorphismAsB,testPolymorphicsB,testIif6,testDollarOrderNotAllowed, theisSemanticChecksgroup; every other test too, which analysis must not reject. - Decision: the engine adapter analyzes every expression as the HL7 Java runner checks every test (
FHIRPathTests.java): with the test'scontextTypeas the input type when it has one, otherwise with the model type of the node thatcontextselects, otherwise with the resource type of the input.mode="strict"sets thestrictoption; the Java runner does not read it, but Callis gates the N1 §11 checks on it, as T0024 says. The context expression itself is compiled without an input type.skipStaticCheck="true"is parsed but not honoured yet (#217); its only test is STU. - Code:
expressionOptionsFor()intools/conformance/src/engine-adapter.ts.
predicate="true"
- Spec: the schema only says the test "represents a predicate".
- Tests:
testPatientHasBirthDate(andtestExtractBirthDate, which ispredicate="false"). - Decision: the result is converted to a Boolean before it is compared, as the HL7 Java test runner does: a single Boolean stays as it is; otherwise the result is
truewhen it is not empty.
Comparing expected outputs
- Spec:
testSchema.xsdlists the output typesboolean,integer,decimal,string,date,dateTime,time,code,idandQuantity, but not how values compare. The reference is the HL7 Java test runner (FHIRPathTests.javain hapifhir/org.hl7.fhir.core). - Tests: all tests with outputs.
- Decision: follow the Java runner, except where noted.
- The result item's type must be the output type. System types count as the output type of the same name (
System.Decimalasdecimal), FHIR types as their own name (FHIR.codeascode), as Java comparesfhirType(). So an expectedstringdoes not accept acode, and FHIR types the schema does not list (uri,instant,Age) never match a typed output. - Decimals compare by value and by number of decimal places, because precision is visible in FHIRPath and Callis keeps it (ADR-0005; N1 §4.1.4 asks for fixed-precision decimals).
1.50does not match1.5. Java compares the text; Callis also treats-0.0as0.0,+1as1and01as1. - Dates, date/times and times compare as text without the
@andTliteral prefixes, so a different precision or a different way of writing the offset is a different value. - Quantities compare by value (as decimals) and by unit.
- An output with empty text checks only the type, as in Java.
- Outputs without a type (the R4 boundary tests) hold a FHIRPath literal, as the schema says; Java compares only their text. Callis compares by the kind of literal (Boolean, number, string, date/time or quantity) and accepts any result type of that kind: the R4 file writes
@2014-01for a month-precision DateTime, which as a literal would be a Date. - With
ordered="false", each output must pair with a different result item. Java only checks that each result item matches some output.
- The result item's type must be the output type. System types count as the output type of the same name (
Tests that use STU features inside phase-1 groups
- Spec: ADR-0001 puts STU features in phase 2.
- Tests:
testPeriodInvariantNew(groupperiod) useslowBoundary()andhighBoundary(); thetype()tests intestTypeand thematchesFull()tests intestMatchesare STU too. - Decision: tests are classified one by one: a test that calls an STU function is STU, even in a group whose other tests are phase 1. The reports show the task that implements it.
Modes
- Spec: the
modevalues intestSchema.xsd. - Tests: the tests and groups with a
mode. - Decision:
strict,lenient/polymorphics,element,htmland thesemanticgroup mode ofisSemanticChecks(not in the schema) are phase 1.tx(%terminologies) is STU (T0032).cdaandcustomare out of scope and skipped, as are the wholecdaTestsanddocumentFunctionsgroups, including their tests that have their ownmode="element".
Features that later tasks add
- Spec: none; this is how the runner reports an engine that is still being built (ADR-0011).
- Tests: every test that calls a spec function or uses a FHIR variable that the engine does not have yet. For example
testDollarOrderNotAllowed(children(),skip()) andtestSubSetOf3(where(),subsetOf()). - Decision: such a test fails as "not implemented", whatever it expects. Without this rule a test that expects a semantic or execution error would pass because the function is unknown, and would fail again once the feature exists. The engine adapter checks the parsed expression for functions of the spec that later tasks own and the registry does not have yet. It also classifies
eval/undefined-variablefor a FHIR variable that T0032 defines as not implemented. These checks retire themselves as the features arrive. The functions that only answer through a host hook (memberOf,subsumes,subsumedBy,conformsTo,htmlChecks) are registered since T0020, and since T0021 the adapter passes the fakeconformsToandhtmlCheckshooks oftools/conformance/src/fake-hooks.ts, so a test that calls one is measured like any other; no suite test callsmemberOf(),subsumes()orsubsumedBy(), which stay empty without a terminology provider. T0010 removes the temporary operator codeeval/not-implemented, its compiler stub and its classifier branch (#104). A genuinely unknown function or variable, which no task adds, is still a semantic or execution error. - Code:
checkImplemented()andclassifyError()intools/conformance/src/engine-adapter.ts.
Converting the XML inputs
- Spec: FHIR XML and FHIR JSON (R5 JSON) define the two formats, and XML 1.0 how XML is read. They do not say how the narrative XHTML is written as a JSON string.
- Tests: every test with an XML input. The ten inputs that copy an official FHIR example are compared with its official JSON (
tools/conformance/src/official-examples.ts). - Decision (T0023,
tools/conformance):- The narrative
divis copied from the XML as written, with its whitespace and references ('stays'). The official JSON examples write the XHTML anew, which changes whitespace and references but not the XHTML.htmlTest01, the one test that reads a narrative, usespatient-example.xml, whose narrative is the same either way. - Attribute values are read as XML 1.0 §3.3.3 requires: a line break written inside a
valueattribute is a space, and the indentation after it is kept (descriptionincodesystem-example.xml). decimalandintegervalues keep their XML text as JSON numbers (1.50,9.5e2,1.5E2), because FHIRPath can see the precision. A value that is not also a JSON number (a leading+) is refused rather than rewritten; none of the inputs has one.- R5
integer64is a JSON string, as R5 JSON requires. XML comments are dropped; FHIR JSON has none. ccda.xmlis a CDA document, not FHIR, and is not converted. Only the out-of-scopecdaTestsgroup uses it.
- The narrative
Duplicate test names
- Tests: the R4 file has two tests named
testEquivalent23(R5 renamed the second totestEquivalent24). - Decision: test IDs are the names, made unique with a
#2,#3, … suffix in document order. The second R4 test istestEquivalent23#2in reports and in the baseline.
FHIR functions
Implemented in packages/core/src/fhir/ (T0020). R4, R5 and the R6 draft define these functions and variables the same way, so there is no version-specific code.
%resource and %rootResource
- Spec: R5 §2.1.9.1.4:
%resourceis "the resource that contains the original node that is in%context", and%rootResource"the container resource for the resource identified by%resource"; §2.1.9.1.7 adds "Do not go past a root resource into a bundle". The same in R4 and the R6 draft §2.1.9.2. Neither says what they are when%contextis part of no resource. - Tests:
isGuardAndOtherImplies,isGuardOtherAndImpliesandisGuardOrInnerImplies(%resourcewith acontext),testMultipleResolve,htmlTest02–04; thetestDollarResourcegroup is commented out in both suites. Direct tests infhir/variables.test.tsandtest/generated-models.test.ts. - Decision: both follow the parent chain of the input nodes, so an input node selected by an earlier evaluation, as the conformance runner's
contextdoes, still belongs to its resource:%resourceis, for each item of%context, the nearest node, the item itself or an ancestor, whose JSON has aresourceType. An item that is part of no resource, such as a data type passed on its own, is used as it is, so%resourceis never undefined. A resource reached from several items is listed once.%rootResourceis, for each item of%resource, the resource that contains it throughcontained, and otherwise the item itself. A resource in aBundleentry is not contained, so the walk never enters the Bundle. FHIR forbids contained resources inside contained resources; should the data nest them anyway, it is the outermost container.- The evaluation options
resourceandrootResourceoverride them, as the T0038 sketch has it. A value is converted like a variable value, typed by the model;nulland[]make the variable empty. Without its own value,%rootResourceis derived from%resource, the default one or the host's. - A host variable of the same name hides them, and
%sct,%loinc,%`vs-[name]`and%`ext-[name]`too, so a host that defined%resourceas a variable before T0020 keeps its value; only%contextand%ucumcannot be redefined. Such a variable is only a value:%rootResourceis still derived from theresourceoption or the input. Avs-orext-without a name is not defined (eval/undefined-variable).
- Code:
createFhirEnvironment()inpackages/core/src/fhir/variables.ts.
hasValue() is always a Boolean
- Spec: R5 §2.1.9.1.5 and R4: true "if the input collection contains a single value which is a FHIR primitive, and it has a primitive value … Otherwise, the return value is empty." The R6 draft §2.1.9.3.2 gives false for a single primitive without a value and keeps empty for anything that is not a single FHIR primitive.
- Tests:
testHasCodingValue1–3(R4 and R5):name.first().hasValue(), aHumanName, expects false.testNoValueHasValueandtestPrimitiveExtensions(R5) expect false for a primitive with only extensions. - Decision: follow the suites (ADR-0001, ADR-0011), as the HL7 Java engine does (
funcHasValue()inFHIRPathEngine.javagives false for anything but one item with a primitive value):hasValue()is true for a single item whose System value is a Boolean, String, Integer, Long, Decimal, Date, DateTime or Time, and false for anything else: a primitive with only extensions, a complex value, a Quantity, empty input or several items. Without a model, a JSON primitive counts as a primitive, and so does a System value such as a literal.getValue()gives that value wherehasValue()is true and is empty otherwise, as all three versions say. No suite exceptions. - Code:
hasValueFunctionandgetValueFunctioninpackages/core/src/fhir/functions.ts.
Local references in resolve()
- Spec: R5 §2.1.9.1.5 resolves a string or a
Reference"if it is a string that is a uri (or canonical or url)", and ignores what does not resolve; the R6 draft leaves the protocols to the engine. How references point into a Bundle is in Bundle references: a URN or an absolute reference matches an entry'sfullUrl, a version is split off and matched againstmeta.versionId, and a relativeType/idis made absolute with the RESTful base of thefullUrlof the entry it is in; without such a base, and in Bundles withoutfullUrls, "resolution expectations are undefined". Contained references are in References. - Tests:
testMultipleResolve(R5); direct tests infhir/resolve.test.ts, including inputs with several resources or Bundles, and a Bundle with the sameType/idon two servers, andtest/generated-models.test.ts. - Decision: without a host hook (T0021),
resolve()finds what is in the data:- A String or a FHIR primitive is the reference; a
Referencegives itsreference, and without a model any object with a stringreferencedoes. With a model, a typed value of another type is not a reference. #idis the contained resource with thatidof the reference's own root resource: the container of the resource the reference is part of (%rootResourcefor that resource), so a reference in a Bundle entry finds the contained resources of that entry, and each resource of an input with several resources finds its own.%rootResourceis used instead for an item that is part of no resource, such as a String literal, where the first of its resources that has the id wins, and for an item in%resourcewhen the host's%rootResourcedoes not hold its container, so therootResourceoption applies to a contained resource evaluated on its own.#alone is that root resource, as FHIR allows a contained resource to refer to its container.- Any other reference is looked up in the nearest
Bundlearound the item, or, for an item that is part of no resource, around each resource of%rootResourcein turn, following the Bundle rules: a URN or an absolute reference matches the first entry with thatfullUrl, and a relativeType/idis made absolute with the RESTful base of thefullUrlof the entry the item is in, even when another server's entry has the same type and id; a target missing on that server does not resolve. A version,/_history/[version], is removed before matching and must equal the resource'smeta.versionId. Where the spec leaves a relative reference undefined, because its entry has no RESTfulfullUrl(aurn:uuid:one, or none) or the item is in no entry, Callis matches the first entry whose resource has that type and id, as the suites' Bundles and many documents expect. - The result is the node that navigation gives for the resource, typed the same way and with the same parent chain:
'#x'.resolve()andcontained.where(id = 'x')are the same node. A contained resource of a type the model does not know is typed as the declaredResource(T0018), so an R6-onlyDeviceAlertis aDeviceAlertunder R6 and aResourceunder R4 and R5. - A reference that is not in the data goes to the host's
resolvehook (T0021), with the JSON of the resource around the reference in its context; a#idreference never does, because a contained resource is in the data or nowhere. What the hook returns is converted like the input and typed by the model as a root node, so aDeviceAlertfrom the hook is aDeviceAlertunder R6 and untyped data under R4 and R5;undefinedandnullresolve nothing. In async mode the hook calls for the items of one collection run at the same time, at mostconcurrencyof them, and the results keep the input order.
- A String or a FHIR primitive is the reference; a
- Code:
resolveFunctionandresolveItem()inpackages/core/src/fhir/resolve.ts.
FHIR equivalence
- Spec: R5 §2.1.9.1.6, the same in R4 and the R6 draft §2.1.9.5.1: for complex types
~requires "all child properties to be equal, except for "id" elements"; aCodingis compared oncodeandsystemonly; twoCodeableConcepts are equivalent when "any Coding in one is equivalent to any Coding in the other". - Tests: none in the suites (the HL7 Java engine has no such rule either); direct tests in
fhir/equivalence.test.tsandtest/generated-models.test.ts. - Decision: for two nodes of the same FHIR model type,
~compares the elements with~, so the children of a complex value compare by equivalence, as N1 §6.1.2 does, and nested values follow the same rules:- Every element named
idis ignored,Resource.idincluded. - A
Codingcomparessystemandcodewith~, so case and whitespace in a code are ignored like in any other string;version,display,userSelectedand the other elements are ignored. Two codings with neither are equivalent. - A
CodeableConceptis equivalent to another when a coding of one is equivalent to a coding of the other. One without codings is equivalent to none, whatever itstext, not even to itself: the rules apply before the kernels' shortcut for two nodes holding the same JSON object, socode ~ codeon a text-only concept is false, as it is for two copies, and so is~between two nodes of one resource that holds such a concept. =is unchanged and compares every element. Untyped data and other models keep the default rule.
- Every element named
- Code:
fhirEquivalenceinpackages/core/src/fhir/equivalence.ts, through themodelEquivalenceextension point ofruntime/equality.ts(T0009).
htmlChecks() on strings
- Spec: the R4 and R5 texts define
htmlChecks()on an xhtml element only, with no value for any other kind of element (R4, R5 §2.1.9.1.5). The R6 draft adds strings: a string is parsed as the content of adiv, and the result is false when it does not parse or breaks the HTML rules (6.0.0-snapshot1 §2.1.9.3.12, FHIR-56303). - Tests: R5
HTMLChecksatcb4eac4:htmlTest02(valueStringwith valid HTML, expects true) andhtmlTest03(valueStringwith abutton, expects false), both onparameters-example-html.json;htmlTest04(valueInteger) expects empty. R4 has noHTMLChecksgroup. - Decision (owner, 2026-11-08): follow the suite and the R6 draft for every provider (R4, R5 and R6). A string is forwarded to the
htmlCheckshook like xhtml; any other input gives empty, and without a hook the result is empty. No suite exceptions are registered: ADR-0001 and ADR-0011 make the suite the arbiter where it clarifies the rules. The hook learns which kind it received fromcontext.kind:xhtmlfor a node the model types asxhtml, which is thedivitself, andstringfor any other string, which is the content of adiv; without a modeltext.divis a string too (T0021).htmlTest01does not parse, becausedivis reserved (below), andhtmlTest04needsempty()(T0041). - Code:
htmlChecksFunctioninpackages/core/src/fhir/functions.tsandhtmlOf()inpackages/core/src/fhir/hooks.ts; the runner's fake checker ischeckHtml()intools/conformance/src/fake-hooks.ts.
Hook-backed functions: errors and empty results
- Spec: the R4 text raises an error where
memberOf()gets a value set that "cannot be resolved as a uri to a value set", whereconformsTo()gets a structure that "cannot be resolved to a valid profile" or an input of more than one element, and wheresubsumes()andsubsumedBy()compare codings of different code systems whose relationship is not well-defined (R4 functions). The R5 and R6 texts give empty in every one of these cases, and for an input or argument that is not a single item (R5 §2.1.9.1.5, R6 draft §2.1.9.3); R5 still says "a run-time error is thrown" forsubsumedBy()across systems, wheresubsumes()says empty, which reads as a leftover. - Tests:
testConformsTo3(R4 and R5):conformsTo('http://trash')expects an execution error, against the R5 text. Direct tests infhir/functions.test.tsandtools/conformance/src/fake-hooks.test.ts. - Decision: the engine follows the R5 shape for what it decides itself: one input item, one argument, a coded value, a non-empty URL, and otherwise empty without a hook call. Whether a value set, profile or relationship can be resolved is the host's knowledge, so the hook decides between the two texts (T0021, #64):
undefined(ornull) means it cannot tell and gives empty, as R5 says; an error it throws, or a rejection, ends the evaluation unchanged, which gives the R4 error, with a stable code when the host throws aFhirPathEvaluationError. The conformance runner's fakeconformsTohook throwseval/invalid-argumentfor a profile that is not a base profile of a resource type of the suite's model, sotestConformsTo3passes with no suite exception. Two codings with the same system and code are equivalent without asking the provider, and for twoCodeableConcepts the pairs of codings are asked in order until one matches; false when every pair is known not to match, empty when none matched and one was unknown. - Code:
memberOfFunction,subsumesFunction,subsumedByFunctionandconformsToFunctioninpackages/core/src/fhir/functions.ts, withcodedValueOf()andcodingsOf()inpackages/core/src/fhir/hooks.ts; the guard and the answer checks arebindHooks()inpackages/core/src/runtime/hooks.ts.
Parser
Reserved div in an HTML fixture
- Spec: N1 identifiers, N1 grammar (
identifierandmultiplicativeExpression), and 3.0.0 grammar.divis reserved; N1 permits onlyas,contains,inandisas keyword-identifiers. The 3.0.0 rule additionally permitsasc,descandsort, but does not adddiv. - Test: R5
htmlTest01:text.div.htmlChecks()(groupHTMLChecks). - Decision: this one expression is an explicit parse-only suite/grammar mismatch. It raises
FhirPathSyntaxError;text.div.htmlChecks()parses. The acceptance test asserts both outcomes and does not count the original expression as a passing parse. No compatibility extension, fixture edit or conformance-baseline change is made.
Function arity is not a grammar error
- Spec: N1 function invocations and grammar (
functionandparamList) allow any syntactically valid argument list. Function resolution and arity checks belong to the compiler (T0008). - Tests: R5
testSection13,testEntry12,testSameSubject16,testHasCoding10, all in the out-of-scopedocumentFunctionsgroup, mark well-formed extension callsinvalid="syntax". - Decision: those calls parse successfully. They remain excluded from parse-only suite acceptance by group, and separate regression tests assert that parsing does not check function signatures.
Quantity
Calendar and definite month factors
- Spec: 3.0.0 time-valued conversions gives calendar month = 30 days, definite UCUM
mo= 30.4375 days, anda= 365.25 days. The older FHIR R5 mapping discussion callsmo30 days. - Tests:
quantity time table,uses calendar factors explicitly and requires explicit conversion before addition, andquantity and datetime calendar consistency. - Decision: use the 3.0.0 definite factors. Calendar year/month stay distinct from definite durations for equality and ordering; equivalence permits the specified counterparts. Calendar-to-calendar conversion uses 12 months/year, 365 days/year or 30 days/month directly, not a transitive chain through UCUM. Addition/subtraction require explicit conversion when calendar year/month units differ. FHIR mapping follows R5's six-code table;
wk/msremain UCUM spellings. (T0006)
Ordering calendar years and months
- Spec: 3.0.0 comparison explicitly gives
6 months > 1 yearasfalseafter converting to years. Quantity equality requires time comparison in the least granular unit while retaining each code system. - Pinned suites: FHIR/fhir-test-cases commit
cb4eac4(seetools/conformance/fixtures/source.json), both R4 and R5:testLessThan29(1 year < 2 months),testGreaterThan29(1 year > 2 months) andtestLessOrEqual28(1 year <= 2 days) all expect empty. - Decision: follow 3.0.0 (ADR-0001): its comparison section gives
6 months > 1 yearasfalseafter converting to years, so those expressions returnfalse,trueandfalse, respectively. Calendar-to-calendar year/month ordering is supported; calendar year/month against definite UCUM counterparts remains empty. The six suite cases are narrowly enumerated conformance exceptions (#88). Direct kernel tests cover these results and reverse operand orders. (T0006)
FHIR Quantities without a UCUM code
- Spec: R5 §2.1.9.1.3 converts a FHIR
QuantitytoSystem.Quantityonly when it has a UCUMsystemandcode. For any other Quantity, N1 §6.1.1 would compare the children, so a unit on one side only would make=false. - Tests: group
testQuantityUnitComparison:testQuantityUnitVsNoUnitEqualandtestQuantityNoUnitVsUnitEqualexpect empty, and the matching equivalence tests expectfalse.testLessThan33,testLessOrEqual30andtestGreaterThan30(parameters-quantity-unit-text) order a quantity with only unit text against a UCUM-coded one with the same unit text by value (#150). - Decision: two FHIR Quantities (or specializations such as
Age) of which at least one does not convert compare by their elements, close to how the HL7 Java engine orders them (sameUnit()inFHIRPathEngine.java). Their units match when both have acodeand the codes are the same. When only one has acode, both must have aunittext and the texts must be the same, as for the suite'smg/dLpair: a UCUM-coded5 mgwithout unit text against5without a code or unit has no unit in common, so=is empty, where the Java engine's missing-equals-missing would make it true. When neither has acode, theunittexts must be the same, and two quantities with neither a code nor a unit match. The rule is the same for=,~,<,<=,>and>=, so the operators agree with each other; the Java engine's equality is stricter when only one has a code, which would make=empty where<and>are both false. When the units do not match,=and the ordering operators are empty and~is false, as for quantities whose units cannot be related. Otherwise the values compare as Decimals, without unit conversion: two quantities without a value are equal, and a missing value makes=and ordering empty and~false. Two FHIR Quantities that both convert compare as System Quantities, with unit conversion. A FHIR Quantity that does not convert is still a complex value against a System Quantity such as a literal:=is false and ordering raiseseval/type-mismatch, as N1 §6.2 requires for operands of different types. Thecomparatorelement (<,<=,>=,>,ad) is ignored in every case, as the R5 mapping and the HL7 Java engine ignore it, so<5 mgcompares as5 mg; the spec defines no meaning for a comparator in FHIRPath operations. (T0018, T0020) - Code:
fhirQuantityPair()inpackages/core/src/runtime/fhir-quantity.ts, used byequality.tsandcomparison.ts.
Equivalence of unsupported or incompatible quantities
- Spec: N1 equivalence says "Attempting to operate on quantities with invalid units will result in
false". 3.0.0 Quantity Equivalence is inconsistent here and says empty; FHIR-59626 ("Quantity equivalence returns false rather than empty for invalid or incomparable units") corrects it in the next release. - Tests: R4
testEquivalent28and R5testEquivalent29(1 'x' ~ 1 year); R4testEquivalent29and R5testEquivalent30(1 year ~ 1 'kg') all expectfalse. - Decision:
~returnsfalsewhen the units cannot be related or the conversion overflows, following N1, the suite and the FHIR-59626 resolution. Equality and ordering keep returning empty for such units (T0006 acceptance criterion). No conformance exception is needed. Direct kernel tests cover both operand orders. (T0006)
Recurring time conversion precision
- Spec: 3.0.0 Quantity Equality requires the least granular time unit, preserving each operand's code system. Unit conversions warns against premature rounding; a recurring fraction cannot be represented exactly by a finite Decimal.
- Tests: direct regression
compares recurring time ratios without rounding distinct values to equality, using0.01666666666666666666666666667 'min'versus1 's'in both operand orders; no pinned-suite counterpart. - Decision: terminating conversion ratios preserve all representable digits; recurring ratios use the Decimal kernel's 28-significant-digit division. Exact equality and ordering must not consume rounded conversion intermediates. The optional provider comparison capability uses exact ratio cross-products; the minimal provider implements it. Both operand orders distinguish the slightly different values in this regression, as well as
1 'min'versus(60 + 10^-28) 's'. Explicit conversions and equivalence still use the Decimal conversion result. (T0006)
UCUM unit algebra
- Spec: 3.0.0 multiplication and division ask for "an appropriate unit as determined by application of the [UCUM] specification" and give examples (
12 'cm' * 3 'cm'is36 'cm2',10 'm/s' * 10 's'is100 'm',60 / 1 's'is60 '/s'), but UCUM defines no canonical spelling. The suite only checks results with=, which accepts any commensurable unit (2.0 'cm' * 2.0 'm' = 0.040 'm2'). - Tests:
testQuantity9–testQuantity11; inpackages/ucum/test/ucum-quantity.test.ts, the multiplication and division rows ofFHIRPath 3.0.0 examples, theunit algebratable, andreturns units whose magnitude times the scale equals the exact product or quotient. - Decision:
@callis/ucumkeeps the simple units as written, in order. Identical simple units add their exponents ('cm2' / 'cm'is'cm'). A later simple unit with the same dimension as an earlier one that has not cancelled out is converted into it with an exact factor, so'm/s' * 'min'is60 'm',2.0 'cm' * 2.0 'm'is400.00 'cm2', and'cm' / 'm'is0.01 '1'. Dimensionless and arbitrary units only combine with identical ones. Integer factors move into the numeric factor, and annotations are dropped, because they carry no meaning (UCUM §12). Multiplying or dividing by'1'keeps the other unit as written. Special units such asCeltake part in no product or quotient, not even with'1'(UCUM §22). A product or quotient whose unit the provider would not accept again (its magnitude needs more than 4,096 bits) is empty. (T0007)
Arbitrary and special UCUM units
- Spec: UCUM §24 and §25: an arbitrary unit such as
[iU]is commensurable with no other unit, and "any term involving arbitrary units … is not comparable with any other arbitrary unit or term". UCUM §21–23 define special units by conversion functions; 3.0.0 quantity equality has23 'Cel' = 73.4 '[degF]'astrue. - Tests:
only matches arbitrary units with the identical unit (UCUM §24, §25),does not convert special units other than Cel and [degF]and theCel/[degF]rows ofFHIRPath 3.0.0 examples. - Decision: quantities with arbitrary units only compare or convert when their units are spelled identically:
1 '[iU]' = 1 '[IU]'and1 '[iU]/mL' = 1000 '[iU]/L'are empty, and~isfalse. Of the 21 special units of the essence file,Celand[degF]convert, on their offset scales, when written alone (an annotation is allowed). Prefixed, raised or compound uses (mCel,Cel/s) and the other special units are valid but not convertible; identical spellings still compare. (T0007)
Calendar keywords and other UCUM time units
- Spec: the 3.0.0 time-valued quantities table relates calendar keywords only to
'a','mo','wk','d','h','min','s'and'ms'. UCUM has more time units (us,a_j,mo_g, …). - Tests: the
calendar keywordsgroup inpackages/ucum/test/ucum-quantity.test.ts, which also checks every pair of minimal units againstminimalUnitSystem. - Decision: when both units are ones the minimal unit system knows (
'1', calendar keywords and the eight UCUM time units),@callis/ucumgives exactly its result. Against other UCUM time units,weektomillisecondstand for their definite counterpart, andyearandmonthonly for equivalence:1 week = 604800000000 'us'istrue,1 year = 31557600000000 'us'is empty and1 year ~ 31557600000000 'us'istrue. An explicit conversion to a calendar keyword converts to its UCUM counterpart and relabels (1 'a_j'becomes1 year). An explicit conversion fromyearormonthto a UCUM unit outside the table is empty, because that unit has no calendar counterpart to relabel to. (T0007)
Exponents after integers in UCUM
- Spec: the UCUM grammar allows no exponent on an integer (
<factor> ::= <digits>), but §9 says "2+10 means 2^10 = 1024". - Tests:
parses 2+10andparses 10-3inpackages/ucum/src/expression/unit-expression.test.ts. - Decision: follow §9: an integer followed by a signed exponent is raised to that power. An unsigned exponent cannot occur, because a run of digits is one integer (§8). (T0007)
Operators
Undetermined equality in union and membership
- Spec: N1 union, membership and containership use equality semantics but do not explicitly specify how an undetermined item comparison affects these operators.
- Tests:
collection operatorsinpackages/core/test/operators.test.ts, including@2020 in @2020-01and a later definite match after an undetermined comparison. The pinned suite has no such case. - Decision: only a
trueequality establishes a duplicate or a membership match. Union retains items with undetermined equality; membership returnsfalsewhen no item definitely matches. A later definite match returnstrue. This keeps union’s result a collection and membership’s nonempty search result Boolean, as their definitions require. The original retained item keeps its input provenance.
Incorrect result comments in N1 ordering examples
- Spec: N1 less or equal and greater or equal define the usual ordering but reverse the result comments for
10 <= 5,10 <= 5.0,'abc' <= 'ABC', and their>=counterparts. - Tests:
ordering operatorsinpackages/core/test/operators.test.tstests all four operators for each N1 operand pair. The pinnedtestLessOrEqual/testGreatorOrEqualgroups also exercise numeric/String ordering. - Decision: follow the operator definitions:
10 <= 5and'abc' <= 'ABC'are false; their>=counterparts are true. String order remains Unicode code point order, through the T0009 kernel.
Filtering criteria use the canonical singleton Boolean rule
- Spec: N1 where and 3.0.0 where require a single Boolean condition, but also refer to singleton evaluation, whose second step treats any other single item in a Boolean context as true.
- Tests:
where through the public synchronous APIinpackages/core/src/functions/filtering.test.tscovers true, false, empty, zero, empty String,'false', Decimal, Date and Quantity criteria, and multi-item errors. The pinnedtestWheregroup has no non-Boolean criterion case. - Decision: follow T0003's established Boolean-context contract and the existing
singleton(result, 'Boolean', asBoolean)helper. Single non-Boolean criteria match; they are not explicitly converted and no JavaScript truthiness rule is used. False/empty does not match. Multiple items raiseeval/singleton-expected. This preserves the canonical rule already documented for where and the owner-approved narrowed T0012 contract; it does not change operators or other Boolean consumers.
Existence criteria stop after the first match
- Spec: N1 exists describes the optional criterion as shorthand for
where(criteria).exists(), but does not explicitly require evaluating later criteria after a match. - Tests:
short-circuits on a match without evaluating a later invalid or failing itemand the internal sync/promise/custom-thenable/cross-realm cases inpackages/core/src/functions/existence.test.ts; the pinnedtestExistsgroup has no later-error case. - Decision: the owner-approved narrowed T0011 contract stops at the first match. Later criteria are not evaluated, including errors they would have raised. A criterion reached before a match still propagates its error; no match gives false. The predicate conversion itself is exactly T0012's canonical helper. This differs from materializing every item through where before asking exists when a later criterion fails, and does not change where's sequential evaluation of all items.
Static analysis
Implemented in packages/core/src/analysis/ (T0024). Every check fires only when every possible type is wrong and never for a value whose type is unknown, so analysis without a model rejects no valid expression of the suite, and with the suite's models and inputs it reports no error for an expression that evaluates (tools/conformance/src/static-analysis.test.ts, which evaluates every test without analysis through compileUnchecked() and then analyzes it; the invalid="semantic" tests are the suite's own exceptions).
Function types are checked statically, operator types when evaluated
- Spec: N1 §11 lists both "a function is passed an input value or argument that is not of the expected type" and "an operator has operands that are not of the expected type" as unsafe uses, and leaves to the implementation whether they are found at compile time or at run time.
- Tests: the suite classifies them differently. A function with an input or argument of the wrong type is a semantic error:
testStartsWithNonString1(Appointment.identifier.startsWith('rand')),testSubstring10aandtestStartsWith12a(length()where a String is expected), andisEffectOnLogic3Base($this.toString()on a Period, which evaluates to empty without an error). An operator with operands of the wrong type is an execution error:testMinus4('a'-'b'),testPrecedence1(-1.convertsToInteger()),testPrecedence3(1 > 2 is Boolean),testLiteralDecimalLessThanInvalid,testConcatenate4,testPlusDate14,16,17andtestMinus6(units that date/time arithmetic rejects).testPlus6(@1974-12-25 + 7) alone expects a semantic error for an operator and passes as "detected late". - Decision: follow the suite, which reflects the HL7 Java engine. A function's input and arguments are checked when the expression is compiled, by the expectations the function declares (
inputandexpectsinfunctions/define.ts): a value none of whose possible types fits issemantic/type-mismatch, an error. An operator whose operands it can never accept, by the rules of the runtime kernels, is reported with the same code as a warning, and evaluation raiseseval/type-mismatchas before; strict mode makes it an error, as N1 §11 lists it. A value of several possible types, such as a choice element or(true | 'foo'), is accepted when one of them fits ((true | 'foo').allTrue()is an execution error in the suite). Where a single Boolean is expected, a value of another type counts as true by singleton evaluation, so it is reported in strict mode only (testIif6, which ismode="strict"). - Code:
#checkExpectation(),#checkPairs()and#operatorSeverity()inpackages/core/src/analysis/analyzer.ts.
Conversion functions on complex values
- Spec: N1
toString()and the other conversions give empty, or false fromconvertsToX(), for a value that does not convert; they do not say that a resource or a complex value is an error. - Tests:
isEffectOnLogic3Baseexpects a semantic error for$this.toString().length() > 10withcontextType="Period", and the type-guard tests ofisSemanticChecksdepend on it. - Decision: a conversion of a value none of whose possible types has a System value (a resource, a complex value such as
PeriodorHumanName) issemantic/type-mismatchwhen the expression is compiled, for every conversion function: the result could only ever be empty or false, and the HL7 Java engine rejects it. A value typed only at run time still converts to empty. A FHIRQuantityhas a System value, so it converts. - Code: the
PRIMITIVEexpectation inpackages/core/src/functions/conversion.ts.
Type guards
- Spec: none. The suite's
isSemanticChecksgroup defines, in its comments, that a type test used by a logical operator narrows the types the other operand is checked against: inA implies B,A and Bandiif(A, B, …)the operandBis checked as ifAwere true; inA or Bandiif(A, …, B)as ifAwere false.AisX is T,X.is(T),(X is T).not(), or a combination of those withandandor. When no type remains,Bis unreachable and reports nothing. The guard is on the expressionXitself:$this.start is dateTimesays nothing about$this(isGuardOtherExpressionBad). - Tests: the
isSemanticChecksgroup, withcontextTypefor the possible types of the focus (Period|Timingmeans either). - Decision: follow the suite. A guard narrows the expression it tests, named by its path (
$this,$this.start,%resource.status), so it applies wherever that path is written in the guarded operand;xorandimplieson the left give no guard. A trueX is Tkeeps the possible types that areTor a subtype of it and narrows a supertype (Element) toT; a false one drops the types that areTor a subtype.X is T1 or X is T2narrows to both when true; nothing is known when it is false, and nothing whenX is T1 and X is T2is false. A guard on$thisdoes not reach a lambda, whose$thisis its own item, except foriif()called without a target, whose arguments have the same focus.asandofType()narrow the same way, to empty when the type cannot be the target (($this as dateTime).toString()with a Period focus raises nothing), as the runtime gives empty there. - Code:
packages/core/src/analysis/scope.tsand#guardOf()inanalyzer.ts.
Strict mode
- Spec: N1 §11 lists the unsafe uses a strict implementation reports: a function or operator that takes a single item called with a value that is not guaranteed to have one, a function or operator with a value not of the expected type, and "equality operators are used on operands that are not both collections or collections containing a single item of the same type".
- Tests:
testIif6,testDollarOrderNotAllowed(mode="strict"); the othermode="strict"tests are caught by the model-aware checks that do not need strict mode.tools/conformance/src/static-analysis.test.tschecks over both suites, with their models and inputs, that an expression strict analysis accepts never raiseseval/singleton-expectedwhen evaluated;single()is excepted, because it raises that error by its contract (N1 §5.2.6). - Decision:
strict: truemakes the analyzer report, as errors, a value whose cardinality is known to allow more than one item where one is expected (semantic/singleton-expected): a repeating element of the model, a union, acombine(), aselect()of such a value, a built-in that gives a collection whatever its input has (toChars(),children(),descendants(),extension(), so'ab'.toChars().length()is an error without a model too), a member of a collection, which is a collection even when the type of its items is unknown (contained.status = true), and the result of a function that gives something for each input item, which repeats when its input does (('#a' | '#b').resolve().id.toString(); theperItemhint ofresolve()andextension(), thefromInputhint ofwhere(),select(),ofType()and the subsetting functions). A value whose cardinality is unknown, such as a path without a model, a variable or a member of one item of unknown type, is never reported, so strict mode without a model only checks what the expression itself makes known. Equality follows the spec's wording: one single item against a value that may repeat is an error, two collections or two single items are not, and two single items of types that are never equal (active = 'true',1 = 'a') aresemantic/type-mismatch. The spec's own corrected examplePatient.name.where(given = 'Wouter').exists()is still an error by its definition, becausegivenrepeats;given.first() = 'Wouter'or'Wouter' in givenis not. Operator type mismatches become errors, and a single value that is not a Boolean where one is expected (iif('x', …),'a' and true,1.not()) is an error instead of counting as true. Order-dependent operations onchildren()anddescendants()are errors (above). Unknown types (above) and ignored fractions stay warnings. Strict mode changes what compiles, never what an expression evaluates to; the runtime half of T0018's strict rule for unknown elements is #216. - Code:
#checkSingleton(),#checkOrdered(),#inferEquality()and#operatorSeverity()inpackages/core/src/analysis/analyzer.ts; thesingletonandorderedexpectations of the functions infunctions/define.ts.
Conversion
Scope of the iif() arguments
- Spec: N1 iif() does not say what the focus and
$thisof its arguments are. 3.0.0 iif() makes it a scoped function: the criterion and the selected branch are evaluated with$thisset to the input, the criterion also when the input is empty,$indexis not set, so it keeps the value of an outer function, and more than one input item is an error. - Tests:
testIif7–testIif11andtestCollectionBoolean1–6;iifinpackages/core/src/functions/conversion.test.ts, with the 3.0.0 examples. - Decision: follow 3.0.0. The input is the focus and
$thisof all three arguments, also when it is empty, so{}.iif(exists(), 'yes', 'no')is'no'andPatient.birthDate.iif(true, $this)is empty without a birth date. Without a target the input is the focus where the call is written.$indexand$totalare those of the enclosing function. More than one input item raiseseval/singleton-expectedbefore the criterion is evaluated. The criterion follows singleton evaluation, as inwhere()(above): a single non-Boolean item counts as true, as the 3.0.0 examplesiif(0, 'true', 'false')andiif('hi', 'true', 'false')show.testIif6ismode="strict"and expects a semantic error for a String criterion; strict mode reports it (T0024). - Code:
iifFunctioninpackages/core/src/functions/conversion.ts, throughLambdaArg.forInput()(functions/define.ts,compiler/lambda.ts).
toString() of a FHIR Quantity
- Spec: N1 toString() converts a Quantity, and R5 maps a FHIR
Quantitywith a UCUM code toSystem.Quantity. The R6 draft adds a FHIR override, §2.1.9.4.1:toString()gives a String only for a FHIR primitive that has a value and a System type, and is empty otherwise. A FHIRQuantityis a complex type, so under that noteObservation.value.toString()is empty. - Tests:
converts a FHIR Quantity with a UCUM code as a System Quantity, with every providerandgives empty for a primitive that has only extensionsinpackages/core/test/conversion-models.test.ts, run against ther4,r5andr6providers. - Decision: the engine behaves the same with every provider (FHIR versions). A FHIR
Quantitywith a UCUM code is a System Quantity (T0018), sotoString()writes it (185.50 '[lb_av]') andconvertsToString()is true, also with the R6 provider. This differs from the R6 draft. A FHIRQuantitywithout a UCUM code is not a System Quantity, sotoString()andtoQuantity()are empty for it, as the R6 note has it. For primitives the R6 note and Callis agree: a primitive with only extensions has no value, and every conversion function gives empty for it,convertsToX()included. Revisit when R6 is final.
Calendar keywords in toString()
- Spec: 3.0.0 toString() writes UCUM units quoted and calendar keywords without quotes, and gives
(4 days).toString()as4 days. N1 only gives the format(+|-)?\d+(.\d+)? '.*'. - Tests:
testQuantityLiteralWkToString(1 'wk'),testQuantityLiteralWeekToString(1 week);toString and convertsToStringinpackages/core/src/functions/conversion.test.ts. - Decision: a Quantity keeps no spelling of its calendar keyword, so
4 daysand4 dayare the same value (T0006).toString()writes the keyword in the singular:(4 days).toString()is'4 day', not the'4 days'of the 3.0.0 example. Both are valid quantity literals, andtoQuantity()reads both back to the same value.
Quantity strings and the unit argument of toQuantity()
- Spec: N1 toQuantity() gives the string format
(?'value'(+|-)?\d+(.\d+)?)\s*('(?'unit'[^']+)'|(?'time'[a-zA-Z]+))?and says that with a unit argument the result is true or false. 3.0.0 corrects that: the result is the converted quantity, or empty. Neither says whether the format must match the whole string, whether the unquoted word must be a calendar keyword, or what an empty unit argument means. - Tests:
testStringQuantityWeekConvertsToQuantityFalse('1 wk'),testStringDecimalLiteralConvertsToQuantityFalse('1.a') and the othertoQuantitytests oftestTypes;toQuantity and convertsToQuantityinpackages/core/src/functions/conversion.test.tsandpackages/ucum/test/conversion-integration.test.ts. - Decision: the format must match the whole string, and an unquoted word must be a calendar keyword in lower case, singular or plural, so
'1 wk'and'1 Day'do not convert. A quoted unit is taken as written, without asking the unit system, as in a quantity literal:'5 \'foo\''is5 'foo'. A unit argument converts the quantity with the unit system as an explicit conversion (3.0.0 time-valued unit conversions), so7 days.toQuantity('wk')is1 'wk'; units that cannot be related give empty, andfalseforconvertsToQuantity(). The unit must be a single String. An empty unit argument converts nothing, as an empty optional argument ofsubstring()is ignored in 3.0.0. - Code:
toQuantityFunctionandconvertsToQuantityFunctioninpackages/core/src/functions/conversion.ts.