gdsyntax 0.1.6

GDScript syntax trees and syntax errors, shared by the gdsuite tools
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
//! Which file of a Godot project uses which, as far as the source tells.
//!
//! The graph links every file of the project to the files it uses:
//!
//! - in a script: `extends`, `preload`/`load` and any other `"res://…"` or
//!   `"uid://…"` string, the `class_name` of another script used by name, and
//!   an autoload used by name;
//! - in a scene or text resource (`.tscn`, `.tres`): its `ext_resource`s.
//!
//! What the source cannot tell is recorded, not guessed. A script that loads
//! a computed path (`load(path)`) is one [`Graph::loads_unknown`] says may
//! load anything; one that loads from a known folder
//! (`load("res://items/" + id)`) uses every file of that folder. What to make
//! of it is the caller's: gdtest runs the tests that reach such a script on
//! any change, while a type check, which reads the source too, ignores it.
//!
//! ```no_run
//! let graph = gdsyntax::project::Graph::build(std::path::Path::new("my_game"));
//! // The scripts and scenes a change to the player can change the meaning of.
//! for file in graph.dependents_of(&["res://player.gd".to_string()]) {
//!     println!("{file}");
//! }
//! ```

use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::Path;

use crate::SyntaxKind;

/// Maps res:// path → set of res:// paths.
pub type DepGraph = HashMap<String, HashSet<String>>;

/// What one file uses, read from its source.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct FileDeps {
    /// `res://` paths, and `uid://` ids still to resolve.
    pub paths: BTreeSet<String>,
    /// Names that may be a `class_name` or an autoload.
    pub names: BTreeSet<String>,
    /// Folders it loads computed paths from: `res://items/`.
    pub folders: BTreeSet<String>,
    /// It loads a path the source does not tell.
    pub loads_unknown: bool,
    /// The `class_name` it declares.
    pub class_name: Option<String>,
    /// Each thing it uses, with how and on which line it first does: the
    /// same as the sets above, told apart.
    pub uses: Vec<Use>,
}

/// How a file uses another.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum UseKind {
    /// `extends "a.gd"` or `extends Actor`.
    Extends,
    /// `const A = preload("…")`: loaded with the script.
    ConstPreload,
    /// `preload("…")` anywhere else.
    Preload,
    /// `load("…")`, `ResourceLoader.load("…")`, `change_scene_to_file("…")`.
    Load,
    /// A load from a folder, `load("res://items/" + id)`: every file there.
    Folder,
    /// Any other `"res://…"` or `"uid://…"` string.
    Path,
    /// In [`FileDeps::uses`], a name that may be a `class_name` or an
    /// autoload; the graph tells which.
    Name,
    /// The `class_name` of another script, used by name.
    ClassName,
    /// An autoload, used by name.
    Autoload,
    /// An `ext_resource` of a scene or text resource.
    ExtResource,
}

impl UseKind {
    /// A kind that says only that a file is named, not how it is used.
    fn is_mention(self) -> bool {
        matches!(self, UseKind::Path | UseKind::Name)
    }
}

/// One thing a file uses, as its source writes it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Use {
    /// A `res://` path, a `uid://` id, a folder for [`UseKind::Folder`], or a
    /// name for [`UseKind::Name`] and [`UseKind::Extends`] by name.
    pub target: String,
    pub kind: UseKind,
    /// The 1-based line it is first used on.
    pub line: usize,
}

/// One file another uses, resolved: see [`Graph::uses`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Edge {
    /// The `res://` path of the file used.
    pub to: String,
    pub kind: UseKind,
    /// The 1-based line of the first such use.
    pub line: usize,
}

/// `uses` once per target and kind, at its first line, without a mention of
/// a target that is also used in a way that says how.
fn settle(uses: UseLines) -> Vec<Use> {
    let specific: HashSet<&String> = uses
        .keys()
        .filter(|(_, kind)| !kind.is_mention())
        .map(|(target, _)| target)
        .collect();
    let mut settled: Vec<Use> = uses
        .iter()
        .filter(|((target, kind), _)| !kind.is_mention() || !specific.contains(target))
        .map(|((target, kind), line)| Use {
            target: target.clone(),
            kind: *kind,
            line: *line,
        })
        .collect();
    settled.sort_by(|a, b| (a.line, a.kind, &a.target).cmp(&(b.line, b.kind, &b.target)));
    settled
}

/// (target, kind) → first line.
type UseLines = std::collections::BTreeMap<(String, UseKind), usize>;

