ahk 0.1.1

The ahk language: a lexer, an AST, a parser and an interpreter for AutoHotkey-style scripts
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! The warnings of a script.
//!
//! Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05 and on the
//! binary of AutoHotkey v1.1.37.02 on 2026-11-05: the `#Warn` directive takes
//! the type of the warning and the mode of it, and the two dialects have
//! their own types. The type that is not one of them is refused at the load
//! with "Parameter #1 invalid." and the source of the directive, and the mode
//! that is not one of them with "Parameter #2 invalid." and the text that was
//! written.
//!
//! The tree has no dialog, and the warnings go to the report. The mode of the
//! "StdOut" writes them to the standard output as well, the way the v2 does:
//! the line of the script and the text of the warning.

use alloc::collections::BTreeSet;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use crate::ast::Node;
use crate::dialect::Dialect;

/// The type of a warning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WarningType {
    /// Every warning of the dialect.
    All,
    /// A variable that is read and never written.
    VarUnset,
    /// A variable of the script that is read and never written.
    UseUnsetGlobal,
    /// A variable of a function that is read and never written.
    UseUnsetLocal,
    /// An environment variable that is accessed.
    UseEnv,
    /// A local variable that has the name of a global one.
    LocalSameAsGlobal,
    /// A class that is overwritten by a variable.
    ClassOverwrite,
    /// A line that comes after a statement that leaves the level.
    Unreachable,
}

/// The way a warning is given.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WarningMode {
    /// The warning is a dialog of the machine. The tree has no dialog, and
    /// the warning goes to the report.
    MsgBox,
    /// The warning goes to the standard output.
    StdOut,
    /// The warning goes to the debug output of the machine. The tree has
    /// none, and the warning goes to the report.
    OutputDebug,
    /// There is no warning.
    Off,
}

/// The mode of the warnings of each type.
///
/// Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05: the warnings
/// of the v2 are on when the script does not say, and they use the mode of the
/// "MsgBox", and the warnings of the "LocalSameAsGlobal" are off.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-05: the
/// warnings of the v1 are off when the script does not say.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TheModes {
    /// The mode of the warning of the variable that is read and never
    /// written.
    pub var_unset: WarningMode,
    /// The mode of the warning of the variable of the script that is read and
    /// never written.
    pub use_unset_global: WarningMode,
    /// The mode of the warning of the variable of a function that is read and
    /// never written.
    pub use_unset_local: WarningMode,
    /// The mode of the warning of the environment variable that is accessed.
    pub use_env: WarningMode,
    /// The mode of the warning of the local that has the name of a global.
    pub local_same_as_global: WarningMode,
    /// The mode of the warning of the class that is overwritten.
    pub class_overwrite: WarningMode,
    /// The mode of the warning of the line that never runs.
    pub unreachable: WarningMode,
}

impl TheModes {
    /// The modes of the v2 when the script does not say.
    pub fn the_defaults_of_the_v2() -> TheModes {
        TheModes {
            var_unset: WarningMode::MsgBox,
            use_unset_global: WarningMode::Off,
            use_unset_local: WarningMode::Off,
            use_env: WarningMode::Off,
            local_same_as_global: WarningMode::Off,
            class_overwrite: WarningMode::Off,
            unreachable: WarningMode::MsgBox,
        }
    }

    /// The modes of the v1 when the script does not say.
    ///
    /// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-05: the
    /// warnings of the v1 are off when the script does not say.
    pub fn the_defaults_of_the_v1() -> TheModes {
        TheModes {
            var_unset: WarningMode::Off,
            use_unset_global: WarningMode::Off,
            use_unset_local: WarningMode::Off,
            use_env: WarningMode::Off,
            local_same_as_global: WarningMode::Off,
            class_overwrite: WarningMode::Off,
            unreachable: WarningMode::Off,
        }
    }

    /// The mode of the type of the warning.
    pub fn the_mode_of(&self, kind: WarningType) -> WarningMode {
        match kind {
            WarningType::All => WarningMode::Off,
            WarningType::VarUnset => self.var_unset,
            WarningType::UseUnsetGlobal => self.use_unset_global,
            WarningType::UseUnsetLocal => self.use_unset_local,
            WarningType::UseEnv => self.use_env,
            WarningType::LocalSameAsGlobal => self.local_same_as_global,
            WarningType::ClassOverwrite => self.class_overwrite,
            WarningType::Unreachable => self.unreachable,
        }
    }

    /// The mode of the type of the warning is written.
    pub fn write(&mut self, kind: WarningType, mode: WarningMode) {
        match kind {
            WarningType::All => {
                self.var_unset = mode;
                self.use_unset_global = mode;
                self.use_unset_local = mode;
                self.use_env = mode;
                self.local_same_as_global = mode;
                self.class_overwrite = mode;
                self.unreachable = mode;
            }
            WarningType::VarUnset => self.var_unset = mode,
            WarningType::UseUnsetGlobal => self.use_unset_global = mode,
            WarningType::UseUnsetLocal => self.use_unset_local = mode,
            WarningType::UseEnv => self.use_env = mode,
            WarningType::LocalSameAsGlobal => self.local_same_as_global = mode,
            WarningType::ClassOverwrite => self.class_overwrite = mode,
            WarningType::Unreachable => self.unreachable = mode,
        }
    }
}

