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
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
pub mod formatting;
pub mod naming;
pub mod ordering;
pub mod quality;
pub mod syntax;

use crate::ast::ScriptFile;
use crate::config::Config;
use crate::diagnostic::Diagnostic;
use crate::token::Token;

/// Run all enabled lint rules on a parsed script file.
///
/// Diagnostics come back with each rule's own default severity; the
/// `[rules]` severity overrides are applied by [`crate::linter::lint_source`],
/// which is the entry point most callers want.
pub fn run_all_rules(file: &ScriptFile, tokens: &[Token], config: &Config) -> Vec<Diagnostic> {
    run_all_rules_with_source(file, tokens, config, None)
}

/// Run all enabled lint rules, optionally with source for token-gap analysis.
///
/// Like [`run_all_rules`], this does not apply the config's severity
/// overrides. See [`crate::linter::lint_source`].
pub fn run_all_rules_with_source(
    file: &ScriptFile,
    tokens: &[Token],
    config: &Config,
    source: Option<&str>,
) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();

    // Syntax rules. `syntax/lex-error` is surfaced by `lint_source`, which
    // owns the lexer output.
    if config.is_rule_enabled("syntax/reserved-identifier") {
        syntax::check_reserved_identifier(tokens, file, &mut diagnostics);
    }

    // Naming rules.
    if config.is_rule_enabled("naming/class-name-pascal-case") {
        naming::check_class_name_pascal_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/function-name-snake-case") {
        naming::check_function_name_snake_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/variable-name-snake-case") {
        naming::check_variable_name_snake_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/constant-name-screaming-case") {
        naming::check_constant_name_screaming_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/signal-name-snake-case") {
        naming::check_signal_name_snake_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/enum-name-pascal-case") {
        naming::check_enum_name_pascal_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/enum-member-screaming-case") {
        naming::check_enum_member_screaming_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/file-name-snake-case") {
        naming::check_file_name_snake_case(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/signal-past-tense") {
        naming::check_signal_past_tense(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/private-underscore-prefix") {
        naming::check_private_underscore_prefix(file, &mut diagnostics);
    }
    if config.is_rule_enabled("naming/node-name-pascal-case") {
        naming::check_node_name_pascal_case(tokens, file, &mut diagnostics);
    }

    // Formatting rules.
    if config.is_rule_enabled("format/max-line-length") {
        formatting::check_max_line_length(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("format/trailing-whitespace") {
        formatting::check_trailing_whitespace(file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/trailing-newline") {
        formatting::check_trailing_newline(file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/no-tabs-as-spaces") {
        formatting::check_indentation_style(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("format/boolean-operators") {
        formatting::check_boolean_operators(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/double-quotes") {
        formatting::check_double_quotes(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/comment-spacing") {
        formatting::check_comment_spacing(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/no-unnecessary-parens") {
        formatting::check_unnecessary_parens(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/number-literals") {
        formatting::check_number_literals(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/one-statement-per-line") {
        formatting::check_one_statement_per_line(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/blank-lines") {
        formatting::check_blank_lines(file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/trailing-comma") {
        formatting::check_trailing_comma(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/operator-spacing") {
        if let Some(src) = source {
            formatting::check_operator_spacing(tokens, file, src, &mut diagnostics);
        }
    }
    if config.is_rule_enabled("format/colon-spacing") {
        if let Some(src) = source {
            formatting::check_colon_spacing(tokens, file, src, &mut diagnostics);
        }
    }
    if config.is_rule_enabled("format/comma-spacing") {
        if let Some(src) = source {
            formatting::check_comma_spacing(tokens, file, src, &mut diagnostics);
        }
    }
    if config.is_rule_enabled("format/brace-spacing") {
        if let Some(src) = source {
            formatting::check_brace_spacing(tokens, file, src, &mut diagnostics);
        }
    }
    if config.is_rule_enabled("format/call-paren-spacing") {
        if let Some(src) = source {
            formatting::check_call_paren_spacing(tokens, file, src, &mut diagnostics);
        }
    }
    if config.is_rule_enabled("format/float-literal-zeros") {
        formatting::check_float_literal_zeros(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("format/large-number-underscores") {
        formatting::check_large_number_underscores(tokens, file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("format/enum-one-per-line") {
        formatting::check_enum_one_per_line(file, source, &mut diagnostics);
    }

    // Ordering rules.
    if config.is_rule_enabled("order/class-member-order") {
        ordering::check_class_member_order(file, &mut diagnostics);
    }

    // Quality rules.
    if config.is_rule_enabled("quality/max-function-length") {
        quality::check_max_function_length(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-file-length") {
        quality::check_max_file_length(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-parameters") {
        quality::check_max_parameters(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/unnecessary-pass") {
        quality::check_unnecessary_pass_in_functions(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/no-debug-print") {
        quality::check_no_debug_print(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/self-comparison") {
        quality::check_self_comparison(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/no-self-assign") {
        quality::check_no_self_assign(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/duplicate-dict-key") {
        quality::check_duplicate_dict_key(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/duplicated-load") {
        quality::check_duplicated_load(tokens, file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/type-hint") {
        quality::check_type_hint(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/empty-function") {
        quality::check_empty_function(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-class-variables") {
        quality::check_max_class_variables(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-public-methods") {
        quality::check_max_public_methods(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-inner-classes") {
        quality::check_max_inner_classes(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/no-else-return") {
        quality::check_no_else_return(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/unreachable-code") {
        quality::check_unreachable_code(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/await-in-loop") {
        quality::check_await_in_loop(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/allocation-in-loop") {
        quality::check_allocation_in_loop(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/process-get-node") {
        quality::check_process_get_node(file, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-nesting-depth") {
        quality::check_max_nesting_depth(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-returns") {
        quality::check_max_returns(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-branches") {
        quality::check_max_branches(file, config, &mut diagnostics);
    }
    if config.is_rule_enabled("quality/max-local-variables") {
        quality::check_max_local_variables(file, config, &mut diagnostics);
    }

    // Sort diagnostics by line number.
    diagnostics.sort_by_key(|d| (d.span.line, d.span.column));
    diagnostics
}

/// Returns a list of all available rule names.
/// Every lint rule, paired with a one-line human description. This is the
/// single source of truth, `all_rule_names()` and the CLI `rules`
/// subcommand both derive from it, so the two can never drift apart.
pub fn all_rules() -> &'static [(&'static str, &'static str)] {
    &[
        (
            "syntax/lex-error",
            "Report lexer errors (unterminated strings, invalid numbers, bad characters)",
        ),
        (
            "syntax/reserved-identifier",
            "Reserved words (namespace, trait, yield, ...) can't be used as names",
        ),
        (
            "naming/class-name-pascal-case",
            "Class names must use PascalCase",
        ),
        (
            "naming/function-name-snake-case",
            "Function names must use snake_case",
        ),
        (
            "naming/variable-name-snake-case",
            "Variable names must use snake_case",
        ),
        (
            "naming/constant-name-screaming-case",
            "Constants must use SCREAMING_SNAKE_CASE (or PascalCase for preloads)",
        ),
        (
            "naming/signal-name-snake-case",
            "Signal names must use snake_case",
        ),
        (
            "naming/enum-name-pascal-case",
            "Enum names must use PascalCase",
        ),
        (
            "naming/enum-member-screaming-case",
            "Enum members must use SCREAMING_SNAKE_CASE",
        ),
        (
            "naming/file-name-snake-case",
            "File names must use snake_case",
        ),
        (
            "naming/signal-past-tense",
            "Signal names should use past tense",
        ),
        (
            "naming/private-underscore-prefix",
            "Private members with _ should not have @export",
        ),
        (
            "naming/node-name-pascal-case",
            "$NodePath references should use PascalCase",
        ),
        (
            "format/max-line-length",
            "Lines must not exceed max length (default: 100)",
        ),
        ("format/trailing-whitespace", "No trailing whitespace"),
        ("format/trailing-newline", "Files must end with a newline"),
        (
            "format/no-tabs-as-spaces",
            "Use consistent indentation (tabs by default)",
        ),
        (
            "format/boolean-operators",
            "Use 'and'/'or'/'not' instead of '&&'/'||'/'!'",
        ),
        ("format/double-quotes", "Prefer double quotes for strings"),
        (
            "format/comment-spacing",
            "Comments must have a space after #",
        ),
        (
            "format/no-unnecessary-parens",
            "No unnecessary parentheses in if/while conditions",
        ),
        (
            "format/number-literals",
            "Number literals must follow formatting rules",
        ),
        (
            "format/one-statement-per-line",
            "One statement per line (no semicolons)",
        ),
        (
            "format/blank-lines",
            "Collapse 3+ blank lines to 2 between top-level members",
        ),
        (
            "format/trailing-comma",
            "Trailing comma on last item of multi-line collections whose closing bracket starts its own line",
        ),
        (
            "format/operator-spacing",
            "One space around binary operators",
        ),
        (
            "format/colon-spacing",
            "No space before ':' and one space after (except `:=` and end of line)",
        ),
        (
            "format/comma-spacing",
            "No space before ',' and one space after (except newline / closing bracket)",
        ),
        (
            "format/brace-spacing",
            "Single-line dictionary literals need a space after '{' and before '}'",
        ),
        (
            "format/call-paren-spacing",
            "No space between a callee and its opening '('",
        ),
        (
            "format/float-literal-zeros",
            "Float literals need leading/trailing zeros",
        ),
        (
            "format/large-number-underscores",
            "Large numbers (integer part >= large_number_threshold, default 10_000) should use underscores",
        ),
        (
            "format/enum-one-per-line",
            "Each enum member on its own line",
        ),
        (
            "order/class-member-order",
            "Class members must follow canonical ordering",
        ),
        (
            "quality/max-function-length",
            "Functions must not exceed max length (default: 50 lines)",
        ),
        (
            "quality/max-file-length",
            "Files must not exceed max length (default: 1000 lines)",
        ),
        (
            "quality/max-parameters",
            "Functions must not have too many parameters (default: 5)",
        ),
        (
            "quality/unnecessary-pass",
            "'pass' alongside other statements is redundant",
        ),
        (
            "quality/no-debug-print",
            "Flag leftover print()/print_debug() calls (advisory, opt-in)",
        ),
        (
            "quality/self-comparison",
            "Flag comparisons of a value with itself",
        ),
        (
            "quality/no-self-assign",
            "Flag assignments of a variable to itself",
        ),
        (
            "quality/duplicate-dict-key",
            "Flag duplicate keys in dictionary literals",
        ),
        (
            "quality/duplicated-load",
            "Flag the same path passed to load()/preload() twice",
        ),
        (
            "quality/type-hint",
            "Declarations should have explicit type hints (advisory, opt-in)",
        ),
        (
            "quality/empty-function",
            "Flag functions whose body is only 'pass' (advisory, opt-in)",
        ),
        (
            "quality/max-class-variables",
            "Classes must not have too many member variables",
        ),
        (
            "quality/max-public-methods",
            "Classes must not have too many public methods",
        ),
        (
            "quality/max-inner-classes",
            "Files must not have too many inner classes",
        ),
        (
            "quality/no-else-return",
            "Drop the 'else' when the 'if' branch returns",
        ),
        (
            "quality/unreachable-code",
            "Flag code after return/break/continue",
        ),
        (
            "quality/await-in-loop",
            "Flag 'await' inside a for/while loop",
        ),
        (
            "quality/allocation-in-loop",
            "Flag .new() allocations inside loops",
        ),
        (
            "quality/process-get-node",
            "Flag $/get_node() lookups inside _process/_physics_process",
        ),
        (
            "quality/max-nesting-depth",
            "Functions must not nest blocks too deeply",
        ),
        (
            "quality/max-returns",
            "Functions must not have too many return statements",
        ),
        (
            "quality/max-branches",
            "Functions must not have too many branches",
        ),
        (
            "quality/max-local-variables",
            "Functions must not have too many local variables",
        ),
    ]
}

pub fn all_rule_names() -> Vec<&'static str> {
    all_rules().iter().map(|(name, _)| *name).collect()
}

/// The `[rules]` keys in `config` that match no rule in the registry,
/// sorted for stable output.
///
/// A misspelled rule name parses as valid TOML and is then silently
/// ignored, so the config looks like it took effect when it did not.
/// Callers surface this to the user; the registry is what decides.
///
/// # Example
///
/// ```
/// use gdstyle::config::{Config, RuleSeverityConfig};
/// use gdstyle::rules;
///
/// let mut config = Config::default();
/// config.rules.insert("naming/variable-snake-case".to_string(), RuleSeverityConfig::Error);
/// assert_eq!(rules::unknown_rule_names(&config), vec!["naming/variable-snake-case"]);
/// ```
pub fn unknown_rule_names(config: &Config) -> Vec<&str> {
    let known = all_rule_names();
    let mut unknown: Vec<&str> = config
        .rules
        .keys()
        .map(String::as_str)
        .filter(|name| !known.contains(name))
        .collect();
    unknown.sort_unstable();
    unknown
}

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

    #[test]
    fn unknown_rule_names_flags_only_misspellings() {
        let mut config = Config::default();
        // A real rule, a near-miss typo, and something entirely made up.
        for name in [
            "naming/variable-name-snake-case",
            "naming/variable-snake-case",
            "format/tabs",
        ] {
            config
                .rules
                .insert(name.to_string(), RuleSeverityConfig::Error);
        }
        assert_eq!(
            unknown_rule_names(&config),
            vec!["format/tabs", "naming/variable-snake-case"]
        );
    }

    #[test]
    fn every_registry_name_is_accepted() {
        // Guards against the registry and the validator drifting apart:
        // a config naming every rule must report nothing unknown.
        let mut config = Config::default();
        for name in all_rule_names() {
            config
                .rules
                .insert(name.to_string(), RuleSeverityConfig::Warn);
        }
        assert!(unknown_rule_names(&config).is_empty());
    }

    #[test]
    fn default_config_has_no_unknown_rules() {
        assert!(unknown_rule_names(&Config::default()).is_empty());
    }
}