brink-ir 0.0.15

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
use brink_format::{LinePart, SlotInfo, SourceLocation};

use crate::hir;
use crate::hir::display_expr;

use super::content::lower_content_parts_pub;
use super::context::LowerCtx;
use super::expr::lower_expr;
use super::lir;

/// Compose two HIR content objects by concatenating their parts and tags.
///
/// Adjacent `Text` parts at the boundary are merged into one. The resulting
/// content uses the first content's `ptr` for source location.
pub fn compose_hir_content(a: &hir::Content, b: &hir::Content) -> hir::Content {
    let mut parts = a.parts.clone();

    // Merge adjacent text parts at the boundary, collapsing double
    // whitespace at the join point (e.g., "Hello " + " world" → "Hello world").
    if let (Some(hir::ContentPart::Text(last)), Some(hir::ContentPart::Text(first))) =
        (parts.last(), b.parts.first())
    {
        let merged =
            if last.ends_with(char::is_whitespace) && first.starts_with(char::is_whitespace) {
                format!("{last}{}", first.trim_start())
            } else {
                format!("{last}{first}")
            };
        let len = parts.len();
        parts[len - 1] = hir::ContentPart::Text(merged);
        parts.extend(b.parts.iter().skip(1).cloned());
    } else {
        parts.extend(b.parts.iter().cloned());
    }

    let mut tags = a.tags.clone();
    tags.extend(b.tags.iter().cloned());

    hir::Content {
        ptr: a.ptr,
        parts,
        tags,
    }
}

/// Compose display or output content from optional HIR content parts.
///
/// Returns `None` if both parts are `None`.
pub fn compose_hir_content_opt(
    a: Option<&hir::Content>,
    b: Option<&hir::Content>,
) -> Option<hir::Content> {
    match (a, b) {
        (None, None) => None,
        (Some(c), None) | (None, Some(c)) => Some(c.clone()),
        (Some(a_content), Some(b_content)) => Some(compose_hir_content(a_content, b_content)),
    }
}

/// Check whether HIR content starts with a whitespace-only text part.
///
/// When content with leading whitespace is emitted inline via
/// `push_text`, the runtime's output buffer suppresses whitespace-only
/// text at the start. `EvalLine`/`EmitLine` bypass this filtering
/// (they resolve the template in one shot), so we must skip recognition
/// for content that relies on the runtime's whitespace suppression.
pub fn starts_with_whitespace_only_text(content: &hir::Content) -> bool {
    matches!(content.parts.first(), Some(hir::ContentPart::Text(s)) if !s.is_empty() && s.trim().is_empty())
}

/// Try to recognize a HIR content line as a known pattern.
///
/// Phase 1: matches `[Text(s)]` (exactly one text part, no dynamic content)
/// and returns `ContentEmission` with `RecognizedLine::Plain(s)`.
///
/// Phase 3: matches lines of `Text` and `Interpolation` parts (with at least
/// one `Interpolation`) and returns `RecognizedLine::Template`.
///
/// Returns `None` for any other pattern — the caller falls back to
/// `EmitContent(lower_content(...))`.
pub fn try_recognize(
    content: &hir::Content,
    ctx: &mut LowerCtx<'_>,
) -> Option<lir::ContentEmission> {
    // Phase 1: plain text — exactly one Text part, nothing else.
    if content.parts.len() == 1
        && let hir::ContentPart::Text(s) = &content.parts[0]
    {
        let source_hash = brink_format::content_hash(s);
        let source_location = build_source_location(content, ctx);
        let tags = content
            .tags
            .iter()
            .map(|t| lower_content_parts_pub(&t.parts, ctx))
            .collect();
        return Some(lir::ContentEmission {
            line: lir::RecognizedLine::Plain(s.clone()),
            metadata: lir::LineMetadata {
                source_hash,
                slot_info: Vec::new(),
                source_location,
            },
            tags,
        });
    }

    // Phase 3: template — all parts are Text/Interpolation/Span
    // (recursively, for Span), with ≥1 Interpolation-or-Span and ≥1
    // non-whitespace Text somewhere in the tree.
    if try_recognize_template(content, ctx) {
        let mut template_parts = Vec::new();
        let mut slot_exprs = Vec::new();
        let mut slot_info = Vec::new();
        let mut hash_source = String::new();
        let mut slot_idx: u8 = 0;

        build_recognized_parts(
            &content.parts,
            ctx,
            &mut template_parts,
            &mut hash_source,
            &mut slot_exprs,
            &mut slot_info,
            &mut slot_idx,
        );

        let source_hash = brink_format::content_hash(&hash_source);
        let source_location = build_source_location(content, ctx);
        let tags = content
            .tags
            .iter()
            .map(|t| lower_content_parts_pub(&t.parts, ctx))
            .collect();

        return Some(lir::ContentEmission {
            line: lir::RecognizedLine::Template {
                parts: template_parts,
                slot_exprs,
            },
            metadata: lir::LineMetadata {
                source_hash,
                slot_info,
                source_location,
            },
            tags,
        });
    }

    None
}

