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
//! Tests for the quote and eval operators in Metal DOL.
//!
//! These tests verify the metaprogramming capabilities of DOL 2.0,
//! including quote (') for capturing expressions as AST data and
//! eval (!) for evaluating quoted expressions.

use metadol::ast::{BinaryOp, Expr, Literal, MatchArm, Pattern, UnaryOp};
use metadol::typechecker::{Type, TypeChecker};

// ============================================
// Helper Functions
// ============================================

fn int_lit(n: i64) -> Expr {
    Expr::Literal(Literal::Int(n))
}

fn float_lit(n: f64) -> Expr {
    Expr::Literal(Literal::Float(n))
}

fn bool_lit(b: bool) -> Expr {
    Expr::Literal(Literal::Bool(b))
}

fn string_lit(s: &str) -> Expr {
    Expr::Literal(Literal::String(s.to_string()))
}

fn ident(name: &str) -> Expr {
    Expr::Identifier(name.to_string())
}

// ============================================
// AST Construction Tests
// ============================================

#[test]
fn test_quote_literal() {
    // Test that Quote(42) can be constructed
    let expr = Expr::Quote(Box::new(int_lit(42)));

    match expr {
        Expr::Quote(inner) => {
            assert!(matches!(*inner, Expr::Literal(Literal::Int(42))));
        }
        _ => panic!("Expected Quote expression"),
    }
}

#[test]
fn test_quote_binary_expr() {
    // '(1 + 2) should be Quote(Binary(Add, 1, 2))
    let expr = Expr::Quote(Box::new(Expr::Binary {
        op: BinaryOp::Add,
        left: Box::new(int_lit(1)),
        right: Box::new(int_lit(2)),
    }));

    match expr {
        Expr::Quote(inner) => match *inner {
            Expr::Binary { op, .. } => assert_eq!(op, BinaryOp::Add),
            _ => panic!("Expected Binary expression inside Quote"),
        },
        _ => panic!("Expected Quote expression"),
    }
}

#[test]
fn test_nested_quote() {
    // ''42 should be Quote(Quote(42))
    let expr = Expr::Quote(Box::new(Expr::Quote(Box::new(int_lit(42)))));

    match expr {
        Expr::Quote(inner) => {
            assert!(matches!(*inner, Expr::Quote(_)));
        }
        _ => panic!("Expected nested Quote"),
    }
}

#[test]
fn test_quote_expr_construction() {
    // Test that Quote expressions can be constructed and inspected
    let expr = Expr::Quote(Box::new(bool_lit(true)));

    if let Expr::Quote(inner) = expr {
        if let Expr::Literal(Literal::Bool(b)) = *inner {
            assert!(b);
        } else {
            panic!("Expected Bool literal");
        }
    } else {
        panic!("Expected Quote");
    }
}

#[test]
fn test_eval_expr_construction() {
    // Test Eval expression construction
    let quoted = Expr::Quote(Box::new(string_lit("hello")));
    let expr = Expr::Eval(Box::new(quoted));

    if let Expr::Eval(inner) = expr {
        if let Expr::Quote(_) = *inner {
            // Good
        } else {
            panic!("Expected Quote inside Eval");
        }
    } else {
        panic!("Expected Eval");
    }
}

// ============================================
// Type Checking Tests
// ============================================

#[test]
fn test_quote_type_is_quoted() {
    let mut checker = TypeChecker::new();

    // '42 should have type Quoted<Int64>
    let expr = Expr::Quote(Box::new(int_lit(42)));
    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], Type::Int64);
        }
        _ => panic!("Expected Quoted type, got {:?}", ty),
    }
}

#[test]
fn test_quote_preserves_inner_type() {
    let mut checker = TypeChecker::new();

    // '(1.5) should have type Quoted<Float64>
    let expr = Expr::Quote(Box::new(float_lit(1.5)));
    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], Type::Float64);
        }
        _ => panic!("Expected Quoted type"),
    }
}

#[test]
fn test_quote_bool_type() {
    let mut checker = TypeChecker::new();

    // 'true should have type Quoted<Bool>
    let expr = Expr::Quote(Box::new(bool_lit(true)));
    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], Type::Bool);
        }
        _ => panic!("Expected Quoted type"),
    }
}

#[test]
fn test_quote_string_type() {
    let mut checker = TypeChecker::new();

    // '"hello" should have type Quoted<String>
    let expr = Expr::Quote(Box::new(string_lit("hello")));
    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], Type::String);
        }
        _ => panic!("Expected Quoted type"),
    }
}

#[test]
fn test_eval_type_unwraps_quoted() {
    let mut checker = TypeChecker::new();

    // !('42) should have type Int64 (unwrapped from Quoted<Int64>)
    let expr = Expr::Eval(Box::new(Expr::Quote(Box::new(int_lit(42)))));
    let ty = checker.infer(&expr).unwrap();

    assert_eq!(ty, Type::Int64);
}

