dol 0.8.1

DOL (Design Ontology Language) - A declarative specification language for ontology-first development
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
# DOL v0.8.0 Architecture

> **Document Version:** 0.8.0
> **Last Updated:** January 2026
> **Commit:** 8ce6145
> **Spec Alignment:** DOL 2.0 Specification (implementation uses v0.8.0 keywords)

> Domain Ontology Language - Comprehensive Technical Reference

## Executive Summary

DOL (Domain Ontology Language) v0.8.0 is a declarative domain-specific language for ontology-first software development. It provides a complete compiler toolchain that transforms natural-language-like specifications into executable code for multiple targets.

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         DOL v0.8.0 COMPILER PIPELINE                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌─────────┐    ┌────────┐    ┌─────┐    ┌─────┐    ┌──────────────────┐  │
│   │  .dol   │───▶│ Lexer  │───▶│ AST │───▶│ HIR │───▶│ Code Generation  │  │
│   │ Source  │    │(logos) │    │     │    │     │    │                  │  │
│   └─────────┘    └────────┘    └─────┘    └─────┘    │  ┌────────────┐  │  │
│                       │            │          │       │  │    Rust    │  │  │
│                       ▼            ▼          ▼       │  ├────────────┤  │  │
│                  ┌─────────┐  ┌─────────┐ ┌───────┐   │  │ TypeScript │  │  │
│                  │ Tokens  │  │Validator│ │ Type  │   │  ├────────────┤  │  │
│                  └─────────┘  └─────────┘ │Checker│   │  │ JSON Schema│  │  │
│                                           └───────┘   │  ├────────────┤  │  │
│                                                       │  │    WASM    │  │  │
│                                                       │  └────────────┘  │  │
│                                                       └──────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘
```

**Key Metrics:**
- **Version**: 0.8.0 "Clarity"
- **Rust Edition**: 2021 (MSRV 1.81)
- **Library Name**: `metadol` (Metal DOL)
- **Total Tests**: 1914 passing
- **Codebase**: ~1M lines

---

## Table of Contents

1. [Project Structure]#1-project-structure
2. [v0.8.0 Language Changes]#2-v080-language-changes
3. [Lexer Architecture]#3-lexer-architecture
4. [Parser Architecture]#4-parser-architecture
5. [Abstract Syntax Tree]#5-abstract-syntax-tree
6. [High-Level IR (HIR)]#6-high-level-ir-hir
7. [Type System]#7-type-system
8. [Code Generation]#8-code-generation
9. [WASM Backend]#9-wasm-backend
10. [Macro System]#10-macro-system
11. [SEX (Side Effect eXecution)]#11-sex-side-effect-execution
12. [MCP Integration]#12-mcp-integration
13. [CLI Tools]#13-cli-tools
14. [Transformation Passes]#14-transformation-passes
15. [Operator Precedence]#15-operator-precedence
16. [What DOL Can Build]#16-what-dol-can-build

---

## 1. Project Structure

```
univrs-dol/
├── Cargo.toml                    # Workspace manifest
├── src/
│   ├── lib.rs                    # Library entry point
│   │
│   ├── lexer.rs                  # Tokenization (logos-based)
│   ├── parser.rs                 # Recursive descent parser
│   ├── ast.rs                    # AST node definitions
│   ├── pratt.rs                  # Operator precedence table
│   │
│   ├── hir/                      # High-Level IR
│   │   ├── mod.rs                # HIR node types
│   │   ├── types.rs              # HIR type system
│   │   ├── symbol.rs             # Symbol table
│   │   └── validate.rs           # HIR validation
│   │
│   ├── lower/                    # AST → HIR lowering
│   │   ├── mod.rs                # Lowering pipeline
│   │   ├── desugar.rs            # Desugaring rules
│   │   └── expr.rs               # Expression lowering
│   │
│   ├── typechecker.rs            # Type inference & checking
│   ├── validator.rs              # Semantic validation
│   │
│   ├── codegen/                  # Code generators
│   │   ├── rust.rs               # Rust codegen
│   │   ├── typescript.rs         # TypeScript codegen
│   │   ├── jsonschema.rs         # JSON Schema codegen
│   │   └── hir_rust.rs           # HIR-based Rust codegen
│   │
│   ├── wasm/                     # WebAssembly backend
│   │   ├── compiler.rs           # WASM code emission
│   │   └── layout.rs             # Memory layout
│   │
│   ├── macros/                   # Macro system
│   │   ├── builtin.rs            # Built-in macros
│   │   └── expand.rs             # Macro expansion
│   │
│   ├── sex/                      # Side effect tracking
│   │   ├── context.rs            # SEX context
│   │   └── lint.rs               # Purity linting
│   │
│   ├── mcp/                      # MCP server
│   │   └── server.rs             # Tool implementations
│   │
│   ├── bin/                      # CLI tools
│   │   ├── dol-parse.rs
│   │   ├── dol-check.rs
│   │   ├── dol-codegen.rs
│   │   ├── dol-migrate.rs
│   │   ├── dol-mcp.rs
│   │   └── dol-test.rs
│   │
│   └── transform/                # AST transformation passes
│       ├── passes.rs             # Optimization passes
│       └── visitor.rs            # Visitor pattern
│
├── examples/                     # Example DOL files
│   ├── genes/
│   ├── traits/
│   ├── constraints/
│   └── evolutions/
│
├── stdlib/                       # Standard library
│
└── tests/                        # Test suite
    ├── codegen/
    ├── e2e/
    └── corpus/