/// The types of the warning that the tree carries.
///
/// Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05 and on the
/// binary of AutoHotkey v1.1.37.02 on 2026-11-05: the tree warns about the
/// variable that is read and never written, about the environment variable
/// that is accessed, and about the line that never runs. The two warnings
/// that are read out of the script -- the local that has the name of a global
/// and the class that is overwritten -- are not carried yet, and the report
/// says so.
pub fn the_types_that_are_carried() -> &'static [WarningType] {
    &[
        WarningType::VarUnset,
        WarningType::UseUnsetGlobal,
        WarningType::UseUnsetLocal,
        WarningType::UseEnv,
        WarningType::LocalSameAsGlobal,
        WarningType::ClassOverwrite,
        WarningType::Unreachable,
    ]
}

/// The name of the type of the warning, the way the v2 writes it.
pub fn the_name_of_the_type(kind: WarningType) -> &'static str {
    match kind {
        WarningType::All => "All",
        WarningType::VarUnset => "VarUnset",
        WarningType::UseUnsetGlobal => "UseUnsetGlobal",
        WarningType::UseUnsetLocal => "UseUnsetLocal",
        WarningType::UseEnv => "UseEnv",
        WarningType::LocalSameAsGlobal => "LocalSameAsGlobal",
        WarningType::ClassOverwrite => "ClassOverwrite",
        WarningType::Unreachable => "Unreachable",
    }
}

/// A warning of the script.
#[derive(Debug, Clone, PartialEq)]
pub struct Warning {
    /// The line of the script that the warning names.
    pub line: u32,
    /// The text of the warning.
    pub message: String,
}

/// The type and the mode that the argument of the `#Warn` names.
///
/// The type is the text that comes before the comma, and the mode is the text
/// that comes after it. The type that is not one of them is named by the
/// caller, and the mode that is not one of them is named by the caller too.
pub fn the_kind_and_the_mode(
    argument: &str,
    dialect: &dyn Dialect,
) -> (Option<WarningType>, Option<WarningMode>) {
    let (kind, mode) = the_parts_of_the_argument(argument);
    let kind = if kind.is_empty() {
        None
    } else {
        dialect.the_type_of_the_warning(kind)
    };
    let mode = if mode.is_empty() {
        None
    } else {
        dialect.the_mode_of_the_warning(mode)
    };
    (kind, mode)
}

/// The texts of the type and of the mode of the argument of the `#Warn`.
///
/// The type is the text that comes before the comma, and the mode is the text
/// that comes after it. A text that is empty is not a name, and the caller
/// asks the tree whether the name is one of them.
pub fn the_parts_of_the_argument(argument: &str) -> (&str, &str) {
    match argument.split_once(',') {
        Some((kind, mode)) => (kind.trim(), mode.trim()),
        None => (argument.trim(), ""),
    }
}

/// The modes of the warnings of the script.
///
/// The directives are read before the script runs, the way the v2 reads them,
/// and the last `#Warn` is the one that counts.
pub fn the_modes_of_the_script(statements: &[Node], dialect: &dyn Dialect) -> TheModes {
    let mut modes = dialect.the_default_warnings();
    the_modes_of_the_level(statements, &mut modes, dialect);
    modes
}

fn the_modes_of_the_level(statements: &[Node], modes: &mut TheModes, dialect: &dyn Dialect) {
    for statement in statements {
        if let Node::Directive { name, argument, .. } = statement {
            if name.eq_ignore_ascii_case("warn") {
                let (kind, mode) = the_kind_and_the_mode(argument, dialect);
                if let Some(kind) = kind {
                    if let Some(mode) = mode {
                        modes.write(kind, mode);
                    }
                }
            }
        }
        for body in the_bodies_of(statement) {
            the_modes_of_the_level(body, modes, dialect);
        }
    }
}

/// The types of the warning that the script asks for.
///
/// The directives are read before the script runs, and the type of the "All"
/// is the type of every warning of the dialect.
pub fn the_types_of_the_script(statements: &[Node], dialect: &dyn Dialect) -> Vec<WarningType> {
    let mut types = Vec::new();
    the_types_of_the_level(statements, &mut types, dialect);
    types
}

fn the_types_of_the_level(
    statements: &[Node],
    types: &mut Vec<WarningType>,
    dialect: &dyn Dialect,
) {
    for statement in statements {
        if let Node::Directive { name, argument, .. } = statement {
            if name.eq_ignore_ascii_case("warn") {
                let (kind, _) = the_kind_and_the_mode(argument, dialect);
                if let Some(kind) = kind {
                    // The type of the "All" is the type of every warning of
                    // the dialect.
                    let kinds = if kind == WarningType::All {
                        dialect.the_types_of_the_warning().to_vec()
                    } else {
                        vec![kind]
                    };
                    for kind in kinds {
                        if !types.contains(&kind) {
                            types.push(kind);
                        }
                    }
                }
            }
        }
        for body in the_bodies_of(statement) {
            the_types_of_the_level(body, types, dialect);
        }
    }
}

