Full Code of dtolnay/inherent for AI

master 159002670802 cached
21 files
29.1 KB
7.7k tokens
38 symbols
1 requests
Download .txt
Repository: dtolnay/inherent
Branch: master
Commit: 159002670802
Files: 21
Total size: 29.1 KB

Directory structure:
gitextract_a9m06ltv/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── src/
│   ├── expand.rs
│   ├── lib.rs
│   ├── parse.rs
│   └── verbatim.rs
└── tests/
    ├── compiletest.rs
    ├── test.rs
    └── ui/
        ├── associated-type.rs
        ├── associated-type.stderr
        ├── blanket-impl.rs
        ├── blanket-impl.stderr
        ├── not-trait-impl.rs
        ├── not-trait-impl.stderr
        ├── not-visible.rs
        └── not-visible.stderr

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
github: dtolnay


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on:
  push:
  pull_request:
  workflow_dispatch:
  schedule: [cron: "40 1 * * *"]

permissions:
  contents: read

env:
  RUSTFLAGS: -Dwarnings

jobs:
  pre_ci:
    uses: dtolnay/.github/.github/workflows/pre_ci.yml@master

  test:
    name: Rust ${{matrix.rust}}
    needs: pre_ci
    if: needs.pre_ci.outputs.continue
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        rust: [nightly, beta, stable, 1.85.0, 1.71.0]
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@master
        with:
          toolchain: ${{matrix.rust}}
      - name: Enable type layout randomization
        run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV
        if: matrix.rust == 'nightly'
      - run: cargo check
      - run: cargo test
        if: matrix.rust != '1.71.0'
      - uses: actions/upload-artifact@v6
        if: matrix.rust == 'nightly' && always()
        with:
          name: Cargo.lock
          path: Cargo.lock
        continue-on-error: true

  minimal:
    name: Minimal versions
    needs: pre_ci
    if: needs.pre_ci.outputs.continue
    runs-on: ubuntu-latest
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@nightly
      - run: cargo generate-lockfile -Z minimal-versions
      - run: cargo check --locked

  doc:
    name: Documentation
    needs: pre_ci
    if: needs.pre_ci.outputs.continue
    runs-on: ubuntu-latest
    timeout-minutes: 45
    env:
      RUSTDOCFLAGS: -Dwarnings
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@nightly
      - uses: dtolnay/install@cargo-docs-rs
      - run: cargo docs-rs

  clippy:
    name: Clippy
    runs-on: ubuntu-latest
    if: github.event_name != 'pull_request'
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@clippy
      - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic

  miri:
    name: Miri
    needs: pre_ci
    if: needs.pre_ci.outputs.continue
    runs-on: ubuntu-latest
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@miri
      - run: cargo miri setup
      - run: cargo miri test
        env:
          MIRIFLAGS: -Zmiri-strict-provenance

  outdated:
    name: Outdated
    runs-on: ubuntu-latest
    if: github.event_name != 'pull_request'
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@v6
      - uses: dtolnay/rust-toolchain@stable
      - uses: dtolnay/install@cargo-outdated
      - run: cargo outdated --workspace --exit-code 1


================================================
FILE: .gitignore
================================================
/target/
/Cargo.lock


================================================
FILE: Cargo.toml
================================================
[package]
name = "inherent"
version = "1.0.13"
authors = ["David Tolnay <dtolnay@gmail.com>"]
categories = ["rust-patterns", "no-std", "no-std::no-alloc"]
description = "Make trait methods callable without the trait in scope"
documentation = "https://docs.rs/inherent"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/inherent"
rust-version = "1.71"

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1.0.74"
quote = "1.0.35"
syn = { version = "2.0.46", features = ["full"] }

[dev-dependencies]
rustversion = "1.0.13"
trybuild = { version = "1.0.108", features = ["diff"] }

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
    "--generate-link-to-definition",
    "--generate-macro-expansion",
    "--extern-html-root-url=core=https://doc.rust-lang.org",
    "--extern-html-root-url=alloc=https://doc.rust-lang.org",
    "--extern-html-root-url=std=https://doc.rust-lang.org",
    "--extern-html-root-url=proc_macro=https://doc.rust-lang.org",
]


================================================
FILE: LICENSE-APACHE
================================================
                              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


================================================
FILE: LICENSE-MIT
================================================
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.


