gdstyle 0.4.0

A fast, opinionated linter and formatter for GDScript (Godot 4.x)
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
use crate::ast::ScriptFile;
use crate::config::Config;
use crate::diagnostic::Diagnostic;
use crate::lexer::Lexer;
use crate::parser::Parser;
use crate::rules;
use crate::token::TokenKind;

/// Lint a single GDScript source string and return diagnostics.
///
/// # Example
///
/// ```
/// use gdstyle::{config::Config, linter};
///
/// let diagnostics = linter::lint_source("func BadName():\n\tpass\n", "demo.gd", &Config::default());
/// assert!(diagnostics.iter().any(|d| d.rule == "naming/function-name-snake-case"));
/// ```
pub fn lint_source(source: &str, file_path: &str, config: &Config) -> Vec<Diagnostic> {
    // Normalize line endings up front. The rest of the pipeline mixes
    // `source.lines()` (strips `\r`) and `source.split('\n')` (keeps `\r`),
    // so on Windows-encoded files every byte offset disagrees by one per
    // line, autofix replacements then land mid-`\r\n` and trailing-
    // whitespace fixes leave the `\r` behind.
    let normalized = normalize_line_endings(source);
    let source = normalized.as_str();

    // Check for inline suppression comments.
    let suppressed_lines = parse_suppression_comments(source);

    // Tokenize.
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize();

    // Parse.
    let mut parser = Parser::new(&tokens);
    let members = parser.parse();

    // Build the script file representation.
    // Use split('\n') instead of lines() to preserve trailing newline detection.
    // split('\n') on "hello\n" gives ["hello", ""], where the final "" signals the
    // trailing newline. The trailing-newline rule checks if the last element is empty.
    let lines: Vec<String> = source.split('\n').map(|l| l.to_string()).collect();
    let file = ScriptFile {
        path: file_path.to_string(),
        members,
        lines,
    };

    // Run all rules.
    let mut diagnostics = rules::run_all_rules_with_source(&file, &tokens, config, Some(source));

    // Surface lexer errors (unterminated strings, invalid numbers, unexpected
    // characters). Without this, a syntactically broken file would be
    // reported as clean: the worst failure mode for a linter.
    if config.is_rule_enabled("syntax/lex-error") {
        for token in &tokens {
            if let crate::token::TokenKind::Error(ref message) = token.kind {
                diagnostics.push(Diagnostic::error(
                    "syntax/lex-error",
                    message.clone(),
                    token.span,
                    file_path,
                ));
            }
        }
    }

    // Filter out suppressed diagnostics.
    diagnostics.retain(|d| !is_suppressed(d, &suppressed_lines));

    // Apply per-rule severity overrides from the config. Rules build their
    // diagnostics with a fixed default severity; this is the single place
    // that knows what the user asked for. Every surface (CLI, GDExtension,
    // formatter) funnels through here, so one pass covers them all.
    for diagnostic in &mut diagnostics {
        if let Some(severity) = config.severity_for(&diagnostic.rule) {
            diagnostic.severity = severity;
        }
    }

    diagnostics
}

/// Convert every `\r\n` outside string literals to `\n`. We do this before
/// any byte-offset computation so the rest of the pipeline can assume
/// LF-only line breaks between tokens.
///
/// Two things are left alone. A string that spans lines keeps its bytes,
/// `\r\n` included: Godot keeps a `\r` inside a string as part of its value,
/// and leaving it in place means no pass has to put it back. A `\r` that
/// isn't followed by `\n` stays too: Godot doesn't treat it as a line break
/// (it is part of a string or comment, or a "stray carriage return" error in
/// code), so turning it into `\n` would split the line.
///
/// # Example
///
/// ```
/// use gdstyle::linter::normalize_line_endings;
///
/// let source = "var a = 1\r\nvar s = \"\"\"x\r\ny\"\"\"\r\n";
/// assert_eq!(normalize_line_endings(source), "var a = 1\nvar s = \"\"\"x\r\ny\"\"\"\n");
/// ```
pub fn normalize_line_endings(source: &str) -> String {
    if !source.contains("\r\n") {
        return source.to_string();
    }
    map_outside_spanning_strings(source, |code| code.replace("\r\n", "\n"))
}

