ahk 0.5.0

The ahk language: a lexer, an AST, a parser and an interpreter for AutoHotkey-style scripts
Documentation
//! The menus of the v1, and the names that they have.
//!
//! The v1 has the `Menu` as a command, and a menu is a thing with a name:
//! the `Menu, MyMenu, Add, Item` makes a menu that is called `MyMenu`, and
//! the `MenuGetHandle` and the `MenuGetName` are the two ways of asking
//! about it.
//!
//! The v2 has the `Menu` as a class, and a script holds the object of it.
//! The tree keeps the menus of the v1 in the runtime, by their names, so
//! that the two dialects agree about the menu that a name means.
//!
//! Measured on the binary of v1.1.37.02 on 2026-11-14:
//!
//! - the `Menu, MyMenu, Add, Item` makes a menu that is called `MyMenu`;
//! - the `MenuGetHandle("MyMenu")` answers the number that names it;
//! - the `MenuGetName` of that number answers the name `MyMenu`;
//! - the `MenuGetHandle` of a menu that is not there throws.

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

use crate::runtime::{Runtime, RuntimeError, Value};

/// The failure of a menu that is not there.
const NO_MENU: &str = "Target menu not found.";

/// The first number that names a menu of the v1.
///
/// The number of a menu is the handle of it, and the handles of the
/// machine are numbers that grow.
const THE_FIRST_HANDLE: u64 = 0x1_0000;

/// An item of a menu of the v1.
pub(crate) struct TheItem {
    /// The name of the item, as the script wrote it.
    pub(crate) name: String,
    /// The name of the function of the script that choosing it runs.
    pub(crate) callback: String,
    /// Whether the item carries a mark.
    pub(crate) checked: bool,
    /// Whether the item can be chosen.
    pub(crate) enabled: bool,
}

/// A menu of the v1.
pub(crate) struct TheMenu {
    /// The name that the script gave it.
    pub(crate) name: String,
    /// The number that names it.
    pub(crate) handle: u64,
    /// The items of it, in the order of the script.
    pub(crate) items: Vec<TheItem>,
    /// The item that the menu takes when the window of the script is
    /// activated.
    pub(crate) default: Option<String>,
}

/// The menus of the script, by their names.
fn the_menus<'a>(rt: &'a mut Runtime<'_>) -> &'a mut Vec<TheMenu> {
    rt.the_menus_of_the_v1()
}

/// The menu of this name, made when it is not there yet.
///
/// The list of the menus grows when the menu is made, and that is why the
/// parameter is the list and not a slice of it.
#[allow(clippy::ptr_arg)]
fn the_menu_of_the_name<'a>(menus: &'a mut Vec<TheMenu>, name: &str) -> &'a mut TheMenu {
    let wanted = name.to_lowercase();
    if let Some(index) = menus
        .iter()
        .position(|menu| menu.name.to_lowercase() == wanted)
    {
        return &mut menus[index];
    }
    // The menu is made when it is first used, and the handle of it is a
    // number that the machine has not given yet.
    let handle = THE_FIRST_HANDLE + menus.len() as u64;
    menus.push(TheMenu {
        name: name.to_string(),
        handle,
        items: Vec::new(),
        default: None,
    });
    let last = menus.len() - 1;
    &mut menus[last]
}

/// The menu of this name, when it is there.
///
/// The `MenuGetHandle` of a menu that is not there throws, and the
/// `Menu, MyMenu, Add, Item` makes the menu when it is not there yet.
#[allow(clippy::ptr_arg)]
fn the_menu_that_is_there<'a>(
    menus: &'a mut Vec<TheMenu>,
    name: &str,
) -> Option<&'a mut TheMenu> {
    let wanted = name.to_lowercase();
    menus
        .iter_mut()
        .find(|menu| menu.name.to_lowercase() == wanted)
}

/// The failure of a menu that is not there.
fn the_failure_of_a_menu_that_is_not_there(line: u32) -> RuntimeError {
    RuntimeError {
        message: NO_MENU.to_string(),
        line,
    }
}

/// The item of a menu, when the menu has it.
fn the_item<'a>(menu: &'a mut TheMenu, item: &str) -> Option<&'a mut TheItem> {
    menu.items
        .iter_mut()
        .find(|held| held.name.eq_ignore_ascii_case(item))
}