/// The warnings of the statements of the script.
///
/// Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05: the warning of
/// the unreachable line is given for the line that comes right after a
/// `Return`, a `Break`, a `Continue`, a `Throw` or a `Goto` of the same level,
/// and the label that is the target of the jump is not warned about.
pub fn the_warnings_of_the_script(statements: &[Node]) -> Vec<Warning> {
    let mut warnings = Vec::new();
    the_warnings_of_the_level(statements, &mut warnings);
    warnings
}

fn the_warnings_of_the_level(statements: &[Node], warnings: &mut Vec<Warning>) {
    let mut after: Option<&'static str> = None;
    for statement in statements {
        if let Some(word) = after {
            // The warning is of the line that comes right after the statement
            // that leaves the level, and not of the lines that come after that
            // one.
            after = None;
            if !matches!(statement, Node::Label { .. }) {
                warnings.push(Warning {
                    line: statement.line(),
                    message: format!("This line will never execute, due to {word} preceding it."),
                });
            }
        }
        if !matches!(statement, Node::Label { .. }) {
            after = the_word_that_leaves_the_level(statement);
        }
        for body in the_bodies_of(statement) {
            the_warnings_of_the_level(body, warnings);
        }
    }
}

/// The word of the statement that leaves the level, when it leaves it.
fn the_word_that_leaves_the_level(statement: &Node) -> Option<&'static str> {
    match statement {
        Node::Break { .. } => Some("Break"),
        Node::Continue { .. } => Some("Continue"),
        Node::Return { .. } => Some("Return"),
        Node::Throw { .. } => Some("Throw"),
        Node::Goto { .. } => Some("Goto"),
        _ => None,
    }
}

/// The bodies of a statement: the levels of their own.
fn the_bodies_of(statement: &Node) -> Vec<&[Node]> {
    match statement {
        Node::Block { body, .. } => vec![body],
        Node::If {
            branches,
            otherwise,
            ..
        } => {
            let mut bodies: Vec<&[Node]> = branches
                .iter()
                .map(|branch| branch.body.as_slice())
                .collect();
            bodies.push(otherwise);
            bodies
        }
        Node::Switch { cases, .. } => cases.iter().map(|case| case.body.as_slice()).collect(),
        Node::While { body, .. } => vec![body],
        Node::Loop { body, .. } => vec![body],
        Node::For { body, .. } => vec![body],
        Node::FunctionDef { body, .. } => vec![body],
        Node::Try {
            body,
            catches,
            otherwise,
            finally,
            ..
        } => {
            let mut bodies: Vec<&[Node]> = vec![body, otherwise, finally];
            bodies.extend(catches.iter().map(|catch| catch.body.as_slice()));
            bodies
        }
        Node::ClassDef {
            methods, nested, ..
        } => {
            let mut bodies: Vec<&[Node]> = methods
                .iter()
                .map(|method| method.body.as_slice())
                .collect();
            for class in nested {
                bodies.extend(the_bodies_of(class));
            }
            bodies
        }
        Node::LegacyIf {
            body, otherwise, ..
        } => vec![body, otherwise],
        Node::HotkeyDefinition { body, .. } => vec![body],
        _ => Vec::new(),
    }
}

/// The warning of the local variable that has the name of a global one.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-05 and on the
/// binary of AutoHotkey v2.0.19 on 2026-11-05: the warning is given once,
/// when the script is read, and the text of it names the variable and the
/// function of it -- "x  (in function f)". The v1 names the line that opens
/// the body of the function, and the v2 names the line of the write of the
/// local.
///
/// A local that is declared global is not a local, and a local that has the
/// name of a variable of the script is warned about. The parameters of the
/// function are declared, and they are not warned about.
pub fn the_warnings_of_the_locals_that_are_globals(
    statements: &[Node],
    dialect: &dyn Dialect,
) -> Vec<Warning> {
    let globals = the_globals_of_the_script(statements);
    let mut warnings = Vec::new();
    the_warnings_of_the_locals_of_the_level(statements, &globals, dialect, &mut warnings);
    warnings
}

fn the_warnings_of_the_locals_of_the_level(
    statements: &[Node],
    globals: &BTreeSet<String>,
    dialect: &dyn Dialect,
    warnings: &mut Vec<Warning>,
) {
    for statement in statements {
        match statement {
            Node::FunctionDef {
                name,
                parameters,
                body,
                declarations,
                body_line,
                ..
            } => {
                let scope = TheScope {
                    name,
                    parameters,
                    body,
                    declarations,
                    body_line: *body_line,
                };
                the_warnings_of_the_locals_of_a_scope(scope, globals, dialect, warnings);
            }
            Node::ClassDef {
                name,
                methods,
                accessors,
                nested,
                ..
            } => {
                the_warnings_of_the_locals_of_a_class(
                    name, methods, accessors, nested, globals, dialect, warnings,
                );
            }
            _ => {}
        }
        for body in the_bodies_of_the_level(statement) {
            the_warnings_of_the_locals_of_the_level(body, globals, dialect, warnings);
        }
    }
}