================================================
FILE: README.md
================================================
\#\[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&logo=docs.rs" height="20">](https://docs.rs/inherent)
[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/inherent/ci.yml?branch=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 = "1.0"
```

## Example

```rust
mod types {
    use inherent::inherent;

    trait Trait {
        fn f(self);
    }

    pub struct Struct;

    #[inherent]
    impl Trait for Struct {
        pub 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)
    }
}
```

<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>


================================================
FILE: src/expand.rs
================================================
use crate::parse::TraitImpl;
use crate::verbatim::VerbatimFn;
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::{Attribute, FnArg, Ident, ImplItem, Pat, Path, Signature, Visibility};

pub fn inherent(mut input: TraitImpl) -> TokenStream {
    let impl_token = &input.impl_token;
    let generics = &input.generics;
    let where_clause = &input.generics.where_clause;
    let trait_ = &input.trait_;
    let ty = &input.self_ty;

    let fwd_methods: Vec<_> = input
        .items
        .iter()
        .filter_map(|item| match item {
            ImplItem::Fn(method) => Some(fwd_method(
                trait_,
                &method.attrs,
                &method.vis,
                &method.sig,
                method.block.brace_token.span.join(),
            )),
            ImplItem::Verbatim(tokens) => {
                if let Ok(method) = syn::parse2::<VerbatimFn>(tokens.clone()) {
                    Some(fwd_method(
                        trait_,
                        &method.attrs,
                        &method.vis,
                        &method.sig,
                        method.semi_token.span,
                    ))
                } else {
                    None
                }
            }
            _ => None,
        })
        .collect();

    input.items = input
        .items
        .into_iter()
        .filter_map(|item| match item {
            ImplItem::Fn(mut method) => {
                method.vis = Visibility::Inherited;
                Some(ImplItem::Fn(method))
            }
            ImplItem::Verbatim(tokens) => {
                if syn::parse2::<VerbatimFn>(tokens.clone()).is_ok() {
                    None
                } else {
                    Some(ImplItem::Verbatim(tokens))
                }
            }
            item => Some(item),
        })
        .collect();

    let body = quote_spanned!(input.brace_token.span=> { #(#fwd_methods)* });

    quote! {
        #impl_token #generics #ty #where_clause #body

        #input
    }
}

fn fwd_method(
    trait_: &Path,
    attrs: &[Attribute],
    vis: &Visibility,
    sig: &Signature,
    body_span: Span,
) -> TokenStream {
    let constness = &sig.constness;
    let asyncness = &sig.asyncness;
    let unsafety = &sig.unsafety;
    let abi = &sig.abi;
    let fn_token = sig.fn_token;
    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
        .pairs()
        .enumerate()
        .map(|(i, pair)| {
            let (input, comma_token) = pair.into_tuple();
            match input {
                FnArg::Receiver(receiver) => {
                    let self_token = receiver.self_token;
                    if receiver.reference.is_some() {
                        (quote!(#receiver #comma_token), quote!(#self_token))
                    } else {
                        (quote!(#self_token #comma_token), quote!(#self_token))
                    }
                }
                FnArg::Typed(arg) => {
                    let var = match arg.pat.as_ref() {
                        Pat::Ident(pat) => pat.ident.clone(),
                        _ => Ident::new(&format!("__arg{}", i), Span::call_site()),
                    };
                    let colon_token = arg.colon_token;
                    let ty = &arg.ty;
                    (quote!(#var #colon_token #ty #comma_token), quote!(#var))
                }
            }
        })
        .unzip();

    let types = generics.type_params().map(|param| &param.ident);
    let wait = asyncness.map(|_| quote!(.await));
    let body = quote!(<Self as #trait_>::#ident::<#(#types,)*>(#(#arg_val,)*) #wait);
    let block = quote_spanned!(body_span=> { #body });
    let args = quote_spanned!(sig.paren_token.span=> (#(#arg_pat)*));

    let has_doc = attrs.iter().any(|attr| attr.path().is_ident("doc"));
    let default_doc = if has_doc {
        None
    } else {
        let mut link = String::new();
        for segment in &trait_.segments {
            link += &segment.ident.to_string();
            link += "::";
        }
        let msg = format!("See [`{}{}`]", link, ident);
        Some(quote!(#[doc = #msg]))
    };

    quote! {
        #(#attrs)*
        #default_doc
        #vis #constness #asyncness #unsafety #abi #fn_token #ident #generics #args #output #where_clause #block
    }
}


================================================
FILE: src/lib.rs
================================================
//! [![github]](https://github.com/dtolnay/inherent)&ensp;[![crates-io]](https://crates.io/crates/inherent)&ensp;[![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&logo=docs.rs
//!
//! <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]
//!     impl Trait for Struct {
//!         pub 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)
//!     }
//! }
//! ```