/// Strip leading and trailing `Glue` parts from content and merge interior
/// `[Text, Glue, Text]` runs into a single `Text`.
///
/// Returns `(has_leading_glue, stripped_content, has_trailing_glue)`.
/// Interior glue adjacent to non-text parts (Interpolation, `InlineConditional`,
/// etc.) is NOT stripped — those prevent recognition.
pub fn strip_boundary_glue(content: &hir::Content) -> (bool, hir::Content, bool) {
    let parts = &content.parts;

    // Strip leading glue
    let mut start = 0;
    let mut has_leading = false;
    while start < parts.len() && parts[start] == hir::ContentPart::Glue {
        has_leading = true;
        start += 1;
    }

    // Strip trailing glue
    let mut end = parts.len();
    let mut has_trailing = false;
    while end > start && parts[end - 1] == hir::ContentPart::Glue {
        has_trailing = true;
        end -= 1;
    }

    // Merge interior [Text, Glue, Text] runs into single Text.
    // Interior glue adjacent to non-Text parts is left alone (will prevent recognition).
    let interior = &parts[start..end];
    let mut merged_parts: Vec<hir::ContentPart> = Vec::with_capacity(interior.len());
    for part in interior {
        match part {
            hir::ContentPart::Glue => {
                // Check if both the previous and next parts are Text.
                // At this point we only have the previous part available, so we
                // check the previous. We'll merge when we see the next Text.
                if matches!(merged_parts.last(), Some(hir::ContentPart::Text(_))) {
                    // Tentatively mark as "pending merge" by pushing Glue.
                    // We'll resolve this when the next part arrives.
                    merged_parts.push(hir::ContentPart::Glue);
                } else {
                    // Glue adjacent to non-Text — keep it (will block recognition).
                    merged_parts.push(hir::ContentPart::Glue);
                }
            }
            hir::ContentPart::Text(s) => {
                // If the previous part is Glue and the part before that is Text,
                // merge all three into one Text.
                if matches!(merged_parts.last(), Some(hir::ContentPart::Glue)) {
                    merged_parts.pop(); // remove the Glue
                    if let Some(hir::ContentPart::Text(prev)) = merged_parts.last_mut() {
                        prev.push_str(s);
                    } else {
                        // Glue was at the start of interior (shouldn't happen after
                        // boundary stripping, but be safe) — keep as separate text.
                        merged_parts.push(hir::ContentPart::Text(s.clone()));
                    }
                } else {
                    merged_parts.push(part.clone());
                }
            }
            _ => {
                merged_parts.push(part.clone());
            }
        }
    }

    let stripped = hir::Content {
        ptr: content.ptr,
        parts: merged_parts,
        tags: content.tags.clone(),
    };

    (has_leading, stripped, has_trailing)
}