```

### Feature Flags

| Feature | Description |
|---------|-------------|
| `cli` | Enable all CLI binaries |
| `serde` | JSON serialization support |
| `mlir` | MLIR code generation (requires LLVM 18) |
| `wasm` | Full WASM compilation support |
| `wasm-runtime` | Native WASM execution (Wasmtime) |
| `vudo` | Container orchestration tools |

---

## 2. v0.8.0 Language Changes

### Renamed Keywords

| v0.7.x | v0.8.0+ | Description |
|--------|---------|-------------|
| `gene` | `gen` | Atomic type declaration |
| `constraint` | `rule` | Invariant declaration |
| `evolves` | `evo` | Evolution declaration |
| `exegesis` | `docs` | Documentation block |

Old keywords still work but emit deprecation warnings.

### Modernized Type Names

| v0.7.x | v0.8.0+ | Notes |
|--------|---------|-------|
| `Int8`, `Int16`, `Int32`, `Int64` | `i8`, `i16`, `i32`, `i64` | Rust-aligned |
| `UInt8`, `UInt16`, `UInt32`, `UInt64` | `u8`, `u16`, `u32`, `u64` | Rust-aligned |
| `Float32`, `Float64` | `f32`, `f64` | Rust-aligned |
| `BoolType` | `bool` | Rust-aligned |
| `StringType` | `string` | Rust-aligned |
| `Void` | `()` | Unit type |
| `List<T>` | `Vec<T>` | Vector type |

### Migration Tool

```bash
# Automatically migrate v0.7 files to v0.8 syntax
dol-migrate 0.7-to-0.8 src/

# Preview changes first
dol-migrate 0.7-to-0.8 --diff src/
```

---

## Relationship to Specifications

### Keyword Evolution (v0.8.0)

DOL v0.8.0 introduced keyword updates for improved clarity and Rust alignment:

| DOL 2.0 Spec | v0.8.0 Current | Reason |
|--------------|----------------|--------|
| `gene` | `gen` | Shorter, avoids biology confusion |
| `constraint` | `rule` | Clearer intent |
| `exegesis` | `docs` | Familiar to developers |
| `Int64` | `i64` | Rust alignment |
| `List<T>` | `Vec<T>` | Rust alignment |

> **Note:** The DOL 2.0 Specification documents (DOLRAC.md, dol2_0_roadmap_checkpoint.md) use original terminology. This ARCHITECTURE.md reflects current implementation. Specification documents will be updated to v0.8.0 terminology in Q2.

### Document Hierarchy

| Document | Authority | Scope |
|----------|-----------|-------|
| ARCHITECTURE.md | Implementation truth | Current codebase |
| DOL 2.0 Spec | Design intent | Language semantics |
| DOLRAC | Runtime design | Execution model, SEX, Spirit packages |
| Roadmap | Timeline | Feature planning |

---

## 3. Lexer Architecture

The lexer uses the `logos` crate for fast, zero-copy tokenization.

```
┌─────────────────────────────────────────────────────────┐
│                    LEXER PIPELINE                       │
├─────────────────────────────────────────────────────────┤
│                                                         │
│   Source Text                                           │
│        │                                                │
│        ▼                                                │
│   ┌─────────────────────────────────────────────────┐   │
│   │              logos Tokenizer                     │   │
│   │  ┌─────────┐ ┌─────────┐ ┌─────────┐           │   │
│   │  │Keywords │ │Operators│ │Literals │           │   │
│   │  └─────────┘ └─────────┘ └─────────┘           │   │
│   └─────────────────────────────────────────────────┘   │
│        │                                                │
│        ▼                                                │
│   Token Stream with Spans                               │
│        │                                                │
│        ▼                                                │
│   Parser                                                │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

### Token Categories

**Declaration Keywords:**
```
gen, trait, rule, system, evo, docs
gene, constraint, evolves, exegesis  (deprecated aliases)
```

**Predicate Keywords:**
```
has, is, derives, from, requires, uses, emits, matches, never, can
```

**Evolution Keywords:**
```
adds, deprecates, removes, because
```

**Quantifiers:**
```
each, all, forall, exists
```

**Control Flow (DOL 2.0):**
```
if, else, match, for, while, loop, break, continue, return
let, val, var, fun, in, where, pub, module, use
```

**Special Operators (DOL 2.0):**

| Token | Symbol | Description |
|-------|--------|-------------|
| Pipe | `\|>` | Pipeline operator |
| Compose | `>>` | Function composition |
| BackPipe | `<\|` | Reverse pipeline |
| Quote | `'` | AST capture |
| Bang | `!` | Eval quoted expr |
| Reflect | `?` | Type introspection |
| Macro | `#` | Macro invocation |
| IdiomOpen | `[\|` | Applicative start |
| IdiomClose | `\|]` | Applicative end |

### Token Structure

