gdstyle 0.3.2

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
use crate::ast::ScriptFile;
use crate::diagnostic::Diagnostic;
use crate::token::{Token, TokenKind};

/// Words Godot's tokenizer turns into keyword or literal tokens, which its
/// parser then refuses wherever it expects a name.
///
/// Mirrors the keyword table in Godot 4's `gdscript_tokenizer.cpp`, minus the
/// entries `Token::is_identifier()` lets through: `match` (for
/// `String.match()`), `when` (added in 4.3 without breaking old code), and the
/// `PI`/`TAU`/`INF`/`NAN` constants. Checked against Godot 4.6.2 in every
/// declaration position this rule inspects. `namespace` and `yield` are
/// reserved without any grammar using them, so the gdstyle lexer tokenises
/// them as plain identifiers; matching on text rather than token kind covers
/// both groups the same way.
const RESERVED_WORDS: &[&str] = &[
    "and",
    "as",
    "assert",
    "await",
    "break",
    "breakpoint",
    "class",
    "class_name",
    "const",
    "continue",
    "elif",
    "else",
    "enum",
    "extends",
    "false",
    "for",
    "func",
    "if",
    "in",
    "is",
    "namespace",
    "not",
    "null",
    "or",
    "pass",
    "preload",
    "return",
    "self",
    "signal",
    "static",
    "super",
    "trait",
    "true",
    "var",
    "void",
    "while",
    "yield",
];

/// True when Godot rejects `word` as a declared name.
///
/// # Example
///
/// ```
/// use gdstyle::rules::syntax::is_reserved_word;
///
/// assert!(is_reserved_word("namespace"));
/// assert!(!is_reserved_word("match")); // Godot allows it as a name.
/// ```
pub fn is_reserved_word(word: &str) -> bool {
    RESERVED_WORDS.contains(&word)
}

/// Flag reserved words used where GDScript expects a declared name:
/// function, variable, constant, signal, enum, enum member, class and loop
/// variable names, plus function, lambda, signal and property-setter
/// parameters.
///
/// Godot fails to parse such a file (`Expected parameter name.` and
/// friends), so this reports at error severity. There is no autofix: the
/// replacement name, and every use of it, is the author's call.
///
/// Works on tokens, not the AST, because the parser skips over declarations
/// whose name is a keyword and so never produces a member to inspect.
///
/// # Example
///
/// ```
/// use gdstyle::{config::Config, linter};
///
/// let source = "func f(namespace: String) -> void:\n\tpass\n";
/// let diagnostics = linter::lint_source(source, "demo.gd", &Config::default());
/// assert!(diagnostics.iter().any(|d| d.rule == "syntax/reserved-identifier"));
/// ```
pub fn check_reserved_identifier(
    tokens: &[Token],
    file: &ScriptFile,
    diagnostics: &mut Vec<Diagnostic>,
) {
    // Layout tokens never separate a keyword from the name it declares, and
    // comments can sit inside a multi-line parameter list.
    let significant: Vec<&Token> = tokens
        .iter()
        .filter(|t| {
            !matches!(
                t.kind,
                TokenKind::Newline
                    | TokenKind::Indent
                    | TokenKind::Dedent
                    | TokenKind::Comment(_)
                    | TokenKind::DocComment(_)
            )
        })
        .collect();

    let mut report = |token: &Token, role: &str| {
        if is_reserved_word(&token.text) {
            diagnostics.push(Diagnostic::error(
                "syntax/reserved-identifier",
                format!(
                    "'{}' is a reserved word in GDScript and cannot be used as {} name",
                    token.text,
                    with_article(role)
                ),
                token.span,
                &file.path,
            ));
        }
    };

    for (index, token) in significant.iter().enumerate() {
        // `obj.signal` is a member access and `$UI/class` or `%signal` a node
        // path, not declarations.
        if index > 0
            && matches!(
                significant[index - 1].kind,
                TokenKind::Dot | TokenKind::Dollar | TokenKind::UniqueNodeMarker | TokenKind::Slash
            )
        {
            continue;
        }
        let Some(next) = significant.get(index + 1) else {
            break;
        };
        // A declaration keyword and its name always share a line. Without
        // this, a keyword that slipped past the checks above would pair with
        // the first word of the next line (`if`, `return`, `var`, ...).
        if next.span.line != token.span.line {
            continue;
        }
        match token.kind {
            TokenKind::Func => {
                if next.kind == TokenKind::LeftParen {
                    // Lambda: no name, straight into the parameter list.
                    report_list_entries(&significant, index + 1, "parameter", &mut report);
                } else {
                    report(next, "function");
                    if significant.get(index + 2).map(|t| &t.kind) == Some(&TokenKind::LeftParen) {
                        report_list_entries(&significant, index + 2, "parameter", &mut report);
                    }
                }
            }
            TokenKind::Signal => {
                report(next, "signal");
                if significant.get(index + 2).map(|t| &t.kind) == Some(&TokenKind::LeftParen) {
                    report_list_entries(&significant, index + 2, "parameter", &mut report);
                }
            }
            TokenKind::Enum => {
                if next.kind == TokenKind::LeftBrace {
                    report_list_entries(&significant, index + 1, "enum member", &mut report);
                } else {
                    report(next, "enum");
                    if significant.get(index + 2).map(|t| &t.kind) == Some(&TokenKind::LeftBrace) {
                        report_list_entries(&significant, index + 2, "enum member", &mut report);
                    }
                }
            }
            TokenKind::Var => report(next, "variable"),
            TokenKind::Const => report(next, "constant"),
            TokenKind::Class | TokenKind::ClassName => report(next, "class"),
            TokenKind::For => report(next, "loop variable"),
            // Property setter, `set(value):`. Requiring the `:` after the
            // parameter list keeps calls such as `set("prop", null)` out.
            TokenKind::Identifier(ref name)
                if name == "set"
                    && next.kind == TokenKind::LeftParen
                    && closing_index(&significant, index + 1)
                        .and_then(|close| significant.get(close + 1))
                        .is_some_and(|t| t.kind == TokenKind::Colon) =>
            {
                report_list_entries(&significant, index + 1, "parameter", &mut report);
            }
            _ => {}
        }
    }
}

