neberu 0.0.0

Exact geometric algebra from the balanced ternary axiom. Governed rewriting, self-certifying canonicalization via the Kase Optimality Theorem.
Documentation
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
// ============================================================
// LOADER — .neb FILE PARSER
// ============================================================
//
// Loads .neb source into Governance.
//
// .neb syntax:
//   // comment
//   type name = { x * x = scalar }    — type definition
//   type name = { }                    — marker type (all generators)
//   pattern = replacement              — concrete relation
//   for x : T  =>  pattern = repl     — single-var parametric
//   for a : T, b : T where pred(a,b)  =>  pattern = repl  — two-var
//
// Bridges: Rust functions registered by name for conditions not yet
// expressible as governance. Session 004 dissolves each bridge as
// span arithmetic and ordering become .neb-native.

use crate::expr::Expr;
use crate::gen::Gen;
use crate::governance::{Governance, Relation};
use crate::rat::Rat;
use crate::trit::{Trit, N, P, Z};
use crate::word::Word;
use std::collections::HashMap;

// ── Type Registry ─────────────────────────────────────────────────────────────

/// A named generator type: the Trit signature required.
/// None = marker type (all generators satisfy).
#[derive(Debug, Clone)]
pub struct TypeDef {
    pub name: String,
    pub sig: Option<Trit>,
}

#[derive(Clone, Default)]
pub struct TypeRegistry {
    types: HashMap<String, TypeDef>,
}

impl TypeRegistry {
    pub fn new() -> Self {
        TypeRegistry::default()
    }

    /// Register the standard Clifford types.
    pub fn with_standard(mut self) -> Self {
        self.register("imag", Some(N));
        self.register("dual", Some(Z));
        self.register("hyp", Some(P));
        self.register("any", None);
        self
    }

    pub fn register(&mut self, name: &str, sig: Option<Trit>) {
        self.types.insert(
            name.to_string(),
            TypeDef {
                name: name.to_string(),
                sig,
            },
        );
    }

    pub fn get(&self, name: &str) -> Option<&TypeDef> {
        self.types.get(name)
    }

    /// Does generator g satisfy the named type?
    /// Uses gen.sig directly — O(1), no governance lookup needed.
    pub fn satisfies(&self, type_name: &str, g: Gen) -> bool {
        match self.get(type_name) {
            None => false,
            Some(td) => match td.sig {
                None => true, // marker: all generators satisfy
                Some(required) => g.sig == required,
            },
        }
    }
}

// ── Bridge Registry ───────────────────────────────────────────────────────────

/// A binary bridge predicate: Rust function for conditions not yet .neb-native.
/// SELF-HOSTING BOUNDARY: each bridge names its Session 004 replacement.
pub type BinaryBridge = fn(Gen, Gen) -> bool;

#[derive(Clone, Default)]
pub struct BridgeRegistry {
    binary: HashMap<String, BinaryBridge>,
}

impl BridgeRegistry {
    pub fn new() -> Self {
        BridgeRegistry::default()
    }

    /// Register the standard bridges.
    /// These dissolve in Session 004 when ordering is .neb-native.
    pub fn with_standard(mut self) -> Self {
        // ordered(a, b): fires when a < b in Gen ordering.
        // Ensures directional anticommutativity (no rewrite cycles).
        // Session 004: replace with .neb ordering relation.
        self.register("ordered", |a, b| a < b);
        self
    }

    pub fn register(&mut self, name: &str, f: BinaryBridge) {
        self.binary.insert(name.to_string(), f);
    }

    pub fn call(&self, name: &str, a: Gen, b: Gen) -> Option<bool> {
        self.binary.get(name).map(|f| f(a, b))
    }
}

// ── Load Error ────────────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct LoadError {
    pub message: String,
    pub line: usize,
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "line {}: {}", self.line, self.message)
    }
}

fn err(msg: impl Into<String>, line: usize) -> LoadError {
    LoadError {
        message: msg.into(),
        line,
    }
}

// ── Main Loader ───────────────────────────────────────────────────────────────

