Skip to main content

tap/
macros.rs

1//! Convenience macros and helper functions for `tap`.
2//!
3//! # Enabling
4//!
5//! This module is not wired up automatically. Add it in `src/tap/mod.rs`:
6//!
7//! ```ignore
8//! pub mod macros;
9//! ```
10//!
11//! All macros are exported at the crate root (`#[macro_export]`), so call them
12//! through the crate name — e.g. `tap::commands! { ... }`, `tap::bail!(...)`,
13//! `tap::cprintln!(...)`.
14//!
15//! # Contents
16//!
17//! | Category             | Items                                                                    |
18//! |----------------------|--------------------------------------------------------------------------|
19//! | Helpers              | [`arg`], [`arg_str`], [`arg_or`], [`arg_str_or`], [`arg_str_opt`]        |
20//! | Registration         | [`commands!`], [`subcommands!`]                                          |
21//! | Argument parsing     | [`args!`]                                                                |
22//! | Errors               | [`bail!`], [`ensure!`]                                                   |
23//! | Output               | [`cprint!`], [`cprintln!`], [`ceprintln!`]                               |
24//! | Scopes / templates   | [`scope!`], [`template!`], [`template_colored!`]                         |
25//!
26//! # Typical usage
27//!
28//! ```ignore
29//! use tap::{commands, args, bail, ensure};
30//!
31//! commands! {
32//!     engine;
33//!     "add" | "a" => my_add {
34//!         required: ["x", "y"],
35//!         docs: "Add two numbers",
36//!     }
37//!     "greet" => my_greet {
38//!         required: ["name"],
39//!         optional: ["greeting"],
40//!         docs: "Say hello",
41//!     }
42//! }
43//!
44//! fn my_add(_: &mut Engine, args: &[&str]) -> ErrorType {
45//!     args! { args;
46//!         x: i64,
47//!         y: i64,
48//!     }
49//!     println!("{}", x + y);
50//!     Ok(())
51//! }
52//! ```
53
54use std::str::FromStr;
55
56// ─────────────────────────────────────────────────────────────────────
57//  Helper functions
58// ─────────────────────────────────────────────────────────────────────
59
60/// Parses a required argument at index `i` into type `T`.
61///
62/// Returns an error when:
63///
64/// * no argument exists at index `i` — `"missing argument <name> (position i)"`;
65/// * the argument exists but fails to parse as `T` — `"argument <name>: <parser error>"`.
66///
67/// The error message includes `name` so users can tell which argument was
68/// wrong rather than receiving a bare parser error.
69pub fn arg<'a, T>(args: &[&'a str], i: usize, name: &str) -> Result<T, String>
70where
71    T: FromStr,
72    T::Err: std::fmt::Display,
73{
74    let s = args
75        .get(i)
76        .ok_or_else(|| format!("missing argument <{}> (position {})", name, i))?;
77    s.parse()
78        .map_err(|e| format!("argument <{}>: {}", name, e))
79}
80
81/// Returns a required argument at index `i` as a string slice.
82///
83/// Unlike [`arg`], no parsing is performed. Errors only when the argument is
84/// missing.
85pub fn arg_str<'a>(args: &[&'a str], i: usize, name: &str) -> Result<&'a str, String> {
86    args.get(i)
87        .copied()
88        .ok_or_else(|| format!("missing argument <{}> (position {})", name, i))
89}
90
91/// Like [`arg`], but falls back to `default` when the argument is absent.
92///
93/// Parsing errors are still reported — if the argument is present, it must
94/// parse as `T`.
95pub fn arg_or<'a, T>(args: &[&'a str], i: usize, name: &str, default: T) -> Result<T, String>
96where
97    T: FromStr,
98    T::Err: std::fmt::Display,
99{
100    match args.get(i) {
101        Some(s) => s.parse().map_err(|e| format!("argument <{}>: {}", name, e)),
102        None => Ok(default),
103    }
104}
105
106/// Like [`arg_str`], but returns `default` when the argument is absent.
107///
108/// Never fails.
109pub fn arg_str_or<'a>(args: &[&'a str], i: usize, default: &'a str) -> &'a str {
110    args.get(i).copied().unwrap_or(default)
111}
112
113/// Returns the argument at index `i` if present, otherwise `None`.
114///
115/// Never fails.
116pub fn arg_str_opt<'a>(args: &[&'a str], i: usize) -> Option<&'a str> {
117    args.get(i).copied()
118}
119
120// ─────────────────────────────────────────────────────────────────────
121//  commands!
122// ─────────────────────────────────────────────────────────────────────
123
124/// Registers one or more top-level commands on an engine.
125///
126/// Each entry has the shape:
127///
128/// ```ignore
129/// "name" | "alias" => handler {
130///     required: ["arg1", "arg2"],   // optional field
131///     optional: ["arg3"],           // optional field
132///     unlimited: true,              // optional, defaults to false
133///     docs: "Description",          // required
134/// }
135/// ```
136///
137/// All fields except `docs` may be omitted. `required`, `optional` and
138/// `unlimited` default to empty/false.
139///
140/// # Example
141///
142/// ```ignore
143/// tap::commands! {
144///     engine;
145///     "echo" => cmd_echo {
146///         required: ["text"],
147///         docs: "Echo back the text",
148///     }
149///     "quit" | "exit" => cmd_quit {
150///         docs: "Exit the shell",
151///     }
152/// }
153/// ```
154#[macro_export]
155macro_rules! commands {
156    (
157        $engine:ident;
158        $(
159            $($name:literal)|+ => $handler:path {
160                $(required: [$($req:literal),* $(,)?],)?
161                $(optional: [$($opt:literal),* $(,)?],)?
162                $(unlimited: $unlim:literal,)?
163                docs: $docs:literal $(,)?
164            }
165        )*
166    ) => {{
167        $(
168            $engine.new_commands(
169                vec![$($name),+],
170                {
171                    let __tap_h: $crate::engine::structs::HandlerType =
172                        ::std::rc::Rc::new($handler);
173                    $crate::engine::structs::CmdInfo::new(
174                        __tap_h,
175                        vec![$($($req),*)?],
176                        vec![$($($opt),*)?],
177                        $crate::commands!(@unlim $($unlim)?),
178                        $docs,
179                    )
180                },
181            );
182        )*
183    }};
184
185    (@unlim $b:literal) => { $b };
186    (@unlim)            => { false };
187}
188
189// ─────────────────────────────────────────────────────────────────────
190//  subcommands!
191// ─────────────────────────────────────────────────────────────────────
192
193/// Registers one or more subcommands on an engine.
194///
195/// Syntax is identical to [`commands!`], except that the handler must be a
196/// `SubHandlerType` (a plain function pointer, not an `Rc`).
197///
198/// # Example
199///
200/// ```ignore
201/// tap::subcommands! {
202///     engine;
203///     "set" => sub_set {
204///         required: ["key", "value"],
205///         docs: "Set a variable",
206///     }
207/// }
208/// ```
209#[macro_export]
210macro_rules! subcommands {
211    (
212        $engine:ident;
213        $(
214            $($name:literal)|+ => $handler:path {
215                $(required: [$($req:literal),* $(,)?],)?
216                $(optional: [$($opt:literal),* $(,)?],)?
217                $(unlimited: $unlim:literal,)?
218                docs: $docs:literal $(,)?
219            }
220        )*
221    ) => {{
222        $(
223            $engine.new_subcommands(
224                vec![$($name),+],
225                $crate::engine::structs::CmdInfo::new(
226                    $handler as $crate::engine::structs::SubHandlerType,
227                    vec![$($($req),*)?],
228                    vec![$($($opt),*)?],
229                    $crate::subcommands!(@unlim $($unlim)?),
230                    $docs,
231                ),
232            );
233        )*
234    }};
235
236    (@unlim $b:literal) => { $b };
237    (@unlim)            => { false };
238}
239
240// ─────────────────────────────────────────────────────────────────────
241//  args!
242// ─────────────────────────────────────────────────────────────────────
243
244/// Binds handler arguments to typed local variables.
245///
246/// Syntax: `args! { <slice>; name: Type, name: Type = default, ... }`.
247///
248/// * `name: Type`             — required, parsed via [`arg`].
249/// * `name: Type = default`   — optional, parsed via [`arg_or`].
250///
251/// Each variable consumes one positional argument, so the order matters.
252/// The trailing comma is allowed and optional.
253///
254/// # Example
255///
256/// ```ignore
257/// fn handler(_: &mut Engine, args: &[&str]) -> ErrorType {
258///     args! { args;
259///         count: u32,
260///         label: String = "default".to_string(),
261///         verbose: bool = false,
262///     }
263///     // ...
264///     Ok(())
265/// }
266/// ```
267#[macro_export]
268macro_rules! args {
269    ($args:expr; $($rest:tt)*) => {
270        let __tap_args: &[&str] = $args;
271        let mut __tap_i: usize = 0usize;
272        $crate::args!(@next __tap_args, __tap_i, $($rest)*);
273        let _ = __tap_i;
274    };
275
276    (@next $args:ident, $i:ident,) => {};
277
278    (@next $args:ident, $i:ident, $name:ident : $ty:ty = $default:expr, $($rest:tt)*) => {
279        let $name: $ty = $crate::macros::arg_or(
280            $args, $i, stringify!($name), $default
281        )?;
282        $i += 1;
283        $crate::args!(@next $args, $i, $($rest)*);
284    };
285
286    (@next $args:ident, $i:ident, $name:ident : $ty:ty = $default:expr) => {
287        let $name: $ty = $crate::macros::arg_or(
288            $args, $i, stringify!($name), $default
289        )?;
290        $i += 1;
291        $crate::args!(@next $args, $i,);
292    };
293
294    (@next $args:ident, $i:ident, $name:ident : $ty:ty, $($rest:tt)*) => {
295        let $name: $ty = $crate::macros::arg(
296            $args, $i, stringify!($name)
297        )?;
298        $i += 1;
299        $crate::args!(@next $args, $i, $($rest)*);
300    };
301
302    (@next $args:ident, $i:ident, $name:ident : $ty:ty) => {
303        let $name: $ty = $crate::macros::arg(
304            $args, $i, stringify!($name)
305        )?;
306        $i += 1;
307        $crate::args!(@next $args, $i,);
308    };
309}
310
311// ─────────────────────────────────────────────────────────────────────
312//  Error helpers — `bail!` / `ensure!`
313// ─────────────────────────────────────────────────────────────────────
314
315/// Early-returns an error from a handler.
316///
317/// Accepts either a literal/expression convertible into the handler's error
318/// type, or a `format!`-style format string with arguments.
319///
320/// ```ignore
321/// fn h(_: &mut Engine, args: &[&str]) -> ErrorType {
322///     if args.is_empty() { bail!("at least one argument required"); }
323///     let n: u32 = args[0].parse().map_err(|_| format!("bad number: {}", args[0]))?;
324///     ensure!(n > 0, "must be positive, got {}", n);
325///     Ok(())
326/// }
327/// ```
328#[macro_export]
329macro_rules! bail {
330    ($msg:literal $(,)?) => {
331        return ::std::result::Result::Err($msg.into())
332    };
333    ($err:expr $(,)?) => {
334        return ::std::result::Result::Err($err.into())
335    };
336    ($fmt:expr, $($arg:tt)*) => {
337        return ::std::result::Result::Err(format!($fmt, $($arg)*).into())
338    };
339}
340
341/// Conditional [`bail!`]: returns an error when the condition is false.
342///
343/// ```ignore
344/// ensure!(count <= 10, "too many items: {}", count);
345/// ensure!(flag, "flag must be set");
346/// ```
347#[macro_export]
348macro_rules! ensure {
349    ($cond:expr, $msg:literal $(,)?) => {
350        if !$cond { $crate::bail!($msg) }
351    };
352    ($cond:expr, $err:expr $(,)?) => {
353        if !$cond { $crate::bail!($err) }
354    };
355    ($cond:expr, $fmt:expr, $($arg:tt)*) => {
356        if !$cond { $crate::bail!($fmt, $($arg)*) }
357    };
358}
359
360// ─────────────────────────────────────────────────────────────────────
361//  Colored printing — `cprint!` / `cprintln!` / `ceprintln!`
362// ─────────────────────────────────────────────────────────────────────
363
364/// Colored `print!`.
365///
366/// The formatted string is passed through
367/// `tooling::colors::set::colorize` before writing to stdout.
368#[macro_export]
369macro_rules! cprint {
370    ($($arg:tt)*) => {
371        ::std::print!("{}", $crate::tooling::colors::set::colorize(&format!($($arg)*)))
372    };
373}
374
375/// Colored `println!`.
376///
377/// With no arguments, emits a plain newline (no colorization needed).
378/// Otherwise formats and colorizes the output.
379#[macro_export]
380macro_rules! cprintln {
381    () => { ::std::println!() };
382    ($($arg:tt)*) => {
383        ::std::println!("{}", $crate::tooling::colors::set::colorize(&format!($($arg)*)))
384    };
385}
386
387/// Colored `eprintln!` — writes to stderr.
388#[macro_export]
389macro_rules! ceprintln {
390    ($($arg:tt)*) => {
391        ::std::eprintln!("{}", $crate::tooling::colors::set::colorize(&format!($($arg)*)))
392    };
393}
394
395// ─────────────────────────────────────────────────────────────────────
396//  Renderable shortcuts — `scope!` / `template!` / `template_colored!`
397// ─────────────────────────────────────────────────────────────────────
398
399/// Populates `Renderable::scope` with `key => value` pairs.
400///
401/// The `key` may include a `:type` suffix (e.g. `"version:int"`) that is
402/// interpreted by the renderer downstream.
403///
404/// ```ignore
405/// scope!(r;
406///     "name" => "Rust",
407///     "version:int" => "1",
408///     "stable:bool" => "true",
409/// );
410/// ```
411#[macro_export]
412macro_rules! scope {
413    ($r:expr; $($key:literal => $val:expr),* $(,)?) => {{
414        $($r.scope.insert($key, $val);)*
415    }};
416}
417
418/// Adds a plain template renderer.
419///
420/// ```ignore
421/// template!(r, "plain", "Hello, {{name}}");
422/// ```
423#[macro_export]
424macro_rules! template {
425    ($r:expr, $name:expr, $templ:expr) => {
426        $crate::tooling::renderable::add_template_render($templ, $name, &mut $r)
427    };
428}
429
430/// Adds a colored template renderer.
431///
432/// The rendered result is passed through `colorize`, so `[?GN]…[?RT]` style
433/// color codes are resolved.
434///
435/// ```ignore
436/// template_colored!(r, "colored", "[?GN]Hello, {{name}}[?RT]");
437/// ```
438#[macro_export]
439macro_rules! template_colored {
440    ($r:expr, $name:expr, $templ:expr) => {
441        $crate::tooling::renderable::add_template_render_colored($templ, $name, &mut $r)
442    };
443}