ahk-cli 0.5.0

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
//! 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};

mod mcp;

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") {
        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 = the_script_path().map(|path| the_full_path(&path));
    let is_file = script.is_some();

    let source = match script.as_deref() {
        Some(path) => match std::fs::read_to_string(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
        }
    };
    let timeout = std::env::args()
        .skip(1)
        .find_map(|argument| {
            argument
                .strip_prefix("--timeout=")
                .and_then(|value| value.parse::<f64>().ok())
        })
        .unwrap_or(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, &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);
        }
    };

    let statements = match parse_with(&source, dialect) {
        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);
            }
            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() -> Option<PathBuf> {
    std::env::args()
        .skip(1)
        .find(|argument| !argument.starts_with('-'))
        .map(PathBuf::from)
}

/// 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.
fn the_full_path(path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        match std::env::current_dir() {
            Ok(directory) => directory.join(path),
            Err(_) => path.to_path_buf(),
        }
    }
}

/// 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)\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, seen: &mut Vec<PathBuf>) -> Result<String, String> {
    resolve_includes_at(source, base, 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,
    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;
        };
        // 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 path = base.join(path);
        let path = match path.canonicalize() {
            Ok(path) => path,
            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 = std::fs::read_to_string(&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);
        }
        out.push_str(&resolve_includes_at(&text, &directory, seen, depth + 1)?);
        out.push('\n');
    }
    Ok(out)
}

/// 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();
    }
}