#[test]
fn test_eval_type_unwraps_quoted_float() {
    let mut checker = TypeChecker::new();

    // !('1.5) should have type Float64
    let expr = Expr::Eval(Box::new(Expr::Quote(Box::new(float_lit(1.5)))));
    let ty = checker.infer(&expr).unwrap();

    assert_eq!(ty, Type::Float64);
}

#[test]
fn test_eval_type_unwraps_quoted_bool() {
    let mut checker = TypeChecker::new();

    // !('true) should have type Bool
    let expr = Expr::Eval(Box::new(Expr::Quote(Box::new(bool_lit(true)))));
    let ty = checker.infer(&expr).unwrap();

    assert_eq!(ty, Type::Bool);
}

// Note: The following test requires TypeChecker.env to be public or
// a public method to bind variables. Currently env is private.
// This test demonstrates the intended behavior but may not compile
// until the API is adjusted.
#[test]
#[ignore = "Requires public access to TypeChecker environment"]
fn test_quote_identifier() {
    let mut checker = TypeChecker::new();

    // Quote of identifier - type depends on identifier's type
    // First bind x to Int32
    // Note: This requires making env public or adding a bind method
    // checker.env.bind("x", Type::Int32);

    let expr = Expr::Quote(Box::new(ident("x")));
    let _ty = checker.infer(&expr);

    // Would check: ty is Quoted<Int32>
}

#[test]
fn test_quote_lambda() {
    let mut checker = TypeChecker::new();

    // '(|x| x + 1) - quote a lambda
    let lambda = Expr::Lambda {
        params: vec![("x".to_string(), None)],
        body: Box::new(Expr::Binary {
            op: BinaryOp::Add,
            left: Box::new(ident("x")),
            right: Box::new(int_lit(1)),
        }),
        return_type: None,
    };
    let expr = Expr::Quote(Box::new(lambda));
    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            // Inner type should be a function type
            match &args[0] {
                Type::Function { .. } => {}
                _ => panic!("Expected function type inside Quoted"),
            }
        }
        _ => panic!("Expected Quoted type"),
    }
}

#[test]
fn test_nested_quote_type() {
    let mut checker = TypeChecker::new();

    // ''42 should have type Quoted<Quoted<Int64>>
    let expr = Expr::Quote(Box::new(Expr::Quote(Box::new(int_lit(42)))));
    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic {
            name: outer_name,
            args: outer_args,
        } => {
            assert_eq!(outer_name, "Quoted");
            assert_eq!(outer_args.len(), 1);
            match &outer_args[0] {
                Type::Generic {
                    name: inner_name,
                    args: inner_args,
                } => {
                    assert_eq!(inner_name, "Quoted");
                    assert_eq!(inner_args.len(), 1);
                    assert_eq!(inner_args[0], Type::Int64);
                }
                _ => panic!("Expected nested Quoted type"),
            }
        }
        _ => panic!("Expected Quoted type"),
    }
}

// ============================================
// Round-trip Tests
// ============================================

#[test]
fn test_quote_eval_roundtrip_type() {
    let mut checker = TypeChecker::new();

    // !('(1 + 2)) should have same type as (1 + 2)
    let inner = Expr::Binary {
        op: BinaryOp::Add,
        left: Box::new(int_lit(1)),
        right: Box::new(int_lit(2)),
    };

    let original_type = checker.infer(&inner).unwrap();

    let quoted_then_evaled = Expr::Eval(Box::new(Expr::Quote(Box::new(inner.clone()))));
    let roundtrip_type = checker.infer(&quoted_then_evaled).unwrap();

    // Types should be the same
    assert_eq!(original_type, roundtrip_type);
}

#[test]
fn test_quote_eval_roundtrip_literal() {
    let mut checker = TypeChecker::new();

    // !('42) should have same type as 42
    let literal = int_lit(42);
    let original_type = checker.infer(&literal).unwrap();

    let quoted_then_evaled = Expr::Eval(Box::new(Expr::Quote(Box::new(literal.clone()))));
    let roundtrip_type = checker.infer(&quoted_then_evaled).unwrap();

    assert_eq!(original_type, roundtrip_type);
}

#[test]
fn test_double_quote_double_eval_roundtrip() {
    let mut checker = TypeChecker::new();

    // !(!'(''42)) should have same type as 42
    let literal = int_lit(42);
    let original_type = checker.infer(&literal).unwrap();

    let double_quoted = Expr::Quote(Box::new(Expr::Quote(Box::new(literal.clone()))));
    let double_evaled = Expr::Eval(Box::new(Expr::Eval(Box::new(double_quoted))));
    let roundtrip_type = checker.infer(&double_evaled).unwrap();

    assert_eq!(original_type, roundtrip_type);
}

