# Compiler and extension reference

`plumb gen` compiles an ontology and its SHACL shapes into a deterministic
Python package. For a step-by-step walk-through, see
[Write and compile a domain package](../how-to/create-a-domain-package.md).

## Command line

```bash
# compile a local ontology file
plumb gen --file pumps.ttl --name Pumps --out pumps

# fetch by IRI: ontoenv resolves and merges the owl:imports closure
plumb gen --iri https://example.org/ontology/pumps --name Pumps --out pumps

# merge extra graphs, such as shapes published separately
plumb gen --file core.ttl --extra shapes.ttl --name Pumps --out pumps
```

`--source` records provenance metadata; `--no-overlay` skips built-in UX
overlays.

Each generated package directory contains:

- `__init__.py` — generated classes, property schemas, and `REGISTRY`,
- `enums.py` — enumeration constants (when the ontology defines an enum root),
- `_shapes.ttl` — exact input shapes graph (loaded lazily by `validate()`
  and `export_ontology()`),
- `_symbols.json` — dependency metadata for linking extensions without
  importing base Python code,
- `_support.json` — per-constraint enforcement and binding diagnostics, and
- `_generated.json` — file ownership manifest used to clean stale files on
  regeneration.

### Reviewing upgrades with `plumb diff`

Compare a saved baseline package directory against a regenerated one without
importing either package:

```bash
plumb diff saved-pumps pumps
plumb diff saved-pumps pumps --json > pumps-upgrade.json
plumb diff saved-pumps pumps --check
```

`plumb diff` separates contract changes from source, compiler, and
dependency provenance changes. With `--check`, it exits with status `1` if
any constraint present in both versions lost constructor, runtime, or solver
enforcement (`make regen` runs this check automatically before publishing).

## Extension annotations

An extension ontology declares its base package in RDF:

```turtle
@prefix ex: <urn:example:pumps#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix codegen: <https://watermetadata.org/plumb/codegen#> .

ex: a owl:Ontology ;
    owl:imports <https://watermetadata.org/ontology/watr> ;
    codegen:baseModule "plumb.watr" .
```

| Annotation | Purpose |
| --- | --- |
| `codegen:baseModule` | Installed Python package providing the base classes |
| `codegen:projection codegen:PropertySchema` | Export a SHACL `NodeShape` as a `PropertySchema` dataclass |
| `codegen:pythonName` | Explicit Python name for a class or field |
| `codegen:localName` | RDF local name for a property, independent of its Python keyword |

Annotations select Python names and projections; all domain rules remain
standard OWL and SHACL.

## OWL and SHACL → Python mapping

| Ontology / SHACL construct | Generated Python |
| --- | --- |
| `owl:Class` / `rdfs:Class` | `Entity` subclass |
| `rdfs:subClassOf` | Python inheritance + full `ancestor_iris` in `meta.is_a()` |
| `rdfs:label`, `skos:definition` / `rdfs:comment` | `.meta` metadata and docstrings |
| `rdfs:domain` / `schema:domainIncludes` | Descriptor attribute on domain class |
| `sh:minCount >= 1` | Required constructor keyword argument (except cycles & class defaults) |
| `sh:maxCount 1` | Scalar attribute (`RelOne`, `Lit`, `EnumOne`, `TermOne`, `ValueOne`); otherwise live collection (`Rel`, `EnumSet`) |
| `sh:class`, `sh:datatype`, `rdfs:range` | Type annotation + runtime range/datatype check |
| `sh:hasValue` | Inserted at construction and protected on mutation |
| `sh:defaultValue` | Replaceable default at construction |
| `sh:in` | Finite allowed choices enforced on mutation |
| `owl:inverseOf` / `s223:inverseOf` | Inverse attribute kept in sync in memory |
| `owl:equivalentProperty` | Canonicalized to the ontology's primary namespace |

An extension class has one constructive parent (either from the base package
or another class in the same extension). Contradictory bounds, defaults, or
inherited choices fail at compile time. Loading a saved graph via
`Model.from_graph()` preserves data as written and never injects defaults.

## Named connection points

A named point is a qualified property shape over `s223:hasConnectionPoint`
with:

- `sh:name` (the Python attribute name, e.g. `inlet` or `sludge`),
- an inlet, outlet, or bidirectional `sh:class`,
- an exact `sh:hasValue` medium and equal positive `sh:qualifiedMinCount`
  and `sh:qualifiedMaxCount`, and
- distinguishing facts (such as a fixed `rdfs:label`) when multiple points
  share a direction and medium.

A single point (`count == 1`) compiles to a `PointRef`; a group (`count > 1`)
compiles to a `PointGroupRef`. Nested `sh:and`, `sh:or`, and `sh:xone`
connection layouts are preserved for the Z3 solver.

## Property schemas

Mark a `sh:NodeShape` with `codegen:projection codegen:PropertySchema`. Each
field is a `s223:hasProperty` shape with a named `sh:qualifiedValueShape`
IRI, qualified min/max count of `1`, and `sh:name`.

| Shape constraint | Field behavior |
| --- | --- |
| `xsd:double`, `xsd:float`, `xsd:decimal` | Accepts a Python number or `QuantityAmount` |
| `sh:defaultValue` on `hasValue` | Default value (otherwise required) |
| `sh:minInclusive`, `sh:maxInclusive`, `sh:in` | Checked on construction |
| `sh:defaultValue` on `hasUnit` | Default unit for bare numbers |
| `sh:in` on `hasUnit` | Permitted units for `QuantityAmount` |
| `sh:hasValue` on `hasUnit` | Fixed unit |
| `rdfs:label` (`sh:hasValue`) | Preserved label distinguishing fields of the same kind |
| `skos:notation` | Displayed by `Schema.describe()` (e.g. `S_NH4`) |

Units are verified against QUDT dimension vectors without implicit unit
conversion.

## Naming rules

- **Classes** keep their IRI local name (`Air_Handling_Unit`).
- **Properties** convert camelCase to snake_case (`hasPoint` → `has_point`),
  except four high-frequency S223 point predicates: `hasMedium` → `medium`,
  `isConnectionPointOf` → `owner`, `connectsThrough` → `connection`, and
  `pairedConnectionPoint` → `paired_with`.
- **Reserved names** owned by `Entity` (including `name`, `type`, `label`,
  `comment`, `meta`, `contains`, `ports`, `sensor`, `actuator`, `quantity`,
  `walk`, `find`, ...) or Python keywords receive a trailing `_`.
- **Collisions** across IRIs receive `_2`, `_3`, ... in deterministic order
  (deprecated terms are suffixed before current ones, and the ontology's
  primary namespace keeps the unsuffixed name).
- **Enumerations** live under `enums.values` as flat names (`Fluid_Water`)
  and under branch attributes (`enums.Substance.Medium.Mix.Fluid.Water`).

## Compiler boundaries

The compiler projects the constructive subset of SHACL into Python; it is
not a general SHACL-SPARQL engine. Complex property paths, non-connection
disjunctions, and SPARQL rules remain enforced by `validate()` using the
exact bundled `_shapes.ttl`.