/// `Menu, MyMenu, Add, Item, Callback`: an item of a menu of the script.
pub(crate) fn add_item(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    callback: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    // The item of a menu of the v1 is the name of it, and what choosing
    // it does is the name of the function of the script.
    menu.items.push(TheItem {
        name: item.to_string(),
        callback: callback.to_string(),
        checked: false,
        enabled: true,
    });
    let _ = line;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, Insert, Item, Callback, Options`: an item of a menu of the
/// script, above the last one.
///
/// The v1 has no place for the item: it goes above the last item of the
/// menu, and it is the only one when the menu is empty.
pub(crate) fn insert_item(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    callback: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    let held = TheItem {
        name: item.to_string(),
        callback: callback.to_string(),
        checked: false,
        enabled: true,
    };
    let at = menu.items.len().saturating_sub(1);
    menu.items.insert(at, held);
    let _ = line;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, Delete, Item`: the removal of an item of a menu.
pub(crate) fn delete_item(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    let before = menu.items.len();
    menu.items
        .retain(|held| !held.name.eq_ignore_ascii_case(item));
    if menu.items.len() == before {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    }
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, DeleteAll`: the removal of every item of a menu.
pub(crate) fn delete_all(
    rt: &mut Runtime<'_>,
    name: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    if menu.items.is_empty() {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    }
    menu.items.clear();
    menu.default = None;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, Enable, Item` and `Menu, MyMenu, Disable, Item`: whether
/// an item of a menu can be chosen.
pub(crate) fn set_enabled(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    on: bool,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    let Some(held) = the_item(menu, item) else {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    };
    held.enabled = on;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, ToggleEnable, Item`: whether an item of a menu can be
/// chosen, the other way round.
pub(crate) fn toggle_enabled(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    let Some(held) = the_item(menu, item) else {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    };
    held.enabled = !held.enabled;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, Check, Item` and `Menu, MyMenu, Uncheck, Item`: whether
/// an item of a menu carries a mark.
pub(crate) fn set_checked(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    checked: bool,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    let Some(held) = the_item(menu, item) else {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    };
    held.checked = checked;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, ToggleCheck, Item`: whether an item of a menu carries a
/// mark, the other way round.
pub(crate) fn toggle_checked(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    let Some(held) = the_item(menu, item) else {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    };
    held.checked = !held.checked;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, Default, Item`: the item that a menu takes when the
/// window of the script is activated.
pub(crate) fn set_default(
    rt: &mut Runtime<'_>,
    name: &str,
    item: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    if the_item(menu, item).is_none() {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    }
    menu.default = Some(item.to_string());
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, NoDefault`: the menu that takes no item when the window
/// of the script is activated.
pub(crate) fn no_default(
    rt: &mut Runtime<'_>,
    name: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    menu.default = None;
    let _ = line;
    Ok(Value::Text(String::new()))
}

/// `Menu, MyMenu, Rename, NewName, OldName`: the new name of an item of a
/// menu.
pub(crate) fn rename_item(
    rt: &mut Runtime<'_>,
    name: &str,
    old: &str,
    new: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    let menu = the_menu_of_the_name(menus, name);
    let Some(held) = the_item(menu, old) else {
        return Err(the_failure_of_a_menu_that_is_not_there(line));
    };
    held.name = new.to_string();
    Ok(Value::Text(String::new()))
}

/// `MenuGetHandle(MenuName)`: the number that names a menu of the script.
pub(crate) fn the_handle_of(
    rt: &mut Runtime<'_>,
    name: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let menus = the_menus(rt);
    for menu in menus.iter() {
        if menu.name.eq_ignore_ascii_case(name) {
            return Ok(Value::Int(menu.handle as i64));
        }
    }
    Err(the_failure_of_a_menu_that_is_not_there(line))
}

/// `MenuGetName(Handle)`: the name of a menu of the script.
pub(crate) fn the_name_of(
    rt: &mut Runtime<'_>,
    handle: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    let wanted = handle.trim();
    let menus = the_menus(rt);
    for menu in menus.iter() {
        if wanted == menu.handle.to_string() {
            return Ok(Value::Text(menu.name.clone()));
        }
    }
    Err(the_failure_of_a_menu_that_is_not_there(line))
}

/// The items of a menu of the script, in the JSON that the desktop wants.
///
/// The desktop takes an array of `[name, checked, enabled, callback]`, and
/// the callback is left out when the item has none.
///
/// The menu that is not there is an empty bar: the tree has no menu bar
/// without a menu, and the bar of nothing is nothing.
pub(crate) fn the_items_of_the_menu(rt: &mut Runtime<'_>, name: &str) -> String {
    let menus = the_menus(rt);
    let Some(menu) = the_menu_that_is_there(menus, name) else {
        return String::from("[]");
    };
    let mut json = String::from("[");
    for (index, item) in menu.items.iter().enumerate() {
        if index > 0 {
            json.push(',');
        }
        json.push('[');
        json.push_str(&the_json_text(&item.name));
        json.push_str(&format!(",{},{}", item.checked, item.enabled));
        if !item.callback.is_empty() {
            json.push(',');
            json.push_str(&the_json_text(&item.callback));
        }
        json.push(']');
    }
    json.push(']');
    json
}

/// The text of the JSON, with the quotes and the escapes of it.
fn the_json_text(text: &str) -> String {
    let mut out = String::from("\"");
    for character in text.chars() {
        match character {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            other => out.push(other),
        }
    }
    out.push('"');
    out
}