/// Put `source`'s line-ending style back on `normalized`: the output of
/// [`normalize_line_endings`] for `source`, after any edits.
///
/// The style comes from `source`'s line breaks outside string literals:
/// CRLF when most of them are `\r\n`, LF otherwise. It is applied to the line
/// breaks outside strings. Strings that span lines were never normalized, so
/// they keep their own line endings whatever the file's style is.
///
/// # Example
///
/// ```
/// use gdstyle::linter::{normalize_line_endings, restore_line_endings};
///
/// // A CRLF file whose string holds an LF line break.
/// let source = "var a = 1  \r\nvar s = \"\"\"x\ny\"\"\"\r\n";
/// let edited = normalize_line_endings(source).replace("1  ", "1");
/// assert_eq!(restore_line_endings(source, &edited), "var a = 1\r\nvar s = \"\"\"x\ny\"\"\"\r\n");
/// ```
pub fn restore_line_endings(source: &str, normalized: &str) -> String {
    if !source.contains("\r\n") {
        return normalized.to_string();
    }
    let mut crlf_breaks = 0;
    let mut lf_breaks = 0;
    map_outside_spanning_strings(source, |code| {
        crlf_breaks += code.matches("\r\n").count();
        lf_breaks += code.matches('\n').count();
        String::new()
    });
    // `lf_breaks` counted every `\n`, the CRLF ones included.
    if crlf_breaks * 2 <= lf_breaks {
        return normalized.to_string();
    }
    map_outside_spanning_strings(normalized, |code| code.replace('\n', "\r\n"))
}

/// `source` with `map` applied to each stretch of text between the string
/// literals that span lines. The literals themselves are copied unchanged.
fn map_outside_spanning_strings(source: &str, mut map: impl FnMut(&str) -> String) -> String {
    let mut mapped = String::with_capacity(source.len() + source.len() / 16);
    let mut cursor = 0;
    for token in Lexer::new(source).tokenize() {
        if !matches!(token.kind, TokenKind::String(_)) || !token.text.contains('\n') {
            continue;
        }
        let start = token.span.offset;
        mapped.push_str(&map(&source[cursor..start]));
        mapped.push_str(&token.text);
        cursor = start + token.span.length;
    }
    mapped.push_str(&map(&source[cursor..]));
    mapped
}

/// Lint a file from disk.
pub fn lint_file(path: &std::path::Path, config: &Config) -> Result<Vec<Diagnostic>, String> {
    let source = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read {}: {}", path.display(), e))?;

    let file_path = path.to_string_lossy().to_string();
    Ok(lint_source(&source, &file_path, config))
}

/// Per-line and per-file suppression state. For each scope, `None` in
/// the rule list means "suppress all diagnostics in this scope"; `Some`
/// means "suppress only these rules".
#[derive(Default)]
pub(crate) struct Suppressions {
    /// Per-line: indexed by line number so `is_suppressed` is O(1).
    per_line: std::collections::HashMap<usize, Vec<Option<Vec<String>>>>,
    /// Per-file: all `# gdstyle:ignore-file` directives merged together,
    /// regardless of where they appear in the source.
    file_level: Vec<Option<Vec<String>>>,
}

impl Suppressions {
    /// Parse every suppression directive out of `source`.
    pub(crate) fn parse(source: &str) -> Self {
        parse_suppression_comments(source)
    }

    /// True when `rule` is suppressed for a member whose header spans lines
    /// `first..=last` (1-based, inclusive) — that is, a `# gdstyle:ignore-file`
    /// covering the rule, or a per-line `# gdstyle:ignore` that resolves onto
    /// any line of that header. Used both to pin a member against reordering
    /// and to exempt it from the `order/class-member-order` check, so `fmt` and
    /// `check` agree on which members opt out.
    pub(crate) fn suppresses_member(&self, first: usize, last: usize, rule: &str) -> bool {
        if self.file_level.iter().any(|r| matches_rule_list(r, rule)) {
            return true;
        }
        (first..=last).any(|line| {
            self.per_line
                .get(&line)
                .is_some_and(|lists| lists.iter().any(|r| matches_rule_list(r, rule)))
        })
    }
}