```rust
pub struct Token {
    pub kind: TokenKind,      // Token category
    pub lexeme: String,       // Original text
    pub span: Span,           // Source location
}

pub struct Span {
    pub start: usize,         // Byte offset start
    pub end: usize,           // Byte offset end
    pub line: usize,          // Line number (1-indexed)
    pub column: usize,        // Column (1-indexed)
}
```

---

## 4. Parser Architecture

Recursive descent parser with two-token lookahead for ambiguity resolution.

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         PARSER ARCHITECTURE                             │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   Token Stream                                                          │
│        │                                                                │
│        ▼                                                                │
│   ┌─────────────────────────────────────────────────────────────────┐   │
│   │                    Recursive Descent Parser                      │   │
│   │                                                                  │   │
│   │   ┌───────────────┐    ┌───────────────┐    ┌───────────────┐   │   │
│   │   │ parse_file()  │───▶│parse_decl()   │───▶│parse_stmt()   │   │   │
│   │   └───────────────┘    └───────────────┘    └───────────────┘   │   │
│   │          │                     │                    │            │   │
│   │          ▼                     ▼                    ▼            │   │
│   │   ┌───────────────┐    ┌───────────────┐    ┌───────────────┐   │   │
│   │   │ ModuleDecl    │    │ Gen/Trait/... │    │ Has/Is/Uses   │   │   │
│   │   └───────────────┘    └───────────────┘    └───────────────┘   │   │
│   │                                                                  │   │
│   │   ┌─────────────────────────────────────────────────────────┐   │   │
│   │   │              Pratt Parser (Expressions)                  │   │   │
│   │   │   parse_expression(precedence) → Expr                    │   │   │
│   │   └─────────────────────────────────────────────────────────┘   │   │
│   └─────────────────────────────────────────────────────────────────┘   │
│        │                                                                │
│        ▼                                                                │
│   Abstract Syntax Tree (AST)                                            │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Grammar Summary

```
file       := [module] [use*] declaration*
module     := 'module' path '@' version

declaration := gen | trait | rule | system | evo | fun | const

gen        := 'gen' NAME '{' statement* '}' docs
trait      := 'trait' NAME '{' statement* '}' docs
rule       := 'rule' NAME '{' statement* '}' docs
system     := 'system' NAME '@' VERSION '{' requirement* statement* '}' docs
evo        := 'evo' NAME '@' VERSION '>' PARENT '{' change* '}' docs

statement  := has_stmt | is_stmt | uses_stmt | derives_stmt
            | matches_stmt | never_stmt | emits_stmt | quantified

has_stmt   := SUBJECT 'has' PROPERTY [':' type] ['=' default]
is_stmt    := SUBJECT 'is' STATE
uses_stmt  := 'uses' REFERENCE
derives_stmt := SUBJECT 'derives' 'from' ORIGIN
matches_stmt := SUBJECT 'matches' TARGET
never_stmt := SUBJECT 'never' ACTION
emits_stmt := ACTION 'emits' EVENT
quantified := ('each' | 'all') phrase predicate

docs       := 'docs' '{' text '}'
```

### Expression Parsing (Pratt Parser)

For DOL 2.0 expressions, a Pratt parser handles operator precedence:

```rust
fn parse_expression(&mut self, min_bp: u8) -> Result<Expr, ParseError> {
    let mut lhs = self.parse_prefix()?;

    while let Some((l_bp, r_bp)) = self.infix_binding_power() {
        if l_bp < min_bp { break; }
        self.advance();
        let rhs = self.parse_expression(r_bp)?;
        lhs = self.make_binary(lhs, op, rhs);
    }

    Ok(lhs)
}
```

---

## 5. Abstract Syntax Tree

### Node Hierarchy

```
┌─────────────────────────────────────────────────────────────────────────┐
│                           AST NODE TYPES                                │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   DolFile                                                               │
│   ├── module: Option<ModuleDecl>                                        │
│   ├── uses: Vec<UseDecl>                                                │
│   └── declarations: Vec<Declaration>                                    │
│                                                                         │
│   Declaration (enum)                                                    │
│   ├── Gen { name, statements, docs, span }                              │
│   ├── Trait { name, statements, docs, span }                            │
│   ├── Rule { name, statements, docs, span }                             │
│   ├── System { name, version, requirements, statements, docs, span }    │
│   ├── Evo { name, version, parent, adds, deprecates, removes, span }    │
│   ├── Function { name, params, return_type, body, span }                │
│   └── Const { name, type, value, span }                                 │
│                                                                         │
│   Statement (enum)                                                      │
│   ├── Has { subject, property, span }                                   │
│   ├── HasField { subject, name, type, default, constraint, span }       │
│   ├── Is { subject, state, span }                                       │
│   ├── DerivesFrom { subject, origin, span }                             │
│   ├── Uses { reference, span }                                          │
│   ├── Emits { action, event, span }                                     │
│   ├── Matches { subject, target, span }                                 │
│   ├── Never { subject, action, span }                                   │
│   └── Quantified { quantifier, phrase, predicate, span }                │
│                                                                         │
│   Expr (enum) - DOL 2.0                                                 │
│   ├── Literal(Literal)                                                  │
│   ├── Identifier(String)                                                │
│   ├── Binary { left, op, right }                                        │
│   ├── Unary { op, operand }                                             │
│   ├── Call { callee, args }                                             │
│   ├── Member { object, field }                                          │
│   ├── Lambda { params, body, return_type }                              │
│   ├── If { condition, then_branch, else_branch }                        │
│   ├── Match { scrutinee, arms }                                         │
│   ├── Block { statements, expr }                                        │
│   ├── Quote(Expr)           // 'expr - capture AST                      │
│   ├── Eval(Expr)            // !expr - evaluate quoted                  │
│   └── Reflect(TypeExpr)     // ?Type - introspection                    │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Core Types

```rust
pub struct Gen {
    pub visibility: Visibility,
    pub name: String,              // e.g., "container.exists"
    pub extends: Option<String>,   // Parent type
    pub statements: Vec<Statement>,
    pub exegesis: String,          // Mandatory docs
    pub span: Span,
}

