Skip to main content

define

Macro define 

Source
define!() { /* proc-macro */ }
Expand description

结构体定义宏:定义一个新的 AST 节点并自动实现 syn::parse::Parse Struct definition macro: Define a new AST node and implement syn::parse::Parse automatically

`define!` 宏用于创建可复用的语法结构。它会根据提供的模式生成一个结构体, 并生成相应的解析逻辑,使其可以直接通过 `syn::parse_macro_input!` 或 `input.parse()` 使用。

§语法

vacro::define!(StructName: <Pattern>);

宏会自动生成:

  1. struct StructName { ... }:包含所有具名捕获的字段。
  2. impl syn::parse::Parse for StructName { ... }:包含解析逻辑。

§注意事项

  • define! 中通常使用具名捕获 (#(name: Type)) 来生成结构体字段。

§示例

// 定义一个简单的常量定义结构
// const NAME: Type = Value;
define!(MyConst:
    const
    #(name: Ident)
    :
    #(ty: Type)
    =
    #(value: syn::Expr)
    ;
);

fn parser(input: ParseStream) -> Result<()> {
    // MyConst 自动实现了 Parse trait
    let MyConst { name, ty, value } = input.parse()?;
    println!("Const {} has type {}, value: {}", name, quote!(#ty), quote!(#value));
    Ok(())
}

The define! macro is used to create reusable syntax structures. It generates a struct based on the provided pattern and implements the parsing logic, making it usable directly via syn::parse_macro_input! or input.parse().

§Syntax

vacro::define!(StructName: <Pattern>);

The macro automatically generates:

  1. struct StructName { ... }: Containing all named captured fields.
  2. impl syn::parse::Parse for StructName { ... }: Containing the parsing logic.

§Notes

  • define! typically uses Named Captures (#(name: Type)) to generate struct fields.

§Example

// Define a simple constant definition structure
// const NAME: Type = Value;
define!(MyConst:
    const
    #(name: Ident)
    :
    #(ty: Type)
    =
    #(value: syn::Expr)
    ;
);

fn parser(input: ParseStream) -> Result<()> {
    // MyConst automatically implements the Parse trait
    let MyConst { name, ty, value } = input.parse()?;
    println!("Const {} has type {}, value: {}", name, quote!(#ty), quote!(#value));
    Ok(())
}