#![doc(html_root_url = "https://docs.rs/inherent/1.0.13")]
#![allow(
    clippy::default_trait_access,
    clippy::module_name_repetitions,
    clippy::needless_doctest_main,
    clippy::needless_pass_by_value,
    clippy::uninlined_format_args
)]

extern crate proc_macro;

mod expand;
mod parse;
mod verbatim;

use proc_macro::TokenStream;
use syn::parse::Nothing;
use syn::parse_macro_input;

use crate::parse::TraitImpl;

#[proc_macro_attribute]
pub fn inherent(args: TokenStream, input: TokenStream) -> TokenStream {
    parse_macro_input!(args as Nothing);
    let input = parse_macro_input!(input as TraitImpl);
    expand::inherent(input).into()
}


================================================
FILE: src/parse.rs
================================================
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 Some((_bang_token, trait_, for_token)) = imp.trait_ else {
            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,
        );
    }
}


================================================
FILE: src/verbatim.rs
================================================
use proc_macro2::TokenStream;
use quote::{ToTokens, TokenStreamExt};
use syn::parse::{Parse, ParseStream, Result};
use syn::{Attribute, Signature, Token, Visibility};

pub struct VerbatimFn {
    pub attrs: Vec<Attribute>,
    pub vis: Visibility,
    pub defaultness: Option<Token![default]>,
    pub sig: Signature,
    pub semi_token: Token![;],
}

impl Parse for VerbatimFn {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(VerbatimFn {
            attrs: input.call(Attribute::parse_outer)?,
            vis: input.parse()?,
            defaultness: input.parse()?,
            sig: input.parse()?,
            semi_token: input.parse()?,
        })
    }
}

impl ToTokens for VerbatimFn {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.append_all(&self.attrs);
        self.vis.to_tokens(tokens);
        self.defaultness.to_tokens(tokens);
        self.sig.to_tokens(tokens);
        self.semi_token.to_tokens(tokens);
    }
}