pub struct System {
    pub name: String,              // e.g., "univrs.orchestrator"
    pub version: String,           // Semver
    pub requirements: Vec<Requirement>,
    pub statements: Vec<Statement>,
    pub exegesis: String,
    pub span: Span,
}

pub struct Evo {
    pub name: String,
    pub version: String,           // New version
    pub parent_version: String,    // Base version
    pub additions: Vec<Statement>,
    pub deprecations: Vec<Statement>,
    pub removals: Vec<String>,
    pub rationale: Option<String>, // 'because' clause
    pub exegesis: String,
    pub span: Span,
}
```

---

## 6. High-Level IR (HIR)

### Design Goals

| Goal | Description |
|------|-------------|
| Minimal | 22 node types (vs 50+ in AST) |
| Canonical | One representation per concept |
| Typed | All expressions carry type info |
| Desugared | No syntactic sugar remains |

### HIR Node Types

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         HIR NODE TYPES (22)                             │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   HirDecl (4)                   HirExpr (12)           HirStmt (6)      │
│   ├── Type                      ├── Literal            ├── Val          │
│   ├── Trait                     ├── Var                ├── Var          │
│   ├── Function                  ├── App                ├── Assign       │
│   └── Module                    ├── Lam                ├── Expr         │
│                                 ├── Let                ├── Return       │
│                                 ├── If                 └── Break        │
│                                 ├── Match                               │
│                                 ├── Proj                                │
│                                 ├── Call                                │
│                                 ├── BinOp                               │
│                                 ├── Record                              │
│                                 └── Tuple                               │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Desugaring Rules

| Source Construct | Desugars To |
|------------------|-------------|
| `let x = e` | `Val { name: x, value: e }` |
| `var x = e` | `Var { name: x, value: e }` |
| `for x in xs { body }` | `loop { match iter.next() { ... } }` |
| `while c { body }` | `loop { if c { body } else { break } }` |
| `x \|> f \|> g` | `g(f(x))` |
| `a && b` | `if a { b } else { false }` |
| `a \|\| b` | `if a { true } else { b }` |
| `[\| f a b \|]` | `f <$> a <*> b` |

### Lowering Pipeline

```
┌─────────┐    ┌───────────────┐    ┌─────────────┐    ┌─────┐
│   AST   │───▶│   Desugar     │───▶│   Symbol    │───▶│ HIR │
│         │    │   Pass        │    │   Resolution│    │     │
└─────────┘    └───────────────┘    └─────────────┘    └─────┘
              Deprecation Warnings
              (old keywords detected)
```

---

## 7. Type System

### Type Hierarchy

```
┌─────────────────────────────────────────────────────────────────────────┐
│                          DOL TYPE SYSTEM                                │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   Primitives                                                            │
│   ├── Numeric: i8, i16, i32, i64, i128, u8, u16, u32, u64, u128        │
│   ├── Floating: f32, f64                                                │
│   ├── Boolean: bool                                                     │
│   ├── String: string                                                    │
│   └── Unit: ()                                                          │
│                                                                         │
│   Compound                                                              │
│   ├── Vec<T>                    // Dynamic array                        │
│   ├── Option<T>                 // Optional value                       │
│   ├── Result<T, E>              // Success or error                     │
│   ├── Map<K, V>                 // Key-value mapping                    │
│   ├── (T1, T2, ...)             // Tuple                                │
│   └── [T; N]                    // Fixed array                          │
│                                                                         │
│   Function Types                                                        │
│   └── (T1, T2) -> R             // Function signature                   │
│                                                                         │
│   User-Defined                                                          │
│   ├── Named(String)             // Reference by name                    │
│   └── Generic<T1, T2>           // Parameterized type                   │
│                                                                         │
│   Type System                                                           │
│   ├── Var(n)                    // Type variable (inference)            │
│   ├── Any                       // Gradual typing                       │
│   ├── Never                     // Bottom type                          │
│   └── Unknown                   // Unresolved                           │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Type Inference

The type checker uses bidirectional type checking:

1. **Synthesis**: Derive type from expression
2. **Checking**: Verify expression matches expected type

```
Literal(42)           ⇒ i64
Literal(3.14)         ⇒ f64
Literal(true)         ⇒ bool
Literal("text")       ⇒ string

Binary(a + b)         ⇒ Numeric (unified from a and b)
Lambda(|x: i64| x+1)  ⇒ (i64) -> i64
If(c, t, e)           ⇒ T (where t ≈ e)
```

---

## 8. Code Generation

