T0018 — Model-aware evaluation
Part of the roadmap. Phase 1 · wave 4 · size L.
- Depends on: T0008
- Parallel with: T0010–T0017
- Background: ADR-0008, ADR-0012 (strict choice types by default)
Goal
Use a ModelProvider during evaluation (design notes).
Scope
- Typed navigation:
ModelNode.typeset from the model- choice elements (
value→valueQuantity, etc.) lenient.choiceSuffix(the internalCompileOptions.lenient; the public option is T0038)- primitive extensions (
_field, index-aligned arrays) - extension-only primitives
- Converting FHIR primitives to System values (memoized), with
FHIR.date→System.Date. - The root identifier as a type, with inheritance (
DomainResource.contained…). is,asandofTypewith model types, following the FHIR rules for primitives and T0008 target resolution. A supplied model disables the model-less resource-name fallback, including for nodes whose model type is unknown. TheofType()matching rule is in the type-target runtime; the function itself is T0042.- Model-ordered children: the
navigateChildren()helper inruntime/navigation.ts, on which T0017 registerschildren()anddescendants(). - Typed complex values in
=and~: elements instead of JSON keys, and the rule for FHIR Quantities without a UCUM code. parseJson(): a lossless JSON parser (JsonNumber), which navigation understands; both are public exports.- The conformance runner evaluates with the generated R4 and R5 models (T0019) and parses its inputs with
parseJson(), and registers the suite exceptionstestType22andtestFHIRPathAsFunction11/16(#111). - The mini FHIR model fixture (
packages/core/test/support/stub-model.ts, from T0003) is extended with the types these tests need, so the core's unit tests do not depend on the generated packages. - R6 support through the same code: the engine is provider-agnostic, with no version-specific cases, and
packages/core/test/generated-models.test.tsruns the same model-aware evaluation cases against the realr4,r5andr6providers (T0039): typed navigation, choice types where the versions differ (Observation.value[x]allowsReferencein R5 only andAttachmentin R5 and R6), FHIR primitive conversion, andis/aswith the types of each version, including the R6-onlyDeviceAlert. This is engine-tested provider support for a draft snapshot, not final R6 stability, an R6 conformance result (there is no official R6 suite, and none is invented) or a public model option (T0038). The suite exceptions above stay R4 and R5 only.
Design notes
The ModelProvider interface and the type rules this task relies on (type-specifier resolution, FHIR primitive → System mapping, the model-less date convenience) are in T0003.
ModelNode
Data from the input is wrapped in a small ModelNode. It is a class, so V8 sees a single object shape:
class ModelNode {readonly value: unknown; // JSON value; undefined for a primitive with only extensionsreadonly primitiveElement?: object; // the matching `_name` object (id/extension) for FHIR primitivesreadonly type?: ModelTypeInfo; // undefined in model-less modereadonly systemType?: SystemTypeName; // what the model maps `type` to: 'Date' for FHIR.datereadonly name: string; // element name (for trace, pathname, children)readonly parent?: ModelNode; // used for %resource, %rootResource and contained-reference resolutionreadonly index?: number; // position in a repeating elementsystemValue(): SystemValue | undefined; // the converted value, computed once}
Nodes are created lazily during navigation. Conversion to a System value (for example FHIR.date → DateValue) is memoized on the node: systemValue() computes it on first use, by systemType (model/node-conversion.ts), and toSystemValue() in the runtime calls it. A value that is not valid for its type keeps the plain JSON mapping (spec notes). A Quantity converts only with a UCUM code, through fromFhirQuantity().
Choice types and primitive extensions
- Choice elements (R5 §2.1.9.1.1):
Observation.valuelooks up the JSON keysvalue+ type suffix (valueQuantity,valueString, …) for each allowed type, and the node gets the type it matched and the element namevalue. WritingObservation.valueQuantityis not valid FHIRPath: it is a semantic error with a model (testtestPolymorphismB, T0024) and empty at runtime. Alenient: { choiceSuffix: true }option accepts it for compatibility (test modelenient/polymorphics), giving the value only when its type is the one the suffix names (spec notes). - Primitive extensions (FHIR JSON):
birthDateand_birthDateare merged into one node. Arrays are aligned by index, withnullplaceholders. A node exists when either part exists.hasValue()is false when only the extension exists, and such a node behaves as empty in System-typed operations: its System value is undefined, andsingleton()treats it as empty wherever a specific type is expected (Patient.active and trueandPatient.active.not()are empty), whileexists(),count(),is,asand extension navigation still see the node.
Navigation rules
- With a model,
getElement(type, name)decides what a name means for a node whose type is known. An unknown element is a semantic error when the analyzer knows the type. At runtime it is empty in normal mode and an error in strict mode (both T0024). The JSON keys that are not elements, includingresourceType, are not navigable. A node the model does not know, such as an object with an unrecognizedresourceType, is navigated like plain JSON, and never gets a type from its data. containedresources andBundle.entry.resourcetake their type fromresourceType, falling back to the declaredResourcewhen the model does not know it. In general, an element typed as a resource is typed bygetRootType().- Root identifier as a type (N1 §10.1, R5 §2.1.9.1, spec notes):
- If the first identifier names a resource, complex or backbone type of the model and the input is of that type (or a subtype, as with
DomainResource), it evaluates to the input. - If it names such a type and the input is of a different type, or has no model type, the result is empty in normal mode and a semantic error in strict mode.
- Otherwise it is an ordinary path. A primitive type name (
id,code,date) is always a path, because FHIR's elements use those names. - Without a model, an identifier that matches the input's
resourceTypeis treated as the type name.
- If the first identifier names a resource, complex or backbone type of the model and the input is of that type (or a subtype, as with
navigateChildren()(T0017 buildschildren()anddescendants()on it) usesgetElements()with a model and the JSON keys without one (spec notes). Keys starting with_never appear as children: with a model they are folded into their primitives, and without one they are skipped, as isresourceType.- Variables are converted like the input, so a variable holding a resource is typed by the model.
Lossless decimals in JSON input
JSON.parse turns 1.50 into 1.5, which loses precision that FHIRPath can observe (toString(), ~, precision()). Callis accepts ordinary parsed JSON, which is convenient but lossy. It also exports parseJson(text), a small parser with no dependencies that keeps each numeric literal as a JsonNumber holding the source text (model/lossless-json.ts). Navigation understands both forms. The conformance runner uses the lossless path through the adapter's optional parseInput(text) hook in tools/conformance/src/engine-adapter.ts, set to parseJson. Without that hook the runner defaults to JSON.parse (T0022: adapter interface, #48).
parseJson()accepts what RFC 8259 allows, likeJSON.parse, and raiseseval/invalid-jsonotherwise. It is iterative, so nesting is not limited by the call stack, and a__proto__key becomes an own property.- A
JsonNumberhastext,toInteger()(a number written without a fraction or exponent, in the 32-bit range),toDecimal()(the exact value, with the scale of the text;9.5e2is950),toNumber(),valueOf(),toString()andtoJSON(), so JavaScript arithmetic andJSON.stringify()treat it as the numberJSON.parsewould have given. - In a collection, a
JsonNumbernode is the Integer or Decimal its text denotes; a typed FHIRdecimalis always a Decimal. Plain output gives that value (an Integer as a number, a Decimal bydecimalOutput), while an object result keeps itsJsonNumbervalues as they are.
Acceptance criteria
-
Observation.value.as(Quantity).unitworks, and so doesObservation.value is Quantity;ofType()uses the same matching rule (matchesTypeTarget()with'ofType') and arrives as a function with T0042.Observation.valueQuantityis empty by default (a semantic error with T0024), and works withlenient.choiceSuffix. -
Patient.name.givenon["a", null]with_given: [null, {extension}]gives two nodes, and the second has no System value, so it behaves as empty in System operations;hasValue()reads that once T0020 is merged. - With
parseJson,1.50keeps its precision end to end: the typed value is the Decimal1.50, anddecimalOutput: 'string'gives'1.50'(toString()is T0014). - With the mini model, unknown
string1,System.Patient,FHIR.BooleanandFoo.Patientraiseeval/unknown-typeacrossis/as(operator and function forms) and theofType()matching rule; resolved mismatches remain false/empty. An object with an unrecognizedresourceTypedoes not bypass the provider.testFHIRPathAsFunction23passes;24needsofType(). R4/R5testType22is registered as the documented suite exception intools/conformance/src/exceptions.ts, together withtestFHIRPathAsFunction11/16(#111); the vendored fixtures and the unknown-type semantics are unchanged. - The same model-aware evaluation cases pass against the real
r4,r5andr6providers inpackages/core/test/generated-models.test.ts, with the engine free of version-specific code: typed navigation, the version-specific allowed types ofObservation.value[x], FHIR primitive conversion,is/aswith each version's types, and the R6-onlyDeviceAlertas a type under R6 and as unknown data under R4 and R5. No R6 conformance result is claimed and no R6 suite exception is registered. - With the real R4 and R5 models,
testMiscellaneousAccessorTestsandtestQuantityUnitComparisonpass.testBasics,testObservations,polymorphicsandtestInheritancepass except for the tests that need other tasks: the semantic errors ofmode="strict"(testSimpleFail,testSimpleWithWrongContext,testPolymorphismB,testPolymorphismAsB,testPolymorphicsB; T0024),extension()(testFHIRPathIsFunction8–10; T0020) andofType()(testFHIRPathAsFunction17–24; T0042).testPolymorphismIsA3(Observation.issued is instanton an absent element) expects empty where Callis givesfalseforison empty input, the T0008 decision this task does not change. The model parts oftestTypespass; its remaining failures are the conversion functions (T0014).