/// Try to recognize content after stripping boundary glue.
///
/// Returns `None` if no glue was stripped (caller already tried plain
/// `try_recognize`) or if the stripped interior is still unrecognizable.
pub fn try_recognize_with_glue(
    content: &hir::Content,
    ctx: &mut LowerCtx<'_>,
) -> Option<(bool, lir::ContentEmission, bool)> {
    let (has_leading, stripped, has_trailing) = strip_boundary_glue(content);

    // If nothing changed, don't retry — caller already tried try_recognize.
    if !has_leading && !has_trailing && stripped.parts.len() == content.parts.len() {
        return None;
    }

    // Empty interior after stripping? Not recognizable.
    if stripped.parts.is_empty() {
        return None;
    }

    let emission = try_recognize(&stripped, ctx)?;
    Some((has_leading, emission, has_trailing))
}

/// Build a `SourceLocation` from the content's syntax pointer and the file path map.
fn build_source_location(content: &hir::Content, ctx: &LowerCtx<'_>) -> Option<SourceLocation> {
    let ptr = content.ptr.as_ref()?;
    let range = ptr.text_range();
    let file = ctx.file_paths.get(&ctx.file)?;
    Some(SourceLocation {
        file: file.clone(),
        range_start: range.start().into(),
        range_end: range.end().into(),
    })
}

/// Check if all content parts are admissible for `Template`/`Span` wire
/// recognition — Text, Interpolation, or (§4.4) a Span whose own
/// `children` are, recursively, the same three shapes — with ≥1
/// Interpolation-or-Span (the reason a markup-only line like `Hello
/// <wave>world</wave>` still needs admission even with zero
/// interpolations: once a Span splits the text into more than one
/// top-level part, it is no longer Phase 1's single-Text-part `Plain`
/// shape either) and (≥1 non-whitespace Text part somewhere in the tree,
/// **or** ≥1 `Span` present at all).
///
/// The `Span`-present escape hatch matters for a point-marker-only line
/// (§8b.11 — `<pause/>` alone, with no surrounding text): the
/// non-whitespace-text requirement (`d7058cd2d`, "skip template
/// recognition for whitespace-only text between slots" — deliberately
/// keeps a bare `{f()} {g()}` off the `Template` path, since the
/// whitespace there is structural glue, not translatable content) would
/// otherwise decline a line whose *entire* content is a childless span,
/// sending it to `EmitContent`'s flattening — which for a span with no
/// children drops `name`/`attrs` and emits **nothing**, silently, with no
/// diagnostic (unlike the interior-`InlineConditional`/`InlineSequence`
/// case below, that flattening loses real data, not just the
/// presentational boundary). A `Span` occupying a content-part slot is
/// never itself whitespace glue — even self-closing, its `name`/`attrs`
/// are the translatable content — so its mere presence satisfies the
/// "real content" requirement the whitespace-glue guard exists for.
///
/// A Span containing something this doesn't admit (a `DIVERT`-adjacent
/// shape has none — `Span`'s HIR children can only ever be
/// Text/Interpolation/Span/InlineConditional/InlineSequence by
/// construction — but an `InlineConditional`/`InlineSequence` nested in a
/// Span is exactly that "something else": §4.4's still-open "span
/// admission" note) declines the *whole* line, which falls back to
/// `EmitContent`'s flattening (`lir::lower::content`'s own doc) — not a
/// silent drop, just not a translation-table entry yet.
fn try_recognize_template(content: &hir::Content, _ctx: &LowerCtx<'_>) -> bool {
    is_template_admissible(&content.parts)
        && content_has_span_or_interpolation(&content.parts)
        && (content_has_nonempty_text(&content.parts) || content_has_span(&content.parts))
}

fn is_template_admissible(parts: &[hir::ContentPart]) -> bool {
    parts.iter().all(|p| match p {
        hir::ContentPart::Text(_) | hir::ContentPart::Interpolation(_) => true,
        hir::ContentPart::Span(span) => is_template_admissible(&span.children),
        hir::ContentPart::Glue
        | hir::ContentPart::Spring
        | hir::ContentPart::InlineConditional(_)
        | hir::ContentPart::InlineSequence(_) => false,
    })
}