### Multi-Target Architecture

```
┌─────────────────────────────────────────────────────────────────────────┐
│                      CODE GENERATION TARGETS                            │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│                              AST / HIR                                  │
│                                  │                                      │
│            ┌─────────────────────┼─────────────────────┐                │
│            │                     │                     │                │
│            ▼                     ▼                     ▼                │
│   ┌─────────────────┐   ┌─────────────────┐   ┌─────────────────┐      │
│   │   RustCodegen   │   │TypeScriptCodegen│   │JsonSchemaCodegen│      │
│   │                 │   │                 │   │                 │      │
│   │  ┌───────────┐  │   │  ┌───────────┐  │   │  ┌───────────┐  │      │
│   │  │  Structs  │  │   │  │Interfaces │  │   │  │  Schemas  │  │      │
│   │  │  Traits   │  │   │  │  Types    │  │   │  │Properties │  │      │
│   │  │  Impls    │  │   │  │  Enums    │  │   │  │Constraints│  │      │
│   │  └───────────┘  │   │  └───────────┘  │   │  └───────────┘  │      │
│   └─────────────────┘   └─────────────────┘   └─────────────────┘      │
│            │                     │                     │                │
│            ▼                     ▼                     ▼                │
│        .rs files            .ts files            .json files            │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Type Mappings

| DOL Type | Rust | TypeScript | JSON Schema |
|----------|------|------------|-------------|
| `i8` | `i8` | `number` | `{ "type": "integer", "minimum": -128 }` |
| `i32` | `i32` | `number` | `{ "type": "integer" }` |
| `i64` | `i64` | `bigint` | `{ "type": "integer" }` |
| `f64` | `f64` | `number` | `{ "type": "number" }` |
| `bool` | `bool` | `boolean` | `{ "type": "boolean" }` |
| `string` | `String` | `string` | `{ "type": "string" }` |
| `Vec<T>` | `Vec<T>` | `T[]` | `{ "type": "array", "items": {...} }` |
| `Option<T>` | `Option<T>` | `T \| null` | `{ "oneOf": [...] }` |

### Generated Code Example

**DOL Input:**
```dol
gen container.exists {
  container has id
  container has name
  container has state
  container derives from creation
}

docs {
  A container represents an isolated execution environment.
}
```

**Rust Output:**
```rust
/// A container represents an isolated execution environment.
#[derive(Debug, Clone, PartialEq)]
pub struct ContainerExists {
    pub id: String,
    pub name: String,
    pub state: String,
}
```

---

## 9. WASM Backend

### Target Specification

| Target | Description | Status |
|--------|-------------|--------|
| `wasm32-wasi` | WASI system interface | Primary |
| `wasm32-unknown-unknown` | Standalone | Planned |

### Compilation Pipeline

```
┌─────────────────────────────────────────────────────────────────────────┐
│                      WASM COMPILATION PIPELINE                          │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   DOL Source                                                            │
│        │                                                                │
│        ▼                                                                │
│   ┌─────────────────────────────────────────────────────────────────┐   │
│   │                    Spirit Compiler                               │   │
│   │                                                                  │   │
│   │   Parse → Lower → TypeCheck → Optimize → WasmEmit               │   │
│   │                                                                  │   │
│   └─────────────────────────────────────────────────────────────────┘   │
│        │                                                                │
│        ▼                                                                │
│   ┌─────────────────────────────────────────────────────────────────┐   │
│   │                    WASM Module                                   │   │
│   │   ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐               │   │
│   │   │ Types   │ │Functions│ │ Memory  │ │ Exports │               │   │
│   │   └─────────┘ └─────────┘ └─────────┘ └─────────┘               │   │
│   └─────────────────────────────────────────────────────────────────┘   │
│        │                                                                │
│        ▼                                                                │
│   .wasm Binary + Source Map                                             │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Memory Model

```
┌─────────────────────────────────────────┐
│            Linear Memory                 │
├─────────────────────────────────────────┤
│ Stack (grows down)     │ Heap (grows up)│
│ ←──────────────────────┼───────────────→│
│ Local vars, frames     │ Allocations    │
└─────────────────────────────────────────┘
```

### Compilation Strategy

Per Compiler_Research.md analysis:
- **Binaryen** over LLVM for WASM (faster compilation, full GC support)
- Reference counting for memory management
- Future: WASM GC proposal integration

### Host Function Bindings

```rust
// Generated WASM imports
#[wasm_bindgen]
extern "C" {
    fn dol_print(msg: &str);
    fn dol_emit_effect(effect: JsValue) -> Promise;
}
```

### Memory Layout

The WASM compiler handles:
- Stack allocation for locals
- Heap allocation for dynamic data
- Field offset calculation with alignment
- Reference counting for memory safety

---

## Standard Library Overview

DOL follows a "batteries included" philosophy with short module names.

| Module | Description | Key Exports | Prelude |
|--------|-------------|-------------|---------|
| `io` | Input/output operations | `print`, `read`, `write` ||
| `msg` | Message passing | `send`, `recv`, `channel` ||
| `mem` | Memory operations | `alloc`, `free`, `copy` | - |
| `time` | Time utilities | `now`, `sleep`, `duration` | - |
| `net` | Networking | `connect`, `listen`, `request` | - |
| `db` | Database access | `query`, `execute`, `connect` | - |
| `fs` | File system | `read_file`, `write_file`, `exists` | - |