/// Load a .neb source string into a Governance.
///
/// `gens`: the generators available for parametric instantiation.
///         Parametric relations are closed over this set at load time.
///         OPEN/CLOSED: Session 004 makes relations dynamically open.
pub fn load(
    source: &str,
    base: Governance,
    types: &TypeRegistry,
    bridges: &BridgeRegistry,
    gens: &[Gen],
) -> Result<Governance, LoadError> {
    let mut gov = base;
    let mut local_types = types.clone();

    for (i, raw_line) in source.lines().enumerate() {
        let line_num = i + 1;
        let line = raw_line.trim();

        if line.is_empty() || line.starts_with("//") {
            continue;
        }

        if line.starts_with("type ") {
            // Type definition.
            let td = parse_type_def(line, line_num)?;
            local_types.register(&td.name.clone(), td.sig);
        } else if line.starts_with("for ") {
            // Parametric relation.
            let relations = parse_parametric(line, line_num, &local_types, bridges, gens)?;
            for rel in relations {
                gov = gov.with_relation(rel);
            }
        } else if line.contains('=') {
            // Concrete relation: pattern = replacement.
            let rel = parse_concrete(line, line_num)?;
            gov = gov.with_relation(rel);
        } else {
            return Err(err(format!("unrecognized line: '{line}'"), line_num));
        }
    }

    Ok(gov)
}

/// Convenience: load with standard types and bridges, all generators from gov.
pub fn load_standard(
    source: &str,
    base: Governance,
    gens: &[Gen],
) -> Result<Governance, LoadError> {
    let types = TypeRegistry::new().with_standard();
    let bridges = BridgeRegistry::new().with_standard();
    load(source, base, &types, &bridges, gens)
}

// ── Parsers ───────────────────────────────────────────────────────────────────

/// Parse `type name = { x * x = scalar }` or `type name = { }`.
fn parse_type_def(line: &str, ln: usize) -> Result<TypeDef, LoadError> {
    let rest = line.strip_prefix("type ").unwrap().trim();
    let eq = rest
        .find(" = ")
        .ok_or_else(|| err("type requires ' = '", ln))?;
    let name = rest[..eq].trim().to_string();
    let body = rest[eq + 3..].trim();
    let inner = body
        .strip_prefix('{')
        .and_then(|s| s.strip_suffix('}'))
        .ok_or_else(|| err("type body must be { ... }", ln))?
        .trim();

    if inner.is_empty() {
        return Ok(TypeDef { name, sig: None });
    }

    // Extract scalar from `x * x = scalar`.
    let eq_pos = inner
        .rfind('=')
        .ok_or_else(|| err("type body needs '='", ln))?;
    let scalar = inner[eq_pos + 1..].trim();
    let sig = match scalar {
        "-1" => Some(N),
        "0" => Some(Z),
        "1" => Some(P),
        _ => {
            return Err(err(
                format!("type scalar must be -1, 0, or 1; got '{scalar}'"),
                ln,
            ))
        }
    };
    Ok(TypeDef { name, sig })
}

/// Parse a concrete relation `pattern = replacement`.
fn parse_concrete(line: &str, ln: usize) -> Result<Relation, LoadError> {
    let parts: Vec<&str> = line.splitn(2, '=').collect();
    if parts.len() != 2 {
        return Err(err("concrete relation requires '='", ln));
    }
    let pat_str = parts[0].trim();
    let repl_str = parts[1].trim();

    let pat_expr = parse_expr_concrete(pat_str, ln)?;
    let mut terms: Vec<_> = pat_expr.terms().collect();
    if terms.len() != 1 {
        return Err(err("pattern must be a single product", ln));
    }
    let (word, coeff) = terms.remove(0);
    if !coeff.abs().is_one() {
        return Err(err("pattern coefficient must be ±1", ln));
    }

    let mut replacement = parse_expr_concrete(repl_str, ln)?;
    if *coeff == Rat::neg_one() {
        replacement = replacement.neg();
    }

    Ok(Relation::new(word.clone(), replacement))
}