/// `"a enum"` reads wrong; pick the article from the role's first letter.
fn with_article(role: &str) -> String {
    let article = if role.starts_with(['a', 'e', 'i', 'o', 'u']) {
        "an"
    } else {
        "a"
    };
    format!("{} {}", article, role)
}

/// Index of the bracket closing the one opened at `open_index`, if any.
fn closing_index(significant: &[&Token], open_index: usize) -> Option<usize> {
    let mut depth = 0usize;
    for (index, token) in significant.iter().enumerate().skip(open_index) {
        match token.kind {
            TokenKind::LeftParen | TokenKind::LeftBracket | TokenKind::LeftBrace => depth += 1,
            TokenKind::RightParen | TokenKind::RightBracket | TokenKind::RightBrace => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return Some(index);
                }
            }
            _ => {}
        }
    }
    None
}

/// Report the first token of each entry in the bracketed list opening at
/// `open_index` (a parameter list or an enum body). Entries are separated by
/// commas at the list's own depth, so default values such as `f(a, b)` or
/// `[1, 2]` don't start new entries.
fn report_list_entries(
    significant: &[&Token],
    open_index: usize,
    role: &str,
    report: &mut impl FnMut(&Token, &str),
) {
    let mut depth = 0usize;
    let mut expects_name = false;
    for token in &significant[open_index..] {
        match token.kind {
            TokenKind::LeftParen | TokenKind::LeftBracket | TokenKind::LeftBrace => {
                depth += 1;
                expects_name = depth == 1;
                continue;
            }
            TokenKind::RightParen | TokenKind::RightBracket | TokenKind::RightBrace => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return;
                }
                continue;
            }
            TokenKind::Comma if depth == 1 => {
                expects_name = true;
                continue;
            }
            // Variadic parameter (`...args`): the name follows the ellipsis.
            TokenKind::Ellipsis if expects_name => continue,
            _ => {}
        }
        if expects_name {
            report(token, role);
            expects_name = false;
        }
    }
}

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

    fn reserved_diagnostics(source: &str) -> Vec<Diagnostic> {
        let tokens = crate::lexer::Lexer::new(source).tokenize();
        let file = ScriptFile {
            path: "test.gd".to_string(),
            members: vec![],
            lines: source.split('\n').map(str::to_string).collect(),
        };
        let mut diagnostics = Vec::new();
        check_reserved_identifier(&tokens, &file, &mut diagnostics);
        diagnostics
    }

    fn flagged_words(source: &str) -> Vec<String> {
        reserved_diagnostics(source)
            .iter()
            .map(|d| d.message.split('\'').nth(1).unwrap_or_default().to_string())
            .collect()
    }

    #[test]
    fn issue_32_parameter_and_function_name() {
        let source = "extends Node\n\n\nfunc _prose(namespace: String) -> Dictionary:\n\treturn { \"namespace\": namespace }\n\n\nfunc trait(id: String) -> float:\n\treturn 0.0\n";
        let diagnostics = reserved_diagnostics(source);
        assert_eq!(diagnostics.len(), 2, "got {:?}", diagnostics);
        assert_eq!(diagnostics[0].span.line, 4);
        assert!(diagnostics[0].message.contains("'namespace'"));
        assert!(diagnostics[0].message.contains("as a parameter name"));
        assert_eq!(diagnostics[1].span.line, 8);
        assert!(diagnostics[1].message.contains("'trait'"));
        assert!(diagnostics[1].message.contains("as a function name"));
        assert!(diagnostics
            .iter()
            .all(|d| d.severity == crate::diagnostic::Severity::Error));
    }

    #[test]
    fn every_declaration_position_is_checked() {
        let source = "\
class_name yield
extends Node
signal void
signal ok(namespace)
enum trait { A }
enum E { OK, self }
enum { in }
const super = 1
static var static = 2
var namespace := 3
class preload:
\tpass
func f(ok, yield = g(1, 2), ...await) -> void:
\tvar true := 1
\tfor is in []:
\t\tpass
\tvar h := func(null): return 1
";
        assert_eq!(
            flagged_words(source),
            vec![
                "yield",
                "void",
                "namespace",
                "trait",
                "self",
                "in",
                "super",
                "static",
                "namespace",
                "preload",
                "yield",
                "await",
                "true",
                "is",
                "null",
            ]
        );
    }

    #[test]
    fn multi_line_parameter_list_with_comments() {
        let source = "func f(\n\ta: int, # first\n\tnamespace: String,\n) -> void:\n\tpass\n";
        assert_eq!(flagged_words(source), vec!["namespace"]);
    }

    #[test]
    fn names_godot_accepts_are_not_flagged() {
        // `match`, `when` and the math constants are soft keywords in Godot 4;
        // reserved words are fine as dictionary keys, strings, member access
        // and default values.
        let source = "\
var match := 1
var when := 2
const PI = 3
func f(match, when, a = self, b = null) -> void:
\tvar d := { \"namespace\": 1, \"trait\": 2 }
\tvar x = obj.namespace
\tvar s := \"yield\"
\tfor i in range(3):
\t\tpass
";
        assert_eq!(flagged_words(source), Vec::<String>::new());
    }

    #[test]
    fn values_nested_in_defaults_are_not_entries() {
        // Reserved words inside a default value's brackets are expressions,
        // not parameter names; only depth-1 commas start a new entry.
        let source = "func f(a := [null, true], b = {\"k\": self}, c = g(1, false), d: Array[int] = [1, 2]) -> void:\n\tpass\n";
        assert_eq!(flagged_words(source), Vec::<String>::new());
    }

    #[test]
    fn keyword_member_access_is_not_a_declaration() {
        // Valid in Godot 4.6: `class` here is an attribute, and `in` must not
        // be read as the name of a class declaration.
        assert_eq!(
            flagged_words("func f(o) -> void:\n\tif o.class in [1]:\n\t\tpass\n"),
            Vec::<String>::new()
        );
    }

    #[test]
    fn node_paths_ending_in_keywords_are_not_declarations() {
        // All valid in Godot 4.6. The lexer splits `$UI/class` into `$`, `UI`,
        // `/`, `class`, so the keyword must not pair with what follows it,
        // on the same line or the next.
        let source = "\
@onready var light = $signal
var x = 1
func f() -> void:
\tvar n = $UI/class
\tif n:
\t\tpass
\tvar m = %for
\tpass
\tif $Menu/enum and %var is Node:
\t\treturn
";
        assert_eq!(flagged_words(source), Vec::<String>::new());
    }

    #[test]
    fn keyword_never_pairs_with_the_next_line() {
        // Even with no `$`/`/` before it, a keyword at the end of a line
        // (lexer confusion, broken code) must not claim the next line's word.
        let source = "var\nself.x = 1\n";
        assert_eq!(flagged_words(source), Vec::<String>::new());
    }

    #[test]
    fn setter_parameters_are_checked_but_set_calls_are_not() {
        let source = "\
var p: int:
\tset(namespace):
\t\tpass
var q: int:
\tget:
\t\treturn 1
\tset(value):
\t\tpass
func f() -> void:
\tset(\"p\", null)
\tobj.set(\"p\", self)
";
        let diagnostics = reserved_diagnostics(source);
        assert_eq!(diagnostics.len(), 1, "got {:?}", diagnostics);
        assert_eq!(diagnostics[0].span.line, 2);
        assert!(diagnostics[0].message.contains("'namespace'"));
    }

    #[test]
    fn roles_starting_with_a_vowel_take_an() {
        let messages: Vec<String> = reserved_diagnostics("enum trait { self }\n")
            .into_iter()
            .map(|d| d.message)
            .collect();
        assert_eq!(
            messages,
            vec![
                "'trait' is a reserved word in GDScript and cannot be used as an enum name",
                "'self' is a reserved word in GDScript and cannot be used as an enum member name",
            ]
        );
    }
}