doge-compiler 0.3.1

Compiler for the Doge programming language — lexer, parser, semantic checks, and Rust codegen.
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
use super::*;
use crate::ast::dump;

fn parse_ok(source: &str) -> Script {
    parse("test.doge", source).expect("expected a clean parse")
}

fn parse_err(source: &str) -> Diagnostic {
    parse("test.doge", source).expect_err("expected a parse error")
}

#[test]
fn decl_and_bark() {
    let script = parse_ok("such age = 7\nbark age\nwow\n");
    assert_eq!(script.stmts.len(), 2);
    assert!(matches!(script.stmts[0], Stmt::Decl { .. }));
    assert!(matches!(script.stmts[1], Stmt::Bark { .. }));
}

#[test]
fn such_disambiguates_var_vs_func() {
    let var = parse_ok("such x = 1\nwow\n");
    assert!(matches!(var.stmts[0], Stmt::Decl { .. }));
    let func = parse_ok("such greet much name:\n    bark name\nwow\nwow\n");
    match &func.stmts[0] {
        Stmt::FuncDef { name, params, .. } => {
            assert_eq!(name, "greet");
            assert_eq!(params.binding_names(), vec!["name".to_string()]);
            assert!(params.vararg.is_none());
        }
        other => panic!("expected FuncDef, got {other:?}"),
    }
}

#[test]
fn func_without_params_omits_much() {
    let func = parse_ok("such no_args:\n    bark 1\nwow\nwow\n");
    match &func.stmts[0] {
        Stmt::FuncDef { params, .. } => assert!(params.is_empty()),
        other => panic!("expected FuncDef, got {other:?}"),
    }
}

#[test]
fn params_carry_defaults_and_a_variadic() {
    let func = parse_ok("such f much a, b = 2, many rest:\n    bark a\nwow\nwow\n");
    match &func.stmts[0] {
        Stmt::FuncDef { params, .. } => {
            assert_eq!(params.required(), 1);
            assert_eq!(params.params.len(), 2);
            assert!(params.params[0].default.is_none());
            assert!(params.params[1].default.is_some());
            assert_eq!(params.vararg.as_deref(), Some("rest"));
            assert_eq!(params.max_positional(), None);
        }
        other => panic!("expected FuncDef, got {other:?}"),
    }
}

#[test]
fn required_param_after_default_is_an_error() {
    let err = parse_err("such f much a = 1, b:\n    bark a\nwow\nwow\n");
    assert_eq!(err.headline, "very order. much default.");
}

#[test]
fn variadic_must_come_last() {
    let err = parse_err("such f much many rest, a:\n    bark a\nwow\nwow\n");
    assert_eq!(err.headline, "very rest. much greedy.");
}

#[test]
fn non_literal_default_is_an_error() {
    let err = parse_err("such f much a = len:\n    bark a\nwow\nwow\n");
    assert_eq!(err.headline, "very default. much dynamic.");
}

#[test]
fn call_collects_positional_and_keyword_args() {
    let script = parse_ok("f(1, mood = 2)\nwow\n");
    match &script.stmts[0] {
        Stmt::ExprStmt {
            expr: Expr::Call { args, kwargs, .. },
        } => {
            assert_eq!(args.len(), 1);
            assert_eq!(kwargs.len(), 1);
            assert_eq!(kwargs[0].0, "mood");
        }
        other => panic!("expected a call, got {other:?}"),
    }
}

#[test]
fn positional_after_keyword_is_an_error() {
    let err = parse_err("f(a = 1, 2)\nwow\n");
    assert_eq!(err.headline, "very order. much muddle.");
}

#[test]
fn repeated_keyword_arg_is_an_error() {
    let err = parse_err("f(a = 1, a = 2)\nwow\n");
    assert_eq!(err.headline, "very keyword. much repeat.");
}

#[test]
fn so_disambiguates_const_vs_import() {
    let konst = parse_ok("so PI = 3\nwow\n");
    assert!(matches!(konst.stmts[0], Stmt::ConstDecl { .. }));
    let import = parse_ok("so math\nwow\n");
    assert!(matches!(import.stmts[0], Stmt::Import { path: None, .. }));
}

#[test]
fn so_string_is_a_path_import_binding_the_stem() {
    let import = parse_ok("so \"lib/utils.doge\"\nwow\n");
    match &import.stmts[0] {
        Stmt::Import { module, path, .. } => {
            assert_eq!(module, "utils");
            assert_eq!(path.as_deref(), Some("lib/utils.doge"));
        }
        other => panic!("expected a path import, got {other:?}"),
    }
}

