docs

你正在阅读 v0.1.2 的文档。Nabi 0.1.2 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#6.8. User-defined meta definitions

本页内容

A meta definition is a user-defined code generator. All of them are one mechanism: a definition binds parts of an input and transcribes a template of Nabi code and template tokens (6.9), hygienically (6.8.9) and to a fixed point (6.8.8). They differ only in how they are triggered and what input they bind. There are four forms; the first three are triggered by an attribute on an item, the fourth by a call:

FormDefined asTriggered byBinds
derive#[impl_derive(T)] @derive {}#[derive(T)] on a typethe type's shape (@Self, @for_fields)
attribute#[impl_attribute(n)] @attribute {}#[n] on an itemthe item (@item)
per-field derive attribute#[impl_derive_attribute(T, a)] @derive {}#[derive(T)] + #[a] on fieldsshape + field attributes
macro#[impl_macro(n)] @macro { (m) => {t} }n!(..) callthe call's tokens (@x: expr, @rep)

The first three generate code from a type or item the author attaches them to; the macro generates code from what the caller writes, the one need the others cannot serve (6.8.12). They share the template engine, the @ tokens, hygiene and the tooling guarantees below; this chapter and 6.9 note where the bound input differs. These four are Nabi's entire metaprogramming surface: together they take the place of Rust's derive, attribute and function-like macros, without procedural code or raw token manipulation.

meta_block      ::= meta_attr visibility? meta_kind block
meta_attr       ::= "#" "[" meta_kind_attr "(" meta_args ")" "]"
meta_kind_attr  ::= "impl_derive" | "impl_attribute" | "impl_derive_attribute" | "impl_macro"
meta_kind       ::= "@derive" | "@attribute" | "@macro"
meta_args       ::= identifier ("," identifier)*

# the @macro block holds rules instead of a flat template:
macro_body      ::= macro_rule+
macro_rule      ::= "(" matcher ")" "=>" block

#6.8.1. The attribute-triggered forms

The three attribute-triggered forms:

nabi
#[impl_derive(TraitName)] pub @derive {
    impl TraitName for @Self { ... }
}

#[impl_attribute(name)] pub @attribute {
    @item                                    // reuse the original item
    fn additional_helper() { ... }            // generate an additional item
}

#[impl_derive_attribute(Trait, attr)] pub @derive {
    @for_fields {
        @apply_if(@has_derive_attr(attr)) {
            // process only fields carrying that attr
        }
    }
}

What each form is used for:

FormUse
#[impl_derive(TraitName)]User-defined derive
#[impl_attribute(name)]User-defined attribute (item wrapper)
#[impl_derive_attribute(Trait, attr)]Per-field derive attribute

The fourth, the call-triggered macro, is defined in 6.8.12.

#6.8.2. #[impl_derive(TraitName)] user-defined derive

An example of a user-defined derive:

This form consists of #[impl_derive(name)] and a body (template block). When #[derive(name)] appears at a use site, the template is expanded for that type to generate code.

#6.8.3. #[impl_attribute(name)] user-defined attribute

An example of a user-defined attribute:

This is a wrapper around an item: it reuses the contents and signature of the original item (@item) to generate a transformed form. It can be attached not only to functions but also to struct, enum, and impl; target restrictions are expressed with @accept.

#6.8.4. #[impl_derive_attribute(Trait, attr)] per-field derive attribute

An example of a per-field derive attribute:

This form takes two arguments: the Trait being derived and the attribute that marks per-field information. It branches inside the derive body by reading the fields' attribute information.

The attribute may declare the keys it takes, as attr(k, ..): #[impl_derive_attribute(Nabion, nabion(deny_unknown_fields))]. Every #[attr(..)] on the type, its variants and its fields must then list only declared keys; anything else is an error that names the valid keys. @Self.has_derive_key(k) reads a key off the type (6.9.6).

#6.8.5. Body (template block)

In every form the body is a template block containing both ordinary Nabi code and template tokens (@Self, @field, @for_fields for the attribute-triggered forms; @x, @rep, @for, @concat for a macro, 6.8.12).

The full list of template tokens is defined in template tokens and expansion.

#6.8.6. pub / visibility

Visibility is written as:

nabi
pub @derive { ... }
pub(pkg) @attribute { ... }
@derive { ... }                  // private