### Prelude

The prelude auto-imports common items without `use` statements:
- Core types: `i8`, `i16`, `i32`, `i64`, `u8`..., `f32`, `f64`, `bool`, `string`
- IO functions: `print`, `println`
- Message functions: `send`, `recv`
- Result/Option: `Ok`, `Err`, `Some`, `None`

---

## 10. Macro System

### Built-in Macros (20+)

| Macro | Signature | Description |
|-------|-----------|-------------|
| `#stringify(e)` | `Expr → string` | Convert expression to string |
| `#concat(a,b,...)` | `string... → string` | Concatenate strings |
| `#env("VAR")` | `string → string` | Read environment variable |
| `#cfg(cond)` | `bool → ()` | Conditional compilation |
| `#derive(T,...)` | `Decl → Decl` | Generate trait implementations |
| `#assert(c)` | `bool → ()` | Runtime assertion |
| `#assert_eq(a,b)` | `T, T → ()` | Assert equality |
| `#format(fmt,...)` | `string,... → string` | String formatting |
| `#dbg(e)` | `T → T` | Debug print (returns value) |
| `#todo(msg)` | `string → Never` | Mark unimplemented |
| `#unreachable()` | `→ Never` | Mark unreachable code |
| `#compile_error(m)` | `string → Never` | Compile-time error |
| `#vec(a,b,c)` | `T... → Vec<T>` | Vector literal |
| `#file()` | `→ string` | Current filename |
| `#line()` | `→ u32` | Current line number |
| `#column()` | `→ u32` | Current column |
| `#module_path()` | `→ string` | Current module path |

### Macro Expansion

```
Source with Macros
┌───────────────────┐
│  MacroExpander    │
│  ┌─────────────┐  │
│  │BuiltinMacros│  │
│  └─────────────┘  │
│  ┌─────────────┐  │
│  │CustomMacros │  │
│  └─────────────┘  │
└───────────────────┘
Expanded AST
```

---

## 11. SEX (Side Effect eXecution)

DOL enforces purity by default. Side effects require explicit marking.

### Purity Zones

```
src/
├── pure/                    # Pure code (default)
│   ├── container.dol        # No I/O, no mutations
│   └── identity.dol
│
└── sex/                     # Side-effecting code
    ├── io.dol               # File I/O
    └── network.dol          # Network calls
```

### SEX Markers

```dol
// Pure function (default)
fun add(a: i64, b: i64) -> i64 {
  a + b
}

// Side-effecting function
sex fun write_log(msg: string) -> () {
  // I/O operation
}

// Side-effecting block
sex {
  // All code here can have effects
}
```

### Effect Tracking

| Context | Pure Calls | SEX Calls | I/O |
|---------|------------|-----------|-----|
| Pure ||||
| SEX ||||

---

## Effect System

DOL v0.8.0 uses **Effect System v2** with compiler-inferred effects. Users never write explicit effect annotations.

### Design Principles

| Principle | Description |
|-----------|-------------|
| **Pure by Default** | Functions are pure unless they call effectful code |
| **Automatic Inference** | Compiler tracks effects through call graph |
| **Transitive Propagation** | Effects bubble up through callers |
| **Zero Annotation** | No `!`, `async`, or effect markers in user code |

### Effect Categories

| Effect | Trigger | Example |
|--------|---------|---------|
| `IO` | print, file ops | `print("hello")` |
| `Net` | network calls | `http.get(url)` |
| `State` | mutable globals | `counter += 1` |
| `Random` | non-determinism | `random.int(1, 10)` |
| `Time` | clock access | `time.now()` |

### Inference Flow

```
fn pure_fn() { ... }           // Inferred: Pure
fn calls_io() { print("x") }   // Inferred: IO (from print)
fn caller() { calls_io() }     // Inferred: IO (propagated)
```

### SEX Integration

The SEX (Side Effect eXecution) system provides explicit boundaries for FFI and unsafe operations. Pure code cannot call SEX functions directly; boundaries must be explicit. See section 11 for full SEX specification.

---

## 12. MCP Integration

DOL provides an MCP server for AI assistant integration.

### Available Tools

| Tool | Description |
|------|-------------|
| `dol/parse` | Parse DOL source to AST |
| `dol/typecheck` | Type check DOL code |
| `dol/compile-rust` | Generate Rust code |
| `dol/compile-typescript` | Generate TypeScript |
| `dol/compile-wasm` | Compile to WebAssembly |
| `dol/eval` | Evaluate DOL expression |
| `dol/reflect` | Introspect DOL types |
| `dol/format` | Format DOL source |
| `dol/list-macros` | List available macros |
| `dol/expand-macro` | Expand macro invocation |

### Server Usage

```bash
# Start MCP server
dol-mcp serve --port 8000

# Or via stdio for subprocess mode
dol-mcp stdio
```

---

## 13. CLI Tools

### Tool Overview