#[test]
fn a_path_import_must_end_in_doge() {
    let err = parse_err("so \"lib/utils\"\nwow\n");
    assert_eq!(err.headline, "very path. much confuse.");
    assert!(err.message.contains(".doge"));
}

#[test]
fn a_path_import_rejects_backslashes() {
    let err = parse_err("so \"lib\\\\utils.doge\"\nwow\n");
    assert_eq!(err.headline, "very path. much confuse.");
}

#[test]
fn a_path_import_must_be_relative() {
    let err = parse_err("so \"/lib/utils.doge\"\nwow\n");
    assert_eq!(err.headline, "very path. much confuse.");
}

#[test]
fn a_path_import_stem_must_be_a_plain_name() {
    let err = parse_err("so \"lib/my-utils.doge\"\nwow\n");
    assert_eq!(err.headline, "very path. much confuse.");
}

#[test]
fn a_path_import_rejects_interpolation() {
    let err = parse_err("so \"lib/{x}.doge\"\nwow\n");
    assert_eq!(err.headline, "very import. much confuse.");
}

#[test]
fn bonk_takes_an_expression() {
    let script = parse_ok("bonk \"x\"\nwow\n");
    let dumped = dump(&script);
    assert!(dumped.contains("Bonk"));
    assert!(dumped.contains("Str \"x\""));
}

#[test]
fn bare_bonk_is_a_parse_error() {
    let err = parse_err("bonk\nwow\n");
    assert!(err.message.contains("expected a value"));
}

#[test]
fn pls_oh_no_shape() {
    let script = parse_ok("pls\n    bark 1\noh no err!\n    bark err\nwow\n");
    match &script.stmts[0] {
        Stmt::Try { err_name, .. } => assert_eq!(err_name, "err"),
        other => panic!("expected Try, got {other:?}"),
    }
}

#[test]
fn objects_hold_methods() {
    let src = "many Shibe:\n    such speak:\n        bark 1\n    wow\nwow\nwow\n";
    let script = parse_ok(src);
    match &script.stmts[0] {
        Stmt::ObjDef { name, methods, .. } => {
            assert_eq!(name, "Shibe");
            assert_eq!(methods.len(), 1);
        }
        other => panic!("expected ObjDef, got {other:?}"),
    }
}

#[test]
fn object_body_rejects_non_methods() {
    let err = parse_err("many Shibe:\n    such x = 1\nwow\nwow\n");
    assert_eq!(err.headline, "very object. much confuse.");
}

#[test]
fn object_can_name_a_parent() {
    let src = "many Corgi much Shibe:\n    such speak:\n        bark 1\n    wow\nwow\nwow\n";
    let script = parse_ok(src);
    match &script.stmts[0] {
        Stmt::ObjDef { name, parent, .. } => {
            assert_eq!(name, "Corgi");
            assert_eq!(parent.as_deref(), Some("Shibe"));
        }
        other => panic!("expected ObjDef, got {other:?}"),
    }
    // A plain object has no parent.
    let plain = parse_ok("many Shibe:\n    such go:\n        bark 1\n    wow\nwow\nwow\n");
    match &plain.stmts[0] {
        Stmt::ObjDef { parent, .. } => assert!(parent.is_none()),
        other => panic!("expected ObjDef, got {other:?}"),
    }
}

#[test]
fn super_parses_as_a_method_call() {
    let src = "many Corgi much Shibe:\n    such speak:\n        return super.speak()\n    wow\nwow\nwow\n";
    let script = parse_ok(src);
    assert!(dump(&script).contains("SuperCall speak"));
}

#[test]
fn bare_super_is_a_friendly_error() {
    let err = parse_err("many A much B:\n    such go:\n        return super\n    wow\nwow\nwow\n");
    assert_eq!(err.headline, "very super. much confuse.");
}

#[test]
fn if_elif_else() {
    let script = parse_ok("if a:\n    bark 1\nelif b:\n    bark 2\nelse:\n    bark 3\nwow\n");
    match &script.stmts[0] {
        Stmt::If {
            branches,
            else_body,
            ..
        } => {
            assert_eq!(branches.len(), 2);
            assert!(else_body.is_some());
        }
        other => panic!("expected If, got {other:?}"),
    }
}

