Files
sakurac/core/traits/invokable.sakura
T

45 lines
2.0 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
#! @file invokable.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the invokable trait, which a type implements to be called as a
#! function is, `f(args)`, and which every function is.
module core;
#! What is called as a function of a signature: a function value, the address of
#! a C function, or a value of a type with an `invoke` taking the arguments.
#!
#! The trait is given the signature whole, as `invokable<def(i64, bool): u8>`,
#! whose parameter types it names `Ts` and whose result `R`, so `invoke` takes a
#! parameter of each of the types, as `def adder::invoke(&mut this, a: i64, b:
#! bool): u8` does. A variadic signature, as `def(i64...): i64`, asks for a
#! variadic `invoke`. Generic code over any signature names it through a type
#! parameter bounded by `signature`, as `invokable<F>`.
#!
#! A call of a value whose type is no function, `f(1, true)`, calls its `invoke`,
#! as `f.invoke(1, true)`, by the rules a method's call has: the overloads are
#! chosen between as they are, and one taking `&mut this` is called on what can be
#! written. Any type with an `invoke` is called so, whether or not it names this
#! trait, which bounds generic code taking functions and callable values alike:
#!
#! ```sakura
#! def twice<F>(f: &mut F, x: i64): i64 where F: invokable<def(i64): i64> {
#! return f(f(x));
#! }
#! ```
#!
#! A function value, and the address of a C function, have an `invoke` the
#! compiler gives them, which calls them, so each is `invokable` of its own type.
#! An `invoke` taking `&this` meets the trait too, since what can be written can
#! be read.
#! @tparam Ts The types of the arguments it is called with.
#! @tparam R The type it gives.
pub trait invokable<def(Ts...): R> {
#! Calls it with the arguments, as `f(args)` does.
#! @param this The value called.
#! @param args The arguments, one of each of the signature's parameter types.
#! @returns What the call gives.
def invoke(&mut this, args: Ts...): R;
}