T0003 — Type system and collection foundations
Part of the roadmap. Phase 1 · wave 1 · size M.
Goal
The shared, dependency-free building blocks used by the runtime, functions and model support (architecture: values, ModelProvider interface).
Scope
src/types/:- System type names and
TypeSpecifier - type-specifier resolution (model namespace first, then System)
- the implicit-conversion table as data
is/assubtype checks against System types plus aModelProviderhook. The hook isModelTypes<T>insrc/types/model-types.ts: the part of a model that the type system uses, whichModelProvidersatisfies structurally, sotypesdoes not depend onmodel.
- System type names and
src/model/model-provider.ts: theModelProvider,ModelTypeInfoandElementInfointerfaces. This is a contract used by T0018 and T0019, so review it carefully.src/model/model-node.ts: theModelNodedata class (structure only; navigation comes in T0008/T0018).src/runtime/collection.ts: theCollectiontype, the frozenEMPTY, and builder helpers.src/runtime/logic.ts: three-valued truth tables forand,or,xor,impliesandnot.src/runtime/singleton.ts: the four-step singleton evaluation from N1 §4.5, with a conversion callback so it does not depend on value classes.src/values/string.ts: string equivalence normalization, plus equality and equivalence kernels for String, Integer and Boolean, and ordering kernels for String and Integer. Boolean has no ordering (N1 §6.2).packages/core/test/support/stub-model.ts: a small FHIR-likeModelProviderfor tests, until the generated models exist (T0019).packages/core/test/support/model-provider-contract.ts:describeModelProviderContract(provider, fixtures), a test suite for the rules below. The stub runs it here; #56 proposes that the generated models run it too.
Design notes
Collections
- Every expression evaluates to a collection: a JavaScript array
readonly Item[]. Empty is[]. Collections never containnullorundefined, and never contain arrays: theItemtype requires object items to be non-iterable, so a nested collection does not compile. T0008 may narrowItemto the closed union of value classes once they all exist. - Collections are never mutated after they are returned (enforced by
readonlytypes). Builders use local mutable arrays. A shared frozenEMPTYconstant avoids allocations. - Order is preserved wherever the spec defines it (navigation,
combine, indexers). Where the spec leaves order undefined (for example the|operator, N1 §6.4.1), Callis still produces a deterministic order: left items first, then new items from the right.
Type system
- A type is named by
{ namespace, name }. The System types areAny,Boolean,String,Integer,Long(phase 2),Decimal,Date,DateTime,TimeandQuantity, all derived fromSystem.Any. - Resolving type specifiers (N1 §10.1): an unqualified name is looked up in the model namespace first (for example
FHIR), then inSystem. Qualified names (FHIR.Patient,System.String) are looked up directly. The pure resolver still returnsundefinedfor an unknown name; T0008 owns execution errors and the separate model-less resource-name matcher (#58, #59). is,asandofTypeaccept the exact type or a subtype, using model inheritance. FHIR primitives follow the FHIR rules (R5 §2.1.9.1.2):Patient.birthDate is dateis true andis System.Dateis false.ofType()accepts both.- Implicit conversions (N1 §5.5):
Integer → Decimal,Integer → Quantity,Decimal → Quantity,Date → DateTime. Phase 2 addsInteger → Long,Long → DecimalandLong → Quantity(the 3.0.0 table; T0028's task file lists only the first two, see #62).System.Longis already a System type name, so a model can map R5'sinteger64to it. - FHIR primitives map to System types using the table on the FHIR page, with one deliberate difference:
FHIR.datemaps toSystem.Date, notSystem.DateTime. The test suite expects this (birthDatehas output typedate), and so do the other major implementations.FHIR.Quantitymaps toSystem.Quantityonly when it has a UCUM system and code (R5 §2.1.9.1.3). - Explicit conversions are the
toX()andconvertsToX()functions. - Model-less convenience: a string that comes from untyped input data (not a string literal) is parsed on demand when it is compared with a date/time value. So
birthDate = @1974-12-25works without a model. The rule never applies when a model is present. It needs the date/time values (T0005) and the equality and comparison dispatch, so T0003 does not implement it; T0009 owns the dispatch and provenance rules (model-less date convenience, #55).
Empty propagation and singleton evaluation
- Operators: an empty operand gives an empty result (N1 §4.4.1). Exceptions follow the spec: Boolean operators use three-valued logic,
|,inandcontainshave their own rules,{} ~ {}istrue, and&treats empty as''. - Functions define their own behaviour for empty input. Most return empty.
- Singleton evaluation (N1 §4.5) is one helper,
singleton(collection, expectedType, convert), that implements the four-step rule.convertturns the item into the expected type, or returns undefined when it cannot, so the helper does not depend on the value classes:- A single item that converts implicitly to the expected type is that value (3.0.0 says "implicitly converted").
- A single item where a
Booleanis expected istrue. - An empty collection stays empty.
- Anything else is an error: more than one item raises
eval/singleton-expected, and a single item that does not convert to an expected type other than Boolean raiseseval/type-mismatch(owner decision, 2026-11-05).
- Boolean contexts (
wherecriteria,iifcriteria, operands ofand/or) use the same helper, producingtrue,falseor empty.
Three-valued logic
and, or, xor, implies and not() follow the truth tables in N1 §6.5, implemented over true | false | undefined (where undefined means empty). Both operands are always evaluated. The spec says short-circuiting must not change semantics, and an error in the right operand has to surface even when the left operand already decides the result. iif() is the lazy construct.
Model principles
- The core does not know about any particular model. A model is supplied through
ModelProvider. - Model-less mode navigates plain JSON:
- property names are JSON keys, and arrays are flattened
resourceTypegives a resource its type name- JavaScript values map to System types: string → String, boolean → Boolean, integer number → Integer, other numbers → Decimal
- there is no choice-type resolution, so
Observation.valueQuantityworks as an ordinary key
- With a model, navigation is type-directed: choice types, FHIR primitive types, inheritance,
_fieldprimitive extensions and semantic checks.
ModelProvider interface
export interface ModelProvider {/** Namespace searched before System for unqualified type names, e.g. 'FHIR'. */readonly namespace: string;/** Model version, e.g. '4.0.1'. */readonly version: string;/** 'Patient', 'HumanName', 'string', 'Patient.contact' (backbone element types are named by path). */getType(name: string): ModelTypeInfo | undefined;/** Type of a root object, e.g. from `resourceType`. */getRootType(json: object): ModelTypeInfo | undefined;/** An element by its FHIRPath name (choice elements without [x]). */getElement(type: ModelTypeInfo, name: string): ElementInfo | undefined;/** All elements, in definition order; used by children(), descendants() and equality. */getElements(type: ModelTypeInfo): readonly ElementInfo[];isSubtypeOf(type: ModelTypeInfo, ancestor: ModelTypeInfo): boolean;/** System type for primitive model types, e.g. FHIR.code → System.String. */getSystemType(type: ModelTypeInfo): SystemTypeName | undefined;}export interface ModelTypeInfo {readonly namespace: string; // 'FHIR'readonly name: string; // 'Patient' | 'string' | 'Patient.contact'readonly kind: 'primitive' | 'complex' | 'resource' | 'backbone';readonly baseName?: string; // 'DomainResource'readonly isAbstract: boolean;}export interface ElementInfo {readonly name: string; // 'value' (no [x])readonly typeNames: readonly string[]; // more than one means a choice elementreadonly isArray: boolean;readonly isChoice: boolean;}
The interface is synchronous and pure. Implementations precompute their indexes, and model data is immutable and shared across evaluations.
The TSDoc in src/model/model-provider.ts is the full contract. The points that implementers (T0019) and users (T0018, T0024) rely on:
ModelTypeInfo.kindhas its own type,ModelTypeKind.namespaceis neverSystem. Type names are case-sensitive.- Lookups are prototype-safe:
getType('constructor')andgetElement(type, '__proto__')are undefined unless the model defines them, andgetRootType()readsresourceTypeas an own property. getType()should return the same object for the same type, so the common case compares by identity. Methods that take aModelTypeInfoidentify it by name, so a copy gives the same answers; the engine also treats equal namespace and name as the same type.getElement()andgetElements()include inherited elements and return the sameElementInfoobjects every time, so callers can cache derived data keyed on them.getElements()lists them in snapshot order, base types first. A primitive type's implicitvalueis not an element.- Every name in
ElementInfo.typeNamesresolves withgetType(): backbone types by path,contentReferenceresolved, and System-typed elements such as FHIR'sElement.idgiven as the matching model type (string). - A choice element appears in JSON as its name plus the type name with the first letter in upper case (
valueQuantity), even when only one type is allowed.choiceJsonName(name, typeName)inmodel-provider.tsis the one implementation of this rule, for T0018, T0019 and T0024. isSubtypeOf()is reflexive.getSystemType()never returnsAny(its type excludes it). It covers every type whose values convert implicitly, including derived primitives (code→String) andQuantitywith its specializations (Age). ForQuantitythis is the type-level answer; whether a value has the UCUM code it needs is checked when the value is converted.
Acceptance criteria
- The three-valued logic tables are tested exhaustively against N1 §6.5.
- All four branches of singleton evaluation are tested, including the
eval/singleton-expectedandeval/type-mismatcherrors. - Type-specifier resolution is tested with a stub model: the model is searched before System, and qualified names resolve directly.
- String equivalence follows N1 string equivalence (case, whitespace).
- The interfaces are documented with TSDoc.