#[test]
fn missing_wow_after_function_is_an_error() {
    let err = parse_err("such f:\n    bark 1\n");
    assert_eq!(err.headline, "very incomplete. such missing wow.");
}

#[test]
fn missing_script_wow_is_an_error() {
    let err = parse_err("such x = 1\n");
    assert_eq!(err.headline, "very incomplete. such missing wow.");
}

#[test]
fn extra_after_wow_is_an_error() {
    let err = parse_err("such x = 1\nwow\nbark x\nwow\n");
    assert_eq!(err.headline, "very extra. much after wow.");
}

#[test]
fn chained_comparison_is_an_error() {
    let err = parse_err("bark 1 < x < 10\nwow\n");
    assert!(err.message.contains("chain comparisons"));
}

#[test]
fn membership_parses_as_a_comparison() {
    let script = parse_ok("bark x in xs\nwow\n");
    assert!(dump(&script).contains("Binary in"));
}

#[test]
fn not_in_parses_as_one_operator() {
    let script = parse_ok("bark x not in xs\nwow\n");
    let dumped = dump(&script);
    assert!(dumped.contains("Binary not in"));
    // It is a single membership test, not a `not` wrapping something.
    assert!(!dumped.contains("Unary not"));
}

#[test]
fn not_before_membership_negates_the_whole_test() {
    // `not x in xs` is `not (x in xs)`, matching Python precedence.
    let script = parse_ok("bark not x in xs\nwow\n");
    let dumped = dump(&script);
    let not_at = dumped.find("Unary not").expect("a leading not");
    let in_at = dumped.find("Binary in").expect("a membership test");
    assert!(in_at > not_at, "the membership test nests under the not");
}

#[test]
fn membership_does_not_chain() {
    assert!(parse_err("bark a in b in c\nwow\n")
        .message
        .contains("chain comparisons"));
    assert!(parse_err("bark a < b not in c\nwow\n")
        .message
        .contains("chain comparisons"));
}

#[test]
fn def_gets_the_python_hint() {
    let err = parse_err("def greet():\n    bark 1\nwow\n");
    assert_eq!(err.headline, "very python. much habit.");
}

#[test]
fn precedence_mul_over_add() {
    // 1 + 2 * 3  parses as  1 + (2 * 3)
    let script = parse_ok("bark 1 + 2 * 3\nwow\n");
    let dumped = dump(&script);
    assert!(dumped.contains("Binary +"));
    assert!(dumped.contains("Binary *"));
    // The multiply is nested under the add (deeper indentation).
    let add_at = dumped.find("Binary +").unwrap();
    let mul_at = dumped.find("Binary *").unwrap();
    assert!(mul_at > add_at);
}

#[test]
fn postfix_chains() {
    // a.b[0](c) — attr, then index, then call.
    let script = parse_ok("bark a.b[0](c)\nwow\n");
    match &script.stmts[0] {
        Stmt::Bark { expr, .. } => assert!(matches!(expr, Expr::Call { .. })),
        other => panic!("expected Bark, got {other:?}"),
    }
}

#[test]
fn multi_line_list_inside_brackets() {
    let script = parse_ok("such xs = [\n    1,\n    2,\n]\nwow\n");
    match &script.stmts[0] {
        Stmt::Decl { expr, .. } => match expr {
            Expr::List { items, .. } => assert_eq!(items.len(), 2),
            other => panic!("expected List, got {other:?}"),
        },
        other => panic!("expected Decl, got {other:?}"),
    }
}

#[test]
fn assign_to_non_target_is_an_error() {
    let err = parse_err("1 = 2\nwow\n");
    assert!(err.message.contains("cannot assign"));
}

#[test]
fn power_is_right_associative() {
    let script = parse_ok("bark 2 ** 3 ** 2\nwow\n");
    let expected = "\
Script
  Bark
    Binary **
      Int 2
      Binary **
        Int 3
        Int 2
";
    assert_eq!(dump(&script), expected);
}

#[test]
fn unary_minus_binds_looser_than_power() {
    // -2 ** 2 is -(2 ** 2), so the power nests under the negation.
    let script = parse_ok("bark -2 ** 2\nwow\n");
    let dumped = dump(&script);
    let neg_at = dumped.find("Unary neg").expect("a negation");
    let pow_at = dumped.find("Binary **").expect("a power");
    assert!(pow_at > neg_at, "the power nests under the negation");
}

