brink-ir 0.0.17

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
//! The annotated-brace family's conditional/alternation half → `Conditional`
//! / `Sequence` (`docs/b0-sequencing.md` §B0.7, charter §6).
//!
//! Native disambiguates block-level vs. inline placement **positionally**,
//! not heuristically: a `CONDITIONAL_BLOCK`/`ALTERNATION_BLOCK` reached as a
//! direct `Block`/`ChoiceBody`/arm item (never wrapped in a `CONTENT_LINE`)
//! occupied its own line and lowers to a block-level `Stmt`; the same node
//! kind reached while walking a `CONTENT_LINE`'s children (this module's
//! caller, `body::lower_content_run`) shared a line with other content and
//! lowers to a `ContentPart::InlineConditional`/`InlineSequence` instead.
//! Old ink's dual inline/promoted lowering paths (`lower/conditional/`,
//! `lower/block/promotion.rs`) exist only because ink's CST doesn't make
//! this distinction structurally — native's does, so this module has one
//! lowering function per construct, not two.

use brink_syntax_native::SyntaxKind as N;
use brink_syntax_native::ast::{self, AstNode as _};
use brink_syntax_native::{SyntaxNode, SyntaxToken};

use crate::hir::FileId;
use crate::provenance::{KindToken, NodeClass, Provenance};
use crate::{
    Block, CondBranch, CondKind, Conditional, Diagnostic, DiagnosticCode, Sequence, SequenceBranch,
    SequenceType, Stmt,
};

use super::body::{lower_block, lower_items};
use super::element::Elements;
use super::expr::lower_expr;
use super::provenance::native_provenance;

fn diag(file: FileId, range: rowan::TextRange, code: DiagnosticCode) -> Diagnostic {
    Diagnostic {
        file,
        range,
        message: code.title().to_string(),
        code,
    }
}