fn record(uses: &mut UseLines, target: String, kind: UseKind, line: usize) {
    let first = uses.entry((target, kind)).or_insert(line);
    *first = (*first).min(line);
}

/// The project's dependency graph.
#[derive(Debug, Default, Clone)]
pub struct Graph {
    /// `forward[a]`: the files `a` uses.
    pub forward: DepGraph,
    /// `reverse[b]`: the files that use `b`.
    pub reverse: DepGraph,
    /// file → folders it loads computed paths from.
    folders: HashMap<String, BTreeSet<String>>,
    /// Files that load paths the source does not tell.
    unknown: HashSet<String>,
    /// The project's autoloads: name → res:// path.
    autoloads: HashMap<String, String>,
    /// file → what it uses, how and where: see [`Graph::uses`].
    edges: HashMap<String, Vec<Edge>>,
}

impl Graph {
    /// Reads the project's scripts, scenes and resources: every file under
    /// `project_abs`, but in folders whose name starts with a dot, folders
    /// with a `.gdignore`, and other projects nested in it.
    pub fn build(project_abs: &Path) -> Graph {
        let mut sources: HashMap<String, FileDeps> = HashMap::new();
        let mut uids: HashMap<String, String> = HashMap::new();
        let mut stack = vec![project_abs.to_path_buf()];
        while let Some(dir) = stack.pop() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let Ok(kind) = entry.file_type() else {
                    continue;
                };
                let path = entry.path();
                if kind.is_dir() {
                    // Godot leaves out a folder with a `.gdignore`, and one
                    // with its own `project.godot` is another project.
                    if !entry.file_name().to_string_lossy().starts_with('.')
                        && !path.join(".gdignore").exists()
                        && !path.join("project.godot").exists()
                    {
                        stack.push(path);
                    }
                    continue;
                }
                if !kind.is_file() {
                    continue;
                }
                let Ok(rel) = path.strip_prefix(project_abs) else {
                    continue;
                };
                let res = format!("res://{}", rel.to_string_lossy().replace('\\', "/"));
                read_file(&path, res, &mut sources, &mut uids);
            }
        }

        let mut graph = Graph {
            autoloads: read_autoloads(project_abs),
            ..Graph::default()
        };
        // Two scripts declaring one name is an error Godot reports; the
        // first path is taken, the same on every run.
        let mut classes: HashMap<&str, &str> = HashMap::new();
        for (file, deps) in &sources {
            if let Some(class) = deps.class_name.as_deref() {
                let taken = classes.entry(class).or_insert(file.as_str());
                if file.as_str() < *taken {
                    *taken = file.as_str();
                }
            }
        }

        for (file, deps) in &sources {
            let mut uses: HashSet<String> = HashSet::new();
            for path in &deps.paths {
                if let Some(target) = uids.get(path) {
                    uses.insert(target.clone());
                } else if path.starts_with("res://") {
                    uses.insert(path.clone());
                }
            }
            // A folder it loads from: it may load any file there.
            for folder in &deps.folders {
                uses.extend(sources.keys().filter(|f| in_folder(f, folder)).cloned());
            }
            for name in &deps.names {
                if let Some(target) = classes.get(name.as_str()) {
                    uses.insert((*target).to_string());
                }
                if let Some(target) = graph.autoloads.get(name) {
                    uses.insert(target.clone());
                }
            }
            graph.forward.entry(file.clone()).or_default();
            for used in &uses {
                graph.add_use(file, used);
            }
            let mut edges: UseLines = UseLines::new();
            for used in &deps.uses {
                let target = used.target.as_str();
                let path = uids
                    .get(target)
                    .cloned()
                    .or_else(|| target.starts_with("res://").then(|| target.to_string()));
                let resolved: Vec<(String, UseKind)> = match used.kind {
                    UseKind::Folder => sources
                        .keys()
                        .filter(|f| in_folder(f, target))
                        .map(|f| (f.clone(), UseKind::Folder))
                        .collect(),
                    UseKind::Name | UseKind::Extends if path.is_none() => {
                        let by_class = classes.get(target).map(|t| {
                            let kind = if used.kind == UseKind::Extends {
                                UseKind::Extends
                            } else {
                                UseKind::ClassName
                            };
                            ((*t).to_string(), kind)
                        });
                        let by_autoload = graph
                            .autoloads
                            .get(target)
                            .map(|t| (t.clone(), UseKind::Autoload));
                        by_class.into_iter().chain(by_autoload).collect()
                    }
                    _ => path.map(|p| (p, used.kind)).into_iter().collect(),
                };
                for (to, kind) in resolved {
                    if to != *file {
                        record(&mut edges, to, kind, used.line);
                    }
                }
            }
            let edges = settle(edges)
                .into_iter()
                .map(|u| Edge {
                    to: u.target,
                    kind: u.kind,
                    line: u.line,
                })
                .collect();
            graph.edges.insert(file.clone(), edges);
            if !deps.folders.is_empty() {
                graph.folders.insert(file.clone(), deps.folders.clone());
            }
            if deps.loads_unknown {
                graph.unknown.insert(file.clone());
            }
        }
        graph
    }

    /// Records that `file` uses `used`, as learned elsewhere than from the
    /// source: gdtest adds what each test was seen loading when it ran.
    pub fn add_use(&mut self, file: &str, used: &str) {
        if file == used {
            return;
        }
        self.reverse
            .entry(used.to_string())
            .or_default()
            .insert(file.to_string());
        self.forward
            .entry(file.to_string())
            .or_default()
            .insert(used.to_string());
    }

    /// The project's autoloads: name → res:// path.
    pub fn autoloads(&self) -> &HashMap<String, String> {
        &self.autoloads
    }

    /// What `file` uses as its source tells, each file once per way it is
    /// used, at the first line it is: the files of [`Graph::forward`] read
    /// from the source, told apart. A file named in a string only and also
    /// used another way is listed that other way only. Uses added with
    /// [`Graph::add_use`] are not in it.
    pub fn uses(&self, file: &str) -> &[Edge] {
        self.edges.get(file).map(Vec::as_slice).unwrap_or(&[])
    }

    /// `changed`, with the files that use one of them, directly or through
    /// other files: the files a change to them can change the meaning of, as
    /// the source tells. A file that loads from the folder of a changed file
    /// is one; a computed `load()` is not.
    pub fn dependents_of(&self, changed: &[String]) -> BTreeSet<String> {
        let start = self.with_folder_loaders(changed);
        let reached = self.users_of(&start);
        start.into_iter().chain(reached).collect()
    }

    /// `changed`, and the files that load computed paths from the folder of
    /// one of them.
    pub fn with_folder_loaders(&self, changed: &[String]) -> HashSet<String> {
        let mut start: HashSet<String> = changed.iter().cloned().collect();
        for (file, folders) in &self.folders {
            if changed
                .iter()
                .any(|c| folders.iter().any(|f| in_folder(c, f)))
            {
                start.insert(file.clone());
            }
        }
        start
    }

    /// Every file that uses one of `start`, directly or through other files.
    /// It has a file of `start` only when a cycle leads back to it.
    pub fn users_of(&self, start: &HashSet<String>) -> HashSet<String> {
        let mut reached: HashSet<String> = HashSet::new();
        let mut frontier: Vec<&String> = start.iter().collect();
        while let Some(file) = frontier.pop() {
            if let Some(users) = self.reverse.get(file) {
                for user in users {
                    if reached.insert(user.clone()) {
                        frontier.push(user);
                    }
                }
            }
        }
        reached
    }

    /// Whether `file` itself loads a path the source does not tell.
    pub fn loads_unknown(&self, file: &str) -> bool {
        self.unknown.contains(file)
    }

    /// Whether any file loads a path the source does not tell.
    pub fn has_unknown_loads(&self) -> bool {
        !self.unknown.is_empty()
    }
}