The visibility keyword is attached to the template block itself. Its effect:

VisibilityWhere it can be used
pub (including pub(pkg))The whole build. Another package writes it with this package's name: #[derive(dep::X)] / #[dep::x] / dep::x!(..) (6.8.11)
privateWithin the file that defines the meta block

Meta names have no module path: a name belongs to the package whose meta block registers it, written bare in that package and with the package's name in others (6.8.11). A meta block's template sees what its module sees: the names it writes resolve, and are access-checked, there (6.9.9). A meta block's or keyword handler's #[cfg] is evaluated with the cfg of the package that defines it (its own features, 9.10.4c).

#6.8.7. Body introducers (@derive / @attribute)

The body introducer indicates the kind of template.

IntroducerUse
@derivederive definitions (impl_derive, impl_derive_attribute)
@attributeattribute definitions (impl_attribute)
@macromacro definitions (impl_macro); its block holds rules (6.8.12)

The introducer determines which template tokens are meaningful in the body. For example, @item is attribute-only, and the matcher tokens (@x: expr, @rep) are @macro-only.

#6.8.8. Fixed-point expansion

If the result of template expansion produces an item carrying another derive or attribute, that item is expanded recursively.

nabi
#[impl_attribute(adds_helper)] pub @attribute {
    @item                                       // the original item as is

    #[derive(MyHelper)]                          // new item: derive processed again
    struct Helper { ... }
}

When this attribute is applied, the #[derive(MyHelper)] in the body is processed in the next expansion pass.

Expansion terminates when it reaches a fixed point where no derive or attribute remains to expand.

Circular expansion (A invokes B and B invokes A again) is detected by the compiler and is an ERROR. The message shows the cycle path (A → B → A).

#6.8.9. No token stream manipulation

Every meta definition (the three attribute-triggered forms and the macro) generates code using template tokens only. Nabi has no arbitrary token transformation facility like Rust's syn or quote, and no procedural form that runs code at compile time.

This restriction guarantees that the output of a meta definition is Nabi code the compiler can understand, securing both tool friendliness and debuggability.

#6.8.10. Comparison with proc macros

Comparing Rust proc macros with Nabi meta blocks:

AspectRust proc macroNabi meta block
InputArbitrary token streamStructural information of the item (fields, variants, etc.)
OutputArbitrary token streamNabi code and template tokens
HygieneUp to the proc macroAutomatic (hygienic)
DebuggingInspect output tokensInspect the expanded AST
ExpressivenessVery highLimited

Nabi's choice trades expressiveness for predictability and ease of debugging.

#6.8.11. Combination with registration/visibility

A meta block carrying #[impl_derive(TraitName)] registers a derive named TraitName, #[impl_attribute(name)] registers the #[name] attribute, and #[impl_macro(name)] registers the macro name!. The compiler collects meta blocks from every file of libraries and user packages before parsing, so they can be used regardless of definition location or file order. If a #[cfg] on a meta block is false, that block is not registered (6.9.9).

A meta name belongs to the package whose meta block registers it. In that package it is written bare (#[derive(MyHash)], #[x], x!(..)) or with pkg::. Another package writes the defining package's name before it, the same root as that package's paths: #[derive(dep::MyHash)], #[dep::x], dep::x!(..). The qualifier is the package alone; meta blocks are not items of the name space and have no module path.

A module-level use dep::x!; imports the macro x!, so the file calls it as x!(..). It imports no item, and it cannot be renamed (as) or re-exported (pub use). A use of an item named like a derive, usually its trait (use dep::MyHash;), also imports the derive, and use dep::*; imports every meta name of dep.

nabi
// package json
#[impl_macro(log)] pub @macro { ... }
#[impl_derive(MyHash)] pub @derive {
    impl pkg::MyHash for @Self { ... }
}

// a package that depends on json
use json::log!;

#[derive(json::MyHash)]
struct Foo { ... }

fn main() {
    json::log!("start");
    log!("imported");
}