/// The scope whose locals are warned about.
///
/// It is a function of the script, a method of a class or the body of a
/// getter.
struct TheScope<'a> {
    /// The name of the scope, the way the warning names it.
    name: &'a str,
    /// The parameters of the scope.
    parameters: &'a [crate::ast::Parameter],
    /// The statements of the scope.
    body: &'a [Node],
    /// The declarations of the scope.
    declarations: &'a crate::ast::Declarations,
    /// The line of the brace that opens the body.
    body_line: u32,
}

/// The warnings of the locals of a function or of a method.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-05: the v1
/// names the line that opens the body of the function, and the v2 names the
/// line of the write of the local.
fn the_warnings_of_the_locals_of_a_scope(
    scope: TheScope<'_>,
    globals: &BTreeSet<String>,
    dialect: &dyn Dialect,
    warnings: &mut Vec<Warning>,
) {
    let TheScope {
        name,
        parameters,
        body,
        declarations,
        body_line,
    } = scope;
    let mut writes = Vec::new();
    the_writes_of_a_level(body, &mut writes, false);
    // The locals of the scope are the names that it writes, and the names
    // that it only reads as well when the scope of a function is its own.
    let mut locals = writes;
    if dialect.the_scope_of_a_function_is_its_own() {
        let mut reads = Vec::new();
        the_reads_of_a_level(body, &mut reads);
        locals.extend(reads);
        locals.sort_by_key(|(_, line)| *line);
    }
    let mut seen = BTreeSet::new();
    for (local, the_line) in locals {
        if !seen.insert(local.to_lowercase()) {
            continue;
        }
        if declarations
            .globals
            .iter()
            .any(|name| name.to_lowercase() == local.to_lowercase())
        {
            continue;
        }
        if parameters
            .iter()
            .any(|parameter| parameter.name.to_lowercase() == local.to_lowercase())
        {
            continue;
        }
        if !globals.contains(&local.to_lowercase()) {
            continue;
        }
        if crate::variables::is_built_in(&local) {
            continue;
        }
        // The v1 names the line that opens the body of the function, and the
        // v2 names the line of the write of the local.
        let line = if dialect.the_scope_of_a_function_is_its_own() {
            body_line
        } else {
            the_line
        };
        warnings.push(Warning {
            line,
            message: format!(
                "This local variable has the same name as a global variable.\n     Specifically: {local}  (in function {name})"
            ),
        });
    }
}

/// The warnings of the locals of the members of a class.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-05: the v1
/// names the method "A.m" -- the class and the method -- and the class that is
/// nested is "A.B.m". Measured on the binary of AutoHotkey v2.0.19 on
/// 2026-11-05: the v2 names the method of the prototype "A.Prototype.m", and
/// the static method is "A.m".
fn the_warnings_of_the_locals_of_a_class(
    path: &str,
    methods: &[crate::ast::MethodDef],
    accessors: &[crate::ast::AccessDef],
    nested: &[Node],
    globals: &BTreeSet<String>,
    dialect: &dyn Dialect,
    warnings: &mut Vec<Warning>,
) {
    for method in methods {
        let name = dialect.the_name_of_a_member_of_a_class(path, &method.name, method.is_static);
        let scope = TheScope {
            name: &name,
            parameters: &method.parameters,
            body: &method.body,
            declarations: &method.declarations,
            body_line: method.body_line,
        };
        the_warnings_of_the_locals_of_a_scope(scope, globals, dialect, warnings);
    }
    for accessor in accessors {
        for (kind, body) in [("get", &accessor.getter), ("set", &accessor.setter)] {
            let Some(body) = body else { continue };
            let name = dialect.the_name_of_a_member_of_a_class(
                path,
                &format!("{}.{kind}", accessor.name),
                accessor.is_static,
            );
            let scope = TheScope {
                name: &name,
                parameters: &accessor.parameters,
                body: &body.body,
                declarations: &body.declarations,
                body_line: body.line,
            };
            the_warnings_of_the_locals_of_a_scope(scope, globals, dialect, warnings);
        }
    }
    for class in nested {
        if let Node::ClassDef {
            name,
            methods,
            accessors,
            nested,
            ..
        } = class
        {
            let path = format!("{path}.{name}");
            the_warnings_of_the_locals_of_a_class(
                &path, methods, accessors, nested, globals, dialect, warnings,
            );
        }
    }
}

/// The names that the level reads, and the lines of the reads.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-05: the scope of
/// a function of the v1 is its own, and the name that it only reads is a local
/// of it: the `f() { y := x }` has a local "x" when the script has a global
/// "x". The name of a variable of the v1 is between two percent signs, and the
/// escape of the v1 -- the backtick -- carries a percent sign that does not
/// open a name.
fn the_reads_of_a_level(statements: &[Node], reads: &mut Vec<(String, u32)>) {
    for statement in statements {
        the_reads_of_a_node(statement, reads);
        for body in the_bodies_of_the_level(statement) {
            the_reads_of_a_level(body, reads);
        }
    }
}

