{"id":13595322,"url":"https://github.com/dtolnay/quote","last_synced_at":"2026-03-03T22:07:13.030Z","repository":{"id":39580284,"uuid":"67273122","full_name":"dtolnay/quote","owner":"dtolnay","description":"Rust quasi-quoting","archived":false,"fork":false,"pushed_at":"2025-03-11T23:56:28.000Z","size":907,"stargazers_count":1411,"open_issues_count":6,"forks_count":95,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-05-08T20:56:50.569Z","etag":null,"topics":["proc-macro","rust","syn"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dtolnay.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"dtolnay"}},"created_at":"2016-09-03T05:34:45.000Z","updated_at":"2025-05-08T16:19:58.000Z","dependencies_parsed_at":"2023-02-17T01:46:01.482Z","dependency_job_id":"552d7f00-6029-405f-aaf6-3369b9668ee4","html_url":"https://github.com/dtolnay/quote","commit_stats":{"total_commits":551,"total_committers":26,"mean_commits":"21.192307692307693","dds":"0.10344827586206895","last_synced_commit":"c8898964b893f47b3337cd18bd463365b9c12576"},"previous_names":[],"tags_count":88,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dtolnay%2Fquote","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dtolnay%2Fquote/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dtolnay%2Fquote/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dtolnay%2Fquote/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dtolnay","download_url":"https://codeload.github.com/dtolnay/quote/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253157355,"owners_count":21863100,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["proc-macro","rust","syn"],"created_at":"2024-08-01T16:01:47.715Z","updated_at":"2026-01-23T05:39:49.293Z","avatar_url":"https://github.com/dtolnay.png","language":"Rust","readme":"Rust Quasi-Quoting\n==================\n\n[\u003cimg alt=\"github\" src=\"https://img.shields.io/badge/github-dtolnay/quote-8da0cb?style=for-the-badge\u0026labelColor=555555\u0026logo=github\" height=\"20\"\u003e](https://github.com/dtolnay/quote)\n[\u003cimg alt=\"crates.io\" src=\"https://img.shields.io/crates/v/quote.svg?style=for-the-badge\u0026color=fc8d62\u0026logo=rust\" height=\"20\"\u003e](https://crates.io/crates/quote)\n[\u003cimg alt=\"docs.rs\" src=\"https://img.shields.io/badge/docs.rs-quote-66c2a5?style=for-the-badge\u0026labelColor=555555\u0026logo=docs.rs\" height=\"20\"\u003e](https://docs.rs/quote)\n[\u003cimg alt=\"build status\" src=\"https://img.shields.io/github/actions/workflow/status/dtolnay/quote/ci.yml?branch=master\u0026style=for-the-badge\" height=\"20\"\u003e](https://github.com/dtolnay/quote/actions?query=branch%3Amaster)\n\nThis crate provides the [`quote!`] macro for turning Rust syntax tree data\nstructures into tokens of source code.\n\n[`quote!`]: https://docs.rs/quote/1.0/quote/macro.quote.html\n\nProcedural macros in Rust receive a stream of tokens as input, execute arbitrary\nRust code to determine how to manipulate those tokens, and produce a stream of\ntokens to hand back to the compiler to compile into the caller's crate.\nQuasi-quoting is a solution to one piece of that \u0026mdash; producing tokens to\nreturn to the compiler.\n\nThe idea of quasi-quoting is that we write *code* that we treat as *data*.\nWithin the `quote!` macro, we can write what looks like code to our text editor\nor IDE. We get all the benefits of the editor's brace matching, syntax\nhighlighting, indentation, and maybe autocompletion. But rather than compiling\nthat as code into the current crate, we can treat it as data, pass it around,\nmutate it, and eventually hand it back to the compiler as tokens to compile into\nthe macro caller's crate.\n\nThis crate is motivated by the procedural macro use case, but is a\ngeneral-purpose Rust quasi-quoting library and is not specific to procedural\nmacros.\n\n```toml\n[dependencies]\nquote = \"1.0\"\n```\n\n*Version requirement: Quote supports rustc 1.68 and up.*\u003cbr\u003e\n[*Release notes*](https://github.com/dtolnay/quote/releases)\n\n\u003cbr\u003e\n\n## Syntax\n\nThe quote crate provides a [`quote!`] macro within which you can write Rust code\nthat gets packaged into a [`TokenStream`] and can be treated as data. You should\nthink of `TokenStream` as representing a fragment of Rust source code.\n\n[`TokenStream`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.TokenStream.html\n\nWithin the `quote!` macro, interpolation is done with `#var`. Any type\nimplementing the [`quote::ToTokens`] trait can be interpolated. This includes\nmost Rust primitive types as well as most of the syntax tree types from [`syn`].\n\n[`quote::ToTokens`]: https://docs.rs/quote/1.0/quote/trait.ToTokens.html\n[`syn`]: https://github.com/dtolnay/syn\n\n```rust\nlet tokens = quote! {\n    struct SerializeWith #generics #where_clause {\n        value: \u0026'a #field_ty,\n        phantom: core::marker::PhantomData\u003c#item_ty\u003e,\n    }\n\n    impl #generics serde::Serialize for SerializeWith #generics #where_clause {\n        fn serialize\u003cS\u003e(\u0026self, serializer: S) -\u003e Result\u003cS::Ok, S::Error\u003e\n        where\n            S: serde::Serializer,\n        {\n            #path(self.value, serializer)\n        }\n    }\n\n    SerializeWith {\n        value: #value,\n        phantom: core::marker::PhantomData::\u003c#item_ty\u003e,\n    }\n};\n```\n\n\u003cbr\u003e\n\n## Repetition\n\nRepetition is done using `#(...)*` or `#(...),*` similar to `macro_rules!`. This\niterates through the elements of any variable interpolated within the repetition\nand inserts a copy of the repetition body for each one. The variables in an\ninterpolation may be a `Vec`, slice, `BTreeSet`, or any `Iterator`.\n\n- `#(#var)*` — no separators\n- `#(#var),*` — the character before the asterisk is used as a separator\n- `#( struct #var; )*` — the repetition can contain other things\n- `#( #k =\u003e println!(\"{}\", #v), )*` — even multiple interpolations\n\nNote that there is a difference between `#(#var ,)*` and `#(#var),*`—the latter\ndoes not produce a trailing comma. This matches the behavior of delimiters in\n`macro_rules!`.\n\n\u003cbr\u003e\n\n## Returning tokens to the compiler\n\nThe `quote!` macro evaluates to an expression of type\n`proc_macro2::TokenStream`. Meanwhile Rust procedural macros are expected to\nreturn the type `proc_macro::TokenStream`.\n\nThe difference between the two types is that `proc_macro` types are entirely\nspecific to procedural macros and cannot ever exist in code outside of a\nprocedural macro, while `proc_macro2` types may exist anywhere including tests\nand non-macro code like main.rs and build.rs. This is why even the procedural\nmacro ecosystem is largely built around `proc_macro2`, because that ensures the\nlibraries are unit testable and accessible in non-macro contexts.\n\nThere is a [`From`]-conversion in both directions so returning the output of\n`quote!` from a procedural macro usually looks like `tokens.into()` or\n`proc_macro::TokenStream::from(tokens)`.\n\n[`From`]: https://doc.rust-lang.org/std/convert/trait.From.html\n\n\u003cbr\u003e\n\n## Examples\n\n### Combining quoted fragments\n\nUsually you don't end up constructing an entire final `TokenStream` in one\npiece. Different parts may come from different helper functions. The tokens\nproduced by `quote!` themselves implement `ToTokens` and so can be interpolated\ninto later `quote!` invocations to build up a final result.\n\n```rust\nlet type_definition = quote! {...};\nlet methods = quote! {...};\n\nlet tokens = quote! {\n    #type_definition\n    #methods\n};\n```\n\n### Constructing identifiers\n\nSuppose we have an identifier `ident` which came from somewhere in a macro\ninput and we need to modify it in some way for the macro output. Let's consider\nprepending the identifier with an underscore.\n\nSimply interpolating the identifier next to an underscore will not have the\nbehavior of concatenating them. The underscore and the identifier will continue\nto be two separate tokens as if you had written `_ x`.\n\n```rust\n// incorrect\nquote! {\n    let mut _#ident = 0;\n}\n```\n\nThe solution is to build a new identifier token with the correct value. As this\nis such a common case, the `format_ident!` macro provides a convenient utility\nfor doing so correctly.\n\n```rust\nlet varname = format_ident!(\"_{}\", ident);\nquote! {\n    let mut #varname = 0;\n}\n```\n\nAlternatively, the APIs provided by Syn and proc-macro2 can be used to directly\nbuild the identifier. This is roughly equivalent to the above, but will not\nhandle `ident` being a raw identifier.\n\n```rust\nlet concatenated = format!(\"_{}\", ident);\nlet varname = syn::Ident::new(\u0026concatenated, ident.span());\nquote! {\n    let mut #varname = 0;\n}\n```\n\n### Making method calls\n\nLet's say our macro requires some type specified in the macro input to have a\nconstructor called `new`. We have the type in a variable called `field_type` of\ntype `syn::Type` and want to invoke the constructor.\n\n```rust\n// incorrect\nquote! {\n    let value = #field_type::new();\n}\n```\n\nThis works only sometimes. If `field_type` is `String`, the expanded code\ncontains `String::new()` which is fine. But if `field_type` is something like\n`Vec\u003ci32\u003e` then the expanded code is `Vec\u003ci32\u003e::new()` which is invalid syntax.\nOrdinarily in handwritten Rust we would write `Vec::\u003ci32\u003e::new()` but for macros\noften the following is more convenient.\n\n```rust\nquote! {\n    let value = \u003c#field_type\u003e::new();\n}\n```\n\nThis expands to `\u003cVec\u003ci32\u003e\u003e::new()` which behaves correctly.\n\nA similar pattern is appropriate for trait methods.\n\n```rust\nquote! {\n    let value = \u003c#field_type as core::default::Default\u003e::default();\n}\n```\n\n\u003cbr\u003e\n\n## Hygiene\n\nAny interpolated tokens preserve the `Span` information provided by their\n`ToTokens` implementation. Tokens that originate within a `quote!` invocation\nare spanned with [`Span::call_site()`].\n\n[`Span::call_site()`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.Span.html#method.call_site\n\nA different span can be provided explicitly through the [`quote_spanned!`]\nmacro.\n\n[`quote_spanned!`]: https://docs.rs/quote/1.0/quote/macro.quote_spanned.html\n\n\u003cbr\u003e\n\n## Non-macro code generators\n\nWhen using `quote` in a build.rs or main.rs and writing the output out to a\nfile, consider having the code generator pass the tokens through [prettyplease]\nbefore writing. This way if an error occurs in the generated code it is\nconvenient for a human to read and debug.\n\nBe aware that no kind of hygiene or span information is retained when tokens are\nwritten to a file; the conversion from tokens to source code is lossy.\n\nExample usage in build.rs:\n\n```rust\nlet output = quote! { ... };\nlet syntax_tree = syn::parse2(output).unwrap();\nlet formatted = prettyplease::unparse(\u0026syntax_tree);\n\nlet out_dir = env::var_os(\"OUT_DIR\").unwrap();\nlet dest_path = Path::new(\u0026out_dir).join(\"out.rs\");\nfs::write(dest_path, formatted).unwrap();\n```\n\n[prettyplease]: https://github.com/dtolnay/prettyplease\n\n\u003cbr\u003e\n\n#### License\n\n\u003csup\u003e\nLicensed under either of \u003ca href=\"LICENSE-APACHE\"\u003eApache License, Version\n2.0\u003c/a\u003e or \u003ca href=\"LICENSE-MIT\"\u003eMIT license\u003c/a\u003e at your option.\n\u003c/sup\u003e\n\n\u003cbr\u003e\n\n\u003csub\u003e\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in this crate by you, as defined in the Apache-2.0 license, shall\nbe dual licensed as above, without any additional terms or conditions.\n\u003c/sub\u003e\n","funding_links":["https://github.com/sponsors/dtolnay"],"categories":["Rust"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdtolnay%2Fquote","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdtolnay%2Fquote","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdtolnay%2Fquote/lists"}