/// Reads what the file at `path` uses into `sources`, and the uid it gives
/// into `uids`.
fn read_file(
    path: &Path,
    res: String,
    sources: &mut HashMap<String, FileDeps>,
    uids: &mut HashMap<String, String>,
) {
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    if !matches!(ext, "gd" | "tscn" | "tres" | "uid" | "import") {
        return;
    }
    let Ok(text) = std::fs::read_to_string(path) else {
        return;
    };
    match ext {
        "gd" => {
            let deps = parse_script(&text, &res);
            sources.insert(res, deps);
        }
        "tscn" | "tres" => {
            if let Some(uid) = header_uid(&text) {
                uids.insert(uid, res.clone());
            }
            sources.insert(res, parse_text_resource(&text));
        }
        // `a.gd.uid` holds the uid of `a.gd`.
        "uid" => {
            let uid = text.trim();
            if uid.starts_with("uid://") {
                uids.insert(uid.to_string(), res.trim_end_matches(".uid").to_string());
            }
        }
        // `icon.png.import` holds the uid of `icon.png`.
        _ => {
            if let Some(uid) = header_uid(&text) {
                uids.insert(uid, res.trim_end_matches(".import").to_string());
            }
        }
    }
}

/// Whether `file` is in `folder`: `res://actors/`, or `res://actors/*.tscn`
/// for the scenes of that folder and the folders in it.
pub fn in_folder(file: &str, folder: &str) -> bool {
    match folder.rsplit_once("/*") {
        Some((dir, suffix)) => file.starts_with(dir) && file.ends_with(suffix),
        None => file.starts_with(folder),
    }
}