/// `{if cond {…} else {…}}` / `{if cond: … else: …}` / `{match subj {…}}`.
///
/// **`CondKind` judgment call** (flagged for the coordinator — a likely
/// D4-style tripwire): a single `if`/`else` here has exactly one condition
/// and an optional else arm. **Correction (issue #1951, 2026-08-01
/// triage):** this comment used to claim "the grammar has no `else if`
/// chain" — false since #1258/#1261 (2026-07-22) added a flat `else if
/// <cond> { … }`/`else if <cond>: …` chain to `family.rs`'s
/// `conditional_block`/`else_branch` (and `control_flow.rs`'s statement-form
/// twin); it parses and executes correctly today. What that ruling did
/// *not* change is this function's shape: a flat native chain still lowers
/// through *nesting*, not a flat multi-branch list — the chain's `else`
/// arm opens a brace-less `CONDITIONAL_BLOCK` of its own (`family.rs::
/// else_branch`'s doc), which recurses back into this same function one
/// level down, producing an `InitialCondition` whose `else` branch's body
/// contains another, nested `Conditional`. Cross-frontend differential
/// testing (`crates/internal/brink-ir/tests/b07_native_body.rs`) found that
/// ink's *own* natural spelling of the simple 2-branch shape
/// (`{cond: body - else: body2}`, `ConditionalWithExpr` plus a branchless
/// first body) lowers the same way, to `CondKind::InitialCondition`, never
/// `IfElse` — `IfElse` only appears for ink's independently-chained
/// multi-condition form (three or more `- cond:` branches, no shared
/// subject), a *flat* multi-branch shape native's own lowering never
/// constructs (it always nests instead, per the paragraph above). So
/// `InitialCondition` — not `IfElse` — is the faithful choice here: it is
/// what the equivalent ink source actually compiles to, and `lir::CondKind`
/// preserves the distinction all the way to codegen (`lir/lower/mod.rs`), so
/// this is a real semantic choice, not cosmetic. (`match` still uses
/// `Switch`, unaffected by this finding.) The practical fallout lands on
/// `hir::emit_native` (the respell emitter), not here: it has no `emit_*`
/// path that re-shapes an ink-sourced `CondKind::IfElse` into this nesting
/// — see that module's doc for the corrected framing.
pub(super) fn lower_conditional(
    file_id: FileId,
    cb: &ast::ConditionalBlock,
    elements: &mut Elements,
    diags: &mut Vec<Diagnostic>,
) -> Conditional {
    let ptr = native_provenance(file_id, NodeClass::Conditional, cb.syntax());

    if cb.is_if() {
        let Some(cond_node) = cb.condition() else {
            diags.push(diag(
                file_id,
                cb.syntax().text_range(),
                DiagnosticCode::E020,
            ));
            return Conditional {
                ptr,
                kind: CondKind::InitialCondition,
                branches: Vec::new(),
            };
        };
        let condition = lower_expr(file_id, &cond_node, diags);
        // B1b (issue #1475): the template condition position of the `as`
        // binding — the same construct the statement form takes, so it
        // reuses the statement form's own lowering (and its E145
        // whole-condition check) verbatim rather than restating the rule.
        let binding = super::control_flow::lower_as_binding(
            file_id,
            cb.as_binding().as_ref(),
            &condition,
            diags,
        );
        let mut branches = Vec::new();
        let if_arm = cb.if_arm();
        // No dedicated arm node when the parser recovered from a missing
        // `if_arm` — fall back to the whole conditional's own span.
        let if_ptr = if_arm.as_ref().map_or(ptr, |arm| {
            native_provenance(file_id, NodeClass::ConditionalBranch, arm.syntax())
        });
        let if_body = if_arm.map_or_else(Block::default, |arm| {
            lower_arm_items(file_id, arm.syntax(), elements, diags)
        });
        branches.push(CondBranch {
            ptr: if_ptr,
            condition: Some(condition),
            binding,
            body: if_body,
            container_id: None,
        });
        if let Some(eb) = cb.else_arm() {
            let else_ptr = native_provenance(file_id, NodeClass::ConditionalBranch, eb.syntax());
            let else_body = lower_arm_items(file_id, eb.syntax(), elements, diags);
            branches.push(CondBranch {
                ptr: else_ptr,
                // Scoped strictly to the success arm — the `else` never
                // sees the binding.
                condition: None,
                binding: None,
                body: else_body,
                container_id: None,
            });
        }
        return Conditional {
            ptr,
            kind: CondKind::InitialCondition,
            branches,
        };
    }

    if cb.is_match() {
        let subject = if let Some(n) = cb.condition() {
            lower_expr(file_id, &n, diags)
        } else {
            diags.push(diag(
                file_id,
                cb.syntax().text_range(),
                DiagnosticCode::E020,
            ));
            crate::Expr::Null
        };
        let branches: Vec<CondBranch> = cb
            .match_arms()
            .map(|arm| lower_match_arm(file_id, &arm, elements, diags))
            .collect();
        return Conditional {
            ptr,
            kind: CondKind::Switch(subject),
            branches,
        };
    }

    // Neither `if` nor `match` — the parser already recorded an error
    // (`family.rs::conditional_block`'s own `p.error`); don't re-diagnose,
    // just hand back an empty, well-formed shape.
    Conditional {
        ptr,
        kind: CondKind::IfElse,
        branches: Vec::new(),
    }
}

