brink-ir 0.0.3

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
//! Diagnostic suppression and expectation directives.
//!
//! Supports:
//! - `// brink-disable-all`  — suppress all diagnostics for the entire project (root file only)
//! - `// brink-disable-file` — suppress all diagnostics in this file
//! - `// brink-disable`      — suppress all diagnostics on the next line
//! - `// brink-disable E027` — suppress specific code(s) on the next line
//! - `// brink-expect E027`  — suppress E027 on next line, error if E027 doesn't appear
//! - `// brink-expect`       — suppress all on next line, error if NO diagnostic appears

use std::collections::BTreeMap;

use rowan::TextRange;

use crate::{Diagnostic, DiagnosticCode, FileId};

/// Parsed suppression/expectation directives for a single file.
#[derive(Debug, Clone, Default)]
pub struct Suppressions {
    /// `// brink-disable-all` found in this file.
    pub disable_all: bool,
    /// `// brink-disable-file` found in this file.
    pub disable_file: bool,
    /// Target line (0-based) → directive. Sorted by line.
    pub line_directives: BTreeMap<u32, LineDirective>,
}

/// A per-line suppression or expectation directive.
#[derive(Debug, Clone)]
pub struct LineDirective {
    /// Whether this is a `disable` or `expect` directive.
    pub kind: DirectiveKind,
    /// `None` = all codes; `Some(vec)` = specific codes.
    pub codes: Option<Vec<DiagnosticCode>>,
    /// Byte range of the directive comment (for "unmet expect" error location).
    pub range: TextRange,
}

/// The kind of a per-line directive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectiveKind {
    /// `// brink-disable` — suppress matched diagnostics silently.
    Disable,
    /// `// brink-expect` — suppress matched diagnostics, error if none match.
    Expect,
}

/// Parse suppression/expectation directives from source text.
#[must_use]
#[expect(
    clippy::cast_possible_truncation,
    reason = "source file line indices and byte offsets fit in u32 for any reasonable file"
)]
pub fn parse_suppressions(source: &str) -> Suppressions {
    let mut result = Suppressions::default();
    let mut byte_offset: u32 = 0;

    for (line_idx, line) in source.lines().enumerate() {
        let line_byte_start = byte_offset;
        // Advance byte_offset past this line + its newline
        byte_offset += line.len() as u32;
        // Account for the newline character(s)
        let rest = &source[byte_offset as usize..];
        if rest.starts_with("\r\n") {
            byte_offset += 2;
        } else if rest.starts_with('\n') || rest.starts_with('\r') {
            byte_offset += 1;
        }

        // Find `//` comment start
        let Some(comment_pos) = line.find("//") else {
            continue;
        };
        let comment = line[comment_pos + 2..].trim();

        if comment == "brink-disable-all" {
            result.disable_all = true;
        } else if comment == "brink-disable-file" {
            result.disable_file = true;
        } else if comment == "brink-disable" || comment == "brink-expect" {
            let kind = if comment == "brink-expect" {
                DirectiveKind::Expect
            } else {
                DirectiveKind::Disable
            };
            let target_line = (line_idx + 1) as u32;
            let comment_byte_start = line_byte_start + comment_pos as u32;
            let comment_byte_end = line_byte_start + line.len() as u32;
            result.line_directives.insert(
                target_line,
                LineDirective {
                    kind,
                    codes: None,
                    range: TextRange::new(comment_byte_start.into(), comment_byte_end.into()),
                },
            );
        } else if let Some(codes_str) = comment
            .strip_prefix("brink-disable ")
            .or_else(|| comment.strip_prefix("brink-expect "))
        {
            let kind = if comment.starts_with("brink-expect") {
                DirectiveKind::Expect
            } else {
                DirectiveKind::Disable
            };
            let codes: Vec<DiagnosticCode> = codes_str
                .split_whitespace()
                .filter_map(DiagnosticCode::from_str_code)
                .collect();
            if !codes.is_empty() {
                let target_line = (line_idx + 1) as u32;
                let comment_byte_start = line_byte_start + comment_pos as u32;
                let comment_byte_end = line_byte_start + line.len() as u32;
                result.line_directives.insert(
                    target_line,
                    LineDirective {
                        kind,
                        codes: Some(codes),
                        range: TextRange::new(comment_byte_start.into(), comment_byte_end.into()),
                    },
                );
            }
        }
    }

    result
}