/// Functions whose first argument is a resource to load. Like Vitest, which
/// follows imports and not `fs.readFile`, files opened with FileAccess or
/// DirAccess are not followed, unless a `"res://…"` string names them: they
/// are mostly saves, replays and logs, read and written while running.
const LOADERS: &[&str] = &["load", "load_threaded_request", "change_scene_to_file"];

/// `# gdtest: loads res://actors/`: a script that loads computed paths says
/// where from, so that it depends on that folder instead of on everything.
/// `res://actors/*.tscn` narrows it to the scenes of that folder. gdtest
/// introduced it, and projects write it so.
const LOADS_DIRECTIVE: &str = "gdtest: loads ";

/// Reads what a script uses. `res` is its own path, which relative paths
/// are read from.
pub fn parse_script(text: &str, res: &str) -> FileDeps {
    let lexed = crate::lexer::tokenize(text);
    let mut tokens: Vec<(SyntaxKind, &str)> = Vec::new();
    // The 1-based line of each of `tokens`.
    let mut lines: Vec<usize> = Vec::new();
    let mut line = 1usize;
    let mut declared_folders: BTreeSet<String> = BTreeSet::new();
    let mut offset = 0usize;
    for token in &lexed.tokens {
        let end = offset + token.len as usize;
        let token_text = &text[offset..end];
        if !token.kind.is_trivia() {
            tokens.push((token.kind, token_text));
            lines.push(line);
        } else if token.kind == SyntaxKind::COMMENT
            && let Some(at) = token_text.find(LOADS_DIRECTIVE)
        {
            for folder in token_text[at + LOADS_DIRECTIVE.len()..].split([' ', ',']) {
                if folder.starts_with("res://") {
                    declared_folders.insert(folder.to_string());
                }
            }
        }
        line += token_text.matches('\n').count();
        offset = end;
    }

    let dir = res.rsplit_once('/').map(|(d, _)| d).unwrap_or("res:/");
    let constants = literal_names(&tokens);
    let mut deps = FileDeps::default();
    let mut uses = UseLines::new();
    for (i, &(kind, token_text)) in tokens.iter().enumerate() {
        match kind {
            SyntaxKind::STRING => {
                if let Some(value) = crate::literal::string_value(token_text)
                    && (value.starts_with("res://") || value.starts_with("uid://"))
                {
                    record(&mut uses, value.clone(), UseKind::Path, lines[i]);
                    deps.paths.insert(value);
                }
            }
            SyntaxKind::IDENTIFIER => {
                let after_extends = i > 0 && tokens[i - 1].0 == SyntaxKind::EXTENDS_KW;
                let how = if after_extends {
                    UseKind::Extends
                } else {
                    UseKind::Name
                };
                record(&mut uses, token_text.to_string(), how, lines[i]);
                deps.names.insert(token_text.to_string());
            }
            SyntaxKind::CLASS_NAME_KW => {
                if let Some(&(SyntaxKind::IDENTIFIER, name)) = tokens.get(i + 1) {
                    deps.class_name = Some(name.to_string());
                }
            }
            _ => {}
        }
        // A call that loads a path: `preload(...)`, `load(...)`,
        // `ResourceLoader.load(...)`, `FileAccess.open(...)`.
        let is_loader = match kind {
            SyntaxKind::PRELOAD_KW => true,
            SyntaxKind::IDENTIFIER => LOADERS.contains(&token_text) && is_loader_call(&tokens, i),
            _ => false,
        };
        if is_loader && matches!(tokens.get(i + 1), Some((SyntaxKind::PARENTHESIS_OPEN, _))) {
            let how = if kind != SyntaxKind::PRELOAD_KW {
                UseKind::Load
            } else if in_const(&tokens, i) {
                UseKind::ConstPreload
            } else {
                UseKind::Preload
            };
            if let Some((target, folder)) =
                read_load_argument(&tokens, i + 2, dir, &constants, &mut deps)
            {
                let how = if folder { UseKind::Folder } else { how };
                record(&mut uses, target, how, lines[i]);
            }
        }
    }
    if !declared_folders.is_empty() {
        deps.loads_unknown = false;
        for folder in &declared_folders {
            record(&mut uses, folder.clone(), UseKind::Folder, 1);
        }
        deps.folders.extend(declared_folders);
    }
    // `extends "a.gd"` is relative to the script.
    for (i, &(kind, _)) in tokens.iter().enumerate() {
        if kind == SyntaxKind::EXTENDS_KW
            && let Some(&(SyntaxKind::STRING, text)) = tokens.get(i + 1)
            && let Some(value) = crate::literal::string_value(text)
        {
            let path = if value.contains("://") {
                value
            } else {
                join_relative(dir, &value)
            };
            record(&mut uses, path.clone(), UseKind::Extends, lines[i]);
            deps.paths.insert(path);
        }
    }
    deps.uses = settle(uses);
    deps
}