fn lower_match_arm(
    file_id: FileId,
    arm: &ast::MatchArm,
    elements: &mut Elements,
    diags: &mut Vec<Diagnostic>,
) -> CondBranch {
    let condition = arm.pattern_expr().map(|n| lower_expr(file_id, &n, diags));
    let body = if let Some(block) = arm.block() {
        lower_block(file_id, &block, elements, diags)
    } else if let Some(expr_node) = arm.bare_expr() {
        // `pattern => expr` with no braces: the arm's "body" is a single
        // expression, not prose. `Stmt::ExprStmt` is the closest existing
        // HIR shape ("expression evaluated for side effects") — a judgment
        // call, since the native grammar doc itself flags this shape as
        // under-specified (`syntax_kind.rs`'s `MATCH_PATTERN` doc: "a bare
        // expression grammar reused, not a real pattern language"). No
        // block-level construct exists for "the value of one expression"
        // in the prose dialect, so this is the least-invented fit.
        let stmts = vec![Stmt::ExprStmt(lower_expr(file_id, &expr_node, diags))];
        let tail = crate::tail_from_stmts(&stmts);
        Block {
            label: None,
            stmts,
            container_id: None,
            tail,
        }
    } else {
        diags.push(diag(
            file_id,
            arm.syntax().text_range(),
            DiagnosticCode::E020,
        ));
        Block::default()
    };
    CondBranch {
        ptr: native_provenance(file_id, NodeClass::ConditionalBranch, arm.syntax()),
        condition,
        // `match` arms are patterns, not conditions — no binding position.
        binding: None,
        body,
        container_id: None,
    }
}

/// Lower an `IF_ARM`/`ELSE_BRANCH` (conditional-family flavor)'s body: a
/// nested `BLOCK` (braced-arm form) or the node's own direct children
/// (colon form — `family.rs::colon_body` opens no wrapper node).
fn lower_arm_items(
    file_id: FileId,
    arm_syntax: &SyntaxNode,
    elements: &mut Elements,
    diags: &mut Vec<Diagnostic>,
) -> Block {
    if let Some(block_node) = arm_syntax.children().find(|n| n.kind() == N::BLOCK) {
        let items: Vec<SyntaxNode> = block_node.children().collect();
        let stmts = lower_items(file_id, &items, 0, elements, diags);
        let tail = crate::tail_from_stmts(&stmts);
        Block {
            label: None,
            stmts,
            container_id: None,
            tail,
        }
    } else {
        let items: Vec<SyntaxNode> = arm_syntax.children().collect();
        let stmts = lower_items(file_id, &items, 0, elements, diags);
        let tail = crate::tail_from_stmts(&stmts);
        Block {
            label: None,
            stmts,
            container_id: None,
            tail,
        }
    }
}

/// `{~ …}` shuffle / `{& …}` cycle / `{! …}` once / `{| …}` stopping.
/// `is_block_level`: whether this alternation occupies its own line (a
/// direct block/arm/choice-body item) — mirrors old ink's
/// `lower_block_sequence`'s leading-`EndOfLine`-per-branch convention,
/// which applies only to the block-promoted case, never the inline one
/// (`lower/conditional/sequence.rs`: `LowerSequence for
/// ast::SequenceWithAnnotation` inserts none; only the dedicated
/// `lower_block_sequence` does).
pub(super) fn lower_alternation(
    file_id: FileId,
    ab: &ast::AlternationBlock,
    elements: &mut Elements,
    diags: &mut Vec<Diagnostic>,
    is_block_level: bool,
) -> Sequence {
    let ptr = native_provenance(file_id, NodeClass::Sequence, ab.syntax());
    let kind = sequence_type(ab);
    let entries: Vec<ast::Entry> = ab.entries().collect();

    let branches: Vec<SequenceBranch> = if entries.is_empty() {
        lower_inline_alternation_branches(file_id, ab.syntax(), elements, diags, is_block_level)
    } else {
        entries
            .iter()
            .map(|e| {
                let branch_ptr = native_provenance(file_id, NodeClass::SequenceBranch, e.syntax());
                let items: Vec<SyntaxNode> = e.items().collect();
                let mut stmts = lower_items(file_id, &items, 0, elements, diags);
                if is_block_level {
                    stmts.insert(0, Stmt::EndOfLine);
                }
                let tail = crate::tail_from_stmts(&stmts);
                SequenceBranch {
                    ptr: branch_ptr,
                    body: Block {
                        label: None,
                        stmts,
                        container_id: None,
                        tail,
                    },
                }
            })
            .collect()
    };

    Sequence {
        ptr,
        kind,
        branches,
        container_id: None,
        counter_id: None,
    }
}