A bare name resolves to this package's block, else the one a use imports, else the standard library's (its meta names stay bare: #[derive(Inspect)]). Otherwise it is an error that lists the qualified forms: `log!` is package `json`'s macro, which a bare name does not reach, help write `json::log!`, or add `use json::log!;` . Two packages whose uses both import the name make it ambiguous, also an error. Inside an expansion, a meta name the template wrote follows the same rule from the defining package and file, so a dependency's macros keep working wherever they expand; a name the use passed in follows it from the use site (6.9.9).

The following are errors:

  • Two meta blocks of one package registering the same derive, attribute or macro name (one macro is one @macro block holding all its rules). Two packages may each register a name.
  • A qualified macro, attribute or derive (dep::x!, #[dep::x], #[derive(dep::X)]) that the named package does not register.
  • A meta block redefining the name of a built-in derive (6.2.1: Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Error) or a built-in attribute (cfg, derive, test, inline, repr, keyword, bench, path, and the other attributes of 6.2 to 6.7). The help suggests a new name (#[impl_attribute(my_bench)]).

#6.8.12. The macro form

A macro is the call-triggered meta definition. Where a derive or attribute generates code from a type or item it is attached to, a macro is invoked like name!(..) and expands into code at that position, generating code from what the caller writes. It is the one need the attribute-triggered forms cannot serve: repeating or generating code driven by the call, not by a type's fields.

#Definition

Like the other forms, a macro is #[impl_macro(name)], a visibility, the @macro introducer, and a block. The block holds one or more rules instead of a flat template: each is a matcher in parentheses, => (the same arrow as a match arm), and a template in braces.

nabi
#[impl_macro(name)] pub @macro {
    ( <matcher> ) => { <template> }
    ( <matcher> ) => { <template> }
    ..
}

#[impl_macro(name)] registers the macro name!, exactly as #[impl_derive(T)] registers the derive T. On a call the rules are tried top to bottom and the first whose matcher matches is expanded; if none matches it is a compile error at the call. Like a derive's or an attribute's, a macro's name belongs to its package: name! there, dep::name! or a use dep::name!; in other packages (6.8.11). The trailing ! at every call marks it as a macro, not a function.

nabi
#[impl_macro(twice)] pub @macro {
    ( @e: expr ) => { { let v = @e; (v, v) } }
}

let p = twice!(compute());      // (the value, the same value)

#Invocation

A macro is called as name!( .. ), name![ .. ] or name!{ .. }, and from another package as dep::name!( .. ); the delimiters are interchangeable and do not change meaning. The arguments are an arbitrary token tree: any tokens with balanced () [] {}, so the lexer and formatter tokenize a call even without knowing the macro. A macro may expand at these positions, in whichever its template produces:

PositionExampleTemplate yields
expressionlet xs = grid![1, 2; 3, 4];an expression
statementdebug!("here");zero or more statements
itemint_impl!(i8, i16, i32); (module level)zero or more items
typelet f: fn_ptr!(i32, i32) = ..;a type
patternmatch x { pair!(a, b) => .. }a pattern

In expression position a call is a primary expression: its expansion is one operand, as if in parentheses, and the postfix forms follow it (grid![1, 2; 3, 4].len(), table!{ .. }.head(5), first!(xs)?).

#Matchers and fragments

A matcher is a token pattern. Literal tokens must appear verbatim in the call; a metavariable @name: <fragment> captures a part of the call for the template. The fragment fixes how many tokens are captured: ident takes one identifier, literal one literal token, and tt one token tree (a token or a balanced group). expr, stmt, block, ty, pat, path and item take the non-empty run of tokens up to the next literal token of the matcher at bracket depth 0 (or to the end of the call or of the enclosing group). A bracketed group in the matcher, ( .. ), [ .. ] or { .. }, matches a balanced group of the call, and its inside is matched as a matcher of its own: [ @rep[sep = ","] { @x: expr } ] matches [5, 6]. Every fragment is captured as raw tokens and is not parsed when matched; the whole expansion is parsed after transcription, so an argument that is not valid where the template puts it is a syntax error in the expansion, reported at the call.

nabi
#[impl_macro(clamp)] pub @macro {
    ( @x: expr , @lo: expr , @hi: expr ) => {
        { let v = @x; if v < @lo { @lo } else if v > @hi { @hi } else { v } }
    }
}

#Repetition

@rep matches a sub-pattern zero or more times. @for transcribes once per element; it is the same iterator as @for_fields (6.9.3), here over a captured sequence.

nabi
#[impl_macro(list)] pub @macro {
    ( @rep[sep = ","] { @x: expr } ) => {
        { let acc = List::new(); @for @x { acc.push(@x); } acc }
    }
}