/// Whether the `preload` at `i` gives a constant: `const A = preload(…)`.
fn in_const(tokens: &[(SyntaxKind, &str)], i: usize) -> bool {
    tokens[..i]
        .iter()
        .rev()
        .take_while(|(kind, _)| *kind != SyntaxKind::NEWLINE)
        .any(|(kind, _)| *kind == SyntaxKind::CONST_KW)
}

/// Whether the loader name at `i` is a call this analysis follows: `load`
/// on its own or on ResourceLoader, `open` on FileAccess or DirAccess, and
/// the other names on anything. `config.load(path)` is not one: it reads a
/// ConfigFile, usually from `user://`.
fn is_loader_call(tokens: &[(SyntaxKind, &str)], i: usize) -> bool {
    let name = tokens[i].1;
    let receiver = if i >= 2 && tokens[i - 1].0 == SyntaxKind::PERIOD {
        Some(tokens[i - 2].1)
    } else {
        None
    };
    match name {
        "load" | "load_threaded_request" => matches!(receiver, None | Some("ResourceLoader")),
        _ => true,
    }
}

/// Names given a string literal once, and never assigned again:
/// `const PATH := "res://a.json"`, `var path = "user://save"`.
fn literal_names(tokens: &[(SyntaxKind, &str)]) -> HashMap<String, String> {
    let mut values: HashMap<String, String> = HashMap::new();
    let mut assigned: HashMap<&str, usize> = HashMap::new();
    for (i, &(kind, text)) in tokens.iter().enumerate() {
        let assigns = matches!(tokens.get(i + 1).map(|t| t.1), Some("=") | Some("+="));
        let declared =
            i > 0 && matches!(tokens[i - 1].0, SyntaxKind::CONST_KW | SyntaxKind::VAR_KW);
        if kind == SyntaxKind::IDENTIFIER && assigns && !declared {
            *assigned.entry(text).or_default() += 1;
        }
        let declares = matches!(kind, SyntaxKind::CONST_KW | SyntaxKind::VAR_KW);
        if !declares {
            continue;
        }
        let Some(&(SyntaxKind::IDENTIFIER, name)) = tokens.get(i + 1) else {
            continue;
        };
        // `const A = "..."`, `const A := "..."`, `const A: String = "..."`.
        let mut at = i + 2;
        if tokens.get(at).map(|t| t.1) == Some(":") {
            at += 1;
            if tokens.get(at).map(|t| t.1) != Some("=") {
                at += 1;
            }
        }
        if tokens.get(at).map(|t| t.1) != Some("=") {
            continue;
        }
        if let Some(&(SyntaxKind::STRING, literal)) = tokens.get(at + 1)
            && matches!(
                tokens.get(at + 2).map(|t| t.0),
                Some(SyntaxKind::NEWLINE) | None
            )
            && let Some(value) = crate::literal::string_value(literal)
        {
            values.insert(name.to_string(), value);
        }
    }
    // A name assigned again later may hold anything.
    values.retain(|name, _| !assigned.contains_key(name.as_str()));
    values
}

