diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/inherent | |
parent | Initial commit. (diff) | |
download | firefox-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 '')
20 files changed, 857 insertions, 0 deletions
diff --git a/third_party/rust/inherent/.cargo-checksum.json b/third_party/rust/inherent/.cargo-checksum.json new file mode 100644 index 0000000000..954034d6b2 --- /dev/null +++ b/third_party/rust/inherent/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"bd0547397529da2c04320940fecc8ffff6aaaf6b4e1e1ee33153d873b895ad6b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"74bd3fad47365c6947c8026d71c4447503eadc4e59cab5b99008758764ca8163","src/default_methods.rs":"71d2d0e6a54f30b5958ecaa48b49fd21560620f98e468a99142bea1d954b36a4","src/expand.rs":"163ad57ac8e5cb2294d96a2ba8db23815c44137e23f8177bfd59f87a4cd3d694","src/lib.rs":"6e844f4e0104c942945e8071b346788f01f5e63e15d378b501b966d10d49f8ed","src/parse.rs":"5478cff1e20ac6dc2c95772eaecfa8b8ec557effe689b536d865287c0b0b89ce","src/visibility.rs":"d5334b8db4953bd7aa9277e75717f2bdaf4ceb01e98db101d040687238f22e20","tests/compiletest.rs":"0a52a44786aea1c299c695bf948b2ed2081e4cc344e5c2cadceab4eb03d0010d","tests/test.rs":"5ba0edc93c0edf63744d45cd293ed8c522ee3a7cb9da3df4d7dacaa6ed004478","tests/ui/default-with-body.rs":"d7a6ad44e8327f298b88e93b43adb019d4278ccd2f56f0ca98c819d08bf8906a","tests/ui/default-with-body.stderr":"e3669c86597c7146dba36f3dfa6a200fd66e315b9e5518171c1ec45c883e1e2d","tests/ui/nonsense-in-default.rs":"694f0e75e213ad78ad30124f00bb45517331f2eceb8f44f4f49d5f5d917ba018","tests/ui/nonsense-in-default.stderr":"96d47e0b3b00197e6f959759a8c57a77d7af68ebfa8d0ed1d4df3f6fe0995717","tests/ui/not-trait-impl.rs":"e99aba255dc75c498d43098c496a2b349631de74ca51b6fdcd90fc744a4fcc94","tests/ui/not-trait-impl.stderr":"12e936203b335bccc3a180c66523c0d434fac6038521d1a6712ee5d37a7eec4d","tests/ui/not-visible.rs":"ee9c08bf412b0ce2b077ab53a2ad4c98ada104c48721b484bfe79ebb2bc36230","tests/ui/not-visible.stderr":"c8bf2a1efbe851a7b1eb1490ea621826f37670bf80d17090b0437140cc396995"},"package":"f3a1325a022293a53274277a7c5c3c5bc73405cb443bb96cc2ce20ff4121e995"}
\ No newline at end of file diff --git a/third_party/rust/inherent/Cargo.toml b/third_party/rust/inherent/Cargo.toml new file mode 100644 index 0000000000..d6a93be653 --- /dev/null +++ b/third_party/rust/inherent/Cargo.toml @@ -0,0 +1,42 @@ +# 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 = "inherent" +version = "0.1.5" +authors = ["David Tolnay <dtolnay@gmail.com>"] +description = "Make trait methods callable without the trait in scope" +documentation = "https://docs.rs/inherent" +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/inherent" +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +proc-macro = true +[dependencies.proc-macro2] +version = "1.0" + +[dependencies.quote] +version = "1.0" + +[dependencies.syn] +version = "1.0" +features = ["full"] +[dev-dependencies.rustversion] +version = "1.0" + +[dev-dependencies.trybuild] +version = "1.0.19" +features = ["diff"] diff --git a/third_party/rust/inherent/LICENSE-APACHE b/third_party/rust/inherent/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/third_party/rust/inherent/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/inherent/LICENSE-MIT b/third_party/rust/inherent/LICENSE-MIT new file mode 100644 index 0000000000..31aa79387f --- /dev/null +++ b/third_party/rust/inherent/LICENSE-MIT @@ -0,0 +1,23 @@ +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/inherent/README.md b/third_party/rust/inherent/README.md new file mode 100644 index 0000000000..102abab63e --- /dev/null +++ b/third_party/rust/inherent/README.md @@ -0,0 +1,104 @@ +\#\[inherent\] +============== + +[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/inherent-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/inherent) +[<img alt="crates.io" src="https://img.shields.io/crates/v/inherent.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/inherent) +[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-inherent-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/inherent) +[<img alt="build status" src="https://img.shields.io/github/workflow/status/dtolnay/inherent/CI/master?style=for-the-badge" height="20">](https://github.com/dtolnay/inherent/actions?query=branch%3Amaster) + +This crate provides an attribute macro to make trait methods callable without +the trait in scope. + +```toml +[dependencies] +inherent = "0.1" +``` + +## Example + +```rust +mod types { + use inherent::inherent; + + trait Trait { + fn f(self); + } + + pub struct Struct; + + #[inherent(pub)] + impl Trait for Struct { + fn f(self) {} + } +} + +fn main() { + // types::Trait is not in scope, but method can be called. + types::Struct.f(); +} +``` + +Without the `inherent` macro on the trait impl, this would have failed with the +following error: + +```console +error[E0599]: no method named `f` found for type `types::Struct` in the current scope + --> src/main.rs:18:19 + | +8 | pub struct Struct; + | ------------------ method `f` not found for this +... +18 | types::Struct.f(); + | ^ + | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `f`, perhaps you need to implement it: + candidate #1: `types::Trait` +``` + +The `inherent` macro expands to inherent methods on the `Self` type of the trait +impl that forward to the trait methods. In the case above, the generated code +would be: + +```rust +impl Struct { + pub fn f(self) { + <Self as Trait>::f(self) + } +} +``` + +## Visibility + +Ordinary trait methods have the same visibility as the trait or the `Self` type, +whichever's is smaller. Neither of these visibilities is knowable to the +`inherent` macro, so we simply emit all inherent methods as private by default. +A different visibility may be specified explicitly in the `inherent` macro +invocation. + +```rust +#[inherent] // private inherent methods are the default + +#[inherent(pub)] // all methods pub + +#[inherent(crate)] // all methods pub(crate) + +#[inherent(in path::to)] // all methods pub(in path::to) +``` + +<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 crate 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/inherent/src/default_methods.rs b/third_party/rust/inherent/src/default_methods.rs new file mode 100644 index 0000000000..9415a48a71 --- /dev/null +++ b/third_party/rust/inherent/src/default_methods.rs @@ -0,0 +1,23 @@ +use syn::parse::{Error, ParseStream, Result}; +use syn::TraitItemMethod; + +pub fn parse(input: ParseStream) -> Result<Vec<TraitItemMethod>> { + let mut items = Vec::new(); + let mut error = None; + while !input.is_empty() { + let item = input.parse::<TraitItemMethod>()?; + if let Some(body) = item.default { + let new_err = Error::new_spanned(body, "Default method can't have a body"); + match &mut error { + None => error = Some(new_err), + Some(e) => e.combine(new_err), + } + } else { + items.push(item); + } + } + match error { + None => Ok(items), + Some(err) => Err(err), + } +} diff --git a/third_party/rust/inherent/src/expand.rs b/third_party/rust/inherent/src/expand.rs new file mode 100644 index 0000000000..d959fa4a60 --- /dev/null +++ b/third_party/rust/inherent/src/expand.rs @@ -0,0 +1,101 @@ +use crate::default_methods; +use crate::parse::TraitImpl; +use crate::visibility::Visibility; +use proc_macro2::{Span, TokenStream}; +use quote::quote; +use syn::{Attribute, FnArg, Ident, ImplItem, Signature}; + +pub fn inherent(vis: Visibility, mut input: TraitImpl) -> TokenStream { + let generics = &input.generics; + let where_clause = &input.generics.where_clause; + let trait_ = &input.trait_; + let ty = &input.self_ty; + + let fwd_method = |attrs: &[Attribute], sig: &Signature| { + let constness = &sig.constness; + let asyncness = &sig.asyncness; + let unsafety = &sig.unsafety; + let abi = &sig.abi; + let ident = &sig.ident; + let generics = &sig.generics; + let output = &sig.output; + let where_clause = &sig.generics.where_clause; + + let (arg_pat, arg_val): (Vec<_>, Vec<_>) = sig + .inputs + .iter() + .enumerate() + .map(|(i, input)| match input { + FnArg::Receiver(receiver) => { + if receiver.reference.is_some() { + (quote!(#receiver), quote!(self)) + } else { + (quote!(self), quote!(self)) + } + } + FnArg::Typed(arg) => { + let var = Ident::new(&format!("__arg{}", i), Span::call_site()); + let ty = &arg.ty; + (quote!(#var: #ty), quote!(#var)) + } + }) + .unzip(); + + let types = generics.type_params().map(|param| ¶m.ident); + + let has_doc = attrs.iter().any(|attr| attr.path.is_ident("doc")); + let default_doc = if has_doc { + None + } else { + let msg = format!("See [`{}::{}`]", quote!(#trait_), ident); + Some(quote!(#[doc = #msg])) + }; + + quote! { + #(#attrs)* + #default_doc + #vis #constness #asyncness #unsafety #abi fn #ident #generics ( + #(#arg_pat,)* + ) #output #where_clause { + <Self as #trait_>::#ident::<#(#types,)*>(#(#arg_val,)*) + } + } + }; + + let mut errors = Vec::new(); + let fwd_methods: Vec<_> = input + .items + .iter() + .flat_map(|item| match item { + ImplItem::Method(method) => vec![fwd_method(&method.attrs, &method.sig)], + ImplItem::Macro(item) if item.mac.path.is_ident("default") => { + match item.mac.parse_body_with(default_methods::parse) { + Ok(body) => body + .into_iter() + .map(|item| fwd_method(&item.attrs, &item.sig)) + .collect(), + Err(e) => { + errors.push(e.to_compile_error()); + Vec::new() + } + } + } + _ => Vec::new(), + }) + .collect(); + + input.items.retain(|item| match item { + ImplItem::Macro(item) if item.mac.path.is_ident("default") => false, + _ => true, + }); + + quote! { + #(#errors)* + + impl #generics #ty #where_clause { + #(#fwd_methods)* + } + + #input + } +} diff --git a/third_party/rust/inherent/src/lib.rs b/third_party/rust/inherent/src/lib.rs new file mode 100644 index 0000000000..7ac6390831 --- /dev/null +++ b/third_party/rust/inherent/src/lib.rs @@ -0,0 +1,123 @@ +//! [![github]](https://github.com/dtolnay/inherent) [![crates-io]](https://crates.io/crates/inherent) [![docs-rs]](https://docs.rs/inherent) +//! +//! [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&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K +//! +//! <br> +//! +//! ##### An attribute macro to make trait methods callable without the trait in scope. +//! +//! # Example +//! +//! ```rust +//! mod types { +//! use inherent::inherent; +//! +//! trait Trait { +//! fn f(self); +//! } +//! +//! pub struct Struct; +//! +//! #[inherent(pub)] +//! impl Trait for Struct { +//! fn f(self) {} +//! } +//! } +//! +//! fn main() { +//! // types::Trait is not in scope, but method can be called. +//! types::Struct.f(); +//! } +//! ``` +//! +//! Without the `inherent` macro on the trait impl, this would have failed with the +//! following error: +//! +//! ```console +//! error[E0599]: no method named `f` found for type `types::Struct` in the current scope +//! --> src/main.rs:18:19 +//! | +//! 8 | pub struct Struct; +//! | ------------------ method `f` not found for this +//! ... +//! 18 | types::Struct.f(); +//! | ^ +//! | +//! = help: items from traits can only be used if the trait is implemented and in scope +//! = note: the following trait defines an item `f`, perhaps you need to implement it: +//! candidate #1: `types::Trait` +//! ``` +//! +//! The `inherent` macro expands to inherent methods on the `Self` type of the trait +//! impl that forward to the trait methods. In the case above, the generated code +//! would be: +//! +//! ```rust +//! # trait Trait { +//! # fn f(self); +//! # } +//! # +//! # pub struct Struct; +//! # +//! # impl Trait for Struct { +//! # fn f(self) {} +//! # } +//! # +//! impl Struct { +//! pub fn f(self) { +//! <Self as Trait>::f(self) +//! } +//! } +//! ``` +//! +//! # Visibility +//! +//! Ordinary trait methods have the same visibility as the trait or the `Self` type, +//! whichever's is smaller. Neither of these visibilities is knowable to the +//! `inherent` macro, so we simply emit all inherent methods as private by default. +//! A different visibility may be specified explicitly in the `inherent` macro +//! invocation. +//! +//! ```rust +//! # use inherent::inherent; +//! # +//! # trait Trait {} +//! # +//! # struct A; +//! #[inherent] // private inherent methods are the default +//! # impl Trait for A {} +//! +//! # struct B; +//! #[inherent(pub)] // all methods pub +//! # impl Trait for B {} +//! +//! # struct C; +//! #[inherent(crate)] // all methods pub(crate) +//! # impl Trait for C {} +//! +//! # struct D; +//! #[inherent(in path::to)] // all methods pub(in path::to) +//! # impl Trait for D {} +//! ``` + +extern crate proc_macro; + +mod default_methods; +mod expand; +mod parse; +mod visibility; + +use proc_macro::TokenStream; +use syn::parse_macro_input; + +use crate::parse::TraitImpl; +use crate::visibility::Visibility; + +#[proc_macro_attribute] +pub fn inherent(args: TokenStream, input: TokenStream) -> TokenStream { + let vis = parse_macro_input!(args as Visibility); + let input = parse_macro_input!(input as TraitImpl); + expand::inherent(vis, input).into() +} diff --git a/third_party/rust/inherent/src/parse.rs b/third_party/rust/inherent/src/parse.rs new file mode 100644 index 0000000000..92a91f624b --- /dev/null +++ b/third_party/rust/inherent/src/parse.rs @@ -0,0 +1,69 @@ +use proc_macro2::{Span, TokenStream}; +use quote::ToTokens; +use syn::parse::{Error, Parse, ParseStream, Result}; +use syn::token::Brace; +use syn::{Attribute, Generics, ImplItem, ItemImpl, Path, Token, Type}; + +#[derive(Clone)] +pub struct TraitImpl { + pub attrs: Vec<Attribute>, + pub defaultness: Option<Token![default]>, + pub unsafety: Option<Token![unsafe]>, + pub impl_token: Token![impl], + pub generics: Generics, + pub trait_: Path, + pub for_token: Token![for], + pub self_ty: Type, + pub brace_token: Brace, + pub items: Vec<ImplItem>, +} + +impl Parse for TraitImpl { + fn parse(input: ParseStream) -> Result<Self> { + let imp: ItemImpl = input.parse()?; + + let (trait_, for_token) = match imp.trait_ { + Some((_bang_token, trait_, for_token)) => (trait_, for_token), + None => { + return Err(Error::new( + Span::call_site(), + "must be placed on a trait impl", + )) + } + }; + + Ok(TraitImpl { + attrs: imp.attrs, + defaultness: imp.defaultness, + unsafety: imp.unsafety, + impl_token: imp.impl_token, + generics: imp.generics, + trait_, + for_token, + self_ty: *imp.self_ty, + brace_token: imp.brace_token, + items: imp.items, + }) + } +} + +impl ToTokens for TraitImpl { + fn to_tokens(&self, tokens: &mut TokenStream) { + let imp = self.clone(); + + ItemImpl::to_tokens( + &ItemImpl { + attrs: imp.attrs, + defaultness: imp.defaultness, + unsafety: imp.unsafety, + impl_token: imp.impl_token, + generics: imp.generics, + trait_: Some((None, imp.trait_, imp.for_token)), + self_ty: Box::new(imp.self_ty), + brace_token: imp.brace_token, + items: imp.items, + }, + tokens, + ); + } +} diff --git a/third_party/rust/inherent/src/visibility.rs b/third_party/rust/inherent/src/visibility.rs new file mode 100644 index 0000000000..72213fda62 --- /dev/null +++ b/third_party/rust/inherent/src/visibility.rs @@ -0,0 +1,50 @@ +use proc_macro2::TokenStream; +use quote::ToTokens; +use syn::ext::IdentExt; +use syn::parse::{Parse, ParseStream, Result}; +use syn::{Ident, Path, Token, VisPublic, VisRestricted}; + +pub struct Visibility { + variant: syn::Visibility, +} + +impl Parse for Visibility { + fn parse(input: ParseStream) -> Result<Self> { + let lookahead = input.lookahead1(); + + let variant = if input.is_empty() { + syn::Visibility::Inherited + } else if lookahead.peek(Token![pub]) { + syn::Visibility::Public(VisPublic { + pub_token: input.parse()?, + }) + } else if lookahead.peek(Token![crate]) + || lookahead.peek(Token![self]) + || lookahead.peek(Token![super]) + { + syn::Visibility::Restricted(VisRestricted { + pub_token: Default::default(), + paren_token: Default::default(), + in_token: None, + path: Box::new(Path::from(input.call(Ident::parse_any)?)), + }) + } else if lookahead.peek(Token![in]) { + syn::Visibility::Restricted(VisRestricted { + pub_token: Default::default(), + paren_token: Default::default(), + in_token: Some(input.parse()?), + path: Box::new(input.call(Path::parse_mod_style)?), + }) + } else { + return Err(lookahead.error()); + }; + + Ok(Visibility { variant }) + } +} + +impl ToTokens for Visibility { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.variant.to_tokens(tokens); + } +} diff --git a/third_party/rust/inherent/tests/compiletest.rs b/third_party/rust/inherent/tests/compiletest.rs new file mode 100644 index 0000000000..f9aea23b51 --- /dev/null +++ b/third_party/rust/inherent/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/inherent/tests/test.rs b/third_party/rust/inherent/tests/test.rs new file mode 100644 index 0000000000..3e271d85c9 --- /dev/null +++ b/third_party/rust/inherent/tests/test.rs @@ -0,0 +1,27 @@ +mod types { + use inherent::inherent; + + trait Trait { + fn f<T: ?Sized>(self); + // A default method + fn g(&self) {} + } + + pub struct Struct; + + #[inherent(pub)] + impl Trait for Struct { + fn f<T: ?Sized>(self) {} + default! { + fn g(&self); + } + } +} + +#[test] +fn test() { + // types::Trait is not in scope. + let s = types::Struct; + s.g(); + s.f::<str>(); +} diff --git a/third_party/rust/inherent/tests/ui/default-with-body.rs b/third_party/rust/inherent/tests/ui/default-with-body.rs new file mode 100644 index 0000000000..df2f67ee66 --- /dev/null +++ b/third_party/rust/inherent/tests/ui/default-with-body.rs @@ -0,0 +1,18 @@ +use inherent::inherent; + +trait A { + fn a(&self) {} +} + +struct X; + +#[inherent] +impl A for X { + default! { + fn a(&self) { + println!("Default with a body >:-P"); + } + } +} + +fn main() {} diff --git a/third_party/rust/inherent/tests/ui/default-with-body.stderr b/third_party/rust/inherent/tests/ui/default-with-body.stderr new file mode 100644 index 0000000000..82dee8dd14 --- /dev/null +++ b/third_party/rust/inherent/tests/ui/default-with-body.stderr @@ -0,0 +1,8 @@ +error: Default method can't have a body + --> $DIR/default-with-body.rs:12:21 + | +12 | fn a(&self) { + | _____________________^ +13 | | println!("Default with a body >:-P"); +14 | | } + | |_________^ diff --git a/third_party/rust/inherent/tests/ui/nonsense-in-default.rs b/third_party/rust/inherent/tests/ui/nonsense-in-default.rs new file mode 100644 index 0000000000..907f6bdd81 --- /dev/null +++ b/third_party/rust/inherent/tests/ui/nonsense-in-default.rs @@ -0,0 +1,16 @@ +use inherent::inherent; + +trait A { + fn a(&self) {} +} + +struct X; + +#[inherent] +impl A for X { + default! { + const NONSENSE: usize = 1; + } +} + +fn main() {} diff --git a/third_party/rust/inherent/tests/ui/nonsense-in-default.stderr b/third_party/rust/inherent/tests/ui/nonsense-in-default.stderr new file mode 100644 index 0000000000..af6ce91e3a --- /dev/null +++ b/third_party/rust/inherent/tests/ui/nonsense-in-default.stderr @@ -0,0 +1,5 @@ +error: expected `fn` + --> $DIR/nonsense-in-default.rs:12:15 + | +12 | const NONSENSE: usize = 1; + | ^^^^^^^^ diff --git a/third_party/rust/inherent/tests/ui/not-trait-impl.rs b/third_party/rust/inherent/tests/ui/not-trait-impl.rs new file mode 100644 index 0000000000..a9a6a11628 --- /dev/null +++ b/third_party/rust/inherent/tests/ui/not-trait-impl.rs @@ -0,0 +1,10 @@ +use inherent::inherent; + +struct Struct; + +#[inherent] +impl Struct { + fn f() {} +} + +fn main() {} diff --git a/third_party/rust/inherent/tests/ui/not-trait-impl.stderr b/third_party/rust/inherent/tests/ui/not-trait-impl.stderr new file mode 100644 index 0000000000..afd9689a44 --- /dev/null +++ b/third_party/rust/inherent/tests/ui/not-trait-impl.stderr @@ -0,0 +1,7 @@ +error: must be placed on a trait impl + --> $DIR/not-trait-impl.rs:5:1 + | +5 | #[inherent] + | ^^^^^^^^^^^ + | + = note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/third_party/rust/inherent/tests/ui/not-visible.rs b/third_party/rust/inherent/tests/ui/not-visible.rs new file mode 100644 index 0000000000..faccf90ff4 --- /dev/null +++ b/third_party/rust/inherent/tests/ui/not-visible.rs @@ -0,0 +1,18 @@ +mod types { + use inherent::inherent; + + trait Trait { + fn f(); + } + + pub struct Struct; + + #[inherent] + impl Trait for Struct { + fn f() {} + } +} + +fn main() { + types::Struct::f(); +} diff --git a/third_party/rust/inherent/tests/ui/not-visible.stderr b/third_party/rust/inherent/tests/ui/not-visible.stderr new file mode 100644 index 0000000000..1adde54555 --- /dev/null +++ b/third_party/rust/inherent/tests/ui/not-visible.stderr @@ -0,0 +1,5 @@ +error[E0624]: associated function `f` is private + --> $DIR/not-visible.rs:17:20 + | +17 | types::Struct::f(); + | ^ private associated function |