#[test]
fn bitwise_precedence_or_over_and() {
    // 1 | 2 & 3 parses as 1 | (2 & 3).
    let script = parse_ok("bark 1 | 2 & 3\nwow\n");
    let dumped = dump(&script);
    let or_at = dumped.find("Binary |").expect("a bit-or");
    let and_at = dumped.find("Binary &").expect("a bit-and");
    assert!(and_at > or_at, "the and nests under the or");
}

#[test]
fn shift_binds_tighter_than_comparison_looser_than_add() {
    // 1 + 2 << 3 is (1 + 2) << 3.
    let script = parse_ok("bark 1 + 2 << 3\nwow\n");
    let dumped = dump(&script);
    let shl_at = dumped.find("Binary <<").expect("a shift");
    let add_at = dumped.find("Binary +").expect("an add");
    assert!(add_at > shl_at, "the add nests under the shift");
}

#[test]
fn ternary_parses_with_both_branches() {
    let script = parse_ok("bark \"a\" if true else \"b\"\nwow\n");
    let expected = "\
Script
  Bark
    Ternary
      cond
        Bool true
      then
        Str \"a\"
      else
        Str \"b\"
";
    assert_eq!(dump(&script), expected);
}

#[test]
fn ternary_else_is_required() {
    let err = parse_err("such x = 1 if true\nwow\n");
    assert_eq!(err.headline, "very half. much ternary.");
}

#[test]
fn ternary_else_nests_to_the_right() {
    // a if p else b if q else c  ==  a if p else (b if q else c)
    let script = parse_ok("bark 1 if a else 2 if b else 3\nwow\n");
    let dumped = dump(&script);
    assert_eq!(dumped.matches("Ternary").count(), 2);
    let first = dumped.find("Ternary").unwrap();
    let second = dumped[first + 1..].find("Ternary").unwrap();
    // The second Ternary is more deeply indented — it is the else branch.
    assert!(second > 0);
}

#[test]
fn subscript_stays_a_plain_index() {
    let script = parse_ok("bark xs[0]\nwow\n");
    match &script.stmts[0] {
        Stmt::Bark { expr, .. } => assert!(matches!(expr, Expr::Index { .. })),
        other => panic!("expected Bark, got {other:?}"),
    }
}

#[test]
fn slice_parses_all_three_parts() {
    let script = parse_ok("bark xs[1:2:3]\nwow\n");
    let expected = "\
Script
  Bark
    Slice
      obj
        Ident xs
      start
        Int 1
      end
        Int 2
      step
        Int 3
";
    assert_eq!(dump(&script), expected);
}

#[test]
fn slice_omits_bounds() {
    let script = parse_ok("bark xs[::-1]\nwow\n");
    let dumped = dump(&script);
    assert!(dumped.contains("start none"));
    assert!(dumped.contains("end none"));
    // The step is present: a negated 1.
    assert!(dumped.contains("Unary neg"));
}

#[test]
fn augmented_assignment_carries_its_operator() {
    let script = parse_ok("count += 1\nwow\n");
    match &script.stmts[0] {
        Stmt::Assign {
            op: Some(BinOp::Add),
            flavored: false,
            ..
        } => {}
        other => panic!("expected an augmented Assign, got {other:?}"),
    }
}

#[test]
fn augmented_assignment_works_on_an_item_and_after_very() {
    let idx = parse_ok("xs[0] *= 2\nwow\n");
    match &idx.stmts[0] {
        Stmt::Assign {
            targets,
            op: Some(BinOp::Mul),
            ..
        } if matches!(targets.as_slice(), [Expr::Index { .. }]) => {}
        other => panic!("expected an augmented item Assign, got {other:?}"),
    }
    let flavored = parse_ok("very n -= 3\nwow\n");
    match &flavored.stmts[0] {
        Stmt::Assign {
            op: Some(BinOp::Sub),
            flavored: true,
            ..
        } => {}
        other => panic!("expected a flavored augmented Assign, got {other:?}"),
    }
}

#[test]
fn destructuring_declaration_collects_names_and_collector() {
    let script = parse_ok("such a, b, many rest = xs\nwow\n");
    match &script.stmts[0] {
        Stmt::Decl { names, rest, .. } => {
            assert_eq!(names, &["a".to_string(), "b".to_string()]);
            assert_eq!(rest.as_deref(), Some("rest"));
        }
        other => panic!("expected a destructuring Decl, got {other:?}"),
    }
}