/// Reads the path a loader call gets, from the token at `at`.
fn read_load_argument(
    tokens: &[(SyntaxKind, &str)],
    at: usize,
    dir: &str,
    constants: &HashMap<String, String>,
    deps: &mut FileDeps,
) -> Option<(String, bool)> {
    let &(kind, text) = tokens.get(at)?;
    let next = tokens.get(at + 1).map(|t| t.0);
    // `FileAccess.open(path, FileAccess.WRITE)` writes: it reads nothing.
    if next == Some(SyntaxKind::COMMA) && matches!(tokens.get(at + 4).map(|t| t.1), Some("WRITE")) {
        return None;
    }
    let literal = match kind {
        SyntaxKind::STRING => crate::literal::string_value(text),
        SyntaxKind::IDENTIFIER => constants.get(text).cloned(),
        _ => None,
    };
    if let Some(value) = literal {
        if value.starts_with("user://") {
            return None;
        }
        let path = if value.contains("://") {
            value
        } else {
            join_relative(dir, &value)
        };
        match next {
            Some(SyntaxKind::PARENTHESIS_CLOSE) | Some(SyntaxKind::COMMA) => {
                deps.paths.insert(path.clone());
                return Some((path, false));
            }
            // `"res://items/" + id` or `"res://items/%s.tres" % id`.
            _ if path.starts_with("res://") => {
                let folder = match path.rfind('/') {
                    Some(slash) if slash >= "res://".len() => &path[..=slash],
                    _ => "res://",
                };
                deps.folders.insert(folder.to_string());
                return Some((folder.to_string(), true));
            }
            _ => deps.loads_unknown = true,
        }
        return None;
    }
    deps.loads_unknown = true;
    None
}

/// `res://a/b` and `../c.gd` give `res://a/c.gd`.
fn join_relative(dir: &str, relative: &str) -> String {
    let mut parts: Vec<&str> = dir.trim_start_matches("res://").split('/').collect();
    parts.retain(|p| !p.is_empty());
    for part in relative.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            _ => parts.push(part),
        }
    }
    format!("res://{}", parts.join("/"))
}

/// Reads what a scene or text resource uses: its `ext_resource`s.
pub fn parse_text_resource(text: &str) -> FileDeps {
    let mut deps = FileDeps::default();
    let mut uses = UseLines::new();
    for (number, line) in text.lines().enumerate() {
        let line = line.trim_start();
        if !line.starts_with("[ext_resource") {
            continue;
        }
        if let Some(target) = attribute(line, "path").or_else(|| attribute(line, "uid")) {
            deps.paths.insert(target.to_string());
            record(
                &mut uses,
                target.to_string(),
                UseKind::ExtResource,
                number + 1,
            );
        }
    }
    deps.uses = settle(uses);
    deps
}

/// The `uid="uid://…"` of a file's first `[…]` header line.
fn header_uid(text: &str) -> Option<String> {
    let header = text.lines().find(|l| l.trim_start().starts_with('['))?;
    attribute(header, "uid")
        .filter(|u| u.starts_with("uid://"))
        .map(str::to_string)
        .or_else(|| {
            // An `.import` file has its uid on a line of its own.
            text.lines()
                .find_map(|l| l.trim().strip_prefix("uid=\""))
                .and_then(|rest| rest.split('"').next())
                .filter(|u| u.starts_with("uid://"))
                .map(str::to_string)
        })
}

/// The value of `name="…"` in a header line.
fn attribute<'a>(line: &'a str, name: &str) -> Option<&'a str> {
    let key = format!(" {name}=\"");
    let start = line.find(&key)? + key.len();
    let end = line[start..].find('"')? + start;
    Some(&line[start..end])
}