/// Parse suppression comments. Two forms are recognised:
///
/// 1. `# gdstyle:ignore[=rule1,rule2]` — per-line scope. On its own line
///    it suppresses the NEXT line; placed at the end of a code line it
///    suppresses the SAME line.
/// 2. `# gdstyle:ignore-file[=rule1,rule2]` — per-file scope. Suppresses
///    the listed rules (or all rules, when no `=...` is given) for every
///    diagnostic in the file, regardless of line. Anywhere in the file
///    works; convention is at the top so it's visible to readers.
fn parse_suppression_comments(source: &str) -> Suppressions {
    let mut suppressions = Suppressions::default();
    let file_prefix = "# gdstyle:ignore-file";
    let line_prefix = "# gdstyle:ignore";

    for (i, line) in source.lines().enumerate() {
        let line_num = i + 1;
        let trimmed = line.trim();

        // File-scope check must come BEFORE the per-line check because
        // `# gdstyle:ignore` is a prefix of `# gdstyle:ignore-file` and
        // would otherwise match first and steal the directive.
        if let Some(rest) = trimmed.strip_prefix(file_prefix) {
            if directive_terminator_ok(rest) {
                let rules = parse_suppression_rules(rest);
                suppressions.file_level.push(rules);
                continue;
            }
        }
        if let Some(pos) = line.find(file_prefix) {
            let rest = &line[pos + file_prefix.len()..];
            if directive_terminator_ok(rest) {
                let rules = parse_suppression_rules(rest);
                suppressions.file_level.push(rules);
                // An inline file-level directive on a code line behaves
                // identically to a standalone one; we don't ALSO record
                // a per-line suppression for that line.
                continue;
            }
        }

        // Standalone per-line suppression: applies to the NEXT line.
        if let Some(rest) = trimmed.strip_prefix(line_prefix) {
            if directive_terminator_ok(rest) {
                let rules = parse_suppression_rules(rest);
                suppressions
                    .per_line
                    .entry(line_num + 1)
                    .or_default()
                    .push(rules);
            }
        }

        // Inline per-line suppression: applies to the SAME line.
        if let Some(pos) = line.find(line_prefix) {
            let before = line[..pos].trim();
            if !before.is_empty() {
                let rest = &line[pos + line_prefix.len()..];
                if directive_terminator_ok(rest) {
                    let rules = parse_suppression_rules(rest);
                    suppressions
                        .per_line
                        .entry(line_num)
                        .or_default()
                        .push(rules);
                }
            }
        }
    }

    suppressions
}

/// After stripping the directive prefix, the remainder must either be
/// empty / pure whitespace / a comment continuation, or start with `=`.
/// Without this check `# gdstyle:ignore-foo` would also match the
/// `# gdstyle:ignore` prefix and be treated as a bare-suppression.
fn directive_terminator_ok(rest: &str) -> bool {
    match rest.chars().next() {
        None => true,
        Some(c) => c == '=' || c.is_whitespace(),
    }
}

fn parse_suppression_rules(rest: &str) -> Option<Vec<String>> {
    let rest = rest.trim();
    rest.strip_prefix('=').map(|rules_str| {
        rules_str
            .split(',')
            .map(|r| r.trim().to_string())
            .filter(|r| !r.is_empty())
            .collect()
    })
}

fn matches_rule_list(rules: &Option<Vec<String>>, rule: &str) -> bool {
    match rules {
        None => true, // bare directive suppresses everything
        Some(rs) => rs.iter().any(|r| r == rule),
    }
}