/// The names that a node reads, and the lines of the reads.
///
/// The match has an arm for every node of the tree of the script, so that a
/// node that is added later is not forgotten here.
fn the_reads_of_a_node(node: &Node, reads: &mut Vec<(String, u32)>) {
    match node {
        Node::Literal { .. } => {}
        Node::Var { name, line } => reads.push((name.clone(), *line)),
        Node::Unary { operand, .. } => the_reads_of_a_node(operand, reads),
        Node::Binary { left, right, .. } => {
            the_reads_of_a_node(left, reads);
            the_reads_of_a_node(right, reads);
        }
        Node::Unset { .. } => {}
        Node::Ternary {
            condition,
            then,
            otherwise,
            ..
        } => {
            the_reads_of_a_node(condition, reads);
            the_reads_of_a_node(then, reads);
            the_reads_of_a_node(otherwise, reads);
        }
        Node::DynamicName { pieces, .. } => {
            for piece in pieces {
                the_reads_of_a_piece(piece, reads);
            }
        }
        Node::AssignDynamic { name, value, .. } => {
            for piece in name {
                the_reads_of_a_piece(piece, reads);
            }
            the_reads_of_a_node(value, reads);
        }
        Node::Assign { value, .. } => the_reads_of_a_node(value, reads),
        Node::LegacyAssign { text, line, .. } => the_names_of_a_text(text, *line, reads),
        Node::LegacyComparison {
            left, text, line, ..
        } => {
            the_reads_of_a_node(left, reads);
            the_names_of_a_text(text, *line, reads);
        }
        Node::LegacyMatch {
            left, texts, line, ..
        } => {
            the_reads_of_a_node(left, reads);
            for text in texts {
                the_names_of_a_text(text, *line, reads);
            }
        }
        Node::LegacyControl { condition, .. } => the_reads_of_a_node(condition, reads),
        Node::Index { target, index, .. } => {
            the_reads_of_a_node(target, reads);
            the_reads_of_a_node(index, reads);
        }
        Node::Call { arguments, .. } => {
            for argument in arguments {
                the_reads_of_a_node(argument, reads);
            }
        }
        Node::New { arguments, .. } => {
            for argument in arguments {
                the_reads_of_a_node(argument, reads);
            }
        }
        Node::LegacyCall {
            parameters, line, ..
        } => {
            for parameter in parameters {
                match parameter {
                    crate::ast::LegacyParameter::Text(text) => {
                        the_names_of_a_text(text, *line, reads)
                    }
                    crate::ast::LegacyParameter::Expression(value) => {
                        the_reads_of_a_node(value, reads)
                    }
                }
            }
        }
        Node::LegacyIf {
            parameters, line, ..
        } => {
            for text in parameters {
                the_names_of_a_text(text, *line, reads);
            }
        }
        Node::Expression { value, .. } => the_reads_of_a_node(value, reads),
        Node::LegacyExpression { value, .. } => the_reads_of_a_node(value, reads),
        Node::Block { .. } => {}
        Node::If { branches, .. } => {
            for branch in branches {
                the_reads_of_a_node(&branch.condition, reads);
                for item in &branch.tail {
                    the_reads_of_a_node(item, reads);
                }
            }
        }
        Node::Switch { subject, cases, .. } => {
            the_reads_of_a_node(subject, reads);
            for case in cases {
                for value in &case.values {
                    the_reads_of_a_node(value, reads);
                }
            }
        }
        Node::While { condition, .. } => the_reads_of_a_node(condition, reads),
        Node::Loop {
            arguments, until, ..
        } => {
            for argument in arguments {
                the_reads_of_a_node(argument, reads);
            }
            if let Some(until) = until {
                the_reads_of_a_node(until, reads);
            }
        }
        Node::Directive { .. } => {}
        Node::Break { .. } => {}
        Node::Continue { .. } => {}
        Node::Return { value, .. } => {
            if let Some(value) = value {
                the_reads_of_a_node(value, reads);
            }
        }
        Node::ExitApp { code, .. } => {
            if let Some(code) = code {
                the_reads_of_a_node(code, reads);
            }
        }
        Node::FunctionDef { .. } => {}
        Node::ClassDef { .. } => {}
        Node::MethodCall {
            target, arguments, ..
        } => {
            the_reads_of_a_node(target, reads);
            for argument in arguments {
                the_reads_of_a_node(argument, reads);
            }
        }
        Node::Property { target, name, .. } => {
            the_reads_of_a_node(target, reads);
            the_reads_of_a_member_name(name, reads);
        }
        Node::AssignProperty {
            target,
            name,
            value,
            ..
        } => {
            the_reads_of_a_node(target, reads);
            the_reads_of_a_member_name(name, reads);
            the_reads_of_a_node(value, reads);
        }
        Node::AssignIndex {
            target,
            index,
            value,
            ..
        } => {
            the_reads_of_a_node(target, reads);
            the_reads_of_a_node(index, reads);
            the_reads_of_a_node(value, reads);
        }
        Node::ArrayLiteral { items, .. } => {
            for item in items.iter().flatten() {
                the_reads_of_a_node(item, reads);
            }
        }
        Node::Group { items, .. } => {
            for item in items {
                the_reads_of_a_node(item, reads);
            }
        }
        Node::Empty { .. } => {}
        Node::Legacy { items, .. } => {
            for item in items {
                the_reads_of_a_node(item, reads);
            }
        }
        Node::ObjectLiteral { items, .. } => {
            for item in items {
                match item {
                    crate::ast::ObjectItem::Property(name, value) => {
                        the_reads_of_a_member_name(name, reads);
                        the_reads_of_a_node(value, reads);
                    }
                    crate::ast::ObjectItem::LegacyKey(key, value) => {
                        the_reads_of_a_node(key, reads);
                        the_reads_of_a_node(value, reads);
                    }
                    crate::ast::ObjectItem::Value(value) => the_reads_of_a_node(value, reads),
                }
            }
        }
        Node::Lambda { body, .. } => the_reads_of_a_node(body, reads),
        Node::Try { .. } => {}
        Node::Throw { value, .. } => {
            if let Some(value) = value {
                the_reads_of_a_node(value, reads);
            }
        }
        Node::Declare { .. } => {}
        Node::Super { .. } => {}
        Node::For { source, .. } => the_reads_of_a_node(source, reads),
        Node::Label { .. } => {}
        Node::Goto { .. } => {}
        Node::HotkeyDefinition { .. } => {}
    }
}

/// The names that a piece of a name that the script builds reads.
fn the_reads_of_a_piece(piece: &crate::ast::DynamicPiece, reads: &mut Vec<(String, u32)>) {
    if let crate::ast::DynamicPiece::Value(value) = piece {
        the_reads_of_a_node(value, reads);
    }
}

/// The names that a member of a value reads.
fn the_reads_of_a_member_name(name: &crate::ast::MemberName, reads: &mut Vec<(String, u32)>) {
    if let crate::ast::MemberName::Dynamic(pieces) = name {
        for piece in pieces {
            the_reads_of_a_piece(piece, reads);
        }
    }
}

/// The names that a text of the v1 reads.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-04: the escape
/// of the v1 makes the character that follows it a literal, and the percent
/// sign that it carries does not close the name of a variable.
fn the_names_of_a_text(text: &str, line: u32, reads: &mut Vec<(String, u32)>) {
    let chars: Vec<char> = text.chars().collect();
    let mut index = 0usize;
    while index < chars.len() {
        if chars[index] == '`' {
            index += 2;
            continue;
        }
        if chars[index] == '%' {
            if let Some(close) = the_closing_percent(&chars, index + 1) {
                let name: String = chars[index + 1..close].iter().collect();
                reads.push((name.trim().to_string(), line));
                index = close + 1;
                continue;
            }
        }
        index += 1;
    }
}

/// The place of the percent sign that closes the name of a variable.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-04: the escape
/// of the v1 makes the character that follows it a literal, and the percent
/// sign that it carries does not close the name of a variable.
fn the_closing_percent(chars: &[char], from: usize) -> Option<usize> {
    let mut index = from;
    while index < chars.len() {
        match chars[index] {
            '`' => index += 2,
            '%' => return Some(index),
            _ => index += 1,
        }
    }
    None
}

/// The names of a scope: the ones that it writes and the ones that it reads.
type TheNames = BTreeSet<String>;

/// The warning of the variable that is read and never written.
///
/// Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05: the warning is
/// given when the script is read, and not when the variable is read: the
/// `if 0 { x := nope }` is warned about, and the read of it never happens.
///
/// The names of the script are the globals: the scopes that the script holds
/// see them, and the scope of a function does not see the names of another
/// function. The warning is given once for each name of each scope.
pub fn the_warnings_of_the_variables_that_are_never_written(statements: &[Node]) -> Vec<Warning> {
    let mut warnings = Vec::new();
    let mut globals = TheNames::new();
    the_warnings_of_the_reads_of_the_script(statements, &mut globals, &mut warnings);
    warnings
}

/// The warnings of the reads of the script and of the scopes that it holds.
///
/// The script is a scope of its own, and the scopes that it holds are seen in
/// the order of the code: a name that the script has read before the scope is
/// a global one.
fn the_warnings_of_the_reads_of_the_script(
    statements: &[Node],
    globals: &mut TheNames,
    warnings: &mut Vec<Warning>,
) {
    // The names that the script writes are the globals.
    let mut writes = Vec::new();
    the_writes_of_a_level(statements, &mut writes, false);
    for (name, _) in writes {
        globals.insert(name.to_lowercase());
    }
    let empty = BTreeSet::new();
    for statement in statements {
        match statement {
            Node::FunctionDef {
                body,
                declarations,
                parameters,
                ..
            } => {
                let mut own = TheNames::new();
                // The parameters are declared, and they are not names that have
                // no value.
                for parameter in parameters {
                    own.insert(parameter.name.to_lowercase());
                }
                // The names that the function writes are the locals of it.
                let mut writes = Vec::new();
                the_writes_of_a_level(body, &mut writes, false);
                for (name, _) in writes {
                    own.insert(name.to_lowercase());
                }
                let mut reads = Vec::new();
                the_reads_of_a_level(body, &mut reads);
                the_warnings_of_the_reads_of_a_scope(
                    &reads,
                    &mut own,
                    Some(&mut *globals),
                    &declarations.globals,
                    false,
                    warnings,
                );
            }
            Node::ClassDef {
                properties,
                methods,
                accessors,
                nested,
                ..
            } => {
                // The body of the class: the values of the properties are read
                // there, and the properties themselves are not variables of the
                // scope.
                let mut own = TheNames::new();
                // The `this` of a class is the value that the class holds, and
                // it is not a variable.
                //
                // Measured on the binary of v2.0.19 on 2026-11-05: the `this`
                // of the body of a class is not warned about, and the `this`
                // of a function is.
                own.insert("this".to_string());
                let mut reads = Vec::new();
                for property in properties {
                    if let Some(value) = &property.value {
                        the_reads_of_a_node(value, &mut reads);
                    }
                }
                the_warnings_of_the_reads_of_a_scope(
                    &reads,
                    &mut own,
                    Some(&mut *globals),
                    &empty,
                    false,
                    warnings,
                );
                for method in methods {
                    let mut own = TheNames::new();
                    for parameter in &method.parameters {
                        own.insert(parameter.name.to_lowercase());
                    }
                    // The `this` of a method is the value that the method was
                    // called on, and it is not a variable.
                    //
                    // Measured on the binary of v2.0.19 on 2026-11-05: the
                    // `this` of a method and the one of a static method are
                    // not warned about.
                    own.insert("this".to_string());
                    let mut writes = Vec::new();
                    the_writes_of_a_level(&method.body, &mut writes, false);
                    for (name, _) in writes {
                        own.insert(name.to_lowercase());
                    }
                    let mut reads = Vec::new();
                    the_reads_of_a_level(&method.body, &mut reads);
                    the_warnings_of_the_reads_of_a_scope(
                        &reads,
                        &mut own,
                        Some(&mut *globals),
                        &method.declarations.globals,
                        false,
                        warnings,
                    );
                }
                for accessor in accessors {
                    for (body, is_the_setter) in [
                        (accessor.getter.as_ref(), false),
                        (accessor.setter.as_ref(), true),
                    ] {
                        let Some(body) = body else { continue };
                        let mut own = TheNames::new();
                        for parameter in &accessor.parameters {
                            own.insert(parameter.name.to_lowercase());
                        }
                        // The `this` of a getter is the value that it was
                        // called on, and it is not a variable.
                        //
                        // Measured on the binary of v2.0.19 on 2026-11-05: the
                        // `this` of a getter is not warned about.
                        own.insert("this".to_string());
                        // The setter takes the value that is written after the
                        // parameters of the property, and the name of it is
                        // "value".
                        //
                        // Measured on the binary of v2.0.19 on 2026-11-05: the
                        // value of the setter is a parameter of it, and the v2
                        // does not warn about it.
                        if is_the_setter {
                            own.insert("value".to_string());
                        }
                        let mut writes = Vec::new();
                        the_writes_of_a_level(&body.body, &mut writes, false);
                        for (name, _) in writes {
                            own.insert(name.to_lowercase());
                        }
                        let mut reads = Vec::new();
                        the_reads_of_a_level(&body.body, &mut reads);
                        the_warnings_of_the_reads_of_a_scope(
                            &reads,
                            &mut own,
                            Some(&mut *globals),
                            &body.declarations.globals,
                            false,
                            warnings,
                        );
                    }
                }
                for class in nested {
                    if let Node::ClassDef { .. } = class {
                        the_warnings_of_the_reads_of_the_script(
                            core::slice::from_ref(class),
                            globals,
                            warnings,
                        );
                    }
                }
            }
            _ => {
                // The body of the script.
                let mut reads = Vec::new();
                the_reads_of_a_level(core::slice::from_ref(statement), &mut reads);
                the_warnings_of_the_reads_of_a_scope(&reads, globals, None, &empty, true, warnings);
            }
        }
    }
}

/// The warnings of the reads of a scope.
///
/// The scope is the script itself, a function, a method or the body of a
/// class. The names of the script are the globals, and the scope of a function
/// does not see the names of another function.
fn the_warnings_of_the_reads_of_a_scope(
    reads: &[(String, u32)],
    own: &mut TheNames,
    mut globals: Option<&mut TheNames>,
    declared_global: &BTreeSet<String>,
    the_script: bool,
    warnings: &mut Vec<Warning>,
) {
    for (name, line) in reads {
        let key = name.to_lowercase();
        if own.contains(&key) {
            continue;
        }
        if crate::variables::is_built_in(name) {
            continue;
        }
        // Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05: the name
        // that the script has seen is a global one.
        if let Some(globals) = globals.as_deref_mut() {
            if globals.contains(&key) {
                continue;
            }
        }
        // Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05: the name
        // that a function declares global is a global one.
        let is_global = the_script || declared_global.contains(&key);
        let message = if is_global {
            format!(
                "This global variable appears to never be assigned a value.\n     Specifically: {name}"
            )
        } else {
            format!(
                "This local variable appears to never be assigned a value.\n     Specifically: {name}"
            )
        };
        // The name is seen now, and the scope that sees it is the scope of it.
        match globals.as_deref_mut() {
            Some(globals) if is_global => globals.insert(key),
            _ => own.insert(key),
        };
        warnings.push(Warning {
            line: *line,
            message,
        });
    }
}

/// The warning of the class that a variable overwrites.
///
/// Measured on the binary of AutoHotkey v1.1.37.02 on 2026-11-05: the text of
/// it is "Class may be overwritten." and the name of the class, and it is
/// given at the line of the write that overwrites it.
pub fn the_warnings_of_the_classes_that_are_overwritten(statements: &[Node]) -> Vec<Warning> {
    let mut classes = BTreeSet::new();
    the_classes_of_the_script(statements, &mut classes);
    let mut warnings = Vec::new();
    let mut writes = Vec::new();
    the_writes_of_a_level(statements, &mut writes, true);
    for (name, line) in writes {
        if !classes.contains(&name.to_lowercase()) {
            continue;
        }
        warnings.push(Warning {
            line,
            message: format!("Class may be overwritten.\n     Specifically: {name}"),
        });
    }
    warnings
}

/// The names of the variables of the script.
///
/// The names that the script writes at its level are the variables of the
/// script, and the classes of the script are variables too.
fn the_globals_of_the_script(statements: &[Node]) -> BTreeSet<String> {
    let mut globals = BTreeSet::new();
    let mut writes = Vec::new();
    the_writes_of_a_level(statements, &mut writes, false);
    for (name, _line) in writes {
        globals.insert(name.to_lowercase());
    }
    let mut classes = BTreeSet::new();
    the_classes_of_the_script(statements, &mut classes);
    for name in classes {
        globals.insert(name);
    }
    globals
}

/// The names of the classes of the script.
fn the_classes_of_the_script(
    statements: &[Node],
    classes: &mut BTreeSet<String>,
) {
    for statement in statements {
        if let Node::ClassDef { name, .. } = statement {
            classes.insert(name.to_lowercase());
        }
        for body in the_bodies_of_the_level(statement) {
            the_classes_of_the_script(body, classes);
        }
    }
}

/// The names that the level writes, and the lines of the writes.
///
/// The names that a function writes are the locals of it, and the walk does
/// not go into the functions when the names that are wanted are the variables
/// of the script.
fn the_writes_of_a_level(statements: &[Node], writes: &mut Vec<(String, u32)>, deep: bool) {
    for statement in statements {
        match statement {
            Node::Assign { name, line, .. } => writes.push((name.clone(), *line)),
            Node::LegacyAssign { name, line, .. } => writes.push((name.clone(), *line)),
            Node::For {
                variables, line, ..
            } => {
                for name in variables {
                    writes.push((name.clone(), *line));
                }
            }
            Node::LegacyCall {
                name,
                parameters,
                line,
            } if name.eq_ignore_ascii_case("VarSet") => {
                // The `VarSet` of the v1 writes the variable of its first
                // parameter, and the parameter is a text.
                if let Some(crate::ast::LegacyParameter::Text(text)) = parameters.first() {
                    if !text.contains('%') {
                        writes.push((text.clone(), *line));
                    }
                }
            }
            _ => {}
        }
        let bodies = if deep {
            the_bodies_of(statement)
        } else {
            the_bodies_of_the_level(statement)
        };
        for body in bodies {
            the_writes_of_a_level(body, writes, deep);
        }
    }
}

/// The bodies of a statement, without the bodies of the functions.
///
/// The functions of the script have a scope of their own, and the variables
/// that they write are the locals of them.
fn the_bodies_of_the_level(statement: &Node) -> Vec<&[Node]> {
    match statement {
        Node::Block { body, .. } => vec![body],
        Node::If {
            branches,
            otherwise,
            ..
        } => {
            let mut bodies: Vec<&[Node]> = branches
                .iter()
                .map(|branch| branch.body.as_slice())
                .collect();
            bodies.push(otherwise);
            bodies
        }
        Node::Switch { cases, .. } => cases.iter().map(|case| case.body.as_slice()).collect(),
        Node::While { body, .. } => vec![body],
        Node::Loop { body, .. } => vec![body],
        Node::For { body, .. } => vec![body],
        Node::Try {
            body,
            catches,
            otherwise,
            finally,
            ..
        } => {
            let mut bodies: Vec<&[Node]> = vec![body, otherwise, finally];
            bodies.extend(catches.iter().map(|catch| catch.body.as_slice()));
            bodies
        }
        Node::LegacyIf {
            body, otherwise, ..
        } => vec![body, otherwise],
        Node::HotkeyDefinition { body, .. } => vec![body],
        _ => Vec::new(),
    }
}