/// The project's autoloads, from its `project.godot`: name → res:// path.
pub fn read_autoloads(project_abs: &Path) -> HashMap<String, String> {
    let mut autoloads = HashMap::new();
    let Ok(text) = std::fs::read_to_string(project_abs.join("project.godot")) else {
        return autoloads;
    };
    let mut in_section = false;
    for line in text.lines() {
        let line = line.trim();
        if line.starts_with('[') {
            in_section = line == "[autoload]";
            continue;
        }
        if !in_section {
            continue;
        }
        if let Some((name, value)) = line.split_once('=') {
            let path = value.trim().trim_matches('"').trim_start_matches('*');
            if path.starts_with("res://") {
                autoloads.insert(name.trim().to_string(), path.to_string());
            }
        }
    }
    autoloads
}

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

    fn project(files: &[(&str, &str)]) -> TempDir {
        let dir = TempDir::new();
        for (path, text) in files {
            let full = dir.0.join(path);
            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
            std::fs::write(full, text).unwrap();
        }
        dir
    }

    fn s(paths: &[&str]) -> Vec<String> {
        paths.iter().map(|p| p.to_string()).collect()
    }

    #[test]
    fn reads_extends_preload_and_load() {
        let deps = parse_script(
            "extends \"res://src/base.gd\"\nconst Util = preload(\"res://src/util.gd\")\nvar x = load(\"res://data/config.gd\")\n",
            "res://a.gd",
        );
        for path in [
            "res://src/base.gd",
            "res://src/util.gd",
            "res://data/config.gd",
        ] {
            assert!(deps.paths.contains(path), "{path}");
        }
        let skipped = parse_script(
            "# preload(\"res://commented.gd\")\nload(\"user://settings.cfg\")\npreload(\"res://valid.gd\")\n",
            "res://a.gd",
        );
        assert_eq!(
            skipped.paths,
            BTreeSet::from(["res://valid.gd".to_string()])
        );
    }

    #[test]
    fn reads_names_strings_and_loads() {
        let deps = parse_script(
            r#"class_name Player extends Actor
const Sword = preload("weapons/sword.gd")
var data = FileAccess.open("res://data/stats.json", FileAccess.READ)
var save = FileAccess.open(save_path, FileAccess.READ)  # a save: not followed
var cfg = ConfigFile.new()
func _ready():
    cfg.load(some_path)  # a ConfigFile: not followed
    var item = load("res://items/%s.tres" % id)
    var scene = "res://levels/one.tscn"
    var any = load(path)
"#,
            "res://actors/player.gd",
        );
        assert_eq!(deps.class_name.as_deref(), Some("Player"));
        assert!(deps.names.contains("Actor"));
        assert!(deps.paths.contains("res://actors/weapons/sword.gd"));
        assert!(deps.paths.contains("res://data/stats.json"));
        assert!(deps.paths.contains("res://levels/one.tscn"));
        assert!(deps.folders.contains("res://items/"));
        assert!(deps.loads_unknown);
    }

    #[test]
    fn constants_and_writes() {
        let deps = parse_script(
            "const DOC := \"res://docs/gate.tscn\"\nvar out = \"user://x.tres\"\nfunc f():\n    load(DOC)\n    load(out)\n",
            "res://f.gd",
        );
        assert!(deps.paths.contains("res://docs/gate.tscn"));
        assert!(!deps.loads_unknown);
        let reassigned = parse_script(
            "var p := \"res://a.tres\"\nfunc f():\n    p = other()\n    load(p)\n",
            "res://f.gd",
        );
        assert!(reassigned.loads_unknown);
        let literal = parse_script(
            "func f():\n    var a = load(\"res://a.gd\")\n    var c = ConfigFile.new()\n    c.load(p)\n",
            "res://f.gd",
        );
        assert!(!literal.loads_unknown);
    }

    #[test]
    fn dependents_follow_names_paths_scenes_and_uids() {
        let dir = project(&[
            ("project.godot", "[autoload]\n\nClock=\"*res://clock.gd\"\n"),
            ("clock.gd", "extends Node\n"),
            ("actor.gd", "class_name Actor\nextends Node\n"),
            ("actor.gd.uid", "uid://actor1\n"),
            ("player.gd", "class_name Player\nextends Actor\n"),
            (
                "hud.gd",
                "extends Control\nvar p: Player\nfunc t():\n    return Clock\n",
            ),
            (
                "level.tscn",
                "[gd_scene format=3]\n\n[ext_resource type=\"Script\" path=\"res://hud.gd\" id=\"1\"]\n",
            ),
            (
                "enemy.tscn",
                "[gd_scene format=3]\n\n[ext_resource type=\"Script\" uid=\"uid://actor1\" id=\"1\"]\n",
            ),
            ("other.gd", "extends Node\nvar x = load(path)\n"),
            (".hidden/skip.gd", "extends Actor\n"),
            ("ignored/.gdignore", ""),
            ("ignored/skip.gd", "extends Actor\n"),
            // Another project, with a class of the same name.
            ("server/project.godot", ""),
            ("server/actor.gd", "class_name Actor\nextends Node\n"),
            ("server/skip.gd", "extends Actor\n"),
        ]);
        let graph = Graph::build(&dir.0);
        let found: Vec<String> = graph
            .dependents_of(&s(&["res://actor.gd"]))
            .into_iter()
            .collect();
        assert_eq!(
            found,
            s(&[
                "res://actor.gd",
                "res://enemy.tscn",
                "res://hud.gd",
                "res://level.tscn",
                "res://player.gd"
            ]),
            "a computed load() is not a dependent; a dot folder, an ignored one and a nested project are not read"
        );
        assert!(
            graph.forward["res://hud.gd"].contains("res://clock.gd"),
            "an autoload used by name"
        );
        assert_eq!(graph.autoloads()["Clock"], "res://clock.gd");
        assert!(graph.loads_unknown("res://other.gd"));
        assert!(graph.has_unknown_loads());
    }

    #[test]
    fn folder_loads_and_the_directive() {
        let dir = project(&[
            (
                "items/sword.tres",
                "[gd_resource type=\"Resource\" format=3]\n",
            ),
            (
                "items.gd",
                "func get(id):\n    return load(\"res://items/\" + id)\n",
            ),
            (
                "restore.gd",
                "# gdtest: loads res://actors/*.tscn\nfunc f(path):\n    return load(path)\n",
            ),
            ("actors/minion.tscn", "[gd_scene format=3]\n"),
            ("actors/minion.gd", "extends Node\n"),
        ]);
        let graph = Graph::build(&dir.0);
        let sword: Vec<String> = graph
            .dependents_of(&s(&["res://items/sword.tres"]))
            .into_iter()
            .collect();
        assert_eq!(sword, s(&["res://items.gd", "res://items/sword.tres"]));
        assert!(
            !graph.loads_unknown("res://restore.gd"),
            "the directive says where from"
        );
        assert!(graph.forward["res://restore.gd"].contains("res://actors/minion.tscn"));
        assert!(!graph.forward["res://restore.gd"].contains("res://actors/minion.gd"));
        assert!(in_folder("res://actors/a/b.tscn", "res://actors/*.tscn"));
        assert!(!in_folder("res://actors/a/b.gd", "res://actors/*.tscn"));
    }

    #[test]
    fn uses_say_how_and_where() {
        let dir = project(&[
            ("project.godot", "[autoload]\n\nClock=\"*res://clock.gd\"\n"),
            ("clock.gd", "extends Node\n"),
            ("actor.gd", "class_name Actor\nextends Node\n"),
            ("stats.gd", "class_name Stats\n"),
            ("items/sword.tres", "[gd_resource format=3]\n"),
            (
                "player.gd",
                "class_name Player\nextends Actor\nconst Hud = preload(\"res://hud.gd\")\nvar p := \"res://hud.gd\"\nfunc f(id):\n    var a: Stats = Stats.new()\n    Clock.tick()\n    load(\"res://items/\" + id)\n    return preload(\"res://level.tscn\")\n",
            ),
            ("hud.gd", "extends Control\n"),
            (
                "level.tscn",
                "[gd_scene format=3]\n\n[ext_resource type=\"Script\" path=\"res://player.gd\" id=\"1\"]\n",
            ),
        ]);
        let graph = Graph::build(&dir.0);
        let uses: Vec<(&str, UseKind, usize)> = graph
            .uses("res://player.gd")
            .iter()
            .map(|e| (e.to.as_str(), e.kind, e.line))
            .collect();
        assert_eq!(
            uses,
            [
                ("res://actor.gd", UseKind::Extends, 2),
                // Named in a string too, but used by preload.
                ("res://hud.gd", UseKind::ConstPreload, 3),
                // Used by name too, but extended: one use.
                ("res://stats.gd", UseKind::ClassName, 6),
                ("res://clock.gd", UseKind::Autoload, 7),
                ("res://items/sword.tres", UseKind::Folder, 8),
                ("res://level.tscn", UseKind::Preload, 9),
            ]
        );
        assert_eq!(
            graph.uses("res://level.tscn")[0],
            Edge {
                to: "res://player.gd".to_string(),
                kind: UseKind::ExtResource,
                line: 3
            }
        );
    }

    #[test]
    fn a_use_added_counts() {
        let dir = project(&[("a.gd", "extends Node\n"), ("b.gd", "extends Node\n")]);
        let mut graph = Graph::build(&dir.0);
        graph.add_use("res://a.gd", "res://b.gd");
        let found: Vec<String> = graph
            .dependents_of(&s(&["res://b.gd"]))
            .into_iter()
            .collect();
        assert_eq!(found, s(&["res://a.gd", "res://b.gd"]));
    }

    /// A temporary folder, removed when dropped.
    struct TempDir(std::path::PathBuf);

    impl TempDir {
        fn new() -> TempDir {
            use std::sync::atomic::{AtomicUsize, Ordering};
            static NEXT: AtomicUsize = AtomicUsize::new(0);
            let n = NEXT.fetch_add(1, Ordering::SeqCst);
            let path =
                std::env::temp_dir().join(format!("gdsyntax-project-{}-{}", std::process::id(), n));
            let _ = std::fs::remove_dir_all(&path);
            std::fs::create_dir_all(&path).unwrap();
            TempDir(path)
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }
}