summaryrefslogtreecommitdiffstats
path: root/third_party/rust/proc-macro-hack
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
commit2aa4a82499d4becd2284cdb482213d541b8804dd (patch)
treeb80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/proc-macro-hack
parentInitial commit. (diff)
downloadfirefox-2aa4a82499d4becd2284cdb482213d541b8804dd.tar.xz
firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.zip
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/proc-macro-hack')
-rw-r--r--third_party/rust/proc-macro-hack/.cargo-checksum.json1
-rw-r--r--third_party/rust/proc-macro-hack/Cargo.toml40
-rw-r--r--third_party/rust/proc-macro-hack/LICENSE-APACHE201
-rw-r--r--third_party/rust/proc-macro-hack/LICENSE-MIT25
-rw-r--r--third_party/rust/proc-macro-hack/README.md142
-rw-r--r--third_party/rust/proc-macro-hack/src/lib.rs657
6 files changed, 1066 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..11b07426ab
--- /dev/null
+++ b/third_party/rust/proc-macro-hack/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{"Cargo.toml":"f1b283315c58f380d50c15f4017fb388ef166c8ee9c6fbc2503a1d666290d356","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"d59d2723bbc1627b629429a9c779d5dcfde579c9723e6ded1052931c4e8efa0a","README.md":"a4b9c5234ba1e780e1b30957ae0b77c5e018a4fc84e39b2a2dc643e02610ae1c","src/lib.rs":"58aba2a6cd51185be905214eefd4485fe2eef8e52f55c469bda0ccfe63b07c26"},"package":"ecd45702f76d6d3c75a80564378ae228a85f0b59d2f3ed43c91b4a69eb2ebfc5"} \ 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..ce783f4548
--- /dev/null
+++ b/third_party/rust/proc-macro-hack/Cargo.toml
@@ -0,0 +1,40 @@
+# 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 believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+edition = "2018"
+name = "proc-macro-hack"
+version = "0.5.11"
+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"
+
+[lib]
+proc-macro = true
+[dependencies.proc-macro2]
+version = "1.0"
+
+[dependencies.quote]
+version = "1.0"
+
+[dependencies.syn]
+version = "1.0.5"
+[dev-dependencies.demo-hack]
+version = "0.0.5"
+
+[dev-dependencies.demo-hack-impl]
+version = "0.0.5"
+[badges.travis-ci]
+repository = "dtolnay/proc-macro-hack"
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..f07734e8d7
--- /dev/null
+++ b/third_party/rust/proc-macro-hack/README.md
@@ -0,0 +1,142 @@
+Procedural macros in expression position
+========================================
+
+[![Build Status](https://api.travis-ci.org/dtolnay/proc-macro-hack.svg?branch=master)](https://travis-ci.org/dtolnay/proc-macro-hack)
+[![Latest Version](https://img.shields.io/crates/v/proc-macro-hack.svg)](https://crates.io/crates/proc-macro-hack)
+
+As of 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 stable or nightly 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
+extern crate proc_macro;
+
+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 type
+ position ([#10]) or 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.*
+
+[#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/src/lib.rs b/third_party/rust/proc-macro-hack/src/lib.rs
new file mode 100644
index 0000000000..0ef954629f
--- /dev/null
+++ b/third_party/rust/proc-macro-hack/src/lib.rs
@@ -0,0 +1,657 @@
+//! As of 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 type
+//! position ([#10]) or 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.*
+//!
+//! [#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"]
+#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))]
+#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
+
+extern crate proc_macro;
+
+use proc_macro2::{Span, TokenStream, TokenTree};
+use quote::{format_ident, quote, ToTokens};
+use std::fmt::Write;
+use syn::ext::IdentExt;
+use syn::parse::{Parse, ParseStream, Result};
+use syn::{braced, bracketed, parenthesized, parse_macro_input, token, Ident, LitInt, Token};
+
+type Visibility = Option<Token![pub]>;
+
+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,
+}
+
+impl Parse for Input {
+ fn parse(input: ParseStream) -> Result<Self> {
+ let ahead = input.fork();
+ parse_attributes(&ahead)?;
+ ahead.parse::<Visibility>()?;
+
+ if ahead.peek(Token![use]) {
+ input.parse().map(Input::Export)
+ } else if ahead.peek(Token![fn]) {
+ input.parse().map(Input::Define)
+ } else {
+ Err(input.error("unexpected input to #[proc_macro_hack]"))
+ }
+ }
+}
+
+impl Parse for Export {
+ fn parse(input: ParseStream) -> Result<Self> {
+ let attrs = input.call(parse_attributes)?;
+ let vis: Visibility = input.parse()?;
+ input.parse::<Token![use]>()?;
+ input.parse::<Option<Token![::]>>()?;
+ let from: Ident = input.parse()?;
+ input.parse::<Token![::]>()?;
+
+ let mut macros = Vec::new();
+ if input.peek(token::Brace) {
+ let content;
+ braced!(content in input);
+ loop {
+ macros.push(content.parse()?);
+ if content.is_empty() {
+ break;
+ }
+ content.parse::<Token![,]>()?;
+ if content.is_empty() {
+ break;
+ }
+ }
+ } else {
+ macros.push(input.parse()?);
+ }
+
+ input.parse::<Token![;]>()?;
+ Ok(Export {
+ attrs,
+ vis,
+ from,
+ macros,
+ })
+ }
+}
+
+impl Parse for Define {
+ fn parse(input: ParseStream) -> Result<Self> {
+ let attrs = input.call(parse_attributes)?;
+ let vis: Visibility = input.parse()?;
+ if vis.is_none() {
+ return Err(input.error("functions tagged with `#[proc_macro_hack]` must be `pub`"));
+ }
+
+ input.parse::<Token![fn]>()?;
+ let name: Ident = input.parse()?;
+ let body: TokenStream = input.parse()?;
+ Ok(Define { attrs, name, body })
+ }
+}
+
+impl Parse for Macro {
+ fn parse(input: ParseStream) -> Result<Self> {
+ let name: Ident = input.parse()?;
+ let renamed: Option<Token![as]> = input.parse()?;
+ let export_as = if renamed.is_some() {
+ input.parse()?
+ } else {
+ name.clone()
+ };
+ Ok(Macro { name, export_as })
+ }
+}
+
+fn parse_attributes(input: ParseStream) -> Result<TokenStream> {
+ let mut attrs = TokenStream::new();
+ while input.peek(Token![#]) {
+ let pound: Token![#] = input.parse()?;
+ pound.to_tokens(&mut attrs);
+ let content;
+ let bracket_token = bracketed!(content in input);
+ let content: TokenStream = content.parse()?;
+ bracket_token.surround(&mut attrs, |tokens| content.to_tokens(tokens));
+ }
+ Ok(attrs)
+}
+
+#[proc_macro_attribute]
+pub fn proc_macro_hack(
+ args: proc_macro::TokenStream,
+ input: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+ proc_macro::TokenStream::from(match parse_macro_input!(input) {
+ Input::Export(export) => {
+ let args = parse_macro_input!(args as ExportArgs);
+ expand_export(export, args)
+ }
+ Input::Define(define) => {
+ parse_macro_input!(args as DefineArgs);
+ expand_define(define)
+ }
+ })
+}
+
+mod kw {
+ syn::custom_keyword!(derive);
+ syn::custom_keyword!(fake_call_site);
+ syn::custom_keyword!(internal_macro_calls);
+ syn::custom_keyword!(support_nested);
+}
+
+struct ExportArgs {
+ support_nested: bool,
+ internal_macro_calls: u16,
+ fake_call_site: bool,
+}
+
+impl Parse for ExportArgs {
+ fn parse(input: ParseStream) -> Result<Self> {
+ let mut args = ExportArgs {
+ support_nested: false,
+ internal_macro_calls: 0,
+ fake_call_site: false,
+ };
+
+ while !input.is_empty() {
+ let ahead = input.lookahead1();
+ if ahead.peek(kw::support_nested) {
+ input.parse::<kw::support_nested>()?;
+ args.support_nested = true;
+ } else if ahead.peek(kw::internal_macro_calls) {
+ input.parse::<kw::internal_macro_calls>()?;
+ input.parse::<Token![=]>()?;
+ let calls = input.parse::<LitInt>()?.base10_parse()?;
+ args.internal_macro_calls = calls;
+ } else if ahead.peek(kw::fake_call_site) {
+ input.parse::<kw::fake_call_site>()?;
+ args.fake_call_site = true;
+ } else {
+ return Err(ahead.error());
+ }
+ if input.is_empty() {
+ break;
+ }
+ input.parse::<Token![,]>()?;
+ }
+
+ Ok(args)
+ }
+}
+
+struct DefineArgs;
+
+impl Parse for DefineArgs {
+ fn parse(_input: ParseStream) -> Result<Self> {
+ Ok(DefineArgs)
+ }
+}
+
+struct EnumHack {
+ token_stream: TokenStream,
+}
+
+impl Parse for EnumHack {
+ fn parse(input: ParseStream) -> Result<Self> {
+ input.parse::<Token![enum]>()?;
+ input.parse::<Ident>()?;
+
+ let braces;
+ braced!(braces in input);
+ braces.parse::<Ident>()?;
+ braces.parse::<Token![=]>()?;
+
+ let parens;
+ parenthesized!(parens in braces);
+ parens.parse::<Ident>()?;
+ parens.parse::<Token![!]>()?;
+
+ let inner;
+ braced!(inner in parens);
+ let token_stream: TokenStream = inner.parse()?;
+
+ parens.parse::<Token![,]>()?;
+ parens.parse::<TokenTree>()?;
+ braces.parse::<Token![.]>()?;
+ braces.parse::<TokenTree>()?;
+ braces.parse::<Token![,]>()?;
+
+ Ok(EnumHack { token_stream })
+ }
+}
+
+#[doc(hidden)]
+#[proc_macro_derive(ProcMacroHack)]
+pub fn enum_hack(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+ let inner = parse_macro_input!(input as EnumHack);
+ proc_macro::TokenStream::from(inner.token_stream)
+}
+
+struct FakeCallSite {
+ derive: Ident,
+ rest: TokenStream,
+}
+
+impl Parse for FakeCallSite {
+ fn parse(input: ParseStream) -> Result<Self> {
+ input.parse::<Token![#]>()?;
+ let attr;
+ bracketed!(attr in input);
+ attr.parse::<kw::derive>()?;
+ let path;
+ parenthesized!(path in attr);
+ Ok(FakeCallSite {
+ derive: path.parse()?,
+ rest: input.parse()?,
+ })
+ }
+}
+
+#[doc(hidden)]
+#[proc_macro_attribute]
+pub fn fake_call_site(
+ args: proc_macro::TokenStream,
+ input: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+ let args = TokenStream::from(args);
+ let span = match args.into_iter().next() {
+ Some(token) => token.span(),
+ None => return input,
+ };
+
+ let input = parse_macro_input!(input as FakeCallSite);
+ let mut derive = input.derive;
+ derive.set_span(span);
+ let rest = input.rest;
+
+ let expanded = quote! {
+ #[derive(#derive)]
+ #rest
+ };
+
+ proc_macro::TokenStream::from(expanded)
+}
+
+fn expand_export(export: Export, args: ExportArgs) -> TokenStream {
+ 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.map(|_| quote!($crate::));
+ let enum_variant = if args.support_nested {
+ if args.internal_macro_calls == 0 {
+ quote!(Nested)
+ } else {
+ format_ident!("Nested{}", args.internal_macro_calls).to_token_stream()
+ }
+ } else {
+ quote!(Value)
+ };
+
+ let from = export.from;
+ let rules = export
+ .macros
+ .into_iter()
+ .map(|Macro { name, export_as }| {
+ let actual_name = actual_proc_macro_name(&name);
+ let dispatch = dispatch_macro_name(&name);
+ let call_site = call_site_macro_name(&name);
+
+ let export_dispatch = if args.support_nested {
+ quote! {
+ #[doc(hidden)]
+ #vis use proc_macro_nested::dispatch as #dispatch;
+ }
+ } else {
+ quote!()
+ };
+
+ let proc_macro_call = if args.support_nested {
+ let extra_bangs = (0..args.internal_macro_calls).map(|_| quote!(!));
+ quote! {
+ #crate_prefix #dispatch! { ($($proc_macro)*) #(#extra_bangs)* }
+ }
+ } else {
+ quote! {
+ proc_macro_call!()
+ }
+ };
+
+ let export_call_site = if args.fake_call_site {
+ quote! {
+ #[doc(hidden)]
+ #vis use proc_macro_hack::fake_call_site as #call_site;
+ }
+ } else {
+ quote!()
+ };
+
+ let do_derive = if !args.fake_call_site {
+ quote! {
+ #[derive(#crate_prefix #actual_name)]
+ }
+ } else if crate_prefix.is_some() {
+ quote! {
+ use #crate_prefix #actual_name;
+ #[#crate_prefix #call_site ($($proc_macro)*)]
+ #[derive(#actual_name)]
+ }
+ } else {
+ quote! {
+ #[#call_site ($($proc_macro)*)]
+ #[derive(#actual_name)]
+ }
+ };
+
+ quote! {
+ #[doc(hidden)]
+ #vis use #from::#actual_name;
+
+ #export_dispatch
+ #export_call_site
+
+ #attrs
+ #macro_export
+ macro_rules! #export_as {
+ ($($proc_macro:tt)*) => {{
+ #do_derive
+ enum ProcMacroHack {
+ #enum_variant = (stringify! { $($proc_macro)* }, 0).1,
+ }
+ #proc_macro_call
+ }};
+ }
+ }
+ })
+ .collect();
+
+ wrap_in_enum_hack(dummy, rules)
+}
+
+fn expand_define(define: Define) -> TokenStream {
+ let attrs = define.attrs;
+ let name = define.name;
+ let dummy = actual_proc_macro_name(&name);
+ let body = define.body;
+
+ quote! {
+ mod #dummy {
+ extern crate proc_macro;
+ pub use self::proc_macro::*;
+ }
+
+ #attrs
+ #[proc_macro_derive(#dummy)]
+ pub fn #dummy(input: #dummy::TokenStream) -> #dummy::TokenStream {
+ use std::iter::FromIterator;
+
+ let mut iter = input.into_iter();
+ iter.next().unwrap(); // `enum`
+ iter.next().unwrap(); // `ProcMacroHack`
+
+ let mut braces = match iter.next().unwrap() {
+ #dummy::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() {
+ #dummy::TokenTree::Group(group) => group.stream().into_iter(),
+ _ => unimplemented!(),
+ };
+ parens.next().unwrap(); // `stringify`
+ parens.next().unwrap(); // `!`
+
+ let inner = match parens.next().unwrap() {
+ #dummy::TokenTree::Group(group) => group.stream(),
+ _ => unimplemented!(),
+ };
+
+ let output: #dummy::TokenStream = #name(inner.clone());
+
+ fn count_bangs(input: #dummy::TokenStream) -> usize {
+ let mut count = 0;
+ for token in input {
+ match token {
+ #dummy::TokenTree::Punct(punct) => {
+ if punct.as_char() == '!' {
+ count += 1;
+ }
+ }
+ #dummy::TokenTree::Group(group) => {
+ count += count_bangs(group.stream());
+ }
+ _ => {}
+ }
+ }
+ count
+ }
+
+ // macro_rules! proc_macro_call {
+ // () => { #output }
+ // }
+ #dummy::TokenStream::from_iter(vec![
+ #dummy::TokenTree::Ident(
+ #dummy::Ident::new("macro_rules", #dummy::Span::call_site()),
+ ),
+ #dummy::TokenTree::Punct(
+ #dummy::Punct::new('!', #dummy::Spacing::Alone),
+ ),
+ #dummy::TokenTree::Ident(
+ #dummy::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")
+ },
+ #dummy::Span::call_site(),
+ ),
+ ),
+ #dummy::TokenTree::Group(
+ #dummy::Group::new(#dummy::Delimiter::Brace, #dummy::TokenStream::from_iter(vec![
+ #dummy::TokenTree::Group(
+ #dummy::Group::new(#dummy::Delimiter::Parenthesis, #dummy::TokenStream::new()),
+ ),
+ #dummy::TokenTree::Punct(
+ #dummy::Punct::new('=', #dummy::Spacing::Joint),
+ ),
+ #dummy::TokenTree::Punct(
+ #dummy::Punct::new('>', #dummy::Spacing::Alone),
+ ),
+ #dummy::TokenTree::Group(
+ #dummy::Group::new(#dummy::Delimiter::Brace, output),
+ ),
+ ])),
+ ),
+ ])
+ }
+
+ fn #name #body
+ }
+}
+
+fn actual_proc_macro_name(conceptual: &Ident) -> Ident {
+ format_ident!("proc_macro_hack_{}", conceptual)
+}
+
+fn dispatch_macro_name(conceptual: &Ident) -> Ident {
+ format_ident!("proc_macro_call_{}", conceptual)
+}
+
+fn call_site_macro_name(conceptual: &Ident) -> Ident {
+ format_ident!("proc_macro_fake_call_site_{}", conceptual)
+}
+
+fn dummy_name_for_export(export: &Export) -> String {
+ let mut dummy = String::new();
+ let from = export.from.unraw().to_string();
+ write!(dummy, "_{}{}", from.len(), from).unwrap();
+ for m in &export.macros {
+ let name = m.name.unraw().to_string();
+ write!(dummy, "_{}{}", name.len(), name).unwrap();
+ }
+ dummy
+}
+
+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,
+ }
+ }
+}