Skip to main content

contract

Macro contract 

Source
macro_rules! contract {
    ( $( $(#[$m:meta])* $id:ident : $t:ty $(, $c:ty)? = $body:expr ; )+ ) => { ... };
}
Expand description

Declare a program’s invocation surface as a typed contract.

Generates a Contract struct with one pub const per input, plus records(), problems(), and parse_and_lint() — the three things every consumer needs and would otherwise write by hand for each project.

§Usage

use argenv_resolve::*;

contract! {
    /// Verbosity level — both a flag and an env var.
    LOG_LEVEL: LogLevel = Input {
        key:     "log_level",
        ty:      Type::Enum,
        default: Some(LogLevel::Info),
        allowed: LogLevel::TOKENS,
        env:     Some(Env::new("APP_LOG_LEVEL")),
        arg:     Some(Arg { value_name: "LEVEL", ..Arg::pair("log-level", 'l') }),
        summary: "Log verbosity.",
        ..Input::EMPTY
    };

    /// HDR output switch.
    HDR: bool = Input {
        key:     "hdr",
        ty:      Type::Bool,
        default: Some(false),
        env:     Some(Env::new("APP_HDR")),
        arg:     Some(Arg { negatable: true, ..Arg::long("hdr") }),
        summary: "Expose HDR output to the application.",
        ..Input::EMPTY
    };
}

let p = Contract::problems();
assert!(p.is_empty(), "{p:#?}");

// In main(), one line resolves and enforces the policy:
// let resolved = Contract::parse_and_lint(OnProblems::FailOnError);
// let level = Contract::LOG_LEVEL.get_from_or_default(&resolved);

§What is generated

  • pub struct Contract;
  • impl Contract { pub const $ID: Input<$T, ..> = ...; ... } — one typed constant per input, carrying both its declaration and (via InputResolveExt) its accessor.
  • Contract::records() -> Vec<Record> — every input as a portable contract record.
  • Contract::problems() -> Vec<String> — every declaration error across the contract (per-input check(), plus check_unique). Call this in a test so a bad declaration fails the build rather than a user’s launch.
  • Contract::parse_and_lint(policy: OnProblems) -> Resolution — reads the process argv and env, resolves, lints, and applies the given policy. The one call that replaces manual parse + lint + error-loop wiring.