fn content_has_span_or_interpolation(parts: &[hir::ContentPart]) -> bool {
    parts.iter().any(|p| {
        matches!(
            p,
            hir::ContentPart::Interpolation(_) | hir::ContentPart::Span(_)
        )
    })
}

/// Whether any top-level part is a `Span` (self-closing or not). Doesn't need
/// to recurse — a nested `Span` always has a top-level `Span` ancestor here,
/// since `ContentPart` children only ever live inside another `Span`.
fn content_has_span(parts: &[hir::ContentPart]) -> bool {
    parts.iter().any(|p| matches!(p, hir::ContentPart::Span(_)))
}

fn content_has_nonempty_text(parts: &[hir::ContentPart]) -> bool {
    parts.iter().any(|p| match p {
        hir::ContentPart::Text(s) => !s.trim().is_empty(),
        hir::ContentPart::Span(span) => content_has_nonempty_text(&span.children),
        _ => false,
    })
}

/// Recursively build wire `LinePart`s from admitted `hir::ContentPart`s
/// (`try_recognize_template` already validated the shape — the `_ =>
/// unreachable!` arm mirrors that same validated-shape invariant this
/// function's caller has always relied on).
///
/// Accumulates the flat `hash_source` string `source_hash` is computed
/// from — **hash-transparency** (§4.4, RULED before any markup ships)
/// means a `Span`'s `name`/`attrs` never touch it, only its `children`'s
/// own text/interpolation-placeholders do, exactly the way a bare
/// `Interpolation` already contributes the placeholder `"{…}"` rather than
/// its resolved value: `Hello <wave>world</wave>` and `Hello world` hash
/// identically. Also accumulates `slot_exprs`/`slot_info` flatly and
/// `slot_idx` globally across the *whole* line, spans included — a
/// `<b>{x}</b>` inside `…{y}…` numbers `x`/`y` in the one left-to-right
/// order `emit_slot_expr` will later push them onto the evaluation stack
/// in, span boundaries notwithstanding.
fn build_recognized_parts(
    parts: &[hir::ContentPart],
    ctx: &mut LowerCtx<'_>,
    out: &mut Vec<LinePart>,
    hash_source: &mut String,
    slot_exprs: &mut Vec<lir::Expr>,
    slot_info: &mut Vec<SlotInfo>,
    slot_idx: &mut u8,
) {
    for part in parts {
        match part {
            hir::ContentPart::Text(s) => {
                out.push(LinePart::Literal(s.clone()));
                hash_source.push_str(s);
            }
            hir::ContentPart::Interpolation(expr) => {
                out.push(LinePart::Slot(*slot_idx));
                slot_exprs.push(lower_expr(expr, ctx));
                slot_info.push(SlotInfo {
                    index: *slot_idx,
                    name: display_expr(expr),
                });
                hash_source.push_str("{…}");
                *slot_idx = slot_idx.saturating_add(1);
            }
            hir::ContentPart::Span(span) => {
                let mut children = Vec::with_capacity(span.children.len());
                build_recognized_parts(
                    &span.children,
                    ctx,
                    &mut children,
                    hash_source,
                    slot_exprs,
                    slot_info,
                    slot_idx,
                );
                out.push(LinePart::Span {
                    name: span.name.clone(),
                    // `LinePart::Span::attrs` is the wire shape's flat
                    // `Vec<(String, String)>` (untouched by #1782 and by
                    // #1829: E164/E165 fire during HIR analysis, before LIR
                    // lowering ever runs, so per-attribute provenance has
                    // nothing to carry across this boundary).
                    attrs: span
                        .attrs
                        .iter()
                        .map(|attr| (attr.name.clone(), attr.value.clone()))
                        .collect(),
                    children,
                });
            }
            hir::ContentPart::Glue
            | hir::ContentPart::Spring
            | hir::ContentPart::InlineConditional(_)
            | hir::ContentPart::InlineSequence(_) => {
                unreachable!("try_recognize_template already validated")
            }
        }
    }
}