// ============================================
// Complex Expression Tests
// ============================================

#[test]
fn test_quote_complex_expression() {
    // '(if x then 1 else 2)
    let expr = Expr::Quote(Box::new(Expr::If {
        condition: Box::new(ident("x")),
        then_branch: Box::new(int_lit(1)),
        else_branch: Some(Box::new(int_lit(2))),
    }));

    match expr {
        Expr::Quote(inner) => {
            assert!(matches!(*inner, Expr::If { .. }));
        }
        _ => panic!("Expected Quote"),
    }
}

#[test]
fn test_quote_match_expression() {
    // Quote a match expression
    let expr = Expr::Quote(Box::new(Expr::Match {
        scrutinee: Box::new(ident("x")),
        arms: vec![
            MatchArm {
                pattern: Pattern::Literal(Literal::Int(1)),
                guard: None,
                body: Box::new(string_lit("one")),
            },
            MatchArm {
                pattern: Pattern::Wildcard,
                guard: None,
                body: Box::new(string_lit("other")),
            },
        ],
    }));

    match expr {
        Expr::Quote(inner) => {
            assert!(matches!(*inner, Expr::Match { .. }));
        }
        _ => panic!("Expected Quote"),
    }
}

#[test]
fn test_quote_pipeline() {
    // '(a |> b |> c)
    let pipeline = Expr::Binary {
        op: BinaryOp::Pipe,
        left: Box::new(Expr::Binary {
            op: BinaryOp::Pipe,
            left: Box::new(ident("a")),
            right: Box::new(ident("b")),
        }),
        right: Box::new(ident("c")),
    };

    let expr = Expr::Quote(Box::new(pipeline));

    match expr {
        Expr::Quote(inner) => match *inner {
            Expr::Binary {
                op: BinaryOp::Pipe, ..
            } => {}
            _ => panic!("Expected pipe expression inside quote"),
        },
        _ => panic!("Expected Quote"),
    }
}

#[test]
fn test_quote_composition() {
    // '(f >> g >> h)
    let composition = Expr::Binary {
        op: BinaryOp::Compose,
        left: Box::new(Expr::Binary {
            op: BinaryOp::Compose,
            left: Box::new(ident("f")),
            right: Box::new(ident("g")),
        }),
        right: Box::new(ident("h")),
    };

    let expr = Expr::Quote(Box::new(composition));

    match expr {
        Expr::Quote(inner) => match *inner {
            Expr::Binary {
                op: BinaryOp::Compose,
                ..
            } => {}
            _ => panic!("Expected compose expression inside quote"),
        },
        _ => panic!("Expected Quote"),
    }
}

#[test]
fn test_quote_nested_lambdas() {
    // '(|x| |y| x + y)
    let nested_lambda = Expr::Lambda {
        params: vec![("x".to_string(), None)],
        body: Box::new(Expr::Lambda {
            params: vec![("y".to_string(), None)],
            body: Box::new(Expr::Binary {
                op: BinaryOp::Add,
                left: Box::new(ident("x")),
                right: Box::new(ident("y")),
            }),
            return_type: None,
        }),
        return_type: None,
    };

    let expr = Expr::Quote(Box::new(nested_lambda));

    match expr {
        Expr::Quote(inner) => match *inner {
            Expr::Lambda { .. } => {}
            _ => panic!("Expected lambda inside quote"),
        },
        _ => panic!("Expected Quote"),
    }
}

#[test]
fn test_quote_call_expression() {
    // '(f(x, y, z))
    let call = Expr::Call {
        callee: Box::new(ident("f")),
        args: vec![ident("x"), ident("y"), ident("z")],
    };

    let expr = Expr::Quote(Box::new(call));

    match expr {
        Expr::Quote(inner) => match *inner {
            Expr::Call { args, .. } => {
                assert_eq!(args.len(), 3);
            }
            _ => panic!("Expected call expression inside quote"),
        },
        _ => panic!("Expected Quote"),
    }
}

// ============================================
// Type Checking Error Tests
// ============================================

#[test]
fn test_eval_non_quoted_fails() {
    let mut checker = TypeChecker::new();

    // !(42) should fail - cannot eval a non-quoted expression
    let expr = Expr::Eval(Box::new(int_lit(42)));
    let result = checker.infer(&expr);

    // Should return Error type due to type error
    match result {
        Ok(Type::Error) => {}
        Ok(other) => panic!("Expected Error type, got {:?}", other),
        Err(e) => panic!("Expected Ok(Error), got Err: {:?}", e),
    }

    // Should have collected an error
    assert!(!checker.is_ok(), "Expected type checker to have errors");
}