#[test]
fn destructuring_assignment_targets_and_swap_rhs() {
    // `p, q = q, p` — the comma right-hand side desugars into a list literal, so
    // the swap reads both values before either store.
    let script = parse_ok("such p = 1\nsuch q = 2\np, q = q, p\nwow\n");
    match &script.stmts[2] {
        Stmt::Assign {
            targets,
            rest,
            expr,
            op: None,
            ..
        } => {
            assert_eq!(targets.len(), 2);
            assert!(rest.is_none());
            assert!(matches!(expr, Expr::List { items, .. } if items.len() == 2));
        }
        other => panic!("expected a destructuring Assign, got {other:?}"),
    }
}

#[test]
fn for_loop_destructures_its_variables() {
    let script = parse_ok("for k, v in d:\n    bark k\nwow\n");
    match &script.stmts[0] {
        Stmt::For { vars, rest, .. } => {
            assert_eq!(vars, &["k".to_string(), "v".to_string()]);
            assert!(rest.is_none());
        }
        other => panic!("expected a destructuring For, got {other:?}"),
    }
}

#[test]
fn single_declaration_rejects_a_comma_list_value() {
    // `such z = 1, 2` has one name but two values — a list must be explicit.
    let err = parse_err("such z = 1, 2\nwow\n");
    assert!(err.message.contains("only one name"));
}

#[test]
fn augmented_assignment_rejects_multiple_targets() {
    let err = parse_err("such a = 1\nsuch b = 2\na, b += 1\nwow\n");
    assert!(err.message.contains("single target"));
}

#[test]
fn collector_must_be_the_last_target() {
    let err = parse_err("such a, many rest, c = xs\nwow\n");
    assert!(err.message.contains("last target"));
}

#[test]
fn plain_assignment_has_no_operator() {
    let script = parse_ok("x = 1\nwow\n");
    match &script.stmts[0] {
        Stmt::Assign { op: None, .. } => {}
        other => panic!("expected a plain Assign, got {other:?}"),
    }
}

#[test]
fn dump_matches_expected() {
    let script = parse_ok("such age = 7\nbark \"age is \" + age\nwow\n");
    let expected = "\
Script
  Decl age
    Int 7
  Bark
    Binary +
      Str \"age is \"
      Ident age
";
    assert_eq!(dump(&script), expected);
}

// ----- REPL snippet parsing -----

fn repl(source: &str) -> ReplParse {
    parse_repl("repl.doge", source)
}

#[test]
fn repl_completes_a_single_statement_without_wow() {
    assert!(matches!(repl("bark 1\n"), ReplParse::Complete(_)));
    assert!(matches!(repl("such x = 1\n"), ReplParse::Complete(_)));
    // A bare expression is a complete snippet on its own (the prompt echoes it).
    assert!(matches!(repl("1 + 2\n"), ReplParse::Complete(_)));
}

#[test]
fn repl_treats_a_cut_off_construct_as_incomplete() {
    // A block header with no body yet.
    assert!(matches!(repl("if true:\n"), ReplParse::Incomplete(_)));
    // A function missing its wow.
    assert!(matches!(
        repl("such greet:\n    return 1\n"),
        ReplParse::Incomplete(_)
    ));
    // A pls with no oh no yet.
    assert!(matches!(
        repl("pls\n    bark 1\n"),
        ReplParse::Incomplete(_)
    ));
    // An unterminated string can be finished on a later line.
    assert!(matches!(repl("bark \"hi\n"), ReplParse::Incomplete(_)));
    // An open bracket.
    assert!(matches!(repl("such xs = [1,\n"), ReplParse::Incomplete(_)));
}

#[test]
fn repl_reports_a_real_syntax_error() {
    // A failure at a real token (not end of input) is an error, not incompleteness.
    assert!(matches!(repl("bark )\n"), ReplParse::Error(_)));
    assert!(matches!(repl("such 1 = 2\n"), ReplParse::Error(_)));
}

#[test]
fn repl_stops_at_a_top_level_wow() {
    // A leading top-level wow ends the snippet; the statement before it completes.
    match repl("bark 1\nwow\n") {
        ReplParse::Complete(script) => assert_eq!(script.stmts.len(), 1),
        other => panic!(
            "expected complete, got a different outcome: {:?}",
            matches!(other, ReplParse::Complete(_))
        ),
    }
}