liveBook · Manning

Custom keyword

As explained in Write Powerful Rust Macros

A custom keyword is a syntax token declared through syn's custom_keyword macro that implements parsing and lookahead support for a DSL-specific keyword.

A custom keyword is a DSL-specific syntax token declared with syn::custom_keyword!. Rust does not otherwise treat words such as bucket or lambda as special, so the macro gives syn explicit parsing knowledge for them. section 9.3.2

Listing 9.6 Our four keywords: bucket, lambda, memory, and timeout
pub(crate) mod kw {
    syn::custom_keyword!(bucket);
    syn::custom_keyword!(lambda);
    syn::custom_keyword!(mem);
    syn::custom_keyword!(time);
}

Declare related tokens together in a conventional kw module. Each declaration creates a type that can be parsed and inspected with lookahead. section 9.3.2

Use the generated types with ParseStream::peek to choose a grammar branch, then consume the token with input.parse(). A parser can therefore distinguish resource declarations and optional properties while producing targeted errors for unsupported input. section 9.3.2

Parsing infrastructure declarations

A parser can recognize bucket and lambda declarations, then parse each declaration's details: input.peek(kw::bucket) selects Bucket, input.peek(kw::lambda) selects Lambda, and Bucket parses kw::bucket before its identifier. Lambda similarly checks kw::mem and kw::time for optional numeric properties. Invalid forms such as a missing lambda name or nonnumeric memory value receive errors tied to the relevant token.

Custom keywords also work as generic Parse implementations: a shared numeric-property helper can parse kw::time or kw::mem through a type parameter constrained by Parse.

How Write Powerful Rust Macros covers it

How deep it goes
Explains declaration, generated Parse support, lookahead, consumption, generic reuse, and diagnostics without descending into macro expansion internals.
Examples
Uses bucket, lambda, mem, and time tokens in resource parsers with missing-name, invalid-number, and range-validation diagnostics.
What it assumes
Assumes Rust parsing and procedural-macro familiarity while teaching how ordinary words become syn-recognized tokens.
What you can do after
Build DSL parsers that branch on custom syntax, consume declared tokens, reuse keyword parsing, and report focused errors.
How it connects
Connects custom keywords to syn, Parse, ParseStream, lookahead, procedural macros, and domain-specific languages.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.