#[test]
fn test_eval_unknown_type() {
    let mut checker = TypeChecker::new();

    // Eval of an identifier with unknown type
    let expr = Expr::Eval(Box::new(ident("unknown")));
    let result = checker.infer(&expr);

    // Should fail because identifier is undefined
    assert!(result.is_err());
}

// ============================================
// Unary Quote Operator Tests
// ============================================

#[test]
fn test_unary_quote_operator() {
    let mut checker = TypeChecker::new();

    // Using the Unary operator form with Quote
    let expr = Expr::Unary {
        op: UnaryOp::Quote,
        operand: Box::new(int_lit(42)),
    };

    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], Type::Int64);
        }
        _ => panic!("Expected Quoted type"),
    }
}

#[test]
fn test_unary_quote_complex_expr() {
    let mut checker = TypeChecker::new();

    // Quote using unary operator on a complex expression
    let expr = Expr::Unary {
        op: UnaryOp::Quote,
        operand: Box::new(Expr::Binary {
            op: BinaryOp::Mul,
            left: Box::new(int_lit(5)),
            right: Box::new(int_lit(10)),
        }),
    };

    let ty = checker.infer(&expr).unwrap();

    match ty {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            assert!(args[0].is_integer());
        }
        _ => panic!("Expected Quoted type"),
    }
}

// ============================================
// QuotedExpr Conversion Tests
// ============================================

#[test]
fn test_quoted_expr_from_expr() {
    use metadol::ast::QuotedExpr;

    // Test conversion from Expr to QuotedExpr
    let expr = int_lit(42);
    let quoted = QuotedExpr::from_expr(&expr);

    match quoted {
        QuotedExpr::Literal(Literal::Int(42)) => {}
        _ => panic!("Expected literal in QuotedExpr"),
    }
}

#[test]
fn test_quoted_expr_to_expr() {
    use metadol::ast::QuotedExpr;

    // Test conversion from QuotedExpr back to Expr
    let quoted = QuotedExpr::Literal(Literal::Int(42));
    let expr = quoted.to_expr();

    match expr {
        Expr::Literal(Literal::Int(42)) => {}
        _ => panic!("Expected literal in Expr"),
    }
}

#[test]
fn test_quoted_expr_roundtrip() {
    use metadol::ast::QuotedExpr;

    // Test roundtrip conversion
    let original = Expr::Binary {
        op: BinaryOp::Add,
        left: Box::new(int_lit(1)),
        right: Box::new(int_lit(2)),
    };

    let quoted = QuotedExpr::from_expr(&original);
    let converted_back = quoted.to_expr();

    // Verify structure is preserved
    match converted_back {
        Expr::Binary {
            op: BinaryOp::Add, ..
        } => {}
        _ => panic!("Expected binary addition after roundtrip"),
    }
}

#[test]
fn test_quoted_expr_nested_quote() {
    use metadol::ast::QuotedExpr;

    // Test QuotedExpr with nested quotes
    let expr = Expr::Quote(Box::new(int_lit(42)));
    let quoted = QuotedExpr::from_expr(&expr);

    match quoted {
        QuotedExpr::Quote(_) => {}
        _ => panic!("Expected Quote in QuotedExpr"),
    }
}

// ============================================
// Integration Tests
// ============================================

#[test]
fn test_quote_preserves_all_literal_types() {
    let mut checker = TypeChecker::new();

    let test_cases = vec![
        (int_lit(42), Type::Int64),
        (float_lit(1.5), Type::Float64),
        (bool_lit(true), Type::Bool),
        (string_lit("test"), Type::String),
    ];

    for (expr, expected_inner) in test_cases {
        let quoted = Expr::Quote(Box::new(expr));
        let ty = checker.infer(&quoted).unwrap();

        match ty {
            Type::Generic { name, args } => {
                assert_eq!(name, "Quoted");
                assert_eq!(args.len(), 1);
                assert_eq!(args[0], expected_inner);
            }
            _ => panic!("Expected Quoted type for literal"),
        }
    }
}

#[test]
fn test_arithmetic_in_quoted_context() {
    let mut checker = TypeChecker::new();

    // '(1 + 2 * 3) - quote preserves operator precedence
    let expr = Expr::Quote(Box::new(Expr::Binary {
        op: BinaryOp::Add,
        left: Box::new(int_lit(1)),
        right: Box::new(Expr::Binary {
            op: BinaryOp::Mul,
            left: Box::new(int_lit(2)),
            right: Box::new(int_lit(3)),
        }),
    }));

    // Just verify it type checks without error
    let result = checker.infer(&expr);
    assert!(result.is_ok());

    // Should be Quoted<Int64>
    match result.unwrap() {
        Type::Generic { name, args } => {
            assert_eq!(name, "Quoted");
            assert_eq!(args.len(), 1);
            assert!(args[0].is_integer());
        }
        _ => panic!("Expected Quoted type"),
    }
}