ahk 0.5.0

The ahk language: a lexer, an AST, a parser and an interpreter for AutoHotkey-style scripts
Documentation
//! The callbacks of the machine: `RegisterCallback`.
//!
//! A callback is an address the machine calls, and the call runs a
//! function of the script. The tree makes the address out of a pool of
//! trampolines: each one is a function of the machine that knows its
//! place in the pool, and the place names the function of the script.
//!
//! The call of the machine arrives while a `DllCall` runs: the runtime
//! is kept in a place of the thread while the native call goes on, and
//! the trampoline reads it back to run the function. The callback runs
//! on the thread of the script, the one that makes the `DllCall`; a
//! callback the machine calls on another thread finds no runtime and
//! answers zero.
//!
//! The re-entry is the one of a callback of a foreign interface: the
//! native call is blocked while the callback runs, and the runtime is
//! not used by the caller until the call comes back. The pointer is
//! read back only for the time of the call.

use alloc::string::{String, ToString};
use alloc::vec::Vec;
use std::cell::Cell;
use std::sync::Mutex;

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

/// The most callbacks the pool carries.
const THE_SLOTS: usize = 64;

/// One registered callback: the function of the script and the number of
/// parameters it takes.
struct Entry {
    name: String,
    params: usize,
    func: Option<Value>,
}

/// The pool of the callbacks, by their place.
static REGISTRY: Mutex<Vec<Option<Entry>>> = Mutex::new(Vec::new());

thread_local! {
    /// The runtime of the thread, while a native call goes on. It is a
    /// pointer and not a reference: the callback reads it back while the
    /// caller is blocked in the native call.
    static CURRENT: Cell<*mut ()> = const { Cell::new(std::ptr::null_mut()) };
}

/// Keep the runtime of the thread for the time of a native call, and
/// answer the place that was there before.
///
/// A call inside a call keeps the outer place: the monitor of a message
/// makes a `DllCall` while a modal dialog pumps, and the runtime has to
/// stay kept when the inner call comes back -- the box goes on pumping.
pub fn set_current(rt: &mut Runtime<'_>) -> usize {
    CURRENT.with(|cell| {
        let previous = cell.get();
        cell.set(rt as *mut Runtime<'_> as *mut ());
        previous as usize
    })
}

/// Give the thread back the place it had before the call.
pub fn clear_current(previous: usize) {
    CURRENT.with(|cell| cell.set(previous as *mut ()));
}

/// A message of the machine arrived while the runtime of the thread is
/// kept (a modal dialog pumps the messages of the thread): the handler
/// `OnMessage` registered for it runs now, and the number it answers is
/// the answer of the window procedure. When nothing is kept, or no
/// handler is registered, the message goes to the procedure of the
/// machine.
pub fn the_message_runs(msg: i64, wparam: i64, lparam: i64, hwnd: i64) -> Option<i64> {
    let ptr = CURRENT.with(|cell| cell.get());
    if ptr.is_null() {
        return None;
    }
    // The runtime is read back for the time of the call only: the caller
    // is blocked in the modal call and does not use it until it returns.
    let rt = unsafe { &mut *(ptr as *mut Runtime<'static>) };
    rt.the_message_runs(msg, wparam, lparam, hwnd)
}

/// Register a callback and answer the address the machine calls.
///
/// The address is the trampoline of a place of the pool; the place keeps
/// the function of the script. The answer is zero when the pool is full.
pub fn register(name: &str, params: usize) -> usize {
    let mut registry = match REGISTRY.lock() {
        Ok(registry) => registry,
        Err(_) => return 0,
    };
    let slot = match registry.iter().position(|entry| entry.is_none()) {
        Some(slot) => slot,
        None => {
            if registry.len() >= THE_SLOTS {
                return 0;
            }
            registry.push(None);
            registry.len() - 1
        }
    };
    registry[slot] = Some(Entry {
        name: name.to_string(),
        params,
        func: None,
    });
    THE_TRAMPOLINES[slot] as usize
}

/// `CallbackCreate`: register a function value (not only a name) and answer
/// the callable address of a trampoline of the pool.
pub fn register_value(func: Value, params: usize) -> usize {
    let mut registry = match REGISTRY.lock() {
        Ok(registry) => registry,
        Err(_) => return 0,
    };
    let slot = match registry.iter().position(|entry| entry.is_none()) {
        Some(slot) => slot,
        None => {
            if registry.len() >= THE_SLOTS {
                return 0;
            }
            registry.push(None);
            registry.len() - 1
        }
    };
    registry[slot] = Some(Entry {
        name: String::new(),
        params,
        func: Some(func),
    });
    THE_TRAMPOLINES[slot] as usize
}

/// `CallbackFree`: let a place of the pool go.
pub fn free(address: usize) {
    if let Some(slot) = THE_TRAMPOLINES.iter().position(|&t| t as usize == address) {
        if let Ok(mut registry) = REGISTRY.lock() {
            if let Some(entry) = registry.get_mut(slot) {
                *entry = None;
            }
        }
    }
}

/// Run the function of a place of the pool with the arguments of the
/// machine.
///
/// The arguments are the numbers the machine put in the registers of
/// the call; the function takes as many as it was registered with. The
/// answer is the number the function answers.
fn invoke(slot: usize, args: [usize; 4]) -> usize {
    let ptr = CURRENT.with(|cell| cell.get());
    if ptr.is_null() {
        return 0;
    }
    let entry = {
        let registry = match REGISTRY.lock() {
            Ok(registry) => registry,
            Err(_) => return 0,
        };
        match registry.get(slot).and_then(|entry| entry.as_ref()) {
            Some(entry) => Entry {
                name: entry.name.clone(),
                params: entry.params,
                func: entry.func.clone(),
            },
            None => return 0,
        }
    };
    // The runtime is read back for the time of the call only: the caller
    // is blocked in the native call and does not use it until the call
    // comes back.
    let rt = unsafe { &mut *(ptr as *mut Runtime<'static>) };
    let values: Vec<Value> = args
        .iter()
        .take(entry.params)
        .map(|&arg| Value::Int(arg as i64))
        .collect();
    let answer = if let Some(func) = &entry.func {
        rt.the_callback_runs(func, &values)
    } else {
        rt.call_named(&entry.name, &values, 0, crate::runtime::Route::Written)
            .map_err(|failure| crate::runtime::as_error(failure, 0))
    };
    match answer {
        Ok(value) => value.to_number().unwrap_or(0.0) as usize,
        Err(_) => 0,
    }
}

/// The trampoline of a place of the pool: it knows its place, and the
/// place names the function of the script.
extern "C" fn trampoline<const SLOT: usize>(
    a0: usize,
    a1: usize,
    a2: usize,
    a3: usize,
) -> usize {
    invoke(SLOT, [a0, a1, a2, a3])
}

macro_rules! trampoline_array {
    ($($index:literal),* $(,)?) => {
        static THE_TRAMPOLINES: [extern "C" fn(usize, usize, usize, usize) -> usize; THE_SLOTS] = [
            $(trampoline::<$index>,)*
        ];
    };
}

trampoline_array!(
    0, 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,
);