brink-ir 0.0.11

Intermediate representations for inkle's ink narrative scripting language
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
#![allow(clippy::panic)]

use brink_syntax::ast::AstNode;
use brink_syntax::parse;
use rowan::TextRange;

use crate::hir::lower::{
    BodyChild, DeclareSymbols, EffectSink, LowerScope, LowerSink, classify_body_child,
    lower_simple_body,
};
use crate::*;

// ─── Test helpers ───────────────────────────────────────────────────

fn make_scope() -> LowerScope {
    LowerScope::new(FileId(0))
}

fn make_sink() -> EffectSink {
    EffectSink::new(FileId(0))
}

/// Parse source and lower the root body.
fn lower_body(source: &str) -> (Block, Vec<Diagnostic>, SymbolManifest) {
    let parsed = parse(source);
    let tree = parsed.tree();
    let scope = make_scope();
    let mut sink = make_sink();
    let block = lower_simple_body(tree.syntax(), &scope, &mut sink);
    let (manifest, diagnostics) = sink.finish();
    (block, diagnostics, manifest)
}

// ─── Mock sink for testing trait abstraction ────────────────────────

struct TestSink {
    diagnostics: Vec<(TextRange, DiagnosticCode)>,
    symbols: Vec<(SymbolKind, String)>,
}

impl TestSink {
    fn new() -> Self {
        Self {
            diagnostics: Vec::new(),
            symbols: Vec::new(),
        }
    }
}

impl LowerSink for TestSink {
    fn diagnose(&mut self, range: TextRange, code: DiagnosticCode) -> crate::hir::lower::Diagnosed {
        self.diagnostics.push((range, code));
        crate::hir::lower::Diagnosed::test_token()
    }

    fn declare_full(
        &mut self,
        kind: SymbolKind,
        name: &str,
        _range: TextRange,
        _params: Vec<ParamInfo>,
        _detail: Option<String>,
        _doc: Option<DocBlock>,
    ) {
        self.symbols.push((kind, name.to_string()));
    }

    fn add_local(&mut self, _local: crate::symbols::LocalSymbol) {}

    fn add_unresolved(
        &mut self,
        _path: &str,
        _range: TextRange,
        _kind: crate::symbols::RefKind,
        _scope: &Scope,
        _arg_count: Option<usize>,
    ) {
    }
}

// ─── Expression lowering tests ──────────────────────────────────────

#[test]
fn lower_integer_literal() {
    let source = "~ temp x = 42\n";
    let (block, diags, _) = lower_body(source);
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(block.stmts.len(), 1);
    match &block.stmts[0] {
        Stmt::TempDecl(td) => {
            assert_eq!(td.name.text, "x");
            assert!(
                matches!(td.value, Some(Expr::Int(42))),
                "expected Int(42), got {:?}",
                td.value
            );
        }
        other => panic!("expected TempDecl, got {other:?}"),
    }
}

#[test]
fn lower_infix_expression() {
    let source = "~ temp y = 3 + 4\n";
    let (block, diags, _) = lower_body(source);
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(block.stmts.len(), 1);
    match &block.stmts[0] {
        Stmt::TempDecl(td) => {
            assert_eq!(td.name.text, "y");
            assert!(
                matches!(
                    &td.value,
                    Some(Expr::Infix(lhs, InfixOp::Add, rhs))
                    if matches!(lhs.as_ref(), Expr::Int(3))
                    && matches!(rhs.as_ref(), Expr::Int(4))
                ),
                "expected 3 + 4, got {:?}",
                td.value
            );
        }
        other => panic!("expected TempDecl, got {other:?}"),
    }
}

// ─── Content lowering tests ─────────────────────────────────────────

