-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
3799 lines (3201 loc) · 131 KB
/
Copy pathexample_test.go
File metadata and controls
3799 lines (3201 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2026 Z5Labs and Contributors
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package dfcad_test
import (
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strings"
"time"
"github.com/z5labs/dfcad"
)
func ExampleParse() {
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"
}
func ExampleParse_failure() {
_, 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
}
func ExampleLoad() {
// 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 ExampleLoadGraph() {
// 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 ExampleGraph_Nearest() {
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 ExampleDiagnostic_Render() {
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 ExampleLoadRegistry() {
// 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 ExampleLoadNodes() {
// 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 ExampleLoadTopology() {
// 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]
}
// 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.
func ExampleLoadTopology_position() {
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 ExampleLoadClaims() {
// 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
}
// 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.
func ExampleLoadClaims_bareScalar() {
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 ExampleClaim_Accuracy() {
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 ExampleRegistry_Undeclared() {
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 ...)
}
func ExampleChecks() {
// 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>)
// contained-areas-do-not-overlap (tolerance <tolerance>) (position <predicate>) (kind <kind>)
// contained-areas-sum (tolerance <tolerance>) (area-tolerance <tolerance>) (position <predicate>) (predicate <predicate>) (kind <kind>) (type <type>) (member-of <id>)
// 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>)
// stays-clear-of-zone (zone <id>) (tolerance <tolerance>) (position <predicate>)
// within-resolves
// zone-members-resolve
}
func ExampleGraph_Invariants() {
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 ExampleGraph_Rules() {
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 ExampleRules_Run() {
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 some of them have an implementation to run. So a run reports three
// answers rather than two: the room references no loop, so the check which
// reads its outline finds nothing to disagree with and passes, while the two
// rules naming a check nothing implements decide nothing — which is not the
// same answer as a rule which held.
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: 1
// undecided: 2
// failed: 0
}
func ExampleRules_Run_structuralInvariants() {
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 ExampleRules_Run_bands() {
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
}
func ExampleGraph_Assertions() {
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, and the containment hierarchy permits it as a parent of the subject's kind.
// required-claim: The subject carries a claim under the named predicate which is still asserted, so the predicate has a resolvable value on 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 ExampleResolveAssertions() {
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 ExampleValidateAssertion() {
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 ExampleValidate() {
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 ExampleDiagnostics() {
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 ExamplePrint() {
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 ExampleFormatter() {
// 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 ExampleParseID() {
// 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 ExampleRegistry_GlobalID() {
// 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 ExampleNodes_Node() {
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 ExampleNodes_Zones() {
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 ExampleClaims_Resolve() {
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
}
// ExampleClaims_Resolve_ambiguous is the other half of the rule: where nothing
// separates two claims, the engine says so instead of picking one.
func ExampleClaims_Resolve_ambiguous() {
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