Movatterモバイル変換


[0]ホーム

URL:


Docs.rs

Cratequote

Source
Expand description

githubcrates-iodocs-rs


This crate provides thequote! macro for turning Rust syntax tree datastructures into tokens of source code.

Procedural macros in Rust receive a stream of tokens as input, executearbitrary Rust code to determine how to manipulate those tokens, and producea stream of tokens to hand back to the compiler to compile into the caller’scrate. Quasi-quoting is a solution to one piece of that — producingtokens to return to the compiler.

The idea of quasi-quoting is that we writecode that we treat asdata.Within thequote! macro, we can write what looks like code to our texteditor or IDE. We get all the benefits of the editor’s brace matching,syntax highlighting, indentation, and maybe autocompletion. But rather thancompiling that as code into the current crate, we can treat it as data, passit around, mutate it, and eventually hand it back to the compiler as tokensto compile into the macro caller’s crate.

This crate is motivated by the procedural macro use case, but is ageneral-purpose Rust quasi-quoting library and is not specific to proceduralmacros.

[dependencies]quote = "1.0"

§Example

The following quasi-quoted block of code is something you might find inaprocedural macro having to do with data structure serialization. The#varsyntax performs interpolation of runtime variables into the quoted tokens.Check out the documentation of thequote! macro for more detail aboutthe syntax. See also thequote_spanned! macro which is important forimplementing hygienic procedural macros.

lettokens =quote! {structSerializeWith #generics #where_clause {        value:&'a#field_ty,        phantom: core::marker::PhantomData<#item_ty>,    }impl#generics serde::SerializeforSerializeWith #generics #where_clause {fnserialize<S>(&self, serializer: S) ->Result<S::Ok, S::Error>whereS: serde::Serializer,        {            #path(self.value, serializer)        }    }    SerializeWith {        value: #value,        phantom: core::marker::PhantomData::<#item_ty>,    }};

§Non-macro code generators

When usingquote in a build.rs or main.rs and writing the output out to afile, consider having the code generator pass the tokens throughprettyplease before writing. This way if an error occurs in the generatedcode it is convenient for a human to read and debug.

Macros§

format_ident
Formatting macro for constructingIdents.
quote
The whole point.
quote_spanned
Same asquote!, but applies a given span to all tokens originating withinthe macro invocation.

Traits§

IdentFragment
Specialized formatting trait used byformat_ident!.
ToTokens
Types that can be interpolated inside aquote! invocation.
TokenStreamExt
TokenStream extension trait with methods for appending tokens.

[8]ページ先頭

©2009-2025 Movatter.jp