/// Parse a concrete expression: generators like e1, e2, scalars, products, sums.
fn parse_expr_concrete(s: &str, ln: usize) -> Result<Expr, LoadError> {
    // Tokenize and evaluate: handles -1, 0, 1, eN, eN*eM, -eN*eM, etc.
    let s = s.trim();

    // Negated expression.
    if let Some(rest) = s.strip_prefix('-') {
        let inner = parse_expr_concrete(rest.trim(), ln)?;
        return Ok(inner.neg());
    }

    // Scalar.
    if let Ok(n) = s.parse::<i64>() {
        return Ok(Expr::int(n));
    }

    // Product of generators: eN * eM * ...
    // Split on '*' and parse each generator.
    let parts: Vec<&str> = s.split('*').collect();
    let mut gens = Vec::new();
    let mut scalar = Rat::one();

    for part in &parts {
        let p = part.trim();
        if let Some(stripped) = p.strip_prefix('-') {
            scalar = scalar.neg();
            let rest = stripped.trim();
            if let Ok(g) = parse_gen_name(rest, ln) {
                gens.push(g);
            } else if let Ok(n) = rest.parse::<i64>() {
                scalar = scalar * Rat::integer(n);
            } else {
                return Err(err(format!("unknown token: '{rest}'"), ln));
            }
        } else if let Ok(g) = parse_gen_name(p, ln) {
            gens.push(g);
        } else if let Ok(n) = p.parse::<i64>() {
            scalar = scalar * Rat::integer(n);
        } else {
            return Err(err(format!("unknown token: '{p}'"), ln));
        }
    }

    if gens.is_empty() {
        Ok(Expr::scalar(scalar))
    } else {
        Ok(Expr::term(scalar, Word::from_gens(&gens)))
    }
}

/// Parse a generator name like `e1` → Gen.
/// In concrete .neb, generator types are inferred from their index
/// and the current governance. Here we use a simple convention:
/// generators are identified by their display name only.
/// The actual type comes from the governance or from parametric context.
fn parse_gen_name(s: &str, ln: usize) -> Result<Gen, LoadError> {
    if let Some(num_str) = s.strip_prefix('e') {
        if let Ok(n) = num_str.parse::<u32>() {
            if n == 0 {
                return Err(err("generator index must be >= 1", ln));
            }
            // In concrete .neb, type is determined by position in the algebra.
            // We use a placeholder: the type will be resolved by the governance.
            // For now: imaginary by default (most common in .neb definitions).
            // Parametric relations use typed Gen directly.
            // TODO Session 004: generators in .neb carry explicit type annotations.
            return Ok(Gen::imaginary(n - 1));
        }
    }
    Err(err(
        format!("'{}' is not a generator name (expected eN)", s),
        ln,
    ))
}

// ── Parametric Parser ─────────────────────────────────────────────────────────

/// Parse and instantiate a parametric relation.
/// `for x : T  =>  x * x = -1`
/// `for a : T, b : T where pred(a, b)  =>  b * a = -a * b`
fn parse_parametric(
    line: &str,
    ln: usize,
    types: &TypeRegistry,
    bridges: &BridgeRegistry,
    gens: &[Gen],
) -> Result<Vec<Relation>, LoadError> {
    let rest = line.strip_prefix("for ").unwrap().trim();
    let arrow = rest
        .find("=>")
        .ok_or_else(|| err("parametric requires '=>'", ln))?;
    let head = rest[..arrow].trim();
    let body = rest[arrow + 2..].trim();

    // Parse head: bindings and optional where clause.
    let (bindings, where_pred) = parse_head(head, ln)?;

    // Parse body: pattern = replacement.
    let eq = body
        .find('=')
        .ok_or_else(|| err("parametric body requires '='", ln))?;
    let pat_str = body[..eq].trim();
    let repl_str = body[eq + 1..].trim();

    let vars: Vec<char> = bindings.iter().map(|(v, _)| *v).collect();
    let pattern_vars = parse_var_pattern(pat_str, &vars, ln)?;
    let replacement = parse_var_replacement(repl_str, &vars, ln)?;

    // Instantiate over the generator set.
    let relations = instantiate(
        &bindings,
        where_pred.as_deref(),
        &pattern_vars,
        &replacement,
        types,
        bridges,
        gens,
        ln,
    )?;

    Ok(relations)
}