| Binary | Purpose | Usage |
|--------|---------|-------|
| `dol-parse` | Parse to JSON AST | `dol-parse file.dol -o ast.json` |
| `dol-check` | Validate syntax/types | `dol-check file.dol --strict` |
| `dol-codegen` | Generate code | `dol-codegen file.dol --target rust` |
| `dol-test` | Run tests | `dol-test tests/` |
| `dol-mcp` | MCP server | `dol-mcp serve` |
| `dol-migrate` | Version migration | `dol-migrate 0.7-to-0.8 src/` |
| `dol-build-crate` | Generate Rust crate | `dol-build-crate file.dol` |
| `vudo` | Container orchestration | `vudo run spirit.dol` |

### Common Workflows

```bash
# Validate and type-check
dol-check src/*.dol --strict

# Generate Rust library
dol-codegen src/*.dol --target rust -o generated/

# Run test suite
dol-test tests/*.dol.test

# Compile to WASM
dol-codegen spirit.dol --target wasm -o app.wasm

# Migrate codebase to v0.8.0
dol-migrate 0.7-to-0.8 --diff src/
dol-migrate 0.7-to-0.8 src/
```

---

## 14. Transformation Passes

### Pass Pipeline

```
┌─────────────────────────────────────────────────────────────────────────┐
│                      TRANSFORMATION PIPELINE                            │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   Input AST                                                             │
│       │                                                                 │
│       ▼                                                                 │
│   ┌─────────────────┐                                                   │
│   │ConstantFolding  │  Evaluate constant expressions at compile time   │
│   └─────────────────┘                                                   │
│       │                                                                 │
│       ▼                                                                 │
│   ┌─────────────────┐                                                   │
│   │DeadCodeElim     │  Remove unreachable code                          │
│   └─────────────────┘                                                   │
│       │                                                                 │
│       ▼                                                                 │
│   ┌─────────────────┐                                                   │
│   │TreeShaking      │  Remove unused declarations                       │
│   └─────────────────┘                                                   │
│       │                                                                 │
│       ▼                                                                 │
│   Optimized AST                                                         │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Pass Interface

```rust
pub trait Pass {
    fn name(&self) -> &str;
    fn should_run(&self, decl: &Declaration) -> bool;
    fn run(&mut self, decl: Declaration) -> PassResult<Declaration>;
}
```

### Visitor Pattern

```rust
pub trait Visitor {
    fn visit_declaration(&mut self, decl: &Declaration);
    fn visit_expression(&mut self, expr: &Expr);
    fn visit_statement(&mut self, stmt: &Statement);
}
```

---

## 15. Operator Precedence

### Binding Power Table

| Operator | Left BP | Right BP | Associativity | Description |
|----------|---------|----------|---------------|-------------|
| `:=` | 10 | 9 | Right | Bind |
| `\|>` | 21 | 20 | Left | Pipe |
| `@` | 31 | 30 | Left | Apply |
| `>>` | 40 | 41 | Right | Compose |
| `->` | 50 | 51 | Right | Arrow |
| `.` | 55 | 55 || Member access |
| `\|\|` | 61 | 60 | Left | Logical OR |
| `&&` | 71 | 70 | Left | Logical AND |
| `==`, `!=` | 80 | 80 || Equality |
| `<`, `>`, `<=`, `>=` | 90 | 90 || Comparison |
| `+`, `-` | 101 | 100 | Left | Addition |
| `*`, `/`, `%` | 111 | 110 | Left | Multiplication |
| `^` | 120 | 121 | Right | Power |
| `as` | 131 | 130 | Left | Type cast |
| `'`, `!`, `?` || 135 || Quote/Eval/Reflect |

---

## 16. What DOL Can Build

### Ontology Specifications

DOL excels at defining domain models with:
- Type definitions (`gen`)
- Behavior interfaces (`trait`)
- Invariants (`rule`)
- System composition (`system`)
- Version evolution (`evo`)

### Code Generation Targets

| Target | Use Case |
|--------|----------|
| **Rust** | Backend services, CLI tools, libraries |
| **TypeScript** | Frontend types, API clients |
| **JSON Schema** | API validation, documentation |
| **WASM** | Browser apps, edge computing, plugins |

### System Capabilities

```
┌─────────────────────────────────────────────────────────────────────────┐
│                     DOL CAPABILITY MATRIX                               │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   Domain Modeling                                                       │
│   ├── Ontology-first design                                             │
│   ├── Natural language predicates                                       │
│   ├── Mandatory documentation                                           │
│   └── Evolution tracking                                                │
│                                                                         │
│   Type Safety                                                           │
│   ├── Full type inference                                               │
│   ├── Generic types                                                     │
│   ├── Algebraic data types                                              │
│   └── Effect tracking (SEX)                                             │
│                                                                         │
│   Meta-Programming                                                      │
│   ├── 20+ built-in macros                                               │
│   ├── Quote/eval for AST manipulation                                   │
│   ├── Reflection for introspection                                      │
│   └── Idiom brackets (applicative)                                      │
│                                                                         │
│   Multi-Target Compilation                                              │
│   ├── Rust (structs, traits, impls)                                     │
│   ├── TypeScript (interfaces, types)                                    │
│   ├── JSON Schema (validation)                                          │
│   └── WebAssembly (portable execution)                                  │
│                                                                         │
│   Tooling                                                               │
│   ├── Parser with error recovery                                        │
│   ├── Type checker                                                      │
│   ├── MCP server (AI integration)                                       │
│   ├── Migration tools                                                   │
│   └── REPL for exploration                                              │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

### Example Use Cases

1. **Univrs.io Ecosystem Ontology**
   - Define network, orchestration, economics types
   - Generate Rust implementations
   - Track specification evolution

2. **API Contract Definition**
   - Define data models in DOL
   - Generate TypeScript types for frontend
   - Generate JSON Schema for validation
   - Generate Rust types for backend

3. **WASM Plugins**
   - Write portable business logic
   - Compile to WASM
   - Run anywhere (browser, edge, server)

4. **Domain-Driven Design**
   - Model ubiquitous language in DOL
   - Mandatory docs enforce shared understanding
   - Evolution tracks domain changes

---

## Appendix A: Quick Reference

### Declaration Syntax

```dol
// Type definition
gen domain.entity {
  entity has property
  entity is state
  entity derives from source
}
docs { Documentation here. }