fn sequence_type(ab: &ast::AlternationBlock) -> SequenceType {
    let marker: Option<SyntaxToken> = ab.marker_token();
    match marker.map(|t| t.kind()) {
        Some(N::TILDE) => SequenceType::SHUFFLE,
        Some(N::AMP) => SequenceType::CYCLE,
        Some(N::BANG) => SequenceType::ONCE,
        // `|` (stopping) and the "no marker recognized" fallback share the
        // same default — native has no combinator syntax (each block picks
        // exactly one marker char, unlike ink's `shuffle stopping` word
        // annotations), so there is no "empty mask" case to special-case.
        _ => SequenceType::STOPPING,
    }
}

/// Single-line, pipe-separated alternatives (`{~ red|blue|green}`). No
/// per-alternative wrapper node exists in the CST
/// (`family.rs::inline_alternatives`) — split `ALTERNATION_BLOCK`'s raw
/// children on top-level `PIPE` tokens ourselves.
fn lower_inline_alternation_branches(
    file_id: FileId,
    ab_syntax: &SyntaxNode,
    elements: &mut Elements,
    diags: &mut Vec<Diagnostic>,
    is_block_level: bool,
) -> Vec<SequenceBranch> {
    let mut branches = Vec::new();
    let mut current: Vec<SyntaxNode> = Vec::new();
    let mut past_marker = false;

    for el in ab_syntax.children_with_tokens() {
        match el {
            rowan::NodeOrToken::Node(n) if n.kind() == N::ALTERNATION_MARKER => {
                past_marker = true;
            }
            rowan::NodeOrToken::Node(n) if past_marker => current.push(n),
            rowan::NodeOrToken::Token(t) if past_marker && t.kind() == N::PIPE => {
                branches.push(finish_inline_branch(
                    file_id,
                    ab_syntax,
                    &current,
                    elements,
                    diags,
                    is_block_level,
                ));
                current.clear();
            }
            _ => {}
        }
    }
    branches.push(finish_inline_branch(
        file_id,
        ab_syntax,
        &current,
        elements,
        diags,
        is_block_level,
    ));
    branches
}

/// This alternative's own span (issue #404): the union of its child nodes.
/// No dedicated per-alternative wrapper node exists in the CST (this
/// module's doc), so the union range does not correspond to any single
/// live syntax node — the [`KindToken::SYNTHETIC_RAW`] marker keeps this
/// honest (never resolves back to a node) while still carrying a real byte
/// range for span-consuming tools (diagnostics, editor folding). An empty
/// alternative (e.g. a bare trailing `|`) falls back to the whole
/// alternation block's span.
fn branch_span(file_id: FileId, items: &[SyntaxNode], ab_syntax: &SyntaxNode) -> Provenance {
    let range = items
        .iter()
        .map(SyntaxNode::text_range)
        .fold(None::<rowan::TextRange>, |acc, r| {
            Some(acc.map_or(r, |a| a.cover(r)))
        });
    Provenance::new(
        file_id,
        range.unwrap_or_else(|| ab_syntax.text_range()),
        KindToken::synthetic(NodeClass::SequenceBranch),
    )
}

fn finish_inline_branch(
    file_id: FileId,
    ab_syntax: &SyntaxNode,
    items: &[SyntaxNode],
    elements: &mut Elements,
    diags: &mut Vec<Diagnostic>,
    is_block_level: bool,
) -> SequenceBranch {
    let ptr = branch_span(file_id, items, ab_syntax);
    // Never trailing-EOL: a pipe-separated alternative is a fragment, not a
    // whole line (see `body::lower_content_run`'s doc). Only the leading
    // `EndOfLine` (added below, for the block-level case) marks a line
    // boundary here.
    let mut stmts = super::body::lower_content_run(file_id, items, None, elements, diags, false);
    if is_block_level {
        stmts.insert(0, Stmt::EndOfLine);
    }
    let tail = crate::tail_from_stmts(&stmts);
    SequenceBranch {
        ptr,
        body: Block {
            label: None,
            stmts,
            container_id: None,
            tail,
        },
    }
}