let xs = list![a, b, c];        // acc.push(a); acc.push(b); acc.push(c);

@rep[sep = ","] { <sub-pattern> } matches the sub-pattern repeated with the sep token between (sep optional; trailing also allows one trailing separator). A metavariable captured inside @rep binds a sequence. @for @x { <body> } emits the body per element; several metavariables from one @rep iterate in lockstep and must have equal length. @rep and @for nest: a metavariable inside two @reps binds a sequence of sequences, and an inner @for @x walks the current element of the outer one ((@rep[sep = ";"] { @rep[sep = ","] { @x: expr } }) => { [@for @x { [@for @x { @x, }], }] } turns 1, 2; 3 into [[1, 2], [3]]). The shape tokens (@Self, @field, @apply_if, ..) belong to the type-driven forms, not a macro: a macro has no shape to test, so using one is an error.

#Name synthesis

@concat(..) joins name tokens and string literals into one identifier, so a macro can generate distinct, named items:

nabi
#[impl_macro(accessors)] pub @macro {
    ( @s: ident ; @rep[sep = ","] { @f: ident : @t: ty } ) => {
        impl @s { @for @f { fn @concat(get_, @f)(self) -> @t { self.@f } } }
    }
}
// accessors!{ P; x: i32, y: i32 } -> impl P { fn get_x(self) -> i32 { self.x } .. }  (and get_y)

A name made by @concat is recorded: the compiler indexes each synthesized item under its generated name, so symbol search, go-to-definition and find-references reach it. @concat forms an identifier at a definition or path position only; its pieces are name tokens and string literals, and it cannot assemble arbitrary syntax.

#The library's boilerplate

The classic reason for a macro is repeating a definition across a fixed list the author writes, which no attribute-triggered form can do. It replaces the hand-copied per-type impls of core::num:

nabi
#[impl_macro(nonzero_div)] pub @macro {
    ( @rep[sep = ","] { @t: ty } ) => {
        @for @t {
            impl Div<NonZero<@t>> for @t {
                type Output = @t;
                const fn div(self, rhs: NonZero<@t>) -> @t { self / rhs.0 }
            }
        }
    }
}

nonzero_div!(i8, i16, i32, i64, u8, u16, u32, u64);

#Recursion

A template may call other macros; their calls expand in turn. A macro may not call itself: a call of a macro inside its own expansion, directly or through other macros, is rejected at once with a compile error naming the call (`name!` expands too deeply or cyclically). Nested expansion of distinct macros is bounded at 256 levels with the same error. To repeat over a list, use @rep / @for instead of recursion.

#Built-in !-forms are reserved

cfg! (6.3) and include_str! / include_bytes! (6.11) end in ! but are fixed compiler built-ins, not macros, and cannot be redefined, shadowed or taken as a macro name. They are the only !-forms the compiler provides; every other name! is a macro defined in Nabi.

#Tooling and hygiene

A macro keeps the guarantees of every meta definition (6.8.9), with the specifics a call site adds:

  • Hygiene is automatic: a name the template binds (a let or a for loop's variable) is fresh and cannot capture or be captured by the call site, and a name passed in through a metavariable resolves at the call site. Any other name the template writes, such as a type in an impl Tr for E header or an imported Complex, refers to the item where the macro is defined.
  • Spans: every expanded token carries the span of the call, so a diagnostic points at the call with the expansion shown as a note.
  • Resolution: the expansion is parsed as ordinary code and synthesized names are indexed, so hover, go-to-definition and find-references reach the items a macro generates.
  • Expansion on request: the language server can expand a call in place (9.9.13).
  • Formatting: the formatter formats a call's arguments when they are Nabi fragments, and leaves a raw tt DSL as written within its balanced delimiters.

#6.8.13. Summary

These four forms (derive, attribute, per-field derive attribute and the call-triggered macro) make up Nabi's entire metaprogramming surface, over one template engine. They lack the expressiveness of procedural macros but cover the core use cases: derives, attributes, per-field attributes, and call-site generation, each hygienic and followable by the tools.

Template tokens and expansion defines the exact list of template tokens (for both the type-driven and the call-driven input) and the expansion mechanism.

Found a mistake? Edit this page on GitHub. Last updated