================================================
FILE: tests/compiletest.rs
================================================
#[rustversion::attr(not(nightly), ignore = "requires nightly")]
#[cfg_attr(miri, ignore = "incompatible with miri")]
#[test]
fn ui() {
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/ui/*.rs");
}


================================================
FILE: tests/test.rs
================================================
mod types {
    use inherent::inherent;

    trait Trait {
        fn f<T: ?Sized>(self);
        // A default method
        fn g(&self) {}

        #[rustversion::since(1.75)]
        async fn a(&self);
    }

    pub struct Struct;

    #[inherent]
    impl Trait for Struct {
        pub fn f<T: ?Sized>(self) {}
        pub fn g(&self);

        #[rustversion::since(1.75)]
        pub async fn a(&self) {}
    }
}

#[test]
fn test() {
    // types::Trait is not in scope.
    let s = types::Struct;
    s.g();
    s.f::<str>();
}

#[rustversion::since(1.75)]
#[test]
fn test_async() {
    fn assert_future<T: std::future::Future<Output = ()>>(_: T) {}

    let s = types::Struct;
    assert_future(s.a());
}


================================================
FILE: tests/ui/associated-type.rs
================================================
use inherent::inherent;

pub trait Trait {
    type Assoc;
    fn f() -> Self::Assoc;
}

pub struct Struct;

#[inherent]
impl Trait for Struct {
    type Assoc = ();

    // TODO: https://github.com/dtolnay/inherent/issues/15
    fn f() -> Self::Assoc {}
}

fn main() {}


================================================
FILE: tests/ui/associated-type.stderr
================================================
error[E0223]: ambiguous associated type
  --> tests/ui/associated-type.rs:15:15
   |
15 |     fn f() -> Self::Assoc {}
   |               ^^^^^^^^^^^
   |
help: use fully-qualified syntax
   |
15 -     fn f() -> Self::Assoc {}
15 +     fn f() -> <Struct as Trait>::Assoc {}
   |


================================================
FILE: tests/ui/blanket-impl.rs
================================================
use inherent::inherent;

trait A {
    fn a(&self);
}

#[inherent]
impl<T> A for T {
    fn a(&self) {}
}

fn main() {}


================================================
FILE: tests/ui/blanket-impl.stderr
================================================
error[E0118]: no nominal type found for inherent implementation
 --> tests/ui/blanket-impl.rs:8:1
  |
8 | impl<T> A for T {
  | ^^^^^^^^^^^^^^^ impl requires a nominal type
  |
  = note: either implement a trait on it or create a newtype to wrap it instead


================================================
FILE: tests/ui/not-trait-impl.rs
================================================
use inherent::inherent;

struct Struct;

#[inherent]
impl Struct {
    fn f() {}
}

fn main() {}


================================================
FILE: tests/ui/not-trait-impl.stderr
================================================
error: must be placed on a trait impl
 --> tests/ui/not-trait-impl.rs:5:1
  |
5 | #[inherent]
  | ^^^^^^^^^^^
  |
  = note: this error originates in the attribute macro `inherent` (in Nightly builds, run with -Z macro-backtrace for more info)


================================================
FILE: tests/ui/not-visible.rs
================================================
mod types {
    use inherent::inherent;

    trait Trait {
        fn f();
    }

    pub struct Struct;

    #[inherent]
    impl Trait for Struct {
        fn f() {}
    }
}

fn main() {
    types::Struct::f();
}


================================================
FILE: tests/ui/not-visible.stderr
================================================
error[E0624]: associated function `f` is private
  --> tests/ui/not-visible.rs:17:20
   |
12 |         fn f() {}
   |         ------ private associated function defined here
...
17 |     types::Struct::f();
   |                    ^ private associated function
Download .txt
gitextract_a9m06ltv/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── src/
│   ├── expand.rs
│   ├── lib.rs
│   ├── parse.rs
│   └── verbatim.rs
└── tests/
    ├── compiletest.rs
    ├── test.rs
    └── ui/
        ├── associated-type.rs
        ├── associated-type.stderr
        ├── blanket-impl.rs
        ├── blanket-impl.stderr
        ├── not-trait-impl.rs
        ├── not-trait-impl.stderr
        ├── not-visible.rs
        └── not-visible.stderr
Download .txt
SYMBOL INDEX (38 symbols across 10 files)

FILE: src/expand.rs
  function inherent (line 7) | pub fn inherent(mut input: TraitImpl) -> TokenStream {
  function fwd_method (line 70) | fn fwd_method(

FILE: src/lib.rs
  function inherent (line 97) | pub fn inherent(args: TokenStream, input: TokenStream) -> TokenStream {

FILE: src/parse.rs
  type TraitImpl (line 8) | pub struct TraitImpl {
  method parse (line 22) | fn parse(input: ParseStream) -> Result<Self> {
  method to_tokens (line 48) | fn to_tokens(&self, tokens: &mut TokenStream) {

FILE: src/verbatim.rs
  type VerbatimFn (line 6) | pub struct VerbatimFn {
  method parse (line 15) | fn parse(input: ParseStream) -> Result<Self> {
  method to_tokens (line 27) | fn to_tokens(&self, tokens: &mut TokenStream) {

FILE: tests/compiletest.rs
  function ui (line 4) | fn ui() {

FILE: tests/test.rs
  type Trait (line 4) | trait Trait {
    method f (line 5) | fn f<T: ?Sized>(self);
    method g (line 7) | fn g(&self) {}
    method a (line 10) | async fn a(&self);
    method f (line 17) | pub fn f<T: ?Sized>(self) {}
    method g (line 18) | pub fn g(&self);
    method a (line 21) | pub async fn a(&self) {}
  type Struct (line 13) | pub struct Struct;
  function test (line 26) | fn test() {
  function test_async (line 35) | fn test_async() {

FILE: tests/ui/associated-type.rs
  type Trait (line 3) | pub trait Trait {
    method f (line 5) | fn f() -> Self::Assoc;
    type Assoc (line 12) | type Assoc = ();
    method f (line 15) | fn f() -> Self::Assoc {}
  type Struct (line 8) | pub struct Struct;
  function main (line 18) | fn main() {}

FILE: tests/ui/blanket-impl.rs
  type A (line 3) | trait A {
    method a (line 4) | fn a(&self);
    method a (line 9) | fn a(&self) {}
  function main (line 12) | fn main() {}

FILE: tests/ui/not-trait-impl.rs
  type Struct (line 3) | struct Struct;
    method f (line 7) | fn f() {}
  function main (line 10) | fn main() {}

FILE: tests/ui/not-visible.rs
  type Trait (line 4) | trait Trait {
    method f (line 5) | fn f();
    method f (line 12) | fn f() {}
  type Struct (line 8) | pub struct Struct;
  function main (line 16) | fn main() {
Condensed preview — 21 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (32K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 16,
    "preview": "github: dtolnay\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 2661,
    "preview": "name: CI\n\non:\n  push:\n  pull_request:\n  workflow_dispatch:\n  schedule: [cron: \"40 1 * * *\"]\n\npermissions:\n  contents: re"
  },
  {
    "path": ".gitignore",
    "chars": 21,
    "preview": "/target/\n/Cargo.lock\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 1026,
    "preview": "[package]\nname = \"inherent\"\nversion = \"1.0.13\"\nauthors = [\"David Tolnay <dtolnay@gmail.com>\"]\ncategories = [\"rust-patter"
  },
  {
    "path": "LICENSE-APACHE",
    "chars": 9723,
    "preview": "                              Apache License\n                        Version 2.0, January 2004\n                     http"
  },
  {
    "path": "LICENSE-MIT",
    "chars": 1023,
    "preview": "Permission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentati"
  },
  {
    "path": "README.md",
    "chars": 2507,
    "preview": "\\#\\[inherent\\]\n==============\n\n[<img alt=\"github\" src=\"https://img.shields.io/badge/github-dtolnay/inherent-8da0cb?style"
  },
  {
    "path": "src/expand.rs",
    "chars": 4501,
    "preview": "use crate::parse::TraitImpl;\nuse crate::verbatim::VerbatimFn;\nuse proc_macro2::{Span, TokenStream};\nuse quote::{quote, q"
  },
  {
    "path": "src/lib.rs",
    "chars": 2769,
    "preview": "//! [![github]](https://github.com/dtolnay/inherent)&ensp;[![crates-io]](https://crates.io/crates/inherent)&ensp;[![docs"
  },
  {
    "path": "src/parse.rs",
    "chars": 1904,
    "preview": "use proc_macro2::{Span, TokenStream};\nuse quote::ToTokens;\nuse syn::parse::{Error, Parse, ParseStream, Result};\nuse syn:"
  },
  {
    "path": "src/verbatim.rs",
    "chars": 968,
    "preview": "use proc_macro2::TokenStream;\nuse quote::{ToTokens, TokenStreamExt};\nuse syn::parse::{Parse, ParseStream, Result};\nuse s"
  },
  {
    "path": "tests/compiletest.rs",
    "chars": 214,
    "preview": "#[rustversion::attr(not(nightly), ignore = \"requires nightly\")]\n#[cfg_attr(miri, ignore = \"incompatible with miri\")]\n#[t"
  },
  {
    "path": "tests/test.rs",
    "chars": 714,
    "preview": "mod types {\n    use inherent::inherent;\n\n    trait Trait {\n        fn f<T: ?Sized>(self);\n        // A default method\n  "
  },
  {
    "path": "tests/ui/associated-type.rs",
    "chars": 271,
    "preview": "use inherent::inherent;\n\npub trait Trait {\n    type Assoc;\n    fn f() -> Self::Assoc;\n}\n\npub struct Struct;\n\n#[inherent]"
  },
  {
    "path": "tests/ui/associated-type.stderr",
    "chars": 279,
    "preview": "error[E0223]: ambiguous associated type\n  --> tests/ui/associated-type.rs:15:15\n   |\n15 |     fn f() -> Self::Assoc {}\n "
  },
  {
    "path": "tests/ui/blanket-impl.rs",
    "chars": 120,
    "preview": "use inherent::inherent;\n\ntrait A {\n    fn a(&self);\n}\n\n#[inherent]\nimpl<T> A for T {\n    fn a(&self) {}\n}\n\nfn main() {}\n"
  },
  {
    "path": "tests/ui/blanket-impl.stderr",
    "chars": 257,
    "preview": "error[E0118]: no nominal type found for inherent implementation\n --> tests/ui/blanket-impl.rs:8:1\n  |\n8 | impl<T> A for "
  },
  {
    "path": "tests/ui/not-trait-impl.rs",
    "chars": 97,
    "preview": "use inherent::inherent;\n\nstruct Struct;\n\n#[inherent]\nimpl Struct {\n    fn f() {}\n}\n\nfn main() {}\n"
  },
  {
    "path": "tests/ui/not-trait-impl.stderr",
    "chars": 243,
    "preview": "error: must be placed on a trait impl\n --> tests/ui/not-trait-impl.rs:5:1\n  |\n5 | #[inherent]\n  | ^^^^^^^^^^^\n  |\n  = no"
  },
  {
    "path": "tests/ui/not-visible.rs",
    "chars": 215,
    "preview": "mod types {\n    use inherent::inherent;\n\n    trait Trait {\n        fn f();\n    }\n\n    pub struct Struct;\n\n    #[inherent"
  },
  {
    "path": "tests/ui/not-visible.stderr",
    "chars": 261,
    "preview": "error[E0624]: associated function `f` is private\n  --> tests/ui/not-visible.rs:17:20\n   |\n12 |         fn f() {}\n   |   "
  }
]

About this extraction

This page contains the full source code of the dtolnay/inherent GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 21 files (29.1 KB), approximately 7.7k tokens, and a symbol index with 38 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!