// Behavior interface
trait domain.behavior {
  uses domain.entity
  entity can action
  each event emits notification
}
docs { Documentation here. }

// Invariant
rule domain.invariant {
  property never exceeds limit
  state matches expected
}
docs { Documentation here. }

// System composition
system domain.application @ 1.0.0 {
  requires dependency >= 0.1.0
  all operations is authenticated
}
docs { Documentation here. }

// Version evolution
evo domain.entity @ 1.1.0 > 1.0.0 {
  adds entity has new_property
  deprecates entity has old_property
  because "Improved API design"
}
docs { Documentation here. }
```

### Expression Syntax (DOL 2.0)

```dol
// Literals
42, 3.14, true, "string"

// Operators
a + b, x |> f, data >> transform

// Functions
fun add(a: i64, b: i64) -> i64 { a + b }

// Lambdas
|x| x * 2
|x: i64, y: i64| -> i64 { x + y }

// Control flow
if condition { then } else { else }
match value { pattern => result, _ => default }
for item in list { process(item) }

// Meta-programming
'expr          // Quote
!quoted        // Eval
?Type          // Reflect
#macro(args)   // Macro call
```

---

## Appendix B: File Extensions

| Extension | Purpose |
|-----------|---------|
| `.dol` | DOL source file |
| `.sex.dol` | Side-effecting DOL |
| `.dol.test` | DOL test file |
| `spirit.dol` | WASM package manifest |
| `system.dol` | Multi-spirit system manifest |

---

## Appendix C: Error Codes

| Code | Category | Description |
|------|----------|-------------|
| E001 | Syntax | Unexpected token |
| E002 | Syntax | Missing documentation |
| E003 | Semantic | Undefined reference |
| E004 | Semantic | Duplicate definition |
| E005 | Type | Type mismatch |
| E006 | Type | Cannot infer type |
| E007 | Effect | Pure context calling SEX |
| W001 | Deprecation | Using deprecated keyword |
| W002 | Style | Naming convention violation |

---

## Appendix D: Spirit Package System

> For full specification, see DOLRAC.md in archive/docs/

A **Spirit** is DOL's package unit—a collection of modules with metadata.

### Package Structure

```
my-spirit/
├── Spirit.dol          # Package manifest
├── src/
│   ├── lib.dol         # Library root
│   ├── main.dol        # Entry point (optional)
│   └── modules/        # Module files
└── tests/
```

### Module Resolution

| Source | Format | Example |
|--------|--------|---------|
| Local | `./path` | `use ./utils.dol` |
| Registry | `@org/name` | `use @univrs/std` |
| Git | `@git:url` | `use @git:github.com/org/repo` |
| HTTPS | URL | `use https://example.com/mod.dol` |

### Visibility

| Modifier | Scope |
|----------|-------|
| (none) | Private to module |
| `pub` | Public everywhere |
| `pub(spirit)` | Public within Spirit only |

---

## Appendix E: Glossary

| Term | Definition |
|------|------------|
| **gen** | Atomic type definition (v0.8.0 keyword, formerly `gene`) |
| **rule** | Validation constraint (v0.8.0 keyword, formerly `constraint`) |
| **docs** | Documentation block (v0.8.0 keyword, formerly `exegesis`) |
| **Spirit** | DOL package unit with manifest and modules |
| **Seance** | Collaborative editing/execution session |
| **SEX** | Side Effect eXecution system for effectful code |
| **HIR** | High-level Intermediate Representation |
| **Spell** | Pure function library (mystical vocabulary) |
| **Loa** | Background service (mystical vocabulary) |
| **Mycelium** | P2P network fabric |

---

## Appendix F: Planned Features

Features designed but not yet implemented:

| Feature | Target | Description |
|---------|--------|-------------|
| Quote `'` | Q2 | Capture expressions as AST |
| Eval `!` | Q2 | Execute quoted expressions |
| Macro `#` | Q2 | Compile-time code generation |
| Reflect `?` | Q2 | Runtime type introspection |
| MLIR Backend | Q3 | LLVM-based code generation |
| Self-Hosting | Q4 | DOL compiler in DOL |
| Seance Sessions | Y2-Q2 | Collaborative editing |
| Spirit Marketplace | Y3-Q2 | Package registry |

See docs/strategy/DOL2_PHASE3_ROADMAP.md for complete timeline.