#[test]
fn simple_text_line() {
    let (block, diags, _) = lower_body("Hello, world!\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(block.stmts.len(), 2, "expected Content + EndOfLine");
    assert!(matches!(&block.stmts[0], Stmt::Content(c) if !c.parts.is_empty()));
    assert!(matches!(&block.stmts[1], Stmt::EndOfLine));
}

#[test]
fn expression_interpolation() {
    let (block, diags, _) = lower_body("Value is {x}\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(block.stmts.len(), 2);
    match &block.stmts[0] {
        Stmt::Content(c) => {
            assert!(c.parts.len() >= 2, "expected text + interpolation");
            assert!(matches!(&c.parts[0], ContentPart::Text(t) if t.contains("Value")));
            assert!(
                matches!(&c.parts[1], ContentPart::Interpolation(Expr::Path(_))),
                "expected path interpolation, got {:?}",
                c.parts[1]
            );
        }
        other => panic!("expected Content, got {other:?}"),
    }
}

#[test]
fn tag_on_content_line() {
    let (block, diags, _) = lower_body("Hello #greeting\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(block.stmts.len(), 2);
    match &block.stmts[0] {
        Stmt::Content(c) => {
            assert!(!c.tags.is_empty(), "expected at least one tag");
            assert!(
                matches!(&c.tags[0].parts[0], ContentPart::Text(t) if t == "greeting"),
                "expected 'greeting' tag, got {:?}",
                c.tags[0].parts
            );
        }
        other => panic!("expected Content, got {other:?}"),
    }
}

#[test]
fn logic_line_assignment() {
    let source = "~ temp x = 0\n~ x = 5\n";
    let (block, diags, _) = lower_body(source);
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(block.stmts.len(), 2, "expected TempDecl + Assignment");
    assert!(matches!(&block.stmts[0], Stmt::TempDecl(_)));
    assert!(matches!(&block.stmts[1], Stmt::Assignment(_)));
}

// ─── Diagnostic tests ───────────────────────────────────────────────

#[test]
fn logic_line_emits_diagnostic_on_malformed() {
    // A logic line with just `~` and nothing else should emit E014.
    let source = "~\n";
    let (_, diags, _) = lower_body(source);
    assert!(
        diags.iter().any(|d| d.code == DiagnosticCode::E014),
        "expected E014 diagnostic, got: {:?}",
        diags.iter().map(|d| d.code.as_str()).collect::<Vec<_>>()
    );
}

// ─── Mock sink tests ────────────────────────────────────────────────

#[test]
fn mock_sink_records_diagnostics() {
    let parsed = parse("~\n");
    let tree = parsed.tree();
    let scope = make_scope();
    let mut sink = TestSink::new();
    let _ = lower_simple_body(tree.syntax(), &scope, &mut sink);
    assert!(
        sink.diagnostics
            .iter()
            .any(|(_, code)| *code == DiagnosticCode::E014),
        "expected E014 in mock sink"
    );
}

#[test]
fn mock_sink_records_symbol_declarations() {
    let parsed = parse("VAR x = 5\n");
    let tree = parsed.tree();
    let scope = make_scope();
    let mut sink = TestSink::new();

    // Declarations are hoisted, not part of body lowering.
    // Directly test the DeclareSymbols trait.
    for node in tree.syntax().descendants() {
        if let Some(var) = brink_syntax::ast::VarDecl::cast(node) {
            let _ = var.declare_and_lower(&scope, &mut sink);
        }
    }
    assert!(
        sink.symbols
            .iter()
            .any(|(kind, name)| *kind == SymbolKind::Variable && name == "x"),
        "expected variable 'x' in mock sink, got: {:?}",
        sink.symbols
    );
}

// ─── BodyChild classification tests ─────────────────────────────────

#[test]
fn classify_recognizes_content_line() {
    let parsed = parse("Hello\n");
    let tree = parsed.tree();
    let mut found = false;
    for child in tree.syntax().children() {
        if matches!(classify_body_child(&child), BodyChild::ContentLine(_)) {
            found = true;
        }
    }
    assert!(found, "expected to find a ContentLine child");
}

#[test]
fn classify_recognizes_logic_line() {
    let parsed = parse("~ temp x = 1\n");
    let tree = parsed.tree();
    let mut found = false;
    for child in tree.syntax().children() {
        if matches!(classify_body_child(&child), BodyChild::LogicLine(_)) {
            found = true;
        }
    }
    assert!(found, "expected to find a LogicLine child");
}

// ─── Accumulator tests ──────────────────────────────────────────────

#[test]
fn accumulator_content_with_glue_suppresses_eol() {
    let source = "Hello<>\n";
    let (block, diags, _) = lower_body(source);
    assert!(diags.is_empty());
    // Glue suppresses EndOfLine — should have Content only, no EndOfLine
    assert!(
        matches!(&block.stmts[0], Stmt::Content(c) if !c.parts.is_empty()),
        "expected Content stmt"
    );
    // Should NOT have EndOfLine after glue
    assert!(
        !block.stmts.iter().any(|s| matches!(s, Stmt::EndOfLine)),
        "EndOfLine should be suppressed by glue"
    );
}

#[test]
fn accumulator_logic_line_with_call_emits_eol() {
    // A function call in a logic line triggers EndOfLine
    let source = "=== function f() ===\n~ return 1\n=== main ===\n~ f()\n";
    let (block, _, _) = lower_body(source);
    // Root body might be empty (knots handle their own bodies),
    // so just verify it compiles and doesn't panic.
    let _ = block;
}

// ─── Doc-comment attachment tests ───────────────────────────────────

/// Lower a complete file and return its manifest + diagnostics.
fn lower_full(source: &str) -> (SymbolManifest, Vec<Diagnostic>) {
    let parsed = parse(source);
    let tree = parsed.tree();
    let (_hir, manifest, diags) = crate::hir::lower(FileId(0), &tree);
    (manifest, diags)
}

#[test]
fn docs_attach_to_all_declaration_kinds() {
    let source = "\
/// An external.
EXTERNAL ping(x)
/// A variable.
VAR health = 100
/// A constant.
CONST SPEED = 0.5
/// A list.
LIST mood = happy, sad
/// A knot.
== hub ==
intro
/// A nested stitch.
= market
stalls
/// A function knot.
== function damage(weapon) ==
~ return 1
";
    let (manifest, diags) = lower_full(source);
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");

    let doc_text = |kind: SymbolKind, name: &str| {
        manifest
            .docs
            .get(&(kind, name.to_string()))
            .unwrap_or_else(|| panic!("doc for {kind:?} {name}"))
            .doc
            .clone()
    };
    assert_eq!(
        doc_text(SymbolKind::External, "ping").as_deref(),
        Some("An external.")
    );
    assert_eq!(
        doc_text(SymbolKind::Variable, "health").as_deref(),
        Some("A variable.")
    );
    assert_eq!(
        doc_text(SymbolKind::Constant, "SPEED").as_deref(),
        Some("A constant.")
    );
    assert_eq!(
        doc_text(SymbolKind::List, "mood").as_deref(),
        Some("A list.")
    );
    assert_eq!(
        doc_text(SymbolKind::Knot, "hub").as_deref(),
        Some("A knot.")
    );
    assert_eq!(
        doc_text(SymbolKind::Stitch, "hub.market").as_deref(),
        Some("A nested stitch."),
        "nested stitch docs are keyed by qualified name"
    );
    assert_eq!(
        doc_text(SymbolKind::Knot, "damage").as_deref(),
        Some("A function knot.")
    );
}

#[test]
fn inapplicable_tags_emit_e043() {
    let source = "\
/// @kind query
== hub ==
intro
/// @param x {int}
VAR health = 100
";
    let (manifest, diags) = lower_full(source);
    let e043: Vec<_> = diags
        .iter()
        .filter(|d| d.code == DiagnosticCode::E043)
        .collect();
    assert_eq!(e043.len(), 2, "one E043 per inapplicable tag: {diags:?}");
    // The dropped tags leave no doc content behind.
    assert!(
        !manifest
            .docs
            .contains_key(&(SymbolKind::Knot, "hub".to_string())),
        "tag-only block with all tags dropped attaches nothing"
    );
}

#[test]
fn undocumented_declarations_have_no_doc_entries() {
    let source = "\
EXTERNAL ping(x)
VAR health = 100
== hub ==
intro
";
    let (manifest, diags) = lower_full(source);
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert!(manifest.docs.is_empty());
}

// ─── Directive annotations (`#@…`) ──────────────────────────────────

/// Full-file lower returning the HIR too.
fn lower_hir(source: &str) -> (HirFile, Vec<Diagnostic>) {
    let parsed = parse(source);
    let tree = parsed.tree();
    let (hir, _manifest, diags) = crate::hir::lower(FileId(0), &tree);
    (hir, diags)
}

/// Collect every tag string that survives into lowered content
/// (blocks, recursively through knots/stitches).
fn all_content_tags(hir: &HirFile) -> Vec<String> {
    fn tags_in_block(block: &Block, out: &mut Vec<String>) {
        for stmt in &block.stmts {
            if let Stmt::Content(c) = stmt {
                for tag in &c.tags {
                    let mut text = String::new();
                    for part in &tag.parts {
                        if let ContentPart::Text(t) = part {
                            text.push_str(t);
                        }
                    }
                    out.push(text);
                }
            }
        }
    }
    let mut out = Vec::new();
    tags_in_block(&hir.root_content, &mut out);
    for knot in &hir.knots {
        tags_in_block(&knot.body, &mut out);
        for stitch in &knot.stitches {
            tags_in_block(&stitch.body, &mut out);
        }
    }
    out
}

fn codes(diags: &[Diagnostic]) -> Vec<DiagnosticCode> {
    diags.iter().map(|d| d.code).collect()
}

#[test]
fn local_directive_marks_var() {
    let (hir, diags) = lower_hir("#@local\nVAR mood = 0\nhello\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(hir.variables.len(), 1);
    assert!(hir.variables[0].is_local);
    // Erasure: the directive never becomes a content tag.
    assert!(all_content_tags(&hir).is_empty());
}

#[test]
fn plain_var_is_not_local() {
    let (hir, diags) = lower_hir("VAR mood = 0\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert!(!hir.variables[0].is_local);
}

#[test]
fn local_directive_marks_knot_from_top_of_body() {
    let (hir, diags) = lower_hir("== guard ==\n#@local\nHalt!\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert_eq!(hir.knots.len(), 1);
    assert!(hir.knots[0].is_local);
    assert!(all_content_tags(&hir).is_empty());
}

#[test]
fn local_directive_marks_stitch() {
    let (hir, diags) = lower_hir("== guard ==\nHalt!\n= mood\n#@local\ngrumpy\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert!(!hir.knots[0].is_local);
    assert!(hir.knots[0].stitches[0].is_local);
}

#[test]
fn knot_directive_coexists_with_plain_knot_tags() {
    let (hir, diags) = lower_hir("== guard ==\n# author: bob\n#@local\nHalt!\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert!(hir.knots[0].is_local);
    // The plain tag line survives as content; the directive is erased.
    assert_eq!(all_content_tags(&hir), vec!["author: bob".to_string()]);
}

#[test]
fn unmarked_knot_is_not_local() {
    let (hir, diags) = lower_hir("== guard ==\nHalt!\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert!(!hir.knots[0].is_local);
}

#[test]
fn unknown_directive_is_e044() {
    let (_hir, diags) = lower_hir("#@locale\nVAR mood = 0\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E044]);
}

#[test]
fn directive_above_content_line_is_e045() {
    let (hir, diags) = lower_hir("#@local\njust text\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E045]);
    // Still erased — never a runtime tag.
    assert!(all_content_tags(&hir).is_empty());
}

#[test]
fn inline_directive_tag_is_e045() {
    let (hir, diags) = lower_hir("some text #@local\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E045]);
    assert!(all_content_tags(&hir).is_empty());
}

#[test]
fn directive_mid_knot_body_is_e045() {
    let (_hir, diags) = lower_hir("== guard ==\nHalt!\n#@local\nmore\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E045]);
}

#[test]
fn dynamic_directive_is_e046() {
    let (_hir, diags) = lower_hir("#@{x}\nVAR mood = 0\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E046]);
}

#[test]
fn mixed_directive_and_plain_tags_is_e047() {
    let (hir, diags) = lower_hir("#@local # art.png\nsome text\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E047]);
    // The plain tag survives; the directive is erased.
    assert_eq!(all_content_tags(&hir), vec!["art.png".to_string()]);
}

#[test]
fn duplicate_local_directive_is_e048() {
    let (hir, diags) = lower_hir("#@local\n#@local\nVAR mood = 0\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E048]);
    // First one still applies.
    assert!(hir.variables[0].is_local);
}

#[test]
fn local_on_const_is_e049() {
    let (_hir, diags) = lower_hir("#@local\nCONST max = 3\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E049]);
}

#[test]
fn local_on_list_is_e049() {
    let (_hir, diags) = lower_hir("#@local\nLIST moods = happy, sad\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E049]);
}

#[test]
fn local_on_external_is_e049() {
    let (_hir, diags) = lower_hir("#@local\nEXTERNAL ping(x)\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E049]);
}

#[test]
fn local_with_args_is_e050() {
    let (_hir, diags) = lower_hir("#@local(now)\nVAR mood = 0\n");
    assert_eq!(codes(&diags), vec![DiagnosticCode::E050]);
}

#[test]
fn directive_with_blank_line_still_attaches() {
    let (hir, diags) = lower_hir("#@local\n\nVAR mood = 0\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    assert!(hir.variables[0].is_local);
}

#[test]
fn plain_tag_lines_are_unaffected() {
    let (hir, diags) = lower_hir("# above\nsome text # inline\n");
    assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
    let tags = all_content_tags(&hir);
    assert_eq!(tags.len(), 2, "both plain tags survive: {tags:?}");
}