/// Apply suppressions to diagnostics for a single file.
///
/// - Removes diagnostics matched by `disable` directives
/// - Removes diagnostics matched by `expect` directives
/// - Emits E036 for `expect` directives with no matching diagnostic
///
/// Returns the filtered+augmented diagnostic list.
#[expect(
    clippy::cast_possible_truncation,
    reason = "source file byte offsets and line counts fit in u32 for any reasonable file"
)]
pub fn apply_suppressions(
    file_id: FileId,
    source: &str,
    diagnostics: Vec<Diagnostic>,
    suppressions: &Suppressions,
) -> Vec<Diagnostic> {
    if suppressions.disable_file {
        return Vec::new();
    }

    // Build line starts table for mapping byte offsets → line numbers
    let line_starts: Vec<u32> = std::iter::once(0)
        .chain(source.bytes().enumerate().filter_map(|(i, b)| {
            if b == b'\n' {
                Some((i + 1) as u32)
            } else {
                None
            }
        }))
        .collect();

    // Track which expect directives were satisfied
    let mut expect_satisfied: BTreeMap<u32, bool> = BTreeMap::new();
    for (&target_line, directive) in &suppressions.line_directives {
        if directive.kind == DirectiveKind::Expect {
            expect_satisfied.insert(target_line, false);
        }
    }

    let mut result = Vec::with_capacity(diagnostics.len());

    for diag in diagnostics {
        let byte_offset: u32 = diag.range.start().into();
        let line = line_starts
            .partition_point(|&start| start <= byte_offset)
            .saturating_sub(1) as u32;

        if let Some(directive) = suppressions.line_directives.get(&line) {
            let matches = match &directive.codes {
                None => true,
                Some(codes) => codes.contains(&diag.code),
            };
            if matches {
                if directive.kind == DirectiveKind::Expect {
                    expect_satisfied.insert(line, true);
                }
                continue; // suppress this diagnostic
            }
        }

        result.push(diag);
    }

    // Emit E036 for unsatisfied expect directives
    for (&target_line, satisfied) in &expect_satisfied {
        if !satisfied && let Some(directive) = suppressions.line_directives.get(&target_line) {
            let message = match &directive.codes {
                None => "expected a diagnostic on the next line, but none was produced".to_string(),
                Some(codes) => {
                    let code_strs: Vec<&str> = codes.iter().map(|c| c.as_str()).collect();
                    format!(
                        "expected diagnostic {} on the next line, but it was not produced",
                        code_strs.join(", ")
                    )
                }
            };
            result.push(Diagnostic {
                file: file_id,
                range: directive.range,
                message,
                code: DiagnosticCode::E036,
            });
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_disable_all() {
        let src = "// brink-disable-all\nHello\n";
        let sup = parse_suppressions(src);
        assert!(sup.disable_all);
        assert!(!sup.disable_file);
        assert!(sup.line_directives.is_empty());
    }

    #[test]
    fn parse_disable_file() {
        let src = "// brink-disable-file\nHello\n";
        let sup = parse_suppressions(src);
        assert!(!sup.disable_all);
        assert!(sup.disable_file);
    }

    #[test]
    fn parse_blanket_disable_next_line() {
        let src = "// brink-disable\nHello\n";
        let sup = parse_suppressions(src);
        assert_eq!(sup.line_directives.len(), 1);
        let dir = sup.line_directives.get(&1);
        assert!(dir.is_some());
        let dir = dir.unwrap();
        assert_eq!(dir.kind, DirectiveKind::Disable);
        assert!(dir.codes.is_none());
    }

    #[test]
    fn parse_specific_disable() {
        let src = "// brink-disable E027 E028\nHello\n";
        let sup = parse_suppressions(src);
        let dir = sup.line_directives.get(&1).unwrap();
        assert_eq!(dir.kind, DirectiveKind::Disable);
        let codes = dir.codes.as_ref().unwrap();
        assert_eq!(codes, &[DiagnosticCode::E027, DiagnosticCode::E028]);
    }

    #[test]
    fn parse_expect_blanket() {
        let src = "// brink-expect\nHello\n";
        let sup = parse_suppressions(src);
        let dir = sup.line_directives.get(&1).unwrap();
        assert_eq!(dir.kind, DirectiveKind::Expect);
        assert!(dir.codes.is_none());
    }

    #[test]
    fn parse_expect_specific() {
        let src = "// brink-expect E025\nHello\n";
        let sup = parse_suppressions(src);
        let dir = sup.line_directives.get(&1).unwrap();
        assert_eq!(dir.kind, DirectiveKind::Expect);
        let codes = dir.codes.as_ref().unwrap();
        assert_eq!(codes, &[DiagnosticCode::E025]);
    }

    #[test]
    fn parse_ignores_invalid_codes() {
        let src = "// brink-disable XXXX E027\nHello\n";
        let sup = parse_suppressions(src);
        let dir = sup.line_directives.get(&1).unwrap();
        let codes = dir.codes.as_ref().unwrap();
        assert_eq!(codes, &[DiagnosticCode::E027]);
    }

    #[test]
    fn parse_all_invalid_codes_produces_no_directive() {
        let src = "// brink-disable XXXX YYYY\nHello\n";
        let sup = parse_suppressions(src);
        assert!(sup.line_directives.is_empty());
    }

    #[test]
    fn apply_disable_file_removes_all() {
        let file_id = FileId(0);
        let source = "// brink-disable-file\nHello\n";
        let sup = Suppressions {
            disable_file: true,
            ..Suppressions::default()
        };
        let diags = vec![Diagnostic {
            file: file_id,
            range: TextRange::new(22.into(), 27.into()),
            message: "test".to_string(),
            code: DiagnosticCode::E025,
        }];
        let result = apply_suppressions(file_id, source, diags, &sup);
        assert!(result.is_empty());
    }

    #[test]
    fn apply_blanket_disable_suppresses() {
        let file_id = FileId(0);
        let source = "// brink-disable\nHello\n";
        let sup = parse_suppressions(source);
        let diags = vec![Diagnostic {
            file: file_id,
            range: TextRange::new(17.into(), 22.into()), // "Hello" on line 1
            message: "test".to_string(),
            code: DiagnosticCode::E025,
        }];
        let result = apply_suppressions(file_id, source, diags, &sup);
        assert!(result.is_empty());
    }

    #[test]
    fn apply_specific_disable_only_matches_code() {
        let file_id = FileId(0);
        let source = "// brink-disable E027\nHello\n";
        let sup = parse_suppressions(source);
        let diags = vec![
            Diagnostic {
                file: file_id,
                range: TextRange::new(22.into(), 27.into()),
                message: "ambiguous".to_string(),
                code: DiagnosticCode::E027,
            },
            Diagnostic {
                file: file_id,
                range: TextRange::new(22.into(), 27.into()),
                message: "unresolved".to_string(),
                code: DiagnosticCode::E025,
            },
        ];
        let result = apply_suppressions(file_id, source, diags, &sup);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].code, DiagnosticCode::E025);
    }

    #[test]
    fn apply_expect_satisfied() {
        let file_id = FileId(0);
        let source = "// brink-expect E025\nHello\n";
        let sup = parse_suppressions(source);
        let diags = vec![Diagnostic {
            file: file_id,
            range: TextRange::new(21.into(), 26.into()),
            message: "unresolved".to_string(),
            code: DiagnosticCode::E025,
        }];
        let result = apply_suppressions(file_id, source, diags, &sup);
        assert!(result.is_empty()); // suppressed and expectation met
    }

    #[test]
    fn apply_expect_unsatisfied_emits_e036() {
        let file_id = FileId(0);
        let source = "// brink-expect E025\nHello\n";
        let sup = parse_suppressions(source);
        let diags = vec![]; // no diagnostics on next line
        let result = apply_suppressions(file_id, source, diags, &sup);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].code, DiagnosticCode::E036);
        assert!(result[0].message.contains("E025"));
    }

    #[test]
    fn apply_blanket_expect_unsatisfied() {
        let file_id = FileId(0);
        let source = "// brink-expect\nHello\n";
        let sup = parse_suppressions(source);
        let diags = vec![];
        let result = apply_suppressions(file_id, source, diags, &sup);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].code, DiagnosticCode::E036);
        assert!(result[0].message.contains("expected a diagnostic"));
    }

    #[test]
    fn diagnostic_on_wrong_line_not_suppressed() {
        let file_id = FileId(0);
        let source = "// brink-disable\nOk line\nBad line\n";
        let sup = parse_suppressions(source);
        // Diagnostic on line 2 ("Bad line"), not line 1
        let diags = vec![Diagnostic {
            file: file_id,
            range: TextRange::new(25.into(), 33.into()),
            message: "test".to_string(),
            code: DiagnosticCode::E025,
        }];
        let result = apply_suppressions(file_id, source, diags, &sup);
        assert_eq!(result.len(), 1);
    }
}