# Code Generator The `dartfx.cdif.codegen` package is an automated code generation engine that translates upstream CDIF specifications into production-grade **Pydantic v2 + RDF** models. By synthesizing **Draft 2020-12 JSON Schemas**, canonical **JSON-LD `@context` maps**, and **SKOS Turtle ontologies**, the generator guarantees zero-drift alignment with CDIF standards. --- ## Generator Architecture The generator operates as a deterministic, four-stage compilation pipeline: ``` +-------------------------------------------------------+ | Upstream CDIF Artifacts | | - Profile JSON Schemas (*.schema.json) | | - Canonical JSON-LD Context (CDIF-context-2026.jsonld)| | - SKOS Ontologies (*.ttl) | +---------------------------+---------------------------+ | v +-------------------------------------------------------+ | Stage 1: Artifact Loader | | (dartfx.cdif.codegen.loader) | | - Discovers profile directories under git-cdif | | - Ingests schemas, context mappings, and Turtle graphs| +---------------------------+---------------------------+ | v +-------------------------------------------------------+ | Stage 2: Schema & Context Resolver | | (dartfx.cdif.codegen.resolver) | | - Unrolls Draft 2020-12 $ref and $defs pointers | | - Extracts inline schemas into top-level models | | - Maps schema properties to RDF predicate URIs | | - Resolves SKOS concepts into Python StrEnums | +---------------------------+---------------------------+ | v +-------------------------------------------------------+ | Stage 3: Intermediate Representation (IR) | | (dartfx.cdif.codegen.ir) | | - ClassIR, FieldIR, EnumIR, ModuleIR | | - Dependency sorting & topological ordering | | - Common definition deduplication | +---------------------------+---------------------------+ | v +-------------------------------------------------------+ | Stage 4: Python Code Emitter | | (dartfx.cdif.codegen.emitter) | | - Emits typed Pydantic v2 models with RdfProperty | | - Injects profile ClassVars and default @contexts | | - Formats source code using Ruff | +---------------------------+---------------------------+ | v +-------------------------------------------------------+ | Generated Modules | | - dartfx.cdif.models.vocabularies | | - dartfx.cdif.models.common | | - dartfx.cdif.models.profiles.* | +-------------------------------------------------------+ ``` --- ## Detailed Pipeline Stages ### 1. Artifact Loading (`loader.py`) The loader locates the local CDIF repository tree (`git-cdif` workspace) and collects: * **Schema Files**: Primary schemas for each profile (e.g. `profile-core/schema/cdif_core.schema.json`). * **JSON-LD Context**: The global mapping file `CDIF-context-2026.jsonld`, which establishes prefix bindings and property-to-URI definitions. * **Controlled Vocabularies**: SKOS Turtle files declaring activities (`cdif_provenance_activity.ttl`), GSBPM steps, and units. ### 2. Schema & Context Resolution (`resolver.py`) Draft 2020-12 JSON Schemas make extensive use of modular definitions (`$defs`), local reference pointers (`#/$defs/...`), and inline object definitions. The resolver: * **Inlines & Deduplicates `$defs`**: Common structures referenced across multiple profiles (such as `Person`, `Identifier`, `SpatialCoverage`) are extracted once and placed in `dartfx.cdif.models.common`. * **Resolves RDF Predicates**: For each schema property, the resolver consults the canonical `@context` to find its full RDF predicate URI (e.g., `schema:name` -> `http://schema.org/name`), translating it into an `RdfProperty(SCHEMA.name)` annotation. * **Parses SKOS Vocabularies**: Concepts in Turtle files with `skos:prefLabel` and `skos:notation` are compiled into Python `StrEnum` classes (e.g., `CdifActivityType`). * **Extracts Conformance Rules**: Captures `required` field lists and `anyOf` requirements to embed as ClassVar tuples (`cdif_required_fields` and `cdif_any_of_required`). ### 3. Intermediate Representation (`ir.py`) The schema data structures are transformed into strongly-typed intermediate representation (IR) nodes: * `ClassIR`: Represents a target Pydantic class, its base class, RDF type, and ClassVar metadata. * `FieldIR`: Represents a field, its Python type expression (e.g., `str | list[str] | None`), alias, and RDF property URI. * `EnumIR`: Represents an enumeration with string values and member names. * `ModuleIR`: Represents a target `.py` file with necessary imports and dependency ordering. The IR engine executes a topological sort on classes to ensure that types referenced by other models are defined first, eliminating circular dependency errors. ### 4. Code Emission (`emitter.py`) The emitter writes idiomatic Python code: * Leverages Python 3.12+ type union syntax (`X | Y | None`). * Annotates fields with `typing.Annotated[Type, RdfProperty(URI)]`. * Configures Pydantic models with `model_config = ConfigDict(arbitrary_types_allowed=True, populate_by_name=True, extra="allow")`. * Injects `@context` generation methods (`default_jsonld_context()`). * Automatically runs `ruff format` on the generated code. --- ## Running the Code Generator ### Via the CLI You can run the generator directly from the command line: ```bash # Generate models into the default models directory cdif codegen # Specify custom source and target paths cdif codegen --cdif-root /path/to/git-cdif --output-dir src/dartfx/cdif/models ``` ### Via Python API You can invoke the generator programmatically within build scripts or CI pipelines: ```python from pathlib import Path from dartfx.cdif.codegen import generate_all # Execute full generation pipeline generated_files: list[Path] = generate_all( cdif_root="/path/to/git-cdif", output_dir="src/dartfx/cdif/models", ) for file_path in generated_files: print(f"Generated: {file_path}") ```