diff options
Diffstat (limited to 'third_party/rust/proc-macro-hack')
20 files changed, 1562 insertions, 0 deletions
diff --git a/third_party/rust/proc-macro-hack/.cargo-checksum.json b/third_party/rust/proc-macro-hack/.cargo-checksum.json new file mode 100644 index 0000000000..135de5575c --- /dev/null +++ b/third_party/rust/proc-macro-hack/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"1833d37aad8fa07e58d16c840b2815da2114c6d92d3625de45baa66b986a68cc","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"d59d2723bbc1627b629429a9c779d5dcfde579c9723e6ded1052931c4e8efa0a","README.md":"ca7e8118aeda26c39cbeaeb0a4cbf5d44bdf17eedc89abbff5d307e4abffdf33","build.rs":"eae956d2a2de606f0c26741fbc849f3c9db89bf14f743d76a452b85c7904860c","src/error.rs":"d31547fe853819b03cf1a485827ceaa7ebffbd45a8d5ef066e94cc862f499583","src/iter.rs":"8d4b817b9abc4e817105b673e15f29ef9bb8284a010ce01ac2d83387fe136947","src/lib.rs":"4b966fffe1e74857e902f0417bfc6f59d063f48f24bc12f0fec3d35e9882365f","src/parse.rs":"53f45dff0aa345644e6cf56619704d413ed732d30f353b966cbf39dd0c00e093","src/quote.rs":"2f8c5ff5174f8869f4fd317156396be6d90b0af566f44840a2cadb2d1180fb45","tests/compiletest.rs":"0a52a44786aea1c299c695bf948b2ed2081e4cc344e5c2cadceab4eb03d0010d","tests/ui/private.rs":"f58d9fafe29bb624cbd8b2fbfce4e0ba9526d5e7a7bcb4366ebe02a192d742e4","tests/ui/private.stderr":"ef4b8437d818a0e037ad23b19ef6d2971e46a4cfe94707d9c5dd402e390ef595","tests/ui/unexpected-arg.rs":"27f8baf78620673ce49eb4a376dd2210e446d2fbc33a4160aa72c40f597a599a","tests/ui/unexpected-arg.stderr":"79e6ff168baf87576c95821d11ec48e7701d50c8c93811aaf9715c1de8e77ce0","tests/ui/unexpected.rs":"157afd8323c9226a8f9ac1f1623a7747d8b9563e95b66d0208020d2d15781adc","tests/ui/unexpected.stderr":"7478c6e53832e3fe5fd6be30aad2824e920780d9b6355b95ca35ffcd2522c3b0","tests/ui/unknown-arg.rs":"724aeb6614c96e925856fb0e73ec38312cc9abc918094188d928e41626fbe512","tests/ui/unknown-arg.stderr":"379cb35e501c17091dd999f0bb889c25596d94838ff5a1437407d4f97f8c13b1"},"package":"dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"}
\ No newline at end of file diff --git a/third_party/rust/proc-macro-hack/Cargo.toml b/third_party/rust/proc-macro-hack/Cargo.toml new file mode 100644 index 0000000000..ec46c31a94 --- /dev/null +++ b/third_party/rust/proc-macro-hack/Cargo.toml @@ -0,0 +1,47 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.31" +name = "proc-macro-hack" +version = "0.5.20+deprecated" +authors = ["David Tolnay <dtolnay@gmail.com>"] +description = "Procedural macros in expression position" +readme = "README.md" +categories = ["development-tools::procedural-macro-helpers"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/proc-macro-hack" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +proc-macro = true + +[dev-dependencies.demo-hack] +version = "0.0.5" + +[dev-dependencies.demo-hack-impl] +version = "0.0.5" + +[dev-dependencies.quote] +version = "1.0" + +[dev-dependencies.rustversion] +version = "1.0" + +[dev-dependencies.syn] +version = "1.0.5" + +[dev-dependencies.trybuild] +version = "1.0.49" +features = ["diff"] diff --git a/third_party/rust/proc-macro-hack/LICENSE-APACHE b/third_party/rust/proc-macro-hack/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/third_party/rust/proc-macro-hack/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third_party/rust/proc-macro-hack/LICENSE-MIT b/third_party/rust/proc-macro-hack/LICENSE-MIT new file mode 100644 index 0000000000..f2675cdf1e --- /dev/null +++ b/third_party/rust/proc-macro-hack/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 David Tolnay + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/proc-macro-hack/README.md b/third_party/rust/proc-macro-hack/README.md new file mode 100644 index 0000000000..b72b8ef9dd --- /dev/null +++ b/third_party/rust/proc-macro-hack/README.md @@ -0,0 +1,155 @@ +Procedural macros in expression position +======================================== + +[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/proc--macro--hack-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/proc-macro-hack) +[<img alt="crates.io" src="https://img.shields.io/crates/v/proc-macro-hack.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/proc-macro-hack) +[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-proc--macro--hack-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/proc-macro-hack) +[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/proc-macro-hack/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/proc-macro-hack/actions?query=branch%3Amaster) + +<table><tr><td><hr> +<b>Note:</b> <i>As of Rust 1.45 this crate is superseded by native support for +#[proc_macro] in expression position. Only consider using this crate if you care +about supporting compilers between 1.31 and 1.45.</i> +<hr></td></tr></table> + +Since Rust 1.30, the language supports user-defined function-like procedural +macros. However these can only be invoked in item position, not in statements or +expressions. + +This crate implements an alternative type of procedural macro that can be +invoked in statement or expression position. + +This approach works with any Rust version 1.31+. + +## Defining procedural macros + +Two crates are required to define a procedural macro. + +### The implementation crate + +This crate must contain nothing but procedural macros. Private helper +functions and private modules are fine but nothing can be public. + +[» example of an implementation crate][demo-hack-impl] + +Just like you would use a #\[proc_macro\] attribute to define a natively +supported procedural macro, use proc-macro-hack's #\[proc_macro_hack\] +attribute to define a procedural macro that works in expression position. +The function signature is the same as for ordinary function-like procedural +macros. + +```rust +use proc_macro::TokenStream; +use proc_macro_hack::proc_macro_hack; +use quote::quote; +use syn::{parse_macro_input, Expr}; + +#[proc_macro_hack] +pub fn add_one(input: TokenStream) -> TokenStream { + let expr = parse_macro_input!(input as Expr); + TokenStream::from(quote! { + 1 + (#expr) + }) +} +``` + +### The declaration crate + +This crate is allowed to contain other public things if you need, for +example traits or functions or ordinary macros. + +[» example of a declaration crate][demo-hack] + +Within the declaration crate there needs to be a re-export of your +procedural macro from the implementation crate. The re-export also carries a +\#\[proc_macro_hack\] attribute. + +```rust +use proc_macro_hack::proc_macro_hack; + +/// Add one to an expression. +/// +/// (Documentation goes here on the re-export, not in the other crate.) +#[proc_macro_hack] +pub use demo_hack_impl::add_one; +``` + +Both crates depend on `proc-macro-hack`: + +```toml +[dependencies] +proc-macro-hack = "0.5" +``` + +Additionally, your implementation crate (but not your declaration crate) is +a proc macro crate: + +```toml +[lib] +proc-macro = true +``` + +## Using procedural macros + +Users of your crate depend on your declaration crate (not your +implementation crate), then use your procedural macros as usual. + +[» example of a downstream crate][example] + +```rust +use demo_hack::add_one; + +fn main() { + let two = 2; + let nine = add_one!(two) + add_one!(2 + 3); + println!("nine = {}", nine); +} +``` + +[demo-hack-impl]: https://github.com/dtolnay/proc-macro-hack/tree/master/demo-hack-impl +[demo-hack]: https://github.com/dtolnay/proc-macro-hack/tree/master/demo-hack +[example]: https://github.com/dtolnay/proc-macro-hack/tree/master/example + +## Limitations + +- Only proc macros in expression position are supported. Proc macros in pattern + position ([#20]) are not supported. + +- By default, nested invocations are not supported i.e. the code emitted by a + proc-macro-hack macro invocation cannot contain recursive calls to the same + proc-macro-hack macro nor calls to any other proc-macro-hack macros. Use + [`proc-macro-nested`] if you require support for nested invocations. + +- By default, hygiene is structured such that the expanded code can't refer to + local variables other than those passed by name somewhere in the macro input. + If your macro must refer to *local* variables that don't get named in the + macro input, use `#[proc_macro_hack(fake_call_site)]` on the re-export in your + declaration crate. *Most macros won't need this.* + +- On compilers that are new enough to natively support proc macros in expression + position, proc-macro-hack does not automatically use that support, since the + hygiene can be subtly different between the two implementations. To opt in to + compiling your macro to native `#[proc_macro]` on sufficiently new compilers, + use `#[proc_macro_hack(only_hack_old_rustc)]` on the re-export in your + declaration crate. + +[#10]: https://github.com/dtolnay/proc-macro-hack/issues/10 +[#20]: https://github.com/dtolnay/proc-macro-hack/issues/20 +[`proc-macro-nested`]: https://docs.rs/proc-macro-nested + +<br> + +#### License + +<sup> +Licensed under either of <a href="LICENSE-APACHE">Apache License, Version +2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. +</sup> + +<br> + +<sub> +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this hack by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. +</sub> diff --git a/third_party/rust/proc-macro-hack/build.rs b/third_party/rust/proc-macro-hack/build.rs new file mode 100644 index 0000000000..6ab40985b6 --- /dev/null +++ b/third_party/rust/proc-macro-hack/build.rs @@ -0,0 +1,31 @@ +use std::env; +use std::process::Command; +use std::str; + +// The rustc-cfg strings below are *not* public API. Please let us know by +// opening a GitHub issue if your build environment requires some way to enable +// these cfgs other than by executing our build script. +fn main() { + let minor = match rustc_minor_version() { + Some(minor) => minor, + None => return, + }; + + // Function-like procedural macros in expressions, patterns, and statements + // stabilized in Rust 1.45: + // https://blog.rust-lang.org/2020/07/16/Rust-1.45.0.html#stabilizing-function-like-procedural-macros-in-expressions-patterns-and-statements + if minor < 45 { + println!("cargo:rustc-cfg=need_proc_macro_hack"); + } +} + +fn rustc_minor_version() -> Option<u32> { + let rustc = env::var_os("RUSTC")?; + let output = Command::new(rustc).arg("--version").output().ok()?; + let version = str::from_utf8(&output.stdout).ok()?; + let mut pieces = version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + pieces.next()?.parse().ok() +} diff --git a/third_party/rust/proc-macro-hack/src/error.rs b/third_party/rust/proc-macro-hack/src/error.rs new file mode 100644 index 0000000000..7334a53d9a --- /dev/null +++ b/third_party/rust/proc-macro-hack/src/error.rs @@ -0,0 +1,39 @@ +use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::iter::FromIterator; + +pub struct Error { + span: Span, + msg: String, +} + +impl Error { + pub fn new(span: Span, msg: impl Into<String>) -> Self { + Error { + span, + msg: msg.into(), + } + } +} + +pub fn compile_error(err: Error) -> TokenStream { + // compile_error!($msg) + TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("compile_error", err.span)), + TokenTree::Punct({ + let mut punct = Punct::new('!', Spacing::Alone); + punct.set_span(err.span); + punct + }), + TokenTree::Group({ + let mut group = Group::new(Delimiter::Brace, { + TokenStream::from_iter(vec![TokenTree::Literal({ + let mut string = Literal::string(&err.msg); + string.set_span(err.span); + string + })]) + }); + group.set_span(err.span); + group + }), + ]) +} diff --git a/third_party/rust/proc-macro-hack/src/iter.rs b/third_party/rust/proc-macro-hack/src/iter.rs new file mode 100644 index 0000000000..722013c7d6 --- /dev/null +++ b/third_party/rust/proc-macro-hack/src/iter.rs @@ -0,0 +1,42 @@ +use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree}; + +pub type Iter<'a> = &'a mut IterImpl; + +pub struct IterImpl { + stack: Vec<token_stream::IntoIter>, + peeked: Option<TokenTree>, +} + +pub fn new(tokens: TokenStream) -> IterImpl { + IterImpl { + stack: vec![tokens.into_iter()], + peeked: None, + } +} + +impl IterImpl { + pub fn peek(&mut self) -> Option<&TokenTree> { + self.peeked = self.next(); + self.peeked.as_ref() + } +} + +impl Iterator for IterImpl { + type Item = TokenTree; + + fn next(&mut self) -> Option<Self::Item> { + if let Some(tt) = self.peeked.take() { + return Some(tt); + } + loop { + let top = self.stack.last_mut()?; + match top.next() { + None => drop(self.stack.pop()), + Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::None => { + self.stack.push(group.stream().into_iter()); + } + Some(tt) => return Some(tt), + } + } + } +} diff --git a/third_party/rust/proc-macro-hack/src/lib.rs b/third_party/rust/proc-macro-hack/src/lib.rs new file mode 100644 index 0000000000..9a5a8ac432 --- /dev/null +++ b/third_party/rust/proc-macro-hack/src/lib.rs @@ -0,0 +1,599 @@ +//! [![github]](https://github.com/dtolnay/proc-macro-hack) [![crates-io]](https://crates.io/crates/proc-macro-hack) [![docs-rs]](https://docs.rs/proc-macro-hack) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs +//! +//! <br> +//! +//! <table><tr><td><hr> +//! <b>Note:</b> <i>As of Rust 1.45 this crate is superseded by native support +//! for #[proc_macro] in expression position. Only consider using this crate if +//! you care about supporting compilers between 1.31 and 1.45.</i> +//! <hr></td></tr></table> +//! +//! Since Rust 1.30, the language supports user-defined function-like procedural +//! macros. However these can only be invoked in item position, not in +//! statements or expressions. +//! +//! This crate implements an alternative type of procedural macro that can be +//! invoked in statement or expression position. +//! +//! # Defining procedural macros +//! +//! Two crates are required to define a procedural macro. +//! +//! ## The implementation crate +//! +//! This crate must contain nothing but procedural macros. Private helper +//! functions and private modules are fine but nothing can be public. +//! +//! [» example of an implementation crate][demo-hack-impl] +//! +//! Just like you would use a #\[proc_macro\] attribute to define a natively +//! supported procedural macro, use proc-macro-hack's #\[proc_macro_hack\] +//! attribute to define a procedural macro that works in expression position. +//! The function signature is the same as for ordinary function-like procedural +//! macros. +//! +//! ``` +//! # extern crate proc_macro; +//! # +//! use proc_macro::TokenStream; +//! use proc_macro_hack::proc_macro_hack; +//! use quote::quote; +//! use syn::{parse_macro_input, Expr}; +//! +//! # const IGNORE: &str = stringify! { +//! #[proc_macro_hack] +//! # }; +//! pub fn add_one(input: TokenStream) -> TokenStream { +//! let expr = parse_macro_input!(input as Expr); +//! TokenStream::from(quote! { +//! 1 + (#expr) +//! }) +//! } +//! # +//! # fn main() {} +//! ``` +//! +//! ## The declaration crate +//! +//! This crate is allowed to contain other public things if you need, for +//! example traits or functions or ordinary macros. +//! +//! [» example of a declaration crate][demo-hack] +//! +//! Within the declaration crate there needs to be a re-export of your +//! procedural macro from the implementation crate. The re-export also carries a +//! \#\[proc_macro_hack\] attribute. +//! +//! ``` +//! use proc_macro_hack::proc_macro_hack; +//! +//! /// Add one to an expression. +//! /// +//! /// (Documentation goes here on the re-export, not in the other crate.) +//! #[proc_macro_hack] +//! pub use demo_hack_impl::add_one; +//! # +//! # fn main() {} +//! ``` +//! +//! Both crates depend on `proc-macro-hack`: +//! +//! ```toml +//! [dependencies] +//! proc-macro-hack = "0.5" +//! ``` +//! +//! Additionally, your implementation crate (but not your declaration crate) is +//! a proc macro crate: +//! +//! ```toml +//! [lib] +//! proc-macro = true +//! ``` +//! +//! # Using procedural macros +//! +//! Users of your crate depend on your declaration crate (not your +//! implementation crate), then use your procedural macros as usual. +//! +//! [» example of a downstream crate][example] +//! +//! ``` +//! use demo_hack::add_one; +//! +//! fn main() { +//! let two = 2; +//! let nine = add_one!(two) + add_one!(2 + 3); +//! println!("nine = {}", nine); +//! } +//! ``` +//! +//! [demo-hack-impl]: https://github.com/dtolnay/proc-macro-hack/tree/master/demo-hack-impl +//! [demo-hack]: https://github.com/dtolnay/proc-macro-hack/tree/master/demo-hack +//! [example]: https://github.com/dtolnay/proc-macro-hack/tree/master/example +//! +//! # Limitations +//! +//! - Only proc macros in expression position are supported. Proc macros in +//! pattern position ([#20]) are not supported. +//! +//! - By default, nested invocations are not supported i.e. the code emitted by +//! a proc-macro-hack macro invocation cannot contain recursive calls to the +//! same proc-macro-hack macro nor calls to any other proc-macro-hack macros. +//! Use [`proc-macro-nested`] if you require support for nested invocations. +//! +//! - By default, hygiene is structured such that the expanded code can't refer +//! to local variables other than those passed by name somewhere in the macro +//! input. If your macro must refer to *local* variables that don't get named +//! in the macro input, use `#[proc_macro_hack(fake_call_site)]` on the +//! re-export in your declaration crate. *Most macros won't need this.* +//! +//! - On compilers that are new enough to natively support proc macros in +//! expression position, proc-macro-hack does not automatically use that +//! support, since the hygiene can be subtly different between the two +//! implementations. To opt in to compiling your macro to native +//! `#[proc_macro]` on sufficiently new compilers, use +//! `#[proc_macro_hack(only_hack_old_rustc)]` on the re-export in your +//! declaration crate. +//! +//! [#10]: https://github.com/dtolnay/proc-macro-hack/issues/10 +//! [#20]: https://github.com/dtolnay/proc-macro-hack/issues/20 +//! [`proc-macro-nested`]: https://docs.rs/proc-macro-nested + +#![recursion_limit = "512"] +#![allow( + clippy::doc_markdown, + clippy::manual_strip, + clippy::module_name_repetitions, + clippy::needless_doctest_main, + clippy::needless_pass_by_value, + clippy::too_many_lines, + clippy::toplevel_ref_arg +)] + +extern crate proc_macro; + +#[macro_use] +mod quote; + +mod error; +mod iter; +mod parse; + +use crate::error::{compile_error, Error}; +use crate::iter::Iter; +use crate::parse::{ + parse_define_args, parse_enum_hack, parse_export_args, parse_fake_call_site, parse_input, +}; +use proc_macro::{Ident, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::fmt::Write; + +type Visibility = Option<Ident>; + +enum Input { + Export(Export), + Define(Define), +} + +// pub use demo_hack_impl::{m1, m2 as qrst}; +struct Export { + attrs: TokenStream, + vis: Visibility, + from: Ident, + macros: Vec<Macro>, +} + +// pub fn m1(input: TokenStream) -> TokenStream { ... } +struct Define { + attrs: TokenStream, + name: Ident, + body: TokenStream, +} + +struct Macro { + name: Ident, + export_as: Ident, +} + +#[proc_macro_attribute] +pub fn proc_macro_hack(args: TokenStream, input: TokenStream) -> TokenStream { + let ref mut args = iter::new(args); + let ref mut input = iter::new(input); + expand_proc_macro_hack(args, input).unwrap_or_else(compile_error) +} + +fn expand_proc_macro_hack(args: Iter, input: Iter) -> Result<TokenStream, Error> { + match parse_input(input)? { + Input::Export(export) => { + let args = parse_export_args(args)?; + Ok(expand_export(export, args)) + } + Input::Define(define) => { + parse_define_args(args)?; + Ok(expand_define(define)) + } + } +} + +#[doc(hidden)] +#[proc_macro_derive(ProcMacroHack)] +pub fn enum_hack(input: TokenStream) -> TokenStream { + let ref mut input = iter::new(input); + parse_enum_hack(input).unwrap_or_else(compile_error) +} + +struct FakeCallSite { + derive: Ident, + rest: TokenStream, +} + +#[doc(hidden)] +#[proc_macro_attribute] +pub fn fake_call_site(args: TokenStream, input: TokenStream) -> TokenStream { + let ref mut args = iter::new(args); + let ref mut input = iter::new(input); + expand_fake_call_site(args, input).unwrap_or_else(compile_error) +} + +fn expand_fake_call_site(args: Iter, input: Iter) -> Result<TokenStream, Error> { + let span = match args.next() { + Some(token) => token.span(), + None => return Ok(input.collect()), + }; + + let input = parse_fake_call_site(input)?; + let mut derive = input.derive; + derive.set_span(span); + let rest = input.rest; + + Ok(quote! { + #[derive(#derive)] + #rest + }) +} + +struct ExportArgs { + support_nested: bool, + internal_macro_calls: u16, + fake_call_site: bool, + only_hack_old_rustc: bool, +} + +fn expand_export(export: Export, args: ExportArgs) -> TokenStream { + if args.only_hack_old_rustc && cfg!(not(need_proc_macro_hack)) { + return expand_export_nohack(export); + } + + let dummy = dummy_name_for_export(&export); + + let attrs = export.attrs; + let vis = export.vis; + let macro_export = match vis { + Some(_) => quote!(#[macro_export]), + None => quote!(), + }; + let crate_prefix = vis.as_ref().map(|_| quote!($crate::)); + let enum_variant = if args.support_nested { + if args.internal_macro_calls == 0 { + Ident::new("Nested", Span::call_site()) + } else { + let name = format!("Nested{}", args.internal_macro_calls); + Ident::new(&name, Span::call_site()) + } + } else { + Ident::new("Value", Span::call_site()) + }; + + let from = export.from; + let mut actual_names = TokenStream::new(); + let mut export_dispatch = TokenStream::new(); + let mut export_call_site = TokenStream::new(); + let mut macro_rules = TokenStream::new(); + for Macro { name, export_as } in &export.macros { + let hacked = hacked_proc_macro_name(name); + let dispatch = dispatch_macro_name(name); + let call_site = call_site_macro_name(name); + + if !actual_names.is_empty() { + actual_names.extend(quote!(,)); + } + actual_names.extend(quote!(#hacked)); + + if !export_dispatch.is_empty() { + export_dispatch.extend(quote!(,)); + } + export_dispatch.extend(quote!(dispatch as #dispatch)); + + if !export_call_site.is_empty() { + export_call_site.extend(quote!(,)); + } + export_call_site.extend(quote!(fake_call_site as #call_site)); + + let do_derive = if !args.fake_call_site { + quote! { + #[derive(#crate_prefix #hacked)] + } + } else if crate_prefix.is_some() { + quote! { + use #crate_prefix #hacked; + #[#crate_prefix #call_site ($($proc_macro)*)] + #[derive(#hacked)] + } + } else { + quote! { + #[#call_site ($($proc_macro)*)] + #[derive(#hacked)] + } + }; + + let proc_macro_call = if args.support_nested { + let extra_bangs = (0..args.internal_macro_calls) + .map(|_| TokenTree::Punct(Punct::new('!', Spacing::Alone))) + .collect::<TokenStream>(); + quote! { + #crate_prefix #dispatch! { ($($proc_macro)*) #extra_bangs } + } + } else { + quote! { + proc_macro_call!() + } + }; + + macro_rules.extend(quote! { + #attrs + #macro_export + macro_rules! #export_as { + ($($proc_macro:tt)*) => {{ + #do_derive + #[allow(dead_code)] + enum ProcMacroHack { + #enum_variant = (stringify! { $($proc_macro)* }, 0).1, + } + #proc_macro_call + }}; + } + }); + } + + if export.macros.len() != 1 { + export_dispatch = quote!({#export_dispatch}); + export_call_site = quote!({#export_call_site}); + actual_names = quote!({#actual_names}); + } + + let export_dispatch = if args.support_nested { + quote! { + #[doc(hidden)] + #vis use proc_macro_nested::#export_dispatch; + } + } else { + quote!() + }; + + let export_call_site = if args.fake_call_site { + quote! { + #[doc(hidden)] + #vis use proc_macro_hack::#export_call_site; + } + } else { + quote!() + }; + + let expanded = quote! { + #[doc(hidden)] + #vis use #from::#actual_names; + + #export_dispatch + #export_call_site + + #macro_rules + }; + + wrap_in_enum_hack(dummy, expanded) +} + +fn expand_export_nohack(export: Export) -> TokenStream { + let attrs = export.attrs; + let vis = export.vis; + let from = export.from; + let mut names = TokenStream::new(); + + for Macro { name, export_as } in &export.macros { + let pub_name = pub_proc_macro_name(name); + if !names.is_empty() { + names.extend(quote!(,)); + } + names.extend(quote!(#pub_name as #export_as)); + } + + if export.macros.len() != 1 { + names = quote!({#names}); + } + + quote! { + #attrs + #vis use #from::#names; + } +} + +fn expand_define(define: Define) -> TokenStream { + let attrs = define.attrs; + let name = define.name; + let pub_name = pub_proc_macro_name(&name); + let hacked = hacked_proc_macro_name(&name); + let body = define.body; + + quote! { + mod #pub_name { + extern crate proc_macro; + pub use self::proc_macro::*; + } + + #attrs + #[doc(hidden)] + #[proc_macro_derive(#hacked)] + pub fn #hacked(input: #pub_name::TokenStream) -> #pub_name::TokenStream { + use std::iter::FromIterator; + + let mut iter = input.into_iter(); + iter.next().unwrap(); // `enum` + iter.next().unwrap(); // `ProcMacroHack` + iter.next().unwrap(); // `#` + iter.next().unwrap(); // `[allow(dead_code)]` + + let mut braces = match iter.next().unwrap() { + #pub_name::TokenTree::Group(group) => group.stream().into_iter(), + _ => unimplemented!(), + }; + let variant = braces.next().unwrap(); // `Value` or `Nested` + let varname = variant.to_string(); + let support_nested = varname.starts_with("Nested"); + braces.next().unwrap(); // `=` + + let mut parens = match braces.next().unwrap() { + #pub_name::TokenTree::Group(group) => group.stream().into_iter(), + _ => unimplemented!(), + }; + parens.next().unwrap(); // `stringify` + parens.next().unwrap(); // `!` + + let inner = match parens.next().unwrap() { + #pub_name::TokenTree::Group(group) => group.stream(), + _ => unimplemented!(), + }; + + let output: #pub_name::TokenStream = #name(inner.clone()); + + fn count_bangs(input: #pub_name::TokenStream) -> usize { + let mut count = 0; + for token in input { + match token { + #pub_name::TokenTree::Punct(punct) => { + if punct.as_char() == '!' { + count += 1; + } + } + #pub_name::TokenTree::Group(group) => { + count += count_bangs(group.stream()); + } + _ => {} + } + } + count + } + + // macro_rules! proc_macro_call { + // () => { #output } + // } + #pub_name::TokenStream::from_iter(vec![ + #pub_name::TokenTree::Ident( + #pub_name::Ident::new("macro_rules", #pub_name::Span::call_site()), + ), + #pub_name::TokenTree::Punct( + #pub_name::Punct::new('!', #pub_name::Spacing::Alone), + ), + #pub_name::TokenTree::Ident( + #pub_name::Ident::new( + &if support_nested { + let extra_bangs = if varname == "Nested" { + 0 + } else { + varname["Nested".len()..].parse().unwrap() + }; + format!("proc_macro_call_{}", extra_bangs + count_bangs(inner)) + } else { + String::from("proc_macro_call") + }, + #pub_name::Span::call_site(), + ), + ), + #pub_name::TokenTree::Group( + #pub_name::Group::new(#pub_name::Delimiter::Brace, #pub_name::TokenStream::from_iter(vec![ + #pub_name::TokenTree::Group( + #pub_name::Group::new(#pub_name::Delimiter::Parenthesis, #pub_name::TokenStream::new()), + ), + #pub_name::TokenTree::Punct( + #pub_name::Punct::new('=', #pub_name::Spacing::Joint), + ), + #pub_name::TokenTree::Punct( + #pub_name::Punct::new('>', #pub_name::Spacing::Alone), + ), + #pub_name::TokenTree::Group( + #pub_name::Group::new(#pub_name::Delimiter::Brace, output), + ), + ])), + ), + ]) + } + + #attrs + #[proc_macro] + pub fn #pub_name(input: #pub_name::TokenStream) -> #pub_name::TokenStream { + #name(input) + } + + fn #name #body + } +} + +fn pub_proc_macro_name(conceptual: &Ident) -> Ident { + Ident::new( + &format!("proc_macro_hack_{}", conceptual), + conceptual.span(), + ) +} + +fn hacked_proc_macro_name(conceptual: &Ident) -> Ident { + Ident::new( + &format!("_proc_macro_hack_{}", conceptual), + conceptual.span(), + ) +} + +fn dispatch_macro_name(conceptual: &Ident) -> Ident { + Ident::new( + &format!("proc_macro_call_{}", conceptual), + conceptual.span(), + ) +} + +fn call_site_macro_name(conceptual: &Ident) -> Ident { + Ident::new( + &format!("proc_macro_fake_call_site_{}", conceptual), + conceptual.span(), + ) +} + +fn dummy_name_for_export(export: &Export) -> String { + let mut dummy = String::new(); + let from = unraw(&export.from).to_string(); + write!(dummy, "_{}{}", from.len(), from).unwrap(); + for m in &export.macros { + let name = unraw(&m.name).to_string(); + write!(dummy, "_{}{}", name.len(), name).unwrap(); + } + dummy +} + +fn unraw(ident: &Ident) -> Ident { + let string = ident.to_string(); + if string.starts_with("r#") { + Ident::new(&string[2..], ident.span()) + } else { + ident.clone() + } +} + +fn wrap_in_enum_hack(dummy: String, inner: TokenStream) -> TokenStream { + let dummy = Ident::new(&dummy, Span::call_site()); + quote! { + #[derive(proc_macro_hack::ProcMacroHack)] + enum #dummy { + Value = (stringify! { #inner }, 0).1, + } + } +} diff --git a/third_party/rust/proc-macro-hack/src/parse.rs b/third_party/rust/proc-macro-hack/src/parse.rs new file mode 100644 index 0000000000..f9c3b80290 --- /dev/null +++ b/third_party/rust/proc-macro-hack/src/parse.rs @@ -0,0 +1,254 @@ +use crate::iter::{self, Iter, IterImpl}; +use crate::{Define, Error, Export, ExportArgs, FakeCallSite, Input, Macro, Visibility}; +use proc_macro::Delimiter::{Brace, Bracket, Parenthesis}; +use proc_macro::{Delimiter, Ident, Span, TokenStream, TokenTree}; + +pub(crate) fn parse_input(tokens: Iter) -> Result<Input, Error> { + let attrs = parse_attributes(tokens)?; + let vis = parse_visibility(tokens); + let kw = parse_ident(tokens)?; + if kw.to_string() == "use" { + parse_export(attrs, vis, tokens).map(Input::Export) + } else if kw.to_string() == "fn" { + parse_define(attrs, vis, kw.span(), tokens).map(Input::Define) + } else { + Err(Error::new( + kw.span(), + "unexpected input to #[proc_macro_hack]", + )) + } +} + +fn parse_export(attrs: TokenStream, vis: Visibility, tokens: Iter) -> Result<Export, Error> { + let _ = parse_punct(tokens, ':'); + let _ = parse_punct(tokens, ':'); + let from = parse_ident(tokens)?; + parse_punct(tokens, ':')?; + parse_punct(tokens, ':')?; + + let mut macros = Vec::new(); + match tokens.peek() { + Some(TokenTree::Group(group)) if group.delimiter() == Brace => { + let ref mut content = iter::new(group.stream()); + loop { + macros.push(parse_macro(content)?); + if content.peek().is_none() { + break; + } + parse_punct(content, ',')?; + if content.peek().is_none() { + break; + } + } + tokens.next().unwrap(); + } + _ => macros.push(parse_macro(tokens)?), + } + + parse_punct(tokens, ';')?; + Ok(Export { + attrs, + vis, + from, + macros, + }) +} + +fn parse_punct(tokens: Iter, ch: char) -> Result<(), Error> { + match tokens.peek() { + Some(TokenTree::Punct(punct)) if punct.as_char() == ch => { + tokens.next().unwrap(); + Ok(()) + } + tt => Err(Error::new( + tt.map_or_else(Span::call_site, TokenTree::span), + format!("expected `{}`", ch), + )), + } +} + +fn parse_define( + attrs: TokenStream, + vis: Visibility, + fn_token: Span, + tokens: Iter, +) -> Result<Define, Error> { + if vis.is_none() { + return Err(Error::new( + fn_token, + "functions tagged with `#[proc_macro_hack]` must be `pub`", + )); + } + let name = parse_ident(tokens)?; + let body = tokens.collect(); + Ok(Define { attrs, name, body }) +} + +fn parse_macro(tokens: Iter) -> Result<Macro, Error> { + let name = parse_ident(tokens)?; + let export_as = match tokens.peek() { + Some(TokenTree::Ident(ident)) if ident.to_string() == "as" => { + tokens.next().unwrap(); + parse_ident(tokens)? + } + _ => name.clone(), + }; + Ok(Macro { name, export_as }) +} + +fn parse_ident(tokens: Iter) -> Result<Ident, Error> { + match tokens.next() { + Some(TokenTree::Ident(ident)) => Ok(ident), + tt => Err(Error::new( + tt.as_ref().map_or_else(Span::call_site, TokenTree::span), + "expected identifier", + )), + } +} + +fn parse_keyword(tokens: Iter, kw: &'static str) -> Result<(), Error> { + match &tokens.next() { + Some(TokenTree::Ident(ident)) if ident.to_string() == kw => Ok(()), + tt => Err(Error::new( + tt.as_ref().map_or_else(Span::call_site, TokenTree::span), + format!("expected `{}`", kw), + )), + } +} + +fn parse_int(tokens: Iter) -> Result<u16, Span> { + match tokens.next() { + Some(TokenTree::Literal(lit)) => lit.to_string().parse().map_err(|_| lit.span()), + Some(tt) => Err(tt.span()), + None => Err(Span::call_site()), + } +} + +fn parse_group(tokens: Iter, delimiter: Delimiter) -> Result<IterImpl, Error> { + match &tokens.next() { + Some(TokenTree::Group(group)) if group.delimiter() == delimiter => { + Ok(iter::new(group.stream())) + } + tt => Err(Error::new( + tt.as_ref().map_or_else(Span::call_site, TokenTree::span), + "expected delimiter", + )), + } +} + +fn parse_visibility(tokens: Iter) -> Visibility { + if let Some(TokenTree::Ident(ident)) = tokens.peek() { + if ident.to_string() == "pub" { + match tokens.next().unwrap() { + TokenTree::Ident(vis) => return Some(vis), + _ => unreachable!(), + } + } + } + None +} + +fn parse_attributes(tokens: Iter) -> Result<TokenStream, Error> { + let mut attrs = TokenStream::new(); + while let Some(TokenTree::Punct(punct)) = tokens.peek() { + if punct.as_char() != '#' { + break; + } + let span = punct.span(); + attrs.extend(tokens.next()); + match tokens.peek() { + Some(TokenTree::Group(group)) if group.delimiter() == Bracket => { + attrs.extend(tokens.next()); + } + _ => return Err(Error::new(span, "unexpected input")), + } + } + Ok(attrs) +} + +pub(crate) fn parse_export_args(tokens: Iter) -> Result<ExportArgs, Error> { + let mut args = ExportArgs { + support_nested: false, + internal_macro_calls: 0, + fake_call_site: false, + only_hack_old_rustc: false, + }; + + while let Some(tt) = tokens.next() { + match &tt { + TokenTree::Ident(ident) if ident.to_string() == "support_nested" => { + args.support_nested = true; + } + TokenTree::Ident(ident) if ident.to_string() == "internal_macro_calls" => { + parse_punct(tokens, '=')?; + let calls = parse_int(tokens).map_err(|span| { + Error::new(span, "expected integer value for internal_macro_calls") + })?; + args.internal_macro_calls = calls; + } + TokenTree::Ident(ident) if ident.to_string() == "fake_call_site" => { + args.fake_call_site = true; + } + TokenTree::Ident(ident) if ident.to_string() == "only_hack_old_rustc" => { + args.only_hack_old_rustc = true; + } + _ => { + return Err(Error::new( + tt.span(), + "expected one of: `support_nested`, `internal_macro_calls`, `fake_call_site`, `only_hack_old_rustc`", + )); + } + } + if tokens.peek().is_none() { + break; + } + parse_punct(tokens, ',')?; + } + + Ok(args) +} + +pub(crate) fn parse_define_args(tokens: Iter) -> Result<(), Error> { + match tokens.peek() { + None => Ok(()), + Some(token) => Err(Error::new( + token.span(), + "unexpected argument to proc_macro_hack macro implementation; args are only accepted on the macro declaration (the `pub use`)", + )), + } +} + +pub(crate) fn parse_enum_hack(tokens: Iter) -> Result<TokenStream, Error> { + parse_keyword(tokens, "enum")?; + parse_ident(tokens)?; + + let ref mut braces = parse_group(tokens, Brace)?; + parse_ident(braces)?; + parse_punct(braces, '=')?; + + let ref mut parens = parse_group(braces, Parenthesis)?; + parse_ident(parens)?; + parse_punct(parens, '!')?; + + let ref mut inner = parse_group(parens, Brace)?; + let token_stream = inner.collect(); + + parse_punct(parens, ',')?; + let _ = parens.next(); + parse_punct(braces, '.')?; + let _ = braces.next(); + parse_punct(braces, ',')?; + + Ok(token_stream) +} + +pub(crate) fn parse_fake_call_site(tokens: Iter) -> Result<FakeCallSite, Error> { + parse_punct(tokens, '#')?; + let ref mut attr = parse_group(tokens, Bracket)?; + parse_keyword(attr, "derive")?; + let ref mut path = parse_group(attr, Parenthesis)?; + Ok(FakeCallSite { + derive: parse_ident(path)?, + rest: tokens.collect(), + }) +} diff --git a/third_party/rust/proc-macro-hack/src/quote.rs b/third_party/rust/proc-macro-hack/src/quote.rs new file mode 100644 index 0000000000..a3d648d1a4 --- /dev/null +++ b/third_party/rust/proc-macro-hack/src/quote.rs @@ -0,0 +1,114 @@ +use proc_macro::{Ident, TokenStream, TokenTree}; +use std::iter; + +macro_rules! quote { + () => { + ::proc_macro::TokenStream::new() + }; + ($($tt:tt)*) => {{ + let mut tokens = ::proc_macro::TokenStream::new(); + quote_each_token!(tokens $($tt)*); + tokens + }}; +} + +macro_rules! quote_each_token { + ($tokens:ident # $var:ident $($rest:tt)*) => { + $crate::quote::Tokens::extend(&mut $tokens, &$var); + quote_each_token!($tokens $($rest)*); + }; + ($tokens:ident $ident:ident $($rest:tt)*) => { + <::proc_macro::TokenStream as ::std::iter::Extend<_>>::extend( + &mut $tokens, + ::std::iter::once( + ::proc_macro::TokenTree::Ident( + ::proc_macro::Ident::new( + stringify!($ident), + ::proc_macro::Span::call_site(), + ), + ), + ), + ); + quote_each_token!($tokens $($rest)*); + }; + ($tokens:ident ( $($inner:tt)* ) $($rest:tt)*) => { + <::proc_macro::TokenStream as ::std::iter::Extend<_>>::extend( + &mut $tokens, + ::std::iter::once( + ::proc_macro::TokenTree::Group( + ::proc_macro::Group::new( + ::proc_macro::Delimiter::Parenthesis, + quote!($($inner)*), + ), + ), + ), + ); + quote_each_token!($tokens $($rest)*); + }; + ($tokens:ident [ $($inner:tt)* ] $($rest:tt)*) => { + <::proc_macro::TokenStream as ::std::iter::Extend<_>>::extend( + &mut $tokens, + ::std::iter::once( + ::proc_macro::TokenTree::Group( + ::proc_macro::Group::new( + ::proc_macro::Delimiter::Bracket, + quote!($($inner)*), + ), + ), + ), + ); + quote_each_token!($tokens $($rest)*); + }; + ($tokens:ident { $($inner:tt)* } $($rest:tt)*) => { + <::proc_macro::TokenStream as ::std::iter::Extend<_>>::extend( + &mut $tokens, + ::std::iter::once( + ::proc_macro::TokenTree::Group( + ::proc_macro::Group::new( + ::proc_macro::Delimiter::Brace, + quote!($($inner)*), + ), + ), + ), + ); + quote_each_token!($tokens $($rest)*); + }; + ($tokens:ident $punct:tt $($rest:tt)*) => { + <::proc_macro::TokenStream as ::std::iter::Extend<_>>::extend( + &mut $tokens, + stringify!($punct).parse::<::proc_macro::TokenStream>(), + ); + quote_each_token!($tokens $($rest)*); + }; + ($tokens:ident) => {}; +} + +pub trait Tokens { + fn extend(tokens: &mut TokenStream, var: &Self); +} + +impl Tokens for Ident { + fn extend(tokens: &mut TokenStream, var: &Self) { + tokens.extend(iter::once(TokenTree::Ident(var.clone()))); + } +} + +impl Tokens for TokenStream { + fn extend(tokens: &mut TokenStream, var: &Self) { + tokens.extend(var.clone()); + } +} + +impl<T: Tokens> Tokens for Option<T> { + fn extend(tokens: &mut TokenStream, var: &Self) { + if let Some(var) = var { + T::extend(tokens, var); + } + } +} + +impl<T: Tokens> Tokens for &T { + fn extend(tokens: &mut TokenStream, var: &Self) { + T::extend(tokens, var); + } +} diff --git a/third_party/rust/proc-macro-hack/tests/compiletest.rs b/third_party/rust/proc-macro-hack/tests/compiletest.rs new file mode 100644 index 0000000000..f9aea23b51 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/compiletest.rs @@ -0,0 +1,6 @@ +#[rustversion::attr(not(nightly), ignore)] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/ui/*.rs"); +} diff --git a/third_party/rust/proc-macro-hack/tests/ui/private.rs b/third_party/rust/proc-macro-hack/tests/ui/private.rs new file mode 100644 index 0000000000..1ab84446c7 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/private.rs @@ -0,0 +1,8 @@ +use proc_macro_hack::proc_macro_hack; + +#[proc_macro_hack] +fn my_macro(input: TokenStream) -> TokenStream { + unimplemented!() +} + +fn main() {} diff --git a/third_party/rust/proc-macro-hack/tests/ui/private.stderr b/third_party/rust/proc-macro-hack/tests/ui/private.stderr new file mode 100644 index 0000000000..d3a3ea7ed4 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/private.stderr @@ -0,0 +1,5 @@ +error: functions tagged with `#[proc_macro_hack]` must be `pub` + --> tests/ui/private.rs:4:1 + | +4 | fn my_macro(input: TokenStream) -> TokenStream { + | ^^ diff --git a/third_party/rust/proc-macro-hack/tests/ui/unexpected-arg.rs b/third_party/rust/proc-macro-hack/tests/ui/unexpected-arg.rs new file mode 100644 index 0000000000..376fc0d986 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/unexpected-arg.rs @@ -0,0 +1,8 @@ +use proc_macro_hack::proc_macro_hack; + +#[proc_macro_hack(fake_call_site)] +pub fn my_macro(input: TokenStream) -> TokenStream { + unimplemented!() +} + +fn main() {} diff --git a/third_party/rust/proc-macro-hack/tests/ui/unexpected-arg.stderr b/third_party/rust/proc-macro-hack/tests/ui/unexpected-arg.stderr new file mode 100644 index 0000000000..f32f05a1cd --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/unexpected-arg.stderr @@ -0,0 +1,5 @@ +error: unexpected argument to proc_macro_hack macro implementation; args are only accepted on the macro declaration (the `pub use`) + --> tests/ui/unexpected-arg.rs:3:19 + | +3 | #[proc_macro_hack(fake_call_site)] + | ^^^^^^^^^^^^^^ diff --git a/third_party/rust/proc-macro-hack/tests/ui/unexpected.rs b/third_party/rust/proc-macro-hack/tests/ui/unexpected.rs new file mode 100644 index 0000000000..122ded5191 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/unexpected.rs @@ -0,0 +1,6 @@ +use proc_macro_hack::proc_macro_hack; + +#[proc_macro_hack] +pub struct What; + +fn main() {} diff --git a/third_party/rust/proc-macro-hack/tests/ui/unexpected.stderr b/third_party/rust/proc-macro-hack/tests/ui/unexpected.stderr new file mode 100644 index 0000000000..60761b5149 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/unexpected.stderr @@ -0,0 +1,5 @@ +error: unexpected input to #[proc_macro_hack] + --> tests/ui/unexpected.rs:4:5 + | +4 | pub struct What; + | ^^^^^^ diff --git a/third_party/rust/proc-macro-hack/tests/ui/unknown-arg.rs b/third_party/rust/proc-macro-hack/tests/ui/unknown-arg.rs new file mode 100644 index 0000000000..aa9b82c8f4 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/unknown-arg.rs @@ -0,0 +1,6 @@ +use proc_macro_hack::proc_macro_hack; + +#[proc_macro_hack(fake_call_site, support_nexted)] +pub use demo::some_macro; + +fn main() {} diff --git a/third_party/rust/proc-macro-hack/tests/ui/unknown-arg.stderr b/third_party/rust/proc-macro-hack/tests/ui/unknown-arg.stderr new file mode 100644 index 0000000000..772e6673d0 --- /dev/null +++ b/third_party/rust/proc-macro-hack/tests/ui/unknown-arg.stderr @@ -0,0 +1,5 @@ +error: expected one of: `support_nested`, `internal_macro_calls`, `fake_call_site`, `only_hack_old_rustc` + --> tests/ui/unknown-arg.rs:3:35 + | +3 | #[proc_macro_hack(fake_call_site, support_nexted)] + | ^^^^^^^^^^^^^^ |