/// Parse `x : T` or `x : T, y : T` optionally followed by `where pred(x, y)`.
#[allow(clippy::type_complexity)]
fn parse_head(head: &str, ln: usize) -> Result<(Vec<(char, String)>, Option<String>), LoadError> {
    let (bindings_str, where_str) = if let Some(pos) = head.find(" where ") {
        (&head[..pos], Some(head[pos + 7..].trim().to_string()))
    } else {
        (head, None)
    };

    let mut bindings = Vec::new();
    for part in bindings_str.split(',') {
        let part = part.trim();
        let colon = part
            .find(':')
            .ok_or_else(|| err(format!("binding '{part}' needs ': TypeName'"), ln))?;
        let var_str = part[..colon].trim();
        let type_str = part[colon + 1..].trim();

        if var_str.len() != 1 || !var_str.chars().next().unwrap().is_lowercase() {
            return Err(err(
                format!("variable must be single lowercase letter, got '{var_str}'"),
                ln,
            ));
        }
        bindings.push((var_str.chars().next().unwrap(), type_str.to_string()));
    }

    if bindings.is_empty() || bindings.len() > 2 {
        return Err(err("parametric supports 1 or 2 variables", ln));
    }
    Ok((bindings, where_str))
}

/// Parse a pattern like `x * x` or `b * a` into a Vec<char>.
fn parse_var_pattern(s: &str, vars: &[char], ln: usize) -> Result<Vec<char>, LoadError> {
    s.split('*')
        .map(|p| {
            let p = p.trim();
            if p.len() == 1 && vars.contains(&p.chars().next().unwrap()) {
                Ok(p.chars().next().unwrap())
            } else {
                Err(err(format!("pattern token '{p}' is not a variable"), ln))
            }
        })
        .collect()
}

/// Parse a replacement like `-1`, `0`, `1`, `a * b`, `-b * a`.
#[derive(Debug, Clone)]
enum VarReplacement {
    Scalar(Rat),
    Word(Vec<char>),
    NegWord(Vec<char>),
}

fn parse_var_replacement(s: &str, vars: &[char], ln: usize) -> Result<VarReplacement, LoadError> {
    match s {
        "-1" => return Ok(VarReplacement::Scalar(Rat::neg_one())),
        "0" => return Ok(VarReplacement::Scalar(Rat::zero())),
        "1" => return Ok(VarReplacement::Scalar(Rat::one())),
        _ => {}
    }
    if let Some(rest) = s.strip_prefix('-') {
        let vars_seq = parse_var_pattern(rest.trim(), vars, ln)?;
        return Ok(VarReplacement::NegWord(vars_seq));
    }
    let vars_seq = parse_var_pattern(s, vars, ln)?;
    Ok(VarReplacement::Word(vars_seq))
}

/// Instantiate a parametric relation over the generator set.
/// OPEN/CLOSED: closed over `gens` at call time. Session 004 makes this live.
#[allow(clippy::too_many_arguments)]
fn instantiate(
    bindings: &[(char, String)],
    where_pred: Option<&str>,
    pattern_vars: &[char],
    replacement: &VarReplacement,
    types: &TypeRegistry,
    bridges: &BridgeRegistry,
    gens: &[Gen],
    ln: usize,
) -> Result<Vec<Relation>, LoadError> {
    let mut relations = Vec::new();

    match bindings.len() {
        1 => {
            let (var, type_name) = &bindings[0];
            for &g in gens {
                if !types.satisfies(type_name, g) {
                    continue;
                }
                let mut assignment = HashMap::new();
                assignment.insert(*var, g);
                if let Some(rel) = build_relation(pattern_vars, replacement, &assignment) {
                    relations.push(rel);
                }
            }
        }
        2 => {
            let (va, ta) = &bindings[0];
            let (vb, tb) = &bindings[1];
            for &ga in gens {
                if !types.satisfies(ta, ga) {
                    continue;
                }
                for &gb in gens {
                    if !types.satisfies(tb, gb) {
                        continue;
                    }
                    if let Some(pred) = where_pred {
                        let a_val = if *va == bindings[0].0 { ga } else { gb };
                        let b_val = if *vb == bindings[1].0 { gb } else { ga };
                        match bridges.call(
                            pred.split('(').next().unwrap_or(pred).trim(),
                            a_val,
                            b_val,
                        ) {
                            Some(false) | None => continue,
                            Some(true) => {}
                        }
                    }
                    let mut assignment = HashMap::new();
                    assignment.insert(*va, ga);
                    assignment.insert(*vb, gb);
                    if let Some(rel) = build_relation(pattern_vars, replacement, &assignment) {
                        relations.push(rel);
                    }
                }
            }
        }
        _ => return Err(err("parametric supports 1 or 2 variables", ln)),
    }

    Ok(relations)
}

