dfcad

package module
v0.0.0-...-367a477 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 31 Imported by: 0

README

dfcad

A data-first CAD engine: a declarative entity graph in text, queried and edited with provenance and error budgets intact.

Status: under construction. This README describes the engine's scope — the boundary it is being built to, and the boundary it is not allowed to cross. Most of what follows is not implemented yet.

What it does

A model is a set of plain text files under version control. The engine works on that model in four ways:

  • Loads a declarative entity graph from text, reporting every problem it finds in one pass with a file, line and column for each.
  • Answers questions about the graph — what exists, what it is, what it contains, what it touches — and returns the provenance and the error budget behind every answer, not just the number.
  • Edits the graph safely. The command line interface is the primary write path: it validates first, writes canonical form, and refuses a change that would produce a graph that fails to load. Nothing is ever partially written.
  • Checks assertions over the graph, so that the properties a model is supposed to hold are enforced in CI rather than remembered.

Changing a model

Every change goes through a command, and every command which changes the model is also an operation of an operation file, so a batch of them is applied as one change with apply:

Command Writes
add-node a semantic node
add-vertex a corner, with where it is and how that is known
add-edge a connection between two corners
set-backing what physically realises an edge, replacing what it named before
add-loop an ordered ring of edges
set-edges the ordered ring a loop runs through, replacing the one it named before
scaffold-loop a room's corners, walls and outline in one change
relate what a node is inside, grouped with and bounded by
classify-type how a scheme outside this model names a type
set-label what a thing is called, and nothing else
retire that a thing stopped existing
add-claim a measured value on a thing, with its provenance
supersede a corrected value, retracting the old one
deprecate-claim that a claim was retracted
add-assertion a named check the one thing it is written on has to satisfy

An invariant — a check every instance of a type has to satisfy — is registry data rather than a change to the model, and stays a hand edit to the registry file declaring the type.

The closed sets

Two vocabularies are compiled into the engine, and they are closed. Nothing else is.

Set Members
kind Zone, Site, Building, Storey, Space, Element, Interface
geometry point, line, area, surface, solid, or absent

Two further sets are fixed by the engine for the same reason:

  • Node families. Semantic nodes carry a kind and a type. Geometric nodes — vertex, edge, loop — carry neither, only a frame, claims and references to each other.
  • Checks. Assertions are named, parameterised checks drawn from a closed registry, not an expression language. Adding a check is an engine change.

These sets are small, and they are meant to stay that way. Growing one is a deliberate decision recorded in docs/decisions/, not a routine change.

What arrives as registry data

Everything domain-specific is supplied by the consuming repository as registry files that the engine loads and validates before it interprets anything else:

Registry Declares
Types Each type with its permitted kind, permitted geometry and a description
Claim predicates Each predicate with its unit, value shape and validation rules
Frames Each frame with its linear unit and its parent
Id namespaces The permitted namespaces for namespace:local identifiers
Tolerances Named tolerances with values and units
File routing Which file a newly authored node is written to, by namespace, kind and type

The engine attaches no meaning to any of these beyond the structure it checks. A wall, a circuit, a setback rule and a survey monument are all registry entries somewhere else; none of them appears in this repository.

Non-goals

The engine deliberately does not contain:

  • No domain vocabulary. No type, predicate, frame, namespace or tolerance specific to buildings, land, or any other subject matter. Vocabulary growth is only reviewable when it lives in a file whose diff someone reads, and that file belongs to the data repository.
  • No database. The source tree is the store. Derived values are build outputs keyed by the digest of the source, never written back into the authored files.
  • No daemon. Every invocation is a process that starts, does its work and exits.
  • No network transport. No server, no client, no wire protocol. The engine reads files and writes files.

Where does a change belong?

The change... Belongs in
Adds a type, predicate, frame, namespace, tolerance or routing rule the data repo
Names a specific building component, discipline or code rule the data repo
Adjusts a numeric tolerance the data repo
Adds a query, an output field or a CLI subcommand here
Changes how claims resolve or how uncertainty propagates here
Adds a named check that any model could use here
Adds a member to kind or geometry here, via an ADR

The rule behind the table: if the change would be meaningless to a repository modelling a different subject, it is not an engine change.

Documentation

  • docs/decisions/ — the architecture decision records. Each states the decision, its reasoning, what it costs and what would reverse it. The identity, claim and uncertainty decisions are recorded, as are the engine-boundary, CLI and authoring ones.
  • docs/machine-output.md — the command line interface's output contract: what is on stdout, what is on stderr, the shape of each command's JSON object and the rule by which that shape may change, and what each exit code means.
  • docs/versioning.md — the three versions this repository carries, which changes move which of them, and the git tag convention a release is cut with. The convention is constrained by what the standard pipeline does with a tag rather than chosen freely, and the table showing which schemes survive that is the part worth reading before tagging anything.
  • docs/publishing.md — the published image: where it is, what the tags mean, what to pin, what the pipeline attaches to each digest, and how long a branch build stays pullable. It describes what the standard pipeline does with a ref rather than a convention layered on top of it.
  • docs/siting-worked-example.md — one question, does this building fit on this plot?, followed from the claims it is answered from through the frame chain and the overlay to the error budget it comes back with, and asked again after a re-survey. It is where the systematic terms earn their keep: the arithmetic is spelled out beside the naive all-quadrature figure it must not equal.
  • docs/surface-accuracy-gate.md — a derived surface put to a decision: does this patio fall enough to drain?, with the accuracy the decision needs stated before the surface was built and the achieved accuracy measured against it. It is where the propagation through a surface is spelled out — the shots in quadrature, the base station added once and cancelling out of a difference, the ground between the shots charged by distance — and it records a miss: the requirement is missed by a factor of four, and survey density is not the reason.
  • docs/token-budget.md — what the discovery path costs an agent, measured with a real tokenizer against a representative model, and how that compares with reading the files instead. It is regenerated from the measurement rather than written down, so the claim in the repository is always the current one.
  • docs/observation-file.md — the format field data is recorded in: one record per line, appended as it is collected and never edited, with a retirement being a later record naming the one it supersedes. It states the line schema field by field, what each precision figure means, and the append-only invariant a validator checks between two revisions.
  • SPEC.md — the entity syntax: the legal tagged forms, their arity and ordering, and the canonical printing of each. It is the definition of the format; the loader is implemented against it, not the other way round.
  • .github/gate/README.md — the model gate: dfcad fmt --check, dfcad check and dfcad review run over a model root on every pull request, so a branch whose model is broken — or whose change to the model needs an explanation — is visibly failing. It is written to be copied — a consuming data repository runs the CLI over its own entities, and this is that half of CI.

Install

The command line tool is a container image, and that is the one install path. There is no binary download.

docker pull ghcr.io/z5labs/dfcad:v1.2.3

The model is a directory of text files, so mount it and ask a question:

$ docker run --rm -v "$PWD:/model:ro" ghcr.io/z5labs/dfcad:v1.2.3 \
    resolve --root /model site:S-103 area | jq -c '{value, accuracy}'
{"value":{"shape":"scalar","unit":"m2","scalar":32},"accuracy":[{"kind":"independent","magnitude":0.08,"unit":"m2"}]}

Every read also answers over a change before it is made. --assume names an operation file — the batch apply would write — and the read answers over the model that batch would produce, writing nothing and locking nothing, so it runs over a read-only mount as readily as the question above:

docker run --rm -v "$PWD:/model:ro" ghcr.io/z5labs/dfcad:v1.2.3 \
    check --root /model --assume into-setback.json

The answer carries assumed, naming the batch and the digests of the tree read and of the tree it would produce; docs/machine-output.md has the member.

Pin the digest rather than the tag in anything automated — ghcr.io/z5labs/dfcad@sha256:…. Digests are authoritative and tags are advisory; there is no latest. docs/publishing.md has the tag convention, how long a build stays pullable, and what is attached to each published digest.

As a library, it is an ordinary Go module:

go get github.com/z5labs/dfcad

License

MIT

Documentation

Overview

Package dfcad is a data-first CAD engine.

A model is a declarative entity graph held in plain text files. The engine loads that graph, answers questions about it with the provenance and error budget behind every answer, edits it without losing either, and checks assertions over it.

Scope

The engine is generic. The only vocabulary compiled in is a small closed set — node kinds and geometry forms. Everything domain specific arrives as registry data supplied by the consuming repository: types, claim predicates, frames, id namespaces, tolerances and the rules saying which file a new node is written to. A domain concept therefore never needs a change here, which is what keeps vocabulary growth reviewable.

There is no database, no daemon and no network transport. The library is paired with a command line interface under cmd/dfcad, which is the intended entry point for scripts, CI and agents.

Loading

LoadGraph is the entry point. It reads a directory of files into one validated Graph — the vocabulary the model declares, both families of nodes, the claims written on them, the frames those claims measure and the boundaries which join the two families — in a single pass which reports every problem it finds rather than stopping at the first.

The passes it composes are exported as well, because a caller which wants one of them should not have to load six: LoadRegistry, LoadNodes, LoadTopology, LoadClaims, ResolveFrames and ResolveBoundaries. What the graph adds over calling them in order is the checks no single pass can make, and not having to know what that order is.

Observations

Field data is not an entity file. An afternoon with a rover produces thousands of shots, and a record was produced by an instrument, at a time, under conditions — so observations sit outside the entity files, one record per line, appended as they are collected and never edited afterwards. Editing one in place destroys the thing which made it evidence: after the edit there is no way to tell, from the file, that the number ever said anything else.

LoadObservations reads a tree of them and validates it against the registry; ParseObservations reads one file without a registry, which is the lexis of a line rather than the soundness of a log. What comes back is an ObservationLog, whose ObservationLog.Current is every Observation no ObservationRetirement names. A retirement removes nothing: the retired record stays where it was written and still says exactly what the instrument said it said.

ValidateAppendOnly is the invariant which needs two revisions rather than one file — every line the older revision had, present and unchanged at the same line number in the newer one. Lines beyond the end of the older revision are an append, which is the only legal change. It knows nothing about git: where the two byte sequences came from is the caller's question.

Which shots fall inside a region is derived and is never stored. Graph.ObservationsWithin computes it from the coordinates on the records and the boundary of the region, over the whole model's corpus (Graph.AllObservations), so carving a new bed out of the back garden gives it the shots inside it with no edit to an observation file anywhere. What *is* stored is the other relationship: an entity naming the file a shot was written in is a deliberate statement that this evidence backs this thing, and Membership.Linked is which of the two a result is.

A record written in another frame is carried across before it is tested, and what the transform cost widens the band the boundary is judged against. A shot nearer the boundary than the survey can place it is reported rather than assigned to a side, which is why Members.Inside and Members.Ambiguous are separate slices and not one carrying a flag.

The ground itself is derived from those shots the same way. Graph.SurfaceWithin interpolates a Surface over the observations inside a region — SurfaceTIN triangulating them, SurfaceIDW weighting them by distance — and Surface.Elevation answers what the ground does at a point nobody stood on. It is a build output: it is kept in the derived cache under BuildDir and written into no source, so deleting that cache costs time and nothing else.

Two things travel with it because they are what make it checkable. Surface.Method and Surface.Parameters are how it was arrived at, since two interpolations of one set of points are two different answers, and Surface.Observations is every record behind it. Its edge is the shots rather than the region: a point beyond the convex hull of them is reported as outside and never extrapolated to.

Every level comes back with the budget it was propagated from (Elevation.Budget), under the same two rules a claim's budget follows: the shots' own errors in quadrature under the weights the interpolation gave them, and a term a whole afternoon shares — a base station, the control a transform was fitted to — added linearly and counted once. Where the derivation states a SurfaceDerivation.Roughness, the ground between the shots is charged for too, growing with the distance from the nearest of them; where it does not, Elevation.Complete is false and the figure is a floor.

Surface.Fall is the difference of two levels, and it is a first-class answer because the subtraction is where the correlation lives: what the two ends share is in both by the same amount and so cancels out of the difference. A caller combining two levels in quadrature would report a drainage fall as several times less certain than it is. docs/surface-accuracy-gate.md is that put to a decision with a stated accuracy requirement, and what it found.

docs/observation-file.md is the specification: the line schema field by field, what each precision figure means and which uncertainty convention it follows, and the two shapes of ambiguous timestamp the format refuses.

Writing

Begin is the entry point for changing a model. A Tx loads the whole graph, holds every file of it in memory, applies mutations to those trees and — at Tx.Commit — interprets the result as though it had already been written. A change which would produce a model that does not load is refused with the diagnostics the load would have raised, and nothing reaches the filesystem; a change which validates is written in canonical form, atomically, and all of its files or none of them.

Which file a new node goes in is Registry.Destination, from the routing rules the registry declares, or Override where a command was told outright. Deciding it is separate from writing it so that the destination can be reported before anything is written, and so that a node the rules do not place is refused rather than filed somewhere plausible.

The changes themselves are on the transaction: Tx.AddNode writes a new semantic node with every axis checked against the registry first, Tx.SetLabel changes what a thing is called and nothing else, and Tx.Retire records that a thing stopped existing. Retiring is not deleting — the id stays in the graph and is never issued again, so a reference written years ago resolves either to the thing it always named or to a node which says what happened to it.

Tx.AddClaim attaches a value and the evidence for it to a thing, checked against what the registry declares the predicate takes. A value is never edited: Tx.Supersede corrects one by writing the new claim and retracting the old in the same change, and Tx.DeprecateClaim retracts a claim in favour of one already written. A retraction requires a replacement, which is what keeps deprecating from being deleting, and the retracted claim keeps everything it said — the record of why the number changed is the thing being kept. None of the three ever writes over what a claim states. A frame whose `transform` names the claim being retracted is re-pointed at the replacement in the same change, because a frame reads exactly the claim it names and never follows a supersession from it.

What none of them refuses but all of them report is a Notice: a claim which carries no accuracy and so can never win resolution, a claim which disagrees with one already written, and a retraction which leaves nothing asserted about a subject and predicate at all. Each is a legitimate state for a model to be in, and none is a thing to find out about later.

Tx.SetBacking states what an edge is physically realised by, replacing every element it named before, so a wall built after its edge was drawn and a wall demolished are each one change. Whether the edge is a physical boundary is computed from what it names and stored nowhere, so nothing else is edited.

Tx.SetEdges restates the ordered ring a loop is traversed through, replacing the whole list rather than patching it, because the order is the data. Every node bounded by the loop reads the new ring with no edit of its own. Whether the ring closes is not judged at commit, as it is not for Tx.AddLoop: the `boundary-loops-close` check reports a ring which does not.

Tx.AddAssertion writes a check on the one thing it constrains, refused before anything is written by the validation ValidateAssertion runs at load and at Tx.Commit by the passes which need the whole model. What must hold of every instance of a type is the type's invariant, which is registry data and is written by hand.

It is the mechanism every authoring command is built on rather than a command itself. See docs/decisions/0015-the-cli-is-the-primary-write-path.md for why the command line interface writes at all, docs/decisions/0016-writes-are-all-or-nothing.md for why a write is refused rather than reported, and docs/decisions/0002-immutable-id-mutable-label.md for why a label is free to change and an id is not.

Checks

An assertion names a check and supplies its parameters, and contains nothing else: no operators, no traversal and no user-defined logic. The checks it may name are a closed registry compiled into the engine, which Checks lists and LookupCheck reads one entry of. Each declares what it constrains, the parameters it takes and the sort of datum each parameter is, so what an assertion constrains can be answered by reading it rather than by evaluating it against a model.

ValidateAssertion is that reading. It resolves the check name and every parameter — including the ones naming a type, a predicate, a frame or a tolerance, which are resolved against the model's own registry — at load, which is where a misspelled check name and a parameter of the wrong sort are reported. A tolerance is always a name from the registry: a numeric literal written where one belongs is refused, so how close is close enough stays one decision in one place.

Adding a check is a change to the engine — a type implementing Check and a line in the registered set — rather than something a model file can do. See docs/decisions/0011-assertions-are-named-parameterised-checks.md for why the registry is closed, and docs/decisions/0012-tolerances-are-registry-data.md for why no check carries a number.

What the set covers is the structural invariants a model has to hold from its first file: that the loops bounding a thing close, that what a node contains covers no ground twice and adds up to the whole, that what an edge says physically realises it is a node the model holds, that expressing something in another frame stays inside a stated error budget, that a shape stays out of a zone it is to keep clear of, and that a measurement written down still matches the shape it describes. Each takes its tolerance by name from the registry, and each which measures is told which predicate carries a position, because neither of those is the engine's to assume. Beside them are the rules about what was said and whether what it names still stands: that a subject carries a claim under a predicate which has not been retracted, that the node something is within and the zones it belongs to have not been retired while it stands, and that an edge's two ends are not one corner written twice. Each of those decides something the load does not: the load checks that a reference names a node of the right kind, and a retired node is still one.

Every check the registry declares has an implementation. One which declared itself and implemented nothing would bind, list and validate exactly as one which does and decide nothing, which Rule.Runs is how to tell apart — and "nothing decided this" is a different answer from "this holds", which is why a test over the registry refuses to let the engine ship one.

The last of them is the one the rest of the engine cannot state on its own. The conflict register compares claims with each other and has nothing to say about a claim disagreeing with the geometry, because the geometry is not a claim — so a node carrying an area whose boundary computes to something else loads, formats, resolves and passes every other rule the model states. `claim-agrees-with-geometry` is that comparison, and what makes it a rule rather than a subtraction is uncertainty: two figures which differ by less than their combined uncertainty do not disagree, so the declared discrepancy is the floor under the comparison rather than the whole of it. It is written on a node, where the shape is the one its boundary encloses or the line it is drawn as, and on an edge, where it is the distance between the two corners the edge runs between — which is the most directly checkable measurement the format can express, and the one an outline never reaches.

Bands

A tolerance treated as a floor is a tolerance whose declared value is not what decided the answer. The widening is right — a claim cannot be held to a precision the geometry does not have — and it is large: an area's band is the corners' accuracy multiplied by the length of the boundary, so half a square foot declared over a room can be applied as eight. Left unsaid, that makes a passing run unfalsifiable. A rule written as "the boundary agrees with the appraisal to within half a square foot" is not testing that, and nothing in the answer says which figure it did test.

So every check which widens says so. Band is what one comparison was decided against — the tolerance named and its value, the figure applied, the difference judged, and each accuracy which widened it with the sensitivity that carried it into the unit compared — and Rules.Run reports one per comparison as an AppliedBand, on the rules which passed as much as on the ones which failed. Band.Decisive is what separates a pass which needed the widening from a pass within the tolerance as written; those are two different states of a model, and only one of them is a criterion which held. Judge is the interface a check implements to report them.

Assertions

An assertion is a check written on one thing — a node, a vertex, an edge or a loop — and it constrains that thing. SemanticNode.Assertions and its siblings are the ones written on it, as written; Graph.Assertions is the same list resolved against the check registry, Graph.AllAssertions is every one in the model and Graph.CheckAssertions runs them.

ResolveAssertions is the half of validating one that needs the whole model, and it runs as part of LoadGraph. A check that cannot examine the thing the assertion was written on is refused, because a rule with nothing to look at passes forever rather than failing. Every id an assertion names is checked to resolve. And an assertion that restates a value the claims already carry is refused: a claim is where a value is recorded, with the source, the method and the date it came from, and repeating it is a second source of truth that goes on saying what it says the day the claim is superseded. What that rule does and does not catch is ResolveAssertions.

Invariants

A type registry entry may declare invariants, which are checks written once on the type and applied to every instance of it. Graph.Invariants is what bears on one instance and Graph.AllInvariants is every binding in the model. Nothing is stored on an instance, so a rule declared today reaches a node written tomorrow without either being touched — which is the point of stating it on the type rather than copying it onto a hundred and fifty nodes.

Invariants are not inherited. A node's are the ones its own type declares: none descends from the node containing it, from a zone it belongs to or from another type, because the type registry declares no hierarchy. What is filtered is applicability — a check declares which kinds and which geometry forms it can examine, an invariant naming one that could examine no instance of the type is refused when the registry loads, and one that can examine some of them binds to those.

Graph.CheckInvariants runs them and returns a Violation for each way an instance does not satisfy one. A violation names the instance, the check, the parameters it was evaluated with and the registry file and line that declared the rule, so a failure of a rule stated once leads back to the one place it is written. A check declaring itself and implementing nothing binds and lists exactly as one that does and runs nothing, which InvariantBinding.Runnable is how to tell apart.

Running them together

A gate does not ask the two questions separately. Graph.Rules is every rule the model states as one list — each type's invariants bound to its instances, then each assertion bound to the thing it is written on — and Rules.Run runs them and returns a CheckRun: how many rules there were, how many ran, how many passed and failed, a Violation for each way one was not satisfied, and an AppliedBand for each comparison decided against a widened tolerance. RuleFilter narrows that to one thing, one type or one check, which is what a gate somebody is iterating against runs.

The order is deterministic and is the order the model was read in, so a listing of what would run and a report of what did both diff against the last run's. A rule whose check declares itself and has no implementation is bound, listed and counted apart from the ones that ran, because "this rule holds" and "nothing has been written to decide whether it holds" are different answers; Rule.Runs is how to tell them apart.

Measuring

How big a room is, is computed from its boundary and is never read from a field. Topology.MeasureRegion gives the area, the perimeter, the centroid and the axis-aligned bounding box of a semantic node from the loops it references; Topology.MeasureLoop, Topology.MeasureEdge and Topology.MeasureVertex do the same one, two and three levels down. Nothing any of them produces is written back, so a measurement cannot disagree with the geometry it describes: move a corner and the answer moves, with no edit which says so and no recorded number left behind to go stale (see docs/decisions/0009-derived-values-are-never-written-back.md).

A node whose declared geometry is `line` is read as open runs rather than as rings. Its loops are the same authoring and are refused for the same four things — an edge walked twice, a corner where three edges meet, a shape in two pieces, an order the chain is not walked in — and are not asked to close: a door, a railing and a wall run each begin somewhere and end somewhere else. What one of them measures is a length and a bounding box, with no area and no centroid, and Topology.AssembleRun is Topology.Assemble with that one requirement dropped.

A node whose declared geometry is `point` is read from the position claimed of the node itself, under the same predicate a corner's position is claimed under. A panel, a receptacle, a condenser and a survey monument are each a thing whose only interesting geometry is where it is, and a boundary authored for one would be dimensions nobody measured. What it measures is what a corner measures — the point as the centroid, a box of no extent, no length and no area — with the accuracy of the claim which placed it.

Graph.Measure is the whole of that in one call, dispatching on whichever family an id names, and Graph.Corners with Graph.Located is what a survey for it has to carry. They are here so that a caller asking how big something is does not write the dispatch itself: which of the four calls a subject takes, and which corners the answer rests on, are properties of the model rather than of the question, and a second implementation of them is a second set of answers. `dfcad measure` is the same pair on the command line.

A Survey is what they are computed against — where the vertices are, the claims which put them there, the tolerance rings are judged against, and the registry. Which predicate carries a position is vocabulary the consuming repository owns, so the positions are resolved by the caller and handed in; Survey.Place takes a Resolution and fills both halves at once. Every figure comes back in the unit of the frame the thing is declared in, an area in the square of it, and with the Budget of the position claims it rests on.

Each figure also comes back with whether it could be computed at all. A ring which does not close, one which crosses itself, one whose corners are not in one plane and one whose corners are collinear each produce a diagnostic and no area — never a plausible-looking number, which for the first three is exactly what a projection or a signed sum would give. A region bounded by more than one ring is measured by nesting, so a courtyard subtracts without anything in the model having to declare which loop is the outside one.

Which ring is inside which is a property of the two shapes and not of the corner either loop happened to be written down from: the answer is taken over the whole of a ring rather than at one point of it, so rotating a loop's edge list or walking it the other way round leaves every figure unchanged, and two rectangles abutting along a wall union rather than cancel. It is the same nesting Topology.RegionOf orients its rings by, which is what stops a plan and a measurement of one node disagreeing about its area. Two rings which cross are neither nested nor beside one another, so the rule has nothing to say about them and the pair is named rather than summed — and that holds whether or not they share a corner or part of a side. Two rings are beside one another only where they have no area in common, and one is inside another only where it has none outside it, which is judged over the areas themselves and not only at the corners: an L-shaped counter drawn as two runs overlapping in its inside corner is refused, not measured with that corner counted twice.

Arcs and tessellation

An edge which curves is stored as the curve it is. An Arc states where the centre of the circle is and one point the wall passes through, and both are claims like any other — resolved by the caller under whichever predicates the consuming repository registers, and handed in through Survey.Bend beside the positions. No form, no kind and nothing compiled into this package learns a name when an arc arrives.

Everything is then measured from the circle. The length of a curved wall is the length of the curve, the area of a ring which bends is its polygon of chords plus the circular segment over each arc, the centroid is where that combined area is centred and the box is where the curve reaches rather than where its two ends do. None of it is a sum over segments, so the sag of a curve is in the answer at full precision and no resolution is chosen on a caller's behalf.

Tessellation is therefore a thing you ask for. Topology.TessellateEdge and Topology.TessellateLoop take the name of a chord tolerance the registry declares and return a Tessellation carrying both the segments and the tolerance they were drawn to, so what a drawing is good for can be read off it. The same arc and the same tolerance give the same points every time. What will not happen is a curve becoming segments on the way to an answer nobody asked to have drawn: an overlay is computed over straight edges, so Topology.RegionOf refuses a curved boundary until the survey names the tolerance it may be drawn to (Survey.Chord), and the Region which comes back then says what it was drawn to (Region.ChordTolerance) and how far the drawing fell from the curve (Region.Deviation). The one place a measurement needs the same is the even-odd nesting of several rings, which is decided at the boundary each ring was drawn as and cannot be where a bulge reaches past one; the figures it nests are still the arcs', exact whatever the chord was.

The other half of that is Graph.UnreadArcs, which is what stops a chorded boundary being a silent one. A caller who never named the vocabulary an arc is written under has no way to tell a model of straight walls from one whose walls curve, and reads the second as the first — reporting the chord between two corners as though it were the wall, which can be out by a third. What is recognisable without the vocabulary is the shape of the claim: an edge has no position of its own, so a position claimed on one is a curve or it is nothing. That is what it reports, as a warning naming the edge and the predicates to name, beside whichever answer was computed.

A rule is held to the same. Every check which reads a shape takes the vocabulary as optional parameters — (arc-centre ...) and (arc-through ...), and (chord ...) where it decides by an overlay — and reads the curve where they are named. Where they are not, Rule.Chorded names each edge the rule reads straight, before a run as well as after, and a CheckRun carries them as ChordedEdge entries on a pass as much as on a failure; a violation of such a rule says in its own message that the figure it compared was the chord's. Where a rule drew a curve to a chord, the run says what to and the deviation that achieved (DrawnCurve).

Topology.TessellateRegion is the same for a whole semantic node, and is what an export goes through: it draws every ring bounding the node at once and returns a RegionTessellation whose outer rings and holes are nested by the same even-odd rule a measurement uses, wound the same way round, and readable as an ordinary Region. Doing it a ring at a time is not the same thing, because which ring is a hole is a property of the region and not of any ring in it. A boundary with nothing curved in it is drawn to itself, unchanged, so a caller has one path rather than a curved one and a straight one. An arc which the named tolerance would take more segments to follow than anything can use is refused, naming the edge, rather than truncated.

Offsetting and overlaying

How big something is answers one question. Whether it fits answers the other, and that one needs the shapes overlaid rather than measured. Topology.RegionOf reads what a node covers out of the loops bounding it as a Region, and Region.Buffer, Region.Union, Region.Intersect, Region.Difference and Region.Containment are the operations over it. All of it runs in process: a setback or a clearance is answerable with no kernel, no spatial database and nothing to stand up first.

A result is a set of [Piece]s, each a ring with the rings taken out of it, because an operation can leave several pieces which do not touch and can leave one with a hole in it. Region.Buffer takes the distance either way round — outwards for a setback, inwards for a clearance — from one construction, so an inward offset which eats the shape returns a region covering nothing rather than the inside-out shape offsetting each edge on its own would give.

A node drawn as a line reads back as a region with no pieces and a boundary: it covers nothing, so there is no area for an operation to be computed over, and every straight run of it names the edge it was written as, the way it was walked and the two corners it runs between — which is the attribution a ring's boundary carries and is what a sheet draws the run from. A node drawn as a point reads back the same way with a Region.Location instead: it covers nothing and it is somewhere, which is what a sheet places a symbol at and what a map writes as a point feature. Covering nothing is a state of that answer and not a refusal, which is what keeps one open run in a storey from refusing the plan of the storey or the map of the model.

The same refusals apply as everywhere else in this package, and for the same reasons. A ring which crosses itself or encloses nothing is a diagnostic and no region. Two regions in different frames are refused rather than combined — Region.In is the explicit way across, and it carries the accuracy of the transform with it — and so are two which do not lie in one plane, because a room on the storey above is inside this one seen from above and is not inside it. Coincidence and the resolution of a rounded corner are judged against the tolerance the registry declares, never against a number compiled in here (see docs/decisions/0012-tolerances-are-registry-data.md). Every answer carries the Budget of the claims behind both operands, so an overlap knows how well the corners which decided it were known.

Region.Containment is six states rather than a yes and a no, because "not inside" covers a region which is nowhere near, one which straddles the boundary and one which is inside and touching. Two regions sharing a wall are ContainmentTouching and never ContainmentOverlapping: a party wall has no area, and reporting it as an overlap would turn every pair of adjacent rooms into a conflict.

Attributing a boundary

A ring of coordinates can be drawn and cannot be attributed. Region.Segments is the other half of the answer: one BoundarySegment per straight run of the boundary, saying which ring it belongs to, which two corners it runs between, which edge produced it and which way round the loop traversed that edge. With it a segment can be named as the party wall, an element backing an edge reaches the run that edge produced, and a claim written on an edge carries through to the segment it is about — none of which a polygon on its own supports, and all of which a consumer would otherwise re-derive by matching coordinates.

BoundarySegment.Origin is what keeps the attribution honest. A run of a region read from the model is the edge itself (SegmentOriginEdge); a run of a drawn boundary is one chord standing in for part of the arc an edge bends along (SegmentOriginArc), which names that edge and is not it; and a run an operation produced (SegmentOriginOperation) names no edge at all, because the boundary of an intersection runs partly along each operand and partly along where they cross and there is no edge which is the second kind.

The buildable region

Topology.BuildableOf is the derivation those operations exist for: the area left inside a boundary once the setback claimed on each of its edges has been taken off it, as a Buildable carrying the parcel, the region left and the Setback applied to each edge.

It is derived and never authored, and that matters more here than anywhere else in this package. A buildable region written down as a polygon of its own is a second statement of where a permanent structure may go, and the day a setback claim changes it is the wrong one (see docs/decisions/0009-derived-values-are-never-written-back.md).

A setback is a claim on the edge it governs, so different setbacks per edge — front, rear, flank — need nothing from the engine but the predicate they were written under: which edge is which is project vocabulary and never lands here (see docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md). An edge with no live claim under that predicate is a diagnostic naming that edge and no region, because reading the silence as nought would site a building up against a boundary nobody intended it to touch; an edge which really is not set back says so, as a claim with a value of nought. Setbacks which meet in the middle leave a region covering nothing, reported as a warning rather than as a failure, because that is the answer to the question. The Budget of the answer is accumulated over the position claims and the setback claims together, so a control point reached through both is counted once.

Reading a storey as a plan

Graph.PlanOf is the answer an annotated floor plan is drawn from: everything a spatial node contains, as rings, each named by the node it came from and each carrying the claims written on it and on the edges bounding it. It is a Plan of Outline values, and it is a query rather than an export — nothing is written anywhere, and everything in it is read out of the model every time it is asked for.

It knows nothing about paper. There is no scale here, no sheet size, no title block and nowhere a leader goes, and there never will be: those are decisions about a drawing, and the moment this package knows one of them it owns a drawing convention that every consuming project disagrees about.

Which claims come back is stated by the caller, as the predicates of an Annotations, with no default. That is the whole of the answer to "is this dimension worth drawing" — it is worth drawing if the caller asked for that predicate — and it is what keeps a domain judgement out of an engine which carries no vocabulary of its own (see docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md).

Which nodes come back can be narrowed too, by kind and by type, with a Selection passed to Graph.PlanOfSelected. It narrows what is reported and never what is walked, and it decides which rooms come back rather than how a room is drawn: an outline is the same in a selected plan as in the whole one.

Each claim comes back whole and carries its Anchor: an edge with its two vertices in the order the edge was authored, or the node with the rings bounding it. The pairing is what stops a renderer working out for itself which claim belongs to which pair of corners, which is the re-derivation Region.Segments exists to prevent one layer down.

Nothing is resolved. Two live claims disagreeing about one wall both come back under the same anchor, because which of them a sheet prints is a decision about the sheet; a retracted claim never comes back at all. The Budget of the plan is over the position claims behind the rings and not over the claims reported, because each of those is a separate statement about a separate quantity and carries its own accuracy.

Nothing the subject contains is dropped. A node the plan cannot draw comes back in Plan.Undrawn rather than being left out — with an UndrawnReason saying which of the two ways it was undrawable, and with the claims written on it — so Plan.Outlines and Plan.Undrawn account between them for every descendant of the subject. A circuit group has no edges and is ordinary; a ring which does not close is a defect the diagnostics locate; both are things somebody put inside that storey, and omitting either would report a sheet as complete which is missing a door. Every undrawable node degrades on its own: the rest of the storey is drawn whichever way it was undrawable, and whether the *run* succeeded is the separate question the diagnostics answer.

A measurement written as an edge which bounds nothing — a dimension string across a room, a span between two jambs — comes back in Plan.Measured as a MeasuredEdge when both its ends are corners the plan drew and it carries a claim the caller asked for. The corners place it rather than its frame, which is not a place, and its ends are those corners exactly as the outlines drew them.

Derived geometry, and where it is kept

Everything above is computed on demand and none of it is stored in the model. That is the whole of why an area cannot contradict the boundary it came from (see docs/decisions/0009-derived-values-are-never-written-back.md), and it is also why asking the same question of the same model twice pays for it twice.

Graph.Derive is the answer to the second half without giving up the first. It computes the derived geometry of a whole model — what each thing covers, its area, its perimeter, its centroid, its bounding box and which regions it lies inside — as a Footprints, and keeps it in a Cache which is a build output directory and never a source.

The cache cannot serve a stale answer, because the key is a Digest over the bytes of the source tree the geometry was derived from. A tree which changed anywhere has a different key and misses. There is no invalidation pass, no timestamp comparison and no dependency list to get wrong — the key *is* the invalidation. The two named decisions a derivation is not otherwise pinned by — the tolerance and the position predicate — are in the key as well, because a footprint judged against a different tolerance is a different answer.

It is advisory in the strongest sense: deleting it changes what a run reports by nothing at all and changes only how long the run takes. Two rules hold that up. An entry which does not verify — truncated, corrupt, written by another version, written under another key — is discarded and recomputed rather than raised, because failing a run over a damaged build output would make a disposable artefact load-bearing. And only a derivation which reported no diagnostic is stored, so the diagnostics a run reports never depend on what a cache happens to hold.

It is bounded by Cache.Prune, which keeps one digest and removes every other: a build which prunes with the digest it just derived against leaves exactly one generation, which is the working set. Removing the directory is always safe.

Membership here is derived rather than read. A courtyard is inside the floor plate around it because of where its corners are, whether or not anybody wrote the containment down, and Footprint.Within is that answer where Nodes.Within is the authored one. It is judged only between regions one operation could be run over — one frame, one tolerance, one plane — so two plates on different storeys are members of neither.

Artefacts, and the instant they carry

An exported artefact is a build output under the same rule: it is keyed by the digest of the tree it was derived from, written beneath the build directory and never into the authored tree, and byte-identical for identical input (see docs/decisions/0021-an-export-is-a-build-output-keyed-by-its-source-digest.md). Nothing may reach an exported byte which is not either covered by the digest or named in the artefact's key.

A clock is the usual way that promise is lost. Every exchange format worth targeting has a field defined as a creation or a modification time — a part 21 header's time stamp, a PDF's CreationDate, a container manifest's created — and filling one from the clock costs a line and makes every export of an unchanged model differ from the last for a reason which has nothing to do with the model.

DerivationEpoch is the single derivation of that instant, and every command whose product is a file reads it from there. It is a function of the source tree, which is why it takes the tree's Digest, and the function is constant: 1970-01-01T00:00:00Z, for every tree, including the one nothing could be read from. An obviously wrong constant is better than a convincing lie, and the provenance the field pretends to carry is carried properly instead, by stating the digest through whatever mechanism the target format has for it.

Epoch carries the encodings such formats demand — Epoch.ISO8601, Epoch.STEP, Epoch.PDF, Epoch.Seconds — so that adding a format is a method there rather than a layout string in an exporter, which is one character away from being a clock reading again.

ExportDir is where such an artefact lands, a sibling of CacheDir under the same build directory. The first exporter to use it is the IFC4 writer in github.com/z5labs/dfcad/ifc, which is a package of its own and imports nothing of this one: it knows IFC and part 21, the command which drives it knows which entity a Kind is, and neither knows the other's vocabulary ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)). DeriveGlobalID is what joins them — the derivation is this package's and the 22-character encoding is IFC's, so this package derives and that one encodes.

Reviewing a change

Every rule above constrains one revision. Some things are suspicious only as changes — a wall which quietly moved, a measurement retracted with nothing in its place, an id which is simply gone — and none of them can be seen without the revision the change was made against. Review is that question: two graphs in, a Finding out for each change which needs an explanation.

It is kept apart from assertions rather than folded into them, and neither is meant to grow into the other. An assertion says the model is wrong and can be evaluated on a fresh checkout; a finding says this change needs an explanation and cannot be evaluated at all without two revisions. A rule which needed the previous revision would be one nothing could run.

What each finding means is a Policy, which is data rather than a check per flag: DefaultPolicy fails on an id which disappeared and on a claim retracted with nothing behind it, and warns about a boundary which moved, because that last one is routinely legitimate. A change which genuinely re-surveyed a room is one somebody meant, and Policy.With is how to say so once rather than by not running the check at all. A finding a policy ignored stays in the result, because a check silently switched off is one nobody remembers is off.

The two revisions come from git, which Repository is the whole of: the merge base of the branch and what it is being merged into, the tree at that commit, and which commit last changed each file — so a finding names the commit which introduced it rather than leaving a reviewer to bisect for it. A checkout whose history does not reach the merge base is refused and told what to fetch, because git answers a shallow clone with the commit its history was cut off at, and a review against that would attribute the whole of the branch's ancestry to this change.

Accuracy

This is the convention every accuracy in the engine is stated under, and it is stated here because a consumer combining two numbers has to be able to find it in one place.

An accuracy is a standard uncertainty: one standard deviation, k = 1, stated in a unit of the same quantity as the claim's own value and written beside the magnitude. There is no other storage convention. A figure quoted at any other coverage — a half-width bound, a 95% interval, a manufacturer's "typical" — is converted to 1σ at the point it enters the model, by whoever enters it, and the conversion is part of the claim's provenance rather than something the engine guesses. A bare number with no stated meaning is worse than none at all, because it gets combined arithmetically anyway and the three conventions differ by a factor of two.

Nothing converts between units. Terms written in more than one unit do not combine, and a budget holding them says so rather than reconciling them.

Each term of an accuracy is tagged independent or systematic, because whether an error is shared is a fact about how the measurement was made and cannot be inferred from the number. Independent terms combine in quadrature. A systematic term — a georeference fit applied to every indoor fact alike — does not partially cancel and does not average away, so a term reached through two inputs of one computation is counted once. Systematic terms of distinct term ids add linearly, because the format cannot state how far two sources correlate and full correlation is the bound. The two totals then combine in quadrature, because an independent error correlates with nothing, the systematic ones included:

u = √( Σ uᵢ² + ( Σ |sⱼ| )² )

Budget is where that arithmetic lives, Uncertainty is what comes out of it, and a figure widened past 1σ always states the coverage factor it was widened by. Nothing widened is ever stored.

See docs/decisions/0006-accuracy-is-one-sigma.md for why, and specification section 6.6.5 for how an accuracy is written down.

Index

Examples

Constants

View Source
const (
	// ObservationTag introduces one observation.
	ObservationTag = "obs"

	// RetirementTag introduces a record retiring an earlier one.
	RetirementTag = "retire"
)

The form tags of the observation format, per observation specification section 3. There are two and there is no third: a line whose tag is neither is refused rather than skipped.

View Source
const (
	// SideHead is the revision under review.
	SideHead = "head"

	// SideBase is the merge base it is compared against.
	SideBase = "base"
)

Which of the two revisions a finding's span points into.

A finding about something head no longer holds can only be pointed at in the revision it was removed from, and a reader jumping to a file needs to be told which of the two it is looking for rather than finding out that the line is not there.

View Source
const BatchVersion = 1

BatchVersion is the version of the operation file format this engine reads.

A file which says nothing about its version is read as one written against this one, which is the only version there is; a file which names another is refused rather than guessed at. The rule the number carries is the one the machine output contract carries ([0014](docs/decisions/0014-the-machine-output-contract-is-part-of-the-interface.md)): a member may be added at any time, and a member is never removed, renamed or given a different meaning without this number changing.

View Source
const BuildDir = ".dfcad"

BuildDir is the directory derived data is written to, relative to the root of the model it was derived from.

Nothing in it is a source. Every byte beneath it can be recomputed from the entity files, deleting the whole of it costs time and nothing else, and no pass reads it for anything but speed ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). It is gitignored for the same reason a compiled binary is: a build output committed beside its source is a second copy of the model which goes stale silently.

It sits beside the entity files rather than inside them. A walk reads only files whose extension is Extension, so nothing here is ever loaded as part of the model however deep it is nested.

View Source
const DefaultDiagnosticLimit = 100

DefaultDiagnosticLimit is how many diagnostics a Diagnostics retains when its Limit is left unset.

A cap exists because a single misplaced parenthesis can make every later form in a file wrong, and a thousand diagnostics describing one mistake is worse than ten: whatever reads them, a person scrolling or an agent with a context window, is pushed past the one that matters.

View Source
const Extension = ".dfc"

Extension is the file extension a directory walk treats as an entity file.

It is compared byte-wise, like everything else the format compares, so a file named Site.DFC is not an entity file. A path named explicitly is read whatever its extension; the extension decides only what a walk picks up.

View Source
const LockName = ".dfcad.lock"

LockName is the file a transaction creates in the model root to say that it holds it.

It is not an entity file, so a walk of the model steps over it and a lock held while somebody reads the tree changes nothing about what they read.

View Source
const ObservationExtension = ".obs"

ObservationExtension is the file extension a directory walk treats as an observation file, per observation specification section 2.

It is compared byte-wise, like every other comparison in this system, so a file named Session.OBS is not an observation file. A path named explicitly is read whatever its extension; the extension decides only what a walk picks up.

View Source
const SpecVersion = "1.3"

SpecVersion is the version of the entity format specification this engine implements, in the MAJOR.MINOR form SPEC.md section 10 defines.

It is a fact about the engine rather than about any file it reads: models carry no version stamp, deliberately, so a consumer that needs to know which dialect of the format it is holding reads it from here — or, from the command line, out of the object `dfcad version` writes. That is the reader SPEC.md section 10 sends here, and it is why the constant is exported from the root package rather than kept unexported beside the loader.

It moves under the rules SPEC.md section 10 states, and it moves independently of the version of the tool and of the version of the machine output contract. docs/versioning.md is the relationship between the three.

View Source
const Unbounded = -1

Unbounded is the depth at which a bounded traversal follows its relation as far as the model goes.

It is a named value rather than a large number or a zero, because both of those read as a bound at the call site: a walk asked for a depth of a thousand looks like one somebody measured, and one asked for a depth of nothing looks like a mistake. A depth of zero takes no step at all and yields nothing, which is what asking for nothing means.

Variables

View Source
var ErrEmptyBudget = errors.New("expected at least one accuracy term in the budget, found none")

ErrEmptyBudget reports that a budget holds no term, and so has no figure to combine.

It is not the same as an uncertainty of zero. A computation which read no claim has no measured input, and answering it with an exact zero would be asserting that its answer is perfect — which is the optimism the whole of this file exists to refuse.

View Source
var ErrExtraInput = errors.New("a batch is one JSON object and nothing after it")

ErrExtraInput is an operation file with something after its object.

One file is one batch. Two objects in one file is either a batch somebody concatenated or a stream of them, and applying the first while silently dropping the rest is the reading which loses work.

View Source
var ErrFinished = errors.New("the transaction has finished")

ErrFinished reports a transaction which has already committed.

A transaction is one change. Committing it — whether it wrote, was refused or failed — ends it, and a caller which wants another change begins another transaction against the model as it now is.

View Source
var ErrGitMissing = errors.New("git is not on the path")

ErrGitMissing reports that git is not on the path.

View Source
var ErrLocked = errors.New("another transaction holds the model root")

ErrLocked reports a model root another transaction already holds.

The engine has no daemon and no journal, so concurrency is handled by refusing rather than by coordinating ([0015](docs/decisions/0015-the-cli-is-the-primary-write-path.md)). A caller which sees this has changed nothing and may simply try again.

View Source
var ErrNoAssertionSubject = errors.New("an assertion is written on the thing it constrains")

ErrNoAssertionSubject is an assertion written on nothing.

View Source
var ErrNoBacking = errors.New(
	"a backing names the elements an edge is backed by, or says that it is virtual",
)

ErrNoBacking is a change to an edge's backing which states neither what it is backed by nor that it is virtual.

It is refused rather than read as "backed by nothing", for the reason a relation to nothing is (ErrNoRelation): a command which named an edge and no backing is one somebody stopped typing, and writing the edge virtual on the strength of it would remove a wall nobody asked to remove. The empty set is a statement, and it is made explicitly.

View Source
var ErrNoCheck = errors.New("an assertion names the check it applies")

ErrNoCheck is an assertion naming no check.

An assertion is a check name and its parameters and nothing else ([0011](docs/decisions/0011-assertions-are-named-parameterised-checks.md)), so one with no name has nothing left to say.

View Source
var ErrNoCorners = errors.New("scaffolding a loop is written with the corners of the loop, in order and closed")

ErrNoCorners is a scaffold with no corner list.

It is the corners which are the room: a scaffold with none is a request to lay out nothing, and reporting it as a list which does not close would answer the wrong question.

View Source
var ErrNoEdges = errors.New("a loop is traversed through one or more edges, in order")

ErrNoEdges is a loop written with no edges to traverse.

View Source
var ErrNoEndpoints = errors.New("an edge runs between two vertices, written start then end")

ErrNoEndpoints is an edge written without both of the vertices it runs between.

View Source
var ErrNoFrame = errors.New("a geometric node is written in exactly one frame")

ErrNoFrame is a geometric node written without one.

It is not optional as a semantic node's frame is. A point with no frame is not a point with an axis left out; it is a coordinate nobody can locate ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

View Source
var ErrNoID = errors.New("a node is written with an id")

ErrNoID reports something authored without an id.

Every entity is written with one, and an id is never derived from anything else about the thing: a node is what its id says it is, for as long as the model holds it ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

View Source
var ErrNoNamespace = errors.New("scaffolding mints ids, which are minted in a declared namespace")

ErrNoNamespace is a scaffold with no id namespace to mint into.

View Source
var ErrNoOperations = errors.New("a batch is one or more operations, in the order they are applied")

ErrNoOperations is an operation file which carries no operation at all.

It is refused rather than applied as a change which does nothing: a file with an empty list is one somebody stopped writing, and a run which reported it as a successful change of nothing would say the batch landed.

View Source
var ErrNoPredicate = errors.New("a claim is written under a predicate, which is its tag")

ErrNoPredicate is a claim written under no predicate. A claim's tag is its predicate, so a claim with no predicate has no tag to be written with.

View Source
var ErrNoRelation = errors.New(
	"a relation names the node which contains this one, a zone it is a member of, or a loop which bounds it",
)

ErrNoRelation is a relation which relates a node to nothing at all.

It is refused rather than applied as a change which does nothing, for the reason an empty batch is: a command which named a node and no relation is one somebody stopped typing, and reporting it as a successful change of nothing would say the relation landed.

View Source
var ErrNoSubject = errors.New("a claim is written about a subject")

ErrNoSubject is a claim written about nothing.

View Source
var ErrNoSupersedingClaim = errors.New("a deprecation names the claim which stands in the retracted one's place")

ErrNoSupersedingClaim is a deprecation naming no claim to stand in the retracted one's place.

View Source
var ErrNoType = errors.New("a classification names the declared type it is written on")

ErrNoType is a classification naming no type to write itself on.

View Source
var ErrNoValue = errors.New("a claim is written with the value being claimed")

ErrNoValue is a claim written with nothing claimed.

The empty value is not this: a text claim of "" is a value a claim may legally hold, and leaving the member out says nothing at all.

View Source
var ErrNotADirectory = errors.New("not a directory")

ErrNotADirectory is a model root which is there but is not a directory.

View Source
var ErrNotARepository = errors.New("not inside a git working tree")

ErrNotARepository reports a directory which is not inside a git working tree.

It is what NotARepositoryError unwraps to, so that a caller which only wants to know which of the things went wrong writes errors.Is and one which wants to say where writes errors.As.

View Source
var ErrNotAnEntityFile = errors.New("not an entity file")

ErrNotAnEntityFile reports a file a walk of the model would not read back, because its extension is not Extension.

View Source
var ErrOutsideModel = errors.New("not beneath the model root")

ErrOutsideModel reports a file which is not beneath the model root.

Functions

func AssertEntityFormat

func AssertEntityFormat(model EntityFormat) error

AssertEntityFormat reports whether a model authored against model loads under this engine.

This is the engine noticing, which is the only place the noticing can happen: files carry no version stamp, deliberately (SPEC.md section 10), so a model at a format this engine does not implement is indistinguishable from a model with a misspelled tag in it — the loader reports the first form it does not recognise, which points the author at their file rather than at their engine. A consumer which knows which format it authored against says so, and gets that answer instead.

The assertion is about the format and not about any particular file, so it is answered before a byte of the model is read. A run which cannot load the model's format has nothing to say about the model's contents, and reporting on them anyway is how a check which ran no rule comes to look like a model with nothing wrong with it.

Example

A model carries no version stamp, deliberately, so whether it loads under a given engine is a question only the consumer holding both can ask.

AssertEntityFormat is that question. A consumer which knows which format it authored its model against says so, and is told which engine it is holding rather than being sent to look at the first form the loader did not recognise. The expected output below carries the version this engine implements, so a bump of it fails here. That is the same forcing function the constant's own test applies: the moment the format moves is the moment somebody should be reading what a consumer of the old one is told.

package main

import (
	"errors"
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The version the model was authored against, pinned by whoever authored
	// it — beside the engine it pins, and never read out of a file. A major
	// apart from this engine, which is the half of the rule that does not
	// dissolve the next time the minor moves.
	authored, err := dfcad.ParseEntityFormat("2.0")
	if err != nil {
		fmt.Println(err)
		return
	}

	err = dfcad.AssertEntityFormat(authored)

	var unsupported dfcad.UnsupportedEntityFormatError
	if errors.As(err, &unsupported) {
		fmt.Printf("the model is %s and this engine is %s\n", unsupported.Model, unsupported.Engine)
	}

	// The format this engine implements loads, and so does every earlier minor
	// of the same major: a minor bump adds forms rather than taking any away.
	fmt.Println(dfcad.AssertEntityFormat(dfcad.SpecFormat()))
	fmt.Println(dfcad.EntityFormat{Major: 1, Minor: 0}.LoadsUnder(dfcad.SpecFormat()))

}
Output:
the model is 2.0 and this engine is 1.3
<nil>
true

func Assume

func Assume(root string, batch Batch) (Assumption, []Diagnostic, error)

Assume reads the model beneath root, applies batch to it in memory and interprets the model the batch would produce. It writes nothing and locks nothing.

It is Begin, Tx.Apply and a dry-run Tx.Commit without the lock and without the diff, and it is those calls rather than a copy of them: the tree is read once by the same read, the operations are applied by the same mutations, every touched file is printed and read back as a commit prints and reads it, and the result is interpreted by the same passes. A batch therefore means the same thing assumed as applied — it is refused by both or by neither, in the same words — and the model which comes back is the model a load would read once the batch had been written.

No lock is taken, so it answers beside a transaction which holds the root, and nothing beneath the root is created, changed or removed.

Refusals come back as Begin, Tx.Apply and Tx.Commit return them:

  • A tree which does not already load returns its diagnostics, a zero Assumption and a nil error.
  • An operation the model refuses returns an OperationError naming which it was, beside the diagnostics the tree raised as it was read — which are warnings, since it loaded.
  • A result which would not load returns the diagnostics that load raised and an Assumption carrying only the Sources they were raised over, with a nil error.

Otherwise the diagnostics are those of the model the batch would produce, the warnings a load of it would raise. Refusal is Diagnostics.HasErrors over them, as it is for a commit.

The error is for the caller: root is not there, cannot be read, or is not a directory — a RootError — or an operation was refused.

Example

ExampleAssume answers over the model a batch would produce without writing it: the batch is applied in memory, and the graph which comes back is the one a load would read had it been written.

Nothing beneath the root changes and no lock is taken, so the fixture is read in place. The graph's digest is the digest of the tree the batch would produce, which is what anything derived from it is keyed by; the digest of the tree that was read comes back beside it.

package main

import (
	"fmt"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	batch, err := dfcad.ParseBatch(strings.NewReader(`{
		"version": 1,
		"operations": [
			{"op": "supersede", "subject": "geom:V-21", "predicate": "position",
			 "claim": {"value": "3.0 6.5 0.0", "unit": "m",
			           "source": "Re-survey RS-2026-003, Acme Surveys",
			           "method": "method:total-station",
			           "accuracy": ["independent 0.002 m"],
			           "date": "2026-06-01"}}
		]
	}`))
	if err != nil {
		fmt.Println(err)
		return
	}

	assumption, diags, err := dfcad.Assume("testdata/checks/satisfied", batch)
	if err != nil {
		fmt.Println(err)
		return
	}
	var collected dfcad.Diagnostics
	collected.Add(diags...)
	if collected.HasErrors() {
		fmt.Println("refused")
		return
	}

	for _, operation := range assumption.Applied {
		for _, effect := range operation.Effects {
			fmt.Printf("%d %s: %s %s %s\n",
				operation.Index, operation.Operation, effect.Op, effect.Tag, effect.ID)
		}
	}

	graph := assumption.Graph
	resolution, err := graph.Claims().Resolve("geom:V-21", "position", graph.Registry())
	if err != nil {
		fmt.Println(err)
		return
	}
	value, _ := resolution.Value()
	position, _ := value.Coordinate()
	fmt.Println("geom:V-21 would be at", position, value.Unit())

	digest, _ := graph.Digest()
	on, err := dfcad.DigestOf("testdata/checks/satisfied")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("base is the tree on disk:", assumption.Base == on)
	fmt.Println("the answer is keyed by another tree:", digest != assumption.Base)

}
Output:
1 supersede: modified vertex geom:V-21
1 supersede: modified vertex geom:V-21
geom:V-21 would be at [3 6.5 0] m
base is the tree on disk: true
the answer is keyed by another tree: true

func Begin

func Begin(root string) (*Tx, []Diagnostic, error)

Begin loads the model beneath root and locks it for one change.

root names the model root, which is a directory. Every entity file beneath it is read and parsed once, and the result is interpreted exactly as LoadGraph would interpret it — because it is the same passes over the same trees.

A tree which does not already load is refused. The diagnostics come back, no transaction does, and the lock is released. Writing into a model which is already broken would report the author's mistake and the pre-existing one together, leaving whoever reads the output to work out which of the two the command was responsible for; and a refusal which cannot be attributed is a refusal nobody can act on.

The diagnostics come back in the order the passes found them, as LoadGraph's do. Collecting them into a Diagnostics is what puts them in reporting order.

The error is for the caller rather than for the author: the root is not there, is not a directory, or is held by another transaction — ErrLocked, reached through LockError. A caller which gets one has changed nothing.

The transaction which comes back must be finished, by Tx.Commit or by Tx.Close, or the lock outlives the process which took it. Deferring Tx.Close is right in both cases: it does nothing to a transaction which has already committed.

func CacheDir

func CacheDir(root string) string

CacheDir is where the derived-geometry cache of the model beneath root lives.

It is a function rather than a constant because a cache belongs to the tree it was derived from. Two models sharing one cache directory would be two sets of entries under different digests in one place, which works and makes pruning either of them impossible to do without reading the other's.

func DeriveGlobalIDNamespace

func DeriveGlobalIDNamespace(url string) string

DeriveGlobalIDNamespace returns the project namespace UUID derived from the pinned url, in the canonical 8-4-4-4-12 text a UUID is written in.

It exists so the first half of the derivation can be checked without running the second: the value it returns is `uuid5(NAMESPACE_URL, url)` to any UUIDv5 implementation, so a reader of the registry can reproduce it from the URL recorded there and see that this package started from the same 128 bits they did.

func ExportDir

func ExportDir(root string) string

ExportDir is where artefacts derived from the model beneath root are written.

It is a sibling of CacheDir and is laid out the same way: one directory per key, named for the digest of the tree the artefact was derived from, so a run against a new revision writes a new directory rather than replacing anything ([0021](docs/decisions/0021-an-export-is-a-build-output-keyed-by-its-source-digest.md)).

An export never lands in the authored tree. A `model.ifc` beside the entity files would be invisible to every check the engine runs — a walk reads only files whose extension is Extension — while looking exactly as authoritative as the coordinates it may have stopped agreeing with. Give it an extension a walk does read and the failure inverts rather than resolving: the artefact becomes an input to the digest of the tree it was derived from, so writing it changes the key it was written under and no export of that tree is ever current again.

func Load

func Load(root string) iter.Seq2[*File, error]

Load reads root into spanned trees, one file at a time.

root may name a single file, which is read whatever its extension, or a directory, beneath which every file whose extension is Extension is read and everything else is ignored. A directory holding no entity file yields nothing and is not an error.

Files arrive in a deterministic order — the lexical order of their paths, directory by directory — so walking the same tree twice yields the same files in the same sequence, and any output built from a walk diffs against the last one.

A file that fails to load yields a nil file and its error, and the walk carries on to the next one. One unloadable file therefore does not hide what is wrong with the rest, which is what makes a single pass over a tree worth running. A caller that wants to stop at the first failure breaks out of the range.

Loading is streaming: a file is opened, read, spanned and yielded before the next one is opened, so a tree costs the largest single file rather than the sum of all of them.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// Every entity file beneath the root arrives in a deterministic order, one
	// at a time, and a file which fails to load does not stop the walk.
	for file, err := range dfcad.Load("testdata/model") {
		if err != nil {
			fmt.Println("could not load:", err)
			continue
		}
		fmt.Printf("%s: %d top-level forms\n", file.Path, len(file.Nodes))
	}

}
Output:
testdata/model/entities/level-1.dfc: 2 top-level forms
testdata/model/registry/registry.dfc: 4 top-level forms

func LoadClaims

func LoadClaims(root string, registry *Registry) (*Claims, []Diagnostic)

LoadClaims reads every claim beneath root, checked against registry.

root is what Load takes: a single file, or a directory beneath which every file whose extension is Extension is read. Claims come back in the order the walk reached them, which is deterministic, and indexed both by the subject they are about and by their own id, so neither resolving a reference nor asking what a model says about a thing has to scan.

registry is a loaded one, because every question this pass asks past the shape of the form is one only registry data answers: is this predicate declared, which of the four shapes does its value take, which unit is it expressed in, and is the namespace of this id one the model declares. A nil registry declares nothing, and every claim is then reported as naming a predicate nothing declares, which is both true and the diagnostic somebody whose registry has not been written yet needs.

Loading is one pass which reports everything it finds. A claim which is structurally wrong, a predicate nothing declares, a value of the wrong shape, a unit which is not the declared one, a date which is not one and a rank which is not one of the two are each a diagnostic, and none of them stops the rest of the tree from being read.

Claims which could be read come back whatever the diagnostics say, for the reason a node whose type is undeclared is still a node: a caller reporting on a tree wants to say what the claim says as well as what is wrong with it.

Which of the two spellings a predicate takes is decided here, because the registry is the only thing which knows. A claim-bearing predicate takes a claim form, and a bare scalar written in that position is a load error nothing downgrades; a predicate declared non-claim-bearing takes a plain value, which becomes no claim because there is no provenance on it for this pass to read. It is recorded apart from the claims, under the subject it was written on, and read back through Claims.PlainOf.

Whether a deprecated claim names the claim which replaced it, and whether following those replacements terminates, is asked once the whole tree has been read rather than as each claim is: a claim in the first file the walk reaches may be superseded by one in the last, and a pass which checked as it read would report it missing for no reason but the order the directory happened to be listed in. What is read claim by claim is the reference itself.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The registry resolves first. Which predicates exist, which of the four
	// shapes each one's value takes and which unit it is expressed in are the
	// only things which can judge a claim.
	registry, diagnostics := dfcad.LoadRegistry("testdata/claim/valid")
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
	}

	claims, diagnostics := dfcad.LoadClaims("testdata/claim/valid", registry)
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
	}

	// How wide is that room, and how do you know? One lookup answers both,
	// because a dimension here is a value plus the evidence for it rather than
	// a column with the provenance in another table.
	//
	// Two claims under one predicate is the normal case, and the disagreement
	// between them is the most valuable thing in the file.
	for claim := range claims.Under("site:S-101", "width") {
		width, _ := claim.Value().Scalar()
		accuracy, _ := claim.Accuracy()

		fmt.Printf("%g %s +/- %g %s, %s, %s\n",
			width, claim.Value().Unit(),
			accuracy.Terms[0].Magnitude, accuracy.Terms[0].Unit,
			claim.Source(), claim.Date().Format("2006-01-02"))
	}

}
Output:
8.5 m +/- 0.05 m, Plan set A-101, sheet 3, 2026-01-09
8.53 m +/- 0.003 m, As-built check AB-2026-009, Acme Surveys, 2026-05-06
Example (BareScalar)

ExampleLoadClaims_bareScalar is the rule which keeps every other example on this page meaning something: where a claim belongs, a number on its own does not load.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/claim/bare-scalar")

	// `(width 8.5)` is one keystroke from correct and reads as a simplification
	// in review, which is why it is a load error rather than a warning: a
	// warning that appears ten thousand times is suppressed the same afternoon,
	// and the provenance model is gone with nothing in the history saying so.
	//
	// Nothing downgrades it. There is no flag, no environment variable and no
	// configuration, because the distinction between a diagnostic which fails
	// the load and one which does not is a property of the rule.
	claims, diagnostics := dfcad.LoadClaims("testdata/claim/bare-scalar", registry)
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
		fmt.Println(diagnostic.Hint)
	}

	// The escape hatch is narrow and deliberate. A claim which cannot say how
	// good its value is leaves the accuracy out, and it loads — as unrankable,
	// which is visible as such rather than as a number quietly indistinguishable
	// from a surveyed one.
	for claim := range claims.Under("site:S-101", "width") {
		width, _ := claim.Value().Scalar()
		fmt.Printf("%g %s, %s, rankable %t\n", width, claim.Value().Unit(), claim.Method(), claim.Rankable())
	}

}
Output:
testdata/claim/bare-scalar/claims.dfc:11:3: error: expected the claim the predicate width bears, found a plain value
the least a claim may say is (width (value <number> m) (source "<evidence>") (method <method-id>) (date "<YYYY-MM-DD>")); accuracy may be left out, and the claim then loads as unrankable
8.4 m, method:estimated, rankable false
8.5 m, method:scaled-from-plan, rankable true

func LoadGraph

func LoadGraph(root string) (*Graph, []Diagnostic)

LoadGraph reads the whole model beneath root in one pass.

root is what Load takes: a single file, or a directory beneath which every file whose extension is Extension is read. Every file is read exactly once and parsed exactly once, and the four passes which interpret a tree — registry, semantic family, geometric family and claims — each read the trees that one walk produced. Asking four questions of a model is four interpretations of it and not four readings of the disk.

The order of the passes is the one dependency between them: registries resolve before any entity is interpreted, because whether a type is declared, which shape a predicate's value takes and which unit it is written in are questions only registry data answers, and a registry is a property of the whole tree rather than of the file an entity happens to sit in. The two joins run last, over what the four passes read: frames, which are declarations measured by claims, and boundaries, which are the references between the two families.

Loading is one pass which reports everything it finds. A file which does not parse, a form which is structurally wrong, a name nothing declares, a reference which reaches nothing, an id two things hold and a ring of references which returns to where it started are each a diagnostic, and none of them stops the rest of the tree from being read. Fixing a model one diagnostic at a time is a guessing loop.

The one thing this pass checks which none of the four can is uniqueness across the families. Each of them enforces it within what it read and against the frames the registry declared — two nodes, two vertices, two claims, a vertex and a frame — and none of them can see a vertex and a claim which hold the same id, because an id is unique across the whole model and not within a family (specification section 6.9).

The graph which comes back is always usable, whatever the diagnostics say. A tree holding no entity file at all yields an empty graph rather than a nil one, so a caller reporting on a model which has not been written yet reports on nothing rather than crashing.

Loading is deterministic. The walk is in the lexical order of the paths, so two loads of one tree produce the same graph in the same order, and anything derived from it — a summary, a listing, a rendering of the diagnostics — diffs against the last run's.

Diagnostics come back in the order the passes found them, which is pass by pass and not file by file. Collecting them into a Diagnostics is what puts them in reporting order.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// One call reads the whole model: the registry, both families of nodes, the
	// claims written on them, the frames and the boundaries. Every file beneath
	// the root is read once, whichever of the six the forms in it belong to.
	graph, diags := dfcad.LoadGraph("testdata/graph/valid")
	for _, diagnostic := range diags {
		fmt.Println(diagnostic)
	}

	fmt.Println(graph.Summary())

	// An id names one thing in the whole model, so a lookup takes an id and not
	// an id and a family.
	room, ok := graph.Node("site:S-101")
	if !ok {
		return
	}
	fmt.Println(room.Label())

	// What contains it, outwards.
	for related := range graph.Ancestors(room) {
		fmt.Println(related.Relation(), related.Node().ID())
	}

}
Output:
7 nodes, 6 vertices, 7 edges, 2 loops, 10 claims, 1 conflicts, 0 unresolved
Meeting Room B
containment site:L-01
containment site:B-01
containment site:S-01

func LoadNodes

func LoadNodes(root string, registry *Registry) (*Nodes, []Diagnostic)

LoadNodes reads every semantic node beneath root, checked against registry.

root is what Load takes: a single file, or a directory beneath which every file whose extension is Extension is read. Nodes come back in the order the walk reached them, which is deterministic, so anything built from them diffs against the last run's, and indexed by id, so resolving a reference does not scan.

registry is a loaded one, because the questions this pass asks — is this type declared, and does it permit the kind and the geometry form written here — are ones only registry data answers. That is also why the two loads are two calls: a registry is a property of the whole source tree, so every file has to have been read before any node is judged against it. A nil registry declares nothing, and every node is then reported as naming a type nothing declares, which is both true and the diagnostic somebody whose registry has not been written yet needs.

Loading is one pass which reports everything it finds. A file which does not parse, a form which is structurally wrong, an axis which is not a member of its closed set, a type nothing declares and a type which does not permit what the node wrote are each a diagnostic, and none of them stops the rest of the tree from being read.

Nodes which could be read come back whatever the diagnostics say. A node whose type is undeclared is still a node with an id, a kind and a label, and a caller reporting on a tree wants to say so rather than to lose it.

An id is unique across the whole model, so a second definition of one is a diagnostic naming both with their positions. The id goes on naming what it named first: an id which moved to the later definition would be an id which changed what it means, which is the one thing an id never does ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

The two relations a node writes to other nodes are read here and checked once the whole tree has been: containment, which nests strictly, and zone membership, which does not. A reference naming no node, a nesting the hierarchy does not permit, a containment cycle and a `member-of` naming something which is not a Zone are each a diagnostic. They are checked after the walk rather than during it because a node in the first file it reaches may be written inside one in the last. Nodes.Within, Nodes.Contains, Nodes.Zones and Nodes.Members are what read them back.

The geometric family — `vertex`, `edge` and `loop` — is not read here. Those carry neither kind nor type and validate under their own rules ([0001](docs/decisions/0001-two-node-families.md)). The one reference which crosses to it, a `boundary` naming a loop, is read and left unresolved for the same reason: this pass has read one family, and no pass which has read one family can say whether an id names a member of the other. ResolveBoundaries is the pass which has read both, and SemanticNode.Boundaries is the ids as they were written.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The registry resolves first. Whether a type is declared, and which kind
	// and which geometry form it permits, is the only thing which can judge a
	// node's axes.
	registry, diagnostics := dfcad.LoadRegistry("testdata/node/valid")
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
	}

	nodes, diagnostics := dfcad.LoadNodes("testdata/node/valid", registry)
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
	}

	for node := range nodes.All() {
		// A node with no geometry is an ordinary node and not a broken one, so
		// the axis reports absence rather than an empty value.
		geometry, ok := node.Geometry()
		if !ok {
			fmt.Printf("%s: %s %s, no geometry\n", node.ID(), node.Kind(), node.Type())
			continue
		}
		fmt.Printf("%s: %s %s, %s\n", node.ID(), node.Kind(), node.Type(), geometry)
	}

}
Output:
site:Z-01: Zone Campus, area
site:S-01: Site SiteBoundary, area
site:B-01: Building OfficeBuilding, solid
site:L-01: Storey Level, surface
site:S-101: Space MeetingRoom, area
site:E-01: Element Partition, line
site:I-01: Interface Doorway, point
site:C-01: Zone CircuitGroup, no geometry

func LoadObservations

func LoadObservations(root string, registry *Registry) (*ObservationLog, []Diagnostic)

LoadObservations reads the observation files beneath root and validates them against the registry, per observation specification section 7.

It is the whole of the format's own checking: ParseObservations answers what each file says and ValidateObservations answers whether the log those files make is sound. What it cannot answer on its own is [section 8](docs/observation-file.md#8-append-only) — whether a file was appended to rather than edited — which is a question about two revisions and is ValidateAppendOnly.

Files are read in the lexical order of their paths, which is what makes "earlier in the log" a question with one answer across a directory of them. A file which cannot be read is a diagnostic and the walk carries on, so one unreadable file does not hide what is wrong with the rest.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/observations/valid"

	registry, _ := dfcad.LoadRegistry(root)

	log, diags := dfcad.LoadObservations(root, registry)
	fmt.Println(log.Len(), "records,", len(diags), "diagnostics")

	// What the log resolves to is every observation no retirement names. The
	// retired one is still in the file and still readable; it is simply not
	// what the log currently says.
	for observation := range log.Current() {
		fmt.Printf("%s %s %.3f %s\n",
			observation.ID, observation.Fix, observation.HorizontalPrecision, observation.Session)
	}

	retired, _ := log.Observation("shot:2026-05-06-0003")
	retirement, _ := log.RetirementOf(retired.ID)

	fmt.Printf("%s: %.3f, retired on line %d: %s\n",
		retired.ID, retired.HorizontalPrecision, retirement.Line(), retirement.Reason)

}
Output:
6 records, 0 diagnostics
shot:2026-05-06-0001 fix:rtk-fixed 0.012 session:2026-05-06-am
shot:2026-05-06-0002 fix:rtk-fixed 0.011 session:2026-05-06-am
shot:2026-05-06-0004 fix:rtk-fixed 0.013 session:2026-05-06-am
shot:2026-05-06-0005 fix:rtk-fixed 0.014 session:2026-05-06-pm
shot:2026-05-06-0003: 0.240, retired on line 8: float solution beside a fixed reshot of the same corner

func LoadRegistry

func LoadRegistry(root string) (*Registry, []Diagnostic)

LoadRegistry reads every registry form beneath root into one registry.

root is what Load takes: a single file, or a directory beneath which every file whose extension is Extension is read. Every file is read, because a registry is a property of the whole source tree and not of any one file in it: a type declared in one file and a frame naming it in another are one declaration and one reference, and a loader reading files independently could not say so.

Loading is one pass which reports everything it finds. A file which does not parse, a form which is structurally wrong, a value of the wrong sort, a name declared twice and a reference to something undeclared are each a diagnostic, and none of them stops the rest of the tree from being read. Fixing a registry one diagnostic at a time is a guessing loop.

The registry which comes back is always usable, whatever the diagnostics say. A tree holding no registry form at all yields an empty registry rather than a nil one, so every layer above answers "is this declared" with "no" rather than crashing on the model whose registry is the thing that has not been written yet.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// One registry for the whole source tree: the frame declared in the first
	// file names a parent declared in the second, and both are one registry.
	registry, diagnostics := dfcad.LoadRegistry("testdata/registry/valid")
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
	}

	project, _ := registry.Project()
	fmt.Println(project.GlobalIDNamespace)

	room, _ := registry.Type("MeetingRoom")
	fmt.Println(room.PermitsKind(dfcad.KindSpace), room.PermitsGeometry(dfcad.GeometrySolid))

	building, _ := registry.Frame("frame:building")
	fmt.Println(building.Unit, building.Parent)

}
Output:
https://example.org/models/riverside
true false
m frame:survey-grid

func LoadTopology

func LoadTopology(root string, registry *Registry) (*Topology, []Diagnostic)

LoadTopology reads every geometric node beneath root, checked against registry.

root is what Load takes: a single file, or a directory beneath which every file whose extension is Extension is read. Nodes come back in the order the walk reached them, which is deterministic, so anything built from them diffs against the last run's, and indexed by id, so resolving a reference does not scan.

registry is a loaded one, because the one question this pass asks past the shape of a form and the references between forms — is the namespace of this id one the model declares — is a question only registry data answers. A nil registry declares nothing, and every node is then reported as minting its id in a namespace nothing declares, which is both true and the diagnostic somebody whose registry has not been written yet needs.

It is a pass of its own rather than part of LoadNodes because the two families validate under different rules. A vertex is not a node missing its kind, and a loader which read both through one path would have to say so with a flag on every check it makes ([0001](docs/decisions/0001-two-node-families.md)).

What a geometric node says about a value it holds is not read here. A vertex's position, an edge's clearance and the curvature of a non-straight edge are all of them claims, and claims are read by LoadClaims wherever they are written — on a semantic node, on a frame or on one of these. This pass reads the nodes and the references between them, which is what a claim is then about.

Loading is one pass which reports everything it finds. A file which does not parse, a form which is structurally wrong, an id which is not one, an id something else already holds, a reference naming nothing and a reference naming the wrong sort of node are each a diagnostic, and none of them stops the rest of the tree from being read.

Nodes which could be read come back whatever the diagnostics say, for the reason a node whose type is undeclared is still a node: a caller reporting on a tree wants to say what is there as well as what is wrong with it.

The references within the family are resolved once every file has been read. An edge in the first file the walk reaches may run between vertices written in the last, and a loader which resolved as it read would report them missing for no reason but the order the directory happened to be listed in.

The references which leave the family are not resolved here. A `backed-by` on an edge names a semantic node and a `boundary` on a semantic node names a loop, and neither pass has read both families; they are questions for the one which has, which for `boundary` is ResolveBoundaries.

Whether a loop closes is not asked here either. It is a question about the positions of the vertices its edges run between, judged against a named tolerance, and neither of those is something reading the references answers. Topology.Assemble is what asks it.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The geometric family is read by a pass of its own, because it validates
	// under its own rules: a vertex is not a node missing its kind.
	registry, diagnostics := dfcad.LoadRegistry("testdata/topology/valid")
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
	}

	topology, diagnostics := dfcad.LoadTopology("testdata/topology/valid", registry)
	for _, diagnostic := range diagnostics {
		fmt.Println(diagnostic)
	}

	// An edge is an ordered pair of vertices: start then end, never sorted.
	edge, _ := topology.Edge("geom:E-01")
	start, end := edge.Vertices()
	fmt.Printf("%s: %s to %s\n", edge.ID(), start, end)

	// A loop is the ring of edges the outline is traversed through, in the
	// order it was written. Two rooms either side of a partition reference the
	// same edge, which is what makes the partition one thing rather than two
	// copies free to drift apart.
	loop, _ := topology.Loop("geom:L-01")
	fmt.Println(loop.ID(), loop.Edges())

}
Output:
geom:E-01: geom:V-01 to geom:V-02
geom:L-01 [geom:E-03 geom:E-04 geom:E-01 geom:E-02]
Example (Position)

ExampleLoadTopology_position is the arrangement two node families exist for: where a corner was measured is a claim on the corner, with the same provenance and the same accuracy rules as the width of a room.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/topology/valid")
	topology, _ := dfcad.LoadTopology("testdata/topology/valid", registry)
	claims, _ := dfcad.LoadClaims("testdata/topology/valid", registry)

	corner, _ := topology.Vertex("geom:V-01")

	// One corner, surveyed twice. Neither reading is thrown away, and the
	// engine has no coordinate field which could have held only one of them.
	for claim := range claims.Under(corner.ID(), "position") {
		position, _ := claim.Value().Coordinate()
		accuracy, _ := claim.Accuracy()

		fmt.Printf("%v %s +/- %g %s, %s\n",
			position, claim.Value().Unit(),
			accuracy.Terms[0].Magnitude, accuracy.Terms[0].Unit,
			claim.Date().Format("2006-01-02"))
	}

}
Output:
[0 0 0] m +/- 0.012 m, 2026-02-18
[0.004 0 0] m +/- 0.003 m, 2026-05-06

func Nests

func Nests(child, parent Kind) bool

Nests reports whether the containment hierarchy permits a node of kind child to be written within a node of kind parent.

It is the whole of what the engine knows about which kinds nest. A pairing it rejects is a load error rather than a warning, because a model in which a storey sits inside a room is a model whose traversals answer nonsense confidently.

func ObservationTags

func ObservationTags() []string

ObservationTags returns the form tags an observation file may write, in the order a diagnostic names them.

func Operations

func Operations() []string

Operations is the name of every operation an operation file may carry, in the order the format documents them.

It is exported because it is the answer to "what can a batch say", which is a question a caller building an operation file asks before it writes one.

func ParseDate

func ParseDate(written string) (time.Time, error)

ParseDate reads a date written the one way this format writes one, per specification section 4.4.

It is what every date in the engine goes through, whether it was read out of a file or handed in by a caller authoring a change.

func ParseObservationTime

func ParseObservationTime(written string) (time.Time, error)

ParseObservationTime reads an observation timestamp, per observation specification section 4.2.

It is RFC 3339 date-time with a numeric offset. Fractional seconds are permitted and carry whatever resolution was written. Z is +00:00 and is unambiguous; -00:00 is not, and neither is a date-time with no offset at all.

A zone abbreviation — CEST, EST — is not RFC 3339 and comes back as a malformed timestamp rather than as an offset: those abbreviations are not unique across the world, and several of them denote two different offsets in one year.

Example
package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	// Z is +00:00 and is unambiguous, and an offset is carried as written.
	at, _ := dfcad.ParseObservationTime("2026-05-06T11:14:22+02:00")
	fmt.Println(at.UTC().Format(time.RFC3339))

	// A local time in a zone the file does not name denotes a different instant
	// depending on where it is read, so two records written that way cannot be
	// ordered.
	_, err := dfcad.ParseObservationTime("2026-05-06T09:14:22")

	var malformed dfcad.MalformedTimestampError
	if errors.As(err, &malformed) {
		fmt.Println(malformed.Reason, "-", malformed.Written)
	}

	// RFC 3339 spells an offset nobody knows -00:00, and a record whose instant
	// is unknown is not evidence of when anything was measured.
	_, err = dfcad.ParseObservationTime("2026-05-06T09:14:22-00:00")
	if errors.As(err, &malformed) {
		fmt.Println(malformed.Reason)
	}

}
Output:
2026-05-06T09:14:22Z
no-offset - 2026-05-06T09:14:22
unknown-offset

func ParseObservations

func ParseObservations(path string, r io.Reader) (*ObservationLog, []Diagnostic)

ParseObservations reads one observation file, per observation specification sections 2 to 6.

What it checks is the file: its encoding, its line terminators, and the lexis and the field count of every record on every line. What it does not check is anything needing more than one line or a registry — a duplicate identity, a retirement which resolves, a frame somebody declared — which is ValidateObservations and needs the whole log.

One pass reports every independent problem it finds and carries on past each one, so a file with eleven malformed lines is eleven diagnostics on one run rather than eleven runs. A line which does not parse contributes no record and stops nothing: the lines after it are read.

The log comes back holding whatever did parse, which is what lets a caller report on a file and still say what the sound part of it holds.

func Print

func Print(w io.Writer, file *File) error

Print writes file in the canonical form of the entity format.

Every model has exactly one canonical printing, and this is it. The command line interface writes it, fmt rewrites a hand-written file into it, and a pull request diff over a tree of them is then about the change rather than about whitespace.

What canonical form settles, and why none of them is a preference:

  • Content is sorted. Top-level forms go in the fixed tag order of the format and then by their own name or id; a form's children go in the order its table lists them, with repeats, claims and assertions sorted among themselves by their inline rendering. Sorting is what stops the two authors of a file — a person and this package — from disagreeing, since an in-memory graph does not carry the order anybody typed things in.
  • A child equal to its default is left out. (rank normal) never prints; (rank deprecated) does. Both spellings load, and only one is written back, so one graph has one printing.
  • A number prints as the shortest decimal that reads back as the same value, gaining a fraction where it would otherwise read back as an integer. Trailing zeros carry no meaning here: significance is a claim's accuracy, written where a query can read it.
  • A sequence whose order is data is never sorted — the ids of a boundary, the components of a coordinate, the terms of a transform. They are written as positional arguments, and positional arguments keep the places they were written in.

Comments survive. A comment attaches to the next sibling written after it and travels with that sibling when it sorts, so a comment above a claim stays above that claim wherever the claim lands. One written after the last sibling stays at the end of the form it was written in. This is the one place a format cycle moves something a person wrote, which is why it is stated rather than left to be discovered.

Line breaking, indentation and the spelling of an atom come from the underlying S-expression printer unchanged, which is also why canonical output carries no blank lines: a blank line between two forms is not preserved, and there is no rule that would put one back. Output ends with exactly one line feed, has no trailing whitespace on any line, and is identical for the same model on every run, in every process.

Printing a file which does not load is not an error. Anything the format does not recognise — an unknown tag, a datum which is not a form — is written back as it was given, after everything the format does recognise. Deciding whether a file is well formed is Validate's job, and a printer which refused to write what it could not classify would be one nobody could run on the file they were fixing.

A nil file writes nothing. A file holding no forms writes the comments it holds and nothing else, which is nothing at all when it holds none either: a file of comments is still a file somebody wrote.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	source := `(node site:S-101
  (frame frame:building)
  ; The corner the survey started from.
  (position
    (rank normal)
    (date "2026-02-18")
    (value (0.0 0.00 0.0) m)
    (method method:total-station)
    (source "Interior control set IC-01"))
  (kind Space)
  (label "Meeting Room B")
  (type MeetingRoom))
`

	file, err := dfcad.Parse("entities/level-1.dfc", strings.NewReader(source))
	if err != nil {
		fmt.Println(err)
		return
	}

	// Canonical form puts the children in the order the format gives them,
	// leaves out the rank which is already the default, and carries the comment
	// along with the claim it annotates.
	if err := dfcad.Print(os.Stdout, file); err != nil {
		fmt.Println(err)
	}

}
Output:
(node
  site:S-101
  (label "Meeting Room B")
  (kind Space)
  (type MeetingRoom)
  (frame frame:building)
  ; The corner the survey started from.
  (position
    (value (0.0 0.0 0.0) m)
    (source "Interior control set IC-01")
    (method method:total-station)
    (date "2026-02-18")))

func ResolveBoundaries

func ResolveBoundaries(nodes *Nodes, topology *Topology) (*Boundaries, []Diagnostic)

ResolveBoundaries joins the two families of one model: it resolves every `boundary` a semantic node wrote to the loop it names and every `backed-by` an edge wrote to the element it names, and indexes what each region depends on and what depends on each loop and edge.

It takes both families already loaded rather than a root, because it adds no reading of its own. LoadNodes and LoadTopology each walk the tree once and each report what its own family got wrong; a third walk here would read every file a third time and report the parse error in it a third time.

It is a pass of its own for the reason there are two loaders at all. A `boundary` is written on a semantic node and names a loop, so answering it means having read both families, and a loader which had read one would have to either resolve it wrongly or leave it — which is what they do ([0001](docs/decisions/0001-two-node-families.md)).

Every reference is checked and every one which fails is reported: a `boundary` naming nothing this model holds, one naming a member of either family which is not a loop, one naming the same loop twice, and the same three for a `backed-by` which has to reach a semantic node of kind Element. A reference which resolves is indexed; one which does not is not, because an index entry for it would be an edge with one end.

Whether the loops themselves close is not asked here. That is a question about the edges of one loop and the positions of their vertices, it is answered against a named tolerance, and Topology.Assemble is what answers it.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order.

Example

ExampleResolveBoundaries follows a wall which two rooms share, from each of them and from the wall.

Neither room holds a coordinate. Each references a loop, the loops reference edges, and the edge between the rooms is named by both — so it is one node with one identity, moving it moves both rooms, and a sliver gap between them is not a state the model can express.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/boundary/valid"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)

	// The two families are loaded separately and joined here, because a
	// `boundary` is written on a semantic node and names a loop: no pass which
	// has read one family can resolve it.
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	room, _ := nodes.Node("site:S-101")
	for edge := range boundaries.Edges(room) {
		fmt.Printf("%s is bounded by %s\n", room.ID(), edge.ID())
	}

	// And the same question from the other end, which is written nowhere and is
	// what makes the sharing visible from the wall.
	partition, _ := topology.Edge("geom:E-02")
	for region := range boundaries.Regions(partition) {
		fmt.Printf("%s bounds %s\n", partition.ID(), region.ID())
	}

}
Output:
site:S-101 is bounded by geom:E-01
site:S-101 is bounded by geom:E-02
site:S-101 is bounded by geom:E-03
site:S-101 is bounded by geom:E-04
geom:E-02 bounds site:S-101
geom:E-02 bounds site:S-102

func ResolveFrames

func ResolveFrames(registry *Registry, claims *Claims) (*Frames, []Diagnostic)

ResolveFrames joins the frames a registry declares to the claims which measure them: it resolves every frame's transform to the claim it names and indexes the chain each frame reaches the root through.

It takes a loaded registry and loaded claims rather than a root, because it adds no reading of its own. LoadRegistry and LoadClaims each walk the tree once and each report what they found; a third walk here would read every file a third time and report the parse error in it a third time.

It is a pass of its own because a frame's transform is a claim. Which frames exist and which parent each names is registry data and resolves first, and the claim which measures one may be written in any file of the tree — so the registry loader cannot resolve it and the claim loader, which does not know what a frame is beyond a form which carries claims, cannot judge it.

What it reports is the one thing neither of those passes can say: a frame whose transform names a claim whose value is not a transform. The claim is a perfectly good claim and the reference reaches it; what it does not carry is a fit between two frames. The rest of what can be wrong with a frame is already reported where it is knowable — a parent nothing declares, a cycle in the chain, a second root and a unit which is no linear unit by LoadRegistry, and a transform naming a claim nothing carries by LoadClaims — and repeating any of them here would report one mistake twice.

A frame whose transform claim resolved but whose value could not be read is not reported here either, for the same reason: the claim loader has already said what was wrong with the value, and this pass would be saying it is therefore not a transform.

Diagnostics come back in the order the pass found them, which is by frame id. Collecting them into a Diagnostics is what puts them in reporting order.

Example

ExampleResolveFrames relates an indoor floor plan to the survey it sits on, and says how well that relationship is actually known.

A shape lives in exactly one frame and is transformed on demand. Storing one corner in two frames is two sources of truth which drift the moment the georeference is re-fitted — and the relationship between the frames is not a configuration constant either. It is a fit, produced by a method on a date with an accuracy, so it is a claim like every other measurement in the model.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/frame/valid"

	registry, _ := dfcad.LoadRegistry(root)
	claims, _ := dfcad.LoadClaims(root, registry)

	// The frames are registry data and the transforms between them are claims,
	// so relating the two is a pass of its own.
	frames, _ := dfcad.ResolveFrames(registry, claims)

	// The building is modelled in millimetres and the survey grid is in metres.
	// Neither number is converted where it was written; the conversion happens
	// here, through the linear unit each frame declares.
	corner := dfcad.Point{3000.0, 4000.0, 0.0}

	on, err := frames.TransformPoint(corner, "frame:building", "frame:survey-grid")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%.1f mm becomes %.3f m\n", corner, on)

	// And the evidence for the step which put it there, which is the whole
	// reason the transform is a claim: a cross-frame answer can say how well the
	// relationship it was computed through is known.
	measurement, _ := frames.Measurement("frame:site")
	accuracy, _ := measurement.Accuracy()

	fmt.Printf("%s, by %s on %s, +/- %g %s\n",
		measurement.Source(), measurement.Method(),
		measurement.Date().Format("2006-01-02"),
		accuracy.Terms[0].Magnitude, accuracy.Terms[0].Unit)

}
Output:
[3000.0 4000.0 0.0] mm becomes [113.000 224.000 0.000] m
Georeferencing report GR-2026-002, Acme Surveys, by method:gnss-static on 2026-02-11, +/- 0.012 m

func Walk

func Walk(root string) iter.Seq2[string, error]

Walk yields the path of every entity file under root, in the order Load reads them.

root may name a single file, which is yielded whatever its extension, or a directory, beneath which every file whose extension is Extension is yielded and everything else is ignored. A directory holding no entity file yields nothing and is not an error.

A path that cannot be reached at all — the root does not exist, a directory beneath it cannot be read — is yielded with the error that stopped it, and the walk carries on. The path is still reported alongside the error, so a caller collecting one result per file has something to key it on.

It is separate from Load because reading a file is not the only thing a caller does with one. Formatting reads the bytes itself, so that it can compare them against what the canonical printer would write; it wants the same enumeration and not the same reading.

func WalkObservations

func WalkObservations(root string) iter.Seq2[string, error]

WalkObservations yields the observation files beneath root, in the lexical order of their paths.

root may name a single file, which is read whatever its extension, or a directory, beneath which every file whose extension is ObservationExtension is yielded and everything else is ignored. A directory holding no observation file yields nothing and is not an error.

It is separate from Walk because the two answer different questions about one tree: entity files and observation files sit in the same repository and neither walk should pick the other up.

Types

type Accuracy

type Accuracy struct {
	// Terms are the terms written inside the accuracy, in written order. There
	// is at least one: an accuracy holding none is a diagnostic rather than an
	// accuracy.
	Terms []AccuracyTerm

	// Span is where the accuracy was written.
	Span Span
}

Accuracy is how well a claim's value is known, per specification section 6.6.5.

The terms are held in the order they were written. They are unordered as far as meaning goes — the canonical printer sorts them — and keeping the written order is what lets a diagnostic about one point at the right line.

type AccuracyTerm

type AccuracyTerm struct {
	// Kind is which of the two terms this is.
	Kind TermKind

	// Magnitude is the one-sigma figure, in Unit.
	Magnitude float64

	// Unit is the unit the magnitude is expressed in, as it was written.
	Unit Unit

	// Source is the id the systematic error is shared with. Empty for an
	// independent term, which is shared with nothing.
	//
	// Two systematic terms are the same term when their ids are byte-equal, not
	// when their magnitudes happen to match. The namespace has to be one the
	// registry declares; the id need not name a node.
	Source ID

	// Span is where the term was written.
	Span Span
}

AccuracyTerm is one term of a claim's accuracy.

The magnitude is a standard uncertainty: one standard deviation, k = 1. There is no other storage convention, and a figure quoted at any other coverage is converted at the point it enters the model, by whoever enters it ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).

A term is what a claim wrote down. Combining the terms of several claims into the error budget of one computed answer is Budget, which is where the difference between the two kinds below is arithmetic rather than only a tag.

func ParseAccuracyTerm

func ParseAccuracyTerm(written string) (AccuracyTerm, error)

ParseAccuracyTerm reads one term of a claim's accuracy written as the form writes it, minus the parentheses: the kind, the magnitude, the unit, and — for a systematic term — the id the error is shared with.

The magnitude is a standard uncertainty, one standard deviation, k = 1. There is no other storage convention, and a figure quoted at any other coverage is converted by whoever enters it ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).

type AddAssertionOperation

type AddAssertionOperation struct {
	// Subject is the thing the assertion constrains: a node, a vertex, an edge
	// or a loop.
	Subject string `json:"subject"`

	// Check is the name of the check it applies, which the engine's closed
	// registry must register.
	Check string `json:"check"`

	// Parameters are its parameters, each written as the entity format writes
	// one without its parentheses — `tolerance boundary-closure` — and in the
	// order they are written. A check which takes none is written with none.
	Parameters []string `json:"parameters,omitempty"`
}

AddAssertionOperation writes a check the thing it names has to satisfy. It is `add-assertion`.

func (*AddAssertionOperation) Name

func (o *AddAssertionOperation) Name() string

Name implements Operation.

type AddClaimOperation

type AddClaimOperation struct {
	// Subject is the thing the claim is about.
	Subject string `json:"subject"`

	// Predicate is the predicate it is written under.
	Predicate string `json:"predicate"`

	// Claim is the value and the evidence for it.
	Claim ClaimAxes `json:"claim"`
}

AddClaimOperation attaches a measured value to a thing, with its provenance. It is `add-claim`.

func (*AddClaimOperation) Name

func (o *AddClaimOperation) Name() string

Name implements Operation.

type AddEdgeOperation

type AddEdgeOperation struct {
	// ID is the id it will be written with.
	ID string `json:"id"`

	// Frame is the frame it is expressed in.
	Frame string `json:"frame,omitempty"`

	// Label is its display text.
	Label string `json:"label,omitempty"`

	// File is where to write it, overriding the routing rules.
	File string `json:"file,omitempty"`

	// Start and End are the vertices it runs between, in that order. The order
	// is significant and is never sorted: an edge is directed.
	Start string `json:"start"`
	End   string `json:"end"`

	// BackedBy are the semantic nodes which physically realise it. An edge
	// which names none is virtual, which is computed rather than written.
	BackedBy []string `json:"backedBy,omitempty"`
}

AddEdgeOperation writes a connection between two corners. It is `add-edge`.

func (*AddEdgeOperation) Name

func (o *AddEdgeOperation) Name() string

Name implements Operation.

type AddLoopOperation

type AddLoopOperation struct {
	// ID is the id it will be written with.
	ID string `json:"id"`

	// Frame is the frame it is expressed in.
	Frame string `json:"frame,omitempty"`

	// Label is its display text.
	Label string `json:"label,omitempty"`

	// File is where to write it, overriding the routing rules.
	File string `json:"file,omitempty"`

	// Edges are the edges of the ring, in the order the loop is traversed. The
	// order is the data and is never sorted.
	Edges []string `json:"edges"`
}

AddLoopOperation writes an ordered ring of edges. It is `add-loop`.

func (*AddLoopOperation) Name

func (o *AddLoopOperation) Name() string

Name implements Operation.

type AddNodeOperation

type AddNodeOperation struct {
	// ID is the id it will be written with.
	ID string `json:"id"`

	// Kind is the kind it declares.
	Kind string `json:"kind,omitempty"`

	// Type is the type it declares.
	Type string `json:"type,omitempty"`

	// Geometry is the geometry form it declares, and is empty for a node with
	// none — which its type has to permit.
	Geometry string `json:"geometry,omitempty"`

	// Frame is the coordinate frame it is expressed in.
	Frame string `json:"frame,omitempty"`

	// Label is its display text, which nothing resolves through.
	Label string `json:"label,omitempty"`

	// File is where to write it, overriding the routing rules. A path relative
	// to the model root, ending in [Extension].
	File string `json:"file,omitempty"`
}

AddNodeOperation writes a new semantic node. It is `add-node`.

func (*AddNodeOperation) Name

func (o *AddNodeOperation) Name() string

Name implements Operation.

type AddVertexOperation

type AddVertexOperation struct {
	// ID is the id it will be written with.
	ID string `json:"id"`

	// Frame is the frame its position is expressed in. A geometric node is
	// always in exactly one.
	Frame string `json:"frame,omitempty"`

	// Label is its display text.
	Label string `json:"label,omitempty"`

	// File is where to write it, overriding the routing rules.
	File string `json:"file,omitempty"`

	// Predicate is the predicate its position is claimed under, and is empty
	// for a corner which has been named and not yet surveyed. The claim below
	// is read only where it is given.
	Predicate string `json:"predicate,omitempty"`

	// Claim is the position claim written in the same change as the vertex,
	// because a vertex and the first thing anybody knows about where it is are
	// one statement.
	Claim ClaimAxes `json:"claim,omitempty"`
}

AddVertexOperation writes a new corner, with where it is and how that is known. It is `add-vertex`.

func (*AddVertexOperation) Name

func (o *AddVertexOperation) Name() string

Name implements Operation.

type AdjacencyFilter

type AdjacencyFilter struct {
	// CrossVirtual allows an edge nothing backs to be crossed. The open line
	// between a foyer and a dining room is written that way, and so is a doorway
	// in a model which draws its openings as nothing at all.
	CrossVirtual bool

	// CrossTypes are the types a backing element may declare for the edge it
	// backs to be crossed. At least one of an edge's backing elements has to
	// declare one of them, rather than all of them, because a doorway is cut into
	// a wall and the model says so by backing one edge with both.
	CrossTypes []string

	// WalkKinds are the kinds a region may declare for the walk to enter it.
	// Every region but the one the walk starts from has to declare one of them.
	WalkKinds []Kind

	// WalkTypes are the types a region may declare for the walk to enter it.
	// Every region but the one the walk starts from has to declare one of them.
	WalkTypes []string
}

AdjacencyFilter says which shared edges an adjacency walk may cross, and which regions it may enter on the other side of them.

It follows the convention RuleFilter sets: a field left empty matches everything, so the zero value crosses every shared edge into every region and a walk with it is Boundaries.AdjacentTo. Within one field the values are alternatives.

The crossing fields, AdjacencyFilter.CrossVirtual and AdjacencyFilter.CrossTypes, are alternatives to each other too, because each names a way through: an edge may be crossed when either of them allows it.

The walk fields, AdjacencyFilter.WalkKinds and AdjacencyFilter.WalkTypes, are not, because each says something a region has to be: a region is entered only when it satisfies every walk field given. A region the walk does not enter is neither reported nor walked through, which is what keeps a site or a storey outline drawn along the outside of two rooms from joining rooms that share no edge with each other.

Which types count as a way through, or as somewhere to go, is the caller's to say. The engine compares the names it is handed with the types the model declares and attaches no meaning to either ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)): a Doorway is a passage in one registry and a word nobody declared in another.

Example (WalkTypes)

ExampleAdjacencyFilter_walkTypes walks only through the regions it is told to enter, rather than through everything which shares an edge.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/boundary/adjacent"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)

	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	room, _ := nodes.Node("site:S-A")

	// Room C is on the far side of the corridor. A walk which enters only
	// corridors reaches the corridor and does not pass through it into room C,
	// because room C is a meeting room.
	corridors := dfcad.AdjacencyFilter{WalkTypes: []string{"Corridor"}}

	for neighbour := range boundaries.AdjacentWalk(room, dfcad.Unbounded, corridors) {
		fmt.Printf("%s reaches %s at depth %d\n", neighbour.From().ID(), neighbour.Node().ID(), neighbour.Depth())
	}

}
Output:
site:S-A reaches site:S-B at depth 1

func (AdjacencyFilter) Enters

func (f AdjacencyFilter) Enters(region *SemanticNode) bool

Enters reports whether a walk may enter the region: report it, and walk on through it.

Only the walk fields decide it. A region is entered when its kind is one of AdjacencyFilter.WalkKinds and its type is one of AdjacencyFilter.WalkTypes, where a field left empty admits every region. A nil region is never entered.

The region a walk starts from is not asked: it is where the walk is, whatever it declares.

func (AdjacencyFilter) Matches

func (f AdjacencyFilter) Matches(edge BoundaryEdge) bool

Matches reports whether the edge may be crossed.

Only the crossing fields decide it; the walk fields decide which regions are entered, not which edges. A filter given no crossing field matches every edge. Otherwise an edge matches in two cases: it is virtual and AdjacencyFilter.CrossVirtual is set, or at least one of the elements backing it declares a type in AdjacencyFilter.CrossTypes. An unresolved edge — one which names backing elements the model does not hold — never matches a crossing field which was given, because nothing is known about what realises it: calling it virtual would be the silent reclassification its load error exists to prevent, and it has no element to declare a type.

type Adjacent

type Adjacent struct {
	// contains filtered or unexported fields
}

Adjacent is one region which shares boundary with another, and the edges the two of them share.

Adjacency is defined by those edges and by nothing else: two semantic nodes are adjacent when at least one edge is part of the boundary of both. It is not a distance, not an overlap and not a guess from two outlines which happen to touch — an edge is one node with one identity, and two regions which reach it through their own loops are either reaching the same edge or they are not ([0001](docs/decisions/0001-two-node-families.md)).

Nothing in the format says two regions are adjacent. The relation is computed from the boundary references every time it is asked, so a partition which comes to be shared makes two rooms adjacent with no edit which says so, and the answer cannot drift away from what the model says ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

The zero value holds no node, no region it was reached from and no edges, which no traversal yields.

func (Adjacent) Depth

func (a Adjacent) Depth() int

Depth returns how many steps of adjacency the traversal took to reach it: one for a region on the other side of an edge of this one, two for a region on the other side of one of those, and so on.

func (Adjacent) From

func (a Adjacent) From() *SemanticNode

From returns the region this one was reached from, which is the region Adjacent.Via names the edges shared with. At a depth of one it is the region the walk started from.

The walk is breadth first and reports each region once, at the fewest steps it can be reached in, so one region reached-from per result is a shortest-path tree: following From from any result reaches the region the walk started from in exactly Adjacent.Depth steps, and every region on the way is itself a result of the same walk. Where more than one region a step nearer borders this one, it is the one with the smallest id, for the reason Via explains.

It is written at every depth rather than only past the first, where it could only ever be the subject, so that a result has one shape whichever step it was found at.

func (Adjacent) Node

func (a Adjacent) Node() *SemanticNode

Node returns the region the traversal reached.

func (Adjacent) Relation

func (a Adjacent) Relation() Relation

Relation returns RelationAdjacency, which is what says the result means a shared boundary edge rather than enclosure or grouping.

func (Adjacent) Via

func (a Adjacent) Via() []*Edge

Via returns the edges this region shares with the one it was reached from, in the order that region's boundary traverses them.

Every shared edge is named rather than only the first. Two rooms either side of a partition with a doorway through it share two edges, and which of them a question is about — the wall, or the opening — is the difference between "what separates these rooms" and "how do you get between them". Boundaries.Classified is what says which each of them is.

A result reached at a depth past the first shares its edges with the region which reached it rather than with the region the question was asked about, for the reason it is a step further away: nothing joins them directly. Where more than one region a step nearer borders it, the one it was reached from is the one with the smallest id — never the one read first — so which edges these are is decided by the model and not by which file each region is written in, and can be checked against the boundaries of the regions a step nearer.

A walk given an AdjacencyFilter names only the edges it crossed: the shared edges the filter allows, and not the wall beside the doorway. Under a filter this is the answer to "how do you get between them", and Boundaries.Classify is still where "what separates them" is asked.

type AlreadyClassifiedError

type AlreadyClassifiedError struct {
	// Type is the type the change was about.
	Type string

	// System is the scheme it is already classified in.
	System string

	// Code is what the registry already says it is called there.
	Code string
}

AlreadyClassifiedError reports a type already classified in the system a change would classify it in.

A type carries at most one code per system, so this is not a change which could be applied twice harmlessly: the second code is either the same one, which the file already says, or a different one, which is a correction rather than an addition and has to be written as one.

func (AlreadyClassifiedError) Error

func (e AlreadyClassifiedError) Error() string

Error implements the [error] interface.

type AlreadyDeprecatedError

type AlreadyDeprecatedError struct {
	// ID is the claim.
	ID ID

	// SupersededBy is the claim which already stands in its place.
	SupersededBy ID
}

AlreadyDeprecatedError is a claim retracted a second time.

func (AlreadyDeprecatedError) Error

func (e AlreadyDeprecatedError) Error() string

Error implements the [error] interface.

type AlreadyRetiredError

type AlreadyRetiredError struct {
	// ID is the node.
	ID ID

	// Date is when it was retired.
	Date time.Time

	// Reason is why it was.
	Reason string
}

AlreadyRetiredError reports a node which was retired before this change.

func (AlreadyRetiredError) Error

func (e AlreadyRetiredError) Error() string

Error implements the [error] interface.

type AmbiguousResolutionError

type AmbiguousResolutionError struct {
	// Subject is the thing the question was asked about.
	Subject ID

	// Predicate is the strict predicate it was asked under.
	Predicate string

	// Candidates are the tied claims, in source order.
	Candidates []*Claim
}

AmbiguousResolutionError reports that a predicate the registry declares strict resolved to more than one equally current claim.

It carries the tied claims rather than a count of them because the caller's next move is to say which ones, where they were written and what they say — a message would have to be parsed back apart to do any of that.

func (AmbiguousResolutionError) Error

func (e AmbiguousResolutionError) Error() string

Error implements the [error] interface.

type AmbiguousSupersessionError

type AmbiguousSupersessionError struct {
	// Subject is the thing the claims are about.
	Subject ID

	// Predicate is the predicate they were written under.
	Predicate string

	// Competing names each live claim, by its id where it wrote one and by
	// where it was written where it did not.
	Competing []string
}

AmbiguousSupersessionError is a correction of a subject and predicate the model states more than once.

Which of the competing claims is being corrected is not something to guess at, so the claims are named and the deprecation is left to be spelled out one at a time.

func (AmbiguousSupersessionError) Error

Error implements the [error] interface.

type Anchor

type Anchor struct {
	// contains filtered or unexported fields
}

Anchor is what a reported claim is written on.

It carries what the claim is attached to *and* the geometry which locates it, so that a consumer never has to go back to the model to place an annotation: an edge anchor names its two vertices in the order the edge was authored, and a node anchor names the rings bounding the node. A renderer given only the id of the edge would have to re-read the edge to find out which two corners a dimension runs between, and re-reading is where the two answers drift apart.

The vertices are in authored order and not in the order any ring traverses them. Two rings either side of a party wall run through one edge opposite ways, and a claim written on the edge is written on the edge rather than on either traversal of it; a consumer which needs the traversal direction reads it from the region's boundary segments, which is where that question is already answered.

The zero Anchor names nothing, and every method below works on it.

func (Anchor) ID

func (a Anchor) ID() ID

ID returns the id of the edge or the node the claim is written on.

func (Anchor) Kind

func (a Anchor) Kind() AnchorKind

Kind returns which family of thing the claim is written on.

func (Anchor) Rings

func (a Anchor) Rings() []ID

Rings returns the loops bounding the node the claim is written on, in the order the node references them.

It is empty for an edge anchor, and for a node which references no loop — which is what a claim carried by an entry of Plan.Undrawn is anchored to where the reason is UndrawnNoBoundary.

func (Anchor) String

func (a Anchor) String() string

String renders the anchor as a person reads it: what the claim is written on and where that is.

func (Anchor) Vertices

func (a Anchor) Vertices() (start, end ID, ok bool)

Vertices returns the anchor's two vertices in the order the edge was authored, and whether it is an edge anchor at all.

type AnchorKind

type AnchorKind string

AnchorKind is which family of thing a claim reported on a plan is written on.

There are two because there are two places a fact about a room can be written: on the room, or on one of the edges bounding it. A width is written on the edge it is the width of; an area and a name are written on the node. Which of the two an annotation came from is what a renderer needs in order to put it anywhere at all, and it is a fact about the model rather than a property of the claim.

const (
	// AnchorEdge is a claim written on an edge of a ring.
	AnchorEdge AnchorKind = "edge"

	// AnchorNode is a claim written on the semantic node the ring bounds.
	AnchorNode AnchorKind = "node"
)

The kinds of anchor.

type Annotation

type Annotation struct {
	// contains filtered or unexported fields
}

Annotation is one live claim reported on a plan, with what it is written on.

The claim comes back whole rather than as a number and a unit. A dimension handed over as a bare figure is exactly what this format exists to refuse ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)), and a sheet is the last place it should be refused less firmly: the string a renderer prints against a wall is a claim somebody made, with a source, a method, a date and an accuracy, and printing it without them is how a design estimate comes to look like an as-built survey.

The zero Annotation carries no claim, and every method below works on it.

func (Annotation) Anchor

func (a Annotation) Anchor() Anchor

Anchor returns what the claim is written on.

func (Annotation) Claim

func (a Annotation) Claim() *Claim

Claim returns the claim, whole.

func (Annotation) Predicate

func (a Annotation) Predicate() string

Predicate returns the predicate the claim was written under, which is one of the predicates the invocation named.

func (Annotation) String

func (a Annotation) String() string

String renders the annotation as a person reads it: the predicate, what it is written on and where the claim itself was written.

type Annotations

type Annotations struct {
	// Predicates are the predicates whose claims are reported, in the order
	// they were named. A predicate named twice is read once.
	Predicates []string
}

Annotations is which claims a plan reports beside the rings it draws.

It is a list of predicates and nothing else. Whether a measurement is worth drawing on a sheet is not a question this engine can answer — it has no vocabulary of its own ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)) — so the answer is "it is worth drawing if the caller asked for that predicate", stated on the invocation, with no default and no default ever.

The consequence is the point: the plan learns nothing about drawing. It does not know that a width goes on a leader and a room name goes in the middle, because it never decides which of them to report.

type Applied

type Applied struct {
	// Index is the operation's place in the batch, counted from one as a person
	// counts a list.
	Index int

	// Operation is the name it was written under.
	Operation string

	// Effects are what it did to the model, in the order the mutations were
	// applied. They are the same effects [Commit] reports against the files
	// they landed in, grouped by the operation which caused them instead.
	Effects []Effect

	// Claim is the id of the claim it wrote, and is empty for an operation
	// which wrote none or wrote one with no id of its own.
	Claim ID

	// Replaced is the id of the claim it retracted, and is empty for an
	// operation which retracted none.
	Replaced ID

	// Snaps is every corner a scaffold landed on a vertex the model already
	// held, and is empty for every other operation. A reuse is the one thing
	// about a scaffold which is surprising when it happens and worse when it
	// does not, so it is reported per operation rather than left to be inferred
	// from which nodes appeared.
	Snaps []Snap

	// Tolerance is the declaration those snaps were judged against, and is the
	// zero tolerance for an operation which judged nothing. It travels with them
	// because the answer depends on it.
	Tolerance Tolerance

	// Notices are what it had to say about the model it produced — that a claim
	// is unrankable, that it now competes with another — in the order the
	// engine reported them. None of them refuses anything.
	Notices []Notice
}

Applied is what one operation of a batch did.

It is reported per operation rather than only in total because a batch is authored as a list and read back as one: an author who wrote fifty operations and is told that eleven nodes were created has to work out which eleven.

type AppliedBand

type AppliedBand struct {
	// Instance is the id of the thing the rule was run against.
	Instance ID `json:"instance"`

	// Type is the name of its type, which is what declared the invariant. It is
	// empty for an assertion, which is declared on the thing itself.
	Type string `json:"type,omitempty"`

	// Check is the check name the rule named.
	Check string `json:"check"`

	// Arguments are the parameters it was evaluated with, each rendered the way
	// it was written.
	Arguments []string `json:"arguments,omitempty"`

	// Parameters are the same parameters as data, one per entry of Arguments
	// and in the same order ([Rule.Parameters]).
	Parameters []Parameter `json:"parameters,omitempty"`

	// Declared is where the rule was written: a position in a registry file for
	// an invariant, and the thing itself for an assertion.
	Declared Span `json:"declared"`

	// Subject is where the thing the rule was run against is written.
	Subject Span `json:"subject"`

	// Band is what the comparison was decided against.
	Band Band `json:"band"`
}

AppliedBand is one band a rule was decided against, with the rule which applied it.

It is to Band what Violation is to Failure: the check reports what it compared and against what, the run says which rule was doing the comparing, and the two are joined once rather than in every check.

Every field a reader needs in order to act on it is here rather than folded into a message, and for the reason Violation states: a rule written once and applied to a hundred and fifty instances is one whose band has to lead back to the single place the tolerance it widened is declared.

type Arc

type Arc struct {
	// Centre is the resolved position of the centre of the circle the edge
	// bends along, in the frame the edge is declared in and in that frame's
	// unit. A centre written in another unit is not read at all
	// ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).
	Centre Value

	// Through is the resolved position of a point the curve passes through
	// between its two ends, which is what says which of the two arcs is meant.
	//
	// A centre and two ends leave two arcs — the short way round and the long
	// way round — and in three dimensions they leave a plane undecided as well,
	// because ends diametrically opposite a centre lie on every plane through
	// the line between them. One point on the curve answers both at once and
	// answers them the way a surveyor would: it is somewhere on the wall, and it
	// was measured.
	//
	// It decides which arc and never where it is. The radius is read from the
	// centre and the start, the sweep from the centre and the two ends, so a
	// point on the curve half a millimetre out picks the same arc and moves no
	// figure — which is why the accuracy of the claim behind it is not
	// accumulated into an answer and the accuracy of the centre is. What it is
	// checked for is being on the circle at all, which a claim disagreeing with
	// the centre is not.
	Through Value
}

Arc is the circle an edge bends along: where its centre is and a point the curve passes through between its two ends.

It is a parameterisation and never a list of points. An arc approximated into segments while it was being authored cannot be recovered afterwards — every consumer inherits the resolution whoever drew it happened to pick, and none of them can tell that it happened. Keeping the curve a curve is what makes the approximation a decision somebody takes deliberately, at the moment something actually requires straight lines, and with a stated tolerance (Topology.TessellateLoop).

It is supplied rather than read, for the reason Positions is: which predicate carries an arc centre is vocabulary the consuming repository owns and not something the engine knows ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)). A repository which spells the two `arc-centre` and `arc-through` resolves those predicates for the edges which bend and hands the result to Survey.Bend; one which spells them something else spells them something else, and nothing here changes. That is what the specification means by the predicate registry being the extension point for a non-straight edge: no form, no kind and nothing compiled in here learns a new name when an arc arrives.

The two ends are the edge's own vertices and are never restated. An arc whose endpoints were written a second time would be a second source of truth for where a corner is, and the first move of a corner would put the two out of step ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

Both fields are positions, which is what lets an arc be claimed the way every other measurement is: each is written under a predicate the registry declares, in the frame's unit, with its own source, method, date and accuracy.

The zero Arc bends nowhere and is reported as a degenerate arc rather than quietly measured as a straight edge.

type ArchiveEntryError

type ArchiveEntryError struct {
	// Name is the entry name, as the archive wrote it.
	Name string

	// Dest is the directory it was being written into.
	Dest string
}

ArchiveEntryError is an archive entry whose name is not a path beneath the directory it was being written into.

It carries the name exactly as the archive wrote it, rather than the path joining it would have produced: what is being reported is what the input said, and the join is the thing which never happened.

func (ArchiveEntryError) Error

func (e ArchiveEntryError) Error() string

Error implements [error].

func (ArchiveEntryError) Unwrap

func (e ArchiveEntryError) Unwrap() error

Unwrap implements the interface errors.Is and errors.As walk.

type Argument

type Argument struct {
	// Name is the tag the parameter was written with.
	Name string

	// Values are the datums written after that tag, in the order they were
	// written. A parameter which takes one value has one.
	Values []*Node

	// Span is where the parameter form was written.
	Span Span
}

Argument is one parameter of an invariant as it was written.

The values are the datums the registry file holds, unmodified. Nothing re-reads them here: every one of them was read as the sort of datum the check declares it takes when the registry loaded, and a name it resolved — a tolerance, a predicate, a type — was resolved against the registry then (ValidateAssertion). What a run needs from this layer is what was written and where, which is also what a violation has to print.

func (Argument) String

func (a Argument) String() string

String renders the parameter the way it was written, which is what a violation naming the parameters it was evaluated with prints.

A value which is not an atom is rendered as an ellipsis rather than expanded. No parameter of any check takes one — every ParameterType is an atom — so this is the rendering of something already reported at load, and quoting a whole subtree into a one-line message would bury the rest of it.

func (Argument) Symbol

func (a Argument) Symbol() (string, bool)

Symbol returns the one symbol written for the parameter, and whether exactly one was written and it is a symbol.

It is how a parameter naming an entry of a registry is read, which is most of them: a tolerance, a predicate and a type are each written as the name they were declared under.

func (Argument) Symbols

func (a Argument) Symbols() []string

Symbols returns every symbol written for the parameter, in the order they were written, which is how a repeated parameter naming registry entries is read. A value which is not a symbol is left out.

type Assembly

type Assembly struct {
	// contains filtered or unexported fields
}

Assembly is one loop assembled into the ring its edges traverse, together with whether that ring closes and the named tolerance it was judged against.

Closure is computed and never stored. Nothing in the format says whether a loop closes, adding an edge changes the answer with no other edit, and a recorded answer would be stale the moment a vertex moved ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

The tolerance travels with the result because the result depends on it. "This loop closes" is not a fact about the loop alone: it is a fact about the loop judged against a stated tolerance, and an answer which did not say which one could not be checked, reproduced or argued with ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).

The zero value is an assembly of no loop, which is what assembling a nil loop yields; every method below works on it.

func (Assembly) Closed

func (a Assembly) Closed() bool

Closed reports whether the edges form a connected, simple cycle: each begins where the last ended, the last ends where the first began, and no corner joins more than two of them.

Two corners which are different vertices count as one point when they are no further apart than the tolerance the assembly was judged against, which is what Assembly.Tolerance reports.

func (Assembly) Loop

func (a Assembly) Loop() *Loop

Loop returns the loop which was assembled.

func (Assembly) Open

func (a Assembly) Open() bool

Open reports whether the edges were read as an open run rather than as a ring.

It is a fact about the reading and not about the edges. A run whose two ends happen to meet is both open and closed — it was read as a chain, and the chain came back to where it began — and a caller drawing it has to know which of the two questions it is holding the answer to.

func (Assembly) Steps

func (a Assembly) Steps() []Step

Steps returns the loop's edges in the order the traversal ran through them, each with the direction it ran.

A loop which did not close still has steps: they are how far the traversal got, which is what a caller reporting on the failure wants to show.

func (Assembly) Tolerance

func (a Assembly) Tolerance() Tolerance

Tolerance returns the declared tolerance closure was judged against.

Its zero value belongs to an assembly whose tolerance was not declared, which is reported as a diagnostic and leaves closure decided by vertex identity alone. There is no default and no fallback ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).

type Assertion

type Assertion struct {
	// Check is the check name written after the assert tag.
	Check string

	// Parameters are the parameter forms written after it, unmodified.
	Parameters []*Node

	// Span is where the assertion was written, which is inside the form of the
	// thing it constrains.
	Span Span
}

Assertion is one check written on one thing, per specification section 6.8.

An assertion is a check name and its parameters and nothing else. There is no expression language, so what an assertion constrains is readable from what is written here — the name resolves in the engine's closed check registry and the registry says what each parameter means ([0011](docs/decisions/0011-assertions-are-named-parameterised-checks.md)).

It is written on the thing it constrains, which is what tells it apart from the Invariant of a type: an invariant is one rule about every instance of a type, and an assertion is one rule about this patio. Neither is a place to record what something *is*; see ResolveAssertions for the rule which keeps an assertion from becoming one.

The check name and the parameters are the check registry's vocabulary rather than this layer's, so what is recorded is what was written and where.

func (Assertion) Arguments

func (a Assertion) Arguments() []Argument

Arguments reads the parameters the assertion was written with.

func (Assertion) String

func (a Assertion) String() string

String renders the assertion as the check name followed by the parameters it was written with.

type AssertionBinding

type AssertionBinding struct {
	// Subject is the thing the assertion was written on, whichever family holds
	// it.
	Subject Entity

	// Form is the form it was written on, which is the axis a check declares
	// first.
	Form SubjectForm

	// Check is what the engine's closed check registry says the named check
	// constrains and takes.
	Check CheckDeclaration

	// Declared is the assertion as it was written. Its span is the file and
	// line a violation points back at.
	Declared Assertion

	// Arguments are the parameters it was written with.
	Arguments []Argument
	// contains filtered or unexported fields
}

AssertionBinding is one assertion together with what the check registry says the check it names constrains and takes.

It is the assertion as something above the format can act on: the written form resolved against the closed registry, with the parameters read as arguments and the implementation attached where there is one. Nothing is stored on the subject, so an assertion is bound from what was written every time it is asked for.

func (AssertionBinding) Applicable

func (b AssertionBinding) Applicable() bool

Applicable reports whether the check can examine the thing the assertion was written on.

One which cannot is a load error rather than a filter, which is what tells it apart from an invariant: an invariant is declared once for a type whose instances differ, so a check which cannot examine this instance is ordinary, while an assertion is written on one thing by somebody looking at it.

func (AssertionBinding) Argument

func (b AssertionBinding) Argument(name string) (Argument, bool)

Argument returns the parameter written under name, and whether one was.

func (AssertionBinding) Runnable

func (b AssertionBinding) Runnable() bool

Runnable reports whether the check has an implementation to run.

A check which declares itself and implements nothing binds, lists and validates exactly as one which does, and running it reports nothing.

func (AssertionBinding) String

func (b AssertionBinding) String() string

String renders the binding as the thing it was written on and the assertion as it was written.

type AssertionSpec

type AssertionSpec struct {
	// Subject is the thing the assertion constrains.
	Subject ID

	// Check is the name of the check it applies.
	Check string

	// Parameters are the parameters, in the order they are written.
	Parameters []string
}

AssertionSpec is an assertion which is not written yet: the thing it constrains, the check it names and the parameters it supplies.

The parameters are text rather than forms, each spelled as the entity format writes it without its parentheses — `predicate width`, `tolerance boundary-closure`, `zone site:Z-90` — which is how an accuracy term is spelled on a command line and in an operation file. Which sort of datum a parameter takes is the check's declaration, exactly as which shape a value takes is the predicate's, so one spelling means a parameter written in either place is read by the same code and refused in the same words.

type Assumption

type Assumption struct {
	// Graph is the model the batch would produce. Its [Graph.Digest] is the
	// digest of the tree the batch would produce — what [DigestOf] would compute
	// were the batch written — so anything derived from it is keyed by that
	// tree and not by the one that was read.
	Graph *Graph

	// Applied is what each operation did, as [Tx.Apply] reports it.
	Applied []Applied

	// Base is the digest of the tree that was read, which is what tells a caller
	// which tree the batch was assumed over.
	Base Digest

	// Sources is what the diagnostics [Assume] returned beside it were raised
	// over: the printing of every file the batch touched, over the files on
	// disk it did not. A caller rendering those diagnostics quotes from it, so
	// that each one is shown the line of the tree the batch would produce
	// rather than the line at the same position on disk.
	//
	// It is set wherever the batch produced a tree, including a tree which
	// would not load — whose diagnostics are the ones that most need it — and
	// nil where it produced none, in which case every diagnostic is about the
	// tree on disk.
	Sources SourceMap
}

Assumption is the model a batch would produce, interpreted without being written.

It is what a read answers over when it is told to assume a batch ([0030](docs/decisions/0030-a-read-may-assume-a-batch.md)): not the tree on disk, but the tree which would be there had the batch been applied.

type BackingSpec

type BackingSpec struct {
	// BackedBy are the ids of the elements which physically realise the edge,
	// in the order they were given. Canonical form sorts them, so the order
	// decides nothing.
	BackedBy []ID

	// Virtual says the edge is backed by nothing at all, which is how a
	// demolished wall's edge becomes the open line it now is.
	Virtual bool
}

BackingSpec is what an edge is physically realised by: the whole set, stated rather than patched.

`backed-by` is unordered and repeatable, so a change to it says what the edge is backed by now rather than which references to add and which to remove. The empty set is stated with Virtual, never by leaving BackedBy empty: an absent statement must not read as "backed by nothing" (specification section 6.3).

func (BackingSpec) Check

func (spec BackingSpec) Check(id ID) error

Check reports what is wrong with the spec on its own terms, before any model is read: that it states neither the elements nor that the edge is virtual, that it states both, or that one of the elements is the empty id.

The edge the spec is written on is named so that the refusal can say which edge it was about.

type Band

type Band struct {
	// Tolerance is the name of the declared tolerance the rule was given, which
	// is where a reader goes to change the floor.
	Tolerance string `json:"tolerance"`

	// Floor is that tolerance's value: the narrowest figure this comparison
	// could have been decided against.
	Floor float64 `json:"floor"`

	// Applied is the figure the difference was actually compared against, which
	// is Floor or the terms combined where that is wider.
	Applied float64 `json:"applied"`

	// Unit is what Floor, Applied and Difference are in. It is the unit of what
	// is compared, so it is the square of the frame's linear unit for an area
	// and the linear unit itself for a length.
	Unit Unit `json:"unit"`

	// Difference is the magnitude of the gap the band was applied to: how far
	// apart the two figures are, with no sign, because which of them is larger
	// is the failure's to say and is not what the band decided.
	Difference float64 `json:"difference"`

	// Widened reports whether Applied is wider than Floor, which is whether the
	// check decided against a figure nobody wrote down.
	Widened bool `json:"widened"`

	// Decisive reports whether the widening is what decided the answer: the
	// difference is inside Applied and outside Floor, so the same comparison
	// made against the declared tolerance alone would have gone the other way.
	//
	// It is what tells a pass which needed the widening from a pass within the
	// tolerance as written, and those are two different states of a model. The
	// first is a criterion the survey is not accurate enough to test; the second
	// is a criterion which held.
	Decisive bool `json:"decisive"`

	// Terms are the accuracies combined into Applied, one per side of the
	// comparison which stated one, in the order the check reports them. It is
	// empty where neither side stated one and the floor is the whole of the
	// test.
	Terms []BandTerm `json:"terms,omitempty"`
}

Band is what a check decided a comparison against, where the tolerance it was declared with is the floor under the answer rather than the whole of it.

Widening is right and is not in question: a claim cannot be held to a precision the geometry does not have, and two figures which differ by less than their combined uncertainty do not disagree. What a band is for is saying so. Left unreported, the number the registry states is not the number the check applies and nothing says which is which — so a rule written as "the boundary agrees with the appraisal to within half a square foot" can be satisfied by a comparison made against eight, and the run which passed it reads exactly like one which did not need to widen anything.

That is the failure this reports: not a wrong answer, but an acceptance criterion nobody can falsify. It is reported on passes as well as failures for the same reason — a pass is the answer whose band nothing else in the output discloses.

A check which decides against the tolerance it was given and nothing else reports no band. There is nothing to disclose: the declared figure is the applied one, and it is already written in the rule.

type BandSource

type BandSource string

BandSource is what stated one of the accuracies a band was widened by.

The set is closed because it is read by whatever acts on the answer, and a phrase composed at each call site would be a vocabulary nothing could match on. Which of them a check reports is decided by what the check compares, and nothing else about a term says which side of the comparison it came from.

const (
	// BandFromClaim is the accuracy the claim under comparison states of
	// itself: the area somebody wrote down, and how well they say they know it.
	BandFromClaim BandSource = "claim"

	// BandFromCorners is the accumulated accuracy of the position claims the
	// subject's own shape is read from.
	BandFromCorners BandSource = "corners"

	// BandFromContainer is the same for the shape the subject is judged
	// against, where the check compares two shapes rather than a shape and a
	// number.
	BandFromContainer BandSource = "container"

	// BandFromTransform is the accumulated accuracy of the transform claims a
	// subject was carried across to reach the frame it is judged in, where the
	// two shapes of a comparison are declared in different frames.
	//
	// It is a side of its own rather than part of the subject's corners because
	// it is fixed somewhere else: a corner is re-surveyed, and a fit between two
	// frames is re-fitted. A reader told only that the subject is loosely known
	// would go and re-occupy corners which were never the problem.
	BandFromTransform BandSource = "transform"
)

The sides of a comparison which state an accuracy of their own.

type BandTerm

type BandTerm struct {
	// Source is which side of the comparison stated it.
	Source BandSource `json:"source"`

	// Sigma is the one standard uncertainty that side states, in Unit. It is
	// one sigma because every accuracy in a model is
	// ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).
	Sigma float64 `json:"sigma"`

	// Unit is what Sigma is in, which is not always the band's own unit: an
	// area is compared in the square of a length and the corners behind it are
	// surveyed in the length, which is the whole reason Sensitivity exists.
	Unit Unit `json:"unit"`

	// Sensitivity is how far the compared figure moves per unit of Sigma, which
	// carries the term into the band's unit. It is one where the two are already
	// in the same unit, and the length of the boundary where a corner
	// displacement is carried across to the area it encloses: displacing a
	// boundary of length P by δ changes the area it encloses by about P·δ. It is
	// a first-order sensitivity and is reported as one.
	Sensitivity float64 `json:"sensitivity"`

	// Contribution is Sigma × Sensitivity, in the band's unit, which is the
	// figure combined into the band. It is written rather than left to be
	// multiplied out because it is the number a reader compares against the
	// declared tolerance, and a reader doing the multiplication is a reader who
	// can do it wrong.
	Contribution float64 `json:"contribution"`

	// Claims are the claims the term was read from, where the side is not one
	// the comparison already names. It is written for [BandFromTransform] — the
	// fits a subject was carried across are claims on frames, which appear
	// nowhere else in the answer — and is empty for every other source, whose
	// claims are the positions of the shapes the failure already points at.
	Claims []ID `json:"claims,omitempty"`
}

BandTerm is one accuracy which went into a band.

It is reported rather than folded into the total because the total is not actionable on its own. A band eight times the tolerance it was declared with is either a tape nobody has calibrated or a figure whose author stated an honest uncertainty, and the two are fixed in different places — so a reader has to be told which side of the comparison the width came from and how much of it each side is.

type Batch

type Batch struct {
	// Version is the version of the format the file was written against, which
	// is [BatchVersion] for a file which did not say.
	Version int

	// Operations are the operations, in the order they are applied. The order
	// is the data: an operation may name what an earlier one wrote.
	Operations []Operation
}

Batch is an ordered list of authoring operations applied as one change.

It is what an operation file decodes to. Applying it is Tx.Apply, which is one transaction however many operations it holds: the model is read once, the operations are applied to it in order, and the model they produce together is interpreted once at Tx.Commit. A batch of fifty edits therefore costs one load rather than fifty, which is the reason it exists ([0015](docs/decisions/0015-the-cli-is-the-primary-write-path.md)).

func ParseBatch

func ParseBatch(r io.Reader) (Batch, error)

ParseBatch reads an operation file.

The file is one JSON object: an optional `version`, which must be BatchVersion, and `operations`, the operations in the order they are applied. Every operation is an object whose `op` names which operation it is and whose other members are that operation's axes, spelled as the flags of the command which makes the same change on its own.

**Nothing is guessed.** A member no operation of that name reads is refused rather than ignored, an operation nothing declares is refused naming the ones there are, and a member an operation requires and which was not written is refused before any model is read. A batch which a caller generated is exactly the input where a silently dropped member is discovered a week later.

**Every problem comes back at once**, as a BatchError holding one OperationError per operation which has one, in the order they were written. An author fixing a refused batch should not have to resubmit it once per mistake ([0016](docs/decisions/0016-writes-are-all-or-nothing.md)).

What cannot be answered here is what the registry decides: which shape a value takes, which predicates and types are declared, which ids are free. Those are read when the batch is applied to a model, by Tx.Apply, and are reported the same way — naming the operation they are about.

Example (Refused)

ExampleParseBatch_refused reports every problem an operation file has at once, each naming the operation it is about by its place in the list.

An author fixing a batch a tool generated should not have to reissue it once per mistake, which is the same rule a refused write is reported by.

package main

import (
	"errors"
	"fmt"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	_, err := dfcad.ParseBatch(strings.NewReader(`{
		"operations": [
			{"op": "add-node", "kind": "Space"},
			{"op": "add-node", "id": "site:S-103", "edges": ["geom:E-01"]},
			{"op": "add-widget", "id": "site:S-104"}
		]
	}`))

	var refused dfcad.BatchError
	if errors.As(err, &refused) {
		for _, problem := range refused.Errs {
			fmt.Println(problem)
		}
	}

	// Every problem is reachable, so a caller branches on what is wrong rather
	// than on the message saying so.
	fmt.Println("no id was written:", errors.Is(err, dfcad.ErrNoID))

}
Output:
operation 1, add-node: a node is written with an id
operation 2, add-node: json: unknown field "edges"
operation 3, add-widget: unknown operation "add-widget": want one of add-node, add-vertex, add-edge, add-loop, scaffold-loop, relate, classify-type, set-label, retire, add-claim, supersede, deprecate-claim, add-assertion, set-backing, set-edges
no id was written: true

type BatchError

type BatchError struct {
	// Errs is what was found, in the order the operations were written. Each
	// one about an operation is an [OperationError] naming which.
	Errs []error
}

BatchError is everything wrong with one operation file.

It carries every problem rather than the first, which is the rule the whole engine reports input by ([0016](docs/decisions/0016-writes-are-all-or-nothing.md)): an author fixing a refused batch should not have to resubmit it once per mistake.

func (BatchError) Error

func (e BatchError) Error() string

Error implements [error].

func (BatchError) Unwrap

func (e BatchError) Unwrap() []error

Unwrap returns every problem, so that errors.Is and errors.As reach each of them.

type Boundaries

type Boundaries struct {
	// contains filtered or unexported fields
}

Boundaries is the boundary references of one model, resolved: which loop each semantic node is bounded by, and which nodes each loop, edge and vertex is part of the boundary of.

It is the join between the two families and is the only thing in the engine which holds one. A `boundary` is written on a semantic node and names a member of the geometric family, so no pass which has read one family can resolve it ([0001](docs/decisions/0001-two-node-families.md)); this is what the pass which has read both produces.

Both directions are indexed, because both are asked and only one is written. "What is this room bounded by" reads the reference forwards; "what does this wall bound" reads it backwards, is written nowhere, and is the question which makes a shared edge visible as shared. Computing the reverse by scanning every node per question would make it quadratic in the size of the model.

A Boundaries is read-only once resolved. The zero value holds nothing, which is what a model with no boundary reference in it yields, and every method below works on it.

func (*Boundaries) Adjacent

func (b *Boundaries) Adjacent(region *SemanticNode) iter.Seq[Adjacent]

Adjacent iterates the regions which share at least one boundary edge with region, each once and with the edges they share.

This is "what borders this room", and it is answered from the model rather than from geometry: the shared edge is the same node reached from both sides, so two rooms are adjacent exactly when one of them reaches an edge the other reaches too. Two outlines which meet along a line drawn twice are two boundaries which happen to coincide, and this reports them as what they are — unrelated — which is the whole reason a boundary is a reference rather than a copy of a coordinate.

A region is never adjacent to itself, however many of its own edges it reaches. Its own boundary is not something on the other side of it.

The order is the order region's boundary traverses its edges, which is the order its loops were written in and is deterministic. A neighbour reached through two shared edges comes back once, carrying both.

Example

ExampleBoundaries_Adjacent answers what borders what, which is read from the edges two regions share rather than from how close their outlines are.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/boundary/adjacent"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)

	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	room, _ := nodes.Node("site:S-A")

	// Every edge the two of them share is named. One is a partition and the
	// other is the doorway through it, which is the difference between what
	// separates two rooms and how anybody gets between them.
	for neighbour := range boundaries.Adjacent(room) {
		for _, edge := range neighbour.Via() {
			fmt.Printf("%s borders %s across %s, which is %s\n",
				room.ID(), neighbour.Node().ID(), edge.ID(), boundaries.Classified(edge).Classification())
		}
	}

	// Room C shares no edge with room A, so it is two steps away rather than
	// one, however close the two of them look on a plan.
	for neighbour := range boundaries.AdjacentTo(room, dfcad.Unbounded) {
		fmt.Printf("%s is %d away\n", neighbour.Node().ID(), neighbour.Depth())
	}

}
Output:
site:S-A borders site:S-B across geom:E-02, which is physical
site:S-A borders site:S-B across geom:E-03, which is virtual
site:S-B is 1 away
site:S-C is 2 away

func (*Boundaries) AdjacentTo

func (b *Boundaries) AdjacentTo(region *SemanticNode, depth int) iter.Seq[Adjacent]

AdjacentTo iterates the regions region borders, the regions those border, and so on, stopping after depth steps.

It is Boundaries.Adjacent followed outward: a depth of one is what is on the other side of this room's walls, a depth of two adds what is on the other side of theirs, and Unbounded is everything reachable from it through shared boundary — which for a floor plan drawn as one connected set of rooms is the floor.

Each region comes back once, at the fewest steps it can be reached in, so a ring of rooms terminates and a room reachable two ways is one result. A depth of zero takes no step and yields nothing.

Every result at the first step is reached from region itself. Past it, a result is reached from the region one step nearer which has the smallest id among those it shares an edge with, and that is the region its Adjacent.From names and its Adjacent.Via names the edges shared with. Each step is expanded in id order to make it so: expanding in the order regions were discovered would choose by the order the files were read in, and moving a region between files would change the answer.

Every shared edge may be crossed. It is Boundaries.AdjacentWalk with an empty AdjacencyFilter, and answers exactly what that does.

func (*Boundaries) AdjacentWalk

func (b *Boundaries) AdjacentWalk(region *SemanticNode, depth int, filter AdjacencyFilter) iter.Seq[Adjacent]

AdjacentWalk iterates the regions reachable from region across the shared edges filter allows to be crossed, through the regions it allows to be entered, stopping after depth steps.

It is Boundaries.AdjacentTo with a say in which edges are ways through. A walk from a corridor with a filter naming only doorways reaches the rooms whose doors open onto it and not the riser behind a solid wall, which is the question "what can somebody reach from here" rather than "what is next to what". A region which shares only edges the filter refuses is not reached across them, though it may still be reached another way.

A region the filter does not enter is neither reported nor walked through, so a walk which enters only spaces cannot step from one room onto the lot both border and from there into a room on its far side. The walk starts from region whatever region declares, and every result, and every region a result is reached from past the first step, is one the filter enters.

Adjacent.Via names only the edges crossed — the crossable edges the result shares with the region it was reached from — so under a filter it answers "how do you get between them" rather than "what separates them". Adjacent.From is the region one step nearer with the smallest id among those which share a crossable edge with it.

An empty filter crosses every shared edge into every region and answers exactly what Boundaries.AdjacentTo does.

Example

ExampleBoundaries_AdjacentWalk answers what can be reached from a room rather than what is next to it, by saying which shared edges are ways through.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/boundary/adjacent"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)

	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	room, _ := nodes.Node("site:S-A")

	// This model draws its doorway as an edge nothing backs, so crossing
	// virtual edges is crossing the doorway. The corridor is reached through it
	// and not through the partition beside it, and room C, behind a partition
	// with no opening, is not reached at all.
	passable := dfcad.AdjacencyFilter{CrossVirtual: true}

	for neighbour := range boundaries.AdjacentWalk(room, dfcad.Unbounded, passable) {
		for _, edge := range neighbour.Via() {
			fmt.Printf("%s reaches %s through %s\n", neighbour.From().ID(), neighbour.Node().ID(), edge.ID())
		}
	}

}
Output:
site:S-A reaches site:S-B through geom:E-03

func (*Boundaries) Bounded

func (b *Boundaries) Bounded(loop *Loop) iter.Seq[*SemanticNode]

Bounded iterates the nodes loop bounds, in the order the walk read them.

It is the reverse of Boundaries.Loops. The reference is written on the semantic node, so this direction is written nowhere and is indexed when the two families are joined.

func (*Boundaries) Classified

func (b *Boundaries) Classified(edge *Edge) BoundaryEdge

Classified pairs edge with its classification and with the elements which back it.

The answer is computed here and is held nowhere: ask it again after adding an element and it is a different answer, which is the point ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

An edge this join never resolved — one from another model, or one asked of a Boundaries which resolved nothing — classifies from what the edge itself wrote. An edge which named no element is virtual; one which named any is unresolved, because nothing here reached them.

func (*Boundaries) Classify

func (b *Boundaries) Classify(region *SemanticNode) iter.Seq[BoundaryEdge]

Classify iterates the edges of region's boundary, each classified, in the order Boundaries.Edges gives them and each yielded once.

This is the question "what actually separates these two rooms", asked of a region rather than of an edge. The answer is computed from whether each edge names an element the model holds, so it cannot disagree with the model: adding a wall moves an edge from virtual to physical with no edit to the region at all.

The order is the order the region's loops traverse its edges, which is deterministic, so anything built from it diffs against the last run's.

Example

ExampleBoundaries_Classify asks what actually separates a region from what is on the other side of each edge of its boundary.

An edge which names an element the model holds is a physical boundary; one which names none is virtual — the open line between a foyer and a dining room. The answer is computed from the reference every time it is asked and is stored nowhere: nothing in the file says "physical", so adding a wall makes the boundary physical with no second edit.

package main

import (
	"fmt"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/boundary/backed"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)

	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	room, _ := nodes.Node("site:S-101")
	for boundary := range boundaries.Classify(room) {
		// Every element is named rather than only the first. A stud wall with a
		// glazed screen over it is two things, and naming one of them would
		// answer with half the wall.
		var backing []string
		for _, element := range boundary.Backing() {
			backing = append(backing, string(element.ID()))
		}

		fmt.Printf("%s is %s", boundary.Edge().ID(), boundary.Classification())
		if len(backing) > 0 {
			fmt.Printf(", backed by %s", strings.Join(backing, " and "))
		}
		fmt.Println()
	}

}
Output:
geom:E-01 is virtual
geom:E-02 is physical, backed by site:W-14 and site:W-15
geom:E-03 is virtual
geom:E-04 is virtual

func (*Boundaries) Edges

func (b *Boundaries) Edges(region *SemanticNode) iter.Seq[*Edge]

Edges iterates the edges region's boundary is assembled from, in the order its loops traverse them and each yielded once.

It reaches through the loops rather than past them. A region depends on an edge because a loop it references names that edge, which is what makes the dependency real: the edge is one node with one identity, and moving it moves every region which reaches it.

An edge reached through two of a region's loops is yielded once, because the question is what the region depends on and not how many ways it gets there.

func (*Boundaries) Loops

func (b *Boundaries) Loops(region *SemanticNode) iter.Seq[*Loop]

Loops iterates the loops region is bounded by, in the order it wrote them.

A node with no boundary yields nothing, which is ordinary: a circuit group and a warranty have no outline, and neither is malformed.

Only a reference which resolved is here. A `boundary` naming nothing, or naming something which is not a loop, is a diagnostic from ResolveBoundaries rather than a state a caller has to interpret.

func (*Boundaries) Regions

func (b *Boundaries) Regions(edge *Edge) iter.Seq[*SemanticNode]

Regions iterates the nodes edge is part of the boundary of, in the order the walk read them.

This is what a shared wall looks like from the wall. Two spaces either side of a partition reference one edge through their own loops, and asking the edge which regions reach it gives both — from one edge with one identity, rather than from two copies of a coordinate which can drift apart ([0001](docs/decisions/0001-two-node-families.md)).

func (*Boundaries) Vertices

func (b *Boundaries) Vertices(region *SemanticNode) iter.Seq[*Vertex]

Vertices iterates the vertices region's boundary is assembled from, in the order its edges reach them — start then end, per edge — and each yielded once.

It is Boundaries.Edges one step further down. A vertex shared by two edges of the same ring is one corner and is yielded once, which is what makes the count of them the count of the region's corners rather than twice it.

type BoundaryEdge

type BoundaryEdge struct {
	// contains filtered or unexported fields
}

BoundaryEdge is one edge of a region's boundary, classified.

It pairs the edge with the elements which physically realise it, which is everything the classification is computed from. The classification itself is not a field: it is BoundaryEdge.Classification, computed from the ids the edge wrote and the elements they reached, so that there is one rule and nowhere for a second copy of the answer to go stale ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

The zero value is no edge, which classifies as virtual: an edge which names nothing is backed by nothing.

func (BoundaryEdge) Backing

func (b BoundaryEdge) Backing() []*SemanticNode

Backing returns the elements which physically realise the edge, in the order the edge named them.

Every one of them is named rather than only the first. An edge realised by a stud partition and the glazed screen above it is backed by two elements, both of which are what somebody asking what separates the rooms is asking about, and picking one of them would answer with half the wall.

It is empty for a virtual edge, and empty for one whose references did not resolve — which BoundaryEdge.Classification tells apart.

func (BoundaryEdge) Classification

func (b BoundaryEdge) Classification() Classification

Classification reports whether the edge is backed by a real element.

The rule is the whole of it, and is specification section 6.3: an edge with at least one resolving `backed-by` is physical, one which wrote none is virtual, and one which wrote some and reached none of them is unresolved. Nothing is read from a stored flag, because there is none to read.

An edge which named two elements and reached one of them is physical, because something real does back it. The reference which failed is still a load error and is still reported; what it is not is a reason to answer a question the model did settle with the answer to one it did not.

func (BoundaryEdge) Edge

func (b BoundaryEdge) Edge() *Edge

Edge returns the edge which was classified.

func (BoundaryEdge) Physical

func (b BoundaryEdge) Physical() bool

Physical reports whether the edge is backed by at least one element the model holds, which is ClassificationPhysical.

func (BoundaryEdge) Relation

func (b BoundaryEdge) Relation() Relation

Relation returns RelationBoundary, which is what says the result is part of what a region's outline is made of rather than something the region encloses or is grouped with.

type BoundarySegment

type BoundarySegment struct {
	// contains filtered or unexported fields
}

BoundarySegment is one straight run of a region's boundary: which ring of the boundary it belongs to, the two corners it runs between, and what produced it.

It is what an exporter attributes a ring back to the model with. Without it a polygon is anonymous coordinates and the correspondence has to be re-derived by matching them, which is exactly the re-derivation this engine exists to prevent: the pairing is known where the boundary is assembled, so it is reported from there rather than reconstructed downstream.

The corners are held as they were read rather than projected into the region's plane, for the reason [Region.figure] projects rather than caching a projection: one projection, done where it is used, cannot fall out of step with the figure it has to line up with.

The zero value is a run from nowhere to nowhere which no edge produced, and BoundarySegment.Origin reports it as SegmentOriginOperation.

func (BoundarySegment) Edge

func (s BoundarySegment) Edge() *Edge

Edge returns the edge the run was written as, or whose arc it stands in for.

It is nil for a run an operation produced, which BoundarySegment.Origin reports as SegmentOriginOperation.

func (BoundarySegment) From

func (s BoundarySegment) From() Point

From returns the corner the run leaves, and BoundarySegment.To the one it arrives at, in the order the loop traversed them.

func (BoundarySegment) Origin

func (s BoundarySegment) Origin() SegmentOrigin

Origin reports what produced the run.

It is computed from what the segment holds rather than stored beside it, for the reason BoundaryEdge.Classification is: one rule, and nowhere for a second copy of the answer to go stale ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

func (BoundarySegment) Reversed

func (s BoundarySegment) Reversed() bool

Reversed reports whether the run goes against the order the edge was written.

The direction is stated because a loop traverses an edge in either order and the answer differs: two rooms either side of a party wall name one edge, and the boundary of the second runs through it the other way round. A caller which read the edge's own vertices and assumed the run followed them would draw one of the two rooms inside out.

It is false for a run an operation produced, which no edge was written for.

func (BoundarySegment) Ring

func (s BoundarySegment) Ring() int

Ring returns which ring of the boundary the run belongs to, counted from zero in the order the rings come back.

It is what makes a flat list of runs a boundary: a plate with a courtyard in it is two rings, and a consumer which could not tell where one ended and the next began would close the outer ring through the hole.

func (BoundarySegment) String

func (s BoundarySegment) String() string

String renders the run as a person reads it: where it goes, what produced it and which way round it ran through the edge.

func (BoundarySegment) To

func (s BoundarySegment) To() Point

To returns the corner the run arrives at.

type Box

type Box struct {
	// Min and Max are the corners of the box, component by component.
	Min, Max Point

	// Unit is the linear unit of the frame the box was computed in.
	Unit Unit
}

Box is an axis-aligned bounding box, in the unit of the frame it was computed in.

It is axis-aligned to the frame's own axes and to nothing else. A tighter box at some other orientation is a different question with a different answer, and the one thing this box is good for — deciding quickly whether two things can possibly interact — needs the axes to be shared.

The zero Box is the box of nothing, which is what a measurement with no bounding box carries.

func (Box) Centre

func (b Box) Centre() Point

Centre returns the middle of the box, which is not the centroid: a box knows where a shape reaches and nothing about where its area is.

func (Box) Size

func (b Box) Size() Point

Size returns the extent of the box along each axis.

func (Box) String

func (b Box) String() string

String writes both corners with the unit they are in.

type Budget

type Budget struct {
	// contains filtered or unexported fields
}

Budget is the accumulated uncertainty of one computed answer, broken out by contributing term.

A derived quantity — the distance between two surveyed corners, the clearance between a wall face and a setback line — is only as trustworthy as the arithmetic which combined the uncertainties of its inputs, and two things make that arithmetic go wrong silently ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)):

  • Combining everything in quadrature is right only for terms which are independent. A term shared between the inputs does not partially cancel and does not average away, so it is counted once rather than once per input. Systematic terms of distinct term ids add linearly, because two sources may correlate — two control points of one network share its adjustment — by an amount the format cannot state, and full correlation is the bound.
  • A shared term counted once per input inflates the budget instead, and the usual response to that is to widen a tolerance rather than to fix the arithmetic.

So a budget accumulates claims rather than numbers. Two systematic terms are the same term when they name the same term id — not when their magnitudes happen to match — and the same term reached through two inputs is counted once. Adding one claim twice adds its terms once, for the same reason: one measurement is one error however many times a computation reads it.

The zero Budget holds nothing and every method below works on it. A budget is accumulated with Budget.Add and then read; the readers copy what they return, so nothing a caller does to the result reaches back into the budget.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/claim/valid"

	registry, _ := dfcad.LoadRegistry(root)
	claims, _ := dfcad.LoadClaims(root, registry)

	// Two facts, each resolved to the claim which is current. Both were shot
	// from the same control point, so both carry survey:CP-3.
	width, _ := claims.Resolve("site:S-101", "width", registry)
	position, _ := claims.Resolve("geom:V-02", "position", registry)

	var budget dfcad.Budget
	for _, resolution := range []dfcad.Resolution{width, position} {
		claim, _ := resolution.Claim()
		budget.Add(claim)
	}

	// The budget is itemised rather than a single number: which term dominates
	// is a more useful answer than the total, because it says what to
	// re-measure.
	for _, term := range budget.Terms() {
		fmt.Printf("%-11s %-14s %g %s, from %d claim(s)\n",
			term.Kind, term.Name, term.Magnitude, term.Unit, len(term.Contributors))
	}

	// The two independent terms combine in quadrature. The control point is one
	// systematic term shared by both facts, so it is counted once and added
	// linearly rather than being allowed to cancel against itself.
	combined, err := budget.Combined()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("combined %.6f %s at k = %g\n", combined.Magnitude, combined.Unit, combined.CoverageFactor)

	// Storage is always one standard deviation. Widening happens where the
	// figure is reported, and the factor travels with it.
	widened, _ := combined.Widen(2)
	fmt.Printf("reported %.6f %s at k = %g\n", widened.Magnitude, widened.Unit, widened.CoverageFactor)

}
Output:
independent the width of site:S-101 0.003 m, from 1 claim(s)
systematic  survey:CP-3    0.008 m, from 2 claim(s)
independent survey:C-0181  0.003 m, from 1 claim(s)
combined 0.009055 m at k = 1
reported 0.018111 m at k = 2

func (*Budget) Add

func (b *Budget) Add(claims ...*Claim)

Add accumulates the accuracy of each claim into the budget.

A nil claim is not an input and contributes nothing. A claim already accumulated contributes nothing further: it is one measurement, and reading it twice does not make its error two errors.

A claim which states no accuracy — or one whose accuracy the loader could only read in part, leaving a magnitude which is not a finite number or a term of no known kind — is accumulated as unknown, and taints the budget until it is fixed.

Example (Unknown)
package main

import (
	"errors"
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/claim/valid"

	registry, _ := dfcad.LoadRegistry(root)
	claims, _ := dfcad.LoadClaims(root, registry)

	// The occupancy of the room is rated rather than measured, so it says
	// nothing about how well it is known.
	occupancy, _ := claims.Resolve("site:S-101", "occupancy", registry)

	var budget dfcad.Budget
	for _, claim := range occupancy.Candidates() {
		budget.Add(claim)
	}

	// An unstated accuracy is unknown and not zero. It taints the budget, and
	// no combined figure comes out of it at all — because a figure computed
	// from the inputs which did state one would be narrower than the truth
	// while looking exactly like it.
	fmt.Println("known:", budget.Known())

	if _, err := budget.Combined(); err != nil {
		var unknown dfcad.UnknownAccuracyError
		if errors.As(err, &unknown) {
			for _, claim := range unknown.Claims {
				fmt.Printf("no accuracy: %s of %s, %s\n",
					claim.Predicate(), claim.Subject(), claim.Source())
			}
		}
	}

}
Output:
known: false
no accuracy: occupancy of site:S-101, Fire strategy FS-2026-001

func (Budget) Combined

func (b Budget) Combined() (Uncertainty, error)

Combined reduces the budget to one standard uncertainty.

The terms combine the way specification section 6.6.5 says they do: independent terms in quadrature, systematic terms linearly, and the two together in quadrature.

u = √( Σ uᵢ² + ( Σ |sⱼ| )² )

Every magnitude is already one standard deviation, so the result is too, and the Uncertainty which comes back says so. Nothing widened is produced here and nothing widened is ever stored; widening is Uncertainty.Widen, which attaches the factor it widened by.

Three things stop it, each a value a caller can inspect: a claim which stated no accuracy (UnknownAccuracyError), terms which are not all in one unit (MixedUnitsError), and a budget holding no term at all (ErrEmptyBudget). The unknown claim is reported first, because a budget which is both tainted and mixed is tainted whatever the units say.

func (Budget) Dominant

func (b Budget) Dominant() (BudgetTerm, bool)

Dominant returns the term contributing most to the combined figure, and whether the budget holds one to return.

The comparison is of each term's own contribution — a systematic term's magnitude against an independent one's, both at 1σ — which is what makes "the control point is most of your budget" answerable. Where two terms tie, the one contributed first wins, so the answer does not depend on the order the walk happened to reach equal claims in.

func (Budget) Known

func (b Budget) Known() bool

Known reports whether every claim the budget accumulated stated an accuracy.

A false answer is the taint: the budget still holds and reports the terms it did read, and Budget.Combined refuses to reduce them to a figure, because a figure computed from some of the inputs would be narrower than the truth while looking exactly like it.

func (*Budget) Merge

func (b *Budget) Merge(other Budget)

Merge accumulates every claim another budget was built from.

It is how a computation over computations keeps a shared term counted once: re-accumulating the claims rather than adding the two combined figures is what lets the same control point reached through two derived answers meet itself in one budget.

func (Budget) Terms

func (b Budget) Terms() []BudgetTerm

Terms returns the accumulated terms, in the order they were first contributed.

The terms are a copy, down to the claims attributed to each, so neither re-ordering them nor appending to one's contributors reaches back into the budget.

func (Budget) Unknown

func (b Budget) Unknown() []*Claim

Unknown returns the accumulated claims which stated no usable accuracy, in the order they arrived.

It is empty for a budget every input of which said how well it is known, which is what Budget.Known reports.

func (Budget) Unranked

func (b Budget) Unranked() []*Claim

Unranked returns the accumulated claims which stated no accuracy at all, in the order they arrived.

They are the claims specification section 6.5 calls unrankable, which an answer still reads where nothing rankable was said — a corner nobody gave an accuracy to is where the model says it is. Each is among Budget.Unknown, and taints the budget exactly as any unknown claim does; this names them apart from a claim whose accuracy was written and could not be read, because the fix for each is different: one wants an accuracy stated, the other one corrected.

type BudgetTerm

type BudgetTerm struct {
	// Kind is which of the two kinds of error this term is, and so how it
	// combines: independent terms in quadrature; systematic terms linearly, one
	// term per term id, because distinct sources may correlate by an amount the
	// format cannot state; and the two totals in quadrature. See
	// [Budget.Combined].
	Kind TermKind

	// Name is what to call the term in a report.
	//
	// For a systematic term it is the term id, which is the thing the error is
	// shared with. For an independent term there is no id in the format — the
	// error belongs to the one measurement — so it is the name of the claim it
	// came from.
	Name string

	// Magnitude is the one-sigma figure, in Unit, exactly as the claim wrote it.
	// Combining takes its absolute value; nothing here rewrites what was
	// written.
	//
	// Where one systematic term was contributed with two magnitudes, this is the
	// larger of them. A budget which cannot tell which fit of a shared error is
	// the right one reports the wider, because a check which fails on a wide
	// budget prompts an investigation and one which passes on a narrow one does
	// not.
	Magnitude float64

	// Unit is the unit the magnitude is expressed in, as it was written.
	Unit Unit

	// Source is the id the systematic error is shared with, and is empty for an
	// independent term.
	Source ID

	// Contributors are the claims which carried this term, in the order they
	// were accumulated.
	//
	// A systematic term shared by several inputs of one computation is one term
	// with several contributors, which is what "counted once" looks like from
	// the reporting side: the magnitude appears in the arithmetic once, and
	// every claim which put it there is still named. Each is named once, so one
	// claim which wrote the same term id twice does not read as two
	// measurements sharing it.
	Contributors []*Claim
}

BudgetTerm is one term of an accumulated budget: an AccuracyTerm together with what it is called and which claims put it there.

The attribution is the reason a budget is a list of terms rather than a number. "±0.06 m" is an answer nobody can act on; "the control point is 80% of it, and it came from this claim" says what to re-measure.

func (BudgetTerm) Shared

func (t BudgetTerm) Shared() bool

Shared reports whether more than one claim contributed this term.

func (BudgetTerm) String

func (t BudgetTerm) String() string

String writes the term for a person: which kind of error it is, how big it is, what it is shared with, and how many inputs put it there.

The count of contributors is written for a shared term and left out for a term one claim carried, because it is the whole of what "counted once" looks like from the reporting side: a figure which appears in the arithmetic once and in three of the inputs is the case a budget is easiest to get wrong about, and it should be readable without going to the machine payload for it.

type Buildable

type Buildable struct {
	// contains filtered or unexported fields
}

Buildable is the area left inside a boundary once every edge's setback has been taken off it.

It is derived and never authored ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)), which matters more here than anywhere else in this package: a buildable region written down as a polygon of its own is a second statement of where a permanent structure may go, and the day a setback claim changes it is the wrong one. Nothing writes this back, so the region cannot disagree with the parcel or with the claims it was computed from — it is recomputed from both every time it is asked for.

The setbacks which produced it come back with it. A region without them is a shape somebody has to reverse-engineer the rule out of; with them, the answer says which claim moved which edge and how far.

The zero Buildable covers nothing and was derived from nothing, and every method below works on it.

func (Buildable) Area

func (b Buildable) Area() float64

Area returns how much is buildable, in the square of the region's unit.

func (Buildable) Boundary

func (b Buildable) Boundary() Region

Boundary returns the region the setbacks were taken off, which is the parcel as the model holds it.

It is returned beside the answer because the two are read together: what is buildable is only meaningful against what the whole of the parcel is, and a caller which had to read the parcel a second time could read it against a different survey.

func (Buildable) Budget

func (b Buildable) Budget() Budget

Budget returns the accumulated accuracy of everything the answer was computed from: the position claims which put the boundary's corners where they are, and the setback claims which pushed each edge back.

Both families are in one budget rather than reported separately because the question the budget answers is about the answer and not about its inputs — how well is the edge of the buildable area known — and a control point shared between a corner and a setback survey is counted once there and twice in two budgets added together ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).

func (Buildable) Empty

func (b Buildable) Empty() bool

Empty reports whether nothing is buildable.

func (Buildable) Region

func (b Buildable) Region() Region

Region returns the buildable area.

It covers nothing where the setbacks meet in the middle, which is an answer rather than a failure and is what Buildable.Empty reports.

func (Buildable) Report

func (b Buildable) Report() string

Report is the buildable region rendered for a person: the summary, and one line per setback beneath it.

It is here rather than in the command so that a library caller reporting the answer and the command reporting it write the same thing.

func (Buildable) Setbacks

func (b Buildable) Setbacks() []Setback

Setbacks returns the setbacks which were applied, one per edge of the boundary and in the order the loops traverse it.

func (Buildable) String

func (b Buildable) String() string

String renders the buildable region as a person reads it.

func (Buildable) Subject

func (b Buildable) Subject() ID

Subject returns the id of the node the boundary was read from.

type ByteOrderMarkError

type ByteOrderMarkError struct {
	// Position is the first byte of the mark, which is the first byte of the
	// file.
	Position Position
}

ByteOrderMarkError reports a file beginning with a UTF-8 byte order mark.

A mark is a load error rather than something to skip. UTF-8 needs none, it is invisible in every editor that would have to remove it, and accepting one puts every byte offset in the file three bytes out for anything reading it outside the loader.

func (ByteOrderMarkError) Error

func (e ByteOrderMarkError) Error() string

Error implements the [error] interface.

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache is a store of derived geometry on disk, keyed by the digest of the source tree the geometry was derived from.

It is a build output and never a source. Deleting it changes what a run reports by nothing at all — only how long the run takes — and every entry in it can be recomputed from the entity files ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

It cannot serve a stale answer. An entry is written under the digest of the tree it was derived from and read back only under that same digest, so a tree which changed by one byte has a different key and misses. There is no invalidation pass, no timestamp comparison and no dependency list to get wrong.

An entry which is unreadable, truncated, corrupt, written by another version of the engine, or written under a different key is discarded and recomputed. A cache is not a source of truth, so the only thing to do with a byte of it which does not verify is to throw it away — failing the run over a damaged build output would make a disposable artefact load-bearing.

What it holds and how it is bounded

One entry per Key: one file, holding the derived geometry of the whole model, beneath a directory named for the digest. A run against a new revision of the tree writes a new directory rather than replacing anything, so a cache nobody prunes grows by one directory per distinct revision derived against.

Cache.Prune is how that is bounded: it keeps one digest and removes every other. A build which derives against the tree it just read calls it with that tree's digest, which leaves the cache holding exactly one revision. Removing the whole directory is always safe as well, and is what a caller who wants no cache at all does.

A nil *Cache is a working cache which holds nothing: every lookup misses and every store does nothing. That is what a derivation with no cache configured runs against, so nothing above has to branch on whether caching is on.

A Cache is safe for concurrent use.

func OpenCache

func OpenCache(dir string) (*Cache, error)

OpenCache opens the cache in dir, creating the directory where it does not exist.

dir is a build output directory: CacheDir is where it conventionally sits for a given model, and anywhere outside the source tree is equally valid. It must not be a directory holding entity files — nothing here writes a file a walk would read, but a cache sharing a directory with sources is one rm away from taking them with it.

func (*Cache) Dir

func (c *Cache) Dir() string

Dir returns the directory the cache writes beneath.

func (*Cache) Lookup

func (c *Cache) Lookup(key Key) (Footprints, bool)

Lookup returns what is stored under key, and whether anything usable was.

An entry which is there and does not verify is discarded — removed from the cache and reported as a miss — rather than returned or raised. Corruption in a build output is a recomputation, never a failed run.

func (*Cache) LookupSurface

func (c *Cache) LookupSurface(key SurfaceKey) (Surface, bool)

LookupSurface returns the surface stored under key, and whether anything usable was.

It is Cache.Lookup for a surface and behaves exactly as it does: an entry which is there and does not verify is discarded and reported as a miss, never returned and never raised.

func (*Cache) Prune

func (c *Cache) Prune(keep Digest) (int, error)

Prune removes every generation of the cache but the one keep names, and reports how many it removed.

This is how the cache is bounded. It holds one directory per source tree digest it has been derived against, so a long-lived checkout accumulates one per revision anybody derived against; a build which prunes with the digest it just used leaves exactly one, which is the working set.

Pruning the zero Digest keeps nothing, which empties the cache without removing the directory itself. That is the same outcome as deleting the directory, said in a way a caller which does not own the directory can say it.

func (*Cache) Stats

func (c *Cache) Stats() CacheStats

Stats returns what the cache has done so far.

func (*Cache) Store

func (c *Cache) Store(key Key, prints Footprints) error

Store writes prints under key, replacing whatever was there.

The write is atomic: the entry is written to a temporary file in the same directory and renamed over the entry, so a run killed mid-write leaves either the previous entry or none, and never half of one.

A key with no digest stores nothing and reports no error. Nothing pins an entry written under an unknown digest, so writing one would be the one way this cache could serve a stale answer.

func (*Cache) StoreSurface

func (c *Cache) StoreSurface(key SurfaceKey, surface Surface) error

StoreSurface writes a surface under key, replacing whatever was there.

A key with no digest, or one naming no region, stores nothing and reports no error: nothing pins such an entry, so writing one is the one way this cache could serve a stale answer.

type CacheError

type CacheError struct {
	// Op is what was being done — "open", "store", "prune".
	Op string

	// Path is the file or directory it was being done to.
	Path string

	// Err is what stopped it.
	Err error
}

CacheError is a cache operation which could not be carried out.

Every one of them is survivable. A cache is advisory, so a store which fails costs a recomputation on the next run and nothing else, and a caller which ignores this error gets the right answer more slowly.

func (CacheError) Error

func (e CacheError) Error() string

func (CacheError) Unwrap

func (e CacheError) Unwrap() error

Unwrap returns what stopped the operation.

type CacheStats

type CacheStats struct {
	// Hits are lookups answered from the cache.
	Hits int

	// Misses are lookups with nothing written under the key.
	Misses int

	// Discards are lookups which found an entry and refused it: unreadable,
	// corrupt, written by another version, or written under another key.
	Discards int

	// Stores are entries written.
	Stores int

	// Errors are entries which could not be written, and digests which could
	// not be computed.
	Errors int
}

CacheStats is what a cache did: enough to tell a run which paid for its derivation from one which did not, and to tell a miss from an entry which was there and unusable.

The last two are the ones worth watching. Discards are entries which were found, judged corrupt and thrown away, which is the cache working as intended exactly once and a broken build output directory if it keeps happening. Errors are writes which did not land, which cost time and nothing else.

type Change

type Change struct {
	// Path is the file, as the walk reached it or as the change named it.
	Path string `json:"path"`

	// Status is what happened to the file, or, on a dry run, what would have.
	Status FileStatus `json:"status"`

	// Effects are the things the change did to the model in this file, in the
	// order the mutations were applied.
	Effects []Effect `json:"effects,omitempty"`

	// Diff is the unified diff from what was on disk to what was written, and
	// is empty where the two are the same.
	Diff string `json:"diff,omitempty"`
}

Change is what a commit did to one file.

type Check

type Check interface {
	// Declare returns what the check is called, what it takes and what it
	// applies to.
	Declare() CheckDeclaration
}

Check is what a check implements to be registered, and it is the whole of the interface: a check declares itself, and the declaration is everything the registry, the loader and a listing need.

Adding a check is therefore a type implementing this method and a line in the registered set below — a change to the engine, reviewed and released like any other. There is deliberately no way to define one from data ([0011](docs/decisions/0011-assertions-are-named-parameterised-checks.md)): an assertion is a name and its parameters, and a format which let a file define what a name meant would be an expression language with extra steps.

type CheckDeclaration

type CheckDeclaration struct {
	// Name is the check name an assertion writes after its tag.
	Name string

	// Description is what the check constrains, in one line.
	Description string

	// Parameters are the parameters it takes, in the order a listing prints
	// them and an assertion is expected to write them.
	Parameters []CheckParameter

	// Forms are the forms it may be written on. A check applies to at least
	// one; there is no check which applies to nothing.
	Forms []SubjectForm

	// Kinds are the node kinds it applies to. Empty applies to every kind, and
	// is what a check with nothing to say about the axis declares.
	Kinds []Kind

	// Geometries are the geometry forms it applies to. Empty applies to any
	// geometry and to a subject with none; a check which measures declares the
	// forms it can measure, and a node with no geometry then satisfies none of
	// them.
	Geometries []Geometry
}

CheckDeclaration is everything a check says about itself: its name, what it constrains, the parameters it takes and what it applies to.

It is data rather than code because everything above the check reads it: validation of an assertion at load, a listing of the registry, and the choice of which checks bear on a node somebody is editing. A check whose parameters were known only to its implementation would answer none of those without being run, which is the property the format is built to keep ([0011](docs/decisions/0011-assertions-are-named-parameterised-checks.md)).

func Checks

func Checks() []CheckDeclaration

Checks returns the declaration of every check the engine registers, in name order.

The registry is closed and compiled in, so this is the whole set for every model: two repositories reading the same engine can write the same assertions. It is what a command listing the available checks prints, and it carries each check's parameters rather than only its name, because a name with no parameters is not something anybody can write an assertion from.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	// The check registry is closed and compiled into the engine, so this is the
	// whole set for every model: a command listing what an assertion may name
	// reads it here rather than out of a file.
	for _, check := range dfcad.Checks() {
		written := []string{check.Name}
		for _, parameter := range check.Parameters {
			written = append(written, fmt.Sprintf("(%s <%s>)", parameter.Name, parameter.Type))
		}
		fmt.Println(strings.Join(written, " "))
	}

}
Output:
boundary-loops-close (tolerance <tolerance>) (position <predicate>)
claim-agrees-with-geometry (predicate <predicate>) (position <predicate>) (tolerance <tolerance>) (discrepancy <tolerance>) (arc-centre <predicate>) (arc-through <predicate>) (chord <tolerance>)
contained-areas-do-not-overlap (tolerance <tolerance>) (position <predicate>) (kind <kind>) (arc-centre <predicate>) (arc-through <predicate>) (chord <tolerance>)
contained-areas-sum (tolerance <tolerance>) (area-tolerance <tolerance>) (position <predicate>) (predicate <predicate>) (kind <kind>) (type <type>) (member-of <id>) (arc-centre <predicate>) (arc-through <predicate>) (chord <tolerance>)
cross-frame-budget-holds (frame <frame>) (limit <tolerance>)
edge-backing-resolves
edge-endpoints-differ
ground-to-grid-stated (crs <predicate>) (ground-to-grid <predicate>) (position <predicate>)
required-claim (predicate <predicate>)
sits-inside (container <id>) (tolerance <tolerance>) (position <predicate>) (arc-centre <predicate>) (arc-through <predicate>) (chord <tolerance>)
stays-clear-of-zone (zone <id>) (tolerance <tolerance>) (position <predicate>) (arc-centre <predicate>) (arc-through <predicate>) (chord <tolerance>)
within-resolves
zone-members-resolve

func LookupCheck

func LookupCheck(name string) (CheckDeclaration, bool)

LookupCheck returns the declaration of one check by name, and whether the engine registers one under it.

func (CheckDeclaration) Parameter

func (d CheckDeclaration) Parameter(name string) (CheckParameter, bool)

Parameter returns the declaration of one parameter by name, and whether the check takes one under that name.

func (CheckDeclaration) PermitsForm

func (d CheckDeclaration) PermitsForm(form SubjectForm) bool

PermitsForm reports whether the check may be written on a subject of this form.

func (CheckDeclaration) PermitsGeometry

func (d CheckDeclaration) PermitsGeometry(geometry Geometry) bool

PermitsGeometry reports whether the check applies to a subject with this geometry form. A subject with no geometry is the zero Geometry, which satisfies a check declaring no geometry and nothing else.

func (CheckDeclaration) PermitsKind

func (d CheckDeclaration) PermitsKind(kind Kind) bool

PermitsKind reports whether the check applies to a node of this kind. A check which declares no kind applies to every one of them.

type CheckParameter

type CheckParameter struct {
	// Name is the tag the parameter is written with.
	Name string

	// Type is the sort of datum its value is.
	Type ParameterType

	// Required says the assertion must write it. An optional parameter left out
	// is not a diagnostic and the check decides what it means.
	Required bool

	// Repeated says it takes one or more values rather than exactly one, which
	// may be written either as a sequence after the tag or as one parenthesised
	// list.
	Repeated bool

	// Restates says the parameter carries a value of the same quantity the
	// subject's own claims carry — the value a check compares a claim under the
	// predicate it was given against.
	//
	// It is the whole of what the restatement rule reads
	// ([ResolveAssertions]), and it is declared rather than inferred because the
	// shape alone cannot tell the two apart: `(minimum 0.9)` beside
	// `(predicate clearance)` is a bound and constrains, while `(is 0.9)` beside
	// it is the claim written a second time. A check which compares against a
	// bound, a range or another node's claim declares nothing here.
	//
	// A check declaring one declares exactly one, declares a
	// [ParameterPredicate] parameter beside it for the quantity it belongs to,
	// and gives it one of the three literal types — a real, a string or a
	// boolean. A name resolved from a registry is not a value of the subject's
	// and cannot restate one.
	Restates bool

	// Description is what the parameter is for, in one line.
	Description string
}

CheckParameter is one named parameter of a check: what it is called, what sort of datum it takes, whether it may be left out and what it is for.

The description is not decoration. It is what a listing of the registry prints and what the diagnostic for the parameter left out says, so a check whose parameters are undescribed is one nobody can use without reading the engine.

type CheckRun

type CheckRun struct {
	// Rules is how many rules were run over, which is not how many ran.
	Rules int `json:"rules"`

	// Ran is how many of them ran: those whose check has an implementation and
	// can examine the thing it is bound to. Rules minus Ran is how many were
	// bound and decided nothing.
	Ran int `json:"ran"`

	// Passed is how many of the ones which ran were satisfied.
	Passed int `json:"passed"`

	// Failed is how many were not, which is how many rules the violations below
	// are about.
	Failed int `json:"failed"`

	// Violations is one entry per way a rule was not satisfied, in the order
	// the rules were run.
	Violations []Violation `json:"violations,omitempty"`

	// Bands is one entry per comparison a rule decided against a figure the
	// tolerance it was given is only the floor under, in the order the rules
	// were run. A rule which passed is in here as much as one which failed:
	// the number the registry states is not the number a widened check applies,
	// and a passing run is where that goes unsaid.
	Bands []AppliedBand `json:"bands,omitempty"`

	// Chorded is one entry per edge a rule read as the straight line between
	// its ends although the model states a curve on it, in the order the rules
	// were run. A rule which passed is in here as much as one which failed: a
	// pass over a chord reads exactly like a pass over the curve everywhere
	// else in a run.
	Chorded []ChordedEdge `json:"chorded,omitempty"`

	// Drawn is one entry per rule which read a curve through straight segments,
	// naming the chord tolerance it drew to and the deviation that achieved, in
	// the order the rules were run.
	Drawn []DrawnCurve `json:"drawn,omitempty"`
}

CheckRun is what running a set of rules found.

The counts are of rules rather than of violations, because a rule is what passes or fails: one loop which does not close and one which closes the wrong way are two ways of failing the same check, and a summary which counted them as two failures would say the model breaks two rules.

type CheckSubject

type CheckSubject struct {
	// contains filtered or unexported fields
}

CheckSubject is what a check is run against: the model, the node the invariant was bound to, and the parameters it supplies.

The graph comes along because a check answers a question about the model and not only about the node — whether the thing a node is written within resolves, whether a claim was ever made under a predicate — and a check which held its own copy of any of that would answer from a model which had moved on. A subject is an Entity rather than a SemanticNode because an assertion is written on any of the four forms and a check declares which of them it examines: `edge-endpoints-differ` is run against an edge, and a subject shaped for the semantic family alone would have nothing to hand it.

func (CheckSubject) Argument

func (s CheckSubject) Argument(name string) (Argument, bool)

Argument returns the parameter written under name, and whether one was.

A parameter the check declares as required is always here, because an invariant missing one is a load error and never reaches a run. An optional one left out is ordinary, which is why this reports whether it was written rather than assuming it was.

func (CheckSubject) Arguments

func (s CheckSubject) Arguments() []Argument

Arguments returns every parameter the invariant supplied, in the order they were written.

What comes back is the check's own copy, down to the values of each parameter: a check is handed what the invariant says and cannot write back through it to the binding, to the instance after it, or to the rendering of the violation it is about to report.

func (CheckSubject) Graph

func (s CheckSubject) Graph() *Graph

Graph returns the model the subject belongs to.

func (CheckSubject) Node

func (s CheckSubject) Node() *SemanticNode

Node returns the node under check, and is nil where the subject belongs to the geometric family.

A check which declares SubjectNode and nothing else is never run against anything else, so it may read this without asking; one which declares more than one form asks CheckSubject.Subject and switches on what came back.

func (CheckSubject) Subject

func (s CheckSubject) Subject() Entity

Subject returns the thing under check, whichever family holds it.

type ChordedEdge

type ChordedEdge struct {
	// Instance is the id of the thing the rule is bound to.
	Instance ID `json:"instance"`

	// Type is the type which declared the rule, and is empty for an assertion.
	Type string `json:"type,omitempty"`

	// Check is the check name the rule names.
	Check string `json:"check"`

	// Arguments are the parameters the rule is written with, each rendered as
	// it was written.
	Arguments []string `json:"arguments,omitempty"`

	// Parameters are the same parameters as data, one per entry of Arguments
	// and in the same order ([Rule.Parameters]).
	Parameters []Parameter `json:"parameters,omitempty"`

	// Declared is where the rule is written.
	Declared Span `json:"declared"`

	// Subject is where the thing the rule is bound to is written.
	Subject Span `json:"subject"`

	// Edge is the id of the edge read straight.
	Edge ID `json:"edge"`

	// Predicates are the predicates the edge states a position under, in name
	// order, which is what to name on the rule to have the curve read.
	Predicates []string `json:"predicates"`

	// Span is where that edge is written.
	Span Span `json:"span"`
	// contains filtered or unexported fields
}

ChordedEdge is one edge a rule read as the straight line between its ends although the model states a curve on it, with the rule which read it.

It is to UnreadArc what AppliedBand is to Band: the model says the edge bends, and the run says which rule decided without reading it — because the fix is on the rule, and a rule written once as an invariant and bound to a hundred instances is one whose disclosure has to lead back to where it is declared.

It is reported on a pass as much as on a failure, which is the point of it. A check which reads a curve straight answers a question about the chord, and a pass over the chord is indistinguishable from a real one by everything else a run says.

func (ChordedEdge) Diagnostic

func (c ChordedEdge) Diagnostic() Diagnostic

Diagnostic renders the finding as the warning a person reads.

It is a warning rather than an error for the reason Graph.UnreadArcs gives: reading a curve as its chord is a decision worth reporting, and one a rough rule can want. What is not on offer is not saying.

type Claim

type Claim struct {
	// contains filtered or unexported fields
}

Claim is one measurable fact about one thing, per specification section 6.5.

A dimension is never a bare column in this system. It is a value plus the evidence for it: where it came from, how it was obtained, how good it is and when. That is what makes "how wide is that room, and how do you know" one lookup rather than a join, and it is the invariant the rest of the engine rests on ([0008](docs/decisions/0008-a-bare-scalar-is-a-load-error.md)).

A claim's tag is its predicate. There is no `claim` keyword and no other way to attach a value to a node, so which predicate a claim is under is a fact about where it was written rather than a child of it.

The fields are unexported and read through the methods below. A Claim is read-only once loaded, and the zero value is a claim nothing could be read from; every method below works on it.

func (*Claim) Accuracy

func (c *Claim) Accuracy() (Accuracy, bool)

Accuracy returns how well the value is known, and whether the claim carries an accuracy at all.

The second result is a state and not a failure. A claim with no accuracy loads, and is unrankable: it can never win resolution, and it is not given a default, because a default would be this package inventing the one number the claim exists to record.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/claim/valid")
	claims, _ := dfcad.LoadClaims("testdata/claim/valid", registry)

	// A claim which does not say how well its value is known loads, and is
	// unrankable: it can never win resolution and it is not given a default,
	// because a default would be the engine inventing the one figure the claim
	// exists to record. It is still a candidate when nothing rankable exists.
	for claim := range claims.Under("site:S-101", "occupancy") {
		_, stated := claim.Accuracy()
		fmt.Println(claim.Predicate(), claim.Rank(), stated, claim.Rankable())
	}

}
Output:
occupancy normal false false

func (*Claim) Combined

func (c *Claim) Combined() (Uncertainty, error)

Combined reduces the claim's own accuracy to one standard uncertainty, by exactly the rule Budget.Combined applies: it is the combined figure of a budget holding this claim alone. Independent terms join in quadrature, systematic terms add linearly with each term id counted once, the two totals join in quadrature, and every magnitude counts by its absolute value (specification section 6.6.5).

It is the figure Claims.Resolve ranks by. Ranking a claim and budgeting an answer computed from it are one question asked twice, and asking it through one Budget is what keeps a claim unrankable in the one exactly where it could not be combined in the other — and what keeps the figure a caller reads here the one resolution compared.

A claim which states no accuracy is an UnknownAccuracyError naming it, and one whose terms are not all in one unit is a MixedUnitsError naming the units, each once in the order written: nothing converts between them ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

Example
package main

import (
	"errors"
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/claim/valid")
	claims, _ := dfcad.LoadClaims("testdata/claim/valid", registry)

	// A claim's accuracy is a list of terms, and the figure it reduces to is
	// the one resolution ranks it by: independent terms in quadrature,
	// systematic ones linearly, the two totals in quadrature. It is always one
	// standard uncertainty, and says so.
	for claim := range claims.Under("site:S-101", "width") {
		combined, err := claim.Combined()
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Println(claim.Source()+":", combined)
	}

	// A claim which states no accuracy has no figure at all, rather than a
	// figure of zero.
	for claim := range claims.Under("site:S-101", "occupancy") {
		_, err := claim.Combined()

		var unknown dfcad.UnknownAccuracyError
		fmt.Println(errors.As(err, &unknown))
	}

}
Output:
Plan set A-101, sheet 3: 0.05 m (k = 1.0, ≈ 68%)
As-built check AB-2026-009, Acme Surveys: 0.008544003745317531 m (k = 1.0, ≈ 68%)
true

func (*Claim) Date

func (c *Claim) Date() time.Time

Date returns the day the value was obtained.

func (*Claim) ID

func (c *Claim) ID() (ID, bool)

ID returns the claim's own id, and whether it wrote one.

A claim id is optional. It is required of a claim something else references — a frame's transform, a supersession — because a reference needs a name to resolve through, and it is noise on the great majority of claims which nothing points at.

func (*Claim) Method

func (c *Claim) Method() ID

Method returns the id naming how the value was obtained.

The engine attaches no meaning to it beyond the namespace being registered. An estimate is a method, and so is an assumption.

func (*Claim) Predicate

func (c *Claim) Predicate() string

Predicate returns the name of the predicate the claim was written under, which the consuming repository's registry declares.

func (*Claim) Rank

func (c *Claim) Rank() Rank

Rank returns the claim's rank, which is RankNormal unless the claim wrote otherwise.

func (*Claim) Rankable

func (c *Claim) Rankable() bool

Rankable reports whether the claim can take part in resolution at all: whether it carries an accuracy whose terms combine into one figure.

Two kinds of claim cannot. One with no accuracy has no figure to rank by, and one whose terms are not all in one unit has terms nothing converts between ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)), so they never become a figure either. The test is the one Claims.Resolve ranks by, which is the arithmetic of a Budget holding this claim alone.

func (*Claim) Source

func (c *Claim) Source() string

Source returns the string naming the evidence for the value.

func (*Claim) Span

func (c *Claim) Span() Span

Span returns where the claim form was written, which is what a diagnostic about the claim as a whole points at.

func (*Claim) Subject

func (c *Claim) Subject() ID

Subject returns the id of the thing the claim is about.

func (*Claim) SupersededBy

func (c *Claim) SupersededBy() (ID, bool)

SupersededBy returns the id of the claim which replaced this one, and whether one was written.

func (*Claim) Value

func (c *Claim) Value() Value

Value returns the claim's value and the unit it is expressed in.

type ClaimAxes

type ClaimAxes struct {
	// Value is what is claimed, in the shape the predicate declares. It is a
	// pointer because the empty string is a value rather than an absence: a text
	// claim of "" is a claim, and a member nobody wrote is not.
	Value *string `json:"value,omitempty"`

	// Unit is the unit it is expressed in, which must be the one the predicate
	// declares. A non-dimensional predicate takes none, and there is no unitless
	// token.
	Unit string `json:"unit,omitempty"`

	// Source is the evidence: a report, a drawing, a person, an instrument log.
	Source string `json:"source,omitempty"`

	// Method is an id naming how the value was obtained.
	Method string `json:"method,omitempty"`

	// Accuracy are the terms of how well it is known, each written as the file
	// writes one without its parentheses: `independent <magnitude> <unit>`, or
	// `systematic <magnitude> <unit> <term-id>`.
	Accuracy []string `json:"accuracy,omitempty"`

	// Date is the day the value was obtained, as YYYY-MM-DD. The day the change
	// is made where it is empty.
	Date string `json:"date,omitempty"`

	// ID is the claim's own id, and is empty for a claim which writes none.
	ID string `json:"id,omitempty"`
}

ClaimAxes is a claim as an operation file writes it: the value and the evidence for it, each spelled exactly as the flag of the same name spells it on a command line.

The spellings are the command line's rather than JSON's own — a value is the string `18.0` and not the number 18.0, an accuracy term is `independent 0.05 m2` — because which of the four shapes a value takes is registry data ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)), and reading `1.0 2.0 3.0` as a scalar or as a coordinate is a question only the declaration answers. One spelling means a claim written on a command line and a claim written in an operation file are read by the same code and refused in the same words.

func (ClaimAxes) Provenance

func (axes ClaimAxes) Provenance(predicate string) (ClaimSpec, error)

Provenance is the evidence every claim written with these axes carries: its source, its method, its accuracy and its date, without the value.

It is what a scaffold is written with, because a scaffold's values are its corners: one value for a list of forty corners would have to mean one of them, and there is no reading of that which is not a guess.

func (ClaimAxes) Spec

func (axes ClaimAxes) Spec(subject ID, predicate string, registry *Registry) (ClaimSpec, error)

Spec is the claim these axes describe, read against what the registry declares about the predicate.

The registry is needed before the value can be read at all: which of the four shapes a value takes is registry data, and reading `1.0 2.0 3.0` as a scalar or as a coordinate is a question only the declaration answers. A predicate nothing declares is therefore answered by ClaimSpec.Check rather than by guessing a shape and reporting the value against it.

type ClaimSpec

type ClaimSpec struct {
	// ID is the claim's own id, and is empty for a claim which writes none.
	//
	// It is optional: an id is required of a claim something references and is
	// noise on the great majority, which nothing points at. [Tx.Supersede] mints
	// one rather than leaving it empty, because the claim it retracts is about
	// to name this one.
	ID ID

	// Subject is the id of the thing the claim is about, which is the form the
	// claim is written inside.
	Subject ID

	// Predicate is the predicate it is written under, which is also its tag. The
	// registry must declare it, and must declare it claim-bearing.
	Predicate string

	// Value is the value and the unit it is expressed in. Its shape and its unit
	// must be the ones the predicate declares.
	Value Value

	// Source is the string naming the evidence — a report, a drawing, a person,
	// an instrument log. It is required.
	Source string

	// Method is the id naming how the value was obtained. It is required, and
	// its namespace must be one the registry declares.
	Method ID

	// Accuracy are the terms of how well the value is known, and are empty for a
	// claim which says nothing about it. Such a claim loads and is unrankable:
	// it can never win resolution and is not given a default.
	Accuracy []AccuracyTerm

	// Date is the day the value was obtained. The zero time is written as the
	// day the change is made.
	Date time.Time
}

ClaimSpec is a claim as it is being written: a value, and the evidence for it.

It is the written form of a Claim rather than the read one, which is why the fields are exported and carry no spans: nothing here has been written anywhere yet. The rank is not among them, because a claim is never authored retracted — a retraction is Tx.DeprecateClaim on a claim which was believed and then corrected, and the record of that correction is the thing the model exists to keep.

func (ClaimSpec) Check

func (spec ClaimSpec) Check(registry *Registry) error

Check reports the first thing about the claim the registry does not permit.

The checks are ordered rather than independent, for the reason NodeSpec.Check's are: they build on each other, and a value reported against the shape of a predicate nothing declares says nothing anybody can act on.

Tx.AddClaim calls it, so a caller which only adds claims never has to. It is exported for the caller which has something to do with the axes first — reading a value out of a command line, which needs the declared shape before it can read anything at all.

type Claims

type Claims struct {
	// contains filtered or unexported fields
}

Claims are the claims of one load: every claim the walk read, in the order it read them, indexed by the id of the thing each is about and by the claim's own id where it wrote one.

Both indexes are the load's own, for the reason Nodes holds one: a second index over one model would be a second answer to "what does this model say about site:S-101", and the two would differ the first time a claim moved between files.

A Claims is read-only once loaded. The zero value holds no claims, which is what a source tree holding none yields, and every method below works on it.

func (*Claims) All

func (c *Claims) All() iter.Seq[*Claim]

All iterates the claims in the order the walk reached them.

That order is deterministic — the lexical order of the paths, and within a file the order the forms were written — so anything built from it diffs against the last run's.

func (*Claims) Claim

func (c *Claims) Claim(id ID) (*Claim, bool)

Claim returns the claim id names, and whether the model holds one.

The zero ID names nothing, so a claim which wrote no id is reachable through Claims.All and Claims.Of and not through here. That is the whole of the arrangement: a claim nothing references needs no name, and a claim something references is found by the name it wrote.

func (*Claims) Conflicts

func (c *Claims) Conflicts() iter.Seq[Conflict]

Conflicts iterates the conflict register: every subject and predicate pair carrying more than one non-deprecated claim, in a deterministic order.

The register is computed by walking the claims, every time it is asked for. Nothing about it is written in a file, stored on a claim or cached here, so it cannot go quiet while the disagreement is still there ([0007](docs/decisions/0007-rank-is-closed.md)): deprecating one of two competing claims removes the entry because the claim is retracted, and nothing else does.

A pair conflicts when more than one live claim is written on it, whatever those claims say. Whether two values agree is a question about a tolerance, and tolerances are registry data the consuming repository owns ([0012](docs/decisions/0012-tolerances-are-registry-data.md)) rather than a constant hidden in this walk — so the register reports that the model states a thing twice, and what each statement is, and leaves agreement to whoever declared what agreement means.

A deprecated claim is never competing. It is retracted rather than out-ranked, so a pair whose second claim is deprecated has one live claim and no entry here, which is the one way of silencing a conflict the format has and it requires asserting in the file that the claim is wrong.

Entries come back ordered by subject and then by predicate, which is an order of what the claims are about rather than of where they were written or of when the walk reached them. Two runs over one model therefore print a register which diffs to nothing, and moving a claim between files does not reshuffle it.

A conflict is a finding rather than a failure and this traversal cannot fail. A predicate the registry declares strict escalates an ambiguity to an AmbiguousResolutionError for a caller asking Claims.Resolve for one number, because there it has to answer; the register is asked what the model says, and a strict predicate with two equally current claims is exactly what it exists to report.

Example

ExampleClaims_Conflicts walks the conflict register: every subject and predicate the model states more than once, computed rather than recorded.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/claim/valid")
	claims, _ := dfcad.LoadClaims("testdata/claim/valid", registry)

	// The room's width is claimed twice, so the pair is in the register. The
	// vertex's position is claimed twice as well and is not: one of those two is
	// deprecated, which retracts it rather than out-ranking it, and that is the
	// only thing which silences a conflict.
	for conflict := range claims.Conflicts() {
		fmt.Printf("%s %s\n", conflict.Subject(), conflict.Predicate())

		for _, claim := range conflict.Claims() {
			value, _ := claim.Value().Scalar()
			fmt.Printf("  %g %s — %s\n", value, claim.Value().Unit(), claim.Source())
		}

		// The register says whether the disagreement has an answer. Having one
		// does not close it: both claims are still asserted, and the pair stays
		// here until one of them is deprecated or corrected.
		winner, resolved := conflict.Resolution().Claim()
		if !resolved {
			fmt.Println("  ambiguous")
			continue
		}

		value, _ := winner.Value().Scalar()
		fmt.Printf("  resolves to %g %s\n", value, winner.Value().Unit())
	}

}
Output:
site:S-101 width
  8.5 m — Plan set A-101, sheet 3
  8.53 m — As-built check AB-2026-009, Acme Surveys
  resolves to 8.53 m

func (*Claims) Current

func (c *Claims) Current(claim *Claim) (*Claim, bool)

Current returns the claim at the end of the chain of replacements which begins at claim, and whether the chain reached one.

A claim nothing replaced is its own answer, so asking this of a live claim gives that claim back. Asking it of a deprecated one follows the replacements as far as they go, which is how a value read out of an old report is traced forward to what the model says now.

The second result is false where the chain does not end in a claim which is still asserted: a `superseded-by` naming a claim this model does not hold, a deprecation which named nothing, and a cycle each leave the walk with no current claim to return. Every one of them is a load diagnostic, so a caller which loaded clean never sees a false here.

func (*Claims) History

func (c *Claims) History(claim *Claim) iter.Seq[*Claim]

History iterates everything claim replaced, nearest first.

It is Claims.Replaced followed all the way back: the claims which named this one, then the claims those replaced, and so on to the ones nothing stands behind. Together with Claims.Current it is what makes a supersession walkable in both directions — a current value traced back through every claim it replaced, and an old one traced forward to what the model says now.

Each claim comes back once, in the order the claims which replaced it were written, depth first. A claim which was reached is not walked into twice, so a cyclic supersession — a load diagnostic, and still a model this can be asked of — terminates here rather than spinning.

Example

ExampleClaims_History traces a current value back through everything it replaced, which is what deprecating a claim rather than deleting one leaves behind.

package main

import (
	"fmt"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/claim/supersession")
	claims, _ := dfcad.LoadClaims("testdata/claim/supersession", registry)

	// Where the vertex is now: three claims were made about it and two of them
	// were retracted, so resolution has one to choose from.
	resolution, _ := claims.Resolve("geom:V-02", "position", registry)

	current, ok := resolution.Claim()
	if !ok {
		fmt.Println("nothing rankable is claimed")
		return
	}

	fmt.Printf("%s — %s\n", mustID(current), current.Source())

	// And why it says that: each claim it stands in place of, nearest first.
	// Every one of them is still in the file, saying what was believed and on
	// what evidence.
	for replaced := range claims.History(current) {
		fmt.Printf("  replaced %s — %s, %s\n", mustID(replaced), replaced.Source(), replaced.Date().Format(time.DateOnly))
	}

	// The chain is walkable in the other direction too, which is how a value
	// read out of a superseded report is followed forward to what the model
	// says now.
	oldest, _ := claims.Claim("survey:C-0100")
	reached, _ := claims.Current(oldest)
	fmt.Printf("%s is now %s\n", mustID(oldest), mustID(reached))

}

// mustID names a claim by the id it wrote, which every claim of a supersession
// writes: a claim something references is found by the name it wrote.
func mustID(claim *dfcad.Claim) dfcad.ID {
	id, _ := claim.ID()
	return id
}
Output:
survey:C-0181 — As-built check AB-2026-009, Acme Surveys
  replaced survey:C-0104 — Interior control set IC-01, Acme Surveys, 2026-02-18
  replaced survey:C-0100 — Plan set A-101, sheet 3, 2026-01-09
survey:C-0100 is now survey:C-0181

func (*Claims) Len

func (c *Claims) Len() int

Len reports how many claims were read.

func (*Claims) Live

func (c *Claims) Live(subject ID, predicate string) []*Claim

Live returns the claims written on subject under predicate which are still asserted, in written order.

A deprecated claim is retracted rather than out-ranked: resolution never considers one, and it is nothing's competitor. So the claims which disagree about a subject and a predicate, the claim a correction supersedes, and the claims which would be left if one were retracted are all this same set.

func (*Claims) Of

func (c *Claims) Of(subject ID) iter.Seq[*Claim]

Of iterates the claims written on one subject, in written order.

A subject with nothing said about it yields nothing, which is a thing with no claims rather than a thing which is missing.

func (*Claims) PlainOf

func (c *Claims) PlainOf(subject ID) iter.Seq[PlainValue]

PlainOf iterates the plain values written on one subject, in written order.

A plain value is read on every form a claim may be written on — a semantic node, a vertex, an edge, a loop and a frame alike — and under a predicate the registry declares non-claim-bearing only. A bare scalar under a claim-bearing predicate is a load error rather than a plain value ([0008](docs/decisions/0008-a-bare-scalar-is-a-load-error.md)), and is not here; neither is a value whose shape or unit the declaration refused, since the diagnostic saying so is the whole of what the model holds of it.

None of them is counted by Claims.Len, reached by Claims.All or Claims.Of, or considered by resolution. A subject with no plain value yields nothing.

Example

A plain value is not a claim, so Claims.Of never reaches one. Claims.PlainOf is how the plain values written on any thing are read back — a node, a vertex, an edge, a loop or, as here, a frame — in the order they were written.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/frame/valid")
	claims, _ := dfcad.LoadClaims("testdata/frame/valid", registry)

	for value := range claims.PlainOf("frame:survey-grid") {
		identifier, _ := value.Value.Text()
		fmt.Printf("%s: %s\n", value.Predicate, identifier)
	}

	// None of them is counted among the claims written on the frame.
	var measured int
	for range claims.Of("frame:survey-grid") {
		measured++
	}
	fmt.Println(measured, "claims")

}
Output:
crs: EPSG:25831
0 claims

func (*Claims) Replaced

func (c *Claims) Replaced(claim *Claim) iter.Seq[*Claim]

Replaced iterates the claims claim replaced, in source order.

It is the reverse of Claims.Replacement, and there may be more than one: two estimates corrected by one survey are two claims naming that survey as what replaced them, and both of them are what the survey stands in place of.

Only the claims which named this one directly come back, and only where naming it retracted them: a `superseded-by` written on a claim which is still asserted is a load error, and a live claim is nothing's predecessor. Claims.History walks the whole of what a claim replaced, through everything those claims replaced in their turn.

func (*Claims) Replacement

func (c *Claims) Replacement(claim *Claim) (*Claim, bool)

Replacement returns the claim which replaced claim, and whether the model holds one.

It is one step along the chain rather than the end of it: the claim which replaced this one may itself be deprecated, which is what makes a supersession a chain rather than a pair. Claims.Current walks it to the end.

A claim which was not deprecated has no replacement, whatever it wrote. A `superseded-by` on a claim which is still asserted is a load error — nothing stands in the place of a claim which has not been retracted — and reading it here would let a file put a live claim behind another one by writing a child the format forbids it.

Neither has a deprecated claim whose `superseded-by` names a claim this model does not hold. That too is a load diagnostic rather than a state a caller has to interpret, and is reported as one.

func (*Claims) Resolve

func (c *Claims) Resolve(subject ID, predicate string, registry *Registry) (Resolution, error)

Resolve decides which claim about one subject under one predicate is current, per decision record [0007](docs/decisions/0007-rank-is-closed.md).

The rule is stated once, here, and is the whole of it:

  • A deprecated claim is not considered. It is retracted rather than out-ranked, and resolution never sees it.
  • The smallest accuracy wins. A claim with no accuracy, or one whose terms are not in one unit, is unrankable and cannot win.
  • Where accuracies tie, the most recent date wins. Recency is the tiebreaker and never the criterion: a dimension scaled off a plan last month does not beat a survey shot taken last year.
  • Where neither separates the candidates, the answer is ambiguous, and every tied claim comes back.
  • Where nothing rankable was said, every live claim comes back as a candidate and nothing wins.

Nothing else takes part. There is no preferred rank, no numeric priority and no override, so two runs over the same claims give the same answer whichever file each was read from and in whatever order the walk reached them. Nothing in this path iterates a map, and the answer is a function of what the claims carry rather than of how they were loaded.

registry decides one thing: whether the predicate is declared strict, which escalates an ambiguous resolution from a report to an AmbiguousResolutionError. The resolution comes back beside the error whatever it says, because a caller reporting the failure wants the tied claims and not just the fact that there were some. A nil registry declares nothing strict.

Comparison of magnitudes is exact. Two accuracies which differ in the last bit are two different accuracies, and an epsilon which called them equal would be a tolerance — which is registry data the consuming repository owns ([0012](docs/decisions/0012-tolerances-are-registry-data.md)), not a constant hidden here.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/claim/valid")
	claims, _ := dfcad.LoadClaims("testdata/claim/valid", registry)

	// Two claims disagree about how wide the room is. Which of them is current
	// is one stated rule rather than whichever file happened to load first:
	// accuracy decides it, and recency only breaks a tie, so a dimension
	// scaled off a plan does not beat a survey shot by being newer.
	resolution, err := claims.Resolve("site:S-101", "width", registry)
	if err != nil {
		fmt.Println(err)
		return
	}

	claim, ok := resolution.Claim()
	if !ok {
		fmt.Println("nothing rankable is claimed")
		return
	}

	width, _ := claim.Value().Scalar()
	fmt.Printf("%g %s, %s\n", width, claim.Value().Unit(), claim.Source())

	// And which step of the rule picked it. An answer which cannot say why it
	// is the answer is a bare number again: "the most accurate of two claims"
	// says which claim to go and read, where the value alone invites a
	// re-measurement nobody needed.
	fmt.Println(resolution.Reason())

	// The answer names the claim it came from. This one wrote no id of its own
	// — a claim needs a name only where something references it — so what
	// traces it back is where it was written.
	if id, wrote := resolution.ClaimID(); wrote {
		fmt.Println(id)
	} else {
		fmt.Println(claim.Span().Start)
	}

}
Output:
8.53 m, As-built check AB-2026-009, Acme Surveys
accuracy
testdata/claim/valid/claims.dfc:18:3
Example (Ambiguous)

ExampleClaims_Resolve_ambiguous is the other half of the rule: where nothing separates two claims, the engine says so instead of picking one.

package main

import (
	"errors"
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/claim/strict")
	claims, _ := dfcad.LoadClaims("testdata/claim/strict", registry)

	// Equally good, equally recent, and they disagree. That is a state of the
	// measurements rather than a mistake in the file, so both come back.
	resolution, err := claims.Resolve("site:S-101", "width", registry)
	fmt.Println(err, resolution.Ambiguous(), resolution.Reason())
	for _, candidate := range resolution.Candidates() {
		id, _ := candidate.ID()
		value, _ := candidate.Value().Scalar()
		fmt.Printf("%s claims %g %s\n", id, value, candidate.Value().Unit())
	}

	// A predicate the registry declares strict escalates the same ambiguity to
	// a failure, because for some quantities no answer is safer than an
	// arbitrary one. The tied claims come back with the error rather than only
	// a count of them.
	_, err = claims.Resolve("site:S-101", "bearing", registry)

	var ambiguous dfcad.AmbiguousResolutionError
	if errors.As(err, &ambiguous) {
		fmt.Println(err)
		for _, candidate := range ambiguous.Candidates {
			fmt.Println(candidate.Span().Start)
		}
	}

}
Output:
<nil> true ambiguous
survey:C-0312 claims 8.5 m
survey:C-0313 claims 8.53 m
expected one current bearing of site:S-101, found 2 equally current: bearing is declared strict
testdata/claim/strict/claims.dfc:10:3
testdata/claim/strict/claims.dfc:17:3

func (*Claims) Under

func (c *Claims) Under(subject ID, predicate string) iter.Seq[*Claim]

Under iterates the claims written on one subject under one predicate, in written order.

More than one is the normal case rather than an error. Two width claims on one node are two measurements, and the disagreement between them is the most valuable thing in the file — which is why this returns all of them and resolution is a separate question asked of the result.

type Classification

type Classification string

Classification is what an edge of a region's boundary separates it by: an element which physically realises the edge, or nothing at all.

It is computed from the model every time it is asked and is stored nowhere. Nothing in the format says which an edge is — there is no flag for it on any form — so adding a wall makes the boundary physical with no second edit and the answer cannot drift away from what the model says ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

const (
	// ClassificationVirtual is an edge which names no backing element. The open
	// line between a foyer and a dining room is one, and it is as ordinary as a
	// wall.
	ClassificationVirtual Classification = "virtual"

	// ClassificationPhysical is an edge at least one of whose backing elements
	// resolved. [BoundaryEdge.Backing] names them.
	ClassificationPhysical Classification = "physical"

	// ClassificationUnresolved is an edge which names backing elements and
	// reached none of them. The edge is not virtual — it says something backs
	// it — and it is not physical either, because nothing in the model is what it
	// names. [ResolveBoundaries] reports each of its references as a load error.
	ClassificationUnresolved Classification = "unresolved"
)

The three answers the classification has.

Two of them are the question — an edge is backed by something real, or it is the open line between a foyer and a dining room. The third is what an edge which names a backing element the model does not hold gets: that is a load error, and reporting it as virtual would be the silent reclassification the error exists to prevent.

type ClassifyTypeOperation

type ClassifyTypeOperation struct {
	// Type is the declared type being classified.
	Type string `json:"type"`

	// System names the scheme. It is opaque: nothing here knows any scheme, and
	// no value is preferred over another.
	System string `json:"system"`

	// Code names the type within that scheme, and is opaque for the same
	// reason.
	Code string `json:"code"`
}

ClassifyTypeOperation says how a scheme outside this model names a type. It is `classify-type`.

func (*ClassifyTypeOperation) Name

func (o *ClassifyTypeOperation) Name() string

Name implements Operation.

type CollapsedRingError

type CollapsedRingError struct {
	// First and Second are the indices of the two corners, counted from one.
	First, Second int

	// Vertex is the vertex both of them are at.
	Vertex ID

	// Tolerance is the declaration they were judged coincident against.
	Tolerance Tolerance
}

CollapsedRingError reports a corner list two of whose corners are one point.

It is refused rather than quietly folded away. Two corners at one point are either a coordinate typed twice or an outline which doubles back on itself, and a scaffold which dropped one of them would write a room with a wall missing and report having written the room that was asked for.

func (CollapsedRingError) Error

func (e CollapsedRingError) Error() string

Error implements the [error] interface.

type Comment

type Comment struct {
	Text string
	Span Span
}

Comment is one comment together with the span of source text it was written in. Text is the comment exactly as it appeared, delimiters included.

type Commit

type Commit struct {
	// DryRun reports whether the change was validated and described without
	// being written.
	DryRun bool `json:"dryRun"`

	// Files is one entry per file a mutation touched, in the lexical order of
	// their paths — which is the order a walk of the model reaches them, so
	// that two runs over the same change report it the same way.
	Files []Change `json:"files"`
}

Commit is what one transaction did.

It is the shape a write command reports on stdout, so its fields carry the names the machine output contract documents rather than being translated on the way out.

func (Commit) Changed

func (c Commit) Changed() []string

Changed returns the files the change wrote or, on a dry run, would have written.

It is the count a report for a person wants: "would write nothing" is what a dry run of a change which does nothing should say, and reporting every dry run that way says the change was pointless rather than that it was not made. Commit.Written is the other question — which files this run actually put on disk — and the two differ only under Tx.DryRun.

func (Commit) Effects

func (c Commit) Effects() []Effect

Effects returns every effect of the change, file by file.

It is here because "what did this command do to the model" is the question an author asks, and answering it from Commit.Files means a nested loop over a grouping the author did not care about.

func (Commit) Written

func (c Commit) Written() []string

Written returns the files the change actually wrote.

A dry run wrote none, whatever it would have written, so it returns nothing. A caller which read this as "the files this run touched" would otherwise report a dry run as having changed the tree, which is the one thing a dry run promises it did not do. What it would have written is Commit.Files, with the status and the diff of each.

type Conflict

type Conflict struct {
	// contains filtered or unexported fields
}

Conflict is one subject and predicate about which the model holds more than one live claim, together with what resolution makes of them.

A conflict is not a state anybody records. It is the condition of a pair carrying more than one non-deprecated value, which is why the register is a traversal: computed, it is always current, where a stored flag is current until somebody forgets to clear it ([0007](docs/decisions/0007-rank-is-closed.md)).

The entry is a value rather than a reference into the model so that a caller holding one is holding what was true of the claims when it asked, and nothing it does to the entry reaches the claims.

func (Conflict) Ambiguous

func (c Conflict) Ambiguous() bool

Ambiguous reports whether the competing claims are equally current, so that resolution picks nothing.

Exactly one of Conflict.Resolved and Ambiguous holds of any entry. A pair with more than one live claim either has a best one or does not, and there is no third answer to report.

func (Conflict) Claims

func (c Conflict) Claims() []*Claim

Claims returns every live claim of the pair, in source order.

It is every competing claim and not only the ones which could still win, because the register exists to show the disagreement rather than the answer: a claim carrying no accuracy is out-ranked by one that does, and it is still a second statement somebody wrote about the same thing. Conflict.Resolution narrows them to the candidates.

Each claim carries the evidence for itself — its value, accuracy, date, source and method — so an entry can be reported without a second lookup. The slice is a copy of the entry's own, so re-ordering it re-orders nothing.

func (Conflict) Predicate

func (c Conflict) Predicate() string

Predicate returns the predicate they were written under.

func (Conflict) Resolution

func (c Conflict) Resolution() Resolution

Resolution returns what the resolution rule makes of the competing claims: which one wins, or which ones are equally current.

func (Conflict) Resolved

func (c Conflict) Resolved() bool

Resolved reports whether resolution picks a winner among the competing claims.

func (Conflict) Subject

func (c Conflict) Subject() ID

Subject returns the id of the thing the competing claims are about.

type ConflictingBackingError

type ConflictingBackingError struct {
	// ID is the edge the change was about.
	ID ID

	// BackedBy are the elements the change also named.
	BackedBy []ID
}

ConflictingBackingError is a change to an edge's backing which says both that it is virtual and what it is backed by.

The two are contradictory rather than additive: a virtual edge is one backed by nothing, so there is no reading of the pair which writes what was asked.

func (ConflictingBackingError) Error

func (e ConflictingBackingError) Error() string

Error implements the [error] interface.

type Containment

type Containment string

Containment is how one region sits against another.

It is the answer to a fitting question — is the desk in the room, does the setback reach the boundary, do these two zones overlap — and it is one of six states rather than a yes and a no, because "not inside" covers a region which is nowhere near, one which straddles the boundary and one which is inside and touching. Those need different work done about them.

const (
	// ContainmentDisjoint is two regions with nothing in common: no shared area
	// and no shared boundary.
	ContainmentDisjoint Containment = "disjoint"

	// ContainmentTouching is two regions which meet along a boundary or at a
	// corner and enclose no area between them.
	//
	// Two rooms either side of a party wall are this, and so are two plots
	// sharing a fence line. It is deliberately not "overlapping": nothing is in
	// both, and a clearance computed as though something were would report a
	// conflict where the model has none.
	ContainmentTouching Containment = "touching"

	// ContainmentOverlapping is two regions which share area, with each
	// reaching outside the other.
	ContainmentOverlapping Containment = "overlapping"

	// ContainmentInside is the other region entirely within this one.
	//
	// Touching the inside of this one's boundary does not stop it being inside:
	// a room whose wall is the building's wall is in the building. What takes it
	// out is reaching across the boundary, which is [ContainmentOverlapping].
	ContainmentInside Containment = "inside"

	// ContainmentSurrounds is this region entirely within the other one, which
	// is [ContainmentInside] read the other way round.
	ContainmentSurrounds Containment = "surrounds"

	// ContainmentCoincident is two regions covering the same area.
	ContainmentCoincident Containment = "coincident"
)

func (Containment) String

func (c Containment) String() string

String returns the containment as it is written.

type Corner

type Corner struct {
	// Position is the coordinate, in the unit of the frame. Its shape and its
	// dimension are the ones the position predicate declares, which is what
	// [ParseValue] reads a command line against.
	Position Value

	// Label is the display text of the vertex written there, and is empty for
	// one with none. A corner which reuses an existing vertex does not rename
	// it: a label is what a thing is already called, and the vertex was there
	// first ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).
	Label string
}

Corner is one corner of a loop being scaffolded: where it is, and what the vertex written there is called.

type CoverageFactorError

type CoverageFactorError struct {
	// Factor is the factor that was asked for.
	Factor float64
}

CoverageFactorError reports a coverage factor an uncertainty cannot be stated at.

A coverage factor multiplies a standard uncertainty, so it has to be a finite number greater than zero. Zero would report every answer as exact and a negative one would report a width as a deficit.

func (CoverageFactorError) Error

func (e CoverageFactorError) Error() string

Error implements the [error] interface.

type Curvature

type Curvature map[ID]Arc

Curvature is the arc each edge bends along, keyed by the edge's id.

An edge which is absent is straight, which is what almost every edge is. That is a state rather than a default: nothing in the model says an edge is straight, and nothing needs to.

type Dangling

type Dangling struct {
	// From is the entity which made the reference.
	From ID `json:"from"`

	// Relation is the child it was written as — `within`, `member-of`,
	// `boundary`, `superseded-by`, `vertices`, `edges` or `backed-by`.
	Relation string `json:"relation"`

	// Span is where the entity making the reference is written.
	Span Span `json:"span"`
}

Dangling is one reference left pointing at nothing.

type DeprecateClaimOperation

type DeprecateClaimOperation struct {
	// Claim is the id of the claim being retracted, which is the id it wrote.
	Claim string `json:"claim"`

	// SupersededBy is the claim which stands in its place. It is required: a
	// rank cannot be used to make a measurement quietly go away.
	SupersededBy string `json:"supersededBy"`
}

DeprecateClaimOperation records that a claim was retracted. It is `deprecate-claim`.

func (*DeprecateClaimOperation) Name

func (o *DeprecateClaimOperation) Name() string

Name implements Operation.

type Derivation

type Derivation struct {
	// Tolerance is the name of the registry tolerance coincidence and planarity
	// are judged against.
	Tolerance string

	// Position is the name of the predicate the corners are read from.
	Position string

	// Cache is where derived geometry is looked up and written back. A nil
	// Cache derives everything every time, which is slower and never different.
	Cache *Cache
}

Derivation is what a derived-geometry pass is computed against: the two named decisions it needs, and the cache it may read and write.

Both names are names and never numbers. Which predicate carries a position is vocabulary the consuming repository owns ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)), and how close two corners have to be to be one corner is a tolerance the project wrote down ([0012](docs/decisions/0012-tolerances-are-registry-data.md)). Both are part of the cache key, because a footprint judged against a different tolerance is a different answer to a different question.

type Destination

type Destination struct {
	// Path is the target file, relative to the model root and written with
	// forward slashes.
	Path string `json:"path"`

	// Rule is the name of the routing rule which chose it. Empty when the
	// destination was overridden.
	Rule string `json:"rule,omitempty"`

	// Overridden reports whether the destination was named outright rather than
	// routed.
	Overridden bool `json:"overridden"`
}

Destination is the file a new node is written to, and what chose it.

The rule is carried beside the path because "where did this go" and "why there" are one question to whoever reads the answer. A destination which came from a `--file` override names no rule and says so, which is what keeps an override from reading as a rule nobody can find in the registry.

func Override

func Override(file string) (Destination, error)

Override returns the destination of a `--file` override, checking that it names somewhere a node may actually be written.

A relative path is kept as written, cleaned, because it is resolved against the model root by whoever writes it. An absolute one is refused rather than silently accepted: the routing rules are relative, the model root is where every path in this format is measured from, and a caller which has an absolute path already knows the root to make it relative to.

Example

ExampleOverride takes a destination the caller named outright, which is what a write command's --file flag does with what it was given.

package main

import (
	"errors"
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	destination, err := dfcad.Override("entities/annexe.dfc")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(destination.Path, "overridden:", destination.Overridden, "rule:", destination.Rule == "")

	// A file no walk of the model reaches is refused: writing into one is a
	// change which appears to have been made and was not.
	_, err = dfcad.Override("notes.md")
	fmt.Println(err)
	fmt.Println(errors.Is(err, dfcad.ErrNotAnEntityFile))

}
Output:
entities/annexe.dfc overridden: true rule: true
notes.md: not an entity file
true

type Diagnostic

type Diagnostic struct {
	// Severity says how much this diagnostic matters.
	Severity Severity `json:"severity"`

	// Span is the source text the diagnostic is about. A diagnostic about a
	// point rather than a range — something missing, something at the end of
	// the file — carries the empty span there, which [Position.Span] builds.
	Span Span `json:"span"`

	// Message says what was expected and what was found, in that order.
	// "invalid entity" is not a message anybody can act on; "expected a unit
	// after the value, found `)`" is.
	Message string `json:"message"`

	// Hint is optional advice on what to do about it. It says something the
	// message does not — where the vocabulary is defined, what the usual cause
	// is — rather than restating the message in other words.
	Hint string `json:"hint,omitempty"`

	// Related are the other places that explain this one: the earlier
	// definition an id collides with, the frame a unit disagrees with. Each is
	// rendered beneath the diagnostic with its own quoted source.
	Related []RelatedLocation `json:"related,omitempty"`
}

Diagnostic is one problem found in user-authored input.

A diagnostic is not an [error]. An error is for the caller of a function; a diagnostic is for whoever wrote the file, human or otherwise, and it exists to be actionable without anybody interpreting it. That is why every diagnostic carries where it is rather than only what went wrong, and why a pass over a file collects them rather than returning the first one.

Both renderings come from these fields directly: Diagnostic.Render writes the human one, and encoding/json writes the machine one. Neither is produced by parsing the other.

func ResolveAssertions

func ResolveAssertions(graph *Graph) []Diagnostic

ResolveAssertions checks every assertion of a loaded model against the model it was written in, returning one diagnostic for every problem it finds.

It is the half of validating an assertion which needs the whole model. The other half is the check registry's and runs as each file is read: the name resolves, the parameters are ones the check takes, and each value is the sort of datum it declares (ValidateAssertion). Three questions are left, and none of them can be answered by a pass which has read one file or one family.

The check has to be able to examine the subject

A check declares what it applies to on three axes — the form, the node kind and the geometry form — and an assertion written on something it cannot examine is refused. `edge-endpoints-differ` on a space is not a rule which happens not to fire; it is a rule which passes on every model forever, and the only moment the mistake is visible is the one where the check and the thing are both in front of the reader.

Every id it names has to resolve

A parameter may name another thing — the setback this patio must stay inside, the element that door has to reach — and every id written in one is checked to name something the model holds, with a diagnostic naming both ends when one does not.

An assertion constrains; it does not record

**An assertion which restates a value the claims already carry is refused.** A claim is where a value is recorded, with the source, the method, the date and the accuracy it came from, and an assertion repeating that value is a second source of truth for one quantity — one which goes on saying what it says the day the claim is superseded, and which no resolution rule reaches because it is not a claim.

The rule reads the check's own declaration rather than guessing from the shape of what was written. A check declares which parameter names the predicate, and — where it has one — which parameter carries a value of that quantity (CheckParameter.Restates). An assertion writing both, on a subject which already claims that predicate, is the claim written twice and is refused.

What it catches, given a check declaring `(predicate …)` and a restating `(is …)`:

; Refused: site:S-101 already claims width, and this says it again.
(node site:S-101
  (width (value 3.6 m) (source "…") (method method:…) (date "2026-03-02"))
  (assert claimed-value-is (predicate width) (is 3.6)))

What it does not catch, and deliberately:

  • A bound, a range or a relation. `(assert clearance-at-least (predicate clearance) (minimum 0.9))` names a predicate the subject claims and constrains it; the check declares `minimum` as a bound rather than as a value of the subject's, so nothing is restated.
  • A check with no value at all. `(assert required-claim (predicate width))` says a claim must be there and does not say what it is.
  • The same pair on a subject which claims nothing under that predicate. There is no first statement for it to be the second of, and the assertion is a constraint on a value which is not there yet.
  • A value under a *different* predicate of the same subject. Two predicates are two quantities, and the rule is about one.

A model with no assertions yields nothing. Diagnostics come back in the order the pass found them, which is Graph.AllAssertions's; collecting them into a Diagnostics is what puts them in reporting order.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/z5labs/dfcad"
)

func main() {
	source := `(node site:S-101
  (kind Space)
  (type MeetingRoom)
  (geometry area)
  (frame frame:building)
  (assert edge-endpoints-differ))
`

	dir, _ := os.MkdirTemp("", "dfcad")
	defer func() { _ = os.RemoveAll(dir) }()

	registry, _ := os.ReadFile("testdata/assert/valid/registry.dfc")
	_ = os.WriteFile(filepath.Join(dir, "registry.dfc"), registry, 0o644)
	_ = os.WriteFile(filepath.Join(dir, "model.dfc"), []byte(source), 0o644)

	// A check declares what it can examine, and a check written on something it
	// cannot is refused when the model loads. It is not a rule which happens
	// not to fire: a check with nothing on its subject to look at passes on
	// every run forever.
	_, diags := dfcad.LoadGraph(dir)
	for _, diagnostic := range diags {
		fmt.Println(diagnostic.Message)
		fmt.Println("hint:", diagnostic.Hint)
	}

}
Output:
expected an assertion naming a check which applies to a node, found edge-endpoints-differ, which applies to edge
hint: an assertion is written on the thing the check examines, so edge-endpoints-differ is written on edge instead

func Validate

func Validate(file *File) []Diagnostic

Validate checks a loaded file against the forms of the entity format, returning one diagnostic for every problem it finds.

This is the schema layer over the generic tree: the part that knows `(node ...)` is a form and `(ndoe ...)` is not, that a form has required and optional children, and which of those children may legitimately repeat. Repeating a claim is the normal case — two width claims on one node are two measurements — so repeated and duplicate are different questions, and only the second is an error.

One pass reports everything it can find. Validation of a form continues into its children after a problem with the form itself, and a problem with one top-level form never hides the next, because fixing a file one diagnostic at a time is a guessing loop.

What it does not check is anything the registry decides. Whether a tag is a declared predicate, whether that predicate bears claims, which shape its value takes, whether an id resolves and whether a check name exists are all questions about registry data rather than about the shape of a form, and they are answered once the registry has been loaded. Structural validation therefore accepts both `(colour "slate")` and the claim form of the same predicate, and leaves the choice between them to the layer which knows.

It follows that a form which carries claims has no unknown child tags: a tag it does not reserve is a claim on it, however it is spelled, and only the predicate registry can say otherwise. A misspelled `kind` on a node is still reported — as the required child it leaves missing.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order, which is by position and is the same for every run over the same input.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	const path = "registry/registry.dfc"

	source := `(project
  (label "Riverside example")
  (globalid-namesapce "https://example.org/models/riverside"))
`

	file, err := dfcad.Parse(path, strings.NewReader(source))
	if err != nil {
		fmt.Println(err)
		return
	}

	// One pass reports both the misspelled tag and the required child the
	// misspelling leaves missing, rather than stopping at the first.
	var diagnostics dfcad.Diagnostics
	diagnostics.Add(dfcad.Validate(file)...)

	if err := diagnostics.Render(os.Stdout, dfcad.Sources{path: []byte(source)}); err != nil {
		fmt.Println(err)
	}

}
Output:
registry/registry.dfc:1:1: error: expected a (globalid-namespace ...) child of the project form, found none
1 | (project
  | ^^^^^^^^
2 |   (label "Riverside example")
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3 |   (globalid-namesapce "https://example.org/models/riverside"))
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
registry/registry.dfc:3:3: error: expected a child of the project form, found (globalid-namesapce ...), which is not a known form
3 |   (globalid-namesapce "https://example.org/models/riverside"))
  |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = hint: did you mean (globalid-namespace ...)?

func ValidateAppendOnly

func ValidateAppendOnly(base, head ObservationSource) []Diagnostic

ValidateAppendOnly checks the append-only invariant between two revisions of one observation file, per observation specification section 8.

The invariant is one sentence: every line the older revision had is present, unchanged, at the same line number in the newer one. Lines the newer revision adds beyond the end of the older one are not a finding — an append is the only legal change.

Comparison is byte for byte over whole lines, including their terminators and including comment and blank lines. Re-indenting a record, re-spelling a number which means the same and rewriting every timestamp into another offset are all the same finding, because none of them is distinguishable from a quiet correction of the data, and the format exists so that they are refused rather than judged.

It knows nothing about git. Where the two byte sequences came from — two commits, a working tree against its merge base, a backup against what is on disk — is the caller's question.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/z5labs/dfcad"
)

func main() {
	read := func(name string) dfcad.ObservationSource {
		src, _ := os.ReadFile(filepath.Join("testdata", "observations", "append", name))
		return dfcad.ObservationSource{Path: name, Bytes: src}
	}

	base := read("base.obs")

	// Bytes at the end are the only legal change, so an append has nothing to
	// report however many records it adds.
	fmt.Println(len(dfcad.ValidateAppendOnly(base, read("appended.obs"))), "on an append")

	// A float solution quietly re-spelled as a fixed one is a correction of the
	// data with nothing in the file to say so, which is exactly what this
	// refuses.
	for _, diagnostic := range dfcad.ValidateAppendOnly(base, read("edited.obs")) {
		fmt.Println(diagnostic.Span.Start, diagnostic.Message)
		fmt.Println(diagnostic.Related[0].Span.Start, diagnostic.Related[0].Message)
	}

}
Output:
0 on an append
edited.obs:6:1 expected line 6 to be what the earlier revision wrote, found it modified
base.obs:6:1 the earlier revision of line 6

func ValidateAssertion

func ValidateAssertion(form *Node, registry *Registry) []Diagnostic

ValidateAssertion checks one written `assert` or `invariant` form against the check registry, returning one diagnostic for every problem it finds.

This is the load-time half of the decision that an assertion is a name and its parameters: the check name is resolved, every parameter is matched to one the check declares, and every value is read as the sort of datum the check says it takes. What comes out is either diagnostics or the knowledge that the assertion is one the engine could run, and it costs nothing but reading the form — which is the whole point of there being no expression language ([0011](docs/decisions/0011-assertions-are-named-parameterised-checks.md)).

registry is the model's own vocabulary, which the parameters naming a type, a predicate, a frame or a tolerance are resolved against. A nil registry declares nothing, and every such parameter is then reported as undeclared, which is what a model with no registry files genuinely is.

An `invariant` is the same shape as an `assert` and is validated by the same call. Whether the check applies to the subject it was written on is a question about that subject rather than about the assertion, and is not asked here.

One pass reports everything it finds. A parameter which is not one the check takes does not stop the ones after it from being read, and a check name which resolves to nothing stops only the parameters, because parameters cannot be judged against a check nobody named.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	const path = "entities/level-1.dfc"

	source := `(node site:S-101
  (kind Space)
  (type MeetingRoom)
  (assert boundary-loops-close (tolerance 0.005)))
`

	file, err := dfcad.Parse(path, strings.NewReader(source))
	if err != nil {
		fmt.Println(err)
		return
	}

	registry, _ := dfcad.LoadRegistry("testdata/registry/valid")

	// An assertion is validated against the check registry before anything runs
	// it: the check name is one the engine registers, and every parameter is
	// the sort of datum that check declares it takes.
	written := file.Nodes[0].Children[4]

	var diagnostics dfcad.Diagnostics
	diagnostics.Add(dfcad.ValidateAssertion(written, registry)...)

	if err := diagnostics.Render(os.Stdout, dfcad.Sources{path: []byte(source)}); err != nil {
		fmt.Println(err)
	}

}
Output:
entities/level-1.dfc:4:43: error: expected a declared tolerance name after the tolerance tag, found the number 0.005
4 |   (assert boundary-loops-close (tolerance 0.005)))
  |                                           ^^^^^
  = hint: a tolerance is registry data rather than a number written where it is used: declare it with (tolerance <name> (value <magnitude> <unit>)) and name it here, so that how close is close enough is one decision in one place

func ValidateObservations

func ValidateObservations(log *ObservationLog, registry *Registry) []Diagnostic

ValidateObservations checks a log against itself and against the registry, per observation specification section 7.2.

These are the questions no single line answers: whether two records share an identity, whether a retirement names a record which is there and which is earlier, and whether the frame and the namespaces a record names are ones a registry file declares. Each is asked of the whole log because a record in the first file a walk reaches may be retired by one in the last, and a pass which asked as it read would report it missing for no reason but the order the directory happened to be listed in.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order.

func (Diagnostic) Render

func (d Diagnostic) Render(w io.Writer, src SourceMap) error

Render writes the human rendering of the diagnostic to w: the header line, the source lines the span covers with the offending text underlined, the hint, and each related location rendered the same way.

src supplies the bytes of the files being pointed at. Where it has none for a path — because it is nil, or because the file has since changed — the header lines are still written and the quoting is left out, so a diagnostic is never lost for want of the source it came from.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	const path = "entities/level-1.dfc"

	source := `(node site:S-101
  (label "Meeting Room B")
  (position (value (0.0 4.05 0.0))))
`

	file, err := dfcad.Parse(path, strings.NewReader(source))
	if err != nil {
		fmt.Println(err)
		return
	}

	// The value written without the unit which has to follow it.
	value := file.Nodes[0].Children[3].Children[1]

	diagnostic := dfcad.Diagnostic{
		Severity: dfcad.SeverityError,
		Span:     value.Span,
		Message:  "expected a unit after the value, found none",
		Hint:     "units are registry data; a frame declares the one its coordinates are in",
	}

	if err := diagnostic.Render(os.Stdout, dfcad.Sources{path: []byte(source)}); err != nil {
		fmt.Println(err)
	}

}
Output:
entities/level-1.dfc:3:13: error: expected a unit after the value, found none
3 |   (position (value (0.0 4.05 0.0))))
  |             ^^^^^^^^^^^^^^^^^^^^^^
  = hint: units are registry data; a frame declares the one its coordinates are in

func (Diagnostic) String

func (d Diagnostic) String() string

String renders the diagnostic as the single line an editor and a terminal already know how to jump to: path:line:column, the severity and the message.

It quotes no source and shows no hint. Diagnostic.Render is the full human rendering.

type Diagnostics

type Diagnostics struct {
	// Limit is how many diagnostics to retain. Zero means
	// [DefaultDiagnosticLimit] and a negative Limit retains everything. Set it
	// before adding anything: lowering it later suppresses nothing already
	// retained.
	Limit int
	// contains filtered or unexported fields
}

Diagnostics collects the problems found in one pass over user-authored input.

One pass reports every independent problem it finds. Stopping at the first turns fixing a file into a guessing loop: fix, rerun, discover the next one, repeat, with no way to see how much is left.

The zero value is ready to use and caps at DefaultDiagnosticLimit. It must be collected into through a pointer; the reading methods take a value and mutate nothing.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	const path = "entities/level-1.dfc"

	source := `(node site:S-101
  (label "Meeting Room B"))
(node site:S-101
  (label "Meeting Room C"))
`

	file, err := dfcad.Parse(path, strings.NewReader(source))
	if err != nil {
		fmt.Println(err)
		return
	}

	// One pass reports every problem it finds, in a deterministic order, even
	// though these two are collected in the order they happen to be noticed.
	var diagnostics dfcad.Diagnostics

	diagnostics.Add(dfcad.Diagnostic{
		Severity: dfcad.SeverityError,
		Span:     file.Nodes[1].Children[1].Span,
		Message:  "expected an unused id, found site:S-101, which is already defined",
		Related: []dfcad.RelatedLocation{
			{Span: file.Nodes[0].Children[1].Span, Message: "first defined here"},
		},
	})
	diagnostics.Add(dfcad.Diagnostic{
		Severity: dfcad.SeverityWarning,
		Span:     file.Nodes[0].Children[2].Span,
		Message:  "expected a (type ...) child before the claims, found none",
	})

	if err := diagnostics.Render(os.Stdout, dfcad.Sources{path: []byte(source)}); err != nil {
		fmt.Println(err)
	}

	fmt.Println(diagnostics.HasErrors())

}
Output:
entities/level-1.dfc:2:3: warning: expected a (type ...) child before the claims, found none
2 |   (label "Meeting Room B"))
  |   ^^^^^^^^^^^^^^^^^^^^^^^^
entities/level-1.dfc:3:7: error: expected an unused id, found site:S-101, which is already defined
3 | (node site:S-101
  |       ^^^^^^^^^^
entities/level-1.dfc:1:7: note: first defined here
1 | (node site:S-101
  |       ^^^^^^^^^^
true

func (*Diagnostics) Add

func (d *Diagnostics) Add(diags ...Diagnostic)

Add records diagnostics, retaining them up to the limit and counting the rest as suppressed.

func (Diagnostics) All

func (d Diagnostics) All() []Diagnostic

All returns the retained diagnostics in reporting order: by file, then by position within it, then by severity and message so that two diagnostics at one position still order the same way on every run.

Ordering is deterministic because the output of two runs over the same input is meant to be diffable; an order that depended on which check happened to run first would make every diff noise.

func (Diagnostics) HasErrors

func (d Diagnostics) HasErrors() bool

HasErrors reports whether any retained diagnostic is an error. It is what decides whether input is refused, and it is separate from Len because a set holding only warnings is not a failure.

func (Diagnostics) Len

func (d Diagnostics) Len() int

Len is how many diagnostics were retained, which is not how many were added once the limit has suppressed any.

func (Diagnostics) Render

func (d Diagnostics) Render(w io.Writer, src SourceMap) error

Render writes every retained diagnostic to w in reporting order, followed by a line saying how many were suppressed when any were.

The count is printed because a truncated list that does not say it was truncated reads as a complete one, and fixing everything it names then leaves the file still failing for reasons nothing ever mentioned.

func (Diagnostics) Suppressed

func (d Diagnostics) Suppressed() int

Suppressed is how many diagnostics were dropped by the limit.

type Digest

type Digest struct {
	// contains filtered or unexported fields
}

Digest is a content digest over a source tree: the one value a derived artefact is keyed by.

It is what makes the cache impossible to serve a stale answer from. A cached value is read only under the digest of the tree it was derived from, so a tree which changed anywhere has a different key and misses — there is no invalidation step to get wrong, because the key is the invalidation ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

How it is computed

SHA-256 over, in this order:

  1. [digestVersion], length-prefixed.
  2. For every entity file beneath the root, in the lexical path order Walk yields them in: the file's path relative to the root, slash-separated, length-prefixed; then the file's bytes, length-prefixed.

Every field is prefixed with its length as eight bytes, big-endian, so no two different trees can serialise to the same byte sequence — without it a file named `a` holding `bc` and one named `ab` holding `c` would digest alike.

Only files a walk reads are covered, which is the set the model is made of. Anything else in the directory — a build output, a README, an editor's swap file — is not an input to any derivation and changing it must not cost a recomputation.

The digest is deterministic: the same tree digests to the same value on any machine, in any order the files happen to be created, whatever their timestamps or permissions. Nothing about the filesystem enters it, only the paths and the bytes.

The zero Digest is the digest of nothing and reports Digest.Known false. It is what a model which is not on disk has, and nothing is cached under it.

func DigestOf

func DigestOf(root string) (Digest, error)

DigestOf computes the digest of the source tree beneath root, exactly as Digest documents it.

root is what Load takes: a single file, or a directory beneath which every file whose extension is Extension is read. A directory holding no entity file digests to the digest of an empty tree, which is a real digest and not the zero one — a model nobody has written yet is a model, and a derivation over it is legitimately cacheable.

Files are read one at a time and hashed as they are read, so digesting a tree costs the largest single file rather than the sum of them.

Example

ExampleDigestOf shows what makes a stale cache hit unrepresentable: the key is a digest over the bytes of the source tree, so an edit anywhere in it — one coordinate, one new file — is a different key.

It also shows what is deliberately not in it. A build output written beside the model is not an input to anything derived from the model, and a recomputation every time somebody's editor wrote a swap file would be a cache which never paid for itself.

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad-model-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	entities := filepath.Join(root, "model.dfc")
	if err := os.WriteFile(entities, []byte("(node site:S-101 (label \"Meeting Room B\") (kind Space))\n"), 0o644); err != nil {
		fmt.Println(err)
		return
	}

	before, _ := dfcad.DigestOf(root)

	// Anything a walk does not read is not an input to a derivation.
	notes := filepath.Join(root, "README.md")
	if err := os.WriteFile(notes, []byte("nothing derives from this\n"), 0o644); err != nil {
		fmt.Println(err)
		return
	}

	unchanged, _ := dfcad.DigestOf(root)

	// One byte of an entity file is a different tree.
	if err := os.WriteFile(entities, []byte("(node site:S-101 (label \"Meeting Room C\") (kind Space))\n"), 0o644); err != nil {
		fmt.Println(err)
		return
	}

	after, _ := dfcad.DigestOf(root)

	fmt.Println(before == unchanged, before == after)

}
Output:
true false

func (Digest) Known

func (d Digest) Known() bool

Known reports whether this is a digest of something.

The zero Digest is not, and is the answer for a tree which could not be read and for a graph which was never on disk. A caller holding one knows only that nothing may be keyed by it.

func (Digest) MarshalText

func (d Digest) MarshalText() ([]byte, error)

MarshalText writes the digest as lower-case hex, and the zero one as nothing.

func (Digest) String

func (d Digest) String() string

String returns the digest as lower-case hex, or "unknown" for the zero one.

func (*Digest) UnmarshalText

func (d *Digest) UnmarshalText(text []byte) error

UnmarshalText reads a digest written as lower-case hex, and the zero one from an empty text.

type DigestError

type DigestError struct {
	// Path is the file which could not be read, empty where the failure was not
	// about one file.
	Path string

	// Err is what stopped it.
	Err error
}

DigestError is a source tree which could not be digested, and the file which stopped it.

A derivation which gets one carries on without a cache rather than failing: the digest is what a cache is keyed by, and a run which cannot key one is a run which computes everything, which is slower and never wrong.

func (DigestError) Error

func (e DigestError) Error() string

func (DigestError) Unwrap

func (e DigestError) Unwrap() error

Unwrap returns what stopped the digest.

type DigestLengthError

type DigestLengthError struct {
	// Want is how many bytes a digest is.
	Want int

	// Got is how many the text decoded to.
	Got int
}

DigestLengthError is text which reads as hex but is not as long as a digest, and how long each is.

It is its own type rather than a message so that a caller reading a digest out of somewhere it did not write — a manifest, a report, a command line argument — can tell "this is not a digest at all" from "this is a digest of some other width", which is the difference between a typo and a format which moved.

func (DigestLengthError) Error

func (e DigestLengthError) Error() string

type DimensionError

type DimensionError struct {
	// Predicate is the predicate the coordinate was written under.
	Predicate string

	// Want is how many components the registry declares.
	Want int

	// Got is how many were written.
	Got int
}

DimensionError is a coordinate with a number of components other than the one its predicate declares.

func (DimensionError) Error

func (e DimensionError) Error() string

Error implements the [error] interface.

type DrawnCurve

type DrawnCurve struct {
	// Instance is the id of the thing the rule ran against.
	Instance ID `json:"instance"`

	// Type is the type which declared the rule, and is empty for an assertion.
	Type string `json:"type,omitempty"`

	// Check is the check name the rule names.
	Check string `json:"check"`

	// Arguments are the parameters it ran with, each rendered as it was
	// written.
	Arguments []string `json:"arguments,omitempty"`

	// Parameters are the same parameters as data, one per entry of Arguments
	// and in the same order ([Rule.Parameters]).
	Parameters []Parameter `json:"parameters,omitempty"`

	// Declared is where the rule is written.
	Declared Span `json:"declared"`

	// Subject is where the thing it ran against is written.
	Subject Span `json:"subject"`

	// Chord is the name of the tolerance the curves were drawn to, and Value
	// its declared value.
	Chord string  `json:"chord"`
	Value float64 `json:"value"`

	// Deviation is how far the worst segment of the drawing fell from the curve
	// it stands in for: what was achieved, which is never more than Value.
	Deviation float64 `json:"deviation"`

	// Unit is what Value and Deviation are in, the linear unit of the frame.
	Unit Unit `json:"unit"`
}

DrawnCurve is the chord tolerance one rule drew its curves to, and the deviation that drawing achieved, with the rule which drew them.

A check deciding by an overlay reads a curve through straight segments, and where it did the answer is about the drawing and not about the arc: within the deviation, and no closer. That is a decision the rule took and stated rather than an error, and it is reported for the reason a band is — the figure the rule names is not the whole of what decided the answer, and a pass is where that goes unsaid.

type Edge

type Edge struct {
	// contains filtered or unexported fields
}

Edge is a connection between two vertices, per specification section 6.3.

Non-straight edges

An edge says which two vertices it runs between and says nothing about the shape of the curve between them, and that is not an omission. Curvature arrives as a claim under a predicate the consuming repository registers — an arc centre, a bulge, a radius — carrying its own source, method, date and accuracy like every other measurement.

**The predicate registry is the extension point.** An arc is registry data rather than a change to this type, to the form tables, to the specification or to anything else compiled in: the consuming repository declares `(predicate arc-centre (unit m) (shape coordinate) (dimension 3) ...)`, an edge is written with a claim under it, and this pass reads that edge exactly as it reads a straight one. Nothing here has to be told which predicates mean curvature, which is what keeps the vocabulary out of the engine ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

An Edge is read-only once loaded. The zero value is an edge with no id, no frame and no endpoints; every method below works on it.

func (*Edge) Assertions

func (e *Edge) Assertions() []Assertion

Assertions returns the assertions written on the edge, in the order they were written. SemanticNode.Assertions says what they are and what they are not.

func (*Edge) BackedBy

func (e *Edge) BackedBy() []ID

BackedBy returns the ids this edge wrote where the id of an element which physically realises it belongs, in the order they were written.

An edge which at least one of these ids resolves for is a physical boundary; an edge which wrote none of them is a virtual one — the open line between a foyer and a dining room.

**That classification is computed and never stored.** Nothing in the format says which an edge is, and adding an element flips the answer with no other edit ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). Boundaries.Classified is what computes it, because resolving these ids means having read both families.

**These are the ids as they were written, and not the elements they reached.** An id naming a vertex, one naming a node which is not an Element, and one naming nothing this model holds are each a diagnostic from ResolveBoundaries and are each still here, because a caller reporting on an edge wants to say what it says as well as what is wrong with it. A repeated id — which is a load error — is held once.

func (*Edge) Frame

func (e *Edge) Frame() ID

Frame returns the id of the frame the edge is expressed in.

func (*Edge) ID

func (e *Edge) ID() ID

ID returns the edge's id.

func (*Edge) Label

func (e *Edge) Label() string

Label returns the edge's display text, which is empty when none was written.

func (*Edge) ObservedIn

func (e *Edge) ObservedIn() []ObservationLink

ObservedIn returns the observation files the edge links to, in the order they were written. SemanticNode.ObservedIn says what a link is and what reading one costs.

func (*Edge) Span

func (e *Edge) Span() Span

Span returns where the edge form was written.

func (*Edge) Vertices

func (e *Edge) Vertices() (start, end ID)

Vertices returns the ids of the two vertices the edge runs between, in the order they were written: start then end.

The order is significant and is never sorted. An edge is directed, a loop is traversed through its edges in the order it names them, and an implementation which sorted the pair would answer "which way does this run" differently on each read.

These are the ids as the edge wrote them. Both name vertices this model holds wherever it loaded clean: an id naming no vertex, and one naming a member of the family which is not a vertex, are each a load error rather than a state a caller has to interpret.

type EdgeSpec

type EdgeSpec struct {
	// ID is the id it will be written with.
	ID ID

	// Label is its display text, and is empty for an edge with none.
	Label string

	// Frame is the frame it is expressed in.
	Frame ID

	// Start and End are the vertices it runs between, in that order. The order
	// is significant and is never sorted: an edge is directed, and the two
	// regions either side of it traverse it opposite ways.
	Start, End ID

	// BackedBy are the ids of the semantic nodes which physically realise it,
	// in the order they were given. An edge which names none is virtual, which
	// is computed from the references rather than written
	// ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).
	BackedBy []ID
}

EdgeSpec is an edge which does not exist yet.

func (EdgeSpec) Check

func (spec EdgeSpec) Check(registry *Registry) error

Check reports the first axis of the spec which the registry does not permit.

func (EdgeSpec) Destination

func (spec EdgeSpec) Destination(registry *Registry, override string) (Destination, error)

Destination is the file the edge goes in.

type Effect

type Effect struct {
	// Op is what happened to it.
	Op Op `json:"op"`

	// Tag is the form it was written as — node, vertex, edge, loop, type — so
	// that an effect says which family it is about without the reader resolving
	// the id.
	Tag string `json:"tag"`

	// ID is the thing it was about, and is empty for a form which carries no id
	// or whose id could not be read. A form which names nothing is still an
	// effect: it changed the file.
	ID ID `json:"id,omitempty"`

	// Name is the plain symbol a registry entry is declared under — a type
	// name, a predicate name — and is empty for every form which names itself
	// with an id instead.
	//
	// It is a second field rather than a widening of ID because the two are not
	// the same thing: an id is namespaced, is never reissued and resolves to a
	// node, and a registry name is none of those. A caller which read either
	// into one field would resolve a type called `site` against the id
	// `site:S-101`.
	Name string `json:"name,omitempty"`
}

Effect is one thing a change did to the model, as opposed to what it did to a file.

The two are not the same question and a caller asks both. Which files changed is what a review, a commit and a formatting check are about; what was created, modified or retired is what the author asked for and what an agent driving the command reads back to know that it landed.

type Elevation

type Elevation struct {
	// contains filtered or unexported fields
}

Elevation is the ground level the surface reports at one point, and where that level came from.

The zero Elevation is what a point outside the surface gets, and every method below works on it.

func (Elevation) At

func (e Elevation) At() Point

At returns the point the question was asked at, with the answer as its third component.

func (Elevation) Budget

func (e Elevation) Budget() SurfaceBudget

Budget returns that uncertainty broken out by contributing term.

It is the actionable half, and it is what a caller needs to combine a level with anything else: two levels off one surface share the terms their shots share, and adding two combined figures in quadrature would count those twice. Surface.Fall is that arithmetic done properly for the difference of two levels.

func (Elevation) Complete

func (e Elevation) Complete() bool

Complete reports whether the uncertainty accounts for the ground between the shots.

It is false where the derivation stated no SurfaceDerivation.Roughness. The level is still answered and its budget still holds every term the shots put there — what is missing is the one term no arithmetic over the shots can supply, and a caller deciding anything against a figure this is false for is deciding against a floor.

func (Elevation) From

func (e Elevation) From() []ID

From returns the records the level was interpolated from, sorted.

func (Elevation) Method

func (e Elevation) Method() SurfaceMethod

Method returns how the level was interpolated.

func (Elevation) Nearest

func (e Elevation) Nearest() float64

Nearest returns how far in plan the level was asked for from the nearest shot the surface rests on, in the surface's unit.

It is the distance the interpolation term of the budget is computed from, and on its own it is the honest answer to "how far from the evidence is this?".

func (Elevation) Report

func (e Elevation) Report() string

Report is the level rendered for a person: the summary, and one line per term of its budget beneath it.

It is here rather than in the command for the reason Fit.Report is: a library caller reporting a level and the command reporting one write the same thing.

func (Elevation) String

func (e Elevation) String() string

String writes the level, its uncertainty and what it came from.

func (Elevation) Uncertainty

func (e Elevation) Uncertainty() float64

Uncertainty returns the standard uncertainty of that level, one sigma, in the surface's unit.

It is propagated from the shots behind the answer under the weights the interpolation gave them, with each shot's independent error in quadrature and every systematic term the shots share added linearly and counted once ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)). Where the derivation stated a roughness it also carries the ground between the shots, which grows with the distance from them; where it did not, Elevation.Complete is false and this figure is a floor.

func (Elevation) Value

func (e Elevation) Value() float64

Value returns the ground level.

func (Elevation) Weights

func (e Elevation) Weights() []float64

Weights returns how much each of those records counted, in the same order as Elevation.From. They sum to one.

type EncodingError

type EncodingError struct {
	// Position is the first byte that is not part of a valid encoding.
	Position Position

	// Byte is that byte.
	Byte byte
}

EncodingError reports a file that is not valid UTF-8.

The position is the first offending byte rather than the file as a whole, because "this file is not UTF-8" is not something anybody can act on and "byte 0xff at line 12, column 3" is.

func (EncodingError) Error

func (e EncodingError) Error() string

Error implements the [error] interface.

type Entity

type Entity interface {
	// ID returns the id the model holds it under.
	ID() ID

	// Span returns where it was written, which is what a diagnostic about it
	// points at.
	Span() Span

	// ObservedIn returns the observation files it links to, as paths and never
	// as records. It is on the interface because the link is the one thing every
	// family carries for the same reason: all four are things somebody measured,
	// and a caller asking what the evidence behind an id is should not have to
	// know which family answered.
	ObservedIn() []ObservationLink
}

Entity is one thing a model holds under an id: a semantic node, or a vertex, an edge or a loop of the geometric family.

It exists because an id is unique across the whole model rather than within a family (specification section 6.9), so "what does this id name" is a question with one answer and no family in it. A caller which knows which family it wants asks that family; a caller holding an id out of a file, a command line or a diagnostic asks Graph.Entity and switches on what came back.

A claim is not an Entity. A claim id is optional, so a claim carries `ID() (ID, bool)` rather than an id, and the model holds only the claims which wrote one. Claims.Claim is the lookup for those.

type EntityFormat

type EntityFormat struct {
	// Major is the component which moves when a currently valid file stops
	// loading, stops meaning what it meant, or stops printing to the same
	// bytes.
	Major int

	// Minor is the component which moves when an optional child, a value shape
	// or a whole new form is added. Files which loaded still load.
	Minor int
}

EntityFormat is one version of the entity format specification: the MAJOR.MINOR pair SPEC.md section 10 states at the top of itself.

It is SpecVersion with the two components apart, because the two are compared rather than displayed. Whether a model loads is a question about the MAJOR on its own and about the MINOR under it, and a string comparison answers neither: "1.10" sorts before "1.9" and is the later of the two.

func ParseEntityFormat

func ParseEntityFormat(written string) (EntityFormat, error)

ParseEntityFormat reads a version written the one way SPEC.md section 10 writes one.

What comes back prints as what went in, and what does not print as what went in is refused: `1.02`, `01.2`, `+1.2` and `1.2.3` are each a version somebody meant and none of them is one this format has a spelling for. Accepting them would mean two spellings of one version, which is the beginning of a comparison that depends on which of them a caller happened to write.

func SpecFormat

func SpecFormat() EntityFormat

SpecFormat is the entity format this engine implements: SpecVersion, parsed.

It is a function rather than a variable so that no caller can assign to it. The version this engine implements is compiled in, and an engine which could be told it implements something else would report that to everybody who asked it — which is the failure this whole check exists to make impossible.

func (EntityFormat) LoadsUnder

func (f EntityFormat) LoadsUnder(engine EntityFormat) bool

LoadsUnder reports whether a model authored against f loads under an engine implementing engine.

It is the rule of SPEC.md section 10 read from the other end. A MINOR bump adds an optional child, a value shape or a whole new form, so an engine loads every model of its own MAJOR up to and including its own MINOR: a 1.1 model holds nothing a 1.2 engine does not know. A model at a later MINOR may hold a form the engine has never heard of, and a MAJOR apart in either direction is the version effect of "anything that makes a currently valid file fail to load" — so neither loads.

Being unable to load the *later* format is the obvious half. The other half is deliberate rather than conservative: a newer engine reading an older MAJOR is exactly the case that MAJOR was moved for, and reading such a file with this engine's rules would give it a meaning its author did not write.

func (EntityFormat) String

func (f EntityFormat) String() string

String implements fmt.Stringer, and is the one spelling of a version: the one SPEC.md states and the one ParseEntityFormat reads back.

type Epoch

type Epoch struct {
	// contains filtered or unexported fields
}

Epoch is the instant an artefact carries where its target format demands a creation or a modification time, together with the encodings such formats demand it in.

The renderings live here rather than in each exporter for the same reason the derivation does. A format's time field has a form the format decides — seconds since 1970 in one, a zoneless ISO 8601 string in the next, a prefixed digit run in a third — and an exporter writing its own is one `time.Format` call away from writing a clock reading instead. Adding a format to the ones below is a method here.

The zero Epoch is the epoch: an Epoch nobody derived renders as the one which was derived, rather than as year one.

func DerivationEpoch

func DerivationEpoch(of Digest) Epoch

DerivationEpoch is the instant an artefact carries wherever the format it is written in demands a creation or a modification time, for an artefact derived from the tree the given digest names.

It is the single derivation of that instant. Every command whose product is a file reads the value from here and no exporter reads a clock, because a clock reading in an exported file defeats everything the artefact is keyed by: two exports of an unchanged tree stop being byte-identical, so there is nothing left to diff, nothing to cache and nothing a golden fixture can hold ([0021](docs/decisions/0021-an-export-is-a-build-output-keyed-by-its-source-digest.md)).

It is a function of the source, and the function is constant

The epoch is defined as a function of the tree the artefact was derived from, which is what the digest names, and that is why the digest is the argument: nothing else may reach the value, and a call site reads as the tree deciding it rather than the machine the export happened to run on.

The function itself is constant — every tree, including the one nothing could be read from, gets 1970-01-01T00:00:00Z. 0021 settled that against the two live alternatives. A commit time is not available to a library which reads files rather than a repository, and is wrong the moment a working copy has an uncommitted edit. A time folded out of the digest would be stable, and is worse: it is a fabricated value with the shape of a real one, so every tool downstream displays a date somebody will eventually rely on. An obviously wrong constant is better than a convincing lie. A receiving tool showing 1970 prompts the question, and the answer — the provenance is the digest, carried through whatever mechanism the target format has for it — is the conversation which should happen.

So the argument does not change the answer, and it is not decoration: it is the rule the signature states. The day a format both mandates a real timestamp and validates it, the response 0021 names is not a clock but an explicit input which enters the artefact's key, and the value moves here rather than into an exporter.

Where the digest is unknown

A tree a file of which could not be read has the zero Digest, and a graph which was never on disk has one too. Both derive an epoch, the same one: producing an artefact may be refused for such a tree and that refusal is a diagnostic, but nothing about a timestamp is entitled to fail or to panic on the way to reporting it.

Note that the published image's org.opencontainers.image.created annotation is not this value. It is the commit's committer time, stamped by the release pipeline, which is a fact about a build rather than about a model — see docs/publishing.md.

Example

ExampleDerivationEpoch is the instant an exported artefact carries wherever its target format demands a creation time.

It is derived from the tree rather than from a clock, so two exports of an unchanged model are byte-identical and the provenance the timestamp field pretends to carry is carried properly instead — by the digest.

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad-model-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	entities := filepath.Join(root, "model.dfc")
	if err := os.WriteFile(entities, []byte("(node site:S-101 (label \"Meeting Room B\") (kind Space))\n"), 0o644); err != nil {
		fmt.Println(err)
		return
	}

	digest, err := dfcad.DigestOf(root)
	if err != nil {
		fmt.Println(err)
		return
	}

	epoch := dfcad.DerivationEpoch(digest)

	// Each format takes the encoding it demands, and no exporter writes its own.
	fmt.Println(epoch.ISO8601())
	fmt.Println(epoch.STEP())
	fmt.Println(epoch.PDF())
	fmt.Println(epoch.Seconds())

	// A tree which could not be read still answers, so a refusal reaches its
	// diagnostic rather than panicking on the way there.
	fmt.Println(dfcad.DerivationEpoch(dfcad.Digest{}) == epoch)

}
Output:
1970-01-01T00:00:00Z
1970-01-01T00:00:00
D:19700101000000Z
0
true

func (Epoch) ISO8601

func (e Epoch) ISO8601() string

ISO8601 is the instant as an ISO 8601 date and time in UTC, with the zone written as Z: 1970-01-01T00:00:00Z.

It is what a format defining its time field as an RFC 3339 string takes — IFC4's IfcDateTime, the created field of a container image manifest, and the date metadata of the XML-derived formats.

func (Epoch) PDF

func (e Epoch) PDF() string

PDF is the instant as a PDF date string, the form ISO 32000-1 section 7.9.4 defines: D:19700101000000Z.

It is what the CreationDate and ModDate entries of a document information dictionary take, which is the field a PDF writer fills from the clock unless it is told not to.

func (Epoch) STEP

func (e Epoch) STEP() string

STEP is the instant as the time stamp in the FILE_NAME header entity of an ISO 10303-21 exchange file: 1970-01-01T00:00:00.

The field carries no zone designator, which is a property of the field rather than of the instant — what is written is the UTC instant, spelt the way part 21 exchange files spell one.

func (Epoch) Seconds

func (e Epoch) Seconds() int64

Seconds is the instant as seconds since 1970-01-01T00:00:00Z.

It is what a format defining its time field as an integer count takes — IFC2x3's IfcTimeStamp, and the modification time of an entry in an archive format which stores POSIX times.

func (Epoch) String

func (e Epoch) String() string

String is the instant as Epoch.ISO8601 renders it.

func (Epoch) Time

func (e Epoch) Time() time.Time

Time is the instant, in UTC.

It is the rendering of last resort: a format whose encoding is not one of the ones below takes this and formats it, in the exporter, under a layout which is that format's business. Any exporter doing so is a candidate for a method here instead.

type Evidence

type Evidence map[ID]*Claim

Evidence is the claim each position a measurement was computed from was read from, keyed by the id of the thing that position belongs to: a vertex's own id for where the corner is, and an edge's for where the centre of the arc it bends along is.

It is the other half of Positions and of Curvature, supplied for the same reason: which predicate carries a position is vocabulary the consuming repository owns and not something the engine knows ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)). What it adds is the provenance a computed answer inherits. An area is only as well known as the corners and the centres it was computed from, and a budget accumulated from these claims is what lets the answer say so ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).

An id which is absent contributes nothing to the budget. The geometry is still computed — a position with no claim behind it is a caller which filled one map and not the other, which Survey.Place and Survey.Bend exist to prevent.

type ExternalClassification

type ExternalClassification struct {
	// System names the scheme, exactly as it was written.
	System string

	// Code names this type within that scheme, exactly as it was written.
	Code string

	// Span is where the classification was written.
	Span Span
}

ExternalClassification is how a scheme outside this model names a type, per specification section 7.3.

It is a pair of opaque strings and the engine interprets neither. There is no list of known systems, no syntax a code is held to, and no behaviour anywhere which reads either value: the pair is carried, printed and reported, and what it means is the business of whoever reads the model against that scheme. That is the whole point of the slot — a mapping from this project's vocabulary to a foreign one is a line of registry data somebody reviews, rather than a table compiled into the engine ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

It is named for the classification of a *type* rather than spelled Classification, which this package already uses for what an edge of a region's boundary separates it by. The two are unrelated and sharing an identifier would be the only thing suggesting otherwise.

type Failure

type Failure struct {
	// Message says what was expected and what was found, in that order.
	Message string

	// Hint is optional advice on what to do about it.
	Hint string

	// Span is the part of the subject which failed — the loop which does not
	// close, the edge which reaches nothing. The zero span means the failure is
	// about the whole subject, and the violation points at the node.
	Span Span

	// Related are the other places which explain this one.
	Related []RelatedLocation
	// contains filtered or unexported fields
}

Failure is what a check reports about a subject which does not satisfy it.

It carries what was wrong and nothing about which rule was being applied: the check name, the parameters and where the rule was declared are the binding's, and are attached to the Violation the run produces. A check which repeated them would be a second place they could disagree from.

type Fall

type Fall struct {
	// contains filtered or unexported fields
}

Fall is how much the ground drops between two points of one surface, and how well that drop is known.

It is a first-class answer rather than a subtraction a caller does, because the subtraction is where the correlation lives. Two levels off one surface are not two independent measurements: they are weighted sums of shots which share afternoons, base stations and the georeference which carried them, and the shared part of that error is in both levels *by the same amount*. It therefore cancels out of the difference — exactly, where both ends rest on the same session — and a caller who combined Elevation.Uncertainty twice in quadrature would report a fall as several times less certain than it is, then go and re-survey ground which was never the problem.

The zero Fall is what a pair of points outside the surface gets, and every method below works on it.

func (Fall) Budget

func (f Fall) Budget() SurfaceBudget

Budget returns the uncertainty of the drop, broken out by contributing term.

A term behind both ends appears once, at the difference of the weights the two ends gave it, so a session behind the whole surface comes back at nought and says so. That is the arithmetic which makes a fall answerable at all from shots no one level is worth deciding against.

func (Fall) Complete

func (f Fall) Complete() bool

Complete reports whether that uncertainty accounts for the ground between the shots, which it does only where the derivation stated a roughness.

func (Fall) Decides

func (f Fall) Decides(required float64) bool

Decides reports whether the fall is known well enough for a decision which needs it to a standard uncertainty of required, in the surface's unit.

It is deliberately a comparison against a figure the caller states rather than a verdict this package reaches: what a fall has to be known to is a property of what is being built on it — a drain, a step, a threshold — and nothing here knows that ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

A requirement which is not a figure greater than zero decides nothing, and a fall whose budget does not account for the ground between the shots decides nothing either: a floor compared against a requirement passes by leaving something out, which is the one way this could report a decision somebody should not make.

func (Fall) From

func (f Fall) From() Elevation

From returns the level at the point the fall was measured from.

func (Fall) Gradient

func (f Fall) Gradient() float64

Gradient returns the drop per unit of run, positive where the ground falls away. It is zero over a run of nothing, there being no gradient to state.

func (Fall) Report

func (f Fall) Report() string

Report is the fall rendered for a person: the summary, and one line per term of the budget beneath it.

The terms are the actionable half, and in a fall they are the surprising half too: the line which reads "cancels" is the whole reason a difference of two levels is worth asking for rather than working out by hand.

func (Fall) Run

func (f Fall) Run() float64

Run returns how far apart the two points are in plan.

func (Fall) String

func (f Fall) String() string

String renders the fall as a person reads it.

func (Fall) To

func (f Fall) To() Elevation

To returns the level at the point it was measured to.

func (Fall) Uncertainty

func (f Fall) Uncertainty() float64

Uncertainty returns the standard uncertainty of the drop, one sigma, in the surface's unit.

func (Fall) Value

func (f Fall) Value() float64

Value returns the drop from the first point to the second, in the surface's unit.

It is positive where the ground falls away from the first point, which is what a drainage question asks, and negative where it rises towards the second.

type File

type File struct {
	// Path is the file these datums were read from, exactly as the loader
	// reached it. It is the Path of every Position in the file.
	Path string

	// Nodes are the top-level datums, in the order they were written. A file
	// holding no datums has none, which is legal and contributes nothing.
	Nodes []*Node

	// Comments are the comments written at the top level of the file, in the
	// order they were written. A comment written inside a list belongs to that
	// list rather than to the file.
	Comments []*Comment
}

File is one loaded source file: the datums it holds, each carrying the span of source text it was written in.

A File says nothing about what those datums mean. Whether a top-level datum is a well-formed entity form, whether its tag is one the format knows and whether its children are the right ones is decided by validation, on this tree, and not here.

func LoadFile

func LoadFile(path string) (*File, error)

LoadFile reads one file into a spanned tree, whatever its extension.

This is the path a file named explicitly — on a command line, in a test — takes. Load is the same thing over a tree.

func Parse

func Parse(path string, r io.Reader) (*File, error)

Parse reads S-expression source into a spanned tree, reporting positions against path.

It is what LoadFile does once the file is open, exported for a caller holding source that did not come from a file it can name.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	source := `(node site:S-101
  (label "Meeting Room B")
  (kind Space))
`

	file, err := dfcad.Parse("entities/level-1.dfc", strings.NewReader(source))
	if err != nil {
		fmt.Println(err)
		return
	}

	// The label, two lists down, still knows where it was written.
	label := file.Nodes[0].Children[2].Children[1]

	fmt.Println(label.Span.Start)
	fmt.Println(source[label.Span.Start.Offset:label.Span.End.Offset])

}
Output:
entities/level-1.dfc:2:10
"Meeting Room B"
Example (Failure)
package main

import (
	"errors"
	"fmt"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	_, err := dfcad.Parse("entities/level-1.dfc", strings.NewReader("(date 2026-03-14)\n"))

	var parseErr dfcad.ParseError
	if errors.As(err, &parseErr) {
		fmt.Println(parseErr.Position)
	}

}
Output:
entities/level-1.dfc:1:7

type FileSources

type FileSources struct{}

FileSources is the SourceMap that reads each file from disk as a diagnostic asks for it. The zero value is ready to use.

It is what a command rendering diagnostics over a tree uses. A pass over a tree reads every file and holds almost none of them, and keeping each one against the chance that it turns out to have a problem would cost the whole tree in memory to quote a handful of lines.

A file it cannot read reports no source, which is exactly the case Diagnostic.Render already handles: the header lines are still written and the quoting is left out.

func (FileSources) Source

func (FileSources) Source(path string) ([]byte, bool)

Source implements SourceMap.

type FileStatus

type FileStatus string

FileStatus is what a commit did to one file.

const (
	// FileCreated marks a file the model did not hold before the change.
	FileCreated FileStatus = "created"

	// FileRewritten marks an existing file replaced by its new contents.
	FileRewritten FileStatus = "rewritten"

	// FileUnchanged marks a file a mutation touched whose canonical printing
	// turned out to be exactly what was already on disk. Nothing is written for
	// one: only the files actually affected are rewritten.
	FileUnchanged FileStatus = "unchanged"
)

type Finding

type Finding struct {
	// Kind is which check reported it.
	Kind FindingKind `json:"kind"`

	// Ruling is what the policy said to do about it.
	Ruling Ruling `json:"ruling"`

	// Subject is the id of the thing the finding is about: the boundary which
	// moved, the claim which was retracted, the id which disappeared.
	Subject ID `json:"subject"`

	// Side is which revision Span points into: [SideHead] or [SideBase].
	Side string `json:"side"`

	// Span is where the change is: in head for a change to something head
	// still holds, and in base for something it does not.
	Span Span `json:"span"`

	// Commit is the commit which introduced the change, and is the zero
	// [Revision] where the review was given no history to attribute it to.
	Commit Revision `json:"commit,omitzero"`

	// Message says what changed and what would have accounted for it.
	Message string `json:"message"`

	// Hint is advice on what to do about it, which is usually the command which
	// records the change properly.
	Hint string `json:"hint,omitempty"`

	// Related are the other places which explain this one — the claim which was
	// rewritten, the vertex which moved.
	Related []RelatedLocation `json:"related,omitempty"`

	// Dangling are the references head still makes to an id it no longer holds,
	// and are empty for every other kind.
	Dangling []Dangling `json:"dangling,omitempty"`
}

Finding is one change which is suspicious as a change.

It is not a Violation and not a Diagnostic, and the difference is the whole reason this mechanism is separate from assertions. An assertion constrains one revision and says the model is wrong; a finding needs two and says this change needs an explanation. Keeping them apart is what stops either growing into the other — an assertion which needed the previous revision would be a rule nothing could evaluate on a fresh checkout.

Finding.Diagnostic is the human rendering, through the same renderer every diagnostic uses. The machine rendering is this struct, and neither is produced by parsing the other.

func Review

func Review(base, head *Graph, policy Policy, history History) []Finding

Review compares head against its merge base and reports every change which is suspicious as a change.

base and head are the same model loaded at two revisions. What comes back is not a judgment about either of them on its own: every finding is about the difference, and a model which has always been in the state a check reports is reported by neither call.

policy decides what each finding means, and every finding carries the ruling it was given — including RulingIgnored, which is in the result and is reported nowhere else. history attributes each finding to the commit which introduced it and may be nil, which is a review with nothing to attribute rather than an error.

The order is deterministic: by check, in the order FindingKinds lists them, then by subject, then by position. Two runs over the same pair of revisions therefore produce the same list, so a diff between two runs is about what changed in the branch.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// One model at two revisions: the merge base, and the change under review.
	base, _ := dfcad.LoadGraph("testdata/review/base")
	head, _ := dfcad.LoadGraph("testdata/review/head")

	// Nothing is wrong with either revision on its own — both load, and both
	// satisfy every rule they state. What needs an explanation is the
	// difference between them, which is a question no single revision can be
	// asked.
	for _, finding := range dfcad.Review(base, head, dfcad.DefaultPolicy(), nil) {
		fmt.Println(finding.Ruling, finding.Kind, finding.Subject)
		fmt.Println(finding.Message)
		fmt.Println(finding.Hint)
	}

}
Output:
warning boundary-moved-without-claim site:S-101
the boundary of site:S-101 moved: the position of geom:V-02 was rewritten from (4.0 0.0 0.0) m to (4.6 0.0 0.0) m inside the claim which already stated it, so nothing new was measured
a corner which moved was measured again, so write the measurement: `dfcad supersede geom:V-02 position ...` keeps what the first survey said beside what the second one found

func (Finding) Diagnostic

func (f Finding) Diagnostic() Diagnostic

Diagnostic is the finding rendered for whoever wrote the change.

A ruling of RulingFailure is an error and everything else is a warning, so that the severity a reader sees is the one the policy stated rather than a second opinion about how much the finding matters.

func (Finding) String

func (f Finding) String() string

String renders the finding as one line: the ruling, the kind and the message.

type FindingKind

type FindingKind string

FindingKind names which diff-aware check produced a finding.

It is a string so that its machine-readable form is the same word a policy is written with and the same word the human rendering prints, for the reason Severity is one: a number would have to be kept in step with three spellings of itself.

const (
	// FindingBoundaryMoved is a physical boundary which moved with no new
	// measurement to account for it — a wall in a different place, where the
	// only thing which changed is the number.
	FindingBoundaryMoved FindingKind = "boundary-moved-without-claim"

	// FindingClaimDeprecated is a claim retracted with nothing standing in its
	// place. It is the belt-and-braces against the load-time rule: the load
	// refuses a deprecation whose replacement it cannot find, and this catches
	// the same shape across two revisions, including the change which retracts
	// a claim and removes its replacement together.
	FindingClaimDeprecated FindingKind = "claim-deprecated-without-replacement"

	// FindingIDDisappeared is an id the base revision held and head does not.
	// An id is assigned once and never reissued
	// ([0002](docs/decisions/0002-immutable-id-mutable-label.md)), so a thing
	// which stopped existing is retired and keeps its id; one which is simply
	// gone takes every reference to it with it.
	FindingIDDisappeared FindingKind = "id-disappeared-without-supersession"
)

The checks a review runs, in the order it reports them.

func FindingKinds

func FindingKinds() []FindingKind

FindingKinds returns every kind a review can report, in the order it reports them.

func ParseFindingKind

func ParseFindingKind(written string) (FindingKind, error)

ParseFindingKind reads a kind as a policy writes it.

type Fit

type Fit struct {
	// contains filtered or unexported fields
}

Fit is the answer to whether one thing sits inside another: the clearance between them, how well that clearance is known, and what that makes of the question.

It is the query the rest of this engine exists to make answerable, and the only one which touches every part of it at once. The proposal is read out of the corners which were surveyed in its own frame, carried into the envelope's frame across the transform claims which relate the two, offset by the clearance it is required to keep, overlaid on the envelope, and measured. The accuracy of every claim any of those steps read is accumulated on the way through ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)), so that the clearance and its error bar are two halves of one answer rather than a number and a footnote.

**The error budget is the point.** The georeference is one transform applied to every fact declared indoors, so its residual does not cancel between two indoor points and does not average away against an outdoor one. Combining it in quadrature with the random terms understates the answer, and understates it worst in exactly the case which motivates asking: a structure sited from interior geometry against an exterior boundary. So the budget adds the systematic terms linearly and counts each of them once however many inputs contributed it, which is Budget's own arithmetic — and this query is where that arithmetic earns its keep, because a shared control point genuinely arrives from both sides of the comparison.

Nothing here is written back to the model ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). A fit is recomputed from the claims every time it is asked for, so it cannot disagree with a re-survey which has landed since somebody last asked.

The zero Fit sited nothing, and every method below works on it.

func (Fit) Budget

func (f Fit) Budget() Budget

Budget returns the accumulated accuracy of everything the answer was computed from: the position claims behind both sets of corners, and the transform claims of every frame the proposal was carried through.

One budget rather than one per side is the whole arrangement. A control point which put the interior corners where they are and also fitted the georeference is one error appearing three times, and two budgets added together would count it twice while looking exactly like the honest answer ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).

func (Fit) Buildable

func (f Fit) Buildable() (Buildable, bool)

Buildable returns the derivation the envelope was, and whether the siting took the envelope's setbacks off it at all.

It is what says which setback claim moved which edge, and what the outline was before they did. The zero Buildable and false come back for a fit which sited inside the outline itself.

func (Fit) Carried

func (f Fit) Carried() bool

Carried reports whether the proposal had to be brought across a frame chain to be compared with the envelope.

It is what says whether a georeference is in the budget at all: two things declared in one frame are compared without reading a transform claim, and the answer is then as good as the positions and no worse.

func (Fit) ChordTolerance

func (f Fit) ChordTolerance() (Tolerance, bool)

ChordTolerance returns the declared tolerance the curves of either outline were drawn to on the way to the answer, and whether either of them bent at all.

A fit is an overlay, so a curved outline has to become segments before there is a question to answer at all. That the answer says which tolerance is what separates a clearance measured against the wall from one measured against a chord which may sit a stated distance inside it.

func (Fit) Clearance

func (f Fit) Clearance() float64

Clearance returns how much room there actually is, in Fit.Unit.

It is positive where the proposal sits wholly inside the envelope, and is then the shortest distance between the two boundaries — the tightest point, which is the only one worth reporting. It is negative where the proposal does not sit inside: how far the part which is outside reaches past the boundary where the two overlap, and how far apart they are where the proposal is not over the envelope at all.

Both signs are the same quantity read the same way round — how much room there is, with a deficit written as a negative amount of it — so a caller which compares the number to a threshold does not have to case-split on which situation the model is in.

func (Fit) Consumed

func (f Fit) Consumed() bool

Consumed reports whether the envelope's setbacks left nothing buildable.

Nothing fits inside a region which covers nothing, so a consumed envelope is VerdictDoesNotFit whatever the proposal and however well anything is known. There is then no boundary to measure a room to, so Fit.Clearance is nought and means nothing; this is what says so, rather than a clearance a caller would have to recognise as a sentinel.

func (Fit) DeclaredIn

func (f Fit) DeclaredIn() ID

DeclaredIn returns the frame the proposal was written in.

func (Fit) Deviation

func (f Fit) Deviation() float64

Deviation returns how far the worst segment of that drawing falls from the curve it stands in for, in Fit.Unit.

It is a bound on the outlines and not an accuracy of the answer, so it is reported beside the margin rather than folded into Fit.Budget: a chord which may lie ten millimetres inside the wall is a decision the caller made, and an uncertainty is what nobody decided.

func (Fit) Envelope

func (f Fit) Envelope() Region

Envelope returns the region the proposal had to sit inside.

It is the envelope's outline as the model holds it, or — where the siting took the envelope's setbacks off it — what those setbacks leave buildable, which Fit.Buildable carries the derivation of.

func (Fit) Frame

func (f Fit) Frame() ID

Frame returns the frame the answer is expressed in, which is the envelope's.

func (Fit) Margin

func (f Fit) Margin() float64

Margin returns how much the clearance beats its requirement by, which is Fit.Clearance less Fit.Required.

It is the quantity the verdict is decided on, and it reduces to the clearance itself where nothing beyond fitting at all was required. The one verdict not decided on it is a Fit.Consumed envelope's, which is decided by there being nothing to fit inside.

func (Fit) Needed

func (f Fit) Needed() Region

Needed returns the proposal grown by the clearance it was required to keep, which is the shape the envelope had to accommodate.

It is the proposal itself where the required clearance was nought.

func (Fit) Proposal

func (f Fit) Proposal() Region

Proposal returns the thing which was sited, expressed in the envelope's frame.

It is the carried region rather than the one which was read, because that is the one every number here was computed from. Handing back the region in its own frame would be handing back coordinates the answer is not in.

func (Fit) Report

func (f Fit) Report() string

Report is the fit rendered for a person: the summary, and one line per term of the budget beneath it.

The terms are the actionable half. "It might fit" is a finding somebody has to do something about, and what to do is decided by which term dominates — re-run the georeference, or re-survey the corners, or accept the risk.

It is here rather than in the command so that a library caller reporting the answer and the command reporting it write the same thing.

func (Fit) Required

func (f Fit) Required() float64

Required returns the clearance the proposal was asked to keep inside the envelope, in Fit.Unit.

func (Fit) Shared

func (f Fit) Shared() Region

Shared returns what the proposal and the envelope have in common.

func (Fit) Spill

func (f Fit) Spill() Region

Spill returns what the proposal needs and the envelope does not offer.

It covers nothing for a proposal which fits, and it is where a refusal points for one which does not: a fit answered only by "no" leaves somebody to work out which corner is over the line.

func (Fit) String

func (f Fit) String() string

String renders the fit as a person reads it.

func (Fit) Subject

func (f Fit) Subject() ID

Subject returns the id of the node which was sited.

func (Fit) Uncertainty

func (f Fit) Uncertainty() (Uncertainty, error)

Uncertainty returns the budget reduced to one standard uncertainty, and what stopped it where it could not be.

It is what the clearance is judged against, so a fit whose uncertainty cannot be computed is VerdictUnknown rather than a fit.

func (Fit) Unit

func (f Fit) Unit() Unit

Unit returns the linear unit of that frame, which every distance here is in and every area in the square of.

func (Fit) Verdict

func (f Fit) Verdict() Verdict

Verdict returns what the clearance makes of the question once its own uncertainty is taken into account.

type Footprint

type Footprint struct {
	// contains filtered or unexported fields
}

Footprint is the derived geometry of one node: the plane figure it covers, how much area that encloses, where the area is centred, how far it reaches and which regions it lies inside.

Everything here is derived and none of it is ever written back into an entity file ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). Footprint.Digest is the digest of the source tree it was computed against, which is what lets a consumer check that a figure it was handed matches the model in front of it rather than an earlier one.

Every figure is in the unit of the frame the node is declared in and nothing converts ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)): a length in that unit, an area in it squared.

A figure comes back with whether it could be computed, because "there is no answer" and "the answer is zero" are different states. The zero Footprint has none of them and every method below works on it.

func (Footprint) Area

func (f Footprint) Area() (float64, bool)

Area returns what the figure encloses, in the square of Footprint.Unit, and whether it could be computed.

func (Footprint) Bounds

func (f Footprint) Bounds() (Box, bool)

Bounds returns the axis-aligned bounding box, and whether it could be computed.

func (Footprint) Centroid

func (f Footprint) Centroid() (Point, bool)

Centroid returns where the area is centred, and whether it could be computed. It is the area centroid and not the mean of the corners.

func (Footprint) Digest

func (f Footprint) Digest() Digest

Digest returns the digest of the source tree it was derived from, which is the zero Digest where the tree could not be digested.

func (Footprint) Frame

func (f Footprint) Frame() ID

Frame returns the frame the node is declared in.

func (Footprint) Perimeter

func (f Footprint) Perimeter() (float64, bool)

Perimeter returns the total length of the loops bounding the node, in Footprint.Unit, and whether it could be computed.

func (Footprint) Pieces

func (f Footprint) Pieces() []Piece

Pieces returns the plane figure the node covers: one Piece per connected part, each a ring with the rings taken out of it.

It is the same figure Topology.RegionOf reads, which is where it came from. A node covering nothing has none.

func (Footprint) String

func (f Footprint) String() string

String writes the figures which were computed, with their units.

func (Footprint) Subject

func (f Footprint) Subject() ID

Subject returns the id of the node the geometry was derived from.

func (Footprint) Unit

func (f Footprint) Unit() Unit

Unit returns the linear unit of that frame, which every figure here is in.

func (Footprint) Within

func (f Footprint) Within() []ID

Within returns the ids of the regions this one lies entirely inside, in id order.

It is derived membership and not the `within` written on a node: a courtyard is inside the floor plate around it because of where its corners are, whether or not anybody wrote the containment down. Nodes.Within is the authored answer, and the two disagreeing is a thing worth knowing rather than a bug in either.

Membership is judged only between regions one operation could be run over — one frame, one tolerance, one plane. Two floor plates on different storeys are inside each other seen from above and are not inside each other, so neither is reported as within the other.

A region coincident with another is not within it. Neither is inside the other, and reporting both as members of each other would make containment cyclic.

type Footprints

type Footprints struct {
	// contains filtered or unexported fields
}

Footprints is the derived geometry of a whole model, and the digest of the source tree every figure in it was computed against.

It is derived as one artefact rather than one per node because membership is a question about the set: which regions a room is inside is not answerable from the room alone. Keying the set by the digest of the tree is what makes that sound — every footprint in one of these was derived from the same bytes.

The zero Footprints holds nothing and every method below works on it.

func (Footprints) All

func (f Footprints) All() iter.Seq[Footprint]

All iterates the footprints in the order the walk reached their nodes, which is deterministic, so anything built from it diffs against the last run's.

func (Footprints) Digest

func (f Footprints) Digest() Digest

Digest returns the digest of the source tree every footprint was derived from, which is the zero Digest where the tree could not be digested.

func (Footprints) Len

func (f Footprints) Len() int

Len reports how many nodes have a derived footprint.

func (Footprints) Of

func (f Footprints) Of(id ID) (Footprint, bool)

Of returns the footprint of one node, and whether it has one. A node which references no loop covers nothing and has none.

func (Footprints) Position

func (f Footprints) Position() string

Position returns the name of the predicate the corners were read from.

func (Footprints) Tolerance

func (f Footprints) Tolerance() string

Tolerance returns the name of the registry tolerance coincidence was judged against.

type Formatted

type Formatted struct {
	// Path is the file, exactly as the walk reached it. On a path that could
	// not be reached it is that path, which need not name a file: a directory
	// that cannot be read and a name that is not there are both reported here.
	Path string

	// Changed reports whether what is on disk differs from its canonical form.
	// A file that failed to be read or parsed reports false: nothing is known
	// about a file that could not be printed.
	Changed bool

	// Written reports whether the file was replaced by its canonical form.
	Written bool

	// Diff is the unified diff from what is on disk to its canonical form, or
	// empty when the file is already canonical or no diff was asked for.
	Diff string

	// Diagnostics are the problems found in the file's contents: it does not
	// parse, it is not UTF-8, it begins with a byte order mark. They are for
	// whoever wrote the file.
	Diagnostics []Diagnostic

	// Err is the failure that stopped the file being read or replaced. It is
	// for the caller: a file it has no permission to read is not a mistake
	// anybody made in the file.
	Err error
}

Formatted is what formatting did to one file, or, where Err says a path could not be reached at all, what stopped it.

func (Formatted) Failed

func (f Formatted) Failed() bool

Failed reports whether the file was neither confirmed canonical nor made so.

type Formatter

type Formatter struct {
	// Rewrite reports whether a file that is not in canonical form is replaced
	// by it.
	//
	// The replacement is atomic. The complete new contents are written to a
	// temporary file in the same directory, flushed to durable storage, and
	// renamed over the target, so an interruption at any point leaves the
	// original file intact rather than a prefix of the new one.
	Rewrite bool

	// Diff reports whether a file that is not in canonical form carries a
	// unified diff of what would change.
	//
	// It is independent of Rewrite: the diff describes the same replacement
	// whether or not the replacement is performed.
	Diff bool
}

Formatter rewrites entity files into the canonical form Print writes.

It exists so that formatting stops being something anybody discusses. A tree that has been through a formatter has one spelling of every model, so a diff over it is about the change rather than about whitespace, and the command line interface writing a file and a person editing one by hand converge instead of developing competing house styles.

Every file is treated on its own. A file that does not parse is reported and left exactly as it was, and the files after it are still formatted: a pass over a tree that stopped at the first unparseable file would be one nobody could run on the tree they were fixing.

The zero value writes nothing, which makes a check the safe default: a caller that has not said it wants the tree changed does not change it.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The zero value writes nothing, so this reports what a rewrite would do
	// without doing any of it. Setting Rewrite is what replaces the files.
	for _, file := range (dfcad.Formatter{}).Format("testdata/model") {
		switch {
		case file.Failed():
			fmt.Printf("%s: could not be formatted\n", file.Path)
		case file.Changed:
			fmt.Printf("%s: not in canonical form\n", file.Path)
		}
	}

}
Output:
testdata/model/entities/level-1.dfc: not in canonical form
testdata/model/registry/registry.dfc: not in canonical form

func (Formatter) Format

func (f Formatter) Format(paths ...string) []Formatted

Format formats every entity file under each of paths.

A path may name a single file, which is formatted whatever its extension, or a directory, beneath which every file whose extension is Extension is formatted. Several of each may be given, and a file reached twice — named twice, or named as well as walked into — is formatted once.

Results come back one per file, in the order the paths were given and, under a directory, in the lexical order Walk yields. The order is therefore the same for every run over the same tree, which is what makes two runs' output worth diffing.

A path the walk cannot reach at all comes back as a result too, carrying the error that stopped it. Its Path is then whatever could not be reached, which is a directory rather than a file when a directory is what could not be read, and it names something that does not exist when that is what was asked for. Leaving those out would mean a caller counting results could not tell a tree it formatted from a tree it mostly failed to open.

Formatting is idempotent: a second pass over what a first one wrote reports every file unchanged, because canonical form is the fixed point the printer writes to.

type Frame

type Frame struct {
	// ID is the frame's id, which is why a frame is the one registry entry
	// named by an id rather than by a plain symbol.
	ID ID

	// Label is the frame's name for a person reading it. Empty when it was not
	// written.
	Label string

	// Unit is the frame's one linear unit
	// ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).
	Unit Unit

	// Parent is the id of the frame this one is expressed relative to. Empty
	// for the root frame.
	Parent ID

	// Transform is the id of the claim holding the transform to the parent.
	// Empty for the root frame.
	Transform ID

	// Claims are the claim forms written on the frame, unmodified. Which
	// predicate each is under, and whether its value is what the predicate
	// declares, is the claim layer's question and not this one's.
	Claims []*Node

	// Span is where the declaration was written: the frame's id, which is what
	// a diagnostic about the declaration points at.
	Span Span

	// Form is the whole of the frame form, from its opening parenthesis to its
	// closing one — the span a node's form is reported by, which is what a
	// retrieval of the frame as a node reports it by too.
	Form Span
}

Frame is one declared coordinate frame, per specification section 7.5.

A frame is both a registry entry and a node: its unit and its parent are vocabulary the consuming repository owns, and it carries an id and claims because the relationship between two frames is a measurement rather than a configuration constant.

func (Frame) Plain

func (f Frame) Plain(predicate string) []Value

Plain returns the plain values written on the frame under predicate, in the order they were written.

A predicate the registry declares non-claim-bearing takes a plain value and no children (specification section 6.5), and the claim pass makes no claim of it: there is no source, no method and no accuracy on it. This is how one is read back from the frame alone — Claims.PlainOf is the same values read by that pass, for every form a claim may be written on — and it is what carries a fact about a frame which is not a measurement — the name of the coordinate reference system it is rooted at, say — without dressing it up as one.

The shape is what was written rather than what the predicate declares, because a Frame carries no registry to look that declaration up in. A form under predicate holding no plain value is not returned: a claim form is one, and so is a transform, which is written as a child form rather than positionally and is read through Frames.Transform with the claim around it.

The slice is empty for a predicate nothing wrote. More than one is not an error here — repeating a predicate is the ordinary case — and what to make of two is the caller's, which is the only place it can be decided.

Example

A predicate the registry declares non-claim-bearing carries a plain value, and Frame.Plain is how one written on a frame is read back.

It is what carries a fact about a frame which is not a measurement. The name of the projected coordinate reference system the chain is rooted at is the example: it names an entry in somebody else's register, so there is no source, no method and no accuracy to put on it, and the engine records it without ever resolving or converting it.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/frame/valid")

	// The root of the chain is the frame declaring no parent, which is the
	// projected system every other frame reaches through its parents.
	root, _ := registry.Frame("frame:survey-grid")

	for _, value := range root.Plain("crs") {
		identifier, _ := value.Text()
		fmt.Printf("%s is rooted at %s\n", root.ID, identifier)
	}

	// A transform is not among them: it is read through the claim which
	// measures it, together with the source and the accuracy of that fit.
	fmt.Println(len(root.Plain("frame-transform")))

}
Output:
frame:survey-grid is rooted at EPSG:25831
0

type FrameCycleError

type FrameCycleError struct {
	// Frame is the frame the walk re-entered.
	Frame ID
}

FrameCycleError reports a parent chain which returns to a frame it already passed through.

The cycle itself is a load error naming every frame in it, which the registry reports. This is what the walk does when a caller asks anyway: it stops at the frame it re-entered rather than following the chain forever.

func (FrameCycleError) Error

func (e FrameCycleError) Error() string

Error implements the [error] interface.

type Frames

type Frames struct {
	// contains filtered or unexported fields
}

Frames is the frame graph of one model: the chain each declared frame reaches the root through, and the claim which measures each frame against its parent.

A frame is both a registry entry and a node, and this is the second half of it. The registry says which frames exist, which unit each is in and which frame each is expressed relative to; what the relationship between two of them actually is, is a measurement — a fit, with a residual, produced by a method on a date — and lives in a claim like every other measurement in the model. Joining the two is what this pass does, and it is why a cross-frame answer can say how well the relationship it used is known.

**A shape lives in exactly one frame and is transformed on demand.** Storing one shape in two frames is two sources of truth which drift the moment the georeference is re-fitted, so a shape assembled from parts in two frames is a load error rather than something this converts between.

A Frames is read-only once resolved. The zero value holds nothing, which is what a model declaring no frame yields, and every method below works on it.

func (*Frames) Chain

func (f *Frames) Chain(frame ID) iter.Seq[Frame]

Chain iterates the frames from frame to the root, beginning with frame itself.

It is what "expressed relative to" means followed all the way up, and it is what every cross-frame answer is composed along. A frame id nothing declares yields nothing.

A chain which does not reach a root stops rather than running forever: at a parent nothing declares, and at a frame it has already passed through. Both are load errors the registry reports, and neither is a reason for a traversal to hang.

func (*Frames) Measurement

func (f *Frames) Measurement(frame ID) (*Claim, bool)

Measurement returns the claim which measures frame's transform to its parent, and whether one resolved.

This is the claim itself and not the transform inside it, because the whole point of the arrangement is what comes with it: the source it was fitted from, the method which produced it, the date it was produced on, and the accuracy it was produced to. That accuracy is a systematic term in every cross-frame budget the transform touches, and it exists here rather than nowhere because a georeference is a measurement rather than a setting.

The root frame has none, which is what makes it the root.

func (*Frames) Root

func (f *Frames) Root() (Frame, bool)

Root returns the frame every chain is rooted at, and whether the model declares one.

It is the projected coordinate reference system the model is expressed relative to. Exactly one frame per model declares neither a parent nor a transform; a second is a load error the registry reports, and this is then the first of them in id order.

func (*Frames) Transform

func (f *Frames) Transform(frame ID) (Transform, bool)

Transform returns the transform which maps a point in frame to a point in frame's parent, and whether one resolved.

It is the value of Frames.Measurement, and reading it without the claim around it is reading a number without the evidence for it. Where the answer is going to be reported to anybody, the claim is what to report from.

func (*Frames) TransformBudget

func (f *Frames) TransformBudget(from, to ID) (Budget, error)

TransformBudget returns the accumulated uncertainty of the relationship between two frames.

It is the budget of every answer Frames.TransformPoint produces along the same route, and it exists separately because a position and how well that position is known are two questions with two answers: a caller placing a point wants the point, and a caller deciding against a clearance wants the budget behind it.

The terms are the accuracies of the fits the route passes through, in the order it passes through them, and a systematic term shared by two of those fits is counted once however many frames it is reached through ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)). That is the whole difference between an honest cross-frame budget and an optimistic one: a building georeferenced against the same control point as the site it sits in does not get to cancel that control point's error against itself.

Two frames which are the same frame have a budget of no terms, which Budget.Combined reports as ErrEmptyBudget rather than as an exact zero. A point is not transformed at all in that case, so there is nothing to be uncertain about and nothing to state a figure for.

A fit which states no accuracy taints the budget rather than being read as exact, and every way a route can fail to exist is the error Frames.TransformPoint reports for it.

Nothing here converts between units. Where the route passes through frames of different linear units, the fits' accuracies are in the units they were written in, and Budget.Combined reports that disagreement as a MixedUnitsError rather than reconciling it ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/frame/valid"

	registry, _ := dfcad.LoadRegistry(root)
	claims, _ := dfcad.LoadClaims(root, registry)
	frames, _ := dfcad.ResolveFrames(registry, claims)

	// The route from the room to the annex climbs two fits and comes back down
	// through a third. Two of the three were fitted against the same control
	// point.
	budget, err := frames.TransformBudget("frame:room", "frame:annex")
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, term := range budget.Terms() {
		fmt.Printf("%-11s %-13s %g %s\n", term.Kind, term.Name, term.Magnitude, term.Unit)
	}

	combined, _ := budget.Combined()
	fmt.Printf("combined %.6f %s at k = %g\n", combined.Magnitude, combined.Unit, combined.CoverageFactor)

	dominant, _ := budget.Dominant()
	fmt.Printf("dominated by %s, shared by %d fits\n", dominant.Name, len(dominant.Contributors))

}
Output:
independent survey:C-0004 0.002 m
independent survey:C-0002 0.004 m
systematic  survey:CP-3   0.008 m
independent survey:C-0003 0.006 m
combined 0.010954 m at k = 1
dominated by survey:CP-3, shared by 2 fits

func (*Frames) TransformPoint

func (f *Frames) TransformPoint(point Point, from, to ID) (Point, error)

TransformPoint maps a point expressed in one frame to the same position expressed in another.

The point is in from's linear unit and the result is in to's, because a frame declares exactly one and a point in a frame is in that one ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)). Every conversion between them applies the pinned definitions in Unit.Metres and nothing else: a transform's `scale` is a scale rather than a unit conversion, so a fit which found no scale error contributes a factor of one however far apart the two units are.

The route is up from's chain to the lowest frame both chains pass through and back down to's, which is what makes this work in both directions and between two frames neither of which contains the other. The transforms above the frame they meet at are not read, because the route does not pass through them.

Everything which can stop it is an error naming what stopped it: a frame nothing declares, a parent chain which cycles, a frame whose transform did not resolve to a transform claim, two frames whose chains never meet, a frame whose linear unit is not one the engine defines, and a transform which cannot be run backwards. Each is a value a caller can inspect rather than a message to match on, and none of them is answered with a position anyway.

type Geometry

type Geometry string

Geometry is one of the geometry forms compiled into the engine.

The set is closed for the same reason Kind is. Absence is not a member: a node with no geometry omits the child, and only the type registry names absence, which is what Type.Absent records.

const (
	GeometryPoint   Geometry = "point"
	GeometryLine    Geometry = "line"
	GeometryArea    Geometry = "area"
	GeometrySurface Geometry = "surface"
	GeometrySolid   Geometry = "solid"
)

The geometry forms, in the order specification section 1 lists them.

func Geometries

func Geometries() []Geometry

Geometries returns the closed set of geometry forms, in specification order.

type GlobalID

type GlobalID string

GlobalID is IFC's identifier for one rooted object: a 128-bit value written as the 22 characters of IFC's own base64 alphabet.

It is derived rather than authored, and it is derived from the node's ID and nothing else ([0004](docs/decisions/0004-globalid-derives-from-a-pinned-namespace.md)). There is no `GlobalId` field anywhere in the format, which is what stops a second identifier per node from being hand-maintained beside the one which identifies the thing, and drifting out of step with it.

Deriving it is what makes an export stable: two exports of a node nothing happened to carry the same GlobalID, so a receiving system sees an update rather than a delete and a re-create. Everything which makes that true is recorded — the pinned URL in the registry, the two derivation steps below — so anyone holding the registry can recompute a value and check this package's arithmetic with any UUIDv5 implementation.

A SemanticNode label is not part of it. Renaming a room changes what is displayed and nothing a downstream system holds, which is the same arrangement ID and SemanticNode.Label already have ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

func DeriveGlobalID

func DeriveGlobalID(url string, id ID) GlobalID

DeriveGlobalID derives the GlobalID of id within the namespace pinned at url, per [0004](docs/decisions/0004-globalid-derives-from-a-pinned-namespace.md).

The derivation is two steps and no state:

  1. The project namespace UUID is `UUIDv5(RFC 4122 URL namespace, url)`.
  2. The node UUID is `UUIDv5(that namespace, id)`, over the whole `namespace:local` id as it is written, encoded as UTF-8.

and the GlobalID is those 128 bits in IFC's 22-character encoding.

It is a pure function of its two arguments. The same url and the same id yield the same characters in every run, every process and on every machine, because nothing here reads a clock, a random source, the environment or anything else which is not one of the two arguments — which is the whole reason the value is derived rather than minted and stored.

url is not checked here. Which URL a model pins is a property of the model and is validated where it is read, and a derivation which refused an unexpected URL would be a derivation which could not reproduce a value exported by an older model — the one thing it exists to do.

Registry.GlobalID is this with the url read from the model's project declaration, and is what a caller holding a loaded model wants.

func (GlobalID) String

func (g GlobalID) String() string

String returns the 22 characters, which is the form an IFC file carries.

type Graph

type Graph struct {
	// contains filtered or unexported fields
}

Graph is one whole model, loaded: the vocabulary it declares, both families of nodes, the claims written on them, the frames those claims measure and the boundaries which join the two families.

This is the type every command reads. A caller which loaded the six pieces itself would have to know that a registry is resolved before an entity is interpreted, that boundaries need both families, that frames need the claims, and that all four passes read the same tree; getting any of that wrong is a model which loads differently depending on which question was asked of it first.

A Graph is read-only once loaded. Nothing here writes to a file and nothing caches a derived answer: the conflict register, a loop's closure and an edge's classification are computed from the model every time they are asked for ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). The one derived thing which may be kept is kept outside the graph, in a build output directory a caller hands in, keyed by the digest of the tree it was derived from — see Graph.Derive and Cache.

func (*Graph) Adjacent

func (g *Graph) Adjacent(region *SemanticNode) iter.Seq[Adjacent]

Adjacent iterates the regions which share at least one boundary edge with region, each with the edges they share.

func (*Graph) AdjacentTo

func (g *Graph) AdjacentTo(region *SemanticNode, depth int) iter.Seq[Adjacent]

AdjacentTo iterates the regions region borders and the regions those border, to at most depth steps.

func (*Graph) AdjacentWalk

func (g *Graph) AdjacentWalk(region *SemanticNode, depth int, filter AdjacencyFilter) iter.Seq[Adjacent]

AdjacentWalk iterates the regions reachable from region across the shared edges filter allows to be crossed, through the regions it allows to be entered, to at most depth steps.

func (*Graph) AllAssertions

func (g *Graph) AllAssertions() iter.Seq[AssertionBinding]

AllAssertions iterates every assertion of the model, family by family in the order Graph.Entity looks them up and, within one thing, in the order they were written.

The order is deterministic for the reason the load's is: a listing of what would run, and a report of what did, have to diff against the last run's.

func (*Graph) AllInvariants

func (g *Graph) AllInvariants() iter.Seq[InvariantBinding]

AllInvariants iterates every invariant bound to every instance of the model, node by node in the order the load read them and, within a node, in the order its type declared them.

The order is deterministic for the reason the load's is: a listing of what would run, and a report of what did, have to diff against the last run's.

func (*Graph) AllObservations

func (g *Graph) AllObservations() (*ObservationLog, []Diagnostic)

AllObservations returns the records of every observation file the model links to, as one log, with whatever is wrong with them.

It is the corpus a question about the model rather than about one entity is answered from — which shots fall inside this region (Graph.ObservationsWithin) is the case it exists for. A file linked by two entities is read once and its records appear once, because the records are the field work and not the links to it.

**This reads every observation file the model links to**, which is precisely what Graph.Observations exists to avoid doing on a caller's behalf. Nothing calls it as part of loading a model, and a command which asks a question about one entity should ask Graph.Observations instead. Reading is still done once for the life of the graph.

The order is the order a walk reads the files in — the lexical order of their paths, then the order of the lines within each — which is what makes "earlier in the log", and so which retirement retires what, one question with one answer.

func (*Graph) Ancestors

func (g *Graph) Ancestors(node *SemanticNode) iter.Seq[Related]

Ancestors iterates the containment chain above node, nearest first.

func (*Graph) AncestorsTo

func (g *Graph) AncestorsTo(node *SemanticNode, depth int) iter.Seq[Related]

AncestorsTo iterates the containment chain above node, nearest first, to at most depth steps.

func (*Graph) Assertions

func (g *Graph) Assertions(subject Entity) []AssertionBinding

Assertions returns the assertions written on one thing, bound to what the check registry says each check constrains, in the order they were written.

It is what a caller showing a thing shows beside its claims: the claims are what is known about it and these are what must hold of it. Graph.Entity is how the thing is found, and either family answers.

An assertion naming a check nothing registers is not among them. That is a load error rather than a rule, and there is no declaration to bind it to; SemanticNode.Assertions and its siblings are the assertions as written, which is what a listing that wants to show the misspelled one reads.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/assert/valid")

	// An assertion is written on the thing it constrains, so retrieving the
	// thing retrieves what has to hold of it. The claims say what the room
	// measures; these say what it may not stop measuring.
	room, _ := graph.Node("site:S-101")
	for _, assertion := range room.Assertions() {
		fmt.Println(assertion)
	}

	// Bound against the check registry, each one carries what the check it
	// names constrains — which is readable without running anything, because an
	// assertion is a name and its parameters and nothing else.
	for _, binding := range graph.Assertions(room) {
		fmt.Printf("%s: %s\n", binding.Check.Name, binding.Check.Description)
	}

}
Output:
within-resolves
required-claim (predicate width)
boundary-loops-close (tolerance boundary-closure)
within-resolves: The node the subject is written within is one the model holds, the containment hierarchy permits it as a parent of the subject's kind, and it has not been retired while the subject still stands.
required-claim: The subject carries at least one claim under the named predicate which is still asserted — one not deprecated. Whether several such claims resolve to one of them, and whether any can be ranked, is not what this decides: an unranked or an ambiguous value is still a value somebody claimed, and the conflict register is what reports it.
boundary-loops-close: Every loop bounding the subject closes: traversing its edges returns to the vertex it started from, within the named tolerance. A loop every node bounded by it draws as a line is an open run and is not asked to close.

func (*Graph) Boundaries

func (g *Graph) Boundaries() *Boundaries

Boundaries returns the join between the two families: which loop bounds which region, and what each edge of a boundary is backed by.

func (*Graph) Bounded

func (g *Graph) Bounded(loop *Loop) iter.Seq[*SemanticNode]

Bounded iterates the nodes loop bounds.

func (*Graph) Bounding

func (g *Graph) Bounding(entity Entity) iter.Seq[*Edge]

Bounding iterates the edges a measurement of entity is computed across, each yielded once and in the order the thing reaches them.

It is Graph.Corners for the other family, and it exists for the same reason: an edge is where a curve is written, so a caller resolving the arcs of a shape has to reach exactly the edges the answer will be read across. One built by hand from a guess is a shape read partly as arcs and partly as the straight lines between their ends, and nothing in the answer would say which was which.

A semantic node reaches them through its loops, which is Boundaries.Edges; a loop reaches them through the ids it names, in the order it names them; an edge is itself; a vertex reaches none, because a corner has no side to bend. An entity of no family reaches none.

func (*Graph) CheckAssertions

func (g *Graph) CheckAssertions() []Violation

CheckAssertions runs every assertion the model writes and returns one violation for each way one of them is not satisfied.

A model whose things carry no assertion, and one whose assertions all hold, both yield none. An assertion naming a check which cannot examine the thing it was written on is not run: that is a load error (ResolveAssertions), and running it would be answering a question about a subject the check has nothing to look at on.

Violations come back in the order Graph.AllAssertions bound them, and within one binding in the order the check reported them. Collecting them into a Diagnostics is what puts them in reporting order, which is by position.

func (*Graph) CheckInvariants

func (g *Graph) CheckInvariants() []Violation

CheckInvariants runs every invariant bound to every instance and returns one violation for each way one of them is not satisfied.

A model whose types declare no invariant, and one whose instances all satisfy theirs, both yield none: a type with nothing to say produces no output rather than a line saying it had nothing to say.

Violations come back in the order Graph.AllInvariants bound them, and within one binding in the order the check reported them. Collecting them into a Diagnostics is what puts them in reporting order, which is by position.

func (*Graph) Claims

func (g *Graph) Claims() *Claims

Claims returns the claims written on both families, which is also where the conflict register and the resolution rule are read from.

func (*Graph) Classified

func (g *Graph) Classified(edge *Edge) BoundaryEdge

Classified pairs edge with its classification and with the elements which physically realise it.

func (*Graph) Classify

func (g *Graph) Classify(region *SemanticNode) iter.Seq[BoundaryEdge]

Classify iterates the edges of region's boundary, each classified physical or virtual.

func (*Graph) Contains

func (g *Graph) Contains(node *SemanticNode) iter.Seq[Related]

Contains iterates the nodes written directly within node.

func (*Graph) Corners

func (g *Graph) Corners(entity Entity) iter.Seq[*Vertex]

Corners iterates the vertices a measurement of entity is computed from, each yielded once and in the order the thing reaches them.

It is the other half of Graph.Measure: a survey which is missing one of these is a measurement which cannot be made, and one built by hand from a guess at which corners matter is the way that happens. A caller places a position for each of these with Survey.Place and has surveyed exactly what the answer needs.

A semantic node reaches them through its loops and its edges, which is Boundaries.Vertices; a loop reaches them through the edges it names, in the order it names them and start before end; an edge is its two ends; a vertex is itself. An entity of no family reaches none.

func (*Graph) Derive

func (g *Graph) Derive(against Derivation) (Footprints, []Diagnostic)

Derive computes the derived geometry of every node of the model which covers area: the plane figure, its area, its perimeter, its centroid, its bounding box, and which regions it lies inside.

The cache is advisory in the strongest sense: deleting it changes what this returns by nothing at all, and changes only how long it takes. That holds because of two rules. The first is the key — a cached set is read back only under the digest of the tree it was derived from, so a changed tree misses. The second is that **only a clean derivation is cached**: a model which reported a diagnostic is stored nowhere and recomputed every run, so the diagnostics a run reports never depend on what a build output directory happens to hold.

A node which references no loop is not derived and is absent from the result. A circuit group and a warranty cover no area, and a footprint of zero for them would be an answer to a question nobody asked.

A node whose geometry could not be read — a ring which does not close, corners which are not in one plane, a tolerance the registry does not declare in the unit of the frame — is a diagnostic and no footprint, exactly as it is from Topology.RegionOf, which is where the figure comes from.

Membership is derived rather than read. Which regions a node lies inside is computed from where its corners are, by Region.Containment, between every pair of regions one operation could be run over. A pair which could not be — two frames, two tolerances, two planes — is not a membership question and is passed over silently, because a refusal is about an operation somebody asked for and nobody asked for this one.

Example

ExampleGraph_Derive computes the derived geometry of a whole model — what each thing covers, how big that is, where it is centred, how far it reaches and which regions it lies inside — and keeps the answer in a build output directory.

None of it is ever written back into an entity file. The cache is keyed by the digest of the source tree the geometry was derived from, so a model which changed anywhere is a different key and a miss; there is no invalidation step to get wrong, because the key is the invalidation.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/derived/model"

	build, err := os.MkdirTemp("", "dfcad-build-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(build) }()

	cache, err := dfcad.OpenCache(build)
	if err != nil {
		fmt.Println(err)
		return
	}

	graph, _ := dfcad.LoadGraph(root)

	against := dfcad.Derivation{
		Tolerance: "boundary-closure",
		Position:  "position",
		Cache:     cache,
	}

	prints, _ := graph.Derive(against)
	for print := range prints.All() {
		fmt.Println(print)
	}

	// The second run is the same answer, read rather than computed. Deleting the
	// whole of the build output directory would change what comes back by
	// nothing at all — only how long it took.
	again, _ := graph.Derive(against)

	fmt.Println(prints.Digest() == again.Digest(), cache.Stats().Hits, cache.Stats().Misses)

}
Output:
site:S-01: area 192.0 m², perimeter 72.0 m, centroid (10.0 5.0 0.0), 1 piece, 1 hole
site:S-02: area 8.0 m², perimeter 12.0 m, centroid (10.0 5.0 0.0), 1 piece
site:S-03: area 16.0 m², perimeter 16.0 m, centroid (4.0 4.0 0.0), 1 piece, within site:S-01
site:S-04: area 1.0 m², perimeter 4.0 m, centroid (3.5 3.5 0.0), 1 piece, within site:S-01, site:S-03
site:S-05: area 12.0 m², perimeter 14.0 m, centroid (2.0 1.5 0.0), 1 piece
true 1 1

func (*Graph) Descendants

func (g *Graph) Descendants(node *SemanticNode) iter.Seq[Related]

Descendants iterates everything contained beneath node, depth first.

func (*Graph) DescendantsTo

func (g *Graph) DescendantsTo(node *SemanticNode, depth int) iter.Seq[Related]

DescendantsTo iterates what is contained beneath node, level by level, to at most depth steps.

func (*Graph) Digest

func (g *Graph) Digest() (Digest, bool)

Digest returns the digest of the bytes this graph was built from, and whether it has one.

It is accumulated as the load reads the tree, not computed later by reading the tree again. That is the difference between a key which names the model in hand and one which names whatever is on disk by the time somebody asks: a file edited between the load and the question would leave the second describing bytes nothing was derived from, and a derivation stored under it is a stale hit waiting for the tree to be put back ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

It is a digest of content and not of provenance, so a graph interpreted from trees a write substituted — which is what Tx.Commit validates against — has the digest of that hypothetical tree, and it is the right one: were those bytes on disk, DigestOf would compute it.

A graph has no digest when any file the walk reached could not be read at all, because the same key would then name a different set of inputs on a machine which could read it. A graph assembled from trees which were never read from anywhere has none either.

func (*Graph) Edges

func (g *Graph) Edges(region *SemanticNode) iter.Seq[*Edge]

Edges iterates the edges region's boundary is assembled from.

func (*Graph) Enclosing

func (g *Graph) Enclosing(span Span) (Entity, bool)

Enclosing returns the entity whose declaring form encloses span — the node, vertex, edge or loop written around it — and whether the model holds one.

It is the step from where a diagnostic points to what that place is. A diagnostic carries a span because every diagnostic has to say where it is; what it is about is then a fact about the model rather than something each place which builds one has to remember to write down. A span inside a claim is inside the node the claim is written on, because a claim is written inside its subject's form.

A span is matched by its path and its lines and columns, and never by its byte offsets, so a span read back out of JSON — which carries no offsets — finds the same entity as the one the diagnostic was built with. A span enclosed by a form starts at or after the form's first byte and ends at or before one past its last; an empty span, which points at a place rather than covering one, has to be before the form's end.

Nothing is returned for a span in a registry file, since a registry declares vocabulary rather than things; for a span between forms or in a comment; and for a span in a file the model does not hold.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/boundary/adjacent")

	// A diagnostic says where it is. What is written there is a fact about the
	// model, so the step from one to the other is a lookup rather than a field
	// every diagnostic has to remember to carry. Line 111 is the edge list of
	// the corridor's outline.
	at := dfcad.Position{Path: "testdata/boundary/adjacent/model.dfc", Line: 111, Column: 10}
	if entity, ok := graph.Enclosing(at.Span()); ok {
		fmt.Println(entity.ID())
	}

	// A registry declares vocabulary rather than things, so a place in one is
	// in no entity's form.
	vocabulary := dfcad.Position{Path: "testdata/boundary/adjacent/registry.dfc", Line: 22, Column: 3}
	_, ok := graph.Enclosing(vocabulary.Span())
	fmt.Println(ok)

}
Output:
geom:L-02
false

func (*Graph) Entity

func (g *Graph) Entity(id ID) (Entity, bool)

Entity returns the thing id names, whichever family holds it, and whether the model holds one.

An id is unique across the whole model, so at most one thing answers to it. The semantic family is looked in first and the geometric family second, which decides nothing: an id both of them hold is a duplicate the load already reported, and the answer is the definition which came first in the files.

A claim is not reachable here, because a claim id is optional and a claim is not an Entity. Claims.Claim is the lookup for one.

func (*Graph) Frames

func (g *Graph) Frames() *Frames

Frames returns the frames the registry declares, joined to the claims which measure them.

func (*Graph) Invariants

func (g *Graph) Invariants(node *SemanticNode) []InvariantBinding

Invariants returns the invariants which bear on one instance, in the order its type declared them.

**Invariants are not inherited.** A node's invariants are the ones its own type declares and nothing else: none descends from the node which contains it, from a zone it is a member of, or from another type — the type registry declares no hierarchy for one type to inherit through (specification section 7.3). An invariant which should hold of the rooms inside a storey is declared on the room type, not on the storey's, and a rule which reached instances through containment would apply to a different set of nodes every time somebody moved one.

What is filtered is applicability, not inheritance. A type may permit more than one kind and more than one geometry form — including no geometry at all — and a check declares which of those it can examine. An invariant naming a check which could examine no instance of the type is refused when the registry loads; one which can examine some of them binds to those and not to the rest, so a check about an area is not run against the instance which has no shape.

Nothing is stored on the instance. The binding is computed from the type every time, which is what makes an invariant declared today apply to an instance written tomorrow without either being touched.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/invariant/valid")

	// An invariant is written once on the type and applies to every instance of
	// it, so what bears on one node is asked of the graph rather than read off
	// the node: nothing was copied onto it, and a room written after the rule
	// was declared carries it exactly as one written before.
	for node := range graph.Nodes().All() {
		for _, binding := range graph.Invariants(node) {
			fmt.Println(binding, "declared on", binding.Type)
		}
	}

	// The corridor's type declares no invariant, which is ordinary: nothing is
	// bound to it and nothing is printed about it. Nor does it inherit the
	// storey's, though it is written inside one.
	corridor, _ := graph.Node("site:S-201")
	fmt.Println("bound to the corridor:", len(graph.Invariants(corridor)))

}
Output:
site:S-103 required-claim (predicate width) declared on MeetingRoom
site:L-01 within-resolves declared on Level
site:Z-02 boundary-loops-close (tolerance boundary-closure) declared on OccupancyZone
site:S-101 required-claim (predicate width) declared on MeetingRoom
site:S-102 required-claim (predicate width) declared on MeetingRoom
bound to the corridor: 0

func (*Graph) Located

func (g *Graph) Located(entity Entity) (*SemanticNode, bool)

Located is the node whose own claimed position is what places entity, and whether there is one.

It is Graph.Corners for the family of shapes which have no corners. A node drawn as a point holds its location as a claim on itself, so a survey built only from the corners its loops reach would place nothing at all for it — and every figure downstream would then report a device which is in the model as one the model does not put anywhere. A caller resolving the position predicate over Graph.Corners resolves it over this as well and has surveyed exactly what the answer needs.

Only a semantic node is ever located. A vertex is placed by its own claim already and is reached as a corner; an edge and a loop are placed by the corners they run between.

func (*Graph) Loops

func (g *Graph) Loops(region *SemanticNode) iter.Seq[*Loop]

Loops iterates the loops region is bounded by, in the order it wrote them.

func (*Graph) Measure

func (g *Graph) Measure(entity Entity, survey Survey) (Measurement, []Diagnostic)

Measure measures whatever an id named, whichever family holds it: a semantic node from the loops which bound it, a loop from the ring its edges traverse, an edge from its two ends, a vertex from where it is.

It is the whole of the dimensional question in one call, and it is here rather than left to each caller because the alternative is that every consuming repository writes the same switch. A caller which dispatched for itself would have to know that a region is measured through its boundaries and a loop is not, that a node with no outline measures nothing rather than nothing being wrong, and which of the four calls takes which argument — and a second implementation of that is a second set of answers the day one of them is missed.

The survey is the caller's, because which predicate carries a position and which tolerance corners are judged coincident against are the consuming repository's vocabulary and never the engine's ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)). Graph.Corners is what says which corners have to be in it.

Nothing is written back. Every figure is recomputed from the claims each time it is asked for, which is what makes it unable to disagree with the geometry it describes ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

An entity of no family — a nil, or a type from outside this package — measures nothing and reports nothing, because there is no question there to refuse.

Example

ExampleGraph_Measure asks how big something is without first working out which family the id names.

It is the same measurement Topology.MeasureRegion gives above, reached through the one call a consumer actually wants: a room, its outline, one of its walls and one of its corners are all measurable, and which of the four measurements applies is a property of the model rather than of the question. Graph.Corners is the other half — the corners a survey has to carry for the answer to rest on all of them.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/measure/courtyard")

	// Which predicate carries a position is vocabulary this repository owns, so
	// the positions are resolved here and handed in. Corners says which vertices
	// the answer needs, so nothing has to guess at the ones it rests on.
	plate, _ := graph.Entity("site:S-01")

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: graph.Registry()}
	for vertex := range graph.Corners(plate) {
		resolution, _ := graph.Claims().Resolve(vertex.ID(), "position", graph.Registry())
		survey.Place(vertex.ID(), resolution)
	}

	measurement, _ := graph.Measure(plate, survey)
	fmt.Println(measurement)

	// The same call answers for a wall and for a corner. An edge encloses
	// nothing and a vertex has no extent, and neither comes back as a zero.
	wall, _ := graph.Entity("geom:E-01")
	corner, _ := graph.Entity("geom:V-01")

	for _, subject := range []dfcad.Entity{wall, corner} {
		measured, _ := graph.Measure(subject, survey)
		fmt.Println(measured)
	}

}
Output:
site:S-01: area 84.0 m², length 56.0 m, centroid (5.0 5.0 0.0), bounds (0.0 0.0 0.0) to (10.0 10.0 0.0)
geom:E-01: length 10.0 m, centroid (5.0 0.0 0.0), bounds (0.0 0.0 0.0) to (10.0 0.0 0.0)
geom:V-01: centroid (0.0 0.0 0.0), bounds (0.0 0.0 0.0) to (0.0 0.0 0.0)

func (*Graph) Members

func (g *Graph) Members(zone *SemanticNode) iter.Seq[Related]

Members iterates the nodes which declared membership of zone.

func (*Graph) MembersTo

func (g *Graph) MembersTo(zone *SemanticNode, depth int) iter.Seq[Related]

MembersTo iterates the nodes which are members of zone and the members of those which are themselves zones, to at most depth steps.

func (*Graph) Nearest

func (g *Graph) Nearest(id ID) (ID, bool)

Nearest returns the id closest to the one asked for which the model does hold, and whether one is close enough to be worth suggesting.

It is what turns "nothing answers to site:S-1O1" into a sentence somebody can act on. Ids are written by hand and by agents, and most of the ones which reach nothing are the id which was meant with a character wrong; a lookup which reports only that it found nothing leaves whoever wrote it reading the files to find out which character.

Close is what it is for a misspelled tag: the same distance and the same tolerance, which is one edit for something short and two for anything longer. The measure counts a transposition as one mistake rather than two, because swapping two characters is what typing produces.

Only entities are considered, which is what Graph.Entity answers for. A claim id is not among them, for the reason it is not an Entity: a claim id is optional, and the model holds only the claims which wrote one.

Candidates are considered in lexical order, so two ids equally close to what was asked for resolve to the same suggestion on every run and the answer is a property of the model rather than of the order the walk read it in.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/graph/valid")

	// An id which reaches nothing is usually the id which was meant with a
	// character wrong, so the answer to a failed lookup is what to try instead
	// rather than only that it failed.
	if _, ok := graph.Entity("site:S-1O1"); !ok {
		if nearest, close := graph.Nearest("site:S-1O1"); close {
			fmt.Println("did you mean", nearest)
		}
	}

	// A misspelling of a vertex is answered by the vertex: an id is unique
	// across the whole model, so the suggestion is not a question of family
	// either.
	fmt.Println(graph.Nearest("geom:V-O1"))

	// An id nothing in the model resembles gets no suggestion. One nobody meant
	// is worse than none: it sends the reader to change a line which was never
	// the problem.
	fmt.Println(graph.Nearest("other:nothing-like-it"))

}
Output:
did you mean site:S-101
geom:V-01 true
 false

func (*Graph) Node

func (g *Graph) Node(id ID) (*SemanticNode, bool)

Node returns the semantic node id names, and whether the model holds one.

It is Graph.Entity narrowed to the family most questions are about, so that a caller which wants a node does not type-assert one out of an interface to find out it had a vertex.

func (*Graph) Nodes

func (g *Graph) Nodes() *Nodes

Nodes returns the semantic family.

func (*Graph) ObservationFiles

func (g *Graph) ObservationFiles() []string

ObservationFiles returns the paths of every observation file the model links to, in lexical order and with a file linked to twice named once.

It is what a command reporting on a model as a whole reads — how much field work is behind this model, and which files hold it — and it answers that without opening one of them.

func (*Graph) Observations

func (g *Graph) Observations(entity Entity) (*ObservationLog, []Diagnostic)

Observations returns the records of the observation files entity links to, with whatever is wrong with them.

**The files are read here and nowhere earlier.** Loading a model verifies that each linked file exists and stops ([resolveObservationLinks]); this is what opens one, and it happens because a caller asked a question the records are the answer to. An entity linking to nothing yields an empty log and no diagnostics, which is the ordinary case and is not a failure.

Reading is done once per set of links for the life of the graph, so a command which asks about one corner four times reads the file behind it once. Nothing is cached beyond the graph: a second invocation reads the files again, because what is on disk may have changed and a cache which outlived the run would be answering about a model which is no longer there.

The diagnostics are the observation format's own — a malformed line, a duplicate record identity, a retirement naming a record which is not there, a frame the registry does not declare — reported against the file they were found in. They are not part of what a load reports, and deliberately so: a model whose survey log has a malformed line still loads, and every command which does not read the records is entitled to run.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The model is loaded whole, and not one observation file is opened doing
	// it: what a load checks is that each linked file is there. That is the
	// whole point of keeping the records outside the entity files — an
	// afternoon with a rover is thousands of shots, and retrieving one corner
	// must not cost a season of field work.
	graph, diags := dfcad.LoadGraph("testdata/graph/observed")
	fmt.Println(len(diags), "diagnostics, and the files not yet read")

	corner, _ := graph.Entity("geom:V-01")

	// The links are part of the model, so saying where the evidence is costs
	// nothing.
	for _, link := range corner.ObservedIn() {
		fmt.Println("observed in", link.Path)
	}

	// Asking for the records is what opens the files. They are read once each
	// for the life of the graph, and the several files a thing links to are one
	// log: "earlier" is a question about the whole of what was read.
	log, problems := graph.Observations(corner)
	fmt.Println(log.Len(), "records of both forms,", len(problems), "problems")

	for observation := range log.Current() {
		fmt.Printf("%s %s %.3f\n", observation.ID, observation.Fix, observation.HorizontalPrecision)
	}

}
Output:
0 diagnostics, and the files not yet read
observed in observations/2026-05-06-site-control.obs
observed in observations/2026-05-07-interior.obs
6 records of both forms, 0 problems
shot:2026-05-06-0001 fix:rtk-fixed 0.012
shot:2026-05-06-0002 fix:rtk-fixed 0.011
shot:2026-05-07-0001 fix:observed 0.004
shot:2026-05-07-0002 fix:observed 0.004

func (*Graph) ObservationsWithin

func (g *Graph) ObservationsWithin(subject ID, against Derivation) (Members, []Diagnostic)

ObservationsWithin returns the observations of the model which fall inside the area a semantic node covers.

**Nothing here is stored and nothing here is read from the model.** Which shots are in a region is computed from their coordinates and the region's boundary every time it is asked, so carving a new region out of the back garden gives it the shots inside it with no edit to an observation file anywhere — and moving that boundary again moves the answer with it ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

The figure comes from Graph.Derive, so a membership query over a model whose derived geometry is already cached pays for the point tests and not for reading the boundary again. against is that derivation: the named tolerance and the named position predicate, and the cache to look in.

The rule at the boundary

A shot is inside when it lies inside the figure by further than it is known to, and ambiguous when it is nearer the boundary than that. What it is known to is three things added:

  • the tolerance named by against, which is how close two corners are one corner and so how well the boundary itself is placed ([0012](docs/decisions/0012-tolerances-are-registry-data.md));
  • the shot's own horizontal precision, at one standard deviation ([0006](docs/decisions/0006-accuracy-is-one-sigma.md));
  • the combined standard uncertainty of the transform, where the shot was carried in from another frame.

The tolerance is added rather than combined in quadrature with the other two because it is not an error: it is a distance the project has stated it does not distinguish from zero, and a stated indifference does not cancel against a measurement. The two statistical terms are combined with each other in quadrature, being independent one-sigma figures.

A shot which is neither inside nor ambiguous is outside, and is not a result.

Frames

A record written in another frame is carried into the subject's frame before it is tested, through the chain of measured transforms between them, and the accuracy of that chain is accumulated into Membership.Budget and into the band above. A frame with no chain to the subject's is reported once, naming the frame and how many records were written in it, rather than once per record or not at all.

A transform whose accuracy nothing states bounds nothing. A shot carried across one is never confidently inside anything: it comes back reported rather than assigned, with Membership.Doubt saying that no band could be arrived at. Treating it as exact instead is what would make a cross-frame membership look better than the survey behind it.

Such a shot still has to be filtered on something, or a coordinate on the far side of the county would be reported as one this region cannot place. What it is filtered on is the tolerance and the shot's own precision — the two terms which *were* stated — so it is reported where it lands near the region and is no result where it plainly does not.

What is judged

Every record of every observation file the model links to, minus those a retirement names: a retired shot is not evidence and is not a member of anywhere. **This reads those files**, which is the one thing Graph.Observations exists to defer; a command which never asks this question never opens one.

Results are ordered by record identity, then by where the record was written, which is deterministic and independent of the order the model was walked in.

Example

ExampleGraph_ObservationsWithin shows what derived membership buys: a region drawn today holding shots taken months before it existed, with nothing appended to an observation file to say so.

The two models below are one survey drawn twice. Every observation file is byte for byte the same in both, and the bed links none of them at all — what differs is where a line is drawn, and the answer moves with it.

package main

import (
	"fmt"
	"math"

	"github.com/z5labs/dfcad"
)

func main() {
	against := dfcad.Derivation{Tolerance: "boundary-closure", Position: "position"}

	show := func(graph *dfcad.Graph, subject dfcad.ID) {
		members, _ := graph.ObservationsWithin(subject, against)

		for _, member := range members.Inside() {
			// A shot in a file the region cites is a shot *of* it, which is
			// stored. A shot merely in the place is written down nowhere.
			relation := "in"
			if member.Linked() {
				relation = "of"
			}

			fmt.Printf("%s holds %s, a shot %s it, %.3f m inside\n",
				subject, member.Observation().ID, relation, member.Clearance())
		}

		// A shot nearer the boundary than the survey can place it is reported
		// rather than assigned to a side. The band is the registry tolerance,
		// the shot's own precision and whatever a change of frame cost.
		for _, member := range members.Ambiguous() {
			doubt, _ := member.Doubt()

			fmt.Printf("%s cannot place %s: %.3f m from the boundary, known to %.3f m\n",
				subject, member.Observation().ID, math.Abs(member.Clearance()), doubt)
		}
	}

	garden, _ := dfcad.LoadGraph("testdata/membership/yard")
	show(garden, "site:S-yard")

	fmt.Println("--- a raised bed is carved out of the north-east corner ---")

	carved, _ := dfcad.LoadGraph("testdata/membership/carved")
	show(carved, "site:S-yard")
	show(carved, "site:S-bed")

}
Output:
site:S-yard holds shot:0001, a shot of it, 3.000 m inside
site:S-yard holds shot:0002, a shot in it, 3.000 m inside
site:S-yard holds shot:0003, a shot in it, 2.000 m inside
site:S-yard holds shot:0004, a shot in it, 3.000 m inside
site:S-yard holds shot:0006, a shot in it, 3.000 m inside
site:S-yard holds shot:0009, a shot in it, 2.000 m inside
site:S-yard cannot place shot:0007: 0.100 m from the boundary, known to 0.245 m
--- a raised bed is carved out of the north-east corner ---
site:S-yard holds shot:0001, a shot of it, 3.000 m inside
site:S-yard holds shot:0003, a shot in it, 2.000 m inside
site:S-yard holds shot:0006, a shot in it, 1.000 m inside
site:S-yard cannot place shot:0004: 0.000 m from the boundary, known to 0.017 m
site:S-yard cannot place shot:0007: 0.100 m from the boundary, known to 0.245 m
site:S-bed holds shot:0002, a shot in it, 3.000 m inside
site:S-bed holds shot:0009, a shot in it, 2.000 m inside
site:S-bed cannot place shot:0004: 0.000 m from the boundary, known to 0.017 m

func (*Graph) OfKind

func (g *Graph) OfKind(kind Kind) iter.Seq[*SemanticNode]

OfKind iterates the semantic nodes of one kind, in the order the walk reached them.

A kind nothing was written under yields nothing, which is ordinary: a model with no zone in it is a model, not a model with something missing.

func (*Graph) OfType

func (g *Graph) OfType(name string) iter.Seq[*SemanticNode]

OfType iterates the semantic nodes which declare one type, in the order the walk reached them.

The name is the one the registry declares. A type nothing was written under yields nothing, and so does a type nothing declares: a node naming an undeclared type is a diagnostic and is still a node of the type it named, so it is yielded here — the graph reports what was written rather than deciding it was not.

func (*Graph) Owners

func (g *Graph) Owners(entity Entity) iter.Seq[*SemanticNode]

Owners iterates the semantic nodes entity belongs to, which is what a caller acting on a diagnostic about it usually acts on: the room missing from the sheet rather than the ring it could not draw.

  • A node belongs to itself.
  • A loop belongs to every node it bounds (Graph.Bounded).
  • An edge belongs to every node whose boundary it is part of (Graph.Regions), which is both rooms either side of a shared wall.
  • A vertex belongs to every node whose boundary's vertices include it — the reverse of Graph.Vertices, indexed when the families are joined.

The loop and the edge read the same index `traverse bounds` does, so what a diagnostic names and what that query answers cannot disagree. Each list is in the order the load read the nodes; a thing which bounds nothing belongs to nothing, and yields nothing.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/boundary/adjacent")

	// What a caller acts on is usually the room rather than the shape: the
	// partition between room A and the corridor belongs to both of them, and
	// a corner belongs to every room it is a corner of.
	for _, id := range []dfcad.ID{"geom:E-02", "geom:L-03", "geom:V-06", "site:S-A"} {
		entity, _ := graph.Entity(id)

		var owners []string
		for node := range graph.Owners(entity) {
			owners = append(owners, string(node.ID()))
		}
		fmt.Println(id, "belongs to", strings.Join(owners, " and "))
	}

}
Output:
geom:E-02 belongs to site:S-A and site:S-B
geom:L-03 belongs to site:S-C
geom:V-06 belongs to site:S-B and site:S-C
site:S-A belongs to site:S-A

func (*Graph) PlanOf

func (g *Graph) PlanOf(node *SemanticNode, survey Survey, annotations Annotations) (Plan, []Diagnostic)

PlanOf reads everything a spatial node contains as rings, with the claims written on those rings and on the nodes they bound.

It is the answer a floor plan is drawn from: the outlines the model already holds, and the statements already written on the edges bounding them, in one answer rather than in one call per room and one more per wall. Nothing is computed which is not already implied by the model, and nothing is written anywhere.

Which nodes are drawn is every descendant of the subject which references at least one loop the run could read, however deep — a room inside a storey and an alcove inside that room are both places somebody draws. The subject itself is not drawn; the question is what is in it.

A descendant whose geometry form is `point` is drawn too, from the position claimed of the node itself: its outline covers nothing and carries a Region.Location, which is where a sheet places a symbol. A panel, a receptacle, a condenser and a survey monument are each that shape — a thing whose only interesting geometry is where it is — and a plan which reported them as having no boundary would leave every device on a floor off the sheet while the model held all of them.

**Nothing the subject contains is dropped.** Every descendant which was not drawn comes back in Plan.Undrawn, named, with an UndrawnReason saying which of the ways it was undrawable and with the claims written on it. A circuit group has no edges and is ordinary; a room whose ring does not close is a defect; both are things somebody put inside this storey, and a query which answered by omitting them would be reporting a sheet as complete which is missing a door. That failure has no downstream symptom at all — the sheet renders, looks right, and the doorway is simply not on it — which is why the engine says so here rather than leaving it to be noticed.

Every ring is read with Topology.RegionOf, so everything which refuses a region refuses one here — a ring which does not close, one which crosses itself, corners which are not in one plane, a tolerance the registry does not declare in the frame's unit, a curve no chord tolerance was named for.

**An undrawable node degrades per node and never refuses the storey**, whether it is undrawable for a reason an author can fix or for no reason at all. Its diagnostics are collected, it comes back under Plan.Undrawn rather than as an outline covering nothing, and every other node is still drawn. That is one rule for every case rather than one per shape of defect: a ring which crosses itself and a ring which does not close are two spellings of the same mistake, and behaving differently between them would make which of the two a model happens to hold decide how much of the sheet comes back. Whether the *run* succeeded is the separate question the diagnostics answer — an unreadable boundary is an error and a caller which treats one as a refusal still refuses — and separating the two is what lets a caller draw the seven rooms it has while it fixes the eighth.

The claims reported are the live ones under each predicate Annotations names, on the node itself and on each edge of its boundary. Nothing is resolved: two live claims disagreeing about one wall both come back, marked with the same anchor, and which one a sheet prints is the caller's decision. A retracted claim is never reported — resolution never considers one, and a sheet printing a value somebody has withdrawn is the failure this refuses.

It is Graph.PlanOfSelected with no selection: every descendant is asked about.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/plan/storey")

	survey := dfcad.Survey{Tolerance: "coincident", Registry: graph.Registry()}
	for vertex := range graph.Topology().Vertices() {
		resolution, _ := graph.Claims().Resolve(vertex.ID(), "position", graph.Registry())
		survey.Place(vertex.ID(), resolution)
	}

	// A node whose declared geometry is a point has no corners: it is placed by
	// a claim on itself, under the same predicate. Graph.Located is what says
	// which nodes those are, so that a survey covers what the answer needs.
	for node := range graph.Nodes().All() {
		located, ok := graph.Located(node)
		if !ok {
			continue
		}

		resolution, _ := graph.Claims().Resolve(located.ID(), "position", graph.Registry())
		survey.Place(located.ID(), resolution)
	}

	level, _ := graph.Node("site:L-01")

	// Which measurements belong on the sheet is stated here and nowhere else.
	// The engine has no opinion about whether a wall length is worth drawing.
	plan, _ := graph.PlanOf(level, survey, dfcad.Annotations{
		Predicates: []string{"area", "caption", "wall-length"},
	})

	fmt.Println(plan)

	for _, outline := range plan.Outlines() {
		// A node drawn as a point covers nothing and is somewhere. What comes
		// back for it is the coordinate a sheet places a symbol at, rather than
		// an area of nought which reads like a room whose ring collapsed.
		if at, located := outline.Region().Location(); located {
			fmt.Printf("%s %s is at (%.1f %.1f %.1f) %s\n",
				outline.Node().Kind(), outline.Subject(), at[0], at[1], at[2], plan.Unit())
			continue
		}

		fmt.Printf("%s %s covers %.1f %s²\n",
			outline.Node().Kind(), outline.Subject(), outline.Region().Area(), plan.Unit())
	}

	// Nothing the storey holds is dropped. What could not be drawn comes back
	// named, with why and with the claims written on it, so that a sheet drawn
	// from this answer can say what is missing from it rather than render
	// looking complete. The lighting circuit has no edges, which is ordinary —
	// and the caption somebody wrote for it is still a caption somebody wrote.
	for _, undrawn := range plan.Undrawn() {
		fmt.Printf("%s %s was not drawn: it %s, and carries %d claim\n",
			undrawn.Node().Kind(), undrawn.Subject(),
			undrawn.Reason().Description(), len(undrawn.Annotations()))
	}

	// A node drawn as a line covers nothing and is still drawn: its boundary is
	// an open run of edges rather than a ring, and the runs of it carry the same
	// attribution a room's do.
	var room dfcad.Outline
	for _, outline := range plan.Outlines() {
		if outline.Subject() == "site:R-01" {
			room = outline
		}
	}

	// Every claim says what it is written on. An edge anchor names its two
	// corners in the order the edge was authored, so a dimension knows which
	// pair of corners it runs between without anybody matching coordinates.
	for _, annotation := range room.Annotations() {
		value := annotation.Claim().Value()

		// A caption is a text claim and a dimension a scalar one. Both are
		// claims: what a sheet prints against a room was stated by somebody,
		// from a source, on a date, and is not a formatting of a number.
		written := fmt.Sprintf("%s value", value.Shape())
		if text, ok := value.Text(); ok {
			written = fmt.Sprintf("%q", text)
		}
		if scalar, ok := value.Scalar(); ok {
			written = fmt.Sprintf("%.2f %s", scalar, value.Unit())
		}

		fmt.Printf("  %s: %s — %s\n", annotation.Predicate(), written, annotation.Anchor())
	}

	// The budget is over the position claims behind the rings. Each claim above
	// carries its own accuracy, because each is a statement about a different
	// quantity.
	combined, _ := plan.Budget().Combined()
	fmt.Printf("the rings are known to ±%.3f %s\n", combined.Standard(), combined.Unit)

}
Output:
site:L-01: 6 outlines, 15 claims, 1 not drawn
Space site:A-01 covers 1.0 m²
Element site:D-01 covers 0.0 m²
Element site:H-01 covers 0.0 m²
Element site:P-01 is at (2.5 1.5 1.2) m
Space site:R-01 covers 12.0 m²
Space site:R-02 covers 12.0 m²
Element site:C-01 was not drawn: it references no loop, and carries 1 claim
  area: 12.00 m2 — node site:R-01, ring geom:L-01
  caption: "Meeting Room A" — node site:R-01, ring geom:L-01
  caption: "MR-A" — node site:R-01, ring geom:L-01
  wall-length: 4.00 m — edge geom:E-01, geom:V-01 to geom:V-02
  wall-length: 3.00 m — edge geom:E-02, geom:V-02 to geom:V-03
  wall-length: 3.02 m — edge geom:E-02, geom:V-02 to geom:V-03
  wall-length: 4.00 m — edge geom:E-03, geom:V-03 to geom:V-04
the rings are known to ±0.024 m

func (*Graph) PlanOfSelected

func (g *Graph) PlanOfSelected(
	node *SemanticNode,
	survey Survey,
	annotations Annotations,
	selection Selection,
) (Plan, []Diagnostic)

PlanOfSelected is Graph.PlanOf asked about only the descendants selection selects.

Every rule of Graph.PlanOf holds over what is selected. Plan.Outlines and Plan.Undrawn account between them for every selected descendant, and a descendant the selection does not select is in neither: it was not asked about, which is a different thing from being left off a sheet it was asked for. A selected node the plan cannot draw is still named under Plan.Undrawn, with its reason and its claims, exactly as it would be unselected.

Everything a plan computes from the rings it drew is over the selected nodes alone: the chord tolerance and the deviation, and Plan.Budget. A sheet of the meeting rooms carries the accuracy of the meeting rooms' corners and not of every corner in the storey. What a selected node's outline says — its region and its annotations — is exactly what it says in the unselected plan: the selection decides which rooms come back and never how a room is drawn.

A selection which selects nothing is an empty plan, not a refusal.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/plan/storey")

	survey := dfcad.Survey{Tolerance: "coincident", Registry: graph.Registry()}
	for vertex := range graph.Topology().Vertices() {
		resolution, _ := graph.Claims().Resolve(vertex.ID(), "position", graph.Registry())
		survey.Place(vertex.ID(), resolution)
	}

	building, _ := graph.Node("site:B-01")

	// A sheet of the meeting rooms asks for the meeting rooms. The storey
	// between the building and them is not one, and they are drawn anyway: a
	// selection narrows what comes back and never what is walked.
	plan, _ := graph.PlanOfSelected(building, survey, dfcad.Annotations{Predicates: []string{"area"}},
		dfcad.Selection{Types: []string{"MeetingRoom"}})

	for _, outline := range plan.Outlines() {
		fmt.Printf("%s %s covers %.1f %s²\n",
			outline.Node().Type(), outline.Subject(), outline.Region().Area(), plan.Unit())
	}

	// Nothing the selection did not ask about is named as undrawn: the circuit
	// group in the storey is not a meeting room, and it was not left off this
	// sheet so much as never on it.
	fmt.Println(len(plan.Undrawn()), "undrawn")

}
Output:
MeetingRoom site:R-01 covers 12.0 m²
MeetingRoom site:R-02 covers 12.0 m²
0 undrawn

func (*Graph) References

func (g *Graph) References(id ID) iter.Seq[Reference]

References iterates every reference the model makes to id, from entities other than the one it names.

A reference an entity makes to itself is not one: a node inside itself and a node which replaced itself are each a diagnostic of their own, and reporting them here as well would make a thing its own referrer and refuse a retirement on the strength of it.

The order is the order the walk reached the referring entities, family by family, so a listing built from it is the same on every run.

The scan is over every entity rather than over an index, because nothing else needs the reverse direction: it is asked once, by a change which is about to refuse itself, and an index maintained for it would have to stay true through every mutation of every transaction.

Example

ExampleGraph_References says what points at one thing, which is what a refusal to retire it reports.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/graph/valid")

	for reference := range graph.References("site:S-101") {
		fmt.Println(reference.From, reference.Relation)
	}

}
Output:
site:E-01 within

func (*Graph) Regions

func (g *Graph) Regions(edge *Edge) iter.Seq[*SemanticNode]

Regions iterates the nodes edge is part of the boundary of, which is what a shared wall looks like from the wall.

func (*Graph) Registry

func (g *Graph) Registry() *Registry

Registry returns the vocabulary the model declares.

func (*Graph) Root

func (g *Graph) Root() string

Root returns what the load was asked for, which is the directory or file the model was read from.

func (*Graph) Rules

func (g *Graph) Rules() Rules

Rules returns every rule the model holds: each type's invariants bound to each of its instances, and each assertion bound to the thing it was written on.

The order is every invariant, in the order Graph.AllInvariants binds them, and then every assertion, in the order Graph.AllAssertions binds them. It is deterministic for the reason the load's is: a listing of what would run, and a report of what did, have to diff against the last run's. The two families are kept whole rather than interleaved per thing because a rule of a type and a rule about this patio are read differently — the first is changed in the registry, for every instance at once — and a listing which alternated between them would have to be sorted before it could be read.

A rule whose check declares itself and implements nothing is here like any other. It binds, it lists, and running it reports nothing; see Rule.Runs.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/rules/valid")

	// A gate does not ask the two questions separately. Every rule the model
	// states comes back as one list, in the order it will run in: every
	// invariant, node by node in the order the model was read, and then every
	// assertion, thing by thing.
	for _, rule := range graph.Rules() {
		written := "assertion, written on it"
		if rule.Invariant() {
			written = "invariant of " + rule.Type
		}
		fmt.Printf("%s — %s\n", rule, written)
	}

}
Output:
site:Z-01 within-resolves — invariant of OccupancyZone
site:S-101 required-claim (predicate width) — invariant of MeetingRoom
site:S-102 required-claim (predicate width) — invariant of MeetingRoom
site:Z-01 required-claim (predicate width) — assertion, written on it
site:S-101 boundary-loops-close (tolerance boundary-closure) — assertion, written on it
geom:V-01 required-claim (predicate position) — assertion, written on it
geom:E-01 required-claim (predicate position) — assertion, written on it

func (*Graph) Summary

func (g *Graph) Summary() Summary

Summary returns what the load counted.

func (*Graph) SurfaceWithin

func (g *Graph) SurfaceWithin(subject ID, against SurfaceDerivation) (Surface, []Diagnostic)

SurfaceWithin derives the ground surface of the observations inside one region.

**It writes nothing into the model.** The surface is a build output: it is computed from the shots and the boundary every time it is asked, it is kept only in the derived cache under BuildDir, and deleting that cache changes what this returns by nothing at all ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

Which shots it rests on is Graph.ObservationsWithin and the same boundary rule: every current record of the model whose coordinate falls inside the region, carried into the region's frame where it was written in another one. Shots the boundary rule could not confidently place are used only where against asks for them, and a shot which was retired is not evidence and is used never.

What it refuses

Fewer than three distinct points in plan is a diagnostic saying how many were found and how many are needed, and no surface. So are points which all fall on one line: they bound no area, and a surface over them would have to invent which way the ground fell away from that line.

Determinism

The same points and the same parameters give the same surface, byte for byte, on every run and on every machine. The points are ordered by record identity before anything is built from them, coincident shots are resolved by a rule which does not depend on the order they were read in, and the facets and the hull are sorted canonically on the way out. A surface which came back with its triangles in a different order each run would make every artefact derived from it differ from itself.

Example

ExampleGraph_SurfaceWithin shows the ground answered for from the shots somebody took, rather than from a surface somebody drew.

Nothing below is stored. The surface is derived from the observations inside the region every time it is asked, kept only under the build output directory, and written into no file a walk would read — so a shot taken tomorrow changes what the ground does here, and no file has to be edited to say so.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/surface/terrace")

	surface, _ := graph.SurfaceWithin("site:S-terrace", dfcad.SurfaceDerivation{
		Against: dfcad.Derivation{Tolerance: "boundary-closure", Position: "position"},
	})

	// How it was derived travels with it. Two interpolations of one set of
	// points are two different answers, and a grid of levels with no method on
	// it is one nobody can check.
	fmt.Println(surface)
	for _, parameter := range surface.Parameters() {
		fmt.Printf("  %s\n", parameter)
	}

	// The surface reaches as far as the shots and no further. A point beyond
	// the hull of them is reported as outside, never extrapolated: there is no
	// measurement out there, and a level continued past the last shot reads
	// exactly like a surveyed one.
	for _, at := range []dfcad.Point{{4, 4, 0}, {14, 8, 0}, {19, 11, 0}} {
		elevation, inside := surface.Elevation(at)
		if !inside {
			fmt.Printf("(%.0f, %.0f) is outside the surveyed ground\n", at[0], at[1])
			continue
		}

		fmt.Printf("(%.0f, %.0f) is at %.3f m ± %.3f m, from %v\n",
			at[0], at[1], elevation.Value(), elevation.Uncertainty(), elevation.From())
	}

	// And a surface can be traced back to the afternoon behind it.
	fmt.Printf("derived from %v\n", surface.Observations())

}
Output:
site:S-terrace: tin from 7 points, 8 facets, hull of 4 points
  method=tin
  tolerance=boundary-closure
  position=position
  minimum-points=3
  ambiguous=excluded
  roughness=unstated
  systematic=none
(4, 4) is at 100.120 m ± 0.014 m, from [shot:0001 shot:0005 shot:0006]
(14, 8) is at 100.540 m ± 0.015 m, from [shot:0003 shot:0005 shot:0007]
(19, 11) is outside the surveyed ground
derived from [shot:0001 shot:0002 shot:0003 shot:0004 shot:0005 shot:0006 shot:0007 shot:0008]

func (*Graph) Topology

func (g *Graph) Topology() *Topology

Topology returns the geometric family.

func (*Graph) UnreadArcs

func (g *Graph) UnreadArcs(survey Survey, subjects ...Entity) ([]UnreadArc, []Diagnostic)

UnreadArcs reports the edges bounding the subjects which state a curve this survey did not read, and a warning for each.

It is what stops a chorded boundary being a silent one. Every figure computed from a survey which does not bend an edge is a figure about the chord, and the difference is not small: a four metre wall bowed into a semicircular bay encloses half as much again as the straight line across it, and a forty foot frontage arc through a right angle is hundreds of square feet. An answer which discarded a claim the model carries and said nothing is worse than one which refused, because nobody goes looking for it.

An edge the survey bends is not reported. Naming the vocabulary is the fix, so a run which named it has nothing to be told; a run which named it and could not resolve one of the two claims on some edge is told about that edge, which is exactly the case an answer would otherwise be quietly straight in.

The warning is a warning and never an error. Reading a curve as a chord is a decision worth reporting and there are answers which want it — a rough take-off, a model whose author has not written the arcs yet — and refusing them would trade one wrong default for another. What is not on offer is not saying.

The order is by edge id, so two runs over one model produce the same list and a diff between them means something. A subject reached twice contributes its edges once.

func (*Graph) Vertices

func (g *Graph) Vertices(region *SemanticNode) iter.Seq[*Vertex]

Vertices iterates the vertices region's boundary is assembled from.

func (*Graph) VerticesNear

func (g *Graph) VerticesNear(spec NearSpec) (Nearness, error)

VerticesNear lists the vertices within a tolerance of a point, and writes nothing.

It is exactly the rule Tx.Scaffold applies to decide which vertex a corner lands on, and it is one function rather than two copies of it: a vertex is a candidate when its position resolves under the predicate, in the frame's unit, and it is near when that position lies within the tolerance's value of the point. The vertex a scaffold snaps a corner to is always the nearest of the ones this lists at that corner, so a lookup made before a scaffold says what the scaffold will do.

A vertex whose position does not resolve is not listed, because nobody can say where it is. Nothing within the tolerance is an empty list rather than an error: a point where nothing stands is an ordinary answer.

func (*Graph) Within

func (g *Graph) Within(node *SemanticNode) (Related, bool)

Within returns the node which strictly contains node, labelled with the relation which produced it, and whether it has one.

func (*Graph) Zones

func (g *Graph) Zones(node *SemanticNode) iter.Seq[Related]

Zones iterates the zones node declared membership of.

func (*Graph) ZonesTo

func (g *Graph) ZonesTo(node *SemanticNode, depth int) iter.Seq[Related]

ZonesTo iterates the zones node is a member of and the zones those are members of, to at most depth steps.

type Histories

type Histories []History

Histories is the histories of both revisions, asked in turn.

A review reads its two revisions out of two directories, and a finding about something head no longer holds points into the second of them. One history per tree, asked in order, is what lets both be attributed to commits of the same range without either having to know that the other exists.

func (Histories) Introduced

func (h Histories) Introduced(path string) (Revision, bool)

Introduced implements History, answering with the first history which recognises the path.

type History

type History interface {
	// Introduced returns the commit which most recently changed the file at
	// path, and whether the history holds one. The path is a span's, exactly as
	// the loader reached it.
	Introduced(path string) (Revision, bool)
}

History says which commit introduced the change to a file.

It is an interface so that the checks below depend on the idea of a history and not on git: a review of two directories somebody exported by hand is the same review with nothing to attribute, and it runs rather than being a case the checks have to know about.

type ID

type ID string

ID identifies one thing in a model for the life of that thing, per specification section 4.1.

An id is assigned once and never changes. Claims, assertions, observation links and every downstream artifact point at ids, so an id which moved would break all of them silently and none of them would say so ([0002](docs/decisions/0002-immutable-id-mutable-label.md)). A SemanticNode label is the other half of that arrangement: it is display text, it is free to change, and nothing resolves through it.

An ID is written `namespace:local`. The namespace says which authority minted the id and is declared in the registry ([0003](docs/decisions/0003-id-namespaces-are-a-closed-registry.md)); the local part is the authority's own name for the thing and is opaque here. The engine attaches no meaning to either beyond that. Nothing infers a Kind, a type, an accuracy or a rendering from an id prefix, which is what keeps `site:S-101` a name rather than a schema.

The underlying type is a string so that an ID is comparable, usable as a map key, and compared exactly the way specification section 4.1 requires: byte for byte, with no case folding, no Unicode normalisation and no trimming. Two ids are the same id when their bytes are the same.

A conversion is not a check. ParseID is what enforces the production, and the zero ID is the id of a thing whose id could not be read — which is a diagnostic naming what was written, not an id anything resolves.

func ParseID

func ParseID(s string) (ID, error)

ParseID reads s as an id, per specification section 4.1.

Both parts are non-empty and the colon is required, so `:x`, `survey:` and an unqualified `corner` are each a MalformedIDError rather than an id with a part missing. The namespace is ASCII and begins with a letter; the local part is written with the characters a symbol is written with, which is what makes every well-formed id a well-formed symbol and so writable in a file without quoting.

Whether the namespace is one the model declares is a question only a Registry answers, and ParseID does not ask it. The shape of an id is a property of the id; which namespaces exist is a property of the model.

A failure yields the zero ID. What was written is carried on the error, so a diagnostic can quote it without the caller having kept a second copy.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The split is on the first colon, so a local part may hold further ones
	// and the namespace never does.
	id, err := dfcad.ParseID("survey:2026:CP-3")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%s | %s\n", id.Namespace(), id.Local())

	// What an id which is not one broke is a field rather than wording inside a
	// message, so a caller can tell a forgotten namespace apart from a
	// misspelled one.
	_, err = dfcad.ParseID("corner")

	var malformed dfcad.MalformedIDError
	if errors.As(err, &malformed) {
		fmt.Printf("%s: %s\n", malformed.Written, malformed.Reason)
	}

}
Output:
survey | 2026:CP-3
corner: unqualified

func (ID) Local

func (id ID) Local() string

Local returns the part of the id after the first colon, which is the minting authority's own name for the thing and means nothing here.

Further colons belong to it: the split is on the first one only.

func (ID) Namespace

func (id ID) Namespace() string

Namespace returns the part of the id before the first colon, which is the authority which minted it.

It is empty for an id which is not one, which only the zero ID and a value converted rather than parsed can be.

func (ID) String

func (id ID) String() string

String returns the id as it was written.

type IDProblem

type IDProblem string

IDProblem says which rule of specification section 4.1 a malformed id broke.

It is a field rather than wording inside a message so that what to do about the id is something a caller and a test can act on. The string value is the phrase a diagnostic would use for it, which is what keeps the two spellings of one problem from drifting.

const (
	// IDUnqualified is an id written with no colon at all, which is a local part
	// with no authority behind it.
	IDUnqualified IDProblem = "unqualified"

	// IDEmptyNamespace is an id beginning with the colon.
	IDEmptyNamespace IDProblem = "empty namespace"

	// IDEmptyLocal is an id ending with the colon.
	IDEmptyLocal IDProblem = "empty local part"

	// IDMalformedNamespace is a namespace which is not ASCII, does not begin
	// with a letter, or holds something other than letters, digits, hyphens and
	// underscores.
	IDMalformedNamespace IDProblem = "malformed namespace"

	// IDMalformedLocal is a local part holding something a symbol may not hold,
	// which is an id no file could be written with.
	IDMalformedLocal IDProblem = "malformed local part"
)

type IncompleteClassificationError

type IncompleteClassificationError struct {
	// Type is the type the change was about.
	Type string

	// Missing names the halves which were blank, in the order they are written.
	Missing []string
}

IncompleteClassificationError reports a classification missing one of its two halves.

Both are refused here rather than at the load which follows, because the load would report a file the caller never wrote and never sees: a write is refused before any byte reaches disk ([0015](docs/decisions/0015-the-cli-is-the-primary-write-path.md)), and the mistake is in the call rather than in the model.

func (IncompleteClassificationError) Error

Error implements the [error] interface.

type InvalidAssertionError

type InvalidAssertionError struct {
	// Subject is the thing the assertion was to be written on.
	Subject ID

	// Check is the check it names.
	Check string

	// Errs is every reason it was refused, in the order the validation found
	// them.
	Errs []error
}

InvalidAssertionError is an assertion the check registry refuses, carrying every reason it does.

Each reason is one of UnregisteredCheckError, UnknownParameterError, RepeatedParameterError, MissingParameterError and ParameterValueError, and errors.As reaches each of them. They are every problem the validation found rather than the first, for the reason a load reports every problem it finds: an author fixing one assertion should not have to reissue it once per mistake.

func (InvalidAssertionError) Error

func (e InvalidAssertionError) Error() string

Error implements the [error] interface.

func (InvalidAssertionError) Unwrap

func (e InvalidAssertionError) Unwrap() []error

Unwrap returns every reason, so that errors.Is and errors.As reach each of them.

type Invariant

type Invariant struct {
	// Check is the check name written after the invariant tag.
	Check string

	// Parameters are the parameter forms written after it, unmodified.
	Parameters []*Node

	// Span is where the invariant was written.
	Span Span
}

Invariant is a check the type registry applies to every instance of a type, including instances added later.

The check name and the parameters are the check registry's vocabulary rather than this layer's, so what is recorded is what was written and where. The layer holding that registry is what decides whether the check exists and whether these are its parameters.

type InvariantBinding

type InvariantBinding struct {
	// Instance is the node the invariant applies to.
	Instance *SemanticNode

	// Type is the name of the type which declared it, which is the type the
	// instance names.
	Type string

	// Check is what the engine's closed check registry says the named check
	// constrains and takes.
	Check CheckDeclaration

	// Declared is the invariant as the registry wrote it. Its span is the
	// registry file and line a violation points back at.
	Declared Invariant

	// Arguments are the parameters it was written with.
	Arguments []Argument
	// contains filtered or unexported fields
}

InvariantBinding is one invariant of a type bound to one instance of that type.

It is what makes an invariant stated once apply to a hundred and fifty rooms: nothing is copied onto the instance and nothing is stored on it, so the binding is computed from the type every time it is asked for and an instance written after the invariant was declared carries it as fully as one written before (Graph.Invariants).

func (InvariantBinding) Runnable

func (b InvariantBinding) Runnable() bool

Runnable reports whether the check has an implementation to run.

A check which declares itself and implements nothing binds, lists and validates exactly as one which does, and running it reports nothing. The two are told apart here rather than by an empty result, because "this rule holds" and "nothing has been written to decide whether it holds" are different answers.

func (InvariantBinding) String

func (b InvariantBinding) String() string

String renders the binding as the instance it applies to and the invariant as it was written.

type Judge

type Judge interface {
	Runner

	// Judge examines one subject and returns the bands every comparison it made
	// was decided against, together with the failures it found — on a subject
	// which satisfies the check as much as on one which does not.
	//
	// A comparison the check declined to make yields no band. There is nothing
	// to disclose about an answer it did not give.
	Judge(subject CheckSubject) ([]Band, []Failure)
}

Judge is a Runner whose answer is decided against a figure it computes rather than against the tolerance it was declared with alone.

It is a third interface rather than a wider Runner because most checks decide against what they were given and have nothing to disclose. A loop either closes or does not; there is no second number behind that answer for a reader to be told about. Widening the band is the exception, and the exception is the thing which has to say so.

A check implements this by implementing Judge.Judge and defining Run as the failures half of it, so that the band a run reports and the band the answer was decided against are one computation. Two would be two numbers which could disagree, and the one thing this whole interface exists to prevent is an answer describing a test it did not run.

type Key

type Key struct {
	// Digest is the digest of the source tree the artefact was derived from.
	Digest Digest

	// Tolerance is the name of the registry tolerance coincidence was judged
	// against.
	Tolerance string

	// Position is the name of the predicate the corners were read from.
	Position string
}

Key identifies one derived artefact: what it was derived from, and the two named decisions it was derived under.

The digest pins the whole of the input the derivation read, and the tolerance and the position predicate pin the choices a caller made which are not in the tree. All three have to be in the key. A footprint judged against a tolerance of five millimetres is a different answer from one judged against fifty, and serving either for the other is the stale hit this whole mechanism exists to make unrepresentable.

func (Key) String

func (k Key) String() string

String writes the key as it reads: the digest, then the two names.

type Kind

type Kind string

Kind is one of the node kinds compiled into the engine.

The set is closed and is fixed by specification section 1 rather than by registry data. It is compiled in because a kind is a structural axis every consuming repository shares — a thing either contains other things or it does not — and not vocabulary about any one subject.

const (
	KindZone      Kind = "Zone"
	KindSite      Kind = "Site"
	KindBuilding  Kind = "Building"
	KindStorey    Kind = "Storey"
	KindSpace     Kind = "Space"
	KindElement   Kind = "Element"
	KindInterface Kind = "Interface"
)

The kinds, in the order specification section 1 lists them.

func Kinds

func Kinds() []Kind

Kinds returns the closed set of node kinds, in specification order.

func SpatialKinds

func SpatialKinds() []Kind

SpatialKinds returns the kinds which sit in the containment hierarchy, in specification order.

func (Kind) Spatial

func (k Kind) Spatial() bool

Spatial reports whether a node of this kind is somewhere rather than a grouping of things which are.

It is the question every walk which means "what is inside this" has to ask first. A zone is a set its members were written into and holds nothing by containment, so a walk which took one for a place would answer "nothing is in here" about a zone whose every member has an outline — which reads as an empty storey rather than as the wrong question.

type LockError

type LockError struct {
	// Path is the lock file, which is [LockName] in the model root.
	Path string

	// Err is what stopped it, and is [ErrLocked] where another transaction
	// holds the root.
	Err error
}

LockError reports a model root which could not be locked.

func (LockError) Error

func (e LockError) Error() string

Error implements the [error] interface.

func (LockError) Unwrap

func (e LockError) Unwrap() error

Unwrap returns the underlying failure.

type Log

type Log struct {
	// contains filtered or unexported fields
}

Log is which commit most recently changed each file over a range of history.

"The commit which introduced the change" is that one: the newest commit in the range which touched the file the change is in. It is the file rather than the form inside it, because a form has no identity git knows about — the same node moves down the file as the ones above it grow — and a commit named from a line number would name the wrong one the first time anything was inserted.

func (*Log) Len

func (l *Log) Len() int

Len is how many files the range touched.

func (*Log) Within

func (l *Log) Within(dir, prefix string) History

Within is the log as seen by a model loaded at dir, whose place in the repository is prefix.

The indirection is what lets one log attribute findings from both revisions. The merge base is read out of a directory somewhere else entirely, and the spans in it name that directory; prefix is what puts a path back where the repository holds it, so a file which was removed by the change is attributed to the commit which removed it rather than to nothing at all.

type Loop

type Loop struct {
	// contains filtered or unexported fields
}

Loop is an ordered ring of edges, per specification section 6.4.

A loop is what a semantic node references when it has an outline: the shape is shared rather than copied, so two spaces either side of a partition reference one edge and cannot drift apart ([0001](docs/decisions/0001-two-node-families.md)).

A Loop is read-only once loaded. The zero value is a loop with no id, no frame and no edges; every method below works on it.

func (*Loop) Assertions

func (l *Loop) Assertions() []Assertion

Assertions returns the assertions written on the loop, in the order they were written. SemanticNode.Assertions says what they are and what they are not.

func (*Loop) Edges

func (l *Loop) Edges() []ID

Edges returns the ids of the edges the loop is traversed through, in the order they were written.

The order is the data. It is the order the loop is traversed, it is preserved exactly as authored, and it is never sorted or made canonical — which is why the result is a slice and not a set. A repeated edge is held as many times as it was written, for the same reason: what the file says is what a diagnostic about it has to be able to quote back.

An id which was not one is not here, because there was no id to keep; that it was written is a diagnostic carrying what was there.

func (*Loop) Frame

func (l *Loop) Frame() ID

Frame returns the id of the frame the loop is expressed in.

func (*Loop) ID

func (l *Loop) ID() ID

ID returns the loop's id.

func (*Loop) Label

func (l *Loop) Label() string

Label returns the loop's display text, which is empty when none was written.

func (*Loop) ObservedIn

func (l *Loop) ObservedIn() []ObservationLink

ObservedIn returns the observation files the loop links to, in the order they were written. SemanticNode.ObservedIn says what a link is and what reading one costs.

func (*Loop) Span

func (l *Loop) Span() Span

Span returns where the loop form was written.

type LoopSpec

type LoopSpec struct {
	// ID is the id it will be written with.
	ID ID

	// Label is its display text, and is empty for a loop with none.
	Label string

	// Frame is the frame it is expressed in.
	Frame ID

	// Edges are the edges it is traversed through, in traversal order. The
	// order is the data and is never sorted.
	Edges []ID
}

LoopSpec is a loop which does not exist yet.

func (LoopSpec) Check

func (spec LoopSpec) Check(registry *Registry) error

Check reports the first axis of the spec which the registry does not permit.

func (LoopSpec) Destination

func (spec LoopSpec) Destination(registry *Registry, override string) (Destination, error)

Destination is the file the loop goes in.

type MalformedDateError

type MalformedDateError struct {
	// Written is what was there instead.
	Written string
}

MalformedDateError reports something written where a date belongs which is not one.

There is one spelling of a date in this format and it is the engine's rather than the caller's, so the parse and the refusal are here: a command taking a date on its command line and a file carrying one are held to the same spelling, and neither has a second copy of it to drift from.

func (MalformedDateError) Error

func (e MalformedDateError) Error() string

Error implements the [error] interface.

type MalformedEntityFormatError

type MalformedEntityFormatError struct {
	// Written is what was there instead.
	Written string
}

MalformedEntityFormatError reports something written where an entity format version belongs which is not one.

There is one spelling of a version and it is SPEC.md's, so the parse and the refusal are here rather than in each caller: a command taking one on its command line and a consumer asserting one from Go are held to the same spelling, and neither has a second copy of it to drift from.

func (MalformedEntityFormatError) Error

Error implements the [error] interface.

type MalformedIDError

type MalformedIDError struct {
	// Written is the text as it appeared.
	Written string

	// Reason is the rule of specification section 4.1 it broke.
	Reason IDProblem
}

MalformedIDError reports text written where an id belongs which is not one.

The text is carried rather than only described because a diagnostic about an id quotes it, and because the rule it broke is a field rather than a sentence so that a caller can tell an unqualified id — which is somebody forgetting a namespace — apart from one whose namespace is spelled with characters no namespace may hold.

func (MalformedIDError) Error

func (e MalformedIDError) Error() string

Error implements the [error] interface.

type MalformedParameterError

type MalformedParameterError struct {
	// Written is the text as it was given.
	Written string

	// Err is why it could not be read as a form, and is nil where it read as
	// something other than one tagged form.
	Err error
}

MalformedParameterError is text written where an assertion parameter belongs which is not one.

A parameter is written as the entity format writes it without its parentheses — `tolerance boundary-closure`, `zone site:Z-90` — so what is refused here is text which does not read as exactly one such form.

func (MalformedParameterError) Error

func (e MalformedParameterError) Error() string

Error implements the [error] interface.

func (MalformedParameterError) Unwrap

func (e MalformedParameterError) Unwrap() error

Unwrap returns why the text could not be read.

type MalformedTermError

type MalformedTermError struct {
	// Written is the text as it was given.
	Written string

	// Reason is why it could not be read.
	Reason TermProblem
}

MalformedTermError reports text written where an accuracy term belongs which is not one.

func (MalformedTermError) Error

func (e MalformedTermError) Error() string

Error implements the [error] interface.

type MalformedTimestampError

type MalformedTimestampError struct {
	// Written is the text as it appeared.
	Written string

	// Reason is the rule of observation specification section 4.2 it broke.
	Reason TimestampProblem
}

MalformedTimestampError reports text written where an observation timestamp belongs which is not one.

There is one spelling of a timestamp in this format and it is the engine's rather than the caller's, so the parse and the refusal are here: a command taking one on its command line and a file carrying one are held to the same spelling, and neither has a second copy of it to drift from.

func (MalformedTimestampError) Error

func (e MalformedTimestampError) Error() string

Error implements the [error] interface.

type MalformedValueError

type MalformedValueError struct {
	// Written is the text as it was given.
	Written string

	// Shape is the shape it was being read as, and is empty where the predicate
	// declared none.
	Shape Shape

	// Reason is why it could not be read.
	Reason ValueProblem
}

MalformedValueError reports text written where a value belongs which is not one of the shape the predicate declares.

func (MalformedValueError) Error

func (e MalformedValueError) Error() string

Error implements the [error] interface.

type MeasuredEdge

type MeasuredEdge struct {
	// contains filtered or unexported fields
}

MeasuredEdge is an edge which bounds nothing the plan drew and runs between two corners it did, with the claims written on it.

It is how a dimension string across a room, or a span between two jambs, reaches a sheet. A measurement between two corners is an ordinary edge carrying a claim, and nothing requires that edge to be in any loop — so a plan which reported only what bounds its outlines would leave exactly those measurements off the answer a sheet is drawn from.

What places it on this plan is its two ends, and not its frame and not any containment. An edge has no `within`, so containment cannot place it; and a frame is not a place — two storeys may share one, and a plan of a parcel would otherwise pull in every edge on the site grid whether or not anything it drew meets it. A measured edge between two corners of a storey's rings is about that storey, structurally. An edge running to a corner no drawn outline has is not on the plan, and is still reachable through Topology.Edges and the `list-geometry` listing built on it.

It is reported only where it carries a live claim under a predicate the invocation annotates with, which keeps Annotations the whole of the answer to what is worth drawing.

A curve claimed on it is not drawn. A measurement runs between two points, so its ends are what it carries, and it is never a chorded edge of the plan.

The zero MeasuredEdge names no edge, and every method below works on it.

func (MeasuredEdge) Annotations

func (m MeasuredEdge) Annotations() []Annotation

Annotations returns the claims reported on it, each anchored to the edge.

func (MeasuredEdge) DeclaredIn

func (m MeasuredEdge) DeclaredIn() ID

DeclaredIn returns the frame the edge was written in, which is the frame a coordinate-valued claim on it is in. It is empty for the zero MeasuredEdge.

func (MeasuredEdge) Edge

func (m MeasuredEdge) Edge() *Edge

Edge returns the edge the claims are written on.

func (MeasuredEdge) From

func (m MeasuredEdge) From() Point

From returns where the first of its vertices is, in Plan.Frame.

It is the coordinate that corner has on the outlines the plan drew, and so is exactly the `from` of every boundary run leaving it.

func (MeasuredEdge) ID

func (m MeasuredEdge) ID() ID

ID returns the id of that edge.

func (MeasuredEdge) Label

func (m MeasuredEdge) Label() string

Label returns what the edge is called, which is empty where it is called nothing.

func (MeasuredEdge) String

func (m MeasuredEdge) String() string

String renders it as a person reads it: which edge, which corners it runs between and how much is written on it.

func (MeasuredEdge) To

func (m MeasuredEdge) To() Point

To returns where the second of its vertices is, in Plan.Frame.

func (MeasuredEdge) Vertices

func (m MeasuredEdge) Vertices() (start, end ID)

Vertices returns the edge's two vertices in the order it was authored, which is the order Anchor.Vertices gives them in.

type Measurement

type Measurement struct {
	// contains filtered or unexported fields
}

Measurement is how big one thing is, computed from where its corners are.

Nothing here is ever written back into a model. An area recorded beside the boundary it describes is a second source of truth which goes stale the first time a wall moves, and the whole reason this is computed on demand is that it cannot disagree with the geometry it is derived from ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

Every figure is in the unit of the frame the thing is declared in, which Measurement.Unit reports and nothing converts ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)). A length is in that unit and an area is in it squared.

Each figure comes back with whether it could be computed at all, because "there is no answer" and "the answer is zero" are different states and a shape which does not close has the first. A figure which is not available is accompanied by a diagnostic saying why, and never by a number which looks plausible.

The zero Measurement measures nothing and every method below works on it.

func (Measurement) Area

func (m Measurement) Area() (float64, bool)

Area returns the enclosed area, in the square of Measurement.Unit, and whether it could be computed.

Nothing encloses an area unless it is a ring which closes, does not cross itself and lies in one plane. Each of those failing is a diagnostic and leaves this reporting that there is no answer, which is the point: a projection of a shape which is not planar, or the signed sum over one which crosses itself, are both numbers, and neither is an area.

func (Measurement) Bounds

func (m Measurement) Bounds() (Box, bool)

Bounds returns the axis-aligned bounding box, and whether it could be computed.

It needs only the corners, so it survives shapes which have no area: a ring with a gap in it still reaches as far as it reaches.

func (Measurement) Budget

func (m Measurement) Budget() Budget

Budget returns the accumulated accuracy of the position claims the figures were computed from.

It is in the frame's linear unit, and is the uncertainty of the corners rather than of the area — the sensitivity of an area to each of its corners is a per-corner quantity, and one number standing in for all of them would be exactly the plausible-looking wrong answer the rest of this file refuses to produce. What it does say is what the answer rests on: which claims, which shared terms among them counted once, and whether any corner stated no accuracy at all, which Budget.Known reports.

func (Measurement) Centroid

func (m Measurement) Centroid() (Point, bool)

Centroid returns where the area of the thing is centred, and whether that could be computed.

It is the area centroid and not the mean of the corners. A room with three corners bunched at one end has its area centred away from them, and the mean of the corners is not a point anybody asked about.

For an edge it is the midpoint of the segment, which is the same definition one dimension down.

func (Measurement) ChordTolerance

func (m Measurement) ChordTolerance() (Tolerance, bool)

ChordTolerance returns the declared tolerance the rings were drawn to on the way to the answer, and whether anything was drawn at all.

Almost nothing is. Every figure a measurement reports is computed from the arc itself, so the only thing a drawing is ever needed for is deciding which of several rings holds which — the even-odd nesting, which is taken at the corners and cannot be taken at the corners of a ring which bulges past one ([measurer.depths]). A measurement of a straight shape and a measurement of a single curved ring both come back with nothing drawn.

Where something was drawn, this and Measurement.Deviation are what say so. An answer which silently chose a resolution for somebody's boundary is the approximation an arc kept as an arc exists to prevent, and the figures are no use to a caller who cannot tell one from the other.

func (Measurement) Deviation

func (m Measurement) Deviation() float64

Deviation returns how far the worst segment of that drawing falls from the curve it stands in for, in the frame's linear unit.

It is what was achieved rather than what was asked for, and it is always within Measurement.ChordTolerance: a curve is divided into a whole number of segments, so an arc which needs two and a bit gets three and follows the curve more closely than it had to.

It bounds the nesting and not the figures. The area of a curved ring is the area of the arc, exact whatever this says; what the drawing decided is which rings were taken away from which.

func (Measurement) Length

func (m Measurement) Length() (float64, bool)

Length returns the extent of an edge, or the total length of the edges of a loop or a region, and whether it could be computed.

For a closed loop that is its perimeter. For one which does not close it is still the total length of the edges written on it, which is what is true: the edges have lengths whether or not they form a ring.

func (Measurement) Report

func (m Measurement) Report() string

Report writes the figures and, under them, the accuracy they rest on: the combined uncertainty of the corners where there is one, and every term which went into it.

It is the detail under Measurement.String rather than a second rendering of the same thing, and it is here rather than in whatever prints it so that a caller reporting a measurement and a command reporting one write the same words. The terms are what make the figure actionable — "±0.006 m" is a number nobody can act on, and "the georeference is most of it, and three corners share it" says what to re-measure (Budget).

The uncertainty is of the corners and not of the area, exactly as Measurement.Budget says. Nothing here reduces it to a tolerance on a figure.

func (Measurement) String

func (m Measurement) String() string

String writes the figures which were computed, with their units.

func (Measurement) Subject

func (m Measurement) Subject() ID

Subject returns the id of the thing which was measured.

func (Measurement) Unit

func (m Measurement) Unit() Unit

Unit returns the linear unit of the frame the thing was measured in, which is empty where the registry declares no frame of that id.

Every figure is in it: a length in the unit, an area in the unit squared. A measurement is never converted into another one, so a figure and this unit together are the whole answer.

type Members

type Members struct {
	// contains filtered or unexported fields
}

Members is which observations fall inside the area one semantic node covers.

The two answers are two slices rather than one carrying a flag, which is the whole point of the type: a shot the model cannot place is not assignable by a caller who forgot to look. Ranging over Members.Inside is the ordinary question — which shots are in this region — and it cannot pick up a shot which is only nearly in it.

The zero Members holds nothing and every method below works on it.

func (Members) Ambiguous

func (m Members) Ambiguous() []Membership

Ambiguous returns the shots nearer the boundary than they are known to, in record identity order.

They are reported rather than assigned. A shot 20 mm outside a boundary, taken with a float solution good to 240 mm, is not outside the region: it is a shot nobody can place, and the honest answer is to say so and let whoever cares reshoot it.

func (Members) Inside

func (m Members) Inside() []Membership

Inside returns the shots which fall inside the region by more than they are known to, in record identity order.

func (Members) Len

func (m Members) Len() int

Len reports how many shots were placed at all, inside and ambiguous together.

func (Members) String

func (m Members) String() string

String writes how many fell each way.

func (Members) Subject

func (m Members) Subject() ID

Subject returns the id of the node the observations were judged against.

func (Members) Tolerance

func (m Members) Tolerance() Tolerance

Tolerance returns the declared tolerance the boundary rule was applied against.

type Membership

type Membership struct {
	// contains filtered or unexported fields
}

Membership is one observation judged against the area one semantic node covers.

It is derived and is written nowhere ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). A shot is *in* a place as a consequence of two things — where it was taken and where the boundary runs — and neither of them is written on the observation record. Writing the answer down would guarantee it went stale the first time somebody moved the boundary, and the shot which is suddenly outside would go on saying it was inside in a file nobody had any reason to open.

A shot *of* a thing is the opposite and is stored: the entity names the file the shot was written in, which is a deliberate statement that this evidence backs this thing. Membership.Linked is which of the two this result is, and the two are not interchangeable — a total station set up on a monument shoots it from a place which may be inside somebody else's garden.

The zero Membership holds no observation and every method below works on it.

func (Membership) Ambiguous

func (m Membership) Ambiguous() bool

Ambiguous reports whether the shot is nearer the boundary than it is known to.

Every result Graph.ObservationsWithin returns is either confidently inside or ambiguous, and the two are separate slices of a Members rather than a flag on one, so that a caller cannot silently assign a shot the model cannot place. This is here for the caller which has one result in hand.

func (Membership) At

func (m Membership) At() Point

At returns the coordinate the judgement was made from, in Membership.Frame.

It is the record's own coordinate where the record was written in that frame, and the carried coordinate where it was not. Reading it rather than the record's is what a caller plotting the shot against the region wants: the two are the same position and are different numbers.

func (Membership) Budget

func (m Membership) Budget() Budget

Budget returns the accuracy of the transform the shot was carried across, which holds no terms where it was not carried at all.

func (Membership) Carried

func (m Membership) Carried() bool

Carried reports whether the shot was written in another frame and brought across to be judged.

It is worth knowing on its own. A carried shot is judged through a chain of measured transforms, so its position is known less well than the record's own precision says, and Membership.Budget is what that cost.

func (Membership) Clearance

func (m Membership) Clearance() float64

Clearance returns how far the shot is from the nearest run of the boundary, measured in the plane of the region and in Membership.Unit.

It is positive inside the region and negative outside it, so an ambiguous shot says which side of the boundary it fell on as well as how near it was.

func (Membership) Doubt

func (m Membership) Doubt() (float64, bool)

Doubt returns how well Membership.Clearance is known, in Membership.Unit, and whether it could be arrived at at all.

It is the band Graph.ObservationsWithin judges the boundary against, and it is three things added: the declared tolerance, the shot's own horizontal precision and the standard uncertainty of the transform which carried it. A false second return is a transform whose accuracy nothing states: the two terms which were stated still decide whether the shot is a result at all, and a shot which is one is reported rather than ever confidently inside.

func (Membership) Frame

func (m Membership) Frame() ID

Frame returns the frame the judgement was made in, which is the subject's and not necessarily the one the record was written in.

func (Membership) Linked

func (m Membership) Linked() bool

Linked reports whether the subject entity names the observation file this shot was written in.

That link is stored, is what the entity format writes as `observed-in`, and is what makes a shot one *of* the subject: somebody decided this evidence backs this thing. A result with it false is a shot merely *in* the place, which nothing wrote down anywhere and which is true only because of where the shot and the boundary are.

It is the subject's own links which decide it, and not those of the corners bounding it. A shot cited by the corner is evidence about the corner.

func (Membership) Observation

func (m Membership) Observation() *Observation

Observation returns the record which was judged.

func (Membership) Offset

func (m Membership) Offset() float64

Offset returns how far the shot lies out of the plane of the region, in Membership.Unit.

It is never negative and is never a reason a shot is excluded: membership is a question asked in plan, and a shot of the ground inside a garden is routinely a few tenths of a metre off the plane the boundary corners happen to define. What it is for is telling a shot on this storey from one two floors above it, which is a judgement about the model rather than about the geometry and is the caller's to make.

func (Membership) String

func (m Membership) String() string

String writes where the shot fell and how well that is known.

The three renderings are the three states, and the unbounded one is spelled out rather than folded into "near the boundary": a shot four metres inside a region on a fit nobody stated the accuracy of is not near anything, and saying it was would be the one reading which sends somebody out to remeasure the wrong thing.

func (Membership) Subject

func (m Membership) Subject() ID

Subject returns the id of the node the observation was judged against.

func (Membership) Tolerance

func (m Membership) Tolerance() Tolerance

Tolerance returns the declared tolerance the boundary rule was applied against.

func (Membership) Unit

func (m Membership) Unit() Unit

Unit returns the linear unit of that frame, which every figure here is in.

type MissingChildError

type MissingChildError struct {
	// Predicate is the predicate the claim was written under.
	Predicate string

	// Child is the tag of the child that was left out.
	Child string

	// Wants is what that child holds.
	Wants string
}

MissingChildError is a claim written without one of the children every claim carries.

The accuracy is never this. Leaving it out is the one escape hatch the rule keeps open, and a claim which takes it loads and is unrankable.

func (MissingChildError) Error

func (e MissingChildError) Error() string

Error implements the [error] interface.

type MissingParameterError

type MissingParameterError struct {
	// Check is the check the assertion names.
	Check string

	// Parameter is the parameter left out.
	Parameter string

	// Want is the sort of datum it takes.
	Want ParameterType

	// Diagnostic is what a load reports for the same assertion written by hand.
	Diagnostic Diagnostic
}

MissingParameterError is a parameter the check requires and the assertion does not write.

func (MissingParameterError) Error

func (e MissingParameterError) Error() string

Error implements the [error] interface.

type MissingReasonError

type MissingReasonError struct {
	// ID is the node which was being retired.
	ID ID
}

MissingReasonError reports a retirement which said nothing about why.

The reason is required because a retirement with no reason is a deletion wearing a hat: the record of what was there survives, and the record of why it stopped being there is the half which explains it.

func (MissingReasonError) Error

func (e MissingReasonError) Error() string

Error implements the [error] interface.

type MissingReplacementError

type MissingReplacementError struct {
	// ID is the claim that would have been retracted.
	ID ID
}

MissingReplacementError is a deprecation which names nothing to stand in the retracted claim's place.

Requiring one is the whole of what keeps `deprecated` from being a delete button ([0007](docs/decisions/0007-rank-is-closed.md)).

func (MissingReplacementError) Error

func (e MissingReplacementError) Error() string

Error implements the [error] interface.

type MixedUnitsError

type MixedUnitsError struct {
	// Units are the units the terms were written in, each once, in the order
	// they were accumulated.
	Units []Unit
}

MixedUnitsError reports that a budget's terms are not all expressed in one unit.

Nothing here converts between units ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)). Adding a figure in millimetres to one in metres to get a budget would be exactly the silent conversion the rest of the engine refuses, so a budget whose terms disagree combines to nothing and says which units it was asked to reconcile.

func (MixedUnitsError) Error

func (e MixedUnitsError) Error() string

Error implements the [error] interface.

type Namespace

type Namespace struct {
	// Name is the namespace itself — the part of an id before the first colon.
	Name string

	// Description says what authority issues these ids. Nothing in the engine
	// reads it ([0003](docs/decisions/0003-id-namespaces-are-a-closed-registry.md)).
	Description string

	// Span is where the declaration was written.
	Span Span
}

Namespace is one declared id namespace, per specification section 7.2.

type NearSpec

type NearSpec struct {
	// Frame is the frame the point is expressed in. Only the vertices written in
	// it are considered, and the point, the positions and the tolerance are all
	// in its one unit.
	Frame ID

	// Predicate is the predicate a vertex's position is claimed under, which has
	// to declare a coordinate.
	Predicate string

	// Tolerance is the name of the declared tolerance a vertex has to be within
	// of the point, which has to be declared in the frame's unit.
	Tolerance string

	// Point is where to look, in the shape the predicate declares and the unit of
	// the frame. [ParseCorner] reads one from a command line.
	Point Value
}

NearSpec is a point to find the vertices around.

It is the question a scaffold asks of every corner — which vertex does this land on — asked on its own and without writing anything. Nothing in it has a default, for the reason nothing in a ScaffoldSpec has one: the frame, the predicate a position is claimed under and how close is close enough are all the consuming repository's to say.

type Nearby

type Nearby struct {
	// Vertex is the vertex.
	Vertex ID

	// At is where its position resolves to, component by component, in the
	// frame's unit.
	At []float64

	// Distance is how far it is from the point, in the frame's unit.
	Distance float64
}

Nearby is one vertex within the tolerance of a point.

type Nearness

type Nearness struct {
	// Point is the point asked about, component by component, in the frame's
	// unit.
	Point []float64

	// Vertices are the vertices within the tolerance of the point, in the order
	// the model's walk reached them. Empty rather than nil when there are none.
	Vertices []Nearby

	// Tolerance is the declaration the vertices were judged against, which
	// travels with the answer because the answer depends on it
	// ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).
	Tolerance Tolerance

	// Unit is the frame's unit, which every coordinate and distance above is in.
	Unit Unit
}

Nearness is what Graph.VerticesNear found.

type NoMergeBaseError

type NoMergeBaseError struct {
	// Head and Base are the two revisions, as they were written.
	Head, Base string
}

NoMergeBaseError is two revisions with no common ancestor.

func (NoMergeBaseError) Error

func (e NoMergeBaseError) Error() string

Error implements [error].

type Node

type Node struct {
	// Datum is the datum itself, as the underlying S-expression parser
	// produced it. A type switch over it says what the node is and, for an
	// atom, what its decoded value is.
	//
	// Datum carries its own children too, unspanned. Children below is the
	// same sequence, spanned; the two are always the same length and in the
	// same order.
	Datum sexpr.Node

	// Span is the extent of the source text Datum was written in.
	Span Span

	// Children are the datums written inside this one, in source order. An
	// atom has none. A list has one child per element, followed by one more
	// for its tail where it has one. A quote shorthand has exactly one.
	Children []*Node

	// Comments are the comments written directly inside this node, in the
	// order they were written. Only a list can hold any, and they belong to
	// the list rather than to any one of its children.
	Comments []*Comment
}

Node is one datum together with the span of source text it was written in.

Every node of every loaded file has a span, which is the whole point of the type: a problem found three layers up in the model can still be reported against the file, line and column somebody wrote.

func ParseParameter

func ParseParameter(written string) (*Node, error)

ParseParameter reads one assertion parameter as it is written on a command line and in an operation file: the parameter form without its parentheses, its tag first and then its values.

Nothing about the check is asked here. Whether the tag is one the check takes and whether each value is the sort of datum it declares are the check registry's questions, answered by the validation a load runs (ValidateAssertion).

type NodeSpec

type NodeSpec struct {
	// ID is the id it will be written with. Its namespace must be one the
	// registry declares.
	ID ID

	// Kind is the kind it will declare, which must be one of [Kinds] and must
	// be one the type permits.
	Kind Kind

	// Type is the type it will declare, which the registry must declare.
	Type string

	// Geometry is the geometry form it will declare, and is empty for a node
	// with no geometry — which the type has to permit.
	Geometry Geometry

	// Frame is the coordinate frame it is expressed in, and is empty for a node
	// which declares none.
	Frame ID

	// Label is its display text, and is empty for a node with none. Nothing
	// resolves through a label, so it is the one axis here which changes nothing
	// but what a person reads.
	Label string
}

NodeSpec is a semantic node which does not exist yet: the axes it will be written with.

It is the axes rather than a SemanticNode because the node being authored has not been read from anywhere, so there is nothing to carry a span, a resolved reference or a claim. The three optional axes are optional as emptiness: a node with no geometry, no frame and no label is ordinary, and the empty string is not a member of either closed set, so nothing is lost by spelling absence that way.

The references a node makes — what contains it, which zones it belongs to, which loops bound it — are not here. A new node is added and then related, so that the refusal to place it and the refusal to relate it are two answers rather than one compound one.

func (NodeSpec) Check

func (spec NodeSpec) Check(registry *Registry) error

Check reports the first axis of the spec which the registry does not permit.

The checks are ordered rather than independent because they build on each other, for the reason the load pass orders the same three: a type nothing declares permits nothing, and reporting a kind as one an undeclared type does not permit says nothing anybody can act on.

Tx.AddNode calls it, so a caller which only adds nodes never has to. It is exported for the caller which has something else to do with the axes first — deciding which file the node goes in, which is a question about the same three — because a misspelled kind answered as a routing rule which matched nothing is an answer about the wrong mistake.

func (NodeSpec) Destination

func (spec NodeSpec) Destination(registry *Registry, override string) (Destination, error)

Destination is the file the node goes in: the one the registry's routing rules choose for it, or the one an override names outright.

override is a path relative to the model root, and is empty where the rules are to decide. It is not checked against them, which is the whole of what an override is for: the rules describe where things ordinarily go, and the one command which needs somewhere else says so rather than having a rule written for it.

The axes are checked before the rules are consulted, and that order is here rather than in the caller because it is the difference between two answers to one mistake. Three of the axes are what a rule matches on, so a misspelled kind reported as a node no rule places sends the author to the registry to write a rule for a kind which does not exist.

type Nodes

type Nodes struct {
	// contains filtered or unexported fields
}

Nodes are the semantic nodes of one load: every node the walk read, in the order it read them, and indexed by id.

The index is the load's own. A load has to build one anyway — an id is unique across the whole model, and finding a duplicate means having somewhere to look the id up — so handing it back costs nothing and saves every caller above building a second one. Two indexes over one model would be two answers to "what is site:S-101", and they would differ the first time a node moved between files.

A Nodes is read-only once loaded. The zero value holds no nodes, which is what a source tree holding none yields, and every method below works on it.

func (*Nodes) All

func (n *Nodes) All() iter.Seq[*SemanticNode]

All iterates the nodes in the order the walk reached them.

That order is deterministic — the lexical order of the paths, and within a file the order the forms were written — so anything built from it diffs against the last run's.

func (*Nodes) Ancestors

func (n *Nodes) Ancestors(node *SemanticNode) iter.Seq[Related]

Ancestors iterates the nodes which contain node, nearest first, each labelled with the relation which produced it.

It is Nodes.Within followed to the root: the node this one sits in, then the node that one sits in, and so on to the node nothing contains. That walk is what answers "which building is this outlet in" without the caller writing the loop and deciding for itself when to stop.

Each node comes back once. A cyclic containment is a load diagnostic and still a model this can be asked of, so the walk stops when it meets a node it has already reached rather than spinning.

func (*Nodes) AncestorsTo

func (n *Nodes) AncestorsTo(node *SemanticNode, depth int) iter.Seq[Related]

AncestorsTo iterates the nodes which contain node, nearest first, and stops after depth steps.

It is Nodes.Ancestors with a bound: a depth of one is the node this one sits in, a depth of two adds the node that one sits in, and Unbounded is the walk to the root which Ancestors is. A depth of zero takes no step and yields nothing.

The bound is what makes a traversal safe to run against a model nobody has read: "the two levels above this outlet" is a question with an answer whose size is known before it is asked, where "everything above it" is a question whose answer is the height of whatever hierarchy it happens to be in.

func (*Nodes) Contains

func (n *Nodes) Contains(node *SemanticNode) iter.Seq[Related]

Contains iterates the nodes written directly within node, in the order the walk read them, each labelled with the relation which produced it.

It is the reverse of Nodes.Within and is one level deep. The reference is written on the contained node, so this direction is not written anywhere; it is indexed at load, because computing it by scanning every node per question would make walking a hierarchy quadratic in the size of the model.

A node written within itself is a load error rather than its own child, and is not yielded here: a caller iterating the contents of a node would otherwise meet the node itself, and every walk below it would be infinite.

func (*Nodes) Descendants

func (n *Nodes) Descendants(node *SemanticNode) iter.Seq[Related]

Descendants iterates everything contained by node, however deep, each labelled with the relation which produced it.

It is Nodes.Contains followed all the way down, depth first, and within one level in the order the walk read the nodes. That order is deterministic, so anything built from it diffs against the last run's.

Each node comes back once, and a node already reached is not walked into twice, so a cyclic containment — a load diagnostic, and still a model this can be asked of — terminates here rather than spinning.

func (*Nodes) DescendantsTo

func (n *Nodes) DescendantsTo(node *SemanticNode, depth int) iter.Seq[Related]

DescendantsTo iterates everything contained by node and stops after depth steps, level by level.

It is Nodes.Descendants with a bound, and it is level by level rather than depth first because a bound is a statement about levels: a depth of two is what a node holds and what those hold, and a walk which went deep before it went wide would report the deepest thing it found before the second thing the node holds. Descendants, which has no bound, has no such choice to make and goes depth first.

Each node comes back once, at the fewest steps it can be reached in.

Example

ExampleNodes_DescendantsTo walks containment with a bound, which is what makes a traversal of a model nobody has read an answer of a known size.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/node/containment"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)

	site, _ := nodes.Node("site:S-01")

	// Level by level, so a bound of two is the two levels which were asked for.
	for contained := range nodes.DescendantsTo(site, 2) {
		fmt.Printf("%s %s at %d\n", contained.Relation(), contained.Node().ID(), contained.Depth())
	}

	// And the other relation, which the walk above never follows: the zones a
	// node is grouped into say nothing about where it is, so nothing inside the
	// site is reached through one.
	partition, _ := nodes.Node("site:E-01")
	for zone := range nodes.ZonesTo(partition, dfcad.Unbounded) {
		fmt.Printf("%s %s at %d\n", zone.Relation(), zone.Node().ID(), zone.Depth())
	}

}
Output:
containment site:B-01 at 1
containment site:L-01 at 2
membership site:Z-fire at 1
membership site:Z-therm at 1
membership site:Z-maint at 1

func (*Nodes) Len

func (n *Nodes) Len() int

Len reports how many nodes were read.

func (*Nodes) Members

func (n *Nodes) Members(zone *SemanticNode) iter.Seq[Related]

Members iterates the nodes which are members of the zone, in the order the walk read them, each labelled with the relation which produced it.

It is the reverse of Nodes.Zones, and is indexed at load for the reason Nodes.Contains is: the reference is written on the member, so this direction is written nowhere.

Membership never reaches through containment. The members of a storey's zone are the nodes which wrote `(member-of ...)` naming it, and not the nodes which happen to sit inside one of them — which is the whole of keeping "is a member of" from quietly meaning "is inside".

Asked of a node which is not a Zone, it gives the nodes which named it anyway, for the reason Nodes.Zones follows such an edge from the other end: naming a non-zone in a `member-of` is a load error, and the two ends of one edge report the same thing or neither is trustworthy.

func (*Nodes) MembersTo

func (n *Nodes) MembersTo(zone *SemanticNode, depth int) iter.Seq[Related]

MembersTo iterates the nodes which are members of zone, and the members of those which are themselves zones, stopping after depth steps.

It is Nodes.Members followed as far as membership nests, and the reverse of Nodes.ZonesTo: where that walks from a thing out to the groups it is in, this walks from a group in to what it groups. A depth of one is the nodes which wrote `(member-of <zone>)`, whatever their type — which is the answer a caller inverting membership by hand over a list of types can only ever approximate.

Each node comes back once, at the fewest steps it can be reached in, so a member reached directly and again through a nested zone is one member.

Nothing here reads containment, at any depth. A node inside a member is not a member unless it wrote its own `member-of`: being inside something grouped is not being grouped.

Example

ExampleNodes_MembersTo walks membership inwards, from a zone to what it groups, which is the direction nothing in the model is written in.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/node/containment"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)

	thermal, ok := nodes.Node("site:Z-therm")
	if !ok {
		fmt.Println("no such node")
		return
	}

	// Every node which wrote `(member-of site:Z-therm)`, whatever its type: the
	// partition, and the maintenance round, which is a zone grouped into this
	// one. The partition is also a member of the maintenance round, and it is
	// reported once, at the fewer steps.
	for member := range nodes.MembersTo(thermal, dfcad.Unbounded) {
		fmt.Printf("%s %s at %d\n", member.Relation(), member.Node().ID(), member.Depth())
	}

}
Output:
membership site:E-01 at 1
membership site:Z-maint at 1

func (*Nodes) Node

func (n *Nodes) Node(id ID) (*SemanticNode, bool)

Node returns the node id names, and whether the model holds one.

The lookup is by index and does not scan. Every layer above resolves references by id — containment, zone membership, boundaries, supersession — and a scan per reference would make resolving a model quadratic in the size of the thing being resolved.

The zero ID names nothing, so a node whose id could not be read is reachable through Nodes.All and not through here. It is a node with a diagnostic against it rather than a node anything may reference.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/node/valid")

	nodes, _ := dfcad.LoadNodes("testdata/node/valid", registry)

	// Lookup is by index rather than by a scan: everything above this layer
	// resolves references by id, and a scan apiece would make resolving a model
	// quadratic in its size.
	room, ok := nodes.Node("site:S-101")
	if !ok {
		fmt.Println("no such node")
		return
	}

	// The label is display text. Changing it would change this line and nothing
	// else about the node — the id it is found by least of all.
	fmt.Printf("%s: %s, a %s\n", room.ID(), room.Label(), room.Kind())

}
Output:
site:S-101: Meeting Room B, a Space

func (*Nodes) Within

func (n *Nodes) Within(node *SemanticNode) (Related, bool)

Within returns the node which strictly contains node, labelled with the relation which produced it, and whether the model holds one.

A node with no parent is ordinary rather than incomplete: a site is the root of its hierarchy and a circuit group sits in no hierarchy at all, so the second result is a state and not a failure.

It is one step outward rather than the whole chain, which is what makes containment walkable a level at a time. Nodes.Ancestors follows it to the root.

A `within` naming a node this model does not hold is a load diagnostic rather than a state a caller has to interpret, and the reference is not followed here: a caller which loaded clean never sees a false for that reason.

func (*Nodes) Zones

func (n *Nodes) Zones(node *SemanticNode) iter.Seq[Related]

Zones iterates the zones node is a member of, in the order they were written, each labelled with the relation which produced it.

Membership is many to many and says nothing about where the node is. A wall between two rooms belongs to the zones of both, a circuit group belongs to zones and sits in no hierarchy, and neither is a special case. Nothing here reads the containment references, so a node's zones are its own and not its parent's.

A `member-of` naming a node this model does not hold has nothing to yield and is skipped. One naming a node which is not a Zone is a load error and is yielded: the edge is what the file says, and a traversal which quietly dropped it would disagree with the source somebody is being asked to fix. It is the rule [Nodes.link] keeps for both relations — a containment the hierarchy forbids is reported and still walked — so that neither goes quiet about an edge the other would show.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, _ := dfcad.LoadRegistry("testdata/node/containment")
	nodes, _ := dfcad.LoadNodes("testdata/node/containment", registry)

	partition, ok := nodes.Node("site:E-01")
	if !ok {
		fmt.Println("no such node")
		return
	}

	// The wall is inside exactly one thing and belongs to three zones which
	// overlap it. Every result says which relation produced it, so "is inside"
	// and "is a member of" can never be read as each other.
	if parent, ok := nodes.Within(partition); ok {
		fmt.Printf("%s %s\n", parent.Relation(), parent.Node().ID())
	}

	for zone := range nodes.Zones(partition) {
		fmt.Printf("%s %s\n", zone.Relation(), zone.Node().ID())
	}

}
Output:
containment site:L-01
membership site:Z-fire
membership site:Z-therm
membership site:Z-maint

func (*Nodes) ZonesTo

func (n *Nodes) ZonesTo(node *SemanticNode, depth int) iter.Seq[Related]

ZonesTo iterates the zones node is a member of, and the zones those are members of, stopping after depth steps.

It is Nodes.Zones followed as far as membership nests. A zone is a node like any other and may itself be written into a zone, so "which zones is this in" has more than one level to it whenever a model groups its groups; a depth of one is the zones the node itself names, which is what it wrote.

Nothing here reads containment, at any depth. A node does not join its parent's zones by being inside it, and a walk which reached one through the other would be the conflation the two relations exist to keep out of the model.

type NotANodeError

type NotANodeError struct {
	// ID is the id which was asked for.
	ID ID

	// Family is the tag the model wrote it as: `vertex`, `edge` or `loop`.
	Family string
}

NotANodeError reports an id which names something other than a semantic node where one was required.

Retiring is a thing the semantic family does. A vertex, an edge and a loop are the shape other things are written in terms of, and a shape which stopped existing is one nothing references any more — which is a change to whatever referenced it rather than a state written on the shape ([0001](docs/decisions/0001-two-node-families.md)).

func (NotANodeError) Error

func (e NotANodeError) Error() string

Error implements the [error] interface.

type NotARepositoryError

type NotARepositoryError struct {
	// Dir is the directory, as it was given.
	Dir string
}

NotARepositoryError is a directory which is not inside a git working tree, and so has no previous revision to be compared with.

func (NotARepositoryError) Error

func (e NotARepositoryError) Error() string

Error implements [error].

func (NotARepositoryError) Unwrap

func (e NotARepositoryError) Unwrap() error

Unwrap implements the interface errors.Is and errors.As walk.

type NotAssertableError

type NotAssertableError struct {
	// ID is the id the assertion was to be written on.
	ID ID

	// What is what that id names: "a frame" or "a claim".
	What string

	// At is where it is defined.
	At Span
}

NotAssertableError is an assertion on something which carries none.

An assertion is a child of a node, a vertex, an edge or a loop (specification sections 6.1 through 6.4). A frame is registry data and declares no `assert` child (section 7.5), and a claim is a statement about a thing rather than a thing an assertion constrains. What must hold of every instance of a type is the type's `invariant`, which is registry data too and is written by hand.

func (NotAssertableError) Error

func (e NotAssertableError) Error() string

Error implements the [error] interface.

type NotClaimBearingError

type NotClaimBearingError struct {
	// Predicate is the predicate that was written under.
	Predicate string

	// Written is the plain value a claim under it would have to be written as
	// instead.
	Written string
}

NotClaimBearingError is a claim written under a predicate the registry declares takes a plain value instead.

The two directions are one rule read from either side, and the loader reports the other one: a claim form under a non-claim-bearing predicate and a plain value under a claim-bearing one are each refused, naming the predicate and what the registry says about it.

func (NotClaimBearingError) Error

func (e NotClaimBearingError) Error() string

Error implements the [error] interface.

type NotCoordinateError

type NotCoordinateError struct {
	// Predicate is the predicate which was named.
	Predicate string

	// Shape is the shape it does declare.
	Shape Shape
}

NotCoordinateError reports a predicate asked to say where a vertex is which does not declare a coordinate.

A position is a point in a frame, so the predicate it is claimed under has to take a coordinate. A scalar or a transform predicate names something a vertex may well carry, but it is not where the vertex is, and measuring the distance from a point to a setback would be an answer to a question nobody can ask.

func (NotCoordinateError) Error

func (e NotCoordinateError) Error() string

Error implements the [error] interface.

type NotOfFamilyError

type NotOfFamilyError struct {
	// ID is the id which was written.
	ID ID

	// Want is the tag the reference required: `vertex` or `edge`.
	Want string

	// Got is the tag the model wrote it as.
	Got string
}

NotOfFamilyError reports an id which names a member of the model other than the one the reference required.

It is separate from NotANodeError, which is about the one operation only the semantic family has. This one is about a reference between geometric nodes: an edge names two vertices and a loop names edges, and an id which reached the wrong one of the three is a mistake about which thing was meant rather than about which family it belongs to.

func (NotOfFamilyError) Error

func (e NotOfFamilyError) Error() string

Error implements the [error] interface.

type NotPermittedError

type NotPermittedError struct {
	// Type is the type the node declares.
	Type string

	// Axis is which axis was refused: `kind` or `geometry`.
	Axis string

	// Value is what was written there, and is empty where the axis was omitted
	// and the type requires it.
	Value string

	// Permitted is what the type permits on that axis.
	Permitted []string
}

NotPermittedError reports an axis of an authored node which the node's type does not permit.

It is a different refusal from UnknownAxisError and reads as one: the value is a real member of its set, and the type this node declares is not one which takes it. The fix is a different type or a different value, and which of the two it is depends on what the author meant — so the message says what the type permits rather than choosing for them.

func (NotPermittedError) Error

func (e NotPermittedError) Error() string

Error implements the [error] interface.

type NothingToSupersedeError

type NothingToSupersedeError struct {
	// Subject is the thing the claim would have been about.
	Subject ID

	// Predicate is the predicate it would have been written under.
	Predicate string
}

NothingToSupersedeError is a correction of a subject and predicate the model says nothing about.

It is a refusal rather than an addition because the two are different intentions: correcting a value which is not there is a mistake about which thing is being corrected, and quietly adding the claim would leave the author believing something had been superseded.

func (NothingToSupersedeError) Error

func (e NothingToSupersedeError) Error() string

Error implements the [error] interface.

type Notice

type Notice struct {
	// Kind is what it is about.
	Kind NoticeKind

	// Subject is the thing the claim is about.
	Subject ID

	// Predicate is the predicate it was written under.
	Predicate string

	// Claim is the claim the notice is about, and is empty where that claim
	// wrote no id of its own.
	Claim ID

	// Competing are the claims already written on the same subject and
	// predicate, and are empty for a notice which is not about a disagreement.
	Competing []*Claim

	// Units are the units an unrankable claim's accuracy terms were written in,
	// each once, in the order written. They are empty unless the notice is about
	// a claim whose accuracy is unrankable because its terms are in more than
	// one unit.
	Units []Unit

	// Unusable reports that an unrankable claim did write accuracy terms, and
	// that one of them is not a term the arithmetic can use — a magnitude which
	// is not a finite number. It is false for every other notice, including one
	// about a claim which wrote no accuracy at all.
	Unusable bool
}

Notice is something a change has to say about the model it produces, which is neither a refusal nor a diagnostic.

It is not a Diagnostic because nothing is wrong with what anybody wrote: the files load, the change is permitted, and what is being reported is a consequence of it which the author is entitled to have wanted. A claim with no accuracy is a legitimate claim, a second claim about one thing is the most valuable thing in a model, and a retraction which leaves nothing behind is sometimes exactly the record that should be kept. What each of them is not is something to discover later.

A notice is a value rather than a sentence so that a caller can branch on it. Notice.Message is the sentence, and is presentation.

func (Notice) Message

func (n Notice) Message() string

Message is the notice as a sentence, for a person reading a terminal.

type NoticeKind

type NoticeKind string

NoticeKind is what a notice is about.

const (
	// NoticeUnrankable is a claim whose accuracy does not combine into one
	// figure, which can never win resolution. That is a claim written with no
	// accuracy, or one whose accuracy terms are not all in one unit — nothing
	// converts between them, and [Notice.Units] names the units it found. A
	// term the arithmetic cannot use at all, such as a magnitude which is not a
	// finite number, stops the combination too, and [Notice.Unusable] says so.
	NoticeUnrankable NoticeKind = "unrankable"

	// NoticeConflict is a claim written on a subject and predicate the model
	// already states, which is a disagreement rather than a replacement.
	NoticeConflict NoticeKind = "conflict"

	// NoticeUnresolvable is a retraction which leaves a subject and predicate
	// with no live claim at all, so nothing resolves under it.
	NoticeUnresolvable NoticeKind = "unresolvable"
)

type Observation

type Observation struct {
	// ID is this record's identity. It is what a claim's provenance points at
	// and what a retirement names, so it is minted once and never reused —
	// including for a record which was retired.
	ID ID

	// At is the instant the observation was taken, by the instrument's clock.
	At time.Time

	// AtWritten is the timestamp exactly as it was written, which carries which
	// offset the author was working in. The instant alone does not: an offset
	// is lost the moment a time is normalised, and it is evidence about where
	// somebody was standing.
	AtWritten string

	// Frame is the frame the coordinate is expressed in, which a registry file
	// declares.
	Frame ID

	// Coordinate is the position, component by component, in the frame's axis
	// order and in the frame's linear unit.
	Coordinate Point

	// Method is how the value was obtained — the same vocabulary a claim's
	// method names. Which methods exist is registry data
	// ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).
	Method ID

	// Fix is the fix quality the instrument reported at the moment of the shot:
	// what solution it had, not how good anybody thought it was. Registry data
	// for the reason Method is.
	Fix ID

	// HorizontalPrecision is the standard uncertainty of this shot in the plane
	// of the first two components — one standard deviation, k = 1
	// ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)) — in the frame's
	// unit.
	HorizontalPrecision float64

	// VerticalPrecision is the standard uncertainty along the third component,
	// on the same convention and in the same unit. It is separate because it is
	// routinely two to three times the horizontal figure, and one number for
	// both would have to be the worse of them.
	VerticalPrecision float64

	// AntennaHeight is the antenna or instrument height the shot was reduced
	// by: the vertical offset from the mark to the phase centre or to the
	// prism, in the frame's unit. The coordinate is of the mark, with this
	// height already reduced out; the figure is recorded so that the reduction
	// can be checked, and undone, by somebody who was not there.
	AntennaHeight float64

	// Session is the occupation this record belongs to — one setup, one base
	// station, one operator's afternoon. It is what makes a systematic error
	// attributable: a base station on the wrong mark ruins a session, and the
	// session is how its records are found.
	Session ID

	// Span is the line the record was written on.
	Span Span
	// contains filtered or unexported fields
}

Observation is one measurement somebody took, as one line of an observation file, per observation specification section 5.

It is not a claim. A claim is what the model asserts about a thing; an observation is a shot, and several of them may sit behind one claim. Nothing here names an entity: what cites a record is a claim's provenance, in the entity format, which is the one place the model says what it believes and why.

Every length on the record — the three coordinate components, both precisions and the antenna height — is in the linear unit of Frame, which is the one unit that frame has ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)). No unit token is written on the line and nothing here converts one.

func (*Observation) Line

func (o *Observation) Line() int

Line is the line of its file the record was written on, which is the only place it can have been: a record is entirely on one line.

type ObservationLink struct {
	// Path is the path as it was written: relative to the model root, with
	// forward slashes, ending in [ObservationExtension].
	//
	// It is kept as written rather than as resolved so that what a diagnostic
	// quotes is what the author typed, and so that two clones of one repository
	// read the same model whatever they were checked out into.
	Path string

	// Span is where the path was written, which is what a diagnostic about the
	// link points at.
	Span Span
}

ObservationLink is one link from an entity to an observation file, per specification section 6.10.

It is a path and not an id, which makes it the one reference of the entity format that names something outside the model's own id space. That is the point of it: an observation file holds thousands of records, they are bulk rather than vocabulary, and a link which named them one at a time would put the bulk back into the entity file it was moved out of.

The link is to the file and never into it. Which record backs which claim is a claim's provenance, in the entity format, and is a different question with a different answer.

type ObservationLog

type ObservationLog struct {
	// contains filtered or unexported fields
}

ObservationLog is the records of one or more observation files, in the order they were written.

Order is the log's own: within a file it is the order of the lines, and across files it is the lexical order of their paths, which is the order a walk reads them in. That is what makes "earlier in the log" a question with one answer however many files the log is spread over.

A log holds every record it read, including ones the validator refuses. The two questions — what does this file say, and is what it says sound — are answered separately so that a diagnostic about the second can still quote the first.

func (*ObservationLog) Current

func (l *ObservationLog) Current() iter.Seq[*Observation]

Current ranges over every observation no retirement names, in log order.

This is what the log resolves to, and it is a view rather than a rewrite: the retired records are still in the file, still readable, and still say exactly what the instrument said they said.

func (*ObservationLog) Len

func (l *ObservationLog) Len() int

Len is how many records the log holds, of both forms.

func (*ObservationLog) Observation

func (l *ObservationLog) Observation(id ID) (*Observation, bool)

Observation returns the observation written under id, and whether there is one. A second record written under the same identity is a duplicate the validator refuses; what this returns is the first.

func (*ObservationLog) Observations

func (l *ObservationLog) Observations() iter.Seq[*Observation]

Observations ranges over every observation, in log order.

func (*ObservationLog) Retired

func (l *ObservationLog) Retired(id ID) bool

Retired reports whether any retirement names id.

func (*ObservationLog) RetirementOf

func (l *ObservationLog) RetirementOf(id ID) (*ObservationRetirement, bool)

RetirementOf returns the retirement naming id, and whether there is one.

func (*ObservationLog) Retirements

func (l *ObservationLog) Retirements() iter.Seq[*ObservationRetirement]

Retirements ranges over every retirement, in log order.

func (*ObservationLog) Session

func (l *ObservationLog) Session(id ID) iter.Seq[*Observation]

Session ranges over the observations of one occupation, in log order.

func (*ObservationLog) Sessions

func (l *ObservationLog) Sessions() []ID

Sessions returns every session the log names, in the order it first named them.

type ObservationRetirement

type ObservationRetirement struct {
	// ID is this record's own identity, minted like any other. A retirement is
	// a record in the log, not an annotation on one.
	ID ID

	// At is when the decision to retire was taken, which is not when the
	// retired shot was measured.
	At time.Time

	// AtWritten is the timestamp exactly as it was written.
	AtWritten string

	// Supersedes is the identity of the record being retired, which appears
	// earlier in the log.
	Supersedes ID

	// Reason is why, in the words of whoever decided. It is never empty: a
	// retirement with no reason is not evidence of anything, and the next
	// person to read the file cannot tell a mistake from a change of mind.
	Reason string

	// Span is the line the record was written on.
	Span Span
	// contains filtered or unexported fields
}

ObservationRetirement is a later record retiring an earlier one, per observation specification section 6.

It removes nothing. The retired record stays exactly where it was written, byte for byte, and both are read: what the log resolves to is every observation no retirement names. Editing the original in place would destroy the thing which made it evidence — after the edit there is no way to tell, from the file, that the number ever said anything else.

func (*ObservationRetirement) Line

func (r *ObservationRetirement) Line() int

Line is the line of its file the record was written on.

type ObservationSource

type ObservationSource struct {
	// Path is the file's path, as a diagnostic should name it.
	Path string

	// Bytes is the revision's content. Nil is a revision in which the file is
	// absent, which is every one of its lines removed.
	Bytes []byte
}

ObservationSource is one revision of one observation file: the path it is known by, and its bytes.

It is a pair rather than a path because the revisions being compared are rarely both on disk — one of them is a commit, an archive entry or what was backed up — and because the path is what a diagnostic names rather than where the bytes came from.

type Op

type Op string

Op is what a change did to one thing in the model.

const (
	// OpCreated marks something the change wrote which the model did not hold.
	OpCreated Op = "created"

	// OpModified marks something the change rewrote in place.
	OpModified Op = "modified"

	// OpRetired marks something the change took out of the model.
	OpRetired Op = "retired"
)

type Operation

type Operation interface {
	// Name is what the operation file writes it under, which is the name of the
	// command making the same change on its own.
	Name() string
	// contains filtered or unexported methods
}

Operation is one authoring operation of a Batch.

The set is closed and is exactly the commands which change the model, so that an author who knows the interface knows the file. It is an interface with an unexported method rather than one struct carrying every axis of every operation, because a member written for an operation which does not read it is a mistake this way and a silently ignored member the other.

type OperationError

type OperationError struct {
	// Index is the operation's place in the batch, counted from one as a person
	// counts a list.
	Index int

	// Operation is the name it was written under, and is empty for one whose
	// name could not be read.
	Operation string

	// Err is what is wrong with it.
	Err error
}

OperationError is a problem with one operation of a batch.

The index is what makes it actionable. A batch is a list an author generated, and a refusal which says only what is wrong leaves them to find which of fifty operations it is wrong about.

func (OperationError) Error

func (e OperationError) Error() string

Error implements [error].

func (OperationError) Unwrap

func (e OperationError) Unwrap() error

Unwrap returns what is wrong with the operation, so that errors.Is and errors.As reach it.

type Outline

type Outline struct {
	// contains filtered or unexported fields
}

Outline is one contained node drawn as rings, with the claims written on it and on the edges bounding it.

The claims travel with the ring rather than in a list beside it, because which pair of corners a dimension belongs to is a fact the model holds and a consumer would otherwise have to re-derive by matching ids. Re-deriving it is the thing this whole answer exists to make unnecessary.

The zero Outline names no node and covers nothing.

func (Outline) Annotations

func (o Outline) Annotations() []Annotation

Annotations returns the claims reported on it, in anchor order.

func (Outline) DeclaredIn

func (o Outline) DeclaredIn() ID

DeclaredIn returns the frame the node's shape was read in, which is the frame every claim written on it and on its edges is in.

It is Plan.Frame for a node declared where its plan is, and another frame for one the plan carried: the region comes back in the plan's frame, and the claims come back whole, as they were written. A coordinate-valued annotation is a coordinate in this frame and not in the plan's, and this is what says so.

func (Outline) Node

func (o Outline) Node() *SemanticNode

Node returns the contained node the rings were read from.

func (Outline) Region

func (o Outline) Region() Region

Region returns the area the node covers, with the rings bounding it and the edge behind each straight run of them, in Plan.Frame.

func (Outline) String

func (o Outline) String() string

String renders the outline as a person reads it: what it is, what it covers and how much is written on it.

func (Outline) Subject

func (o Outline) Subject() ID

Subject returns the id of that node, which is what names the rings.

type OutsideRepositoryError

type OutsideRepositoryError struct {
	// Dir is the directory, as it was given.
	Dir string

	// Root is the top level it was measured against.
	Root string
}

OutsideRepositoryError is a directory the working tree does not hold.

func (OutsideRepositoryError) Error

func (e OutsideRepositoryError) Error() string

Error implements [error].

func (OutsideRepositoryError) Unwrap

func (e OutsideRepositoryError) Unwrap() error

Unwrap implements the interface errors.Is and errors.As walk.

It is ErrOutsideModel because it is the same mistake the engine reports under that name — a path named as part of something which does not contain it — seen from the repository rather than from the model root.

type OverrideError

type OverrideError struct {
	// Path is the file, as it was asked for.
	Path string

	// Err is why it was refused: [ErrOutsideModel] or [ErrNotAnEntityFile].
	Err error
}

OverrideError reports a `--file` which names somewhere a node may not be written.

It is the same judgement Tx.Insert makes of a target path, made before the model is loaded rather than after, so that an invocation naming an impossible file is answered as the wrong invocation it is rather than as a change which was refused.

func (OverrideError) Error

func (e OverrideError) Error() string

Error implements the [error] interface.

func (OverrideError) Unwrap

func (e OverrideError) Unwrap() error

Unwrap returns the underlying failure.

type Parameter

type Parameter struct {
	// Name is the tag the parameter was written with.
	Name string `json:"name"`

	// Type is what the check declares the parameter takes. It is empty where
	// the check declares no parameter by that name, which only a model the load
	// refused can hold.
	Type ParameterType `json:"type,omitempty"`

	// Values are the values written for it, one element per value and in the
	// order written: a float64 for a [ParameterReal], a bool for a
	// [ParameterBoolean], and for every other type a string holding the name,
	// the id or the text as written, unquoted.
	//
	// A value which is not an atom of the declared type is nil. Like an
	// undeclared name, that is only possible in a model the load refused, and a
	// nil is what says so rather than a guess at what was meant.
	Values []any `json:"values"`
}

Parameter is one parameter of a rule as data rather than as the text it was written in.

It is the same parameter Argument.String renders, read the way the check reads it: a caller wanting the tolerance or the predicate a rule runs with takes it from here instead of parsing an s-expression back out of a string.

It is one shape whatever the check declares. A parameter taking one value carries one, and a repeated one carries each of them, whether it was written as a sequence after its tag or as one parenthesised list — specification section 6.8 permits both, and they are one parameter.

Nothing a value names is resolved. A tolerance is its name here, and what it was decided against is Band.Floor's to report.

type ParameterType

type ParameterType string

ParameterType is the sort of datum one parameter of a check takes.

The set is closed and is what specification section 6.8 permits a parameter's value to be: an id, a name symbol — of a registry entry, or of one of the closed sets the engine compiles in — a real number, a string or a boolean. A check declares which of them each of its parameters takes, and that declaration is the whole of what validates an assertion: there is no second place saying what `(tolerance ...)` means.

const (
	ParameterID        ParameterType = "id"
	ParameterReal      ParameterType = "real"
	ParameterString    ParameterType = "string"
	ParameterBoolean   ParameterType = "boolean"
	ParameterKind      ParameterType = "kind"
	ParameterGeometry  ParameterType = "geometry"
	ParameterTypeName  ParameterType = "type"
	ParameterPredicate ParameterType = "predicate"
	ParameterFrame     ParameterType = "frame"
	ParameterTolerance ParameterType = "tolerance"
)

The sorts of datum a parameter takes. The four which name a registry entry — a type, a predicate, a frame and a tolerance — are resolved against the registry of their sort at load, which is what makes an assertion inspectable without evaluating it ([0011](docs/decisions/0011-assertions-are-named-parameterised-checks.md)).

func ParameterTypes

func ParameterTypes() []ParameterType

ParameterTypes returns the sorts of datum a check parameter may take.

type ParameterValueError

type ParameterValueError struct {
	// Check is the check the assertion names.
	Check string

	// Parameter is the parameter whose value is wrong.
	Parameter string

	// Want is the sort of datum it takes.
	Want ParameterType

	// Diagnostic is what a load reports for the same assertion written by hand,
	// which says what was found.
	Diagnostic Diagnostic
}

ParameterValueError is a parameter whose value is not the sort of datum the check declares it takes: a number where a tolerance name belongs, a predicate the registry does not declare, two values where one is taken.

func (ParameterValueError) Error

func (e ParameterValueError) Error() string

Error implements the [error] interface.

type ParseError

type ParseError struct {
	// Position is where the failure was reported.
	Position Position

	// Err is the failure the tokenizer or the parser reported.
	Err error
}

ParseError reports a failure from the underlying S-expression tokenizer or parser, placed in a file.

The underlying error already knows the line and the column; what it cannot know is which file it was reading or where that lands in the bytes. Err is kept rather than flattened into a message so that errors.As still reaches the tokenizer's and the parser's own types.

func (ParseError) Error

func (e ParseError) Error() string

Error implements the [error] interface.

func (ParseError) Unwrap

func (e ParseError) Unwrap() error

Unwrap returns the underlying failure.

type Piece

type Piece struct {
	// contains filtered or unexported fields
}

Piece is one connected part of a region: a ring bounding it and the rings taken out of it.

Both are needed and neither is derivable from the other. An operation over two rooms can leave two pieces which do not touch — a corridor cut in half by a lift core — and it can leave one piece with a courtyard in it. A result type which could only say "these points" would have to pick one of those to be unable to represent.

The rings are closed without repeating their first point at the end, the outer one runs anticlockwise seen from the region's own normal and the holes run clockwise.

func (Piece) Area

func (p Piece) Area() float64

Area returns what the piece encloses once its holes are taken away, in the square of the region's unit.

func (Piece) Holes

func (p Piece) Holes() [][]Point

Holes returns the rings taken out of the piece.

func (Piece) Outer

func (p Piece) Outer() []Point

Outer returns the ring bounding the piece.

type PlainValue

type PlainValue struct {
	// Predicate is the predicate it was written under.
	Predicate string

	// Value is what was written, read against the shape and the unit the
	// predicate declares exactly as a claim's value is. Its span is where the
	// whole form was written.
	Value Value
}

PlainValue is one plain value: the spelling specification section 6.5 gives a predicate the registry declares non-claim-bearing, written directly after the predicate's tag with nothing after it.

It is not a claim, and it is not a claim with its provenance left out. There is no id, no source, no method, no accuracy, no date and no rank on it, because the registry says the predicate carries none — which is what makes a fact such as the coordinate reference system a frame is rooted at something other than a measurement.

type Plan

type Plan struct {
	// contains filtered or unexported fields
}

Plan is a spatial node's contents drawn as rings, with the claims the invocation asked for anchored to what they are written on.

It is a query and not an export. Everything in it is read out of the model every time it is asked for — the rings out of the corners and the edges, the claims out of the files they were written in — so a plan cannot disagree with the model it was read from, and there is no artefact of it to go stale ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

It knows nothing about paper. There is no scale here, no sheet size, no title block, no leader and no text height, and there never will be: those are decisions about a drawing, and this is the answer a drawing is made from. The boundary is deliberate — the moment the engine knows where a leader goes, it owns a drawing convention, and drawing conventions are the thing every consuming project disagrees about.

Nothing here is resolved. Where two live claims compete under one predicate on one anchor, both come back: which of them a sheet prints is a decision about the sheet, and a query which picked one would make that decision invisibly and in the wrong place.

The zero Plan draws nothing, and every method below works on it.

func (Plan) Annotations

func (p Plan) Annotations() int

Annotations returns how many claims the plan reports in total.

The claims of an undrawn node are counted, because they were reported. They are facts somebody authored about something the subject contains, and the plan hands them back whether or not it could draw the thing they are written on.

func (Plan) Budget

func (p Plan) Budget() Budget

Budget returns the accumulated accuracy of the position claims which put every drawn corner where it is.

It is the accuracy of the *geometry* and not of the annotations. Each claim reported carries its own accuracy, because each is a separate statement about a separate quantity and combining a room's area with a wall's fire rating would produce a figure of nothing at all ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)). What this answers is the question a sheet has to carry: how well is the line I am drawing known.

func (Plan) ChordTolerance

func (p Plan) ChordTolerance() (Tolerance, bool)

ChordTolerance returns the declared tolerance the rings which bend were drawn to, and whether any of them bent at all.

A ring is a list of points, so a curve on a sheet is always an approximation of the wall; this is what says how good an approximation, and its absence is what says there was nothing to approximate. A plan which does not carry it and whose subject has curved walls is a sheet drawn straight through them, which Graph.UnreadArcs is what reports.

func (Plan) Deviation

func (p Plan) Deviation() float64

Deviation returns how far the worst segment of that drawing falls from the curve it stands in for, in Plan.Unit.

It is what was achieved rather than what was asked for, and is always within Plan.ChordTolerance.

func (Plan) Empty

func (p Plan) Empty() bool

Empty reports whether nothing the subject contains was drawn.

It is a state of the answer and not a failure. A storey nobody has outlined yet contains nothing drawable, which is the truthful answer to what it looks like in plan. It says nothing about Plan.Undrawn, which may well hold entries for a plan which is empty: a storey holding one room whose ring does not close draws nothing and has something to say about why.

func (Plan) Frame

func (p Plan) Frame() ID

Frame returns the coordinate frame every coordinate of the plan is in.

It is the frame the subject declares. Where the subject declares none it is the frame of the subject's first boundary loop, which is how Topology.RegionOf reads a node's frame, and where it has neither it is the root frame (Frames.Root). An outline read in any other frame is carried into this one, and Outline.DeclaredIn names the frame it came from.

func (Plan) Measured

func (p Plan) Measured() []MeasuredEdge

Measured returns the edges which bound no outline the plan drew, run between two corners it did, and carry at least one live claim under a predicate it was asked to annotate with — in edge id order.

A corner is a vertex of an edge in the boundary of a drawn outline, ring or open run alike, so under a Selection the corners are those of the outlines it selected: a measurement across a room nobody asked for is not on a sheet of the rooms somebody did. The ends were drawn, so the position claims behind them are already in Plan.Budget.

func (Plan) Outlines

func (p Plan) Outlines() []Outline

Outlines returns the contained nodes which were drawn, in id order.

The order is by id rather than by the order the walk read them, so that it is a property of what the model says rather than of which file each node happens to be written in. Moving a room between files leaves the answer identical.

func (Plan) Report

func (p Plan) Report() string

Report renders the plan with each outline under it, then each measured edge, and then everything it could not draw, which is the detail somebody reading a terminal asked for rather than the summary.

What was not drawn comes last rather than in id order among the outlines, because it is a different answer: the outlines are the sheet, and this is the list of what is missing from it.

func (Plan) String

func (p Plan) String() string

String renders the plan as a person reads it.

func (Plan) Subject

func (p Plan) Subject() ID

Subject returns the id of the node whose contents were drawn.

func (Plan) Tolerance

func (p Plan) Tolerance() Tolerance

Tolerance returns what corners were judged coincident against.

func (Plan) Undrawn

func (p Plan) Undrawn() []Undrawn

Undrawn returns the contained nodes which were not drawn, in id order, each with why it was not and with the claims written on it.

It and Plan.Outlines partition everything the subject contains: every node the walk reached is in exactly one of them, so a consumer which reads both has seen the whole of what the model puts inside that storey. Nothing is dropped, which is the property this exists for — a node omitted from an answer reads identically to a node the model does not hold, and a doorway missing from a sheet is not a difference anybody notices downstream.

func (Plan) Unit

func (p Plan) Unit() Unit

Unit returns the linear unit of that frame, which every coordinate in the rings is in and every area in the square of.

type Point

type Point [3]float64

Point is a position in one frame: three ordered components, expressed in that frame's one linear unit.

It carries no unit of its own, and that is not an omission. A frame declares exactly one linear unit ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)), so naming the frame a point is in names the unit it is in as well, and a point which carried a second one would be a point in two units.

The order of the components is significant and is never sorted.

type Policy

type Policy struct {
	// Default is the ruling for a kind Kinds does not name. The zero Ruling is
	// read as [RulingFailure]: a check added to the engine later is answered
	// rather than silently allowed by a policy written before it existed.
	Default Ruling

	// Kinds is the ruling for each kind it names.
	Kinds map[FindingKind]Ruling
}

Policy is what a review does about each kind of finding.

It is stated rather than implied, and it is data rather than a flag per check, so that "this repository fails on a disappearing id and warns on a wall which moved" is one readable value which a run reports back.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	base, _ := dfcad.LoadGraph("testdata/review/base")
	head, _ := dfcad.LoadGraph("testdata/review/head")

	// A wall which moved because the room was surveyed again is a change
	// somebody meant. Saying so is a policy, stated once, rather than not
	// running the check.
	policy := dfcad.DefaultPolicy().With(dfcad.FindingBoundaryMoved, dfcad.RulingIgnored)

	for _, finding := range dfcad.Review(base, head, policy, nil) {
		// The finding is still here. A check which was switched off silently is
		// one nobody remembers is off, so what the policy acknowledged is
		// readable from the run which acknowledged it.
		fmt.Println(finding.Ruling, finding.Kind)
	}

	fmt.Println(policy.Ruling(dfcad.FindingIDDisappeared), "is still what an id which vanished means")

}
Output:
ignored boundary-moved-without-claim
failure is still what an id which vanished means

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy is the policy a review runs under when nobody stated one.

Two of the three fail. An id which disappeared and a claim retracted with nothing in its place are both breaches of a rule the model is built on rather than judgment calls, and each takes references or evidence with it.

A boundary which moved warns, because it is the one of the three which is routinely legitimate: a corner measured again genuinely moves, and the check cannot see the survey which justified it. Warning is what makes it a question for the reviewer rather than a wall for the author.

func (Policy) Ruling

func (p Policy) Ruling(kind FindingKind) Ruling

Ruling is what the policy says about one kind.

func (Policy) With

func (p Policy) With(kind FindingKind, ruling Ruling) Policy

With is the policy with one kind ruled differently, and the receiver unchanged.

type Position

type Position struct {
	// Path is the file this position is in, exactly as the loader reached it.
	Path string `json:"path"`

	// Line is the 1-based line number.
	Line int `json:"line"`

	// Column is the 1-based byte offset into Line.
	Column int `json:"column"`

	// Offset is the 0-based byte offset into the file.
	Offset int `json:"offset"`
}

Position is one point in one source file.

Line and Column are 1-based. Column is a byte offset into its line rather than a count of characters, so a multi-byte rune advances it by its encoded width; that is the convention the underlying S-expression tokenizer reports and it is kept unchanged here. Offset is a 0-based byte offset into the whole file.

Both spellings of the same point are carried because both are needed and neither is cheap to recover from the other once the source bytes are gone: a person reads path:line:column, and a tool slicing the source for a caret or a span of text wants the offset.

func (Position) Span

func (p Position) Span() Span

Span returns the empty span at the position, which is what something with no source text of its own — a token that is missing, the end of the file — points at.

func (Position) String

func (p Position) String() string

String renders the position as path:line:column, which is the spelling every editor and every terminal already knows how to jump to.

type Positions

type Positions map[ID]Value

Positions is where the vertices of a model are: the resolved value of each vertex's position, keyed by the vertex's id.

It is supplied rather than read, because which predicate carries a position is vocabulary the consuming repository owns and not something the engine knows ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)). A repository which spells it `position` resolves that predicate for every vertex and hands the result here; one which spells it something else spells it something else, and nothing in this file changes.

A vertex which is absent is a vertex with no position anything could resolve — none was claimed, or the claims tie and the tie is unbroken. That is a state and not a failure: Topology.Assemble measures what it can and says so where it cannot, rather than inventing a coordinate to measure against.

type Predicate

type Predicate struct {
	// Name is the predicate name, which is also the tag a claim under it is
	// written with.
	Name string

	// Unit is the unit its values are expressed in. Empty means the predicate
	// is non-dimensional.
	Unit Unit

	// Shape is the shape its values take.
	Shape Shape

	// Dimension is how many components a coordinate value has. Zero for every
	// other shape.
	Dimension int

	// ClaimBearing reports whether the predicate takes a claim rather than a
	// plain value. It defaults to true, so opting out is something somebody
	// writes down and a reviewer reads.
	ClaimBearing bool

	// Strict reports whether an ambiguous resolution of this predicate is a
	// failure rather than a report. It defaults to false.
	Strict bool

	// Description is free text. Empty when it was not written.
	Description string

	// Span is where the declaration was written.
	Span Span
}

Predicate is one declared claim predicate, per specification section 7.4.

type Project

type Project struct {
	// Label is the project's name for a person reading it. Empty when it was
	// not written.
	Label string

	// GlobalIDNamespace is the URL every IFC GlobalId is derived from
	// ([0004](docs/decisions/0004-globalid-derives-from-a-pinned-namespace.md)),
	// by [DeriveGlobalID]. Changing it re-identifies every node in the model:
	// every downstream system holding a previously exported identifier sees the
	// whole model deleted and re-created, and the old values can only be
	// recomputed from the old URL.
	GlobalIDNamespace string

	// Description is free text. Empty when it was not written.
	Description string

	// Span is where the declaration was written.
	Span Span
}

Project is the one project declaration a model carries, per specification section 7.1.

type Rank

type Rank string

Rank is how a claim stands relative to the other claims about the same thing, per specification section 6.5.

The set is closed at two members and is compiled in. There is no `preferred`, no numeric priority, no weight and no override: a claim cannot be promoted above its peers, and where two normal claims disagree the disagreement stays visible until one of them is deprecated or corrected ([0007](docs/decisions/0007-rank-is-closed.md)).

const (
	RankNormal     Rank = "normal"
	RankDeprecated Rank = "deprecated"
)

The ranks, in the order specification section 6.5 lists them.

func Ranks

func Ranks() []Rank

Ranks returns the closed set of claim ranks, in specification order.

type Reason

type Reason string

Reason is which step of the resolution rule produced an outcome.

It exists because an answer which cannot say why it is the answer is a number again. "24.2 m²" and "24.2 m², because it is the most accurate of three claims" are different things to act on: the first invites a re-measurement nobody needed, and the second says which claim to go and read.

The set is closed and mirrors Claims.Resolve's rule step for step, so a caller branching on it is branching on the rule rather than on a message.

const (
	// ReasonUnclaimed is a subject with no live claim under the predicate at
	// all. It is what the zero [Resolution] reports, and it is not the same as
	// an unranked one: nothing was said, rather than nothing rankable.
	ReasonUnclaimed Reason = "unclaimed"

	// ReasonOnly is the one live claim under the predicate, which wins by there
	// being nothing to compare it against.
	ReasonOnly Reason = "only"

	// ReasonAccuracy is a claim whose accuracy is smaller than that of every
	// claim it could be compared against, which is the criterion.
	ReasonAccuracy Reason = "accuracy"

	// ReasonRecency is a claim which tied on accuracy and carried the later
	// date. Recency is the tiebreaker and never the criterion, which is why it
	// is a reason of its own rather than folded into the one above.
	ReasonRecency Reason = "recency"

	// ReasonUnranked is the one live claim under a predicate nothing rankable
	// was said about. It is still what the model says and is still the answer;
	// what it is not is an answer the rule chose.
	ReasonUnranked Reason = "unranked"

	// ReasonAmbiguous is more than one claim the rule cannot separate, whether
	// because they are equally accurate and equally recent, because their
	// accuracies are in units nothing converts between, or because nothing
	// rankable was said about any of them.
	ReasonAmbiguous Reason = "ambiguous"
)

The reasons, one per step of the rule.

type Reference

type Reference struct {
	// From is the entity which made the reference.
	From ID

	// Relation is the child it was written as — `within`, `member-of`,
	// `boundary`, `superseded-by`, `vertices`, `edges` or `backed-by` — which is
	// what says how the two things are related and what has to change for the
	// reference to go away.
	Relation string

	// Span is where the entity making the reference is named, which is what a
	// message about it points at.
	Span Span
}

Reference is one place the model names an id from somewhere else.

It is what "who points at this" means: the entity which wrote the reference, the relation it wrote it as, and where that entity is defined. A caller refusing to retire something still referenced reports these, because "still referenced" without saying by what leaves the author reading every file to find out.

type ReferencedError

type ReferencedError struct {
	// ID is the node which was being retired.
	ID ID

	// By is every reference to it, in the order the walk reached the entities
	// which made them.
	By []Reference
}

ReferencedError reports a node which other things still point at.

Retiring one would leave every reference below pointing at something which says it stopped existing, which is a model whose answers depend on which of the two ends of each reference the reader believes. Either those references are redirected to whatever replaced it — which is what a replacement is for — or they are changed first and the retirement reissued.

func (ReferencedError) Error

func (e ReferencedError) Error() string

Error implements the [error] interface.

Every referrer is named rather than counted: "still referenced" without saying by what leaves the author reading every file in the model to find out.

type Region

type Region struct {
	// contains filtered or unexported fields
}

Region is the area a thing covers, as a plane figure operations can be run over.

It is derived from the graph and never written back to it ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)): a region is read out of the loops bounding a node every time it is asked for, so an offset or an overlay cannot disagree with the geometry it was computed from.

Everything about it is in one frame and one unit, and nothing here converts ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)). Two regions in different frames are refused rather than combined; Region.In is how one is brought into the other's frame, and it is a step a caller takes deliberately because the transform between two frames is a measurement with an accuracy of its own and not a detail an operation should apply behind a caller's back.

Every operation carries the accuracy of the position claims the operands were read from ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)), so an overlap comes back knowing how well the corners which decided it were known.

The zero Region covers nothing, is in no frame, and every operation over it reports that rather than answering.

func (Region) Area

func (r Region) Area() float64

Area returns the total area covered, holes taken away, in the square of Region.Unit.

func (Region) Bounds

func (r Region) Bounds() (Box, bool)

Bounds returns the axis-aligned bounding box of everything the region covers, and whether there was anything to bound.

func (Region) Budget

func (r Region) Budget() Budget

Budget returns the accumulated accuracy of the position claims every operand behind the region was read from.

It accumulates across operations: the intersection of two rooms carries the claims of both rooms' corners, and a region brought into another frame carries the accuracy of the transform which brought it there. A term shared between them — one georeference fit behind every indoor corner — is counted once, which is Budget's own arithmetic.

func (Region) Buffer

func (r Region) Buffer(distance float64) (Region, []Diagnostic)

Buffer returns everything within a distance of the region, or everything far enough inside it, according to the sign of the distance.

An outward offset — a positive distance — is the setback question: everything within three metres of this boundary. An inward offset is the clearance one: everything at least three metres inside it. Both are one construction, which is why they cannot disagree at the corners: the boundary is thickened by the distance, and an outward offset adds that thickening to the region while an inward one takes it away.

An inward offset which eats the region returns a region covering nothing. That is the answer — a corridor 1.6 m wide has nothing 1 m clear of both walls — and it is why the collapse is not reported as a failure. What is never returned is the inside-out shape the arithmetic of offsetting each edge on its own produces when the edges cross over each other.

Corners are rounded, and the rounding follows the circle to within the declared tolerance rather than to a segment count written down here.

An offset smaller than that tolerance is refused. It is a distance the project has said it cannot tell from zero, and an answer to it would be a boundary moved by less than the uncertainty of where the boundary is.

Example

ExampleRegion_Buffer offsets a floor plate outwards and inwards, which are the setback question and the clearance one and are the same construction run either way round.

The plate has a courtyard in it, and both offsets do the right thing to it without anything having to say which of the two rings is the hole: growing the plate shrinks the courtyard, and shrinking the plate grows it.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/overlay/shapes"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	node, _ := nodes.Node("site:S-04")
	plate, _ := topology.RegionOf(node, boundaries, survey)

	fmt.Println(plate)

	for _, distance := range []float64{1, -1} {
		offset, _ := plate.Buffer(distance)

		// One piece with one hole either way round. Growing the plate by a metre
		// shrinks the courtyard by one, and shrinking the plate by a metre grows
		// the courtyard by one — which is the same offset applied to the whole of
		// the boundary rather than two rules about two rings.
		bounds, _ := offset.Bounds()
		fmt.Printf("offset by %g m: %.2f m², %d hole, reaching %s\n",
			distance, offset.Area(), len(offset.Pieces()[0].Holes()), bounds)
	}

	// An inward offset which eats a shape returns a region covering nothing,
	// which is the answer rather than a failure: a corridor 400 mm wide has
	// nothing 300 mm clear of both of its walls.
	corridor, _ := nodes.Node("site:S-07")
	thin, _ := topology.RegionOf(corridor, boundaries, survey)

	collapsed, _ := thin.Buffer(-0.3)
	fmt.Println(collapsed.Empty(), collapsed.Area())

}
Output:
site:S-04: area 84.0 m², 1 piece, 1 hole
offset by 1 m: 139.12 m², 1 hole, reaching (9.0 -1.0 0.0) to (21.0 11.0 0.0) m
offset by -1 m: 28.88 m², 1 hole, reaching (11.0 1.0 0.0) to (19.0 9.0 0.0) m
true 0

func (Region) ChordTolerance

func (r Region) ChordTolerance() (Tolerance, bool)

ChordTolerance returns the declared tolerance the rings which bend were drawn to on the way to reading the region, and whether any of them was drawn at all.

It travels with the region because the region is an approximation of the boundary wherever it is true, and an outline which does not say how closely it follows the curve it came from is one nobody downstream can judge. A region with nothing curved in it is not an approximation of anything and says so by reporting none.

func (Region) Containment

func (r Region) Containment(other Region) (Containment, []Diagnostic)

Containment returns how another region sits against this one.

It is computed from the operations above rather than beside them, so it cannot disagree with them: what the two share, what this one has that the other does not and what the other has that this one does not are three overlays, and which of the six states holds follows from which of them cover anything.

Boundary-touching is defined rather than left to fall out. Two regions which meet along a boundary and enclose nothing between them are ContainmentTouching and never ContainmentOverlapping — a party wall is not an overlap. A region inside another and touching it from the inside is ContainmentInside, because touching the inside of a boundary is not crossing it. Both are judged at the declared tolerance, so two corners closer together than the project can survey them are the same corner here too.

func (Region) Deviation

func (r Region) Deviation() float64

Deviation returns how far the worst segment of that drawing falls from the curve it stands in for, in Region.Unit.

It is what was achieved rather than what was asked for, and is always within Region.ChordTolerance: a curve is divided into a whole number of segments, so an arc which needs two and a bit gets three and follows the curve more closely than it had to.

func (Region) Difference

func (r Region) Difference(other Region) (Region, []Diagnostic)

Difference returns everything this region covers and the other does not.

It is not commutative and does not pretend to be: a room less a desk is a room with a gap in it and a desk less a room is nothing.

func (Region) Empty

func (r Region) Empty() bool

Empty reports whether the region covers nothing.

func (Region) Frame

func (r Region) Frame() ID

Frame returns the frame the region is declared in.

func (Region) In

func (r Region) In(target ID, frames *Frames) (Region, []Diagnostic)

In returns the region expressed in another frame.

It is the explicit step operations refuse to take on a caller's behalf. Two regions in different frames are not combined until one of them has been brought into the other's frame here, because the transform between two frames is a measurement with an accuracy of its own ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)) — and an operation which applied it quietly would produce an answer whose budget was narrower than what it rests on.

The accuracy of the transform is accumulated into the result's budget, so a clearance computed after a change of frame knows what the change of frame cost it.

The target frame has to be in the unit the tolerance was declared in. A region moved into a frame written in millimetres is judged against a tolerance in metres by a factor of a thousand, and there is no conversion here which would make that right ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

A region which is a Region.Location rather than an area is carried the same way and pays the same accuracy for it, and so is an open run: its corners are carried run by run and come back in the rings and the order they were walked in, each attributed to the operation rather than to an edge whose coordinates are in the other frame. What does not apply to one is the rest of the above: a tolerance is what corners are judged coincident against and a plane is what rings are nested in, and a coordinate has neither.

func (Region) Intersect

func (r Region) Intersect(other Region) (Region, []Diagnostic)

Intersect returns everything both regions cover.

Two regions which meet only along a boundary intersect in nothing: a shared wall line has no area, and reporting it as an overlap would turn every pair of adjacent rooms into a conflict. Region.Containment is what tells that case apart from two regions which are nowhere near each other.

It is commutative in the same sense Region.Union is.

func (Region) Location

func (r Region) Location() (Point, bool)

Location returns where a node drawn as a point sits, and whether the model placed it there at all.

It is the whole shape of such a node. A panel, a survey monument and a receptacle each have a position and no extent, so the region covers nothing and Region.Empty is true for one — which is why the second return value is here rather than left to be inferred from a coordinate of nought, a place every model has and most devices are not at.

It is absent for every region read from loops and for every region an operation over an area produced. A shape which covers an area is located by its corners, and one point standing for it would be a centroid this does not claim to be. Region.In is the exception, and is not one of those operations: carrying a thing into another frame moves it and does not change what it is, so a point goes in a point and comes out a point.

func (Region) Pieces

func (r Region) Pieces() []Piece

Pieces returns the connected parts the region covers.

There may be none, which is a region covering nothing rather than an error — an inward offset which collapsed a room comes back this way, and so does the intersection of two rooms which do not meet.

func (Region) Segments

func (r Region) Segments() []BoundarySegment

Segments returns the straight runs of the region's boundary, in the order the rings are traversed, each saying what produced it.

It is the pairing the boundary was assembled from rather than a correspondence worked back out of coordinates. A run of a region read from a model is the edge it was written as, or a chord of the drawing of that edge's arc, and BoundarySegment.Reversed says which way round the loop ran through it. That is what lets a ring be attributed back to the model it came from: a party wall can be named, an element backing an edge can be carried onto the segment that edge produced, and a claim written on an edge reaches the run it is about.

A region an operation produced attributes none of its boundary, and says so: every run of it comes back as SegmentOriginOperation with no edge. The boundary of an intersection runs partly along each operand and partly along where they cross, and there is no edge which is the second kind — so the answer is that an operation put it there, and not the nearest edge which nearly did.

The runs are derived from the region every time they are asked for and are stored nowhere else ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

Example

ExampleRegion_Segments attributes a boundary back to the model it came from: which edge produced each straight run of it, which way round the loop ran through that edge, and what produced a run no edge did.

It is what an exporter needs and what a polygon on its own cannot say. A ring of coordinates can be drawn; it cannot say which segment is the party wall, which element backs it, or which claim was written about it. The pairing is known where the boundary is assembled, so it is reported from there rather than re-derived downstream by matching coordinates.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/overlay/shapes"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	node, _ := nodes.Node("site:S-01")
	room, _ := topology.RegionOf(node, boundaries, survey)

	// Every run of the boundary of a region read from the model is an edge
	// somebody wrote, and says which ring of the boundary it belongs to and
	// which way round the loop ran through it.
	for _, segment := range room.Segments() {
		fmt.Printf("ring %d: %s\n", segment.Ring(), segment)
	}

	// An operation attributes none of its boundary, and says so rather than
	// naming the edge which nearly produced a run: an offset corner is where the
	// offset put it and no edge of the model runs there.
	offset, _ := room.Buffer(1)

	origins := map[dfcad.SegmentOrigin]int{}
	for _, segment := range offset.Segments() {
		origins[segment.Origin()]++
	}

	fmt.Printf("offset: %d runs, all %s, none of them an edge\n",
		origins[dfcad.SegmentOriginOperation], dfcad.SegmentOriginOperation)

}
Output:
ring 0: (0.0 0.0 0.0) to (4.0 0.0 0.0): edge geom:E-011, forwards
ring 0: (4.0 0.0 0.0) to (4.0 3.0 0.0): edge geom:E-012, forwards
ring 0: (4.0 3.0 0.0) to (0.0 3.0 0.0): edge geom:E-013, forwards
ring 0: (0.0 3.0 0.0) to (0.0 0.0 0.0): edge geom:E-014, forwards
offset: 36 runs, all operation, none of them an edge

func (Region) String

func (r Region) String() string

String writes what the region covers, with its unit.

func (Region) Subject

func (r Region) Subject() ID

Subject returns the id of the node the region was read from.

func (Region) Tolerance

func (r Region) Tolerance() Tolerance

Tolerance returns the declared tolerance the region's coincidence and snapping are judged against.

func (Region) Union

func (r Region) Union(other Region) (Region, []Diagnostic)

Union returns everything either region covers.

It is commutative, and not merely in the sense that the areas agree: the pieces come back in the same order with their rings written from the same corner whichever operand it was called on, because an answer which depended on that would be one a caller had to normalise before comparing.

func (Region) Unit

func (r Region) Unit() Unit

Unit returns the linear unit of that frame, which every figure here is in and which an area is in the square of.

type RegionTessellation

type RegionTessellation struct {
	// contains filtered or unexported fields
}

RegionTessellation is the area a semantic node covers with every curve in its boundary replaced by the straight segments which stand in for it, together with the chord tolerance that was decided to and the deviation achieved.

It is Tessellation one dimension up. An edge and a loop each become one run of points; a region becomes a set of rings — an outer ring per connected part and the rings taken out of it — because that is what a region is, and a result which could only carry one ring would have to be unable to represent a floor plate with a courtyard in it.

RegionTessellation.Region is the drawn figure as an ordinary Region, and it is the point of the type. Every operation over regions is over straight segments, so a curved boundary has nothing they can be run against until it is drawn; once it is, the result is the same kind of value a straight boundary reads as and goes the same places. A region with nothing curved in it comes back exactly as Topology.RegionOf reads it, so a caller has one path rather than a curved one and a straight one.

Nothing here is ever written back ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). The arcs in the model are untouched and stay exact; this is computed at the moment something needs straight lines and thrown away after.

The zero RegionTessellation covers nothing and was drawn to nothing, which is what tessellating a node with no outline yields.

func (RegionTessellation) Area

func (t RegionTessellation) Area() float64

Area returns the total area the drawn figure covers, holes taken away, in the square of RegionTessellation.Unit.

It is the area of the segments and not of the curves, which is what makes it the wrong number to report a region's size with: Topology.MeasureRegion computes that from the arcs themselves and is exact. This is what the drawn figure encloses, which is what a consumer of the drawn figure will compute.

func (RegionTessellation) Budget

func (t RegionTessellation) Budget() Budget

Budget returns the accumulated accuracy of the position claims behind it.

func (RegionTessellation) ChordTolerance

func (t RegionTessellation) ChordTolerance() Tolerance

ChordTolerance returns the declared tolerance the curves were drawn to: how far a segment standing in for a curve was allowed to fall from it.

It is a tolerance the registry declares and never a number this package chose ([0012](docs/decisions/0012-tolerances-are-registry-data.md)), for the reason Tessellation.ChordTolerance is.

func (RegionTessellation) Deviation

func (t RegionTessellation) Deviation() float64

Deviation returns the furthest any segment falls from the curve it stands in for, in RegionTessellation.Unit.

It is what was achieved rather than what was asked for, and is always within RegionTessellation.ChordTolerance. A region with nothing curved in it deviates from itself by nothing.

func (RegionTessellation) Empty

func (t RegionTessellation) Empty() bool

Empty reports whether the drawn figure covers nothing.

func (RegionTessellation) Frame

func (t RegionTessellation) Frame() ID

Frame returns the frame it was drawn in.

func (RegionTessellation) Pieces

func (t RegionTessellation) Pieces() []Piece

Pieces returns the connected parts the drawn figure covers, each with the ring bounding it and the rings taken out of it.

The outer ring of a piece runs one way and its holes the other, exactly as they do for a region which was never drawn, so the two are interchangeable downstream.

func (RegionTessellation) Region

func (t RegionTessellation) Region() Region

Region returns the drawn figure as an ordinary region, which every operation over regions takes.

func (RegionTessellation) Segments

func (t RegionTessellation) Segments() []BoundarySegment

Segments returns the straight runs of the drawn boundary, each naming the edge it was written as or whose arc it stands in for.

A chord of a drawn arc comes back as SegmentOriginArc and names the edge which bends along it, so a drawing is attributable back to the model corner by corner rather than arriving as anonymous coordinates. It is not the edge, and the origin is what says so: the chord is as close to the curve as the tolerance the drawing was made to allowed, and no closer.

func (RegionTessellation) String

func (t RegionTessellation) String() string

String writes how much of a shape the drawing came to and how closely it follows the boundary it was drawn from.

func (RegionTessellation) Subject

func (t RegionTessellation) Subject() ID

Subject returns the id of the node whose boundary was drawn.

func (RegionTessellation) Unit

func (t RegionTessellation) Unit() Unit

Unit returns the linear unit of that frame, which its points and its deviation are in and which its area is in the square of.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is the vocabulary one consuming repository declares: its types, claim predicates, frames, id namespaces, tolerances and file routing rules, plus the one project declaration.

It is the whole registry set of a model rather than one file's worth, and it is queryable as a whole so that every layer above validates against it instead of reading registry files again for itself. A second reading would be a second answer to "is this type declared", and the two would disagree the first time a file moved.

A Registry is read-only once loaded. The zero value declares nothing, which is the same thing an empty source tree yields, and every query below works on it.

func (*Registry) Declares

func (r *Registry) Declares(sort Sort, name string) bool

Declares reports whether the registry declares name in the given sort.

It is the question every layer above asks of a name it did not mint — a node's type, a claim's predicate, an id's namespace, a check's tolerance parameter — and it is one method rather than five so that a caller holding a Sort does not switch on it. An unknown sort declares nothing.

func (*Registry) Destination

func (r *Registry) Destination(subject Subject) (Destination, error)

Destination returns the file a new node belongs in, per the routing rules the registry declares.

Exactly one rule must match. A node matched by none and a node matched by several are both a RoutingError naming the node and the rules consulted, and neither is resolved by picking one — a rule chosen by being written first, or by being the most specific, is a filing decision made by the tool and visible in nothing the author wrote. Making both a refusal is what keeps the registry the whole answer to where things go: rules which overlap are made disjoint, and a node nothing covers gets a rule.

The path which comes back is relative to the model root. Turning it into a file is Tx.Insert's job, which resolves it against the root the transaction holds.

Example

ExampleRegistry_Destination routes a new node to the file the registry says it belongs in, and shows what happens to one the rules do not cover.

package main

import (
	"errors"
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	registry, diags := dfcad.LoadRegistry("testdata/graph/valid")
	for _, diagnostic := range diags {
		fmt.Println(diagnostic)
	}

	// A node the rules place: one rule matches it, and the destination says
	// which, so that "where did this go" and "why there" are one answer.
	destination, err := registry.Destination(dfcad.Subject{
		ID:   "site:S-104",
		Kind: dfcad.KindSpace,
		Type: "MeetingRoom",
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(destination.Path, "by rule", destination.Rule)

	// A geometric node carries neither a kind nor a type, so it is routed by a
	// rule which matches on its namespace alone.
	geometry, err := registry.Destination(dfcad.Subject{ID: "geom:V-07"})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(geometry.Path, "by rule", geometry.Rule)

	// A node no rule covers is refused rather than filed somewhere plausible.
	// The refusal names it and every rule there was, because the fix is a rule
	// and a fix nobody is told to make is one nobody makes.
	_, err = registry.Destination(dfcad.Subject{
		ID:   "site:P-01",
		Kind: dfcad.KindElement,
		Type: "Partition",
	})

	var unplaced dfcad.RoutingError
	if errors.As(err, &unplaced) {
		fmt.Println("ambiguous:", unplaced.Ambiguous())
		for _, rule := range unplaced.Consulted {
			fmt.Println(" consulted", rule.Name, "->", rule.File)
		}
	}

}
Output:
entities/site.dfc by rule rooms
entities/geometry.dfc by rule geometry
ambiguous: false
 consulted corridors -> entities/circulation.dfc
 consulted geometry -> entities/geometry.dfc
 consulted rooms -> entities/site.dfc

func (*Registry) Frame

func (r *Registry) Frame(id ID) (Frame, bool)

Frame returns the declaration of a frame, and whether it is declared.

func (*Registry) Frames

func (r *Registry) Frames() iter.Seq[Frame]

Frames iterates the declared frames in id order.

func (*Registry) GlobalID

func (r *Registry) GlobalID(id ID) (GlobalID, bool)

GlobalID returns the GlobalID of id under the URL the model's project declaration pins, and whether the model pinned one.

A model with no project declaration, and a model whose declaration does not pin a URL a GlobalID could derive from, are both load errors already — so the false here is what a caller holding the registry of a load which failed gets. It is the answer rather than a derivation from the empty URL, which would be 22 characters indistinguishable from any other GlobalID, stable across runs, and a stable identifier for a model nobody pinned. A registry which recorded a project whose `globalid-namespace` was not a URL holds the empty string for it, so absent and unusable are the same case here on purpose.

Any ID derives, including a geometric node's. What IFC gives a GlobalId to is IFC's question, and answering it here would be this package holding an opinion about an exporter which does not exist yet ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	// The URL is pinned in the registry, and the GlobalId falls out of it and
	// the node id. Nothing is stored, nothing is authored, and the same two
	// inputs produce the same 22 characters on every machine.
	registry, _ := dfcad.LoadRegistry("testdata/model")

	globalID, ok := registry.GlobalID("site:S-101")
	if !ok {
		fmt.Println("no project declaration to derive from")
		return
	}

	project, _ := registry.Project()

	// The project namespace UUID is the first half of the derivation, so
	// anybody holding the URL can recompute it and check the arithmetic.
	fmt.Println(dfcad.DeriveGlobalIDNamespace(project.GlobalIDNamespace))
	fmt.Println(globalID)

	// Renaming the room would change its label and nothing here.
	fmt.Println(globalID == dfcad.DeriveGlobalID(project.GlobalIDNamespace, "site:S-101"))

}
Output:
bf22703b-ecd8-5c1f-929c-021883f35524
2GX9NtsjvT$PykCkbFuEnE
true

func (*Registry) Names

func (r *Registry) Names(sort Sort) []string

Names returns every name declared in the given sort, in order. An unknown sort declares nothing.

func (*Registry) Namespace

func (r *Registry) Namespace(name string) (Namespace, bool)

Namespace returns the declaration of an id namespace, and whether it is declared.

Every query below tolerates a nil registry, answering that nothing is declared. A caller which did not read the diagnostics of a load which failed outright is holding one, and "nothing is declared" is both true of it and the answer which produces a diagnostic rather than a panic.

func (*Registry) Namespaces

func (r *Registry) Namespaces() iter.Seq[Namespace]

Namespaces iterates the declared id namespaces in name order.

Every iterator here is ordered rather than in map order, because output built from one is meant to diff against the last run's.

func (*Registry) Predicate

func (r *Registry) Predicate(name string) (Predicate, bool)

Predicate returns the declaration of a claim predicate, and whether it is declared.

func (*Registry) Predicates

func (r *Registry) Predicates() iter.Seq[Predicate]

Predicates iterates the declared claim predicates in name order.

func (*Registry) Project

func (r *Registry) Project() (Project, bool)

Project returns the model's project declaration, and whether it has one.

func (*Registry) Route

func (r *Registry) Route(name string) (Route, bool)

Route returns the declaration of a file routing rule, and whether it is declared.

func (*Registry) Routes

func (r *Registry) Routes() iter.Seq[Route]

Routes iterates the declared file routing rules in name order.

Name order rather than the order they were written, for the reason every other iterator here is ordered: a rule which matches is chosen by matching and not by position, so nothing about routing depends on the order, and a listing which did would change when a registry file moved.

func (*Registry) Tolerance

func (r *Registry) Tolerance(name string) (Tolerance, bool)

Tolerance returns the declaration of a named tolerance, and whether it is declared.

func (*Registry) Tolerances

func (r *Registry) Tolerances() iter.Seq[Tolerance]

Tolerances iterates the declared named tolerances in name order.

func (*Registry) Type

func (r *Registry) Type(name string) (Type, bool)

Type returns the declaration of a node type, and whether it is declared.

func (*Registry) Types

func (r *Registry) Types() iter.Seq[Type]

Types iterates the declared node types in name order.

func (*Registry) Undeclared

func (r *Registry) Undeclared(sort Sort, name string, span Span) Diagnostic

Undeclared is the diagnostic for a name written where the registry declares no entry of that sort.

It lives here rather than at each call site because the answer to "there is no such type" is the same wherever the type was written, and because only the registry can say what is declared instead. The hint offers the nearest declared name when one is close enough to be a misspelling of what was written, and otherwise lists the declared set, which is what makes the diagnostic actionable on an empty registry: the set is empty, and saying so is the whole of the answer.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	const path = "entities/level-1.dfc"

	source := "(node site:S-101 (kind Space) (type MeetingRoom))\n"

	file, err := dfcad.Parse(path, strings.NewReader(source))
	if err != nil {
		fmt.Println(err)
		return
	}

	// A repository which has not written its registry yet loads, and every node
	// in it is invalid against a registry which declares nothing.
	registry, _ := dfcad.LoadRegistry("testdata/registry/empty")

	written := file.Nodes[0].Children[3].Children[1]
	undeclared := registry.Undeclared(dfcad.SortType, "MeetingRoom", written.Span)

	if err := undeclared.Render(os.Stdout, dfcad.Sources{path: []byte(source)}); err != nil {
		fmt.Println(err)
	}

}
Output:
entities/level-1.dfc:1:37: error: expected a declared type, found MeetingRoom, which no registry file declares
1 | (node site:S-101 (kind Space) (type MeetingRoom))
  |                                     ^^^^^^^^^^^
  = hint: no type is declared; a registry file declares one with (type ...)

type RelateOperation

type RelateOperation struct {
	// ID is the node being related.
	ID string `json:"id"`

	// Within is the node which strictly contains it, and is empty where the
	// operation says nothing about containment. A node is contained by one
	// other node, so writing one replaces whatever parent it had.
	Within string `json:"within,omitempty"`

	// MemberOf are zones it is grouped into, added to whatever memberships it
	// already declares.
	MemberOf []string `json:"memberOf,omitempty"`

	// Boundary are loops which bound it, added the same way.
	Boundary []string `json:"boundary,omitempty"`
}

RelateOperation writes the references a node makes to the rest of the model: what contains it, which zones it is grouped into, and which loops bound it. It is `relate`.

func (*RelateOperation) Name

func (o *RelateOperation) Name() string

Name implements Operation.

type Related struct {
	// contains filtered or unexported fields
}

Related is one node a traversal reached, together with the relation which reached it.

It is a value rather than a bare node so that the label travels with the result. A traversal which handed back nodes would leave the caller to remember which question it asked, and a wall belonging to two rooms and a circuit belonging to no room are exactly the cases where remembering wrong is easy.

The zero value holds no node and no relation, which no traversal yields.

func (Related) Depth

func (r Related) Depth() int

Depth returns how many steps of that relation the traversal took to reach it.

A traversal which follows one reference answers 1, which is the node next to the one the question was asked about. A walk answers how far out it had got, so that a caller can say "the storey, two levels up" rather than counting the results and hoping the order it read them in meant something.

The bounded walks go level by level, so what they report is the fewest steps there are — a node a walk could reach two ways is reached at the depth of the shorter of them, once.

func (Related) Node

func (r Related) Node() *SemanticNode

Node returns the node the traversal reached.

func (Related) Relation

func (r Related) Relation() Relation

Relation returns which relation reached it, which is what says whether the result means physical enclosure or arbitrary grouping.

type RelatedLocation

type RelatedLocation struct {
	// Span is the source text this location is about.
	Span Span `json:"span"`

	// Message says why this location is related — "first defined here", not a
	// repeat of the diagnostic's own message.
	Message string `json:"message"`
}

RelatedLocation is a second place a diagnostic points at, with its own message saying why it is being pointed at.

"already defined" is only actionable when it can show both definitions, and a diagnostic that could name just one position could not say that at all.

type Relation

type Relation string

Relation is which relation produced a traversal result.

The two the format writes between semantic nodes are not interchangeable and are never collapsed into one. Containment is physical enclosure and nests strictly: a node is written inside at most one other, and following those references reaches a root. Membership is arbitrary grouping and is many to many: a node is written into any number of zones, and a zone holds any number of nodes.

Every traversal in this package yields its results labelled with the relation which produced them, because a caller which cannot tell them apart cannot trust any of them. "The things in this storey" and "the things grouped with this storey" are different questions, and a result which answers one while looking like the other is worse than no result at all.

const (
	// RelationContainment is the relation `(within <node-id>)` writes: the node
	// which strictly contains this one.
	RelationContainment Relation = "containment"

	// RelationMembership is the relation `(member-of <zone-id>)` writes: a zone
	// this node is grouped into.
	RelationMembership Relation = "membership"

	// RelationBoundary is the relation `(boundary <loop-id>)` writes, followed
	// through the loop to what it is assembled from: the edges a region's
	// outline is made of. It crosses between the two families rather than
	// joining two semantic nodes, which is why what it reaches is an [Edge]
	// rather than a node ([0001](docs/decisions/0001-two-node-families.md)).
	RelationBoundary Relation = "boundary"

	// RelationAdjacency is the relation nothing writes: two regions are adjacent
	// when an edge is part of the boundary of both. It is computed from the
	// boundary references every time it is asked, so a wall which comes to be
	// shared makes two regions adjacent with no edit which says so.
	RelationAdjacency Relation = "adjacency"
)

The relations a traversal reports.

Three of them follow a reference the format writes — a `within`, a `member-of` and a `boundary` — and the fourth is written nowhere at all: adjacency is read from where two of those boundaries meet, and is stored no more than any other derived value ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

type RelationSpec

type RelationSpec struct {
	// Within is the node which strictly contains this one, and is empty where
	// the change says nothing about containment.
	//
	// A node is contained by one other node, never two, so writing one replaces
	// whatever parent the node already had rather than being written beside it.
	Within ID

	// MemberOf are zones this node is grouped into, in the order they are
	// written. They are added to whatever memberships the node already
	// declares, because membership is many to many and a node belonging to
	// three zones is as ordinary as one belonging to none.
	MemberOf []ID

	// Boundary are loops which bound this node, in the order they are written,
	// and are added the same way. A node with two is ordinary as well: an
	// outline and the void it encloses are two loops on one node.
	Boundary []ID
}

RelationSpec is how a node is joined to the rest of the model: the one node which strictly contains it, the zones it is grouped into, and the loops which bound it.

The three are carried together and are never collapsed into one. They are different relations with different shapes — containment is at most one and nests, membership is any number and does not, a boundary leaves the semantic family altogether — and none of them is ever derived from another ([0001](docs/decisions/0001-two-node-families.md)). What they share is only that they are references a node makes rather than axes it declares, which is why NodeSpec carries none of them: a node is added and then related, so that the refusal to place it and the refusal to relate it are two answers rather than one compound one.

Nothing here is resolved. Whether an id names a node this model holds, whether the hierarchy permits the pairing, whether a `boundary` names a loop and whether following the containment terminates are all questions about the whole model, and the model this change produces is interpreted at Tx.Commit — so a relation to something which does not exist is refused with the diagnostic a load of the result would have raised, which is the same one a hand-written file gets for the same mistake.

type RepeatedParameterError

type RepeatedParameterError struct {
	// Check is the check the assertion names.
	Check string

	// Parameter is the tag which was written more than once.
	Parameter string

	// Diagnostic is what a load reports for the same assertion written by hand.
	Diagnostic Diagnostic
}

RepeatedParameterError is a parameter written twice.

A parameter takes every value it has at once, so the second is not more of the first: it is a second answer to the same question.

func (RepeatedParameterError) Error

func (e RepeatedParameterError) Error() string

Error implements the [error] interface.

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository is a git working tree a review reads two revisions out of.

It is the git command line rather than a library. Reading the object database is a second implementation of a format this engine does not own, and the one thing a review must never do is disagree with git about what changed.

func OpenRepository

func OpenRepository(dir string) (*Repository, error)

OpenRepository finds the working tree dir is inside.

dir may be anywhere beneath the top level — the model root of a repository which holds more than a model is the ordinary case — and what comes back is rooted at the top level, because that is what every path git reports is relative to.

func (*Repository) Dir

func (r *Repository) Dir() string

Dir is the top level of the working tree.

func (*Repository) Extract

func (r *Repository) Extract(revision, dest string) error

Extract writes the tree of one revision into dest, which must already exist.

It is `git archive` read through the standard library rather than a second worktree, because a worktree is a mutation of the repository — it writes an administrative file, it can be left behind by a run which is killed, and it refuses outright when one of the same name survives an earlier run. Reading an archive changes nothing and leaves nothing.

Only regular files and directories are written. A model is text files, and a symbolic link or a device node in an archive is either not part of one or is something a review should not be creating on the machine it runs on.

func (*Repository) Log

func (r *Repository) Log(from, to string) (*Log, error)

Log reads which commit last changed each file between two revisions.

The range is exclusive of from and inclusive of to, which is the range a change is: the commits this branch added, and not the ones it was branched from. A merge inside the range contributes nothing of its own, because the commits it merged are in the range too and each says what it changed.

func (*Repository) MergeBase

func (r *Repository) MergeBase(head, base string) (string, error)

MergeBase is the commit head and base last had in common — the revision a change is a change against, rather than whatever base happens to point at now.

It is the merge base and not base itself because those two differ the moment anything else lands on base, and a review against the tip would report every change made by everybody else as part of this one.

A truncated history is refused rather than answered from. Git reports a merge base at the point a shallow clone was cut off, which is a commit the two revisions never shared, and the review which followed would attribute the whole of the branch's ancestry to this change.

func (*Repository) Prefix

func (r *Repository) Prefix(dir string) (string, error)

Prefix is where path sits inside the repository, slash-separated, which is the spelling every path git reports uses.

A path outside the working tree is ErrOutsideModel — the same answer the engine gives for a file outside the model root, because it is the same mistake: a review of a directory the repository does not hold has no history to read.

func (*Repository) Resolve

func (r *Repository) Resolve(revision string) (string, error)

Resolve is the full object name of a revision.

func (*Repository) Shallow

func (r *Repository) Shallow() bool

Shallow reports whether the clone's history is truncated.

type RepositoryError

type RepositoryError struct {
	// Dir is the directory the command ran in.
	Dir string

	// Args are the arguments git was given, without the program name.
	Args []string

	// Stderr is what git said, trimmed of its trailing line feed.
	Stderr string

	// Cause is what stopped the command, which is an [exec.ExitError] for a
	// command which ran and refused.
	Cause error
}

RepositoryError is something git was asked and could not answer.

func (RepositoryError) Error

func (e RepositoryError) Error() string

Error implements [error].

func (RepositoryError) Unwrap

func (e RepositoryError) Unwrap() error

Unwrap implements the interface errors.Is and errors.As walk.

type Resolution

type Resolution struct {
	// contains filtered or unexported fields
}

Resolution is the answer to "which claim about this thing is current", and the evidence for that answer.

A resolution is a value rather than a claim because there are three outcomes and only one of them is a claim. One claim can win outright; several can be equally current, which is ambiguity and is reported rather than broken by picking one; and a subject can have nothing rankable said about it, which is an unranked answer rather than an absent one. The zero Resolution is what a subject nothing has been claimed about resolves to, and every method below works on it.

func (Resolution) Ambiguous

func (r Resolution) Ambiguous() bool

Ambiguous reports whether more than one claim is equally current.

Ambiguity is a state of the claims and not a failure of the engine: two measurements of one thing, equally good and equally recent, genuinely do not decide between themselves, and the honest answer is both of them. A predicate the registry declares strict escalates it to an AmbiguousResolutionError instead, because for some quantities no answer is safer than an arbitrary one.

One unrankable claim standing alone is not ambiguity. There is nothing to be ambiguous between; the answer is simply unranked, which Resolution.Resolved reports and Resolution.Candidates names.

func (Resolution) Candidates

func (r Resolution) Candidates() []*Claim

Candidates returns the claims which could still be the answer, in source order.

An ambiguous resolution returns every tied claim rather than an arbitrary pick, because narrowing four claims to two is most of the work of deciding between them and a caller which is shown one of the two cannot tell that the other exists.

The claims are a copy of the resolution's own slice, so re-ordering them re-orders nothing in the model.

func (Resolution) Claim

func (r Resolution) Claim() (*Claim, bool)

Claim returns the claim which won, and whether one did.

The claim itself is the answer rather than only its value, because the point of the model is that a number arrives with the evidence for it: what won and why is one lookup, and Resolution.ClaimID is the short form of it.

func (Resolution) ClaimID

func (r Resolution) ClaimID() (ID, bool)

ClaimID returns the id of the claim the answer came from, and whether the winning claim wrote one.

A claim id is optional, so a resolved answer can be traced back to a claim which has no name of its own. That is what the second result distinguishes, and Resolution.Claim then carries the span which names it instead.

func (Resolution) Predicate

func (r Resolution) Predicate() string

Predicate returns the predicate the resolution was asked under.

func (Resolution) Reason

func (r Resolution) Reason() Reason

Reason returns which step of the rule produced this outcome.

The zero Resolution reports ReasonUnclaimed, which is what a subject nothing has been claimed about resolves to. Every other reason is written by the step which produced it, so the reason and the outcome cannot drift apart: Resolution.Resolved is true exactly for the three reasons which picked a claim, and Resolution.Ambiguous is true exactly for ReasonAmbiguous.

func (Resolution) Resolved

func (r Resolution) Resolved() bool

Resolved reports whether one claim won outright.

func (Resolution) Subject

func (r Resolution) Subject() ID

Subject returns the id of the thing the resolution is about.

func (Resolution) Value

func (r Resolution) Value() (Value, bool)

Value returns the value of the claim which won, and whether one did.

type RetireOperation

type RetireOperation struct {
	// ID is the thing which stopped existing.
	ID string `json:"id"`

	// Reason is why, in the author's words. It is required: a retirement with
	// no reason is a deletion wearing a hat.
	Reason string `json:"reason"`

	// Replacement is the node which stands in its place, where one does.
	// Supplying one is also what redirects the references to it.
	Replacement string `json:"replacement,omitempty"`

	// Date is when it stopped existing, as YYYY-MM-DD. Today by default.
	Date string `json:"date,omitempty"`
}

RetireOperation records that a thing stopped existing. It is `retire`.

func (*RetireOperation) Name

func (o *RetireOperation) Name() string

Name implements Operation.

type Retirement

type Retirement struct {
	// contains filtered or unexported fields
}

Retirement is how a node stopped existing: when, why, and what stands in its place where anything does.

Retiring is not deleting. The id stays in the graph, is never removed and is never issued again to a different thing ([0002](docs/decisions/0002-immutable-id-mutable-label.md)), so a reference written years ago either resolves to the thing it always named or resolves to a retired node which says what happened to it. A model which deleted instead would answer the second case with silence.

The reason is required and the replacement is not, which is the asymmetry the format is built on: a retirement with no reason is a deletion wearing a hat, and a thing which stopped existing did not necessarily get replaced by something.

The zero value is the retirement of a node which was not retired, which is what SemanticNode.Retirement reports with a false beside it.

func (Retirement) Date

func (r Retirement) Date() time.Time

Date returns when the thing ceased to exist in the model.

func (Retirement) Reason

func (r Retirement) Reason() string

Reason returns why it was retired, in the author's words.

func (Retirement) Span

func (r Retirement) Span() Span

Span returns where the `retired` child was written.

func (Retirement) SupersededBy

func (r Retirement) SupersededBy() (ID, bool)

SupersededBy returns the id of the node which replaced this one, and whether one did.

A replacement is optional here — unlike on a claim, where a deprecation naming nothing is a load error — because a thing which stopped existing did not necessarily get replaced. A wall which was demolished was replaced by nothing at all, and saying so is not the same as failing to say what replaced it.

type RetirementSpec

type RetirementSpec struct {
	// Date is when the thing ceased to exist. The zero time is written as the
	// day the change is made, because a retirement is dated by when it happened
	// and the common case is that it is happening now.
	Date time.Time

	// Reason is why, in the author's words. It is required.
	Reason string

	// SupersededBy is the node which replaced it, and is empty where nothing
	// did. Supplying one is also what lets the references to the retired node be
	// redirected rather than refused.
	SupersededBy ID
}

RetirementSpec is how a node is being retired: when, why, and what replaces it where anything does.

It is the written form of a Retirement rather than the read one, which is why the fields are exported and carry no spans: nothing here has been written anywhere yet.

type Revision

type Revision struct {
	// SHA is the full object name of the commit.
	SHA string `json:"sha"`

	// Summary is the first line of its message.
	Summary string `json:"summary,omitempty"`

	// Author is the name the commit was authored under.
	Author string `json:"author,omitempty"`

	// Date is when it was authored, in the zone it was authored in.
	Date time.Time `json:"date,omitzero"`
}

Revision names one commit.

It is what "the commit which introduced this change" means to a reviewer: the hash to quote, the subject line to recognise it by, and who wrote it and when. A finding which could not say that would leave the reviewer bisecting the branch to find out who moved the wall.

func (Revision) Named

func (r Revision) Named() bool

Named reports whether the revision names a commit at all.

func (Revision) Short

func (r Revision) Short() string

Short is the abbreviated object name, which is the spelling a person reads and every git command accepts.

func (Revision) String

func (r Revision) String() string

String renders the revision the way a log line does: the short name and the subject.

type RollbackError

type RollbackError struct {
	// Err is the failure which began the rollback.
	Err error

	// Failed are the files which could not be put back, in the order they were
	// written.
	Failed []string
}

RollbackError reports a change which failed part way through the renames and could not be completely undone.

It is the one failure of a write which leaves the tree in a state nobody asked for, so it names the files rather than only saying that something went wrong: those files hold what the failed change wrote, and everything else was restored.

func (RollbackError) Error

func (e RollbackError) Error() string

Error implements the [error] interface.

func (RollbackError) Unwrap

func (e RollbackError) Unwrap() error

Unwrap returns the failure which began the rollback.

type RootError

type RootError struct {
	// Path is the root, as it was given.
	Path string

	// Err is what stopped it being read: [ErrNotADirectory], or the file
	// system's own error.
	Err error
}

RootError is a model root which could not be read as one, and why.

It is the caller's error rather than the author's: nothing about the model was read, so there is nothing a diagnostic could point at.

func (RootError) Error

func (e RootError) Error() string

Error implements [error].

func (RootError) Unwrap

func (e RootError) Unwrap() error

Unwrap returns what stopped the root being read, so that errors.Is and errors.As reach it.

type Route

type Route struct {
	// Name is the rule name, which is a plain symbol and not an id. It is what a
	// report of where a node went, and a refusal to route one, name the rule by.
	Name string

	// Namespace is the id namespace an instance must carry. Empty matches any.
	Namespace string

	// Kind is the kind an instance must declare. Empty matches any.
	Kind Kind

	// Type is the type name an instance must declare. Empty matches any.
	Type string

	// File is the target file, relative to the model root and written with
	// forward slashes.
	File string

	// Description is free text. Empty when it was not written.
	Description string

	// Span is where the declaration was written.
	Span Span
	// contains filtered or unexported fields
}

Route is one declared file routing rule, per specification section 7.7.

A routing rule answers the question a write path has to answer and a read path never asks: which file does a newly authored node go in. Left to each author it becomes "wherever the last person put things", which is how one category of thing ends up spread over six files.

The three criteria are the axes a new node has before it has anything else: the namespace of its id, its kind and its type. A criterion left out matches anything, so a rule written with none of them matches every node. Which criteria are worth writing is the consuming repository's judgement and not the engine's ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

func (Route) Matches

func (r Route) Matches(subject Subject) bool

Matches reports whether a new node with these axes satisfies every criterion the rule writes.

A criterion the rule leaves out is not a criterion: it matches anything. That is what lets a registry say "every Space goes here" without also having to enumerate the types which are spaces.

A rule the loader could not read matches nothing at all, whatever it says. The diagnostic about it is the answer; routing through it as though the parts which failed to read had been left out would turn one reported mistake into a node filed somewhere nothing points at.

type RoutingError

type RoutingError struct {
	// Subject is the node which could not be placed.
	Subject Subject

	// Matched are the rules which matched it, in name order. It holds two or
	// more for an ambiguous routing and none for an unmatched one, which is what
	// tells the two apart without matching a message.
	Matched []Route

	// Consulted is every routing rule the registry declares, in name order. It
	// is the whole set rather than the ones which matched, because the answer to
	// an unmatched node is what the rules do say — which is where the missing
	// rule goes.
	Consulted []Route
}

RoutingError reports a new node the routing rules do not place.

Both reasons are the same failure seen from two sides — the rules do not say where this node goes — and both are refusals rather than defaults. A model which files an unmatched node somewhere plausible is a model in which the rules describe part of the tree and nobody knows which part ([0015](docs/decisions/0015-the-cli-is-the-primary-write-path.md)); the fix is a rule, and a fix nobody is told to make is one nobody makes.

func (RoutingError) Ambiguous

func (e RoutingError) Ambiguous() bool

Ambiguous reports whether more than one rule matched, as opposed to none.

func (RoutingError) Error

func (e RoutingError) Error() string

Error implements the [error] interface.

type Rule

type Rule struct {
	// Subject is the thing the rule is about, whichever family holds it.
	Subject Entity

	// Form is the family the subject belongs to, which is the axis a check
	// declares first.
	Form SubjectForm

	// Type is the name of the type which declared the rule, and is empty for an
	// assertion: an assertion is written on the thing itself, and
	// [Rule.Declared] already points there.
	Type string

	// Check is what the engine's closed check registry says the named check
	// constrains and takes.
	Check CheckDeclaration

	// Arguments are the parameters the rule was written with, in the order they
	// were written.
	Arguments []Argument

	// Declared is where the rule is written. For an invariant that is a
	// position in a registry file rather than in the file the subject is in;
	// for an assertion it is the assertion, on the thing it constrains.
	Declared Span
	// contains filtered or unexported fields
}

Rule is one check bound to one thing it constrains: an invariant of the thing's type, or an assertion written on the thing itself.

It is the one shape a gate reads. InvariantBinding and AssertionBinding each answer a question about one kind of rule — which invariants bear on this instance, which assertions are written on this loop — and a run which has to report how many checks there were, run them in a deterministic order and name the ones which failed is asking about both at once. Held as two lists it would be two counts, two orders and two renderings of a failure, and the two would drift.

The two are told apart by Rule.Invariant rather than by which list they came out of, and a reader acts on them the same way: what failed, which rule, the parameters it ran with, and where the rule is written are here whichever kind it is.

func (Rule) Applicable

func (r Rule) Applicable() bool

Applicable reports whether the check can examine the thing the rule is bound to.

It is false only for an assertion, and an assertion it is false for is a load error rather than a rule which quietly does not apply (ResolveAssertions). An invariant which could not examine an instance was never bound to it: a type declares one rule for instances which differ, so a check about an area not reaching the instance which has no shape is ordinary rather than wrong.

func (Rule) Chorded

func (r Rule) Chorded() []ChordedEdge

Chorded returns every edge this rule reads as the straight line between its ends although the model states a curve on it: an edge bounding a shape the rule reads, which claims a position the rule does not read as an arc.

It is a question about the model and the rule and not about a run, so it has the same answer before a run as after, and a gate can read which of its passes will rest on an unread arc without running one. The rule either named no arc vocabulary, or named one the edge does not state both halves of.

The order is by edge id, for the reason Graph.UnreadArcs gives. A rule whose check reads no shape, or which cannot run, reads nothing straight.

func (Rule) Invariant

func (r Rule) Invariant() bool

Invariant reports whether the rule is an invariant of the subject's type, as against an assertion written on the subject itself.

func (Rule) Judge

func (r Rule) Judge() ([]AppliedBand, []Violation)

Judge runs the check and returns both what it decided against and what it found: a band for every comparison made against a figure wider than the tolerance the rule was given could have been, and a violation for every way the rule is not satisfied.

The bands come back whether or not the rule was satisfied, which is the whole point of them: a pass decided against a band eight times its declared tolerance is the answer nothing else in a run discloses. A check which decides against what it was given reports none, and neither does a rule nothing runs.

Rule.Run is this without the bands, for a caller which only wants the gate.

func (Rule) Parameters

func (r Rule) Parameters() []Parameter

Parameters returns the parameters the rule was written with, as data, in the order they were written: Parameters()[i] and Arguments[i] are one parameter.

It is nil for a rule written with no parameters.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/checks/violating")

	// A rule's parameters come back as data as well as the text they were
	// written in: the tolerance a rule runs with is read by name, rather than
	// parsed back out of "(tolerance boundary-closure)". Each carries the type
	// the check declares it takes, which is what says "position" here names a
	// predicate rather than being a string.
	rule := graph.Rules()[0]
	fmt.Println(rule)

	for _, parameter := range rule.Parameters() {
		fmt.Printf("%s (%s): %v\n", parameter.Name, parameter.Type, parameter.Values)
	}

}
Output:
site:L-01 contained-areas-do-not-overlap (tolerance boundary-closure) (position position)
tolerance (tolerance): [boundary-closure]
position (predicate): [position]

func (Rule) ReadsArcs

func (r Rule) ReadsArcs() bool

ReadsArcs reports whether the rule names the vocabulary a curved edge is written in, which is whether an edge its shapes are bounded by and which claims an arc under those names is read as that arc.

It is false for a rule whose check reads no shape, which has no curve to read.

func (Rule) Run

func (r Rule) Run() []Violation

Run runs the check against the thing the rule is bound to and returns one violation for each way it is not satisfied.

A rule which satisfies its check yields none, and so does one nothing runs: Rule.Runs is what tells those two apart, and a caller counting how many checks passed has to ask it rather than reading the empty result.

func (Rule) Runnable

func (r Rule) Runnable() bool

Runnable reports whether the check has an implementation to run.

A check which declares itself and implements nothing binds, lists and validates exactly as one which does, and running it reports nothing. It is told apart here rather than by an empty result, because "this rule holds" and "nothing has been written to decide whether it holds" are different answers.

func (Rule) Runs

func (r Rule) Runs() bool

Runs reports whether Rule.Run would run anything, which is what a listing of the rules a gate would exercise reports of each of them.

func (Rule) String

func (r Rule) String() string

String renders the rule as the thing it is bound to and the rule as it was written.

type RuleFilter

type RuleFilter struct {
	// Subjects are the things the rule may be bound to, by id. A subject is any
	// of the four families, because an assertion is written on any of them.
	Subjects []ID

	// Types are the type names an instance may declare. It selects the rules
	// bound to instances of those types, whether the rule is an invariant of
	// the type or an assertion written on one of its instances; a vertex, an
	// edge and a loop declare no type and are selected by none of them.
	Types []string

	// Checks are the check names a rule may name.
	Checks []string
}

RuleFilter narrows a run to a subset of the rules a model holds.

A filter left empty matches everything, and filters combine: a rule is selected when it satisfies every filter which was given. Within one filter the values are alternatives, so two subjects means the rules of either.

The point of narrowing is a gate somebody is iterating against — one room, one type, one check they have just written — and the answers have to compose the way a reader expects, which is that each filter can only take rules away.

func (RuleFilter) Matches

func (f RuleFilter) Matches(rule Rule) bool

Matches reports whether the rule satisfies every filter which was given.

type Rules

type Rules []Rule

Rules is a set of rules in the order they will be run.

func (Rules) Run

func (rs Rules) Run() CheckRun

Run runs every rule and reports what it found.

Violations come back in the order the rules were in, and within one rule in the order the check reported them. Collecting them into a Diagnostics is what puts them in reporting order, which is by position.

Bands come back in the same order and from the same rules, passing and failing alike. They are a second list rather than something hung off a violation because the answer they are about is most often a pass, which has no violation to hang anything off.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/rules/valid")

	// A gate somebody is iterating against runs one thing, one type or one
	// check rather than the model. Each filter can only take rules away, so the
	// answers compose the way a reader expects.
	rules := graph.Rules().Select(dfcad.RuleFilter{Types: []string{"MeetingRoom"}})
	for _, rule := range rules {
		fmt.Println(rule)
	}

	run := rules.Run()

	// Every check the engine registers declares what it constrains and takes,
	// and every one of them has an implementation to run. The room references
	// no loop, so the check which reads its outline finds nothing to disagree
	// with and passes; the first room carries its width and the second does
	// not, so the type's requirement holds of one and fails the other.
	fmt.Println("rules:", run.Rules)
	fmt.Println("passed:", run.Passed)
	fmt.Println("undecided:", run.Rules-run.Ran)
	fmt.Println("failed:", run.Failed)

}
Output:
site:S-101 required-claim (predicate width)
site:S-102 required-claim (predicate width)
site:S-101 boundary-loops-close (tolerance boundary-closure)
rules: 3
passed: 2
undecided: 0
failed: 1
Example (Bands)
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/checks/agreement")

	// Some checks treat the tolerance they are declared with as a floor rather
	// than the whole test: two figures which differ by less than their combined
	// uncertainty do not disagree, so the band widens to whatever the evidence
	// can actually tell apart. That is right, and it means the number the
	// registry states is not the number the check applied.
	//
	// So every such comparison comes back as a band, whether it agreed or not.
	// The room below claims 12.2 m² of a shape which computes to 12.0 — four
	// times the declared discrepancy — and passes, because the claim is good to
	// 0.25 m² and the corners put the shape within 0.112. Nothing else in the
	// run says that: it is a pass either way.
	rules := graph.Rules().Select(dfcad.RuleFilter{Subjects: []dfcad.ID{"site:S-107"}})

	run := rules.Run()
	fmt.Println("passed:", run.Passed, "failed:", run.Failed)

	for _, applied := range run.Bands {
		band := applied.Band

		fmt.Printf("%s %s: declared %v %s, applied %v %s\n",
			applied.Instance, applied.Check, band.Floor, band.Unit, band.Applied, band.Unit)
		fmt.Printf("gap of %v %s, decided by the widening: %t\n",
			band.Difference, band.Unit, band.Decisive)

		for _, term := range band.Terms {
			fmt.Printf("  %s: %v %s × %v = %v %s\n",
				term.Source, term.Sigma, term.Unit, term.Sensitivity, term.Contribution, band.Unit)
		}
	}

}
Output:
passed: 1 failed: 0
site:S-107 claim-agrees-with-geometry: declared 0.05 m2, applied 0.2739415996156845 m2
gap of 0.1999999999999993 m2, decided by the widening: true
  claim: 0.25 m2 × 1 = 0.25 m2
  corners: 0.008 m × 14 = 0.112 m2
Example (StructuralInvariants)
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/checks/violating")

	// Every failure below is a file which loads. A loop which does not close,
	// two rooms drawn over one another, parts which do not add up to the whole,
	// a part drawn in another frame, a fit too loose for the answer it is used
	// for and a room in a setback are all well-formed models, and nothing short
	// of running the rules finds any of them.
	for _, violation := range graph.Rules().Run().Violations {
		fmt.Printf("%s — %s\n", violation.Check, violation.Message)
	}

}
Output:
contained-areas-do-not-overlap — expected no two of the shapes within site:L-01 to cover the same ground, found site:S-101 and site:S-102 overlapping by 4.0 m²
contained-areas-sum — expected what site:L-01 contains to add up to its own 24.0 m², found 28.0 m², which is 4.0 m² more than the whole
stays-clear-of-zone — expected site:S-102 to stay clear of the zone site:Z-90, found it crossing into it over 4.0 m²
boundary-loops-close — expected the loop geom:L-13 to close, found a gap of 0.3 m between geom:V-13 and geom:V-09
contained-areas-sum — expected everything summed into site:L-05 to be declared in frame:building, the frame it is drawn in, found site:S-501 in frame:annex
boundary-loops-close — expected the loop geom:L-13 to close, found a gap between geom:V-13 and geom:V-09 whose size could not be measured
cross-frame-budget-holds — expected site:A-01 in frame:building to be known to within 0.008 m, found a combined uncertainty of 0.01 m (k = 1.0, ≈ 68%) accumulated from 2 terms

func (Rules) Select

func (rs Rules) Select(filter RuleFilter) Rules

Select returns the rules which satisfy the filter, in the order they were in.

type Ruling

type Ruling string

Ruling is what a Policy says to do about a finding.

The three exist because a diff-aware check is a question rather than a rule: a wall which moved because it was measured again is a change somebody meant, and a gate which could only fail on it would be one every author learned to route around. Downgrading a kind to a warning, or acknowledging it outright, is the stated way to say so.

const (
	// RulingFailure reports the finding and fails the run.
	RulingFailure Ruling = "failure"

	// RulingWarning reports the finding and does not fail the run.
	RulingWarning Ruling = "warning"

	// RulingIgnored keeps the finding in the result and reports it nowhere
	// else. It is in the result rather than dropped so that what a policy
	// acknowledged is readable from the run which acknowledged it: a check
	// silently switched off is one nobody remembers is off.
	RulingIgnored Ruling = "ignored"
)

The rulings, from the one which stops a change to the one which says nothing.

func ParseRuling

func ParseRuling(written string) (Ruling, error)

ParseRuling reads a ruling as a policy writes it.

func Rulings

func Rulings() []Ruling

Rulings returns every ruling a policy may state, strongest first.

type Runner

type Runner interface {
	Check

	// Run examines one subject and returns one failure for every way it does
	// not satisfy the check. A subject which satisfies it yields none.
	//
	// Run is never called with a subject the check does not apply to: whether
	// the check can examine a node of this kind, with this geometry, is decided
	// by the binding and by the registry load before it.
	Run(subject CheckSubject) []Failure
}

Runner is a Check which can be run against a subject.

It is a second interface rather than a method on Check because declaring a check and implementing it are separately useful: everything above the registry — validating an assertion at load, listing what a model may write, binding an invariant to the instances it applies to — reads the declaration and never runs anything, and a check which is declared and not yet implemented is exactly what those layers have to keep working against.

type ScaffoldLoopOperation

type ScaffoldLoopOperation struct {
	// Namespace is the declared id namespace the new nodes are minted in.
	Namespace string `json:"namespace"`

	// Frame is the frame the corners are expressed in.
	Frame string `json:"frame,omitempty"`

	// Label is the loop's display text.
	Label string `json:"label,omitempty"`

	// File is where to write everything, overriding the routing rules.
	File string `json:"file,omitempty"`

	// Predicate is the predicate a corner's position is claimed under.
	Predicate string `json:"predicate"`

	// Tolerance is the declared tolerance two corners are judged to be one
	// point by, which is also what says the list closed.
	Tolerance string `json:"tolerance"`

	// Corners are the corners of the loop, in order and authored closed: the
	// last names the first corner again. Each is written in the shape the
	// position predicate declares.
	Corners []string `json:"corners"`

	// NoSnap writes a new vertex at every corner, even where one is already
	// there. Every corner which would have been reused is still reported.
	NoSnap bool `json:"noSnap,omitempty"`

	// Bounds is the semantic node the loop bounds, and is empty for a scaffold
	// which binds the loop to nothing. Naming one writes the `boundary`
	// reference in the same operation, so a room and its outline are one
	// statement.
	Bounds string `json:"bounds,omitempty"`

	// VertexMark, EdgeMark and LoopMark are what the minted ids are named
	// after, and are empty for the tag of the form being written. They are what
	// lets a generated batch mint into the consuming repository's own naming
	// scheme rather than into this engine's.
	VertexMark string `json:"vertexMark,omitempty"`
	EdgeMark   string `json:"edgeMark,omitempty"`
	LoopMark   string `json:"loopMark,omitempty"`

	// Claim is the evidence every position claim is written with. Its value is
	// not read: a corner's value is the corner. Its unit is read, and a corner
	// list written without one is read in the unit the position predicate
	// declares.
	Claim ClaimAxes `json:"claim,omitempty"`
}

ScaffoldLoopOperation writes a room's corners, walls and outline in one operation. It is `scaffold-loop`.

func (*ScaffoldLoopOperation) Name

func (o *ScaffoldLoopOperation) Name() string

Name implements Operation.

type ScaffoldSpec

type ScaffoldSpec struct {
	// Namespace is the declared id namespace the new nodes are minted in.
	Namespace string

	// Frame is the frame the corners are expressed in.
	Frame ID

	// Corners are the corners of the loop, in order, closed: the last names the
	// first corner again.
	Corners []Corner

	// Label is the loop's display text, and is empty for a loop with none.
	Label string

	// Predicate is the predicate a corner's position is claimed under, which
	// the consuming repository declares rather than the engine knowing
	// ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).
	Predicate string

	// Provenance is the evidence every position claim is written with: its
	// source, its method, its accuracy and its date. The subject, the predicate
	// and the value of each claim come from the corner it is about.
	Provenance ClaimSpec

	// Tolerance is the name of the declared tolerance two corners are judged
	// coincident against, which is also what says the list closed.
	Tolerance string

	// Snap says to reuse an existing vertex a corner lands on rather than write
	// a second one at the same point.
	Snap bool

	// Bounds is the semantic node the loop bounds, and is empty where the
	// scaffold is to bind the loop to nothing.
	//
	// Naming one writes the `boundary` reference in this same change, which is
	// what makes a room and its outline one operation. A scaffold which could
	// mint the shape and not say what it is the shape of leaves the one fact
	// nothing else in the batch can state to be hand-edited in afterwards.
	Bounds ID

	// VertexMark, EdgeMark and LoopMark are what the minted ids are named
	// after, and are empty for the tag of the form being written — which mints
	// `<namespace>:vertex-1`, `<namespace>:edge-1` and `<namespace>:loop-1`.
	//
	// They are here so that a generated batch lands in the consuming
	// repository's own naming scheme rather than in this engine's, because the
	// alternative is rewriting every id the batch minted by hand, which is the
	// same pass a scaffold exists to avoid. A mark is a name and not a schema:
	// nothing is inferred back out of one
	// ([0002](docs/decisions/0002-immutable-id-mutable-label.md)), and the
	// three are separate rather than one pattern because the three forms are.
	VertexMark string
	EdgeMark   string
	LoopMark   string
}

ScaffoldSpec is a loop to be created from an ordered list of corners.

It is the one operation in this interface which mints ids, and it mints them because the alternative is naming several dozen vertices and edges by hand to describe one room. What it does not do is decide anything else: the frame, the predicate a position is claimed under, the tolerance two corners are judged coincident against and the evidence behind every claim are all supplied, and none of them has a default.

type Scaffolding

type Scaffolding struct {
	// Loop is the id of the loop which was written.
	Loop ID

	// Vertices are the vertex each corner is at, in corner order, with the
	// closing corner left out — it is the first corner written again.
	Vertices []ID

	// Created are the vertices which were minted, in the order they were.
	Created []ID

	// Edges are the loop's edges, in traversal order.
	Edges []ID

	// Reused are the edges of that ring which the model already held, in the
	// order the traversal reaches them. An edge shared by two regions is
	// written once and named by both, which is the whole of what makes a
	// partition one wall rather than two.
	Reused []ID

	// Snaps are the corners which landed on a vertex the model already held, in
	// corner order. Empty rather than nil when none did.
	Snaps []Snap

	// Tolerance is the declaration coincidence and closure were judged against,
	// which travels with the answer because the answer depends on it
	// ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).
	Tolerance Tolerance

	// Bounds is the node the loop was written on as a boundary, and is empty
	// where the scaffold bound nothing. It is reported because it is the half
	// of the change which is not geometry: an author who asked for a room's
	// outline and for the room to reference it reads back both.
	Bounds ID
}

Scaffolding is what scaffolding a loop created.

Everything in it is reported whether or not the change was written, which is what makes a dry run worth doing: the ids, the reuses and the tolerance which decided them are the whole of what the author is checking before committing to them.

type SegmentOrigin

type SegmentOrigin string

SegmentOrigin is what produced one straight run of a region's boundary.

It is what stops an attribution being read as more than it is. A run which is an edge and a run which is one chord of the drawing of an arc both name an edge, and a consumer which carried the second back into the model as though it were the first would be writing a straight wall where a curved one is.

const (
	// SegmentOriginEdge is a run which is an edge, corner to corner as it was
	// written. It is the case an attribution is wanted for: the segment is the
	// edge, and a claim written on the edge is a claim about the segment.
	SegmentOriginEdge SegmentOrigin = "edge"

	// SegmentOriginArc is a chord standing in for part of the arc an edge bends
	// along. It names that edge, which is what makes a drawn boundary
	// attributable at all, and it is not the edge: the run is as close to the
	// curve as the chord tolerance the drawing was made to allowed, and no
	// closer.
	SegmentOriginArc SegmentOrigin = "arc"

	// SegmentOriginOperation is a run an operation produced, which no authored
	// edge is behind. An offset, a union and a region carried into another frame
	// are all this: the boundary is where the operation put it, and naming an
	// edge for it would be a lie the next derivation acts on.
	SegmentOriginOperation SegmentOrigin = "operation"
)

The three things which produce a run of a boundary.

func (SegmentOrigin) String

func (o SegmentOrigin) String() string

String returns the origin as it is written.

type Selection

type Selection struct {
	// Kinds are the kinds a selected node declares one of. Empty selects every
	// kind.
	Kinds []Kind

	// Types are the types a selected node declares one of. Empty selects every
	// type.
	Types []string
}

Selection is which of a subject's descendants a plan is asked about: those declaring one of Kinds, and one of Types.

Within one field any of its values, across the two fields both, and an empty field is no narrowing at all — so the zero Selection selects every node. That is the rule every filter of the command line follows, and it is any rather than every within a field because a node declares one kind and one type: a selection demanding two of either would select nothing by construction.

It narrows what a plan reports and never what it walks. A room three levels below the subject is selected by Types {"Office"} whether or not anything between it and the subject is an office, because the question is which rooms to draw, and a walk which stopped at the first node the selection refused would answer "no rooms" for a model whose every room is inside a storey.

A kind or type nobody declared is not refused here: it selects nothing, exactly as a declared one nothing instantiates does. Telling those two apart is a question about the registry which a caller asks before asking for a plan — the command line refuses such a value as a usage error — and the answer to "which of these nodes is an X" is the same whichever of the two X is.

func (Selection) Selects

func (s Selection) Selects(node *SemanticNode) bool

Selects reports whether node is one the selection asks about. A nil node is never selected.

type SelfLoopError

type SelfLoopError struct {
	// ID is the edge which was being written.
	ID ID

	// Vertex is the vertex written at both ends of it.
	Vertex ID
}

SelfLoopError reports an edge written between one vertex and itself.

func (SelfLoopError) Error

func (e SelfLoopError) Error() string

Error implements the [error] interface.

type SelfReplacementError

type SelfReplacementError struct {
	// ID is the node.
	ID ID
}

SelfReplacementError reports a node retired in favour of itself.

func (SelfReplacementError) Error

func (e SelfReplacementError) Error() string

Error implements the [error] interface.

type SelfSupersessionError

type SelfSupersessionError struct {
	// ID is the claim.
	ID ID
}

SelfSupersessionError is a claim named as its own replacement.

func (SelfSupersessionError) Error

func (e SelfSupersessionError) Error() string

Error implements the [error] interface.

type SemanticNode

type SemanticNode struct {
	// contains filtered or unexported fields
}

SemanticNode is one node of the semantic family, per specification section 6.1.

A semantic node is described by a small fixed set of axes rather than by a class per concept: a kind, a type, and — where it has them — a geometry form and a frame. That is what keeps this API the size of the axes rather than the size of the vocabulary. A consuming repository which needs a hundred and fifty types writes a hundred and fifty registry entries and no Go types ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

The two axes which may be absent are absent as a state and not as a degenerate value. A circuit group, a warranty and a system have no geometry and no frame, and none of them is malformed; representing them without a special case is the point of the design ([0001](docs/decisions/0001-two-node-families.md)). SemanticNode.Geometry and SemanticNode.Frame therefore each report whether the node has that axis, which is what tells a node with no geometry apart from one whose geometry form is the empty string — a thing the closed set has no member for and which no file can produce.

The fields are unexported and read through the methods below. The tree a node was read from is not part of its interface: a caller which reached through to it would be reading the file a second time, in a second way, and the two readings would disagree the first time canonical form moved a child.

A SemanticNode is read-only once loaded. The zero value is a node with no id, no kind and no type, which is what a form nothing could be read from yields; every method below works on it.

func (*SemanticNode) Assertions

func (n *SemanticNode) Assertions() []Assertion

Assertions returns the assertions written on the node, in the order they were written.

They are what constrains the thing, where the claims are what is known about it, and a caller showing one shows both: "this patio must stay inside this setback" is written here and is not derivable from anything else on the node.

They come back as they were written, which includes an assertion naming a check nothing registers — a load error, and still something somebody wrote on this node. Graph.Assertions is the same list resolved against the check registry, which is what a caller wanting to know what each one constrains reads.

The invariants of the node's type are not among them. Those are stated once on the type and are read with Graph.Invariants; a node which carried a copy would be a node whose rules could drift from its type's.

func (*SemanticNode) Boundaries

func (n *SemanticNode) Boundaries() []ID

Boundaries returns the ids this node wrote where a loop id belongs, in the order they were written.

A semantic node references a loop and never carries coordinates. That is what makes a shared wall shared: two spaces either side of a partition reference one edge through their loops, so moving it moves both of them and a sliver gap between them is not a state this model can express ([0001](docs/decisions/0001-two-node-families.md)).

A node with no boundary is ordinary rather than incomplete, and a node with two is as well: an outline and the void it encloses are two loops on one node. Nothing here says which is which, because the format does not.

**These are the ids as they were written, and not the loops they reached.** An id naming a vertex, and one naming nothing this model holds, are each a diagnostic from ResolveBoundaries and are each still here, because a caller reporting on a node wants to say what it says as well as what is wrong with it. A caller which wants only the loops walks Boundaries.Loops, which yields what resolved and nothing else. A repeated id — which is a load error — is held once.

Resolving them is a question about both families at once, and this pass has read one, which is why the answer is not here.

func (*SemanticNode) Frame

func (n *SemanticNode) Frame() (ID, bool)

Frame returns the id of the node's frame, and whether it has one.

A node is declared in at most one frame; declaring it in two is unrepresentable, which is the point. A node with no geometry usually has no frame either, and a node may legitimately have neither. The second result is false on the same two occasions SemanticNode.Geometry's is: no `frame` child, or one no id could be read from.

func (*SemanticNode) Geometry

func (n *SemanticNode) Geometry() (Geometry, bool)

Geometry returns the node's geometry form, and whether it has one.

A node with no geometry is ordinary rather than incomplete, so the second result is a state and not a failure. It is false when the node wrote no `geometry` child, which the node's type has to permit, and also when what it wrote was not a geometry form — that is a diagnostic of its own, and there is no form to report.

func (*SemanticNode) ID

func (n *SemanticNode) ID() ID

ID returns the node's id, which never changes for the life of the thing it names ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

func (*SemanticNode) Kind

func (n *SemanticNode) Kind() Kind

Kind returns the node's kind, which is one of the seven Kinds compiled into the engine.

func (*SemanticNode) Label

func (n *SemanticNode) Label() string

Label returns the node's display text, which is empty when none was written.

A label is free-form and carries no uniqueness guarantee. Nothing resolves through it and nothing in the engine reads it, so changing it changes the label and nothing else about the node: a rename is a one-line diff and not a re-identification.

func (*SemanticNode) MemberOf

func (n *SemanticNode) MemberOf() []ID

MemberOf returns the ids of the zones this node declares membership of, in the order they were written.

Membership is many to many and unconstrained in its count: a node belongs to as many zones as it says, and one belonging to none is as ordinary as one belonging to three. Nothing here reads the containment references, so a node's zones are its own and never inherited from what contains it.

These are the ids as the node wrote them, with a repeated one — which is a load error — held once. Nodes.Zones resolves them to the zones, labelled with the relation which produced them.

func (*SemanticNode) ObservedIn

func (n *SemanticNode) ObservedIn() []ObservationLink

ObservedIn returns the observation files the node links to, in the order they were written, per specification section 6.10.

These are the links and never the records. Nothing is read to answer this, which is what makes retrieving a node cost the entity files and not the field work behind them; Graph.Observations is what opens the files, and it does so because somebody asked a question the records answer.

A node linking to no observation file is the ordinary case: most of a model is not surveyed directly, and the shots behind the corners of a room are linked from the corners.

func (*SemanticNode) Retired

func (n *SemanticNode) Retired() bool

Retired reports whether the node was retired.

It is SemanticNode.Retirement for the callers which only want the question answered — a listing which leaves retired nodes out unless it was asked for them reads better as a predicate than as a two-result call whose first result it drops.

func (*SemanticNode) Retirement

func (n *SemanticNode) Retirement() (Retirement, bool)

Retirement returns how the node was retired, and whether it was.

A retired node is still a node the model holds: it is reachable by its id, carries every claim it ever carried, and is what a reference to that id resolves to. What retirement says is that the thing it named stopped existing, which is a state of the model rather than an absence from it.

func (*SemanticNode) Span

func (n *SemanticNode) Span() Span

Span returns where the node form was written, which is what a diagnostic about the node as a whole points at.

func (*SemanticNode) Type

func (n *SemanticNode) Type() string

Type returns the name of the node's type, which the consuming repository's registry declares. The engine attaches no meaning to it beyond the axes that declaration permits.

func (*SemanticNode) Within

func (n *SemanticNode) Within() (ID, bool)

Within returns the id of the node which strictly contains this one, and whether it wrote one.

Containment nests strictly, so there is at most one: a node is written inside one other node, never two. A node with no parent is ordinary rather than incomplete, which is why the second result is a state and not a failure.

This is the id as the node wrote it. Nodes.Within resolves it to the node, labelled with the relation which produced it, and is what a traversal uses.

type SessionSystematic

type SessionSystematic struct {
	// Session is the occupation the term belongs to, matched against
	// [SurfacePoint.Session].
	Session ID

	// Magnitude is the one-sigma figure, in the frame's linear unit. Zero or
	// less states nothing and contributes nothing.
	Magnitude float64
}

SessionSystematic is a systematic uncertainty every shot of one occupation shares, stated by whoever asks for a surface.

It is the error which does not average away however many shots the afternoon produced: a base station set up over the wrong mark, an antenna height typed in once, a benchmark whose level is out. Every shot of that session moves the same way and by the same amount, so the term is added linearly and counted once ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)) rather than combined in quadrature with itself.

It is stated on the derivation because the observation format does not carry it. A record states the precision the instrument reported for that shot, which is the independent part and nothing else; what the whole setup was worth is a judgment made afterwards, by whoever reduced the session. Stating it here keeps that judgment on the question — it lands on the result and in the cache key like every other parameter — rather than in a constant nobody can read back off the answer.

A session nothing is stated for contributes no shared term. That is not a claim that it has none, and Elevation.Complete is where a level says how far its budget reaches.

func (SessionSystematic) String

func (s SessionSystematic) String() string

String writes the term as the session and what it is worth.

type SetBackingOperation

type SetBackingOperation struct {
	// ID is the edge whose backing is being stated.
	ID string `json:"id"`

	// BackedBy are the elements which physically realise it now, replacing
	// every one it named before. The member is required, and the empty array is
	// how a virtual edge is written: a member left out is refused rather than
	// read as "backed by nothing".
	BackedBy *[]string `json:"backedBy"`
}

SetBackingOperation replaces what an edge is physically realised by. It is `set-backing`.

func (*SetBackingOperation) Name

func (o *SetBackingOperation) Name() string

Name implements Operation.

type SetEdgesOperation

type SetEdgesOperation struct {
	// ID is the loop whose ring is being stated.
	ID string `json:"id"`

	// Edges are the edges of the ring, in the order the loop is traversed,
	// replacing every one it named before. The order is the data and is never
	// sorted.
	Edges []string `json:"edges"`
}

SetEdgesOperation replaces the edges a loop is traversed through. It is `set-edges`.

func (*SetEdgesOperation) Name

func (o *SetEdgesOperation) Name() string

Name implements Operation.

type SetLabelOperation

type SetLabelOperation struct {
	// ID is the thing being renamed.
	ID string `json:"id"`

	// Label is what it is now called. An empty one removes the label, which is
	// how a thing goes back to having none.
	Label string `json:"label"`
}

SetLabelOperation changes what a thing is called, and nothing else. It is `set-label`.

func (*SetLabelOperation) Name

func (o *SetLabelOperation) Name() string

Name implements Operation.

type Setback

type Setback struct {
	// contains filtered or unexported fields
}

Setback is one edge's setback: how far the boundary is pushed back along that edge, and the claim which says so.

The claim is carried rather than only the number, for the reason a Resolution carries one: "six metres" is a figure somebody has to go and check, and "six metres, from this claim, measured this way, this accurate" is the answer with the evidence already attached.

func (Setback) Claim

func (s Setback) Claim() *Claim

Claim returns the claim the distance was resolved from.

func (Setback) Distance

func (s Setback) Distance() float64

Distance returns how far back the setback pushes the boundary, in Setback.Unit.

func (Setback) Edge

func (s Setback) Edge() *Edge

Edge returns the edge the setback was claimed on.

func (Setback) String

func (s Setback) String() string

String renders the setback as a person reads it: the edge, the distance and the claim behind it.

func (Setback) Unit

func (s Setback) Unit() Unit

Unit returns the unit the distance is in, which is the linear unit of the region's frame.

type Setbacks

type Setbacks struct {
	// Predicate is the predicate an edge's setback distance is claimed under.
	//
	// There is no default. A derivation told no predicate would have to guess
	// which of a project's distances is the one which pushes a building back
	// from its boundary, and the guess would be wrong silently.
	Predicate string

	// Claims is the family the setback claims are read from, which is the one
	// [LoadClaims] loaded.
	Claims *Claims
}

Setbacks is where the setback distances a buildable region is derived from are read.

It is the predicate and the claims and nothing else. Which edge is the front one, which the rear and which a side is not modelled here and never will be ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)): a setback is a claim written on the edge it applies to, so an authority which requires six metres at the front and three at the sides writes those numbers on those edges and the derivation applies each where it was written.

type Severity

type Severity string

Severity says how much a diagnostic matters.

It is a string so that its machine-readable form is the same word its human rendering prints, and so that neither has to be kept in step with a number.

const (
	// SeverityError marks input the engine refuses. Nothing downstream of an
	// error may be trusted to mean what it says.
	SeverityError Severity = "error"

	// SeverityWarning marks input the engine accepts but which is very likely
	// not what its author meant.
	SeverityWarning Severity = "warning"
)

type ShallowHistoryError

type ShallowHistoryError struct {
	// Head and Base are the two revisions the review was asked to compare.
	Head, Base string

	// Boundary is the commit the history is truncated at, where the truncation
	// is what made the merge base wrong rather than missing.
	Boundary string
}

ShallowHistoryError is a checkout whose history is cut off short of the merge base.

It says what it needs rather than answering from what it has, which is the only safe answer: a shallow clone reports a merge base at the point its history was truncated, and a review against the wrong base reports every commit before the cut as though this change had made it.

func (ShallowHistoryError) Error

func (e ShallowHistoryError) Error() string

Error implements [error].

type Shape

type Shape string

Shape is the shape a predicate's claim values take, per specification section 6.6.

const (
	ShapeScalar     Shape = "scalar"
	ShapeCoordinate Shape = "coordinate"
	ShapeTransform  Shape = "transform"
	ShapeText       Shape = "text"
)

The value shapes, in the order specification section 6.6 lists them.

func Shapes

func Shapes() []Shape

Shapes returns the closed set of value shapes, in specification order.

type SingularTransformError

type SingularTransformError struct {
	// Frame is the frame the transform is declared on.
	Frame ID

	// Parent is the frame it maps into.
	Parent ID
}

SingularTransformError reports a transform which maps a frame into its parent and cannot be run backwards.

A rotation of zero determinant or a scale of zero collapses the frame onto a plane, a line or a point, and more than one position in the frame then has the same position in the parent. Coming back is not a computation which went wrong; it is a question with more than one answer.

func (SingularTransformError) Error

func (e SingularTransformError) Error() string

Error implements the [error] interface.

type Siting

type Siting struct {
	// Frames is the frame graph the proposal is carried across, which is the one
	// [ResolveFrames] produced.
	//
	// It is required only where the two things being compared are declared in
	// different frames, which is the case this whole query exists for. Where it
	// is needed and absent, the answer is a diagnostic rather than a comparison
	// of two frames' numbers because they are both numbers.
	Frames *Frames

	// Clearance is how much room the proposal is required to keep between
	// itself and the envelope's boundary, in the linear unit of the envelope's
	// frame.
	//
	// Nought is the ordinary case and means "inside it at all". A positive
	// distance is a maintenance strip, an access route, a fire appliance
	// standing: the proposal has to be that far inside as well as inside. There
	// is no default beyond nought, and a negative distance is refused — a
	// requirement to overhang the boundary is not a requirement.
	Clearance float64

	// Setbacks, where it is given, takes the setback claimed on each edge of
	// the envelope off it before anything is compared, so that the proposal is
	// sited inside what the envelope's setbacks leave buildable rather than
	// inside its outline.
	//
	// The region is derived exactly as [Topology.BuildableOf] derives it, from
	// the same reading of the envelope's outline, and is never authored
	// ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)):
	// a buildable area written down as a polygon of its own is a second
	// statement of where a permanent structure may go. Deriving it inside the
	// query rather than beside it is what puts the setback claims and the
	// envelope's corners in the same budget as the proposal's corners and the
	// transforms, so a term they share is counted once rather than once per
	// answer.
	//
	// The zero Setbacks is the ordinary case and sites inside the outline, as
	// a run given no setbacks always has. [Siting.Clearance] is kept inside the
	// region the setbacks leave, and is one distance on top of them rather than
	// a substitute for them: a clearance is the same on every edge, and
	// setbacks are what differ from one edge to the next.
	Setbacks Setbacks
}

Siting is what a fit is judged against: the frames the answer is composed across, and the clearance the proposal is required to keep inside the envelope.

It is a struct rather than two more parameters for the reason Setbacks is: the two travel together, and a query given one of them has not been asked a question yet.

type Snap

type Snap struct {
	// Corner is the corner's place in the list, counted from one as a person
	// counts a list.
	Corner int

	// Vertex is the vertex it landed on.
	Vertex ID

	// Distance is how far it was from that vertex, in the frame's unit.
	Distance float64

	// Unit is the unit the distance is in, which is the frame's.
	Unit Unit

	// Reused reports whether the vertex was used for this corner rather than a
	// second one being written at the same point. It is false exactly when
	// snapping was switched off, which is the case worth warning about: a
	// duplicate vertex at one point is the sliver the topology model exists to
	// prevent.
	Reused bool
}

Snap is one corner which landed on a vertex the model already held.

Both outcomes are reported, and that is the point of the type. A reuse which happened and a reuse which was declined are the same measurement — this corner is this far from that vertex — and an author who is surprised by either wants to see the distance rather than infer it from which nodes appeared.

type Sort

type Sort string

Sort is which of the five registries an entry belongs to.

It exists so that the questions every layer above asks — is this name declared, and what do I say when it is not — are one method each rather than five. The string value is the tag the entry is written with, which is what makes a diagnostic about it read as the form somebody wrote.

const (
	SortNamespace Sort = "namespace"
	SortType      Sort = "type"
	SortPredicate Sort = "predicate"
	SortFrame     Sort = "frame"
	SortTolerance Sort = "tolerance"
	SortRoute     Sort = "route"
)

The registries a name may be declared in. There is no sort for the project declaration: it declares no name and there is exactly one of it.

type SourceMap

type SourceMap interface {
	// Source returns the bytes of path, and whether it has them.
	Source(path string) ([]byte, bool)
}

SourceMap resolves a file path to the bytes read from it, so a diagnostic can quote the line it points at.

It is an interface rather than a map so that a caller holding a whole tree can re-read a file on demand instead of keeping every file it loaded in memory for the sake of the few that turn out to have problems.

type Sources

type Sources map[string][]byte

Sources is the SourceMap a caller already holding the bytes uses.

func (Sources) Source

func (s Sources) Source(path string) ([]byte, bool)

Source implements SourceMap.

type Span

type Span struct {
	Start Position `json:"start"`
	End   Position `json:"end"`
}

Span is the extent of the source text one node was written in.

Start is the first byte of that text and End is one byte past its last, so for source bytes src the text is exactly src[Start.Offset:End.Offset] and its length is End.Offset-Start.Offset. A half-open span is what lets an empty extent be expressed at all, and it makes the arithmetic of underlining a range subtraction rather than a subtraction and a correction.

In JSON it is a string rather than an object — see Span.MarshalJSON — and that spelling is the one the machine output contract writes.

func (Span) MarshalJSON

func (s Span) MarshalJSON() ([]byte, error)

MarshalJSON writes the span as the text Span.String renders.

It is a string rather than the two nested objects the fields would marshal to, because the object form is the single most expensive thing the engine writes: eight keys and two copies of the path for one location, repeated on every claim of every answer. docs/token-budget.md priced it at roughly half of what `dfcad get` costs and a third of `dfcad resolve`, for a reader that wants a file and a line.

The byte offsets are not written. They are a convenience for a tool which is holding the source bytes, and a tool holding the bytes is one line index away from recovering them; every other reader — a person, an editor, an agent deciding whether to open the file — wants path:line:column and pays for the offsets on every span it never reads.

func (Span) String

func (s Span) String() string

String renders the span the way it is written in JSON: path:line:column for an empty span, and path:line:column-line:column for one with extent.

The path is written once. A span never runs across two files — the extent of one node is text in one file — so repeating it on the far end would state the same thing twice.

func (*Span) UnmarshalJSON

func (s *Span) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the text form back.

What comes back carries the paths, lines and columns and leaves both offsets zero, because the text form does not write them. That is a documented property of the encoding rather than an oversight: a span is round-tripped through JSON to say where something is, and where something is has never been the offset.

type SpanTextError

type SpanTextError struct {
	// Text is the string that could not be read as a span.
	Text string
}

SpanTextError is a JSON span which is not in the form Span.MarshalJSON writes.

That is the whole of what is accepted, and it is deliberately narrower than what could be parsed. A written extent whose end is not strictly after its start is refused rather than read: `a.dfc:1:1-1:1` is an empty span written the long way and would come back out as `a.dfc:1:1`, and `a.dfc:2:5-1:1` is not a span at all. Accepting either would mean a text this package read and wrote again was not the text it was given, which is the one property a canonical encoding has.

func (SpanTextError) Error

func (e SpanTextError) Error() string

Error implements [error].

type Step

type Step struct {
	// contains filtered or unexported fields
}

Step is one edge of an assembled loop, in the order the loop is traversed and in the direction the traversal runs through it.

The direction is the step's and never the edge's. An edge is written once, with its two vertices ordered, and two loops either side of it traverse it in opposite directions — which is the whole point of the edge being one node rather than two. So a step says which vertex this traversal entered by and which it left by, and Step.Reversed reports when that is the opposite of the way the edge was written.

The zero value is a step through no edge, which no assembly yields.

func (Step) Edge

func (s Step) Edge() *Edge

Edge returns the edge the step runs through.

func (Step) From

func (s Step) From() ID

From returns the vertex the traversal entered the edge by.

func (Step) Reversed

func (s Step) Reversed() bool

Reversed reports whether the traversal runs through the edge against the order its two vertices were written in.

It is a property of this traversal and not of the edge. The edge is shared, and the room on the other side of it traverses it the other way.

func (Step) To

func (s Step) To() ID

To returns the vertex the traversal left the edge by.

type Subject

type Subject struct {
	// ID is the id the node will be written with. Its namespace is what a rule
	// matching on one compares against.
	ID ID

	// Kind is the kind it will declare.
	Kind Kind

	// Type is the type name it will declare.
	Type string
}

Subject is the new node a routing decision is about.

It is the three axes a node has before it has anything else — the namespace of its id, its kind and its type — because those are the three a routing rule matches on and the three an author has already decided by the time they ask where the node goes. Nothing here is a SemanticNode: the node being routed does not exist yet, which is the whole reason the question is being asked.

func (Subject) String

func (s Subject) String() string

String spells the subject for a message about it, which names every axis it has because a refusal to route says which node it could not place.

An axis a geometric node does not have is not printed as an empty one. "kind , type " reads as something the caller forgot rather than as the vertex it describes, and a vertex has no kind to have forgotten.

type SubjectForm

type SubjectForm string

SubjectForm is one of the forms a check may be written on, spelled as the tag that form is written with.

It is what a check declares it applies to on the axis every subject has. A check about the endpoints of an edge is meaningless on a vertex, and saying so in the declaration is what lets the mistake be a diagnostic rather than a check which quietly passes on everything it cannot examine.

const (
	SubjectNode   SubjectForm = "node"
	SubjectVertex SubjectForm = "vertex"
	SubjectEdge   SubjectForm = "edge"
	SubjectLoop   SubjectForm = "loop"
)

The forms an assertion may be written on, per specification sections 6.1 through 6.4. A type-level invariant is written on a type declaration and applies to its instances, which are nodes.

func SubjectForms

func SubjectForms() []SubjectForm

SubjectForms returns the forms an assertion may be written on, in specification order.

type Summary

type Summary struct {
	// contains filtered or unexported fields
}

Summary is what one load counted: how much of a model there is, and how much of it does not agree with itself or does not join up.

It is counted at load rather than derived on demand because it is what a command prints before anything else and what a person reads to know whether they loaded the tree they meant to. A number which is cheap to get is a number which gets printed; one which costs a traversal is one which gets left out of the output and then out of the habit.

The zero value is the summary of an empty model, which is what a tree holding no entity file yields.

func (Summary) Claims

func (s Summary) Claims() int

Claims returns how many claims the load read.

func (Summary) Conflicts

func (s Summary) Conflicts() int

Conflicts returns how many subject and predicate pairs more than one live claim was written on.

func (Summary) Edges

func (s Summary) Edges() int

Edges returns how many edges the load read.

func (Summary) Kinds

func (s Summary) Kinds() []Kind

Kinds returns the kinds the model wrote at least one node under, in the order Kinds lists them.

The order is the closed set's rather than the model's, so two models of the same shape summarise in the same order and a summary diffs against the last one. A kind nothing was written under is left out rather than reported as zero: a list of every kind with six zeroes in it hides the one line somebody is reading.

func (Summary) Loops

func (s Summary) Loops() int

Loops returns how many loops the load read.

func (Summary) Nodes

func (s Summary) Nodes() int

Nodes returns how many semantic nodes the load read.

func (Summary) OfKind

func (s Summary) OfKind(kind Kind) int

OfKind returns how many semantic nodes declared one kind.

func (Summary) OfType

func (s Summary) OfType(name string) int

OfType returns how many semantic nodes declared one type.

func (Summary) String

func (s Summary) String() string

String writes the totals as the one line a command prints after a load.

The two breakdowns are not in it. They are as long as the model's vocabulary, and a line which grows with the number of declared types is a line nobody reads; Summary.Kinds and Summary.Types are what a caller which wants them walks.

func (Summary) Types

func (s Summary) Types() []string

Types returns the type names the model wrote at least one node under, in lexical order.

Lexical, because a type is registry data and the registry's own order is a property of which file declared what — a model which moved a declaration between files would summarise differently while holding the same nodes.

func (Summary) Unresolved

func (s Summary) Unresolved() int

Unresolved returns how many references name nothing the model holds.

func (Summary) Vertices

func (s Summary) Vertices() int

Vertices returns how many vertices the load read.

type SupersedeOperation

type SupersedeOperation struct {
	// Subject is the thing the claim is about.
	Subject string `json:"subject"`

	// Predicate is the predicate the claim being corrected was written under.
	Predicate string `json:"predicate"`

	// Claim is the new value and the evidence for it.
	Claim ClaimAxes `json:"claim"`
}

SupersedeOperation corrects a value: it states the new one and retracts the old. It is `supersede`.

func (*SupersedeOperation) Name

func (o *SupersedeOperation) Name() string

Name implements Operation.

type Surface

type Surface struct {
	// contains filtered or unexported fields
}

Surface is a ground surface derived from the observations inside one region.

It is a build output and never a source. Nothing here is written into an entity file, an observation file, or anything else a walk would read ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)); the only place it is written at all is the derived cache under BuildDir, which the repository ignores and which can be deleted without changing a single answer. A surface stored as source would be a drawing of the ground which stopped being true the first time somebody took another shot.

The method travels with it

Surface.Method and Surface.Parameters are on the result rather than being remembered by whoever asked, because two interpolations of one set of points are two different surfaces. A cut-and-fill worked out against a triangulation and one worked out against a smoothed surface disagree, and the disagreement is invisible in the numbers.

Plan and elevation

The surface is a function of the first two components of its frame, and the elevation it answers with is the third ([0005](docs/decisions/0005-one-linear-unit-per-frame.md) — one unit for all three). The region supplies which shots are in it and nothing else: a region is a figure in plan, and a terrace whose loop is drawn on a slope is still surveyed in the frame's own vertical.

Its edge is the shots, not the region

A surface reaches as far as there is evidence: the convex hull of the points it rests on. A point beyond that hull is reported as outside rather than answered for (Surface.Elevation), because there is no measurement out there and continuing the last facet's slope into the neighbour's garden is a made-up number which reads exactly like a surveyed one.

The zero Surface holds nothing, is Surface.Derived false, and every method below works on it.

func (Surface) Covers

func (s Surface) Covers(at Point) bool

Covers reports whether the surface has anything to say at a point.

It is the hull test Surface.Elevation applies, asked on its own, for a caller sampling a grid which wants to know which cells are surveyed before it asks for a level in any of them.

func (Surface) Derived

func (s Surface) Derived() bool

Derived reports whether a surface was arrived at at all.

A region with too few shots in it, or with shots which all fall on one line, yields a diagnostic and no surface; this is how a caller which kept only the result tells that from a surface which happens to be flat.

func (Surface) Digest

func (s Surface) Digest() Digest

Digest returns the digest of the source tree the surface was derived from.

func (Surface) Elevation

func (s Surface) Elevation(at Point) (Elevation, bool)

Elevation returns the ground level at a point, and whether the surface has anything to say there.

The second return is the whole of the rule at the edge. A point beyond the convex hull of the shots is **outside**, and outside is reported rather than answered: the last facet's slope continued past the last shot is a number with no measurement under it, and handed back beside real ones it is indistinguishable from one. A caller which wants ground level beyond the survey has to go and take a shot there.

Only the first two components of at are read. The third is the answer.

func (Surface) Facets

func (s Surface) Facets() []SurfaceFacet

Facets returns the triangles of a SurfaceTIN surface, as indices into Surface.Points. Every other method has none.

func (Surface) Fall

func (s Surface) Fall(from, to Point) (Fall, bool)

Fall returns how much the ground drops between two points, and whether the surface has anything to say at both of them.

Both ends are answered by Surface.Elevation and are subject to the same rule at the edge: a point beyond the hull of the shots is outside, and a fall with one end outside is not answered at all rather than answered from an extrapolation nobody measured.

The uncertainty which comes back is **not** the two levels combined in quadrature. Every term the two ends share is entered once, at the difference of the weights they gave it, which is what makes a systematic error behind the whole survey cancel out of the difference instead of being counted twice into it. The independent error of a shot which backs both ends partially cancels the same way.

Only the first two components of each point are read.

Example

ExampleSurface_Fall shows a decision made against a derived surface: how much the ground falls across a patio, and whether that is known well enough to decide anything by.

The requirement is stated first and in the same units as the answer. A fall which has to be one in eighty over four metres is fifty millimetres of drop, and the survey has to resolve that well enough for the decision to turn on the patio rather than on the survey — here, five millimetres at one sigma.

The part worth reading twice is the last line of the budget. Every shot of the patio was taken in one occupation on one base station, and whatever that base station is out by is in both ends of the fall by the same amount. It therefore cancels: the difference is known better than either level it is the difference of, and a caller who combined the two levels in quadrature would have counted that error twice over and gone off to re-survey ground which was never the problem.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	graph, _ := dfcad.LoadGraph("testdata/surface/patio")

	surface, _ := graph.SurfaceWithin("site:S-patio", dfcad.SurfaceDerivation{
		Against: dfcad.Derivation{Tolerance: "boundary-closure", Position: "position"},

		// What the project says about the ground between the shots, and what an
		// afternoon on one base station is worth. Neither is in any file: the
		// first is a property of the paving and the second of the setup, and a
		// budget which assumed nought for either would be quietly optimistic.
		Roughness: 0.003,
		Systematic: []dfcad.SessionSystematic{
			{Session: "session:2026-06-03-am", Magnitude: 0.010},
		},
	})

	threshold, drain := dfcad.Point{3.5, 5, 0}, dfcad.Point{3.5, 1, 0}

	fall, inside := surface.Fall(threshold, drain)
	if !inside {
		return
	}

	fmt.Printf("the patio falls %.3f m over %.1f m, which is %.0f mm of drop\n",
		fall.Value(), fall.Run(), fall.Value()*1000)
	fmt.Printf("each level on its own is worth %.4f m\n", fall.From().Uncertainty())
	fmt.Printf("the fall between them is worth %.4f m\n", fall.Uncertainty())

	for _, term := range fall.Budget().Terms() {
		if term.Kind == dfcad.TermSystematic {
			fmt.Printf("%s: %.4f m\n", term.Name, term.Magnitude)
		}
	}

	// Which is the whole point of asking: the answer is measured against a
	// requirement somebody stated, and it does not meet it.
	fmt.Println("decides a fall known to 5 mm:", fall.Decides(0.005))
	fmt.Println("decides a fall known to 30 mm:", fall.Decides(0.030))

}
Output:
the patio falls 0.050 m over 4.0 m, which is 50 mm of drop
each level on its own is worth 0.0182 m
the fall between them is worth 0.0215 m
session:2026-06-03-am: 0.0000 m
decides a fall known to 5 mm: false
decides a fall known to 30 mm: true

func (Surface) Frame

func (s Surface) Frame() ID

Frame returns the frame every coordinate on the surface is in.

func (Surface) Hull

func (s Surface) Hull() []Point

Hull returns the convex hull of the points in plan, counter-clockwise.

It is the edge of the surface: Surface.Elevation answers inside it and reports outside beyond it.

func (Surface) Len

func (s Surface) Len() int

Len returns how many points the surface rests on.

func (Surface) Method

func (s Surface) Method() SurfaceMethod

Method returns how the points were interpolated.

func (Surface) Observations

func (s Surface) Observations() []ID

Observations returns every record the surface was derived from, sorted.

This is the traceability the surface exists to keep: a level read off it came from these shots and no others, so a base station later found to have been on the wrong mark can be followed forwards into every surface which used it.

It includes records which are not vertices — shots of a mark another shot already stands for — because they were read, judged and used to decide which point that mark is.

func (Surface) Parameters

func (s Surface) Parameters() []SurfaceParameter

Parameters returns every input the derivation was carried out under, including the method and the defaults which were filled in.

func (Surface) Points

func (s Surface) Points() []SurfacePoint

Points returns the shots the surface rests on, ordered by record identity.

func (Surface) Roughness

func (s Surface) Roughness() float64

Roughness returns how far the ground was stated to depart from the interpolation, one sigma per unit of distance in plan from the nearest shot. It is zero where the derivation stated nothing, which is what makes every level read off the surface report Elevation.Complete false.

func (Surface) String

func (s Surface) String() string

String writes what the surface is: the region, the method, and what it rests on.

func (Surface) Subject

func (s Surface) Subject() ID

Subject returns the region the surface covers.

func (Surface) Unit

func (s Surface) Unit() Unit

Unit returns the linear unit of that frame, which every length here is in.

type SurfaceBudget

type SurfaceBudget struct {
	// contains filtered or unexported fields
}

SurfaceBudget is the accumulated uncertainty of one answer read off a surface, broken out by contributing term.

It exists for the reason Budget does. A level is a weighted sum of shots, and combining everything behind it in quadrature is right only where the errors are independent: two shots of one afternoon share a base station, and a systematic error in it moves both the same way, so it adds linearly and is counted once however many shots carried it. Getting that backwards understates a level and — much worse — makes a *difference* of two levels look uncertain when the shared part of it cancels exactly.

The zero SurfaceBudget holds nothing and every method below works on it.

func (SurfaceBudget) Combined

func (b SurfaceBudget) Combined() Uncertainty

Combined reduces the budget to one standard uncertainty.

The terms combine the way specification section 6.6.5 says they do, which is the way Budget.Combined combines a budget of claims:

u = √( Σ uᵢ² + ( Σ |sⱼ| )² )

Every magnitude is already one standard deviation, so the result is too, and the Uncertainty which comes back says so. Widening is Uncertainty.Widen, which attaches the factor it widened by.

func (SurfaceBudget) Complete

func (b SurfaceBudget) Complete() bool

Complete reports whether the budget accounts for the ground between the shots.

It is false where the derivation stated no SurfaceDerivation.Roughness, which makes every figure here a floor: the uncertainty the answer has from the shots alone, with nothing said about how well the interpolation between them models ground nobody measured.

func (SurfaceBudget) Dominant

func (b SurfaceBudget) Dominant() (SurfaceTerm, bool)

Dominant returns the term contributing most to the combined figure, and whether the budget holds one to return.

It is what makes a budget actionable. "±20 mm" is a number somebody has to do something about, and what to do — take more shots, take better ones, or level the session in — is decided by which term is most of it.

func (SurfaceBudget) String

func (b SurfaceBudget) String() string

String writes the combined figure with its unit and coverage factor.

func (SurfaceBudget) Terms

func (b SurfaceBudget) Terms() []SurfaceTerm

Terms returns the accumulated terms.

The terms are a copy, down to the records attributed to each, so nothing a caller does to the result reaches back into the budget.

func (SurfaceBudget) Unit

func (b SurfaceBudget) Unit() Unit

Unit returns the linear unit every magnitude in the budget is in.

type SurfaceDerivation

type SurfaceDerivation struct {
	// Against is the geometry derivation the region is read from: the named
	// tolerance, the named position predicate, and the cache both this surface
	// and that geometry are looked up in.
	Against Derivation

	// Method is how the points are interpolated. An empty Method is
	// [SurfaceTIN], which honours the shots exactly and so is the answer a
	// caller who did not choose should get.
	Method SurfaceMethod

	// Power is the exponent [SurfaceIDW] weights distance by. Zero or less is
	// [defaultSurfacePower]. It is read by no other method.
	Power float64

	// Neighbours is how many of the nearest shots [SurfaceIDW] weights. Zero or
	// less is every shot of the region. It is read by no other method.
	Neighbours int

	// Ambiguous is whether shots the boundary rule could not confidently place
	// are used.
	//
	// It is a modelling choice and not a detail. A surface derived without them
	// stops at the shots the model is sure of, which pulls the surveyed area in
	// from the boundary; one derived with them reaches the boundary and rests
	// part way on evidence the model has said it cannot place. Neither is wrong
	// and the answer differs, so which was asked for is recorded.
	Ambiguous bool

	// Roughness is how far the ground departs from the interpolation, one sigma
	// per unit of distance in plan from the nearest shot.
	//
	// It is the only statement anybody can make about the ground *between* the
	// shots, and it has to be stated because nothing in a set of shots implies
	// it: a laid slab and a ploughed field sampled on the same grid give the
	// same arithmetic and are not known equally well. A surface derived without
	// one still answers, and every level it gives reports [Elevation.Complete]
	// false — the figure is then a floor, the uncertainty the answer has from
	// the shots alone.
	//
	// Zero or less states nothing. It is read by every method.
	Roughness float64

	// Systematic is what each occupation's shared error is worth, one entry per
	// session. A session named twice takes the larger of the two figures, for
	// the reason a budget does ([BudgetTerm.Magnitude]); a session nothing is
	// stated for contributes no shared term.
	Systematic []SessionSystematic
}

SurfaceDerivation is a request for a ground surface: which region's shots to derive it from, by which method, and under which parameters.

Every field of it ends up on the result and in the cache key. That is the point of the type: a surface is not a thing the model holds, it is the answer to this question, and an answer separated from its question is a grid of numbers nobody can check.

func (SurfaceDerivation) Parameters

func (d SurfaceDerivation) Parameters() []SurfaceParameter

Parameters is every input this derivation was carried out under, in a fixed order.

The order is fixed because this set is hashed into a cache key: two orderings of one set of parameters would key one answer under two names, and the second run would recompute what the first had already stored.

A parameter a method does not read is not reported. Recording a power on a triangulation would say that changing it changes the answer, and it does not.

type SurfaceFacet

type SurfaceFacet [3]int

SurfaceFacet is one triangle of a SurfaceTIN surface, as three indices into Surface.Points.

It is indices rather than points so that a facet and the shots it was built from cannot come apart: an elevation read off a facet names the three records it was interpolated from, and it can only do that if the facet still knows which points those were.

func (SurfaceFacet) Vertices

func (f SurfaceFacet) Vertices() (int, int, int)

Vertices returns the three indices into Surface.Points, counter-clockwise in plan.

type SurfaceKey

type SurfaceKey struct {
	// Digest is the digest of the source tree the surface was derived from.
	Digest Digest

	// Subject is the node whose area the shots were taken from.
	Subject ID

	// Method is how they were interpolated.
	Method SurfaceMethod

	// Parameters is every parameter of the derivation, rendered by
	// [SurfaceDerivation.Parameters].
	Parameters string
}

SurfaceKey identifies one derived surface: the tree it came from, the region it covers, and every parameter it was derived under.

It is Key for a surface and is separate from it for the reason Key holds the tolerance and the predicate: what is not in the tree has to be in the key, or an answer to one question is served for another. The subject is in it because a surface is one region's and not the model's.

func (SurfaceKey) String

func (k SurfaceKey) String() string

String writes the key as it reads: the digest, the region, then the parameters.

type SurfaceMethod

type SurfaceMethod string

SurfaceMethod is how a ground surface is interpolated from the shots behind it.

It is a closed set compiled in, like a geometry form and unlike a type or a tolerance ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)): each member is an algorithm this package implements, so a name nothing here implements is not a surface anybody could be handed.

Which one produced a surface travels with the surface, because two interpolations of one set of points are two different answers to the same question. A caller handed a grid of levels with no method on it cannot tell an answer which honours every shot from one which smooths them away.

const (
	// SurfaceTIN is a Delaunay triangulated irregular network with linear
	// interpolation across each facet.
	//
	// It honours every shot exactly: the elevation at a point a shot was taken
	// at is that shot's elevation, and nothing between two shots is higher or
	// lower than both. That is what makes it the method to reach for where the
	// shots are the answer rather than a sample of one.
	SurfaceTIN SurfaceMethod = "tin"

	// SurfaceIDW is inverse distance weighting: every elevation is the weighted
	// mean of the shots around it, weighted by distance in plan raised to a
	// negative power.
	//
	// It smooths, and it is the method to reach for where the shots are a noisy
	// sample of a surface which is genuinely smooth. It honours a shot exactly
	// only at the shot itself.
	SurfaceIDW SurfaceMethod = "idw"
)

func SurfaceMethods

func SurfaceMethods() []SurfaceMethod

SurfaceMethods returns every interpolation method a surface may be derived by.

func (SurfaceMethod) Known

func (m SurfaceMethod) Known() bool

Known reports whether this is a method the engine implements.

type SurfaceParameter

type SurfaceParameter struct {
	// Name is what the parameter is called.
	Name string `json:"name"`

	// Value is what it was, rendered.
	Value string `json:"value"`
}

SurfaceParameter is one input a derivation was carried out under, written the way it goes into a cache key and onto a result.

Both halves are text. A parameter set which is compared, hashed and shown has to have one rendering, and a set of typed fields of which each method uses half would need a second rendering for every one of those three jobs.

func (SurfaceParameter) String

func (p SurfaceParameter) String() string

String writes the parameter as name=value.

type SurfacePoint

type SurfacePoint struct {
	// contains filtered or unexported fields
}

SurfacePoint is one shot the surface rests on, in the surface's frame.

It is a shot and not a coordinate: which record it came from is on it, so a level read off the surface can be traced back to the afternoon somebody stood there. That is what Surface.Observations is assembled from.

The zero SurfacePoint holds no shot and every method below works on it.

func (SurfacePoint) Ambiguous

func (p SurfacePoint) Ambiguous() bool

Ambiguous reports whether the boundary rule could not confidently place the shot in the region. A surface holds such a point only where the derivation asked for one.

func (SurfacePoint) At

func (p SurfacePoint) At() Point

At returns the coordinate, in the surface's frame and unit.

func (SurfacePoint) Budget

func (p SurfacePoint) Budget() SurfaceBudget

Budget returns the shot's own uncertainty broken out by term.

It is the budget of the shot rather than of anything read off the surface: the weights an interpolation applies are not in it, and neither is the ground between this shot and the next one.

func (SurfacePoint) Carried

func (p SurfacePoint) Carried() bool

Carried reports whether the shot was written in another frame and transformed before it was used.

func (SurfacePoint) Coincident

func (p SurfacePoint) Coincident() []ID

Coincident returns every other record this point stands for: shots which fall within the derivation's tolerance of it in plan and so are the same point.

They are recorded rather than dropped. Two shots of one mark half an hour apart are evidence about repeatability, and a surface which mentioned only the one it happened to keep would lose the other from its provenance entirely.

func (SurfacePoint) Elevation

func (p SurfacePoint) Elevation() float64

Elevation returns the third component of the coordinate, which is what a surface is a surface of.

func (SurfacePoint) Independent

func (p SurfacePoint) Independent() float64

Independent returns the part of that uncertainty which correlates with no other shot — the instrument's own precision, and the random part of any transform the shot was carried across.

It is separate from SurfacePoint.Uncertainty because it is the only part which averages away. Twenty shots of one afternoon reduce this by a factor of four or so between them and reduce the systematic terms by nothing at all.

func (SurfacePoint) Observation

func (p SurfacePoint) Observation() ID

Observation returns the identity of the record this point was read from.

func (SurfacePoint) Session

func (p SurfacePoint) Session() ID

Session returns the occupation that record belongs to.

func (SurfacePoint) String

func (p SurfacePoint) String() string

String writes the point as its record and where it is.

func (SurfacePoint) Systematic

func (p SurfacePoint) Systematic() []SurfaceTerm

Systematic returns the shared terms the shot carries, sorted by the id each is shared with.

func (SurfacePoint) Uncertainty

func (p SurfacePoint) Uncertainty() float64

Uncertainty returns the standard uncertainty of that elevation, one sigma: the independent part and every systematic term the shot carries, combined the way a budget combines them.

func (SurfacePoint) Unit

func (p SurfacePoint) Unit() Unit

Unit returns the linear unit the coordinate and every uncertainty on the shot are in.

type SurfaceTerm

type SurfaceTerm struct {
	// Kind is which of the two kinds of error this is, and so how it combines:
	// independent terms in quadrature, systematic terms linearly.
	Kind TermKind

	// Name is what to call the term in a report: the record for a shot's own
	// error, the term id for a shared one, and [interpolationTerm] for the
	// ground between the shots.
	Name string

	// Source is the id a systematic error is shared with — a session, or the
	// control the transform which carried a shot was fitted to. It is empty for
	// an independent term.
	Source ID

	// Magnitude is the one-sigma contribution to the answer, in the surface's
	// unit, with the weight of everything which carried it already applied.
	//
	// It is zero for a term which cancelled: a session error behind both ends of
	// a fall moves both by the same amount and is not in the difference at all.
	// Such a term is reported rather than dropped, because "the base station
	// cancels" is the answer to why a fall is known better than either level.
	Magnitude float64

	// From are the records which carried the term into this answer, sorted.
	From []ID
}

SurfaceTerm is one term of the budget of something read off a surface.

It is BudgetTerm for a surface and is separate from it for one reason: what contributes here is an observation record and not a claim, and a budget which had to name a claim could not attribute a level to the afternoon somebody stood there. The two kinds combine identically — [0006](docs/decisions/0006-accuracy-is-one-sigma.md) — and SurfaceBudget applies exactly the arithmetic Budget.Combined does.

The magnitude is what the term contributes to *this* answer, weight already applied. An independent shot which carries a tenth of the weight of a level contributes a tenth of its own uncertainty to it, and the term says so rather than making a reader multiply.

func (SurfaceTerm) Shared

func (t SurfaceTerm) Shared() bool

Shared reports whether more than one record carried this term.

func (SurfaceTerm) String

func (t SurfaceTerm) String() string

String writes the term as it reads in a report.

The interpolation term names the shot its distance was measured from, because an answer with two ends has two of them and neither is the other.

type Survey

type Survey struct {
	// Positions is where the vertices are.
	Positions Positions

	// Evidence is the claim each of those positions was read from.
	Evidence Evidence

	// Curvature is the arc each edge which bends bends along. An edge which is
	// absent is straight.
	Curvature Curvature

	// Tolerance is the name — never a number — of the tolerance corners are
	// judged coincident and rings judged planar against.
	Tolerance string

	// Chord is the name — never a number — of the tolerance a curve is drawn
	// to where an answer cannot be reached without straight segments: an
	// overlay, a setback, a fit, and the nesting of several rings one of which
	// bends.
	//
	// Empty is a survey which refuses such a question rather than answering it
	// at a resolution nobody named, which is what every caller which named no
	// chord gets and what the engine did before there was a name to give. It is
	// never a fallback and never a default
	// ([0012](docs/decisions/0012-tolerances-are-registry-data.md)): how closely
	// a curve has to be followed is a decision a project makes, and a figure
	// computed to a resolution the engine picked would be an approximation
	// nobody could judge.
	//
	// Nothing which can be computed from the arc itself reads it. An area, a
	// length, a centroid and a bounding box are computed from the
	// parameterisation, so naming a chord does not move them and not naming one
	// does not stop them.
	Chord string

	// Registry is the vocabulary the frames, their units and the tolerance are
	// read from.
	Registry *Registry
}

Survey is what a measurement is computed against: where the corners are, the claims which put them there, the tolerance corners are judged coincident against, and the registry the frames and their units are read from.

They travel together because every measurement needs them, and because an answer computed against some of them could not say what it was computed against. A size is not a fact about a shape alone: it is a fact about a shape, read in a frame whose unit the registry declares, from positions which are claims, judged against a tolerance a project wrote down ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).

The zero Survey measures nothing and reports why, which is what a caller which has not loaded a registry yet gets rather than a panic.

func (*Survey) Bend

func (s *Survey) Bend(edge ID, centre, through Resolution)

Bend records that one edge bends along an arc, from the resolution which decided where its centre is.

It is to Curvature what Survey.Place is to Positions, and it is here for the same reason: the centre of an arc is a claim like any other, and a caller filling the curvature without the evidence behind it leaves an answer whose budget is narrower than what it rests on.

The evidence recorded is the centre's, because the centre is what every figure computed from the arc rests on. Arc.Through says which of two arcs was meant and moves nothing, so accumulating its accuracy would widen a budget by a claim no figure was computed from.

An edge either bends or does not, so an arc with only one of its two positions resolved bends nothing. That is not a curve half stated, it is a claim somebody has yet to write.

Either half stated with no accuracy is read by the rule Survey.Place reads a corner by: it is unranked rather than absent.

Example

A curved wall is kept as the curve it is, and measured from the circle rather than from a drawing of it.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/measure/arcs"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	// Which predicates carry an arc is vocabulary this repository owns too, so
	// the two behind one are resolved here and handed in. An edge nobody has
	// claimed a centre for is straight.
	for edge := range topology.Edges() {
		centre, _ := claims.Resolve(edge.ID(), "arc-centre", registry)
		through, _ := claims.Resolve(edge.ID(), "arc-through", registry)
		survey.Bend(edge.ID(), centre, through)
	}

	room, _ := nodes.Node("site:S-01")

	measurement, _ := topology.MeasureRegion(room, boundaries, survey)

	// Four metres square, plus the half disc its east wall bows out into. The
	// figure is the closed form and not a sum over chords, so it is right to
	// every digit rather than to whatever resolution somebody drew at.
	area, _ := measurement.Area()
	length, _ := measurement.Length()
	fmt.Printf("%s: %.6f %s², bounded by %.6f %s of wall\n",
		measurement.Subject(), area, measurement.Unit(), length, measurement.Unit())

	// Straight lines are wanted only where something actually needs them, and
	// then the tolerance is named and travels with the answer.
	bay, _ := topology.Edge("geom:E-02")
	drawn, _ := topology.TessellateEdge(bay, survey, "chord-deviation")

	fmt.Printf("%s drawn as %d segments, within %.6f %s of the curve, to %s\n",
		drawn.Subject(), len(drawn.Points())-1, drawn.Deviation(), drawn.Unit(), drawn.ChordTolerance().Name)

}
Output:
site:S-01: 22.283185 m², bounded by 18.283185 m of wall
geom:E-02 drawn as 16 segments, within 0.009631 m of the curve, to chord-deviation

func (*Survey) Place

func (s *Survey) Place(vertex ID, resolution Resolution)

Place records where one vertex is, from the resolution which decided it.

It is what keeps Survey.Positions and Survey.Evidence in step. Both come from one resolution per vertex, and a caller filling them separately can leave a corner whose position is measured and whose provenance is not — which shows up much later as an answer with a narrower budget than the evidence supports.

A position claim which states no accuracy is placed, and is its own evidence. Specification section 6.5 makes it unrankable rather than absent: it cannot win, and it is still the answer where nothing rankable was said. It contributes no term to any budget computed from it — it taints the budget as unknown, which is what Budget.Unranked then names — so a corner nobody gave an accuracy to is measured from where the model says it is, and the answer says it rests on a claim nobody ranked rather than folding it in as though it carried an accuracy.

A resolution which read nothing places nothing: a vertex nobody has surveyed yet, and one whose claims tie, which the rule declined to choose between.

type TakenIDError

type TakenIDError struct {
	// ID is the id which was asked for.
	ID ID

	// What names the sort of thing which already holds it, so that the refusal
	// says what was hit rather than only that something was.
	What string

	// At is where that thing is defined.
	At Span

	// Retired reports whether the thing which holds it was retired, which is
	// the case an author is most likely to have thought was free.
	Retired bool
}

TakenIDError reports an id which already names something in the model.

An id is unique across the whole model and is never issued again to a different thing, which is what makes a reference written years ago mean today what it meant then ([0002](docs/decisions/0002-immutable-id-mutable-label.md)). A retired id is taken as firmly as a live one is: retiring says the thing stopped existing, not that its name came free.

func (TakenIDError) Error

func (e TakenIDError) Error() string

Error implements the [error] interface.

type TargetError

type TargetError struct {
	// Path is the file, as it was asked for.
	Path string

	// Root is the model root it was judged against.
	Root string

	// Err is why it was refused: [ErrOutsideModel] or [ErrNotAnEntityFile].
	Err error
}

TargetError reports a file a transaction refuses to write.

Both reasons are the same mistake seen from two sides: a file the model would not read back is a change which appears to have been made and was not. A path outside the root is never walked, and a path inside it whose extension is not Extension is stepped over.

func (TargetError) Error

func (e TargetError) Error() string

Error implements the [error] interface.

The root is carried as a field rather than printed, because the reasons name it themselves where it is the point.

func (TargetError) Unwrap

func (e TargetError) Unwrap() error

Unwrap returns the underlying failure.

type TermKind

type TermKind string

TermKind is which of the two kinds of error an accuracy term describes, per specification section 6.6.5.

const (
	// TermIndependent is an error which does not correlate with any other.
	// Independent terms combine in quadrature.
	TermIndependent TermKind = "independent"

	// TermSystematic is an error shared with everything else naming the same
	// term id. Systematic terms add linearly, and a term contributing to two
	// inputs of one derivation is counted once.
	TermSystematic TermKind = "systematic"
)

The accuracy terms, in the order specification section 6.6.5 lists them. The string value is the tag the term is written with.

type TermProblem

type TermProblem string

TermProblem says why text written where an accuracy term belongs is not one.

const (
	// TermUnknownKind is a term which is neither independent nor systematic.
	TermUnknownKind TermProblem = "unknown kind"

	// TermWrongCount is a term written with the wrong number of parts for its
	// kind.
	TermWrongCount TermProblem = "wrong number of parts"

	// TermNotANumber is a magnitude which is not a real number.
	TermNotANumber TermProblem = "magnitude is not a number"
)

type Tessellation

type Tessellation struct {
	// contains filtered or unexported fields
}

Tessellation is a curve replaced by the straight segments which stand in for it, together with the chord tolerance that was decided to.

The tolerance travels with the result because the result is meaningless without it. A list of points which does not say how closely it follows the curve it came from is exactly the approximation this package refuses to bake into a model: nobody downstream can tell whether it is good enough for what they are about to do with it, and nobody can reproduce it.

Nothing here is ever written back ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). A tessellation is computed at the moment something needs straight lines and is thrown away after; the arc in the model is untouched and stays exact.

The zero Tessellation holds no points, which is what tessellating nothing yields; every method below works on it.

func (Tessellation) ChordTolerance

func (t Tessellation) ChordTolerance() Tolerance

ChordTolerance returns the declared tolerance the curve was drawn to: how far a segment standing in for the curve was allowed to fall from it.

It is a tolerance the registry declares and never a number this package chose ([0012](docs/decisions/0012-tolerances-are-registry-data.md)). How closely a curve has to be followed is a decision a project makes — a millimetre for a setting-out drawing, a hundred millimetres for an area take-off — and a default compiled in here would be the engine making it for them.

func (Tessellation) Closed

func (t Tessellation) Closed() bool

Closed reports whether the points form a ring, which they do when the loop they came from closed.

func (Tessellation) Deviation

func (t Tessellation) Deviation() float64

Deviation returns the furthest any segment falls from the curve it stands in for, in Tessellation.Unit.

It is what was actually achieved rather than what was asked for, and it is always within Tessellation.ChordTolerance. The two differ because a curve is divided into a whole number of segments: an arc which needs two and a bit segments gets three, and follows the curve more closely than it had to.

func (Tessellation) Points

func (t Tessellation) Points() []Point

Points returns the ends of the segments, in traversal order.

A ring does not repeat its first point at the end, which Tessellation.Closed is what says. Every arc contributes its own two ends exactly as they were surveyed, so two tessellations which meet at a corner meet at the corner and not near it.

func (Tessellation) String

func (t Tessellation) String() string

String writes how many segments the curve became and how closely they follow it.

func (Tessellation) Subject

func (t Tessellation) Subject() ID

Subject returns the id of the edge or loop which was tessellated.

func (Tessellation) Unit

func (t Tessellation) Unit() Unit

Unit returns the linear unit of the frame it was computed in, which its points and its deviation are in.

type TimestampProblem

type TimestampProblem string

TimestampProblem is the rule of observation specification section 4.2 a timestamp broke.

It is a string so that the machine-readable form is the same word the human rendering prints, which is the convention Severity follows for the same reason.

const (
	// TimestampNotRFC3339 is text which is not an RFC 3339 date-time at all.
	TimestampNotRFC3339 TimestampProblem = "not-rfc3339"

	// TimestampNoOffset is a date-time written with no offset. It is a local
	// time in a zone the file does not name, so it denotes a different instant
	// depending on where it is read, and two records written this way cannot be
	// ordered.
	TimestampNoOffset TimestampProblem = "no-offset"

	// TimestampUnknownOffset is a date-time written with the offset -00:00,
	// which RFC 3339 section 4.3 defines as *the offset is unknown*. A record
	// whose instant is unknown is not evidence of when anything was measured.
	TimestampUnknownOffset TimestampProblem = "unknown-offset"
)

type Tolerance

type Tolerance struct {
	// Name is the tolerance name.
	Name string

	// Value is its magnitude.
	Value float64

	// Unit is the unit that magnitude is in.
	Unit Unit

	// Description is free text. Empty when it was not written.
	Description string

	// Span is where the declaration was written.
	Span Span
}

Tolerance is one declared named tolerance, per specification section 7.6.

No numeric literal tolerance appears in engine code and none appears in an assertion: an operation that needs one takes a name and reports which name it used ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).

type ToleranceUnitError

type ToleranceUnitError struct {
	// Tolerance is the declaration which was reached for.
	Tolerance Tolerance

	// Frame is the frame it was to be applied in.
	Frame ID

	// Want is the frame's unit, which is what it had to be declared in.
	Want Unit
}

ToleranceUnitError reports a tolerance declared in a unit other than the one of the frame it is being applied in.

Nothing converts between units ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)). A tolerance in millimetres silently scaled to judge a frame in metres is the mistake that decision exists to prevent, and one applied without scaling would be a thousand times the number somebody wrote down.

func (ToleranceUnitError) Error

func (e ToleranceUnitError) Error() string

Error implements the [error] interface.

type TooFewCornersError

type TooFewCornersError struct {
	// Corners is how many were written.
	Corners int
}

TooFewCornersError reports a corner list which cannot describe a ring.

A closed list names its first corner twice, so the shortest one there is has four entries and describes a triangle. Anything shorter is not a loop which failed to close; it is a list which never described one.

func (TooFewCornersError) Error

func (e TooFewCornersError) Error() string

Error implements the [error] interface.

type Topology

type Topology struct {
	// contains filtered or unexported fields
}

Topology is the geometric family of one load: every vertex, edge and loop the walk read, in the order it read them, and each indexed by id.

The name is the one the three members have together. They are the topological entities of a boundary representation — a point, a connection between two points, and a ring of connections — and what this type holds is the way they refer to one another rather than any coordinate, which lives on a claim.

The index is the load's own, for the reason Nodes holds one: an id is unique across the whole model, so a load has to build an index to find a duplicate at all, and two indexes over one model would be two answers to "what is geom:V-01".

A Topology is read-only once loaded. The zero value holds nothing, which is what a source tree with no geometry in it yields, and every method below works on it.

func (*Topology) Assemble

func (t *Topology) Assemble(loop *Loop, positions Positions, tolerance string, registry *Registry) (Assembly, []Diagnostic)

Assemble reads a loop as the ring its edges traverse and reports whether that ring closes, judged against the named tolerance.

The order of the loop's edges is the order it is traversed, and the edges themselves are directed, so assembling one means deciding which way round each edge is entered: the ring is what says that, and an edge shared by two regions is traversed one way by one of them and the other way by the other.

tolerance is a name from the tolerance registry and never a number. A name nothing declares is a diagnostic, and closure is then decided by vertex identity alone; there is no default and no fallback ([0012](docs/decisions/0012-tolerances-are-registry-data.md)). Which tolerance produced the answer comes back on the assembly, because an answer computed against a tolerance which does not say which one cannot be reproduced.

positions is where the vertices are, which the caller resolves under whichever predicate its registry declares for a position. It is what a gap is measured with. A vertex with no resolved position is not a failure: the gap is reported as one whose size could not be measured, which is what is true.

Everything is measured in the unit of the loop's frame, and nothing is converted. A frame has exactly one linear unit ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)), so a position written in another unit, or a tolerance declared in one, is reported rather than silently scaled.

The three ways a loop fails are three diagnostics, because they are three different mistakes with three different fixes:

  • A gap. Two edges which should meet do not, and nothing brings them within the tolerance. The diagnostic names both corners and how far apart they are, so the author knows whether this is a typo or a survey which moved.
  • An order. The edges do form one ring, but not in the order they are written. Nothing is missing and nothing has to move; the list has to be rewritten in the order the ring is walked.
  • A shape which is not a simple cycle. An edge written twice, a corner where three edges meet, or edges which form more than one ring. No reordering fixes any of them, which is why calling them a gap would send the author looking in the wrong place.

Diagnostics come back in the order the pass found them. Collecting them into a Diagnostics is what puts them in reporting order.

Example

ExampleTopology_Assemble reads a loop as the ring its edges traverse and says whether it closes, against a tolerance the registry declares by name.

The answer is computed and never stored: adding an edge changes it with no other edit, and a recorded answer would be stale the moment a corner moved.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/boundary/valid"

	registry, _ := dfcad.LoadRegistry(root)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)

	// Which predicate carries a position is vocabulary this repository owns, so
	// the positions are resolved here and handed in rather than looked up by a
	// name the engine would have to know.
	positions := make(dfcad.Positions)
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		if value, ok := resolution.Value(); ok {
			positions[vertex.ID()] = value
		}
	}

	loop, _ := topology.Loop("geom:L-02")

	assembly, _ := topology.Assemble(loop, positions, "boundary-closure", registry)

	fmt.Printf("%s closes: %t, judged against %s (%v %s)\n",
		loop.ID(), assembly.Closed(), assembly.Tolerance().Name, assembly.Tolerance().Value, assembly.Tolerance().Unit)

	// The corridor runs through the shared partition against the order that
	// edge was written in, because the room on the other side runs through it
	// the other way. One edge, one identity, a direction per traversal.
	for _, step := range assembly.Steps() {
		fmt.Printf("  %s: %s to %s, reversed: %t\n", step.Edge().ID(), step.From(), step.To(), step.Reversed())
	}

}
Output:
geom:L-02 closes: true, judged against boundary-closure (0.005 m)
  geom:E-05: geom:V-02 to geom:V-05, reversed: false
  geom:E-06: geom:V-05 to geom:V-06, reversed: false
  geom:E-07: geom:V-06 to geom:V-03, reversed: false
  geom:E-02: geom:V-03 to geom:V-02, reversed: true

func (*Topology) AssembleRun

func (t *Topology) AssembleRun(loop *Loop, positions Positions, tolerance string, registry *Registry) (Assembly, []Diagnostic)

AssembleRun reads a loop as the open run of edges its traversal walks, and is Topology.Assemble with the one requirement a run does not have: that the walk returns to the corner it began at.

A door, a window, a railing, a wall run and a duct are each an open chain of edges rather than a region, which is what the geometry form `line` declares. The edges are written the way a loop's are — ordered, in one frame, resolving to edges this model holds — because a run is the same authoring and not a second one: a chain and a ring differ in whether the last edge ends where the first began, and in nothing else.

So every refusal Topology.Assemble makes is made here too. An edge written twice doubles back, a corner where three edges meet is a branch, and edges in two disconnected pieces are two runs; none of the three is fixed by closing anything, and each is refused with the same distinction drawn between it and the others. What is not refused is the loose end: a chain has exactly two of them, and having them is what a run *is* rather than a mistake in one.

Order is still the order the run is walked, and edges written in some other order are reported as being in the wrong order rather than as a gap — the same diagnostic a ring gets, for the same reason. A run whose ends happen to meet is a ring somebody drew as a chain: it comes back closed as well as open, and nothing is refused for it.

Assembly.Open reports which of the two readings produced an assembly, and Assembly.Closed whether the walk came back to where it started.

Example

ExampleTopology_AssembleRun reads a loop as the open run of edges it walks, which is the shape a node declaring the geometry form `line` has.

A door, a window, a railing, a wall run and a duct all begin somewhere and end somewhere else. Asking one of them to close would be asking it to be a rectangle standing beside the wall rather than a run along it, so the one requirement dropped here is that requirement — every other refusal a loop is read under is made exactly as it is of a ring.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/boundary/run"

	registry, _ := dfcad.LoadRegistry(root)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)

	positions := make(dfcad.Positions)
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		if value, ok := resolution.Value(); ok {
			positions[vertex.ID()] = value
		}
	}

	railing, _ := topology.Loop("geom:L-12")

	assembly, _ := topology.AssembleRun(railing, positions, "boundary-closure", registry)

	// Open, and not closed. The two answers are different questions: the first
	// is how the edges were read and the second is whether the walk came back to
	// where it began.
	fmt.Printf("%s open: %t, closed: %t\n", railing.ID(), assembly.Open(), assembly.Closed())

	// The chain begins at the corner the room's south wall ends at, so moving
	// that vertex moves the wall and the railing together.
	for _, step := range assembly.Steps() {
		fmt.Printf("  %s: %s to %s\n", step.Edge().ID(), step.From(), step.To())
	}

}
Output:
geom:L-12 open: true, closed: false
  geom:E-21: geom:V-03 to geom:V-21
  geom:E-22: geom:V-21 to geom:V-22

func (*Topology) BuildableOf

func (t *Topology) BuildableOf(
	node *SemanticNode,
	boundaries *Boundaries,
	survey Survey,
	setbacks Setbacks,
) (Buildable, []Diagnostic)

BuildableOf derives the area left buildable inside a node's boundary once every edge's setback has been taken off it.

The boundary is read with Topology.RegionOf, so everything that refuses a region refuses this: a ring which does not close, corners which are not in one plane, a boundary which bends, a tolerance the registry does not declare in the frame's unit. The setback of each edge is resolved from the claims written on that edge, under the predicate Setbacks names, by the ordinary resolution rule — so the most accurate current claim wins and the evidence comes back with the answer.

Every edge needs one. An edge with no live claim under the predicate is a diagnostic naming that edge and no region, because the alternative is to read the silence as nought and site a building up against a boundary nobody intended it to touch. A setback of nought is a thing somebody can write down, and writing it down is how it is said.

The construction is Region.Buffer's, applied per edge: the strip within the setback of an edge is taken off the parcel, and what is left is what is at least that far inside every edge. Corners are rounded to the declared tolerance the same way, so a front setback and a side setback meeting at a corner cannot disagree about where the corner of the buildable area is. What is never produced is the inside-out shape offsetting each edge on its own gives when the offsets cross over each other: setbacks which meet in the middle leave a region covering nothing, reported as a warning rather than as a failure, because "nothing is buildable here" is the answer to the question and a permit application is exactly where it needs to be legible.

Diagnostics are collected rather than stopped at: a parcel missing three setback claims reports all three, so fixing it is one edit rather than three rounds of the same guess.

Example

ExampleTopology_BuildableOf derives what may be built on a plot from the plot's boundary and the setback claimed on each of its edges.

Nothing in the model says what is buildable. The region is read back out of the corners, the edges and the claims every time it is asked for, so the day the frontage setback changes there is no second polygon left saying the old answer — which is the failure this derivation exists to make unrepresentable, because the shape it describes is the one a permanent structure gets placed against.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/buildable/parcels"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	setbacks := dfcad.Setbacks{Predicate: "setback", Claims: claims}

	// Six metres at the road, three at each flank and four at the rear. Which
	// edge is which is written on the edges rather than known here.
	plot, _ := nodes.Node("plan:P-01")

	sited, _ := topology.BuildableOf(plot, boundaries, survey, setbacks)
	fmt.Println(sited.Report())

	// How well the edge of it is known follows from the corners and from the
	// setbacks together, term by term, with the control point every corner was
	// shot from counted once.
	combined, _ := sited.Budget().Combined()
	dominant, _ := sited.Budget().Dominant()
	fmt.Printf("±%.3f %s, of which the largest term is %s\n",
		combined.Standard(), combined.Unit, dominant.Name)

	// A plot its own setbacks consume comes back covering nothing, with a
	// diagnostic saying so. It is the answer to the question rather than a
	// failure to answer it, so it is a warning and the region is still a region.
	infill, _ := nodes.Node("plan:P-02")

	consumed, diags := topology.BuildableOf(infill, boundaries, survey, setbacks)
	fmt.Println(consumed, diags[0].Severity)

}
Output:
plan:P-01: 240.0 m² buildable of 600.0 m²
  geom:E-101: 6.0 m
  geom:E-102: 3.0 m
  geom:E-103: 4.0 m
  geom:E-104: 3.0 m
±0.023 m, of which the largest term is the setback of geom:E-101
nothing is buildable inside plan:P-02 warning

func (*Topology) Edge

func (t *Topology) Edge(id ID) (*Edge, bool)

Edge returns the edge id names, and whether the model holds one.

func (*Topology) Edges

func (t *Topology) Edges() iter.Seq[*Edge]

Edges iterates the edges in the order the walk reached them.

func (*Topology) FitWithin

func (t *Topology) FitWithin(
	proposal, envelope *SemanticNode,
	boundaries *Boundaries,
	survey Survey,
	siting Siting,
) (Fit, []Diagnostic)

FitWithin answers whether one node's area sits inside another's, across whatever frame chain relates the two, and says how well the answer is known.

It is one composition of steps which exist separately, and the composition is the story: the envelope and the proposal are read with Topology.RegionOf, the proposal is carried into the envelope's frame with Region.In, grown by the required clearance with Region.Buffer, overlaid on the envelope with Region.Intersect and Region.Difference, and measured. Every one of those accumulates the accuracy of what it read, so the budget which comes out is the budget of the answer and not of any one step.

**Everything the steps refuse, this refuses.** A ring which does not close, a tolerance the registry declares in the wrong unit, two frames with no measured chain between them, a clearance shorter than the distance two corners are one corner — each is the diagnostic the step which found it writes, pointing where the edit is. Nothing here re-words them, and nothing here works around one.

A proposal and an envelope declared in one frame are compared without reading a transform at all, and the budget then holds no georeference term because none was applied. That is the difference the whole arrangement is about: a cross-frame answer costs what the georeference costs, and it says so.

Where Siting.Setbacks is given, what the proposal is sited inside is not the envelope's outline but what the setback claimed on each of its edges leaves buildable, derived as Topology.BuildableOf derives it and refused as it refuses: an edge with no live setback claim is a diagnostic naming that edge, never a setback of nought. The budget then carries the setback claims and the envelope's corners beside the proposal's corners and the transforms, in one budget — a control point behind the boundary survey and the georeference alike is counted once, where combining the answers of `buildable` and of a fit against the outline would count it twice. Setbacks which leave nothing buildable are answered rather than refused: nothing fits inside a region which covers nothing, and Fit.Consumed says that was why.

The two nodes may be the same node, which fits inside itself with a clearance of nought — an answer rather than a mistake, and one whose uncertainty is the accuracy of its own corners.

Diagnostics are collected rather than stopped at, and a fit which was computed and cannot be decided comes back with VerdictUnknown and a warning saying why, rather than as a failure: "this could not be worked out" and "this was worked out and the model cannot tell" are different answers.

Example
package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/siting/surveyed"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	// The frames are joined to the claims which measure them, because the
	// relationship between two of them is a measurement and not a setting.
	frames, _ := dfcad.ResolveFrames(registry, claims)

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	// The footprint was set out on the building's own grid and the plot was
	// surveyed on the site grid, so deciding this reads the georeference.
	footprint, _ := nodes.Node("plan:S-01")
	plot, _ := nodes.Node("plan:P-01")

	answer, _ := topology.FitWithin(footprint, plot, boundaries, survey, dfcad.Siting{Frames: frames})

	combined, _ := answer.Uncertainty()
	fmt.Printf("%s: %.2f m clear, ±%.4f m, carried across %s\n",
		answer.Verdict(), answer.Clearance(), combined.Standard(), answer.DeclaredIn())

	// The control point behind the interior corners is behind the boundary
	// survey and the georeference as well. It is one error however many inputs
	// reach it, so it appears in the sum once — and adds linearly rather than in
	// quadrature, because it does not cancel against itself.
	var shared dfcad.BudgetTerm
	for _, term := range answer.Budget().Terms() {
		if term.Shared() {
			shared = term
		}
	}

	fmt.Printf("%s %s: %.3f m from %d claims\n",
		shared.Kind, shared.Name, shared.Magnitude, len(shared.Contributors))

	// A clearance inside its own uncertainty is neither a pass nor a failure.
	// Ten millimetres of daylight is no answer at all when the answer is known
	// to twenty.
	tight, _ := nodes.Node("plan:S-03")

	marginal, diags := topology.FitWithin(tight, plot, boundaries, survey, dfcad.Siting{Frames: frames})
	fmt.Println(marginal.Verdict(), marginal.Verdict().Decided(), diags[0].Severity)

	// What the plot allows is narrower than the plot. The setback claimed on each
	// of its edges is taken off that edge, and the footprint is sited inside
	// what is left — derived here, never authored, and in the same budget as
	// everything else, so the plot's control point is still counted once.
	allowed, _ := topology.FitWithin(footprint, plot, boundaries, survey, dfcad.Siting{
		Frames:   frames,
		Setbacks: dfcad.Setbacks{Predicate: "setback", Claims: claims},
	})

	derivation, _ := allowed.Buildable()
	within, _ := allowed.Uncertainty()
	fmt.Printf("%s: %.2f m clear of %.0f m² buildable, ±%.4f m\n",
		allowed.Verdict(), allowed.Clearance(), derivation.Area(), within.Standard())

}
Output:
fits: 4.00 m clear, ±0.0203 m, carried across frame:building
systematic control:CP-1: 0.008 m from 9 claims
might-fit false warning
does-not-fit: -2.00 m clear of 240 m² buildable, ±0.0204 m

func (*Topology) Len

func (t *Topology) Len() int

Len reports how many geometric nodes were read, of all three sorts together.

func (*Topology) Loop

func (t *Topology) Loop(id ID) (*Loop, bool)

Loop returns the loop id names, and whether the model holds one.

func (*Topology) Loops

func (t *Topology) Loops() iter.Seq[*Loop]

Loops iterates the loops in the order the walk reached them.

func (*Topology) MeasureEdge

func (t *Topology) MeasureEdge(edge *Edge, survey Survey) (Measurement, []Diagnostic)

MeasureEdge measures one edge: how long it is, where its midpoint is and how far it reaches.

Everything is in the unit of the edge's frame and nothing is converted. A position written in another unit is not read at all, which is reported rather than scaled ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

An edge whose two ends are at the same point is a diagnostic and not a length of zero quietly returned. It gives a loop through it no direction, and the author who wrote it meant two corners.

func (*Topology) MeasureLoop

func (t *Topology) MeasureLoop(loop *Loop, survey Survey) (Measurement, []Diagnostic)

MeasureLoop measures one loop: its area, its perimeter, its centroid and its bounding box.

The loop is assembled first, because a size is a property of the ring its edges traverse and not of the list they were written in. Every diagnostic Topology.Assemble raises comes back from here, and a loop which does not assemble into one closed ring has no area — which is reported as no answer rather than as the signed sum over whatever the edges did form.

Three more things stop an area being computable, each its own diagnostic because each is a different mistake: corners which do not lie in one plane, a ring which crosses itself, and a ring whose corners are collinear and so enclose nothing.

func (*Topology) MeasureRegion

func (t *Topology) MeasureRegion(region *SemanticNode, boundaries *Boundaries, survey Survey) (Measurement, []Diagnostic)

MeasureRegion measures a semantic node from the loops which bound it: the area it encloses, the total length of its boundary, its centroid and its bounding box.

The region holds no coordinate of its own. It references loops, the loops reference edges and the edges reference vertices, so a measurement of it is computed the whole way down every time it is asked — which is why it cannot disagree with the geometry it describes ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

A region bounded by more than one ring is measured by nesting. A ring inside another is a hole and its area is taken away; a ring inside that hole is an island and is added back. That is the even-odd rule, and it is what makes a courtyard subtract without anything in the model having to say which loop is the outside one.

A node which declares the geometry form `line` is read as open runs instead. Its loops are the same authoring — ordered edges, refused for a branch, a doubled edge or a shape in two pieces — and are walked as chains rather than as rings, so what comes back is how far the run reaches and the box around it, with no area and no centroid. A door, a railing and a wall run are each that shape, and requiring one of them to close would be requiring it to be something else.

A node which declares the geometry form `point` is read from the position claimed of the node itself instead. It references no loop and never will — a receptacle is not a rectangle, and authoring one as a ring would be inventing dimensions the model does not have — so what places it is a claim written on it, under the same predicate a corner's position is written under. What comes back is what Topology.MeasureVertex returns for a corner: the point as the centroid, the box of zero extent around it as the bounds, no length and no area, and the accuracy of the claim which put it there.

A region which references no loop is not malformed — a circuit group and a warranty have no outline — and measures nothing.

Example

ExampleTopology_MeasureRegion answers how big a room is from the boundary it references, rather than from a number written down beside it.

An area recorded in the model is a second source of truth. It is right on the day somebody typed it and wrong the first time a wall moves, and nothing in the file says which of those it currently is. Computing it means the question cannot be answered wrongly: the corners are the only thing stated, and the answer is derived from them every time it is asked.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/measure/courtyard"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	// Which predicate carries a position is vocabulary this repository owns, so
	// the positions are resolved here and handed in. Place fills the claim behind
	// each one at the same time, which is what lets the answer carry a budget.
	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	plate, _ := nodes.Node("site:S-01")

	measurement, _ := topology.MeasureRegion(plate, boundaries, survey)

	// Ten metres square, less a four-metre courtyard in the middle of it.
	// Nothing in the model says which of the two loops is the hole: the one
	// inside the other is, and it is taken away.
	area, _ := measurement.Area()
	length, _ := measurement.Length()
	fmt.Printf("%s: %g %s², bounded by %g %s of wall\n", measurement.Subject(), area, measurement.Unit(), length, measurement.Unit())

	// And how well that is known, which is the whole reason a position is a
	// claim: the tie to the control point is one error shared by every corner,
	// so it is counted once instead of eight times.
	combined, _ := measurement.Budget().Combined()
	dominant, _ := measurement.Budget().Dominant()
	fmt.Printf("corners known to %s, mostly %s\n", combined, dominant.Name)

}
Output:
site:S-01: 84 m², bounded by 56 m of wall
corners known to 0.013856406460551019 m (k = 1.0, ≈ 68%), mostly control:CP-3

func (*Topology) MeasureVertex

func (t *Topology) MeasureVertex(vertex *Vertex, survey Survey) (Measurement, []Diagnostic)

MeasureVertex measures one corner: where it is, and how far it reaches, which for a point is the same answer twice.

A corner has no extent, so it has no length and encloses no area, and both come back as no answer rather than as a zero. Its centroid is the point itself, which is Measurement.Centroid's own definition one dimension further down than the midpoint of an edge, and its bounding box is the box of zero extent there. Reporting both is what lets a caller ask how far anything reaches without first asking which family it named.

The position is read in the unit of the vertex's frame and nothing is converted, exactly as it is for an edge ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)). A corner nobody has surveyed yet is a diagnostic and no figures, because a position which was never claimed is unknown rather than the origin.

func (*Topology) RegionOf

func (t *Topology) RegionOf(node *SemanticNode, boundaries *Boundaries, survey Survey) (Region, []Diagnostic)

RegionOf reads the area a semantic node covers out of the loops bounding it.

It is the entry point to every operation in this file, and it refuses more than it accepts. A ring which does not close, one whose corners are not in one plane, one which crosses itself and one whose corners are collinear all come back as diagnostics and no region — the same diagnostics Topology.MeasureRegion raises, because they are the same defects and an offset computed over any of them would be a shape which looks like an answer.

The tolerance named by the survey has to be one the registry declares in the unit of the node's frame. Coincidence is judged against it and offsets are drawn to it, so there is no default and no fallback ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).

A boundary which bends is refused unless the survey names a chord tolerance for it (Survey.Chord). An overlay is computed over straight segments, so a curve has to become segments somewhere, and where that happens is a decision the caller takes and states rather than one this makes on their behalf: a survey which names a chord has decided to draw the curve and has said how closely, and Region.ChordTolerance and Region.Deviation carry that decision out with the answer. A survey which names none is refused, naming the loop which bends.

A node which references no loop is not malformed — a circuit group covers no area — and comes back as a region which covers nothing.

Example

ExampleTopology_RegionOf reads the area two rooms cover and overlays them, which is the question a setback or a clearance is asked as: not how big is this, but what is left of it once that is taken out.

Nothing about what a region covers is stored. It is read back out of the loops bounding the node every time it is asked for, so an overlap cannot disagree with the geometry it was computed from.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/overlay/shapes"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	first, _ := nodes.Node("site:S-01")
	second, _ := nodes.Node("site:S-02")

	room, _ := topology.RegionOf(first, boundaries, survey)
	store, _ := topology.RegionOf(second, boundaries, survey)

	shared, _ := room.Intersect(store)
	both, _ := room.Union(store)
	rest, _ := room.Difference(store)

	fmt.Println(shared)
	fmt.Println(both)
	fmt.Println(rest)

	// How the two sit against each other, which "not inside" does not say: each
	// of them reaches outside the other.
	containment, _ := room.Containment(store)
	fmt.Printf("%s and %s are %s\n", room.Subject(), store.Subject(), containment)

}
Output:
the region derived from site:S-01: area 4.0 m², 1 piece
the region derived from site:S-01: area 24.0 m², 1 piece
the region derived from site:S-01: area 8.0 m², 1 piece
site:S-01 and site:S-02 are overlapping

func (*Topology) TessellateEdge

func (t *Topology) TessellateEdge(edge *Edge, survey Survey, chord string) (Tessellation, []Diagnostic)

TessellateEdge replaces one edge with the straight segments which stand in for it, no further from it than the named chord tolerance allows.

It is the only way an arc becomes segments, and it is explicit for that reason. Nothing in this package tessellates on the way to an answer: a length, an area, a centroid and a bounding box are all computed from the arc itself (Topology.MeasureEdge), so the resolution of a drawing never leaks into a figure somebody reports.

A straight edge tessellates to its two ends and deviates from itself by nothing, which is what makes a ring of straight edges and a ring with one arc in it the same kind of result to a caller.

The tolerance is named and the registry declares it, in the unit of the edge's frame. There is no default and no fallback ([0012](docs/decisions/0012-tolerances-are-registry-data.md)).

The same edge and the same tolerance produce the same points every time, to the last bit. A tessellation which drifted between two runs would show up as a diff in whatever it was written into and as an argument about which run was right.

func (*Topology) TessellateLoop

func (t *Topology) TessellateLoop(loop *Loop, survey Survey, chord string) (Tessellation, []Diagnostic)

TessellateLoop replaces a loop with the ring of straight segments which stands in for it, no further from it than the named chord tolerance allows.

The loop is assembled first, so the segments come back in the order the ring is traversed and in the direction the traversal runs — an arc written once and traversed by the room on either side of it tessellates the other way round for the other room, and its two ends are still the two corners. Every diagnostic Topology.Assemble raises comes back from here.

A ring which did not close is still tessellated, and Tessellation.Closed says so. The gap is already reported by the pass whose job that is, and the segments as far as the traversal got are what a caller drawing the failure wants to show.

Topology.TessellateEdge says why this is explicit, what the named tolerance is, and why the same input gives the same output every time.

func (*Topology) TessellateRegion

func (t *Topology) TessellateRegion(
	node *SemanticNode,
	boundaries *Boundaries,
	survey Survey,
	chord string,
) (RegionTessellation, []Diagnostic)

TessellateRegion replaces the boundary of a semantic node with the straight segments which stand in for it, no further from it than the named chord tolerance allows.

It is Topology.TessellateLoop over every ring bounding a node at once, and the reason it is one call rather than a loop a caller writes is the nesting. Which ring is a hole is not written in the model — it is worked out by asking which rings hold which, by the even-odd rule (Topology.MeasureRegion) — and a caller drawing each loop on its own gets rings with no answer to that and no way to compute one, because the drawn rings are points and the nesting is over the region they came from.

The nesting is taken at the segments here rather than at the corners. That is what makes a curved region nestable at all: a courtyard whose wall bows out past a corner of the plate around it is inside the plate and outside the polygon of its chords, which is the shape Topology.MeasureRegion refuses to nest rather than answer wrongly about. Drawing the curve is the caller deciding to answer it, to a resolution they named.

A region with nothing curved in it is drawn to itself, unchanged: the same rings, the same orientation, the same pieces and a deviation of nothing. It is not a case a caller has to avoid, and Topology.RegionOf and this give back the same region for it.

The tolerance is named and the registry declares it, in the unit of the node's frame. There is no default and no fallback ([0012](docs/decisions/0012-tolerances-are-registry-data.md)), and a run which named none is refused rather than given one.

Everything which refuses a region refuses this: a ring which does not close, corners which are not in one plane, rings in two planes, a ring which crosses itself, a ring whose corners are collinear. An arc which the tolerance would take more segments to follow than anything can use is refused too, naming that edge — see [maxChordDivisions].

Example

A boundary which curves is drawn to straight segments when something actually needs them — an export, a plan ring, a polygon — and the tolerance it was drawn to travels with it.

package main

import (
	"fmt"

	"github.com/z5labs/dfcad"
)

func main() {
	root := "testdata/measure/arcs"

	registry, _ := dfcad.LoadRegistry(root)
	nodes, _ := dfcad.LoadNodes(root, registry)
	topology, _ := dfcad.LoadTopology(root, registry)
	claims, _ := dfcad.LoadClaims(root, registry)
	boundaries, _ := dfcad.ResolveBoundaries(nodes, topology)

	survey := dfcad.Survey{Tolerance: "boundary-closure", Registry: registry}
	for vertex := range topology.Vertices() {
		resolution, _ := claims.Resolve(vertex.ID(), "position", registry)
		survey.Place(vertex.ID(), resolution)
	}

	for edge := range topology.Edges() {
		centre, _ := claims.Resolve(edge.ID(), "arc-centre", registry)
		through, _ := claims.Resolve(edge.ID(), "arc-through", registry)
		survey.Bend(edge.ID(), centre, through)
	}

	// A floor plate with a round courtyard in the middle of it. Nothing measures
	// it as it stands: which of two rings is inside the other is decided at
	// their corners, and a ring which bulges past a corner is not a question the
	// corners answer. Drawing the curve is what makes it answerable, and the
	// answer says how closely it was drawn.
	plate, _ := nodes.Node("site:S-31")

	drawn, diags := topology.TessellateRegion(plate, boundaries, survey, "chord-deviation")
	for _, diagnostic := range diags {
		fmt.Println(diagnostic)
	}

	piece := drawn.Pieces()[0]

	fmt.Printf("%s: %.4f %s², %d piece with %d hole\n",
		drawn.Subject(), drawn.Area(), drawn.Unit(), len(drawn.Pieces()), len(piece.Holes()))
	fmt.Printf("bounded by %d corners around %d segments, within %.6f %s of the boundary, to %s\n",
		len(piece.Outer()), len(piece.Holes()[0]), drawn.Deviation(), drawn.Unit(), drawn.ChordTolerance().Name)

	// What comes back is an ordinary region, so everything which takes one takes
	// this. A boundary which was never curved comes back from here exactly as
	// Topology.RegionOf reads it, which is what makes that one path rather than
	// two.
	bounds, _ := drawn.Region().Bounds()
	fmt.Println(bounds)

}
Output:
site:S-31: 87.5142 m², 1 piece with 1 hole
bounded by 4 corners around 32 segments, within 0.009631 m of the boundary, to chord-deviation
(30.0 0.0 0.0) to (40.0 10.0 0.0) m

func (*Topology) Vertex

func (t *Topology) Vertex(id ID) (*Vertex, bool)

Vertex returns the vertex id names, and whether the model holds one.

The lookup is by index and does not scan, for the reason Nodes.Node is: every layer above resolves references by id, and a scan per reference would make resolving a model quadratic in the size of the thing being resolved.

The zero ID names nothing, so a vertex whose id could not be read is reachable through Topology.Vertices and not through here. It is a vertex with a diagnostic against it rather than one anything may reference.

func (*Topology) Vertices

func (t *Topology) Vertices() iter.Seq[*Vertex]

Vertices iterates the vertices in the order the walk reached them.

That order is deterministic — the lexical order of the paths, and within a file the order the forms were written — so anything built from it diffs against the last run's.

type Transform

type Transform struct {
	// Translation is the offset, ordered tx, ty, tz, expressed in the parent
	// frame's linear unit.
	Translation [3]float64

	// Rotation is a 3x3 matrix in row-major order.
	Rotation [9]float64

	// Scale is the one scale factor.
	Scale float64

	// Span is where the transform was written.
	Span Span
}

Transform is the value of a transform claim, per specification section 6.6.3.

It maps a point in the frame which declares it to a point in that frame's parent. Scale is a scale and not a unit conversion: a transform between frames of different units has a scale of one unless the fit genuinely found a scale error ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

type Tx

type Tx struct {
	// DryRun reports whether [Tx.Commit] performs every step of the change
	// except the writing.
	//
	// A dry run loads, mutates, validates and prints exactly as a real one
	// does, and is refused by exactly the same diagnostics; what it does not do
	// is rename anything into place. The [Commit] it returns carries the diff of
	// every file which would change, because a dry run which does not say what
	// would change has reported nothing.
	DryRun bool
	// contains filtered or unexported fields
}

Tx is one all-or-nothing change to a model.

A transaction loads the whole model, holds every file of it as a tree in memory, applies mutations to those trees, and — at Tx.Commit — interprets the result as though it had already been written. A change which would produce a model that does not load is refused, with the diagnostics the load would have raised, and nothing reaches the disk ([0016](docs/decisions/0016-writes-are-all-or-nothing.md)).

This is the mechanism every authoring command is built on rather than a command itself. What a command adds is which mutations to apply; everything after that — validating, printing canonically, writing atomically, rolling back, and reporting what changed — is the same for all of them, and is here so that it is the same for all of them.

A transaction holds the model root for as long as it is open, so two of them cannot interleave. It is one change and one use: Tx.Commit ends it, whether it wrote, was refused or failed, and a caller wanting another change begins another transaction against the model as it now is.

Nothing about a Tx is safe for concurrent use. The lock is between processes and between transactions, not between goroutines sharing one.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	// A transaction writes, so this works on a copy of the fixture rather than
	// on the fixture.
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	// Begin reads the whole model and holds the root until the transaction
	// finishes. A tree which does not already load is refused here, before
	// anything is asked of it, so a refusal later is about the change.
	tx, diags, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range diags {
		fmt.Println(diagnostic)
	}
	defer func() { _ = tx.Close() }()

	// Every step of the change except the writing, which is what a --dry-run
	// on a write command sets.
	tx.DryRun = true

	form, err := dfcad.Parse("", strings.NewReader(
		`(node site:S-103 (kind Space) (type MeetingRoom) (label "Meeting Room C") (geometry area) (frame frame:building) (within site:L-01))`,
	))
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := tx.Insert("entities/site.dfc", form.Nodes[0]); err != nil {
		fmt.Println(err)
		return
	}

	// Committing interprets the model as it would be once written. Nothing
	// reaches the disk unless that model loads.
	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range refused {
		fmt.Println(diagnostic)
	}

	// What the change did to the model, and what it would have done to the
	// files.
	for _, effect := range commit.Effects() {
		fmt.Printf("%s %s %s\n", effect.Op, effect.Tag, effect.ID)
	}
	for _, file := range commit.Files {
		fmt.Printf("%s %s\n", filepath.Base(file.Path), file.Status)
	}

}
Output:
created node site:S-103
site.dfc rewritten
Example (Refused)
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	// An id the model already holds. Nothing about the form itself is wrong,
	// which is why only interpreting the whole model finds it.
	form, err := dfcad.Parse("", strings.NewReader(
		`(node site:S-101 (kind Space) (type MeetingRoom) (geometry area) (frame frame:building))`,
	))
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := tx.Insert("entities/site.dfc", form.Nodes[0]); err != nil {
		fmt.Println(err)
		return
	}

	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}

	// The change is refused with the diagnostics the load would have raised,
	// and the tree is exactly as it was: no file was written, and there is
	// nothing to reconcile before trying again.
	for _, diagnostic := range refused {
		fmt.Println(diagnostic.Message)
		fmt.Println(diagnostic.Hint)
	}
	fmt.Println(len(commit.Files), "files changed")

}
Output:
expected an id nothing else holds, found site:S-101, which already names something in this model
an id is unique across the whole model, and is never issued again to a different thing
0 files changed

func (*Tx) AddAssertion

func (tx *Tx) AddAssertion(spec AssertionSpec) error

AddAssertion writes an assertion on the thing it constrains: a check name and the parameters it is applied with, as a child of that thing's form.

**What is wrong with the assertion itself is refused here**, before anything is written: a subject nothing holds, a subject which carries no assertion (a frame, a claim), a check the engine does not register, and a parameter the check does not take, one it requires and which is missing, one written twice or a value not of the sort the check declares. The last four are the validation every load runs on every assertion (ValidateAssertion) and come back together as one InvalidAssertionError, so the write path and a hand-written file are held to one rule in one set of words.

**What is wrong with the assertion in this model is refused at Tx.Commit**, with the diagnostics a load of the result would have raised: a check which cannot examine the subject's form, kind or geometry, an assertion restating a value the subject's claims already carry, and a parameter naming an id nothing holds (ResolveAssertions). Those are questions about the whole model, and the model is interpreted once, when the change is committed.

A subject this same change wrote counts, which is what lets one batch add a node and the rule it has to satisfy.

What must hold of every instance of a type is not this. That is the type's `invariant`, which is registry data and is written by hand in the registry file which declares the type.

Example

ExampleTx_AddAssertion writes a rule on the one thing it constrains: a check the engine registers, with the parameters it takes spelled as the entity format writes them without their parentheses.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/checks/satisfied")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	if err := tx.AddAssertion(dfcad.AssertionSpec{
		Subject:    "geom:L-10",
		Check:      "boundary-loops-close",
		Parameters: []string{"tolerance boundary-closure", "position position"},
	}); err != nil {
		fmt.Println(err)
		return
	}

	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range refused {
		fmt.Println(diagnostic)
	}
	for _, effect := range commit.Effects() {
		fmt.Println(effect.Op, effect.Tag, effect.ID)
	}

	graph, _ := dfcad.LoadGraph(root)
	loop, _ := graph.Entity("geom:L-10")

	for _, binding := range graph.Assertions(loop) {
		fmt.Println(binding)
	}

}
Output:
modified loop geom:L-10
geom:L-10 boundary-loops-close (position position) (tolerance boundary-closure)
Example (Refused)

ExampleTx_AddAssertion_refused writes a tolerance as a number where the check takes the name of one.

It is refused before anything is written, by the validation a load runs over the same assertion typed into a file by hand, and the reason is a typed error naming the parameter rather than a sentence to parse.

package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/checks/satisfied")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	err = tx.AddAssertion(dfcad.AssertionSpec{
		Subject:    "geom:L-10",
		Check:      "boundary-loops-close",
		Parameters: []string{"tolerance 0.005"},
	})

	var value dfcad.ParameterValueError
	if errors.As(err, &value) {
		fmt.Println("parameter:", value.Parameter)
		fmt.Println("takes:", value.Want)
	}

}
Output:
parameter: tolerance
takes: tolerance

func (*Tx) AddClaim

func (tx *Tx) AddClaim(spec ClaimSpec) (ID, []Notice, error)

AddClaim writes a new claim on the thing its subject names.

Every axis is checked against the registry before anything is written: a predicate nothing declares, a predicate declared to take a plain value instead, a value of the wrong shape, a coordinate of the wrong dimension, a unit other than the declared one and an id whose namespace nobody declared are each a refusal the author can act on without reading the registry.

The claim is written inside the form of its subject, which is where a claim lives: a claim's tag is its predicate, and there is no other way to attach a value to a thing.

Nothing here edits a value. A claim which is wrong is corrected by Tx.Supersede, which writes the new value and retracts the old one in the same change, so that the record of what was believed and why it changed survives ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

The notices are what the change has to say about the model it produced: that the claim is unrankable, and that it disagrees with what was already written. Neither refuses it.

Example

ExampleTx_AddClaim attaches a measured value to a thing, with the evidence that makes it a claim rather than a number.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	// The partition is already measured twice, so a third measurement is a
	// third opinion. That is the normal case rather than an error, and the
	// notice says so rather than the change being refused.
	id, notices, err := tx.AddClaim(dfcad.ClaimSpec{
		Subject:   "site:E-01",
		Predicate: "width",
		Value:     dfcad.ScalarValue(0.103, "m"),
		Source:    "Fit-out check FC-2026-004, Acme Surveys",
		Method:    "method:total-station",
		Accuracy:  []dfcad.AccuracyTerm{{Kind: dfcad.TermIndependent, Magnitude: 0.003, Unit: "m"}},
		Date:      time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC),
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	if _, _, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	}

	// A claim nothing references writes no id of its own.
	fmt.Printf("claim id %q\n", id)

	for _, notice := range notices {
		fmt.Println(notice.Kind, "with", len(notice.Competing), "claims already written")
	}

}
Output:
claim id ""
conflict with 2 claims already written
Example (Unrankable)

ExampleTx_AddClaim_unrankable writes the least a claim may say. Leaving the accuracy out is permitted and is the one escape hatch the bare-scalar rule keeps open; what it produces is a claim which can never win resolution.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	_, notices, err := tx.AddClaim(dfcad.ClaimSpec{
		Subject:   "site:S-102",
		Predicate: "width",
		Value:     dfcad.ScalarValue(1.8, "m"),
		Source:    "Plan set A-101, sheet 3",
		Method:    "method:scaled-from-plan",
		Date:      time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC),
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	if _, _, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	}

	for _, notice := range notices {
		fmt.Println(notice.Kind)
	}

	graph, _ := dfcad.LoadGraph(root)

	for claim := range graph.Claims().Under("site:S-102", "width") {
		fmt.Println("rankable:", claim.Rankable())
	}

}
Output:
unrankable
rankable: false

func (*Tx) AddEdge

func (tx *Tx) AddEdge(spec EdgeSpec, path string) error

AddEdge writes a new edge into the file at path.

Both endpoints are resolved before anything is written, against the model and against what this same change has already added: an id naming nothing, and one naming a member of the model which is not a vertex, are each a refusal naming what was reached. An edge between one vertex and itself is refused as well, which is a load error rather than a shape this format can hold.

The shared-edge case is this operation and nothing more. Two regions which meet along a wall name one edge, so the second of them is written by naming the vertices the first already has — which is why the endpoints are named by id rather than by coordinate.

func (*Tx) AddLoop

func (tx *Tx) AddLoop(spec LoopSpec, path string) error

AddLoop writes a new loop into the file at path.

Every edge id is resolved before anything is written, against the model and against what this same change has already added. Whether the edges form a closed, connected, simple cycle is a question about where their vertices are, which Topology.Assemble answers against a named tolerance; it is checked when the model the change produces is loaded, which is what refuses a change which would not load.

func (*Tx) AddNode

func (tx *Tx) AddNode(spec NodeSpec, path string) error

AddNode writes a new semantic node into the file at path.

Every axis is checked against the registry before anything is written, and the first one which is not permitted comes back as an error carrying the set which would have been: an unregistered type, a kind or a geometry form the type does not permit, an undeclared frame and an id namespace nobody declared are each a refusal the author can act on without reading the registry.

An id something already holds is refused, naming where that thing is defined, and an id this same change has already written is refused with it. A retired id is refused the same way, because retiring says the thing stopped existing rather than that its name came free: an id is never issued twice ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

path is where the node goes. Registry.Destination is what decides it from the registry's routing rules, and Override is the one way a command names somewhere else; neither decision is taken here, so that `dfcad route` and every command which writes answer the question the same way.

Nothing reaches the disk until Tx.Commit, which interprets the model the change would produce and refuses one which would not load.

Example

ExampleTx_AddNode writes a new semantic node into the file the registry's routing rules choose for it.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	spec := dfcad.NodeSpec{
		ID:       "site:S-103",
		Kind:     dfcad.KindSpace,
		Type:     "MeetingRoom",
		Geometry: dfcad.GeometryArea,
		Frame:    "frame:building",
		Label:    "Meeting Room C",
	}

	// Where it goes is the registry's decision, asked the same way `dfcad
	// route` asks it.
	destination, err := tx.Graph().Registry().Destination(dfcad.Subject{
		ID:   spec.ID,
		Kind: spec.Kind,
		Type: spec.Type,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	if err := tx.AddNode(spec, destination.Path); err != nil {
		fmt.Println(err)
		return
	}

	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range refused {
		fmt.Println(diagnostic)
	}

	fmt.Println(destination.Path, "by rule", destination.Rule)
	for _, effect := range commit.Effects() {
		fmt.Printf("%s %s %s\n", effect.Op, effect.Tag, effect.ID)
	}

}
Output:
entities/site.dfc by rule rooms
created node site:S-103
Example (Taken)

ExampleTx_AddNode_taken refuses an id something already holds, which a retired id is as much as a live one: retiring says the thing stopped existing, not that its name came free.

package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	err = tx.AddNode(dfcad.NodeSpec{
		ID:       "site:S-101",
		Kind:     dfcad.KindSpace,
		Type:     "MeetingRoom",
		Geometry: dfcad.GeometryArea,
		Frame:    "frame:building",
	}, "entities/site.dfc")

	var taken dfcad.TakenIDError
	if errors.As(err, &taken) {
		fmt.Println(taken.ID, "already names", taken.What)
		fmt.Println("retired:", taken.Retired)
	}

}
Output:
site:S-101 already names a node
retired: false

func (*Tx) AddVertex

func (tx *Tx) AddVertex(spec VertexSpec, path string) error

AddVertex writes a new vertex into the file at path.

The id, its namespace and the frame are checked against the registry before anything is written, and so is the position claim where one is given: the predicate, the shape of the value, its dimension and its unit are held to exactly the rules Tx.AddClaim holds a claim to, because it is the same kind of claim written in the same place.

Nothing reaches the disk until Tx.Commit, which interprets the model the change would produce and refuses one which would not load.

Example

ExampleTx_AddVertex writes a corner together with where it is. The position is a claim like any other, carrying its evidence, its method, its accuracy and its date, so two surveys of one corner are two claims rather than a number somebody overwrote.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	accuracy, err := dfcad.ParseAccuracyTerm("independent 0.004 m")
	if err != nil {
		fmt.Println(err)
		return
	}

	spec := dfcad.VertexSpec{
		ID:    "geom:V-07",
		Label: "Store, north-east corner",
		Frame: "frame:building",
		Position: dfcad.ClaimSpec{
			Predicate: "position",
			Value:     dfcad.CoordinateValue([]float64{4, 6, 0}, "m"),
			Source:    "Interior control set IC-01, Acme Surveys",
			Method:    "method:total-station",
			Accuracy:  []dfcad.AccuracyTerm{accuracy},
			Date:      time.Date(2026, 2, 18, 0, 0, 0, 0, time.UTC),
		},
	}

	// A geometric node declares neither a kind nor a type, so the rule which
	// files it matches on the namespace of its id and nothing else.
	destination, err := spec.Destination(tx.Graph().Registry(), "")
	if err != nil {
		fmt.Println(err)
		return
	}

	if err := tx.AddVertex(spec, destination.Path); err != nil {
		fmt.Println(err)
		return
	}

	if _, _, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(destination.Path, "by rule", destination.Rule)

	graph, _ := dfcad.LoadGraph(root)

	resolution, _ := graph.Claims().Resolve("geom:V-07", "position", graph.Registry())
	value, _ := resolution.Value()
	at, _ := value.Coordinate()

	fmt.Println("geom:V-07 is at", at, value.Unit())

}
Output:
entities/geometry.dfc by rule geometry
geom:V-07 is at [4 6 0] m

func (*Tx) Apply

func (tx *Tx) Apply(batch Batch) ([]Applied, error)

Apply performs every operation of a batch, in order, as part of this change.

**It is one change.** The model is read once, at Begin; every operation is applied to the trees the transaction holds; and the model they produce together is interpreted once, at Tx.Commit, which refuses one which would not load. No operation is validated against the model as it stands halfway through the batch, so an end state which loads is accepted however its intermediate states would have read — a node and the claims which reference it are one statement, and requiring each half of it to stand alone would make the pair unwritable.

**An operation may name what an earlier one wrote.** The ids this same change has already written count as taken, resolve as references and answer as the subject of a claim, which is what makes an edge between two vertices of the same batch, or a claim on a node of it, the ordinary case rather than a special one.

**Any failure refuses the whole batch.** The first operation the model refuses comes back as an OperationError naming which it was and why, and the transaction is left with nothing to commit: a caller which gets one closes it and reissues the corrected file ([0016](docs/decisions/0016-writes-are-all-or-nothing.md)). The operations after it are not attempted, because an operation may depend on the one which failed and reporting the failures it caused beside the failure itself buries the one which is real.

Nothing reaches the disk here whether it succeeded or failed. Tx.Commit is what writes, and Tx.DryRun is what does everything except the writing.

Example

ExampleTx_Apply applies a batch of edits as one change: the model is read once, every operation is applied to it in order, and what they produce together is validated once.

The second operation names what the first one wrote, which is the pair a batch exists for — a node and the claim about it are one statement, and applying them as two commands would mean two loads and a moment in which the model holds a room nobody has measured.

package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	batch, err := dfcad.ParseBatch(strings.NewReader(`{
		"version": 1,
		"operations": [
			{"op": "add-node", "id": "site:S-103", "kind": "Space", "type": "MeetingRoom",
			 "geometry": "area", "frame": "frame:building", "label": "Meeting Room C"},
			{"op": "add-claim", "subject": "site:S-103", "predicate": "width",
			 "claim": {"value": "0.102", "unit": "m",
			           "source": "As-built check AB-2026-020, Acme Surveys",
			           "method": "method:total-station",
			           "accuracy": ["independent 0.003 m"],
			           "date": "2026-05-06"}}
		]
	}`))
	if err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	applied, err := tx.Apply(batch)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Nothing has been written yet. The batch is one change, and the change is
	// made by committing it.
	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range refused {
		fmt.Println(diagnostic)
	}

	for _, operation := range applied {
		for _, effect := range operation.Effects {
			fmt.Printf("%d %s: %s %s %s\n",
				operation.Index, operation.Operation, effect.Op, effect.Tag, effect.ID)
		}
	}
	for _, file := range commit.Files {
		fmt.Println(filepath.Base(file.Path), file.Status)
	}

}
Output:
1 add-node: created node site:S-103
2 add-claim: modified node site:S-103
site.dfc rewritten

func (*Tx) Classify

func (tx *Tx) Classify(name string, classification ExternalClassification) error

Classify writes an external classification onto a declared type.

It is the write path for the `classification` child of specification section 7.3: how a scheme outside this model names one of this project's types. Both strings are carried through unread — the engine has no list of systems and no syntax for a code — so what this validates is that the type is declared, that both halves were given, and that the type is not already classified in that system.

The child is appended to the declaration, which decides nothing about where it lands: canonical form sorts the children of every form, so the classification prints where specification section 7.3 tables it whatever order it was added in.

A model which does not load is never reached here — Begin refuses one — and the change itself is validated by Tx.Commit like any other, so a classification which would not read back is refused before anything is written.

Example

ExampleTx_Classify says how a scheme outside this model names one of this project's types.

Both strings are opaque. The engine copies them and reads neither: what a code means belongs to whoever is mapping the model into that scheme, which is what keeps the mapping registry data somebody reviews rather than a table compiled into the engine.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	// One type, two schemes. Neither displaces the other: they are two
	// vocabularies' answers to the same question.
	for _, classification := range []dfcad.ExternalClassification{
		{System: "IFC4", Code: "IfcSpace"},
		{System: "Uniclass2015", Code: "SL_25_10_50"},
	} {
		if err := tx.Classify("MeetingRoom", classification); err != nil {
			fmt.Println(err)
			return
		}
	}

	if _, _, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	}

	graph, _ := dfcad.LoadGraph(root)

	declared, _ := graph.Registry().Type("MeetingRoom")
	for _, classification := range declared.Classifications {
		fmt.Println(classification.System, classification.Code)
	}

	// A second code from a system the type already carries is refused: it is a
	// disagreement rather than a richer mapping, and nothing has a rule for
	// choosing between the two.
	second, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = second.Close() }()

	fmt.Println(second.Classify("MeetingRoom", dfcad.ExternalClassification{
		System: "IFC4",
		Code:   "IfcZone",
	}))

}
Output:
IFC4 IfcSpace
Uniclass2015 SL_25_10_50
expected a system MeetingRoom is not already classified in, found "IFC4", in which it is already "IfcSpace"

func (*Tx) Close

func (tx *Tx) Close() error

Close ends the transaction without writing anything, releasing the model root.

It does nothing to a transaction Tx.Commit has already ended, which is what makes deferring it right in every case: a caller defers Close and then commits, and the model root is released exactly once either way.

func (*Tx) Commit

func (tx *Tx) Commit() (Commit, []Diagnostic, error)

Commit validates the change and writes it.

Every file a mutation touched is printed in canonical form, and the model is then interpreted from those printings together with the files nothing touched — which is the model as it would be once written, read back exactly as a load would read it. A change which produces an error is refused: the diagnostics come back, the error is nil, and nothing at all was written. They are the diagnostics that load would have raised, because they came from the same passes over the text which would have been on disk.

The diagnostics come back whether or not the change was refused. An error refuses it and a warning does not, and a warning about the model that was just written is exactly as worth reading as one about the model that was not; dropping it because the write succeeded would hide it from the only run that could have reported it. Refusal is Diagnostics.HasErrors over what comes back, which is the same test every other pass is judged by.

A change which validates is written atomically. Every file's complete new contents go to a temporary file beside it and are flushed to durable storage before any of them is renamed into place, so an interruption before the renames leaves the tree untouched. Should a rename fail once others have succeeded, the files already renamed are put back and the failure is reported: a change spanning several files lands completely or not at all.

Only the files a mutation touched are considered, and a touched file whose canonical printing is exactly what is already on disk is not written either. Everything else keeps the bytes it had, whether or not those bytes are canonical — a write command is not a formatter, and rewriting a file nobody asked about would put somebody else's reformatting in the author's diff.

The commit which comes back describes what happened whether or not anything was written: which files changed, what the change did to the model, and the unified diff of each. With Tx.DryRun set it describes what would have happened and the disk is not touched.

Commit ends the transaction and releases the model root, whether it wrote, was refused or failed. Calling it again returns ErrFinished.

func (*Tx) DeprecateClaim

func (tx *Tx) DeprecateClaim(id, supersededBy ID) ([]Notice, error)

DeprecateClaim retracts the claim id names in favour of the claim supersededBy names.

A replacement is required and is checked. `deprecated` with nothing standing in the retracted claim's place is what would make it a delete button, and a claim which was believed and then corrected is the record of why the number changed ([0007](docs/decisions/0007-rank-is-closed.md)).

The claim itself is not touched beyond its rank: its value, its evidence, its method and its date stay exactly as they were written, which is the whole point of retracting rather than editing.

A retraction which leaves the subject and predicate with no live claim is permitted and reported. Nothing then resolves under that predicate, which is a state a model may legitimately be in — an area somebody withdrew and has not yet re-measured is unknown rather than wrong — and is not something to find out about later.

Example

ExampleTx_DeprecateClaim retracts a claim in favour of one already written. A replacement is required, which is the whole of what keeps deprecated from becoming a delete button.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	if _, err := tx.DeprecateClaim("survey:W-0002", ""); err != nil {
		fmt.Println(err)
	}

	notices, err := tx.DeprecateClaim("survey:W-0002", "survey:W-0003")
	if err != nil {
		fmt.Println(err)
		return
	}

	if _, _, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("notices:", len(notices))

	graph, _ := dfcad.LoadGraph(root)
	fmt.Println("live claims of the width:", len(graph.Claims().Live("site:E-01", "width")))

}
Output:
expected the claim which replaces survey:W-0002, found none: a deprecated claim carries (superseded-by <claim-id>), which is what keeps deprecated from being a delete
notices: 0
live claims of the width: 1

func (*Tx) Form

func (tx *Tx) Form(id ID) (*Node, bool)

Form returns the top-level form the model wrote id as, and whether the model holds one.

It is how a mutation reaches what it is about. Tx.Graph says what the model means — which ids are taken, what a reference reaches, which type a node declares — and this says where that was written, which is what Tx.Replace and Tx.Remove take. An Entity carries its span and not its form, because nothing which only reads a model needs one.

Only the forms written with an id as their first argument answer here, which is every entity and every claim which wrote an id of its own. A form the transaction removed no longer answers, and one it inserted does.

func (*Tx) Graph

func (tx *Tx) Graph() *Graph

Graph returns the model as the transaction found it.

It is what a mutation is built from: which ids are taken, what a reference would reach, which types the registry declares. It does not change as mutations are applied — a transaction interprets its trees once, at Tx.Commit, because interpreting the whole model after every mutation would make a batch of edits cost the model size times the batch size for an answer only the last one needs.

func (*Tx) Insert

func (tx *Tx) Insert(path string, form *Node) error

Insert adds form to the file at path.

A relative path is resolved against the model root; an absolute one is taken as it is. Either way it must name a file beneath the root whose extension is Extension, because a file the walk would not read back is a change which appears to have been made and was not. A path naming no file the model holds creates one.

The form is written at the end of the file, which decides nothing: canonical form sorts the contents of a file, so where in the tree a form is inserted has no bearing on where it is printed.

func (*Tx) MintClaimID

func (tx *Tx) MintClaimID(subject ID, predicate string) (ID, error)

MintClaimID is the id a claim of this subject and predicate is given when something comes to reference it.

The format is `<subject>:<predicate>:<n>`: the id of the thing the claim is about, the predicate it is written under, and the lowest ordinal from one which nothing in the model already holds. Every part of it is already established vocabulary — the subject's namespace is declared, and a local part may hold further colons — so the id which comes back is a well-formed id and a well-formed symbol, writable in a file without quoting.

It is stable in the sense that matters: an id, once written, is what it is forever, and minting one again for the same pair yields the next ordinal rather than the one already taken. Nothing is ever inferred back out of it. It is a name, not a schema — the same rule every other id in this model is held to ([0002](docs/decisions/0002-immutable-id-mutable-label.md)) — so a caller reading `site:S-101:area:2` learns nothing from it that the claim does not say for itself.

func (*Tx) MintID

func (tx *Tx) MintID(namespace, mark string) (ID, error)

MintID is the id a node this change creates is given.

The format is `<namespace>:<mark>-<n>`: a declared id namespace, the tag of the form being written, and the lowest ordinal from one which nothing in the model already holds. It is a name and not a schema, and nothing is inferred back out of one ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

The transaction is asked as well as the model, for the reason Tx.MintClaimID asks it: what this same change has already written is not in the model it loaded, and a scaffold minting a hundred vertices would otherwise mint the same id a hundred times.

func (*Tx) Relate

func (tx *Tx) Relate(id ID, spec RelationSpec) error

Relate writes the references a node makes to the rest of the model: what contains it, which zones it is grouped into, and which loops bound it.

It is the other half of Tx.AddNode, which writes a node's own axes and none of its references. A batch which creates a room, a circuit and a receptacle and cannot then say the receptacle is in the room and on the circuit has written three things and no model, and the relations are exactly the class of fact which used to have to be hand-edited into the files afterwards.

**Containment is replaced and the other two are added.** A node is strictly contained by one other node, so naming a parent supersedes whatever parent was written before; membership and boundary are any number, so naming one adds it. Naming a zone or a loop the node already names is not refused here and is refused at Tx.Commit, because a reference written twice is a load error and the load is what says so.

**Nothing here is resolved.** A parent which does not exist, a parent the hierarchy does not permit, a `member-of` naming something which is not a Zone and a `boundary` naming something which is not a loop are each refused when the model this change would produce is interpreted, with the diagnostics that load would have raised — so relating a node wrongly through this interface and authoring the same mistake by hand are answered in the same words.

What is refused here is what is wrong with the invocation rather than with the model: an id naming nothing, an id naming something which is not a semantic node, and a relation which relates the node to nothing.

Example

ExampleTx_Relate writes the references a node makes to the rest of the model: what contains it, which zones it is grouped into, and which loops bound it.

It is the other half of dfcad.Tx.AddNode, which writes a node's own axes and none of its references. A node is added and then related, so that the refusal to place it and the refusal to relate it are two answers rather than one compound one.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	if err := tx.AddNode(dfcad.NodeSpec{
		ID:       "site:S-103",
		Kind:     dfcad.KindSpace,
		Type:     "MeetingRoom",
		Geometry: dfcad.GeometryArea,
		Frame:    "frame:building",
		Label:    "Meeting Room C",
	}, "entities/site.dfc"); err != nil {
		fmt.Println(err)
		return
	}

	// The three relations are written in one change, and the node they are
	// written on is one this same change created.
	if err := tx.Relate("site:S-103", dfcad.RelationSpec{
		Within:   "site:L-01",
		MemberOf: []dfcad.ID{"site:Z-01"},
		Boundary: []dfcad.ID{"geom:L-01"},
	}); err != nil {
		fmt.Println(err)
		return
	}

	if _, refused, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	} else {
		for _, diagnostic := range refused {
			fmt.Println(diagnostic)
		}
	}

	graph, _ := dfcad.LoadGraph(root)

	node, _ := graph.Node("site:S-103")
	within, _ := node.Within()

	fmt.Println("within:", within)
	fmt.Println("member of:", node.MemberOf())
	fmt.Println("bounded by:", node.Boundaries())

}
Output:
within: site:L-01
member of: [site:Z-01]
bounded by: [geom:L-01]
Example (Refused)

ExampleTx_Relate_refused relates a node to a parent the containment hierarchy does not permit.

Nothing is resolved when the relation is written: the model the change would produce is interpreted at the commit, and the refusal is the diagnostic a load of that model would have raised — the same one the same mistake gets when it is typed into a file by hand.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	// A room written straight into the site, which the hierarchy does not
	// permit: a Space is written within a Storey or another Space.
	if err := tx.Relate("site:S-102", dfcad.RelationSpec{Within: "site:S-01"}); err != nil {
		fmt.Println(err)
		return
	}

	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("files written:", len(commit.Files))
	for _, diagnostic := range refused {
		fmt.Println(diagnostic.Message)
	}

}
Output:
files written: 0
expected a kind the hierarchy permits to contain a Space, found site:S-01, which is a Site

func (*Tx) Remove

func (tx *Tx) Remove(form *Node) error

Remove takes the form out of the file it was written in.

Removing is not the same as retiring in the model's sense — a claim is deprecated by writing a rank on it, and stays in the file so that the record of what was once believed survives ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)). This is the mechanical operation the commands which do either are built from.

A file whose every form is removed is written empty rather than deleted. An empty entity file is legal and contributes nothing, and deleting is a second kind of mutating step with its own failure mode, which a change spanning several files would then have to roll back too.

func (*Tx) Replace

func (tx *Tx) Replace(old, new *Node) error

Replace swaps the form old for new, wherever old was written.

old is a top-level form of a file the transaction holds — one reached through Tx.Graph and the spans its entities carry, or one an earlier Tx.Insert of the same transaction added. Anything else is an UnknownFormError: a transaction changes the model it loaded, and a form it never saw belongs to some other one.

func (*Tx) Retire

func (tx *Tx) Retire(id ID, spec RetirementSpec) error

Retire marks the node id names as having stopped existing.

Retiring is not deleting. The form stays in the file, the id stays in the graph, and every claim ever written on the node is still there to be read: a reference written years ago resolves either to the thing it always named or to a retired node which says what happened to it ([0002](docs/decisions/0002-immutable-id-mutable-label.md)). That is also why the id is never issued again — Tx.AddNode refuses a retired one.

A reason is required. A retirement which does not say why is a deletion wearing a hat: what the record loses is not the node, which is still there, but the one sentence explaining why it stopped being true.

A node other things still reference is refused, naming every referrer, unless a replacement is supplied. Where one is, every reference to the retired node is redirected to it in the same change — which is the whole of what a replacement is for, and is why redirecting them is not left as a second command somebody may not run.

The change is still interpreted at Tx.Commit as though it had been written, so a redirection which produces a model that does not load — a containment the hierarchy does not permit, a `member-of` naming something which is not a Zone — is refused there with the diagnostics a load would have raised.

Example

ExampleTx_Retire records that a thing stopped existing, and moves what referenced it onto the thing which replaced it.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	// Without a replacement this is refused, naming the partition written
	// inside the room: a reference to something which says it stopped existing
	// is a question the model cannot answer.
	err = tx.Retire("site:S-101", dfcad.RetirementSpec{
		Date:         time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC),
		Reason:       "Knocked through into the room beside it.",
		SupersededBy: "site:S-102",
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range refused {
		fmt.Println(diagnostic)
	}

	for _, effect := range commit.Effects() {
		fmt.Printf("%s %s %s\n", effect.Op, effect.Tag, effect.ID)
	}

	// The retired node is still a node the model holds, and says what happened
	// to it.
	graph, _ := dfcad.LoadGraph(root)

	node, _ := graph.Node("site:S-101")
	retirement, _ := node.Retirement()
	replacement, _ := retirement.SupersededBy()
	fmt.Println(node.Label(), "retired on", retirement.Date().Format(time.DateOnly), "for", replacement)

	// And the partition is inside the room which replaced it.
	partition, _ := graph.Node("site:E-01")
	within, _ := partition.Within()
	fmt.Println("site:E-01 is within", within)

}
Output:
modified node site:E-01
modified node site:S-101
Meeting Room B retired on 2026-06-01 for site:S-102
site:E-01 is within site:S-102

func (*Tx) Root

func (tx *Tx) Root() string

Root returns the model root the transaction holds.

func (*Tx) Scaffold

func (tx *Tx) Scaffold(spec ScaffoldSpec, override string) (Scaffolding, []Notice, error)

Scaffold writes the vertices, edges and closed loop an ordered corner list describes, in one change.

**The list is authored closed**: its last corner names its first again, within the tolerance the spec names, and a list which does not return to where it started is refused with the gap and its size. Closing one silently would leave a tool unable to tell an outline somebody finished from one they stopped typing halfway through, and the wall it invented would appear in no diagnostic anywhere.

**A corner within the tolerance of a vertex the model already holds reuses that vertex**, and the reuse is reported with the distance it moved. That is the whole reason this operation exists: a second room which shares a wall with the first shares its two corners and the edge between them, and a duplicate vertex a millimetre away is precisely the sliver the topology model is for. The edge between two reused corners is reused too, so the partition is one node named by both rooms rather than two which can drift apart.

Snapping is switched off with Snap false, which is reported rather than silent: every corner which would have been reused comes back as a Snap with Reused false, so a run which chose to write a duplicate says which vertex it duplicated and by how far it missed.

override is a `--file` naming where everything goes, and is empty where the routing rules are to decide. Nothing reaches the disk until Tx.Commit.

Example

ExampleTx_Scaffold writes a room from its corners: the vertices, the edges between them and the closed loop they form, in one change.

The list is authored closed — its last corner names its first again — and a corner which lands on a vertex the model already holds reuses that vertex rather than writing a second one at the same point. Here the new store shares the room's south wall, so both of its northern corners and the edge between them are the ones already written: one node named by two loops, which cannot drift apart because there is nothing to drift.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	accuracy, err := dfcad.ParseAccuracyTerm("independent 0.004 m")
	if err != nil {
		fmt.Println(err)
		return
	}

	metres := func(x, y, z float64) dfcad.Corner {
		return dfcad.Corner{Position: dfcad.CoordinateValue([]float64{x, y, z}, "m")}
	}

	built, notices, err := tx.Scaffold(dfcad.ScaffoldSpec{
		Namespace: "geom",
		Frame:     "frame:building",
		Label:     "Store boundary",
		Corners: []dfcad.Corner{
			metres(0, 3, 0), metres(4, 3, 0), metres(4, 6, 0), metres(0, 6, 0), metres(0, 3, 0),
		},
		Predicate: "position",
		Provenance: dfcad.ClaimSpec{
			Source:   "Interior control set IC-01, Acme Surveys",
			Method:   "method:total-station",
			Accuracy: []dfcad.AccuracyTerm{accuracy},
			Date:     time.Date(2026, 2, 18, 0, 0, 0, 0, time.UTC),
		},
		Tolerance: "boundary-closure",
		Snap:      true,
	}, "")
	if err != nil {
		fmt.Println(err)
		return
	}

	if _, _, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("loop:", built.Loop)
	fmt.Println("created:", built.Created)
	fmt.Println("reused:", built.Reused)
	for _, snap := range built.Snaps {
		fmt.Printf("corner %d reuses %s, %v %s away\n", snap.Corner, snap.Vertex, snap.Distance, snap.Unit)
	}
	fmt.Println("notices:", len(notices))

	// The ring closes, judged against the tolerance the scaffold was given.
	graph, _ := dfcad.LoadGraph(root)

	positions := dfcad.Positions{}
	for vertex := range graph.Topology().Vertices() {
		resolution, _ := graph.Claims().Resolve(vertex.ID(), "position", graph.Registry())
		if value, ok := resolution.Value(); ok {
			positions[vertex.ID()] = value
		}
	}

	loop, _ := graph.Topology().Loop(built.Loop)
	assembly, _ := graph.Topology().Assemble(loop, positions, "boundary-closure", graph.Registry())

	fmt.Println("closed:", assembly.Closed())

}
Output:
loop: geom:loop-1
created: [geom:vertex-1 geom:vertex-2]
reused: [geom:E-03]
corner 1 reuses geom:V-04, 0 m away
corner 2 reuses geom:V-03, 0 m away
notices: 0
closed: true
Example (Unclosed)

ExampleTx_Scaffold_unclosed refuses a corner list which does not return to where it started, naming the gap and its size.

Closing one silently would leave the tool unable to tell an outline somebody finished from one they stopped typing halfway through, and the wall it invented would appear in no diagnostic anywhere.

package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	metres := func(x, y, z float64) dfcad.Corner {
		return dfcad.Corner{Position: dfcad.CoordinateValue([]float64{x, y, z}, "m")}
	}

	_, _, err = tx.Scaffold(dfcad.ScaffoldSpec{
		Namespace: "geom",
		Frame:     "frame:building",
		Corners: []dfcad.Corner{
			metres(0, 3, 0), metres(4, 3, 0), metres(4, 6, 0), metres(0, 6, 0),
		},
		Predicate: "position",
		Provenance: dfcad.ClaimSpec{
			Source: "Interior control set IC-01, Acme Surveys",
			Method: "method:total-station",
		},
		Tolerance: "boundary-closure",
		Snap:      true,
	}, "")

	var unclosed dfcad.UnclosedLoopError
	if errors.As(err, &unclosed) {
		fmt.Println(err)
		fmt.Println("the gap is", unclosed.Gap, unclosed.Unit)
	}

}
Output:
the corner list does not close: corner 4 is 3.0 m from corner 1, and the tolerance boundary-closure permits 0.005 m
the gap is 3 m

func (*Tx) SetBacking

func (tx *Tx) SetBacking(id ID, spec BackingSpec) error

SetBacking replaces what the edge id names is physically realised by.

Every `backed-by` the edge wrote is removed and the ones the spec states are written in their place, so that a wall built after its edge was drawn, a wall demolished and a wall replaced by another are each one statement of what the edge is backed by now. Its vertices, frame, label, claims and assertions are untouched: none of them is what the change is about, and an edge's identity is fixed ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

Whether the edge is then a physical boundary or a virtual one is computed from what this writes and is stored nowhere, so the change flips that answer with no other edit (specification section 6.3, [0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

What is refused here is what is wrong with the invocation: an empty id, an id nothing holds, an id naming something other than an edge, and a spec BackingSpec.Check refuses. **The elements are not resolved here.** One which names nothing, one which names geometry and one which names a node of another kind are each refused at Tx.Commit with the diagnostic a load of the result would have raised — the one the same mistake gets when it is typed into a file by hand.

Retiring the element a demolished wall was is a second change, after this one. Tx.Retire reads the references of the model as the change found it, so an edge made virtual earlier in the same change still counts as referring to the element.

Example

ExampleTx_SetBacking backs an edge which was drawn before its wall was built.

Whether an edge is a physical boundary or a virtual one is computed from what it is backed by and stored nowhere, so stating the backing is the whole of the edit: the classification flips with nothing else written.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/boundary/backed")); err != nil {
		fmt.Println(err)
		return
	}

	before, _ := dfcad.LoadGraph(root)
	opening, _ := before.Topology().Edge("geom:E-01")
	fmt.Println("before:", before.Classified(opening).Classification())

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	if err := tx.SetBacking("geom:E-01", dfcad.BackingSpec{BackedBy: []dfcad.ID{"site:W-14"}}); err != nil {
		fmt.Println(err)
		return
	}

	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range refused {
		fmt.Println(diagnostic)
	}

	for _, effect := range commit.Effects() {
		fmt.Printf("%s %s %s\n", effect.Op, effect.Tag, effect.ID)
	}

	after, _ := dfcad.LoadGraph(root)
	opening, _ = after.Topology().Edge("geom:E-01")
	fmt.Println("after:", after.Classified(opening).Classification(), opening.BackedBy())

}
Output:
before: virtual
modified edge geom:E-01
after: physical [site:W-14]

func (*Tx) SetEdges

func (tx *Tx) SetEdges(id ID, edges []ID) error

SetEdges replaces the edges the loop id names is traversed through.

The whole ordered list is replaced, as Tx.AddLoop writes it: the order is the data (specification section 6.4), so a change to a ring states the ring rather than patching one, and a patch to an ordered list is the edit most likely to be wrong. The edges are written in the order they were given and never sorted. Everything else the loop carries — its label, frame, claims, assertions, observation links and the comments written inside it — is the subtree which was there, and its identity is fixed ([0002](docs/decisions/0002-immutable-id-mutable-label.md)). Every node which names the loop in `boundary` reads the new ring with no edit of its own, because the shape is shared rather than copied.

What is refused here is what is wrong with the invocation, before anything is written: an empty id, an empty list of edges, an edge named as the empty id, an id nothing holds or which names something other than a loop, and an edge id which names nothing or something other than an edge. The edges are resolved as Tx.AddLoop resolves them, against the model and against what this same change has already written, so an edge written earlier in the change counts.

Whether the edges are expressed in the loop's frame is judged when the model the change produces is loaded: Tx.Commit refuses a ring naming an edge in another frame with the diagnostic a load of the result would have raised, the one the same edit typed into the file by hand gets.

**Whether the ring closes is judged nowhere on the write path**, as it is not for Tx.AddLoop. It is a question about where the edges' vertices are, which is answered against a tolerance the registry names, and the load names none. A ring which does not close is written, and the `boundary-loops-close` check reports it wherever the model asks for it — which is what makes this the edit that proves that check can fail.

Example

ExampleTx_SetEdges restates the ring a loop is traversed through.

The whole ordered list is replaced rather than patched, because the order is the data. The room bounded by the loop reads the new ring with nothing else written.

package main

import (
	"fmt"
	"os"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/checks/satisfied")); err != nil {
		fmt.Println(err)
		return
	}

	before, _ := dfcad.LoadGraph(root)
	outline, _ := before.Topology().Loop("geom:L-13")
	fmt.Println("before:", outline.Edges())

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	ring := []dfcad.ID{"geom:E-16", "geom:E-15", "geom:E-14", "geom:E-13"}
	if err := tx.SetEdges("geom:L-13", ring); err != nil {
		fmt.Println(err)
		return
	}

	commit, refused, err := tx.Commit()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, diagnostic := range refused {
		fmt.Println(diagnostic)
	}

	for _, effect := range commit.Effects() {
		fmt.Printf("%s %s %s\n", effect.Op, effect.Tag, effect.ID)
	}

	after, _ := dfcad.LoadGraph(root)
	outline, _ = after.Topology().Loop("geom:L-13")
	store, _ := after.Node("site:S-901")
	fmt.Println("after:", outline.Edges())
	fmt.Println("bounded by:", store.Boundaries())

}
Output:
before: [geom:E-13 geom:E-14 geom:E-15 geom:E-16]
modified loop geom:L-13
after: [geom:E-16 geom:E-15 geom:E-14 geom:E-13]
bounded by: [geom:L-13]

func (*Tx) SetLabel

func (tx *Tx) SetLabel(id ID, label string) error

SetLabel changes the display text of the thing id names, and nothing else.

A label carries no meaning to anything in the engine: nothing resolves through it, nothing derives from it, and no two things are required to have different ones. Renaming is therefore a one-line diff rather than a re-identification — the id, the global id derived from it and every reference written to it are what they were ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

An empty label removes the child, which is how a thing goes back to having none. A label nobody wrote and an empty one are the same state to everything but a person reading it, and the format spells that state as the child being absent.

func (*Tx) Sources

func (tx *Tx) Sources() SourceMap

Sources returns the bytes the transaction's diagnostics were raised over, so that a caller rendering them quotes the line each one is about.

Before Tx.Commit that is the tree on disk, because nothing has been printed and every diagnostic so far — Begin's, Tx.Apply's — is about what was read. After it, every file the change touched is its canonical printing, which is what the commit's diagnostics point into, and every file it did not touch is still read from disk as FileSources reads it.

That matters where the printing is not on disk. A refused change and a dry run wrote nothing, so the disk holds the tree before the change while the diagnostics describe the tree after it, and quoting a line from disk at the position one names would show a line which has nothing to do with it. A change which was written is what is on disk, and the two agree.

It may be called after the transaction is finished, which is when a caller holding a commit's diagnostics wants it.

func (*Tx) Supersede

func (tx *Tx) Supersede(spec ClaimSpec) (ID, []Notice, error)

Supersede corrects a value: it writes the new claim and retracts the one it replaces, in one change which lands completely or not at all.

The claim being corrected is the one live claim written on the spec's subject under its predicate. It is named that way rather than by its id because the great majority of claims write none — an id is required only of a claim something references — and the claim being corrected is exactly one which is about to be referenced for the first time. A pair nothing states is refused rather than added to, and a pair stated more than once is refused naming the competing claims, because which of them is being corrected is not something to guess at.

The new claim is given an id, minted where the spec carries none, because the claim it replaces names it. That is the whole of when a claim id is generated: a claim nothing points at needs no name, and one something points at is found by the name it wrote. The format is stated and stable — see Tx.MintClaimID.

Correction is supersession and never an edit. The old claim keeps its value, its evidence, its method and its date exactly as they were written, and what changes is that it now says it was retracted and by what ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

Example

ExampleTx_Supersede corrects a value. The new claim is written and the claim it replaces is retracted in its favour, in one change which lands completely or not at all — and the old claim keeps everything it said, because a correction is a record of why the number changed rather than a new number in place of the old one.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/z5labs/dfcad"
)

func main() {
	root, err := os.MkdirTemp("", "dfcad")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = os.RemoveAll(root) }()

	if err := os.CopyFS(root, os.DirFS("testdata/graph/valid")); err != nil {
		fmt.Println(err)
		return
	}

	tx, _, err := dfcad.Begin(root)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = tx.Close() }()

	// The claim being corrected is named by its subject and predicate, because
	// the one it replaces wrote no id — an id is required only of a claim
	// something references, and this one is about to be referenced for the
	// first time.
	id, _, err := tx.Supersede(dfcad.ClaimSpec{
		Subject:   "geom:V-01",
		Predicate: "position",
		Value:     dfcad.CoordinateValue([]float64{0.001, 0.002, 0}, "m"),
		Source:    "Interior control set IC-02, Acme Surveys",
		Method:    "method:total-station",
		Accuracy:  []dfcad.AccuracyTerm{{Kind: dfcad.TermIndependent, Magnitude: 0.002, Unit: "m"}},
		Date:      time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC),
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	if _, _, err := tx.Commit(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("minted", id)

	graph, _ := dfcad.LoadGraph(root)

	replacement, _ := graph.Claims().Claim(id)
	for retracted := range graph.Claims().Replaced(replacement) {
		was, _ := retracted.Value().Coordinate()
		fmt.Println(retracted.Rank(), "claim of", was, "from", retracted.Source())
	}

}
Output:
minted geom:V-01:position:1
deprecated claim of [0 0 0] from Interior control set IC-01, Acme Surveys

type Type

type Type struct {
	// Name is the type name, which is a plain symbol and not an id.
	Name string

	// Kinds are the kinds an instance may declare, in the order they were
	// written.
	Kinds []Kind

	// Geometries are the geometry forms an instance may declare, in the order
	// they were written.
	Geometries []Geometry

	// Absent reports whether an instance may omit its geometry child, which is
	// the registry's `absent`.
	Absent bool

	// Description is the one line the registry gives the type.
	Description string

	// Classifications are how schemes outside this model name the type, in the
	// order they were written. At most one per system, and none is the ordinary
	// case.
	Classifications []ExternalClassification

	// FillsOpening reports whether an instance written within an Element
	// stands in an opening cut through that element rather than being a part
	// of it, which is the registry's `(fills-opening #t)`.
	//
	// It is the one thing the containment hierarchy cannot say on its own. A
	// `within` edge between two elements is physical enclosure either way, and
	// what it does not say is whether the inner one is built out of the outer —
	// a baluster of a railing — or set into a hole in it, which the outer one is
	// then missing where the inner one stands. The engine interprets nothing
	// here: it is a structural statement about two nodes of one kind, carried
	// the way a geometry form is, and it holds whatever the type is called
	// ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).
	FillsOpening bool

	// Invariants are the checks which apply to every instance.
	Invariants []Invariant

	// Span is where the declaration was written.
	Span Span
}

Type is one declared node type, per specification section 7.3.

The engine attaches no meaning to a type beyond the axes recorded here. It does not know that one type is a wall and another a parcel, and no behaviour anywhere depends on which ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

func (Type) ClassifiedAs

func (t Type) ClassifiedAs(system string) (string, bool)

ClassifiedAs returns the code this type carries in system, and whether it carries one at all.

The comparison is exact. A system is an opaque string the registry wrote, so two spellings of what somebody meant as one scheme are two schemes here — the engine has no list of systems to fold them against, and inventing one would be the domain knowledge this child exists to keep out ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

func (Type) PermitsGeometry

func (t Type) PermitsGeometry(geometry Geometry) bool

PermitsGeometry reports whether an instance of the type may declare geometry.

func (Type) PermitsKind

func (t Type) PermitsKind(kind Kind) bool

PermitsKind reports whether an instance of the type may declare kind.

type Uncertainty

type Uncertainty struct {
	// Magnitude is the combined figure, at CoverageFactor standard deviations.
	Magnitude float64

	// Unit is the unit the figure is expressed in, which is the unit every term
	// of the budget was written in.
	Unit Unit

	// CoverageFactor is k: how many standard uncertainties Magnitude is. It is
	// one for the figure [Budget.Combined] produces, which is the storage
	// convention.
	CoverageFactor float64
}

Uncertainty is one combined figure together with the coverage it is stated at.

The coverage factor travels with the figure rather than beside it because a width with no factor attached is the ambiguity decision record [0006](docs/decisions/0006-accuracy-is-one-sigma.md) exists to remove: a half-width bound, a 1σ uncertainty and a 95% interval differ by a factor of two, and nothing in the bare number tells them apart. Uncertainty.String therefore always writes the factor, and there is no rendering here which leaves it out.

Storage is always 1σ. An Uncertainty whose CoverageFactor is not one is a presentation of a budget and is never written back into a model ([0009](docs/decisions/0009-derived-values-are-never-written-back.md)).

func (Uncertainty) Confidence

func (u Uncertainty) Confidence() (string, bool)

Confidence returns the approximate confidence of the coverage factor for a normal distribution, and whether the factor is one of the three which has a customary spelling.

Only the customary factors are spelled. Reporting "≈ 86.6%" for k = 1.5 would be arithmetic on an assumption about the distribution that nothing in the model states, and the factor itself is the honest thing to print.

func (Uncertainty) Standard

func (u Uncertainty) Standard() float64

Standard returns the figure at one standard deviation, whatever coverage this one is stated at.

It is what widening is computed from, so that widening an already widened figure states the coverage asked for rather than compounding two factors.

func (Uncertainty) String

func (u Uncertainty) String() string

String writes the figure with its unit and its coverage factor.

The factor is never left out, which is what makes this safe to print anywhere: a widened number without its factor attached is a number which means whatever the reader assumed.

func (Uncertainty) Widen

func (u Uncertainty) Widen(factor float64) (Uncertainty, error)

Widen returns the same uncertainty stated at the given coverage factor.

It is computed from Uncertainty.Standard rather than from Magnitude, so widening a figure already stated at k = 2 to k = 3 gives three standard uncertainties and not six. A factor which is not a finite number greater than zero is a CoverageFactorError rather than a figure nobody can act on.

type UnclosedLoopError

type UnclosedLoopError struct {
	// Last is the index of the final corner, counted from one as a person
	// counts a list.
	Last int

	// Gap is how far that corner is from the first, in the frame's unit, and
	// is negative where it could not be measured at all.
	Gap float64

	// Unit is the unit the gap is in, which is the frame's.
	Unit Unit

	// Tolerance is the declaration the gap was judged against.
	Tolerance Tolerance
}

UnclosedLoopError reports a corner list whose last corner does not return to its first.

A closed list is the whole of what says the author finished the room. A tool which quietly joined the last corner back to the first could not tell "I have written the outline" from "I stopped typing halfway", and the wall it invented would be in no diagnostic anywhere.

func (UnclosedLoopError) Error

func (e UnclosedLoopError) Error() string

Error implements the [error] interface.

type UndeclaredFrameError

type UndeclaredFrameError struct {
	// Frame is the id which was asked for.
	Frame ID
}

UndeclaredFrameError reports a frame id no registry file declares a frame of.

It is an error rather than a diagnostic because it is a caller's mistake and not an author's: nothing in the model asked for this frame, a caller did.

func (UndeclaredFrameError) Error

func (e UndeclaredFrameError) Error() string

Error implements the [error] interface.

type UndeclaredTypeError

type UndeclaredTypeError struct {
	// Type is the name which was asked for.
	Type string

	// Declared is every type the registry declares, in name order.
	Declared []string
}

UndeclaredTypeError reports a type name no registry file declares.

The declared set travels with it rather than only the name, so that a caller which cannot spell the type can list what there was without re-reading the registry.

func (UndeclaredTypeError) Error

func (e UndeclaredTypeError) Error() string

Error implements the [error] interface.

type Undrawn

type Undrawn struct {
	// contains filtered or unexported fields
}

Undrawn is one node inside a plan's subject which the plan could not draw, with why, and with the claims written on it anyway.

It is the other half of Plan.Outlines rather than a footnote to it. Together the two account for every node the subject contains, which is the property that makes a sheet checkable: a renderer which drew every outline and listed every Undrawn has drawn or named everything the model puts inside that storey, and a caption nobody drew is a line on the sheet rather than an absence nothing records.

The claims come back whichever way the node was undrawn, because they are authored facts and being unable to draw the thing they are written on is not a reason to withhold them. What cannot come back is an edge anchor for a node which has no edges — a node with no loop has none, so what it carries is exactly its own claims.

The zero Undrawn names nothing, and every method below works on it.

func (Undrawn) Annotations

func (u Undrawn) Annotations() []Annotation

Annotations returns the claims reported on it, in anchor order.

func (Undrawn) DeclaredIn

func (u Undrawn) DeclaredIn() ID

DeclaredIn returns the frame the node's shape was read in, which is the frame the claims written on it are in. Where the node references no loop there was no shape to read, and it is the frame the node declares, if any.

func (Undrawn) Node

func (u Undrawn) Node() *SemanticNode

Node returns the contained node which was not drawn.

func (Undrawn) Reason

func (u Undrawn) Reason() UndrawnReason

Reason returns why it was not drawn.

func (Undrawn) String

func (u Undrawn) String() string

String renders it as a person reads it: what it is, why it is not on the sheet and how much is written on it.

func (Undrawn) Subject

func (u Undrawn) Subject() ID

Subject returns the id of that node.

type UndrawnReason

type UndrawnReason string

UndrawnReason is why a node inside a plan's subject was not drawn.

It is a closed set, because the ways a plan can fail to draw something it was asked about are a closed set: the model gives the node no shape at all, it gives edges which could not be read, or it gives a node whose shape is a position and says nothing about where that position is. Which one it is decides who acts on it — the first is ordinary and nobody has to do anything, the others are defects whose position the diagnostics carry — and a consumer which could not tell them apart would have to decide by reading prose.

const (
	// UndrawnNoBoundary is a node which references no loop. A circuit group, a
	// warranty and a lighting schedule are all ordinary and none of them has
	// edges, so this is a shape the model never gave rather than one it gave
	// wrongly.
	UndrawnNoBoundary UndrawnReason = "no-boundary"

	// UndrawnUnreadableBoundary is a node which references loops the run could
	// not read: a ring which does not close, one which crosses itself, corners
	// which are not in one plane, a curve the invocation named no chord
	// tolerance for. Every one of those is reported as a diagnostic naming the
	// loop, the file and the position, which is where an author reads what to
	// change.
	UndrawnUnreadableBoundary UndrawnReason = "unreadable-boundary"

	// UndrawnNoPosition is a node whose geometry form is point and which
	// nothing claims a position of under the predicate the run named. A panel
	// nobody has set out yet is this, and it is a defect rather than an
	// ordinary absence: the node declares that its shape is where it is, and
	// the model then does not say where that is.
	//
	// It is kept apart from UndrawnNoBoundary because the fix is different and
	// so is the urgency. A circuit group never had a shape; a receptacle has
	// one and it is missing, and a sheet drawn without it is a sheet with a
	// device left off.
	UndrawnNoPosition UndrawnReason = "no-position"

	// UndrawnUncarried is a node whose shape was read, in a frame other than
	// the plan's, and could not be carried into the plan's frame: the two
	// frames are not related by any chain of measured transforms, a transform
	// on the way could not be applied, or the plan's frame is in a unit other
	// than the tolerance's. [Region.In] says which, on a diagnostic.
	//
	// It is a defect of the same urgency as an unreadable boundary. The shape is
	// there and is somewhere the plan cannot say where, and a sheet which drew
	// it at its own coordinates would draw it somewhere the model does not put
	// it.
	UndrawnUncarried UndrawnReason = "uncarried"
)

The reasons a node inside a plan's subject was not drawn.

func (UndrawnReason) Description

func (r UndrawnReason) Description() string

Description is the reason as a person reads it.

It is a phrase rather than a sentence, so that a renderer can put it after whatever it is a reason about. It says which of the two reasons applies and nothing more: the detail — which loop, where it was written, how wide the gap is — is in the diagnostics, because that is where anything an author has to act on belongs and a second copy of it here would be a second thing to keep true.

type Unit

type Unit string

Unit is a unit name as it was written.

The set of unit names and the definition of each are the engine's, not a registry's ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)): a model that could declare its own would be a model in which ft means whatever the last registry said. What is recorded here is the name a registry entry was written with; the arithmetic layer is what gives it a magnitude.

const (
	UnitMillimetre Unit = "mm"
	UnitCentimetre Unit = "cm"
	UnitMetre      Unit = "m"
	UnitKilometre  Unit = "km"
	UnitFoot       Unit = "ft"
	UnitSurveyFoot Unit = "usft"
)

The linear units the engine defines, in the order the table below pins them: the metre and the two prefixed spellings of it a model is authored in, then the two feet.

func LinearUnits

func LinearUnits() []Unit

LinearUnits returns the closed set of linear units, in the order above.

func (Unit) Metres

func (u Unit) Metres() (float64, bool)

Metres returns how long one of the unit is in metres, and whether it is a linear unit the engine defines.

It answers for the linear units and for nothing else. A predicate may declare a unit of any quantity its consuming repository measures — an angle, a mass, a temperature — and the set of those is not the engine's to close; the set of linear units is, because a frame declares one and every cross-frame answer is computed through it.

type UnitError

type UnitError struct {
	// Predicate is the predicate the value was written under.
	Predicate string

	// Want is the unit the registry declares, and is empty for a
	// non-dimensional predicate.
	Want Unit

	// Got is the unit that was written, and is empty where none was.
	Got Unit
}

UnitError is a value expressed in a unit other than the one its predicate declares.

The rule is equality and not convertibility, in both directions: a value in another unit is converted by whoever writes it rather than by the engine, and there is no unitless token, so a non-dimensional value is written with no unit at all ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

func (UnitError) Error

func (e UnitError) Error() string

Error implements the [error] interface.

type UnknownAccuracyError

type UnknownAccuracyError struct {
	// Claims are the claims which carried no usable accuracy, in the order they
	// were accumulated.
	Claims []*Claim
}

UnknownAccuracyError reports that a budget cannot be combined because one or more of the claims it accumulated states no accuracy.

An unstated accuracy is unknown and not zero. Treating it as zero would let a claim nobody measured pass silently through a clearance computation and come out the far side looking like the most accurate input it had, so an unknown term taints the budget instead: no combined figure comes out of it at all until the claim it came from says how well it is known ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).

The claims are carried rather than counted because the caller's next move is to say which ones and where they were written, and a message would have to be taken apart again to do that.

func (UnknownAccuracyError) Error

func (e UnknownAccuracyError) Error() string

Error implements the [error] interface.

type UnknownAxisError

type UnknownAxisError struct {
	// Axis is what was being named: `namespace`, `kind`, `type`, `geometry` or
	// `frame`.
	Axis string

	// Value is what was asked for.
	Value string

	// Permitted is every value the axis accepts, in the order the set is
	// spelled: specification order for a closed set, name order for registry
	// data.
	Permitted []string
}

UnknownAxisError reports a value on one axis of an authored node which names nothing the model has.

It carries the permitted set rather than only the name, because a refusal which says a value is wrong without saying what would have been right is one the author answers by guessing. Which set that is depends on the axis: the kinds and the geometry forms are closed sets compiled into the engine, and the namespaces, the types and the frames are registry data the consuming repository writes ([0010](docs/decisions/0010-the-engine-carries-no-domain-vocabulary.md)).

func (UnknownAxisError) Error

func (e UnknownAxisError) Error() string

Error implements the [error] interface.

type UnknownBatchVersionError

type UnknownBatchVersionError struct {
	// Version is what the file said.
	Version int

	// Known is the version this engine reads.
	Known int
}

UnknownBatchVersionError is an operation file written against a version of the format this engine does not read.

func (UnknownBatchVersionError) Error

func (e UnknownBatchVersionError) Error() string

Error implements [error].

type UnknownClaimError

type UnknownClaimError struct {
	// ID is the id that was asked for.
	ID ID
}

UnknownClaimError is a claim id nothing in the model carries.

A claim id is optional, so an id naming no claim is as often a claim which wrote none as a claim which is not there. Both readings are in the message, because the answer to the second is to write an id on the claim rather than to go looking for a claim which does not exist.

func (UnknownClaimError) Error

func (e UnknownClaimError) Error() string

Error implements the [error] interface.

type UnknownEntityError

type UnknownEntityError struct {
	// ID is the id which was asked for.
	ID ID

	// Nearest is the id closest to it which the model does hold, and is empty
	// where nothing is close enough to be worth suggesting.
	Nearest ID
}

UnknownEntityError reports an id nothing in the model answers to.

func (UnknownEntityError) Error

func (e UnknownEntityError) Error() string

Error implements the [error] interface.

type UnknownFindingKindError

type UnknownFindingKindError struct {
	// Kind is what was asked for.
	Kind string

	// Known is every kind a review reports, in the order it reports them.
	Known []FindingKind
}

UnknownFindingKindError is a policy written about a check no review runs.

The set is listed rather than pointed at, because it is closed and compiled in: a caller told only that its name was wrong has nowhere to look the real ones up.

func (UnknownFindingKindError) Error

func (e UnknownFindingKindError) Error() string

Error implements [error].

type UnknownFormError

type UnknownFormError struct {
	// Span is where the form says it was written, which is the zero span for a
	// form which was never read from a file.
	Span Span
}

UnknownFormError reports a form the transaction does not hold.

A form is located by where it was written, so this is what a caller gets for a form built from nothing, read out of a different model, or already removed by an earlier mutation of the same transaction.

func (UnknownFormError) Error

func (e UnknownFormError) Error() string

Error implements the [error] interface.

type UnknownOperationError

type UnknownOperationError struct {
	// Operation is the name which was written.
	Operation string

	// Known is every operation there is, in the order the format documents
	// them.
	Known []string
}

UnknownOperationError is an `op` naming no operation.

func (UnknownOperationError) Error

func (e UnknownOperationError) Error() string

Error implements [error].

type UnknownParameterError

type UnknownParameterError struct {
	// Check is the check the assertion names.
	Check string

	// Parameter is the tag which was written.
	Parameter string

	// Takes is every parameter the check does take, in declared order.
	Takes []string

	// Diagnostic is what a load reports for the same assertion written by hand.
	Diagnostic Diagnostic
}

UnknownParameterError is a parameter the check does not take.

func (UnknownParameterError) Error

func (e UnknownParameterError) Error() string

Error implements the [error] interface.

type UnknownRevisionError

type UnknownRevisionError struct {
	// Revision is what was asked for, as it was written.
	Revision string
}

UnknownRevisionError is a revision the repository does not hold.

func (UnknownRevisionError) Error

func (e UnknownRevisionError) Error() string

Error implements [error].

type UnknownRulingError

type UnknownRulingError struct {
	// Ruling is what was asked for.
	Ruling string

	// Known is every ruling there is.
	Known []Ruling
}

UnknownRulingError is a policy which names no ruling.

func (UnknownRulingError) Error

func (e UnknownRulingError) Error() string

Error implements [error].

type UnknownUnitError

type UnknownUnitError struct {
	// Frame is the frame which declared it.
	Frame ID

	// Unit is what it declared, which is empty where it declared none the
	// registry could read.
	Unit Unit
}

UnknownUnitError reports a frame whose declared linear unit is not one the engine defines, asked to convert something into or out of it.

Nothing is assumed in its place. A frame whose unit cannot be read is a frame whose coordinates have no magnitude, and converting them as though they were metres is the unlabelled conversion [0005](docs/decisions/0005-one-linear-unit-per-frame.md) exists to prevent.

func (UnknownUnitError) Error

func (e UnknownUnitError) Error() string

Error implements the [error] interface.

type UnmeasuredFrameError

type UnmeasuredFrameError struct {
	// Frame is the frame whose transform did not resolve.
	Frame ID

	// Parent is the frame the transform maps it into.
	Parent ID
}

UnmeasuredFrameError reports a frame whose transform to its parent did not resolve to a transform claim, asked to transform something through it.

The relationship between two frames is a measurement rather than a configuration constant, so a frame whose measurement is missing has no relationship to its parent at all — and answering with one anyway would mean inventing the fit nobody made.

func (UnmeasuredFrameError) Error

func (e UnmeasuredFrameError) Error() string

Error implements the [error] interface.

type UnreadArc

type UnreadArc struct {
	// contains filtered or unexported fields
}

UnreadArc is one edge which states a curve that nothing read, together with the predicates it states it under.

It is the answer to a question a caller cannot ask any other way. Which predicates carry an arc is vocabulary the consuming repository owns and nothing here knows (Arc), so an invocation which names none has no way to tell a model of straight walls from one whose walls curve — and reads the second as the first, silently, reporting the chord between two corners as though it were the wall. That is a figure which can be out by a third and carries nothing saying so.

What is recognisable without the vocabulary is the shape of the claim. An edge has no position of its own — its ends are its vertices, and an arc is written as a centre and a point on the curve because those are the only positions which are the edge's (Arc.Through) — so a position claimed on an edge is a curve or it is nothing. That is what this reports, and it reports the predicate names it found rather than deciding what they mean: naming them is the fix, and the answer is what to name.

func (UnreadArc) Edge

func (a UnreadArc) Edge() *Edge

Edge returns the edge which states the curve.

func (UnreadArc) Predicates

func (a UnreadArc) Predicates() []string

Predicates returns the predicates it states a position under, in name order and each named once.

func (UnreadArc) Span

func (a UnreadArc) Span() Span

Span returns where the edge was written.

func (UnreadArc) String

func (a UnreadArc) String() string

String renders the finding as a person reads it.

type UnregisteredCheckError

type UnregisteredCheckError struct {
	// Check is the name which was written.
	Check string

	// Registered is every check the engine registers, in name order.
	Registered []string

	// Diagnostic is what a load reports for the same assertion written by hand.
	Diagnostic Diagnostic
}

UnregisteredCheckError is an assertion naming a check the engine does not register.

The registry is closed and compiled in, so the set it names is the whole of what could have been meant: adding a check is a change to the engine, and reading the set is how an author finds that out.

func (UnregisteredCheckError) Error

func (e UnregisteredCheckError) Error() string

Error implements the [error] interface.

type UnrelatedFramesError

type UnrelatedFramesError struct {
	// From and To are the two frames.
	From ID
	To   ID
}

UnrelatedFramesError reports two frames whose parent chains never meet.

Every frame of one model reaches one root, so this is a model with more than one root or with a chain which breaks before reaching it — each of them a load error the registry reports. It is an error here rather than a nil answer because "nowhere" is not a position.

func (UnrelatedFramesError) Error

func (e UnrelatedFramesError) Error() string

Error implements the [error] interface.

type UnsupportedEntityFormatError

type UnsupportedEntityFormatError struct {
	// Model is the format the model was authored against, as its author
	// asserted it.
	Model EntityFormat

	// Engine is the format this engine implements, which is [SpecFormat].
	Engine EntityFormat
}

UnsupportedEntityFormatError reports a model authored against an entity format this engine does not implement.

It carries both versions because naming one of them answers half the question: an author told only that their model is 1.3 does not know whether to upgrade the engine or to stop writing 1.3, and an author told only that the engine is 1.2 has been told a fact about a binary rather than about their model.

func (UnsupportedEntityFormatError) Error

Error implements the [error] interface.

The two readings are separate sentences because they are fixed in different places. An engine behind its model is upgraded; a MAJOR apart is a model and an engine which were never going to meet, and the fix is to pin the engine the model was written for.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value is the value of one claim, together with the unit it is expressed in, per specification section 6.6.

Which of the four shapes a value takes is registry data — the predicate declares it — so a Value is read through the accessor for the shape it has and yields nothing through the other three. That is what keeps a coordinate from being read as a scalar by a caller which forgot to look.

The fields are unexported and read through the methods below. The zero Value is the value of a claim whose value could not be read: its shape is the empty string, which the closed set has no member for, and every accessor reports that it holds nothing.

func CoordinateValue

func CoordinateValue(components []float64, unit Unit) Value

CoordinateValue is an ordered set of components in a unit, which is the value of a claim under a predicate declaring ShapeCoordinate.

The order is significant and is never sorted: the components are the axes of the frame the value is expressed in, in the order that frame gives them.

func ParseCorner

func ParseCorner(written string, unit Unit, declared Predicate) (Value, error)

ParseCorner reads one corner of a scaffold's list, in the shape the position predicate declares.

It is ParseValue with one difference, and the difference is the whole reason it exists: a corner written with no unit is read in the unit the predicate declares rather than in none. A claim's unit is an axis of the claim — the author says what they measured in, and a unit other than the declared one is the mistake the check exists to catch — but a corner is not a claim somebody wrote. It is a coordinate in a frame, and the only unit it may legally be in is the one the predicate declares, so requiring it to be written is requiring a flag whose one permitted value is already known.

A unit which was written is read as written and is still held to the declaration, so a corner list typed in the wrong unit is refused exactly as it was.

func ParseValue

func ParseValue(written string, unit Unit, declared Predicate) (Value, error)

ParseValue reads text written where a value belongs, as the shape the predicate declares.

It is here rather than in a command for the reason ParseDate is: the one spelling of a value is the engine's, so a value handed in by a caller authoring a change and a value written in a file are held to the same rule and refused in the same words. What differs is only the punctuation the two mediums allow — a coordinate is parenthesised in a file and is a run of numbers here — and unit tokens, which a file writes after the value and which arrive here as an argument of their own.

A scalar is one real number. A coordinate is its components in order, separated by whitespace. Text is taken exactly as it was written, including an empty string, which is a text value a claim may legally hold. A transform is its thirteen reals in the order the form writes them: the three of the translation, the nine of the rotation row by row, then the scale.

Whether the unit is the one the predicate declares is ClaimSpec.Check's question rather than this one's: the unit is carried through unread so that a value which is malformed and a value which is in the wrong unit are two answers rather than one.

func ScalarValue

func ScalarValue(number float64, unit Unit) Value

ScalarValue is a real number in a unit, which is the value of a claim under a predicate declaring ShapeScalar.

The four constructors here are how a value is built by something authoring one, as against read out of a file. A Value carries no exported fields because a value read from a file is what the file said and nothing else is free to say otherwise; an authored one has no span, which is the only difference between the two.

func TextValue

func TextValue(text string) Value

TextValue is a string, which is the value of a claim under a predicate declaring ShapeText. A text value carries no unit token.

func TransformValue

func TransformValue(transform Transform) Value

TransformValue is a rigid transform, which is the value of a claim under a predicate declaring ShapeTransform. A transform carries no unit token.

func (Value) Coordinate

func (v Value) Coordinate() ([]float64, bool)

Coordinate returns the ordered components of the value, and whether it is a coordinate.

The components are copied, because the order of them is significant and a caller which sorted the slice in place would be re-ordering the model's own reading of the file.

func (Value) Scalar

func (v Value) Scalar() (float64, bool)

Scalar returns the value as a real number, and whether it is one.

func (Value) Shape

func (v Value) Shape() Shape

Shape returns which of the four shapes the value takes, which is the empty string for a value which could not be read.

func (Value) Span

func (v Value) Span() Span

Span returns where the value form was written.

func (Value) Text

func (v Value) Text() (string, bool)

Text returns the value as a string, and whether it is one.

func (Value) Transform

func (v Value) Transform() (Transform, bool)

Transform returns the value as a transform, and whether it is one.

func (Value) Unit

func (v Value) Unit() Unit

Unit returns the unit the value is expressed in, exactly as it was written.

It is empty for a non-dimensional predicate and for the two shapes which carry no unit token. Nothing here converts: a value whose unit is not the one its predicate declares is a diagnostic, and the value is not read ([0005](docs/decisions/0005-one-linear-unit-per-frame.md)).

type ValueProblem

type ValueProblem string

ValueProblem says why text written where a value belongs is not one.

It is a field rather than wording inside a message so that what to do about the value is something a caller and a test can act on.

const (
	// ValueNotANumber is a component which is not a real number.
	ValueNotANumber ValueProblem = "not a number"

	// ValueWrongCount is a value written with the wrong number of components
	// for its shape.
	ValueWrongCount ValueProblem = "wrong number of components"

	// ValueNoShape is a value under a predicate whose declared shape could not
	// be read, which leaves nothing to read the value as.
	ValueNoShape ValueProblem = "no declared shape"
)

type ValueShapeError

type ValueShapeError struct {
	// Predicate is the predicate the value was written under.
	Predicate string

	// Want is the shape the registry declares.
	Want Shape

	// Got is the shape of the value that was written, and is empty for a claim
	// carrying no value at all.
	Got Shape
}

ValueShapeError is a value of a shape other than the one its predicate declares.

func (ValueShapeError) Error

func (e ValueShapeError) Error() string

Error implements the [error] interface.

type Verdict

type Verdict string

Verdict is what a siting query concluded about whether something fits, judged against the uncertainty of its own answer.

Three of the four are answers and the fourth is a refusal to give one. The distinction which matters is between VerdictFits and VerdictMightFit: a clearance of 40 mm is a comfortable fit where the answer is known to 5 mm and is no answer at all where it is known to 60 mm, and a result which reported both as "it fits" would be telling somebody to pour concrete on the strength of a number smaller than its own error bar.

const (
	// VerdictFits is a proposal which clears the envelope by more than the
	// uncertainty of the clearance.
	VerdictFits Verdict = "fits"

	// VerdictMightFit is a proposal whose clearance is inside the uncertainty of
	// the clearance, in either direction.
	//
	// It is neither a pass nor a failure and it is not a rounding of one into
	// the other. What it says is that the model, as measured, cannot tell: the
	// answer is to go and measure the thing which dominates the budget, which is
	// what [Budget.Dominant] names.
	VerdictMightFit Verdict = "might-fit"

	// VerdictDoesNotFit is a proposal which misses the envelope by more than the
	// uncertainty of the clearance.
	VerdictDoesNotFit Verdict = "does-not-fit"

	// VerdictUnknown is a clearance whose uncertainty could not be computed, so
	// that there is nothing to judge it against.
	//
	// A claim which states no accuracy is the usual cause, and it is why this is
	// not folded into [VerdictMightFit]: "the model cannot tell" and "the model
	// was never asked" need different work done about them
	// ([0006](docs/decisions/0006-accuracy-is-one-sigma.md)).
	VerdictUnknown Verdict = "unknown"
)

func (Verdict) Decided

func (v Verdict) Decided() bool

Decided reports whether the verdict answers the question.

VerdictFits and VerdictDoesNotFit do; the other two say that the question stands, for two different reasons.

func (Verdict) String

func (v Verdict) String() string

String returns the verdict as it is written.

type Vertex

type Vertex struct {
	// contains filtered or unexported fields
}

Vertex is a point of the geometric family, per specification section 6.2.

A vertex has no coordinates of its own. Its position is a claim like any other, with the same predicate validation, resolution and accuracy rules, and is read with LoadClaims rather than from here. That is the whole point of the arrangement: two surveys of one corner are two claims on one vertex, each with its source, its method, its date and its accuracy, and the disagreement between them is what the conflict register is for. A coordinate field would have room for exactly one of them and no room at all for where it came from.

A Vertex is read-only once loaded. The zero value is a vertex with no id and no frame, which is what a form nothing could be read from yields; every method below works on it.

func (*Vertex) Assertions

func (v *Vertex) Assertions() []Assertion

Assertions returns the assertions written on the vertex, in the order they were written. SemanticNode.Assertions says what they are and what they are not.

func (*Vertex) Frame

func (v *Vertex) Frame() ID

Frame returns the id of the frame the vertex's position is expressed in.

There is no second result, as a semantic node's frame has, because a vertex is always in exactly one frame: a position means nothing without one, so a vertex which wrote none is structurally wrong rather than a vertex with an axis absent.

func (*Vertex) ID

func (v *Vertex) ID() ID

ID returns the vertex's id, which never changes for the life of the corner it names ([0002](docs/decisions/0002-immutable-id-mutable-label.md)).

func (*Vertex) Label

func (v *Vertex) Label() string

Label returns the vertex's display text, which is empty when none was written.

func (*Vertex) ObservedIn

func (v *Vertex) ObservedIn() []ObservationLink

ObservedIn returns the observation files the vertex links to, in the order they were written. SemanticNode.ObservedIn says what a link is and what reading one costs.

This is the link most models write most often: a corner is a thing somebody occupied, and the shots they took there are the evidence behind every claim about where it is.

func (*Vertex) Span

func (v *Vertex) Span() Span

Span returns where the vertex form was written, which is what a diagnostic about the vertex as a whole points at.

type VertexSpec

type VertexSpec struct {
	// ID is the id it will be written with. Its namespace must be one the
	// registry declares.
	ID ID

	// Label is its display text, and is empty for a vertex with none.
	Label string

	// Frame is the frame its position is expressed in, which the registry must
	// declare. A vertex is always in exactly one.
	Frame ID

	// Position is the claim saying where it is, and is written only where it
	// names a predicate. Its subject is this vertex whatever it holds.
	//
	// A vertex with no position claim is ordinary rather than incomplete: a
	// corner somebody has named and not yet surveyed is a corner whose position
	// is unknown, which is a state this model can hold and a coordinate of zero
	// is not.
	Position ClaimSpec
}

VertexSpec is a vertex which does not exist yet: the axes it will be written with.

The position is part of it rather than a claim added afterwards because a vertex is written into a file and a claim is written inside the form of its subject: a vertex and the first thing anybody knows about where it is are one change or they are two, and two leaves a vertex with no position in the model in between.

func (VertexSpec) Check

func (spec VertexSpec) Check(registry *Registry) error

Check reports the first axis of the spec which the registry does not permit.

func (VertexSpec) Destination

func (spec VertexSpec) Destination(registry *Registry, override string) (Destination, error)

Destination is the file the vertex goes in, decided exactly as NodeSpec.Destination decides a node's.

type Violation

type Violation struct {
	// Instance is the id of the thing which failed.
	Instance ID `json:"instance"`

	// Type is the name of its type, which is what declared the invariant. It is
	// empty for an assertion, which is declared on the thing itself.
	Type string `json:"type,omitempty"`

	// Check is the check name the invariant named.
	Check string `json:"check"`

	// Arguments are the parameters it was evaluated with, each rendered the way
	// it was written.
	Arguments []string `json:"arguments,omitempty"`

	// Parameters are the same parameters as data, one per entry of Arguments
	// and in the same order ([Rule.Parameters]).
	Parameters []Parameter `json:"parameters,omitempty"`

	// Declared is where the rule was written. For an invariant that is a
	// position in a registry file rather than in the file the instance is in;
	// for an assertion it is the assertion, on the thing which failed.
	Declared Span `json:"declared"`

	// Subject is where what failed was written: the node, or the part of it the
	// check pointed at.
	Subject Span `json:"subject"`

	// Message says what was expected and what was found.
	Message string `json:"message"`

	// Hint is optional advice on what to do about it.
	Hint string `json:"hint,omitempty"`

	// Related are the other places which explain this one. Where the invariant
	// was declared is not among them; it is [Violation.Declared], and
	// [Violation.Diagnostic] renders it.
	Related []RelatedLocation `json:"related,omitempty"`
}

Violation is one thing failing one check written about it: an invariant of its type, or an assertion written on it.

Every field a reader needs to act on it is here rather than folded into the message: which thing failed, which rule, the parameters that rule was evaluated with, and the file and line which declared it — because a rule stated once and applied to a hundred and fifty instances is one whose failure has to lead back to the one place it is written.

The two kinds of rule share the shape because a reader acts on them the same way, and are told apart by Violation.Type: an invariant carries the type which declared it, and an assertion carries none, because it is declared on the thing which failed and Violation.Declared already points there.

Violation.Diagnostic is the human rendering, through the same renderer every diagnostic uses. The machine rendering is this struct, and neither is produced by parsing the other.

func (Violation) Diagnostic

func (v Violation) Diagnostic() Diagnostic

Diagnostic renders the violation as a diagnostic, pointing at what failed and noting where the rule it failed was declared.

An invariant reads as the rule of a type, because that is where a reader has to go to change it and because the one line is stated once for every instance of it. An assertion reads as a rule of the thing itself, and the related location is still written: the assertion may be lines away from the part of the subject the check pointed at.

func (Violation) String

func (v Violation) String() string

String renders the violation as the single line an editor and a terminal already know how to jump to.

func (Violation) Written

func (v Violation) Written() string

Written renders the invariant as the check name followed by the parameters it was evaluated with, which is how a report names the rule that failed.

type WriteError

type WriteError struct {
	// Path is the file that was to be replaced.
	Path string

	// Err is the failure that stopped it.
	Err error
}

WriteError reports a file that could not be replaced.

The path is carried because the failure the operating system reports names the temporary file being written rather than the file being replaced, and the temporary one is not a name anybody asked for or can act on.

func (WriteError) Error

func (e WriteError) Error() string

Error implements the [error] interface.

func (WriteError) Unwrap

func (e WriteError) Unwrap() error

Unwrap returns the underlying failure.

Directories

Path Synopsis
cmd
dfcad command
Command dfcad is the command line interface to the dfcad engine.
Command dfcad is the command line interface to the dfcad engine.
Package gml writes polygon, line and point features as GML 3.2 documents.
Package gml writes polygon, line and point features as GML 3.2 documents.
Package ifc writes IFC4 spatial models as ISO 10303-21 exchange files.
Package ifc writes IFC4 spatial models as ISO 10303-21 exchange files.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL