ahk-cli 0.6.1

Run an ahk script on this machine: the script on stdin, the report on stdout
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
//! The runner: a script on stdin, a report on stdout.
//!
//! This is the binary that runs on the lab box. The MCP hands it a script
//! over stdin -- in memory, never a file -- and reads the report back.
//!
//! ```sh
//! echo 'Msg "hello"' | ahk
//! ```
//!
//! A script may come from a file instead: the path of the file is the one
//! argument that is not a flag, and the file is read instead of the
//! standard input.
//!
//! ```sh
//! ahk script.ahk
//! ```
//!
//! The runtime then knows the file of the script, and the `Edit` and the
//! `Reload` of v2.0.31 have a file to work with. The includes of the
//! script are resolved against the directory of the file, and the path of
//! the file is a full path, so that `A_ScriptFullPath` is one.
//!
//! The exit code is 0 when the script finished, 1 when it failed, and 2
//! when it did not parse; the report is on stdout either way.
//!
//! The `--surface` flag is the other way round: it prints the table of
//! the names of v2 with the state of each one, and it does not read a
//! script.

#![cfg_attr(windows, windows_subsystem = "windows")]

use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

use ahk_cli::{json, report};


use ahk::dialect::{self, Dialect};
use ahk::parse_with;
use ahk::runtime::Runtime;
use ahk::surface;
#[cfg(not(windows))]
use ahk_box::LabDesktop;

/// Where the runtime says it is running.
///
/// A script that types forever has to be stoppable from outside, and the
/// only thing that can stop it is the process. The pid file is how the
/// `ahk_stop` tool finds it -- and how a human finds it, with `cat`.
///
/// `XDG_CACHE_HOME` is the first choice, then the cache directory of the
/// home directory. A host with neither -- a Windows one that nobody
/// configured -- gets the temporary directory, and never the working
/// directory: the file has to be where the stop looks for it, and the
/// working directory changes from one call to the next.
fn pid_file() -> PathBuf {
    let base = match std::env::var_os("XDG_CACHE_HOME") {
        Some(base) => PathBuf::from(base),
        None => match std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
            Some(home) => PathBuf::from(home).join(".cache"),
            None => std::env::temp_dir(),
        },
    };
    base.join("ahk").join("run.pid")
}

fn write_pid_file() {
    let path = pid_file();
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let _ = std::fs::write(&path, format!("{}\n", std::process::id()));
}

fn clear_pid_file() {
    let _ = std::fs::remove_file(pid_file());
}

/// How much stack the run of a script gets.
///
/// The frames of the tree are heavier than the ones of v2, and a script
/// that recurses needs a stack that the recursion rail fits in.
const STACK_BYTES: usize = 128 * 1024 * 1024;
/// How much of that stack the run may use.
const STACK_BUDGET: usize = 64 * 1024 * 1024;

fn main() -> std::process::ExitCode {
    // A GUI-subsystem binary has no console of its own: when a terminal
    // launched it, attach to that console so the report is printed; when
    // the shell launched it (double-click / drag-drop), stay console-less.
    #[cfg(windows)]
    let has_console = the_parent_console();
    #[cfg(not(windows))]
    let has_console = true;
    // The help is answered before anything else: a host that asks for it
    // wants the usage of the runner, and not a run.
    if std::env::args()
        .skip(1)
        .any(|argument| argument == "--help" || argument == "-h")
    {
        print!("{}", the_help());
        return std::process::ExitCode::from(0);
    }
    let dialect = the_dialect();
    // The flag is answered before the script is read: the command is
    // about the tree, and it must not wait for a script that is not
    // coming.
    if std::env::args()
        .skip(1)
        .any(|argument| argument == "--surface")
    {
        // The behaviour is the call of every name that has a probe: the
        // state says what a name is, and the probe says whether it works.
        let behaviour = std::env::args()
            .skip(1)
            .any(|argument| argument == "--behavior" || argument == "--behaviour");
        // The JSON is for the CI, and the text is for a human.
        if std::env::args()
            .skip(1)
            .any(|argument| argument == "--json")
        {
            print_surface_json(dialect, behaviour);
        } else {
            print_surface(dialect, behaviour);
        }
        return std::process::ExitCode::from(0);
    }

    // The MCP server: a client debugs AHK development by reading the errors
    // of a script (check / run / surface) over JSON-RPC on stdio.
    if std::env::args().skip(1).any(|argument| argument == "--mcp") {
        ahk_cli::mcp::serve();
        return std::process::ExitCode::from(0);
    }

    // The file association: `.ahk` opens with this runner, the way the
    // original AutoHotkey64.exe is the handler of the scripts. The open
    // verb runs the script resident (--wait) so hotkeys and GUI stay alive,
    // like the original. HKCU overrides the machine association (scoop).
    if std::env::args()
        .skip(1)
        .any(|argument| argument == "--associate" || argument == "--unassociate")
    {
        let register = std::env::args().skip(1).any(|a| a == "--associate");
        return the_association(register);
    }
    let (script_raw, script_args) = the_script_path_and_args();
    let script = script_raw.map(|path| the_full_path(&path));
    let is_file = script.is_some();

    let source = match script.as_deref() {
        Some(path) => match read_script_file(path) {
            Ok(source) => source,
            Err(error) => {
                // A file that cannot be read is a failure of the load,
                // and it is reported as one.
                let error = format!("the script \"{path:?}\" cannot be read: {error}");
                let report = report::the_failure_of_the_load(&error, 0, 0);
                println!("{report}");
                return std::process::ExitCode::from(2);
            }
        },
        None => {
            let mut source = String::new();
            if let Err(error) = std::io::stdin().read_to_string(&mut source) {
                eprintln!("cannot read the script: {error}");
                return std::process::ExitCode::from(2);
            }
            source
        }
    };
    // A script run from a file lives until it ends or is stopped, the way
    // the original AutoHotkey runs it: no budget of time unless one is asked
    // for. A script on stdin keeps the bounded default of the runner.
    let timeout = std::env::args()
        .skip(1)
        .find_map(|argument| {
            argument
                .strip_prefix("--timeout=")
                .and_then(|value| value.parse::<f64>().ok())
        })
        .unwrap_or(if is_file { 0.0 } else { 60.0 });
    // A espera e' o pedido do runner: o run fica vivo depois que as
    // declaracoes do script acabam, como um script que pede para viver.
    let wait = std::env::args()
        .skip(1)
        .any(|argument| argument == "--wait");

    // The includes are resolved here and not in the language: the
    // language crate does no I/O, and the runner is the one that has a
    // disk to read from. The base is the directory of the file of the
    // script, and the working directory when the script has no file.
    let base = script
        .as_deref()
        .and_then(Path::parent)
        .unwrap_or(Path::new("."));
    let source = match resolve_includes(&source, base, script.as_deref(), &mut Vec::new()) {
        Ok(source) => source,
        Err(error) => {
            let report = report::the_failure_of_the_load(&error, 0, 0);
            println!("{report}");
            if is_file && !has_console { the_gui_error(&error.to_string()); }
            return std::process::ExitCode::from(2);
        }
    };

    // The v1 includes the library of a function the script calls but does
    // not define: the `Lib\FuncName.ahk` of the script, of the documents
    // or of the interpreter. The `BarChart` of a script of the v1 is
    // the `Lib\BarChart.ahk` that no `#Include` names.
    //
    // The tokens of the source come with it: the source is read once, and
    // the parse of the whole script reads the tokens of it instead of
    // reading the source again.
    let (source, tokens) = include_the_function_libraries(source, base, dialect);

    let parsed = match tokens {
        Some(tokens) => ahk::Parser::with_dialect(&source, tokens, dialect).parse_script(),
        None => parse_with(&source, dialect),
    };
    let statements = match parsed {
        Ok(statements) => statements,
        Err(error) => {
            let report = report::the_failure_of_the_load(&error.message, error.line, error.column);
            println!("{report}");
            if is_file && !has_console { the_gui_error(&error.message); }
            return std::process::ExitCode::from(2);
        }
    };

    // From here on, the run can be stopped from outside: the pid file says
    // which process to kill.
    write_pid_file();
    let _guard = PidGuard;

    // The path of the file of the script goes down with the run: the
    // runtime knows the file, and the `Edit` and the `Reload` of
    // v2.0.31 have a file to work with.
    let script_path = script.map(|path| path.to_string_lossy().into_owned());
    // A copy of the path for the runner itself: the run of the script takes
    // the path with it, and the runner needs it again when the script asks
    // to run again.
    let the_file = script_path.clone();

    // The script runs on a thread with a stack of its own: the tree's
    // frames are heavier than the ones of v2, and the recursion rail has
    // to fit in the stack of the run. The report is written down there,
    // because a value of the runtime is not `Send` and cannot travel.
    let handle = std::thread::Builder::new()
        .stack_size(STACK_BYTES)
        .spawn(move || {
            // `AHK_DESKTOP=x11` selects the X11 backend (XTEST + XGetImage)
            // instead of the uinput one: a FreeBSD box has no /dev/uinput,
            // and a Wayland box has no X11 focus for uinput to reach. Both
            // are the same AHK language, with a different desktop.
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            let x11 =
                ahk_box::desktop_kind().eq_ignore_ascii_case("x11") && ahk_box::x11_available();
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            let mut x11_desktop = ahk_box::x11::X11Desktop::new();
            // On a Windows machine the desktop is the one of the Windows:
            // the keyboard of `user32`, the windows of `user32` and the
            // registry of `advapi32`. The lab box is a Linux desktop, and
            // it is not there.
            #[cfg(windows)]
            let mut windows_desktop = ahk_box::windows::WindowsDesktop::new();
            #[cfg(not(windows))]
            let mut lab_desktop = LabDesktop::new();
            #[cfg(not(windows))]
            lab_desktop.ensure_session_env();
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            let desktop: &mut dyn ahk::desktop::Desktop = if x11 {
                &mut x11_desktop
            } else {
                &mut lab_desktop
            };
            #[cfg(windows)]
            let desktop: &mut dyn ahk::desktop::Desktop = &mut windows_desktop;
            #[cfg(not(any(target_os = "linux", target_os = "freebsd", windows)))]
            let desktop: &mut dyn ahk::desktop::Desktop = &mut lab_desktop;
            let mut runtime = Runtime::new(desktop, Duration::from_secs_f64(timeout))
                .with_stack_budget(STACK_BUDGET)
                .with_source(&source)
                .with_dialect(dialect);
            if wait {
                // O run e' residente: ele fica vivo depois que as
                // declaracoes do script acabam.
                runtime = runtime.with_resident(true);
            }
            if timeout <= 0.0 {
                // The `--timeout=0` says that the script is a daemon: the
                // run has no budget of time, and its output is the file
                // of the pid and the stop that reads it.
                runtime = runtime.with_no_budget(true);
            }
            // The runtime knows the file of the script when the host gave
            // one, and the `Edit` and the `Reload` of v2.0.31 have a file
            // to work with.
            if let Some(path) = script_path.as_deref() {
                runtime = runtime.with_script_path(path);
            }
            if !script_args.is_empty() {
                runtime = runtime.with_args(script_args);
            }
            let report = runtime.run_and_stay(&statements);
            #[cfg_attr(windows, allow(unused_mut))]
            let mut notes = report.notes.clone();
            #[cfg(not(windows))]
            notes.extend(lab_desktop.notes().iter().cloned());
            let payload = report::the_report(&report, &notes);
            (payload, report.ok, report.reload)
        })
        .expect("the thread of the run starts");
    let (payload, ok, reload) = match handle.join() {
        Ok(triple) => triple,
        Err(_) => {
            eprintln!("the run of the script died");
            return std::process::ExitCode::from(1);
        }
    };
    // The script asked to run again: the `Reload` of v2.0.31 starts the
    // script again in a process of its own, and this instance ends. The
    // runner is the one that owns the process, so the runner is the one
    // that starts the new instance -- with the same file and the same
    // arguments of the run.
    if reload {
        if let Some(path) = the_file.as_deref() {
            if let Err(reason) = the_script_runs_again(path) {
                eprintln!("the script did not run again: {reason}");
                return std::process::ExitCode::from(2);
            }
        }
    }
    println!("{payload}");
    if !ok && is_file && !has_console {
        let msg = the_error_of_payload(&payload).unwrap_or_else(|| "the script failed".to_string());
        the_gui_error(&msg);
    }
    // The exit code goes out through the return, and not through
    // `process::exit`: that one leaves without running the destructors, and
    // the guard that removes the pid file is a destructor.
    std::process::ExitCode::from(if ok { 0 } else { 1 })
}

/// The script runs again, in a process of its own.
///
/// The program is the runner itself -- the script of the tree is run by it
/// -- and the file of the script is the one argument: the run goes on with
/// the same file and the same arguments.
fn the_script_runs_again(script: &str) -> Result<(), String> {
    let program = std::env::current_exe()
        .map_err(|error| format!("the machine did not say what this program is: {error}"))?;
    let mut command = std::process::Command::new(program);
    command.arg(script);
    // The flags of the run are the runner's, and the runner reads them from
    // the command line: the ones that are not the file of the script are
    // carried to the new instance.
    for argument in std::env::args().skip(1) {
        if argument.starts_with('-') {
            command.arg(argument);
        }
    }
    command
        .stdin(std::process::Stdio::null())
        .spawn()
        .map(|_| ())
        .map_err(|error| format!("the machine did not start the script again: {error}"))
}

/// The file of the script, when the host gave one.
///
/// The runner reads the script from the standard input, and a host that
/// runs a file of its own names the file here: the path is the one
/// argument that is not a flag. A run with no such argument keeps the
/// behaviour of the runner that reads the standard input, and the runtime
/// has no file.
/// Attach to the console of the parent (the terminal that launched us),
/// and point the standard handles at it when they are not already set
/// (a redirection keeps its own handles). A GUI-subsystem binary otherwise
/// has no console, so a double-click or a drag-drop shows no terminal.
#[cfg(windows)]
mod ffi {
    use std::ffi::c_void;
    #[link(name = "kernel32")]
    unsafe extern "system" {
        pub fn AttachConsole(id: u32) -> i32;
        pub fn GetStdHandle(h: u32) -> *mut c_void;
        pub fn SetStdHandle(h: u32, v: *mut c_void) -> i32;
        pub fn CreateFileW(
            name: *const u16,
            access: u32,
            share: u32,
            sec: *const c_void,
            disp: u32,
            flags: u32,
            tmpl: *mut c_void,
        ) -> *mut c_void;
    }
    #[link(name = "shell32")]
    unsafe extern "system" {
        pub fn SHChangeNotify(event: i32, flags: u32, a: *const c_void, b: *const c_void);
    }
    #[link(name = "user32")]
    unsafe extern "system" {
        pub fn MessageBoxW(hwnd: *mut c_void, text: *const u16, caption: *const u16, kind: u32) -> i32;
    }
}

/// Attach to the console of the parent (the terminal that launched us),
/// and point the standard handles at it when they are not already set
/// (a redirection keeps its own handles). A GUI-subsystem binary otherwise
/// has no console, so a double-click or a drag-drop shows no terminal.
#[cfg(windows)]
fn the_parent_console() -> bool {
    const ATTACH_PARENT: u32 = u32::MAX;
    const STD_IN: u32 = -10i32 as u32;
    const STD_OUT: u32 = -12i32 as u32;
    const STD_ERR: u32 = -11i32 as u32;
    unsafe {
        if ffi::AttachConsole(ATTACH_PARENT) == 0 {
            return false; // no parent console: double-click / drag-drop, stay silent
        }
        let conout = wide("CONOUT$");
        let conin = wide("CONIN$");
        let out = ffi::CreateFileW(conout.as_ptr(), 0x4000_0000, 3, std::ptr::null(), 3, 0, std::ptr::null_mut());
        let inp = ffi::CreateFileW(conin.as_ptr(), 0x8000_0000, 3, std::ptr::null(), 3, 0, std::ptr::null_mut());
        let invalid = -1isize as *mut std::ffi::c_void;
        let h = ffi::GetStdHandle(STD_OUT);
        if (h.is_null() || h == invalid) && !out.is_null() { ffi::SetStdHandle(STD_OUT, out); }
        let h = ffi::GetStdHandle(STD_ERR);
        if (h.is_null() || h == invalid) && !out.is_null() { ffi::SetStdHandle(STD_ERR, out); }
        let h = ffi::GetStdHandle(STD_IN);
        if (h.is_null() || h == invalid) && !inp.is_null() { ffi::SetStdHandle(STD_IN, inp); }
    }
    true
}

/// In file mode with no console (double-click / drag-drop), a failure is
/// shown as a message box, the way the original AutoHotkey reports a script
/// that does not load or run.
#[cfg(windows)]
fn the_gui_error(message: &str) {
    unsafe {
        ffi::MessageBoxW(std::ptr::null_mut(), wide(message).as_ptr(), wide("ahk").as_ptr(), 0x10);
    }
}

/// A desktop that is not Windows has no message box of the machine to show
/// the failure with: the report on the standard output is the whole of it.
#[cfg(not(windows))]
fn the_gui_error(_message: &str) {}

#[cfg(windows)]
fn wide(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}

/// The `error` field of a report payload, for the message box of a failed
/// run in file mode. A naive scan of the JSON string is enough for a dialog.
fn the_error_of_payload(payload: &str) -> Option<String> {
    let at = payload.find("\"error\":\"")? + "\"error\":\"".len();
    let rest = &payload[at..];
    let mut out = String::new();
    let mut chars = rest.chars();
    while let Some(c) = chars.next() {
        match c {
            '"' => break,
            '\\' => match chars.next() {
                Some('n') => out.push('\n'),
                Some('t') => out.push('\t'),
                Some('"') => out.push('"'),
                Some('\\') => out.push('\\'),
                Some(other) => out.push(other),
                None => break,
            },
            other => out.push(other),
        }
    }
    if out.is_empty() { None } else { Some(out) }
}

fn the_association(register: bool) -> std::process::ExitCode {
    #[cfg(windows)]
    {
        let exe = std::env::current_exe()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|_| "ahk.exe".to_string());
        let reg = |args: &[&str]| -> bool {
            std::process::Command::new("reg")
                .args(args)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        };
        if register {
            let open = format!("\"{}\" \"%1\"", exe);
            let mut ok = reg(&["add", "HKCU\\Software\\Classes\\.ahk", "/ve", "/d", "ahk.Script", "/f"])
                && reg(&["add", "HKCU\\Software\\Classes\\ahk.Script", "/ve", "/d", "AutoHotkey Script (ahk rust)", "/f"])
                && reg(&["add", "HKCU\\Software\\Classes\\ahk.Script\\DefaultIcon", "/ve", "/d", &format!("{},0", exe), "/f"])
                && reg(&["add", "HKCU\\Software\\Classes\\ahk.Script\\shell\\open\\command", "/ve", "/d", &open, "/f"]);
            // The shell may still pick the progid the original installer left
            // (ahk_auto_file / AutoHotkeyScript); point their open command at
            // this runner too, so whichever it chooses runs the tree.
            for progid in ["ahk_auto_file", "AutoHotkeyScript"] {
                ok &= reg(&["add", &format!("HKCU\\Software\\Classes\\{}\\shell\\open\\command", progid), "/ve", "/d", &open, "/f"]);
            }
            if ok {
                // Windows 10/11 keeps a per-user override (UserChoice /
                // UserChoiceLatest) that wins over the classes default; drop
                // it so the .ahk default (ahk.Script) is the handler.
                let ux = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.ahk";
                reg(&["delete", &format!("{}\\UserChoice", ux), "/f"]);
                reg(&["delete", &format!("{}\\UserChoiceLatest", ux), "/f"]);
                // Tell the shell the association changed, so explorer picks
                // the new handler without a logoff.
                unsafe { ffi::SHChangeNotify(0x0800_0000, 0x1000, std::ptr::null(), std::ptr::null()); }
                println!("associated .ahk with {} (open runs resident)", exe);
                return std::process::ExitCode::from(0);
            }
            eprintln!("the association could not be written");
            return std::process::ExitCode::from(1);
        }
        let ok = reg(&["delete", "HKCU\\Software\\Classes\\.ahk", "/f"])
            & reg(&["delete", "HKCU\\Software\\Classes\\ahk.Script", "/f"]);
        println!(".ahk association removed (the machine's handler returns)");
        std::process::ExitCode::from(if ok { 0 } else { 1 })
    }
    #[cfg(not(windows))]
    {
        let _ = register;
        eprintln!("the .ahk file association is a thing of Windows");
        std::process::ExitCode::from(1)
    }
}

fn the_script_path_and_args() -> (Option<PathBuf>, Vec<String>) {
    let mut args = std::env::args().skip(1);
    let mut script = None;
    let mut script_args = Vec::new();
    for argument in args.by_ref() {
        if !argument.starts_with('-') {
            script = Some(PathBuf::from(argument));
            break;
        }
    }
    if script.is_some() {
        script_args.extend(args);
    }
    (script, script_args)
}

/// The path of the script as a full path.
///
/// An absolute path is kept as it is, and a relative one is joined with
/// the working directory: `A_ScriptFullPath` is a full path, and the
/// `Edit` and the `Reload` of v2.0.31 need one. The working directory
/// that cannot be read leaves the path as it is, and the run fails on the
/// file that is not there.
///
/// The path has the separator of the Windows, and not the one of the
/// shell that launched the runner: the host of the runner may write the
/// path with the slash, and the names of the script are the ones that
/// the v1 writes.
///
/// Measured on the binary of v1.1.37.02: the script of
/// the path "C:/Users/some/some.ahk" has the `A_ScriptFullPath` of
/// "C:\\Users\\some\\some.ahk", the `A_ScriptDir` of
/// "C:\\Users\\<user>" and the `A_ScriptName` of "some.ahk".
fn the_full_path(path: &Path) -> PathBuf {
    let path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        match std::env::current_dir() {
            Ok(directory) => directory.join(path),
            Err(_) => path.to_path_buf(),
        }
    };
    #[cfg(windows)]
    let path = PathBuf::from(path.to_string_lossy().replace('/', "\\"));
    path
}

/// The usage of the runner.
///
/// The runner has no man page, and the host that calls it is a program:
/// the usage is a few lines, and it says that the script may come from a
/// file.
fn the_help() -> String {
    let mut text = String::new();
    text.push_str("usage: ahk [flags] [script]\n");
    text.push('\n');
    text.push_str(
        "The script comes from the standard input, and the report goes to the\n\
         standard output. A path as the one argument that is not a flag names\n\
         the file of the script: the file is read instead of the standard\n\
         input, the includes are resolved against its directory, and the\n\
         runtime knows the file.\n",
    );
    text.push('\n');
    text.push_str("flags:\n");
    text.push_str("  --dialect=v1     speak the v1 dialect instead of the v2\n");
    text.push_str("  --timeout=N      stop the script after N seconds (60 by default,\n");
    text.push_str("                   and 0 means that the run has no budget of time)\n");
    text.push_str("  --wait           keep the run alive after the statements of the script end\n");
    text.push_str("  --associate      register .ahk to open with this runner (Windows)\n");
    text.push_str("  --unassociate    remove the .ahk association (Windows)\n");
    text.push_str("  --mcp            serve a Model Context Protocol server on stdio (check/run/surface/v1/diff)\n");
    text.push_str("  --surface        print the names of the dialect and the state of each\n");
    text.push_str("  --surface --json the same table, as JSON\n");
    text.push_str("  --behavior       with --surface, say whether each name works\n");
    text.push_str("  --help           print this usage\n");
    text
}

/// The dialect that the run speaks.
///
/// The v2 is the dialect of the tree, and it is the one of every run that
/// does not ask for another one. The `--dialect=v1` asks for the legacy
/// dialect of AutoHotkey, which is measured on the binary of v1.1.37.02.
fn the_dialect() -> &'static dyn Dialect {
    let asked = std::env::args().skip(1).find_map(|argument| {
        argument
            .strip_prefix("--dialect=")
            .map(|value| value.to_lowercase())
    });
    match asked.as_deref() {
        Some("v1") => dialect::v1(),
        // The mechanisms of v2.1 beside the v2.0.19: the names and the tables
        // are the ones of the v2, and the mechanisms that the v2.1 adds are the
        // ones that the gate turns on.
        Some("v2.1") | Some("v2_1") => dialect::v2_1(),
        // The dialect of KeySharp: the v2.1 mechanisms and the extensions of
        // KeySharp beside them. The refusal names the dialects the tree
        // speaks, and this one is the third of them.
        Some("ks") => dialect::ks(),
        // The KeySharp without the mechanisms of the v2.1: the two
        // switches of the dialect are orthogonal, and this is the fourth
        // combination of them.
        Some("ks20") | Some("ks2.0") => dialect::ks_20(),
        Some("v2") | None => dialect::v2(),
        Some(other) => {
            eprintln!(
                "the dialect {other} is not one this tree speaks: the tree speaks v1, v2, v2.1, ks and ks20."
            );
            std::process::exit(2);
        }
    }
}

/// Print the surface of v2 and where every name of it stands here.
///
/// The report is a line for every name of the surface and a summary at
/// the end: the number is the point of the command, and it is what makes
/// "what is missing" a measurement and not an opinion.
fn print_surface(dialect: &'static dyn Dialect, behaviour: bool) {
    let entries = surface::entries_of(dialect);
    let mut out = String::new();
    for entry in &entries {
        out.push_str(&entry.line());
        if behaviour {
            if let Some(answer) = ahk::behavior::behaviour_of(dialect, &entry.full_name()) {
                out.push_str("\tbehaviour=");
                out.push_str(&answer);
            }
        }
        out.push('\n');
    }
    out.push_str(&surface::summary_of(&entries, dialect).text());
    out.push('\n');
    print!("{out}");
}

/// Print the surface of the dialect as JSON.
///
/// The text of the surface is for a human, and the JSON is for the CI: the
/// numbers of the summary and the state of every name, with the reason of
/// the ones that are refused or that are pending.
///
/// The plan of the v1 dialect asks for this shape: "the JSON, for the CI,
/// is a piece of F5".
fn print_surface_json(dialect: &'static dyn Dialect, behaviour: bool) {
    let entries = surface::entries_of(dialect);
    let summary = surface::summary_of(&entries, dialect);
    let mut report = json::Object::new(64 * 1024);
    report.text("dialect", summary.dialect);
    report.number("total", summary.total as i64);
    report.number("values", summary.values as i64);
    report.number("refusals", summary.refusals as i64);
    report.number("pending", summary.pending as i64);
    report.field("entries", |out| {
        out.push('[');
        for (index, entry) in entries.iter().enumerate() {
            if index > 0 {
                out.push(',');
            }
            let mut row = json::Object::new(96);
            row.text("name", entry.name);
            row.text("kind", entry.kind.as_str());
            row.text(
                "state",
                match entry.state {
                    surface::State::Value => "value",
                    surface::State::Refusal(_) => "refusal",
                    surface::State::Pending(_) => "pending",
                },
            );
            if !entry.class.is_empty() {
                row.text("class", entry.class);
            }
            if let surface::State::Refusal(reason) | surface::State::Pending(reason) = entry.state {
                row.text("reason", reason);
            }
            if behaviour {
                if let Some(answer) = ahk::behavior::behaviour_of(dialect, &entry.full_name()) {
                    row.text("behavior", &answer);
                }
            }
            out.push_str(&row.finish());
        }
        out.push(']');
    });
    println!("{}", report.finish());
}

/// The source with the includes put in place of the lines that ask for
/// them.
///
/// A `#Include "path"` line is replaced by the text of the file, and the
/// path is taken from the directory of the file that asks for it. An
/// include that is already in the tree is not put in twice; the
/// `#IncludeAgain` line puts its file in every time it asks for it, which
/// is the difference between the two directives.
///
/// The nesting is counted: a file that includes itself, or a group of files
/// that include one another, is refused with the reason instead of making
/// the runner recurse until the stack is gone.
fn resolve_includes(
    source: &str,
    base: &Path,
    file: Option<&Path>,
    seen: &mut Vec<PathBuf>,
) -> Result<String, String> {
    resolve_includes_at(source, base, file, seen, 0)
}

/// How deep the includes may nest.
const MAX_INCLUDE_DEPTH: usize = 64;

/// `resolve_includes`, with the depth of the nesting the tree is in.
fn resolve_includes_at(
    source: &str,
    base: &Path,
    file: Option<&Path>,
    seen: &mut Vec<PathBuf>,
    depth: usize,
) -> Result<String, String> {
    if depth > MAX_INCLUDE_DEPTH {
        return Err(format!(
            "the includes nest more than {MAX_INCLUDE_DEPTH} deep: a file includes itself, or a group of them includes one another."
        ));
    }
    let mut out = String::with_capacity(source.len());
    for line in source.lines() {
        let Some((again, argument)) = the_include_of(line) else {
            out.push_str(line);
            out.push('\n');
            continue;
        };
        // `*i` asks for the include to be skipped when the file is not
        // there, the way the directive of the reference does.
        let (ignore_missing, argument) = match argument.strip_prefix('*') {
            Some(rest) => {
                let end = rest
                    .find(|character: char| character.is_whitespace())
                    .unwrap_or(rest.len());
                let (option, rest) = rest.split_at(end);
                if !option.eq_ignore_ascii_case("i") {
                    return Err(format!("the include option \"*{option}\" is not one this tree speaks."));
                }
                (true, rest.trim())
            }
            None => (false, argument),
        };
        // A comment may follow the path; it is not part of it.
        let argument = strip_include_comment(argument);
        // The path is in quotes, or it is the rest of the line.
        let path = argument
            .strip_prefix('"')
            .and_then(|rest| rest.strip_suffix('"'))
            .unwrap_or(argument)
            .trim();
        if path.is_empty() {
            return Err("an include needs a path.".to_string());
        }
        let script_dir = absolute_dir(base);
        let line_file = file
            .map(|path| path.to_string_lossy().into_owned())
            .unwrap_or_else(|| "*".to_string());
        let path = if path.starts_with('<') && path.ends_with('>') {
            // `<Lib>` is the library include: the Lib folders of the
            // script, of the documents and of the interpreter are searched.
            match find_library(&path[1..path.len() - 1], &script_dir) {
                Some(path) => path,
                None if ignore_missing => {
                    out.push('\n');
                    continue;
                }
                None => return Err(format!("the include \"{path}\" cannot be found.")),
            }
        } else {
            let expanded = expand_include_vars(path, &script_dir, &line_file);
            base.join(expanded)
        };
        let path = match path.canonicalize() {
            Ok(path) => path,
            Err(_) if ignore_missing => {
                out.push('\n');
                continue;
            }
            Err(_) => return Err(format!("the include \"{path:?}\" cannot be found.")),
        };
        if !again && seen.contains(&path) {
            // The file is already in the tree, and `#Include` puts it in
            // once: the line becomes nothing.
            out.push('\n');
            continue;
        }
        let text = read_script_file(&path)
            .map_err(|error| format!("the include \"{path:?}\" cannot be read: {error}"))?;
        let directory = path.parent().unwrap_or(Path::new(".")).to_path_buf();
        // The file is in the tree now, and a later `#Include` of it is
        // skipped. `#IncludeAgain` ignores this list and asks again.
        if !seen.contains(&path) {
            seen.push(path.clone());
        }
        out.push_str(&resolve_includes_at(&text, &directory, Some(&path), seen, depth + 1)?);
        out.push('\n');
    }
    Ok(out)
}

/// The text of a script file, the way the reference reads it: a BOM names
/// the encoding, and a file without one is UTF-8 when it can be and the
/// ANSI code page of the machine when it cannot.
fn read_script_file(path: &Path) -> Result<String, String> {
    let bytes = std::fs::read(path).map_err(|error| error.to_string())?;
    Ok(decode_script_bytes(&bytes))
}

/// The bytes of a script as text: UTF-8 or UTF-16 when a BOM says so, and
/// otherwise UTF-8 first, the ANSI code page second.
fn decode_script_bytes(bytes: &[u8]) -> String {
    if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
        return String::from_utf8_lossy(rest).into_owned();
    }
    if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
        return decode_utf16(rest, true);
    }
    if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
        return decode_utf16(rest, false);
    }
    match std::str::from_utf8(bytes) {
        Ok(text) => text.to_string(),
        Err(_) => decode_ansi(bytes),
    }
}

/// UTF-16 as text, little or big endian, an unpaired surrogate replaced.
fn decode_utf16(bytes: &[u8], little: bool) -> String {
    let units: Vec<u16> = bytes
        .chunks_exact(2)
        .map(|pair| {
            if little {
                u16::from_le_bytes([pair[0], pair[1]])
            } else {
                u16::from_be_bytes([pair[0], pair[1]])
            }
        })
        .collect();
    char::decode_utf16(units)
        .map(|result| result.unwrap_or('\u{FFFD}'))
        .collect()
}

/// The ANSI code page of the machine. On Windows it is the one the system
/// answers for (`GetACP`), and the conversion is the system's own; elsewhere
/// it is CP1252, the page the dialect was measured on.
fn decode_ansi(bytes: &[u8]) -> String {
    #[cfg(windows)]
    {
        unsafe extern "system" {
            fn GetACP() -> u32;
            fn MultiByteToWideChar(
                code_page: u32,
                flags: u32,
                text: *const u8,
                text_len: i32,
                wide: *mut u16,
                wide_len: i32,
            ) -> i32;
        }
        // SAFETY: the bytes are a live slice for the length passed, and the
        // wide buffer is sized by the first call that asks for the size.
        unsafe {
            let page = GetACP();
            let len = bytes.len() as i32;
            let needed = MultiByteToWideChar(page, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0);
            if needed > 0 {
                let mut wide = vec![0u16; needed as usize];
                let written = MultiByteToWideChar(
                    page,
                    0,
                    bytes.as_ptr(),
                    len,
                    wide.as_mut_ptr(),
                    needed,
                );
                if written > 0 {
                    wide.truncate(written as usize);
                    return char::decode_utf16(wide)
                        .map(|result| result.unwrap_or('\u{FFFD}'))
                        .collect();
                }
            }
        }
        String::from_utf8_lossy(bytes).into_owned()
    }
    #[cfg(not(windows))]
    {
        const HIGH: [char; 32] = [
            '\u{20AC}', '\u{0081}', '\u{201A}', '\u{0192}', '\u{201E}', '\u{2026}',
            '\u{2020}', '\u{2021}', '\u{02C6}', '\u{2030}', '\u{0160}', '\u{2039}',
            '\u{0152}', '\u{008D}', '\u{017D}', '\u{008F}', '\u{0090}', '\u{2018}',
            '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}',
            '\u{02DC}', '\u{2122}', '\u{0161}', '\u{203A}', '\u{0153}', '\u{009D}',
            '\u{017E}', '\u{0178}',
        ];
        bytes
            .iter()
            .map(|&byte| {
                if byte < 0x80 {
                    byte as char
                } else if byte < 0xA0 {
                    HIGH[(byte - 0x80) as usize]
                } else {
                    byte as char
                }
            })
            .collect()
    }
}

/// The libraries of the functions the script calls but does not define.
///
/// The v1 searches the `Lib` folder for the `FuncName.ahk` of a call that
/// has no function, and includes it. The runner does the same: it reads
/// the names the parse leaves undefined, includes the library of each,
/// and reads again until no new library is found.
///
/// The source comes back with the tokens of it: the source is lexed once
/// for the names, and the parse of the whole script reads the tokens
/// instead of reading the source again. The tokens are `None` when the
/// source does not lex -- the parse of the whole script is the one that
/// says so -- and when the loop ends without a library to add.
fn include_the_function_libraries(
    mut source: String,
    base: &Path,
    dialect: &'static dyn Dialect,
) -> (String, Option<Vec<ahk::lexer::Token>>) {
    let script_dir = absolute_dir(base);
    let mut seen: Vec<PathBuf> = Vec::new();
    for _ in 0..64 {
        // The names the script calls but does not define. The source is
        // lexed once here, and the tokens of it are the ones of the parse
        // of the whole script.
        let (missing, lexed) = match ahk::lexer::tokenize_with(&source, dialect) {
            Ok(lexed) => {
                let (missing, lexed) =
                    ahk::parser::the_undefined_functions_of_the_tokens(&source, lexed, dialect);
                (missing, Some(lexed))
            }
            // The source does not lex: there is no name to look for, and
            // the parse of the whole script is the one that says so.
            Err(_) => (Vec::new(), None),
        };
        let mut added = false;
        for name in missing {
            let Some(path) = find_library(&name, &script_dir) else {
                continue;
            };
            let canon = path.canonicalize().unwrap_or_else(|_| path.clone());
            if seen.contains(&canon) {
                continue;
            }
            seen.push(canon);
            let Ok(text) = read_script_file(&path) else {
                continue;
            };
            let directory = path.parent().unwrap_or(Path::new(".")).to_path_buf();
            let resolved =
                resolve_includes(&text, &directory, Some(&path), &mut Vec::new()).unwrap_or(text);
            source.push('\n');
            source.push_str(&resolved);
            added = true;
        }
        if !added {
            // The source is the one the tokens are of.
            return (source, lexed);
        }
    }
    // The loop ended with the source changed: the tokens are of the source
    // before the last library, and the parse of the whole script reads the
    // source again.
    (source, None)
}

/// The directory as an absolute path, without the `\\?\` prefix that
/// `canonicalize` puts on Windows: the expanded `%A_ScriptDir%` is a path
/// the script itself may compare against.
fn absolute_dir(base: &Path) -> PathBuf {
    if base.is_absolute() {
        base.to_path_buf()
    } else {
        match std::env::current_dir() {
            Ok(directory) => directory.join(base),
            Err(_) => base.to_path_buf(),
        }
    }
}

/// The comment that follows an include path: a `;` at the start of the
/// argument or after a space, outside quotes, begins it.
fn strip_include_comment(argument: &str) -> &str {
    let mut quoted = false;
    let mut previous = ' ';
    for (index, character) in argument.char_indices() {
        if character == '"' {
            quoted = !quoted;
        } else if character == ';' && !quoted && previous.is_whitespace() {
            return argument[..index].trim_end();
        }
        previous = character;
    }
    argument
}

/// The built-in variables an include path may reference, expanded the way
/// the reference expands them. A reference that is not one of them is left
/// as it is.
fn expand_include_vars(path: &str, script_dir: &Path, line_file: &str) -> String {
    let mut out = String::with_capacity(path.len());
    let mut rest = path;
    while let Some(start) = rest.find('%') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        let Some(end) = after.find('%') else {
            out.push('%');
            rest = after;
            continue;
        };
        let name = &after[..end];
        let value = match name.to_ascii_lowercase().as_str() {
            "a_scriptdir" => Some(script_dir.to_string_lossy().into_owned()),
            "a_linefile" => Some(line_file.to_string()),
            "a_appdata" => std::env::var("APPDATA").ok(),
            "a_appdatacommon" => std::env::var("PROGRAMDATA").ok(),
            "a_mydocuments" => std::env::var("USERPROFILE")
                .ok()
                .map(|home| format!("{home}\\Documents")),
            _ => None,
        };
        match value {
            Some(value) => out.push_str(&value),
            None => {
                out.push('%');
                out.push_str(name);
                out.push('%');
            }
        }
        rest = &after[end + 1..];
    }
    out.push_str(rest);
    out
}

/// The library include `<Name>`: the Lib folder of the script, then the
/// one of the documents, then the one beside the interpreter. A name with
/// a backslash asks for a function of a library: `Lib\Func` looks for
/// `Lib\Func.ahk` and then for `Lib.ahk`.
fn find_library(name: &str, script_dir: &Path) -> Option<PathBuf> {
    let mut roots = vec![script_dir.join("Lib")];
    if let Ok(home) = std::env::var("USERPROFILE") {
        roots.push(PathBuf::from(home).join("Documents\\AutoHotkey\\Lib"));
    }
    if let Ok(exe) = std::env::current_exe() {
        if let Some(directory) = exe.parent() {
            roots.push(directory.join("Lib"));
        }
    }
    let (library, function) = match name.split_once('\\') {
        Some((library, function)) => (library, Some(function)),
        None => (name, None),
    };
    for root in roots {
        if let Some(function) = function {
            let path = root.join(library).join(format!("{function}.ahk"));
            if path.is_file() {
                return Some(path);
            }
        }
        let path = root.join(format!("{library}.ahk"));
        if path.is_file() {
            return Some(path);
        }
    }
    None
}

/// The include that the line asks for: whether it is `#IncludeAgain`, and
/// its argument.
///
/// The directive is matched by its whole name, because `#Include` is a
/// prefix of `#IncludeAgain` and the two are not the same line. A line
/// whose directive is neither is a line of the script, and it is left as it
/// is.
fn the_include_of(line: &str) -> Option<(bool, &str)> {
    let trimmed = line.trim();
    let rest = trimmed.strip_prefix('#')?;
    let end = rest
        .find(|character: char| character.is_whitespace())
        .unwrap_or(rest.len());
    let (name, argument) = rest.split_at(end);
    let again = if name.eq_ignore_ascii_case("include") {
        false
    } else if name.eq_ignore_ascii_case("includeagain") {
        true
    } else {
        return None;
    };
    Some((again, argument.trim()))
}

/// Removes the pid file when the run ends, however it ends.
struct PidGuard;

impl Drop for PidGuard {
    fn drop(&mut self) {
        clear_pid_file();
    }
}