fn build_relation(
    pattern_vars: &[char],
    replacement: &VarReplacement,
    assignment: &HashMap<char, Gen>,
) -> Option<Relation> {
    let source_gens: Vec<Gen> = pattern_vars
        .iter()
        .map(|&c| assignment.get(&c).copied())
        .collect::<Option<Vec<_>>>()?;
    let source = Word::from_gens(&source_gens);

    let target = match replacement {
        VarReplacement::Scalar(r) => Expr::scalar(*r),
        VarReplacement::Word(vars) => {
            let gens: Vec<Gen> = vars
                .iter()
                .map(|&c| assignment.get(&c).copied())
                .collect::<Option<Vec<_>>>()?;
            Expr::term(Rat::one(), Word::from_gens(&gens))
        }
        VarReplacement::NegWord(vars) => {
            let gens: Vec<Gen> = vars
                .iter()
                .map(|&c| assignment.get(&c).copied())
                .collect::<Option<Vec<_>>>()?;
            Expr::term(Rat::neg_one(), Word::from_gens(&gens))
        }
    };

    Some(Relation::new(source, target))
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gen::Gen;

    fn gens_cl200() -> Vec<Gen> {
        vec![Gen::imaginary(0), Gen::imaginary(1)]
    }

    fn gens_mixed() -> Vec<Gen> {
        vec![Gen::imaginary(0), Gen::degenerate(0), Gen::hyperbolic(0)]
    }

    #[test]
    fn load_empty() {
        let gov = load_standard("", Governance::free(), &[]).unwrap();
        assert_eq!(gov.num_relations(), 0);
    }

    #[test]
    fn load_comments_and_blanks() {
        let gov = load_standard("// comment\n\n// another\n", Governance::free(), &[]).unwrap();
        assert_eq!(gov.num_relations(), 0);
    }

    #[test]
    fn load_type_def_imag() {
        let source = "type imag = { x * x = -1 }";
        let types = TypeRegistry::new();
        let bridges = BridgeRegistry::new();
        load(source, Governance::free(), &types, &bridges, &[]).unwrap();
        // No relations generated — just a type def
    }

    #[test]
    fn load_type_def_marker() {
        let source = "type step = { }";
        let types = TypeRegistry::new();
        let bridges = BridgeRegistry::new();
        load(source, Governance::free(), &types, &bridges, &[]).unwrap();
    }

    #[test]
    fn load_parametric_imag_square() {
        let source = "\
type imag = { x * x = -1 }
for x : imag  =>  x * x = -1
";
        let gens = gens_cl200(); // both imaginary
        let types = TypeRegistry::new();
        let bridges = BridgeRegistry::new();
        let gov = load(source, Governance::free(), &types, &bridges, &gens).unwrap();
        // Should generate 2 square rules (one per imaginary generator)
        assert_eq!(gov.num_relations(), 2);
        let e1 = Expr::gen(Gen::imaginary(0));
        assert_eq!(gov.mul(&e1, &e1), Expr::int(-1));
    }

    #[test]
    fn load_parametric_anticommute_directional() {
        let source = "\
type any = { }
for a : any, b : any where ordered(a, b)  =>  b * a = -a * b
";
        let gens = gens_cl200();
        let gov = load_standard(source, Governance::free(), &gens).unwrap();
        // ordered(a,b) fires when a < b. One pair: (0,1).
        // Generates: e2*e1 → -e1*e2
        let e2e1 = Expr::term(
            Rat::one(),
            Word::from_gens(&[Gen::imaginary(1), Gen::imaginary(0)]),
        );
        let result = gov.canonicalize(&e2e1);
        assert_eq!(
            result.coeff(&Word::from_gens(&[Gen::imaginary(0), Gen::imaginary(1)])),
            Rat::neg_one()
        );
    }

    #[test]
    fn load_trit_neb_file() {
        let source = include_str!("neb/trit.neb");
        let gens = gens_cl200();
        let gov = load_standard(source, Governance::free(), &gens).unwrap();
        let e1 = Expr::gen(Gen::imaginary(0));
        let e2 = Expr::gen(Gen::imaginary(1));
        assert_eq!(gov.mul(&e1, &e1), Expr::int(-1));
        assert_eq!(gov.mul(&e2, &e2), Expr::int(-1));
        let e2e1 = Expr::term(
            Rat::one(),
            Word::from_gens(&[Gen::imaginary(1), Gen::imaginary(0)]),
        );
        let canon = gov.canonicalize(&e2e1);
        assert_eq!(
            canon.coeff(&Word::from_gens(&[Gen::imaginary(0), Gen::imaginary(1)])),
            Rat::neg_one()
        );
    }

    #[test]
    fn load_mixed_concrete_and_parametric() {
        let source = "\
type imag = { x * x = -1 }
for x : imag  =>  x * x = -1
e2*e1 = -e1*e2
";
        // Note: concrete relations use Gen::imaginary by default for eN notation
        let gens = gens_cl200();
        let types = TypeRegistry::new();
        let bridges = BridgeRegistry::new();
        let gov = load(source, Governance::free(), &types, &bridges, &gens).unwrap();
        let e1 = Expr::gen(Gen::imaginary(0));
        assert_eq!(gov.mul(&e1, &e1), Expr::int(-1));
    }

    #[test]
    fn load_mixed_types() {
        let source = "\
type imag = { x * x = -1 }
type dual = { x * x = 0  }
type hyp  = { x * x = 1  }
for x : imag  =>  x * x = -1
for x : dual  =>  x * x = 0
for x : hyp   =>  x * x = 1
";
        let gens = gens_mixed();
        let types = TypeRegistry::new();
        let bridges = BridgeRegistry::new();
        let gov = load(source, Governance::free(), &types, &bridges, &gens).unwrap();
        assert_eq!(
            gov.mul(&Expr::gen(Gen::imaginary(0)), &Expr::gen(Gen::imaginary(0))),
            Expr::int(-1)
        );
        assert!(gov
            .mul(
                &Expr::gen(Gen::degenerate(0)),
                &Expr::gen(Gen::degenerate(0))
            )
            .is_zero());
        assert_eq!(
            gov.mul(
                &Expr::gen(Gen::hyperbolic(0)),
                &Expr::gen(Gen::hyperbolic(0))
            ),
            Expr::int(1)
        );
    }

    #[test]
    fn load_parametric_matches_cl_constructor() {
        // Parametric .neb loading must produce identical results to Governance::cl().
        let source = include_str!("neb/trit.neb");
        let gens = gens_cl200();
        let neb_gov = load_standard(source, Governance::free(), &gens).unwrap();
        let built_gov = Governance::cl(2, 0, 0);

        let e1 = Expr::gen(Gen::imaginary(0));
        let e2 = Expr::gen(Gen::imaginary(1));
        assert_eq!(neb_gov.mul(&e1, &e1), built_gov.mul(&e1, &e1));
        assert_eq!(neb_gov.mul(&e2, &e2), built_gov.mul(&e2, &e2));
        let e2e1 = Expr::term(
            Rat::one(),
            Word::from_gens(&[Gen::imaginary(1), Gen::imaginary(0)]),
        );
        assert_eq!(neb_gov.canonicalize(&e2e1), built_gov.canonicalize(&e2e1));
    }
}