fn is_suppressed(diagnostic: &Diagnostic, suppressions: &Suppressions) -> bool {
    // File-level wins first: a `# gdstyle:ignore-file` at any line
    // covers diagnostics anywhere in the file. This is the right home
    // for class/file-scope limits like `quality/max-public-methods`,
    // which report against the class header itself and can't be
    // suppressed with a same-line comment without uglifying the
    // signature.
    if suppressions
        .file_level
        .iter()
        .any(|rules| matches_rule_list(rules, &diagnostic.rule))
    {
        return true;
    }
    let Some(line_suppressions) = suppressions.per_line.get(&diagnostic.span.line) else {
        return false;
    };
    line_suppressions
        .iter()
        .any(|rules| matches_rule_list(rules, &diagnostic.rule))
}

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

    #[test]
    fn lint_clean_source() {
        let source = r#"class_name Player
extends CharacterBody2D

signal health_changed(old_value: int, new_value: int)

const MAX_SPEED: float = 200.0

@export var speed: float = 100.0

var health: int = 100

@onready var label: Label = $Label

func _ready() -> void:
	pass

func take_damage(amount: int) -> void:
	pass
"#;
        let config = Config::default();
        let diagnostics = lint_source(source, "player.gd", &config);
        assert!(
            diagnostics.is_empty(),
            "clean source should produce no diagnostics, got: {:?}",
            diagnostics
        );
    }

    #[test]
    fn lint_detects_bad_class_name() {
        let source = "class_name my_player\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(diagnostics
            .iter()
            .any(|d| d.rule == "naming/class-name-pascal-case"));
    }

    #[test]
    fn lint_detects_bad_function_name() {
        let source = "func takeDamage() -> void:\n\tpass\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(diagnostics
            .iter()
            .any(|d| d.rule == "naming/function-name-snake-case"));
    }

    #[test]
    fn lint_surfaces_unterminated_string_as_error() {
        let source = "var x = \"oops\nvar y = 5\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        let lex_errors: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule == "syntax/lex-error")
            .collect();
        assert!(
            !lex_errors.is_empty(),
            "unterminated string must produce a syntax/lex-error diagnostic"
        );
        assert_eq!(lex_errors[0].severity, crate::diagnostic::Severity::Error);
    }

    #[test]
    fn lint_detects_trailing_whitespace() {
        let source = "var x = 5   \n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(diagnostics
            .iter()
            .any(|d| d.rule == "format/trailing-whitespace"));
    }

    #[test]
    fn lint_detects_long_line() {
        let long_line = format!("var x = \"{}\"", "a".repeat(110));
        let source = format!("{}\n", long_line);
        let config = Config::default();
        let diagnostics = lint_source(&source, "test.gd", &config);
        assert!(diagnostics
            .iter()
            .any(|d| d.rule == "format/max-line-length"));
    }

    #[test]
    fn inline_suppression_works() {
        let source = "class_name my_player  # gdstyle:ignore=naming/class-name-pascal-case\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.rule == "naming/class-name-pascal-case"),
            "suppressed rule should not appear"
        );
    }

    #[test]
    fn standalone_suppression_works() {
        let source = "# gdstyle:ignore=naming/class-name-pascal-case\nclass_name my_player\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.rule == "naming/class-name-pascal-case"),
            "suppressed rule should not appear"
        );
    }

    /// Build a 25-public-method class for the file-scope tests below.
    /// We rebuild it inline because every test needs to start from a
    /// known-clean source — sharing a `const` across tests would make
    /// failures harder to trace.
    fn bloated_class(prelude: &str) -> String {
        let mut s = String::from(prelude);
        s.push_str("class_name Bloated\nextends Node\n");
        for i in 0..25 {
            s.push_str(&format!("\nfunc method_{}() -> void:\n\tpass\n", i));
        }
        s
    }

    #[test]
    fn file_suppression_silences_class_level_rule() {
        // Regression for the user-reported gap: a `# gdstyle:ignore`
        // standalone above the class header doesn't catch
        // `quality/max-public-methods` because the diagnostic anchors
        // at line 1 and the standalone form suppresses the NEXT line.
        // The file-level directive sidesteps that mismatch entirely.
        let source = bloated_class("# gdstyle:ignore-file=quality/max-public-methods\n");
        let config = Config::default();
        let diagnostics = lint_source(&source, "test.gd", &config);
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.rule == "quality/max-public-methods"),
            "file-level suppression should silence max-public-methods, got: {:?}",
            diagnostics
        );
    }

    #[test]
    fn file_suppression_bare_form_silences_everything() {
        // `# gdstyle:ignore-file` (no `=...`) drops every diagnostic
        // in the file — for generated code or third-party drops.
        let source = "# gdstyle:ignore-file\nclass_name my_bad_name\nvar AlsoBad: int = 5\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(
            diagnostics.is_empty(),
            "bare ignore-file should drop everything, got: {:?}",
            diagnostics
        );
    }

    #[test]
    fn file_suppression_anywhere_in_file() {
        // The directive doesn't have to live on line 1 — anywhere in
        // the file works. This matters for files that already start
        // with a class-level `##` docstring before the suppression.
        let mut source = String::from("## Docstring for Bloated.\n");
        source.push_str(&bloated_class(""));
        source.push_str("\n# gdstyle:ignore-file=quality/max-public-methods\n");
        let config = Config::default();
        let diagnostics = lint_source(&source, "test.gd", &config);
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.rule == "quality/max-public-methods"),
            "file-level suppression must apply regardless of position, got: {:?}",
            diagnostics
        );
    }

    #[test]
    fn file_suppression_narrows_to_listed_rules() {
        // A scoped `# gdstyle:ignore-file=...` only silences the
        // listed rules — others still fire. The unlisted naming rule
        // on `BadName` must remain.
        let source = "# gdstyle:ignore-file=quality/max-public-methods\nclass_name Bloated\nextends Node\nvar BadName: int = 5\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(
            diagnostics
                .iter()
                .any(|d| d.rule == "naming/variable-name-snake-case"),
            "scoped ignore-file should NOT silence unlisted rules, got: {:?}",
            diagnostics
        );
    }

    #[test]
    fn file_suppression_does_not_swallow_per_line_directive() {
        // Regression guard: the `ignore-file` parsing path runs before
        // `ignore` and `continue`s when it matches. Make sure a
        // regular per-line `# gdstyle:ignore` directive still routes
        // through the per-line path.
        let source = "# gdstyle:ignore=naming/class-name-pascal-case\nclass_name my_player\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(
            !diagnostics
                .iter()
                .any(|d| d.rule == "naming/class-name-pascal-case"),
            "per-line directive still works alongside ignore-file support"
        );
    }

    #[test]
    fn suppress_all_rules_on_line() {
        let source = "# gdstyle:ignore\nclass_name my_player\n";
        let config = Config::default();
        let diagnostics = lint_source(source, "test.gd", &config);
        // All diagnostics on line 2 should be suppressed.
        let line_2_diags: Vec<_> = diagnostics.iter().filter(|d| d.span.line == 2).collect();
        assert!(line_2_diags.is_empty());
    }

    #[test]
    fn config_disables_rule() {
        let source = "class_name my_player\n";
        let mut config = Config::default();
        config.rules.insert(
            "naming/class-name-pascal-case".to_string(),
            crate::config::RuleSeverityConfig::Off,
        );
        let diagnostics = lint_source(source, "test.gd", &config);
        assert!(!diagnostics
            .iter()
            .any(|d| d.rule == "naming/class-name-pascal-case"));
    }

    #[test]
    fn config_escalates_rule_to_error() {
        // The reported bug: `"rule" = "error"` parsed fine but every
        // diagnostic still came out as a warning, so `check` exited 0.
        let source = "var BadName: int = 5\n\nfunc DoThing() -> void:\n\tpass\n";
        let mut config = Config::default();
        for rule in [
            "naming/variable-name-snake-case",
            "naming/function-name-snake-case",
        ] {
            config
                .rules
                .insert(rule.to_string(), crate::config::RuleSeverityConfig::Error);
        }

        let diagnostics = lint_source(source, "bad_test.gd", &config);
        let escalated: Vec<_> = diagnostics
            .iter()
            .filter(|d| d.rule.starts_with("naming/"))
            .collect();
        assert_eq!(escalated.len(), 2, "got: {:?}", diagnostics);
        assert!(
            escalated
                .iter()
                .all(|d| d.severity == crate::diagnostic::Severity::Error),
            "configured rules must report as errors, got: {:?}",
            escalated
        );
    }

    #[test]
    fn unconfigured_rule_keeps_default_warning_severity() {
        let source = "var BadName: int = 5\n";
        let diagnostics = lint_source(source, "test.gd", &Config::default());
        let diagnostic = diagnostics
            .iter()
            .find(|d| d.rule == "naming/variable-name-snake-case")
            .expect("naming diagnostic");
        assert_eq!(diagnostic.severity, crate::diagnostic::Severity::Warning);
    }

    #[test]
    fn config_downgrades_error_by_default_rule() {
        // `syntax/lex-error` is the one rule that defaults to Error. An
        // unmentioned rule must keep that default (guarded by
        // `lint_surfaces_unterminated_string_as_error`), but an explicit
        // `"warn"` must still be able to downgrade it.
        let source = "var x = \"oops\nvar y = 5\n";
        let mut config = Config::default();
        config.rules.insert(
            "syntax/lex-error".to_string(),
            crate::config::RuleSeverityConfig::Warn,
        );
        let diagnostics = lint_source(source, "test.gd", &config);
        let lex_error = diagnostics
            .iter()
            .find(|d| d.rule == "syntax/lex-error")
            .expect("lex error diagnostic");
        assert_eq!(lex_error.severity, crate::diagnostic::Severity::Warning);
    }

    #[test]
    fn lint_real_world_script() {
        let source = r#"@tool
class_name StateMachine
extends Node
## Hierarchical state machine for the player.
##
## Initializes states and delegates engine callbacks to the state.

signal state_changed(previous: String, current: String)

@export var initial_state: Node

var is_active: bool = true

@onready var _state: Node = $State

func _init() -> void:
	add_to_group("state_machine")

func _ready() -> void:
	state_changed.connect(_on_state_changed)

func _physics_process(delta: float) -> void:
	_state._physics_process(delta)

func transition_to(target_path: String) -> void:
	pass

func _on_state_changed(previous: String, current: String) -> void:
	pass
"#;
        let config = Config::default();
        let diagnostics = lint_source(source, "state_machine.gd", &config);
        assert!(
            diagnostics.is_empty(),
            "real-world clean script should have no issues, got: {:?}",
            diagnostics
        );
    }
}