Full Code of chancancode/rust-delegate for AI

main 8847e2333c93 cached
33 files
130.0 KB
32.1k tokens
148 symbols
1 requests
Download .txt
Repository: chancancode/rust-delegate
Branch: main
Commit: 8847e2333c93
Files: 33
Total size: 130.0 KB

Directory structure:
gitextract_6vrwi07n/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       ├── nightly-build.yml
│       ├── publish.yml
│       └── test.yml
├── .gitignore
├── .release-plz.toml
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── src/
│   ├── attributes.rs
│   └── lib.rs
└── tests/
    ├── argument_modifier.rs
    ├── associated_const_delegation.rs
    ├── async_await.rs
    ├── closure.rs
    ├── delegate_to_enum.rs
    ├── delegation.rs
    ├── expand/
    │   ├── fields.expanded.rs
    │   └── fields.rs
    ├── expr.rs
    ├── expr_attribute.rs
    ├── fields.rs
    ├── function.rs
    ├── generic.rs
    ├── in_macro_expansion.rs
    ├── inline_args.rs
    ├── nested.rs
    ├── returntype.rs
    ├── segment_attributes.rs
    ├── stack.rs
    └── through_trait.rs

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

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


================================================
FILE: .github/workflows/nightly-build.yml
================================================
on:
  schedule:
    - cron: "0 0 * * *"
  workflow_dispatch:

name: Nightly Build

jobs:
  test:
    name: Build
    runs-on: ubuntu-latest
    strategy:
      matrix:
        rust:
          - stable
          - beta
          - nightly
    steps:
      - name: Checkout sources
        uses: actions/checkout@v2

      - name: Install stable toolchain
        uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: ${{ matrix.rust }}
          override: true

      - name: Build
        uses: actions-rs/cargo@v1
        with:
          command: build
          args: --all --all-features


================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish new release

on:
  push:
    branches:
      - main

jobs:
  test:
    name: Release test
    runs-on: ubuntu-latest
    if: ${{ github.repository_owner == 'kobzol' }}
    steps:
      - &checkout
        name: Checkout repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 0
          persist-credentials: false
      - &install-rust
        name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
      - name: Install cargo-expand
        uses: actions-rs/cargo@v1
        with:
          command: install
          args: --locked --version 1.0.118 cargo-expand
      - run: cargo test
  # Release unpublished packages.
  release:
    name: Release-plz release
    runs-on: ubuntu-latest
    if: ${{ github.repository_owner == 'kobzol' }}
    needs:
      - test
    permissions:
      contents: write
      id-token: write
    steps:
      - *checkout
      - *install-rust
      - name: Run release-plz
        # 0.5.118
        uses: release-plz/action@01df7609d1a7310c0776a102df00daf509d56e33
        with:
          command: release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  # Create a PR with the new versions and changelog, preparing the next release.
  create-release-pr:
    name: Release-plz PR
    runs-on: ubuntu-latest
    if: ${{ github.repository_owner == 'kobzol' }}
    permissions:
      contents: write
      pull-requests: write
    concurrency:
      group: release-plz-${{ github.ref }}
      cancel-in-progress: false
    steps:
      - *checkout
      - *install-rust
      - name: Run release-plz
        # 0.5.118
        uses: release-plz/action@01df7609d1a7310c0776a102df00daf509d56e33
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .github/workflows/test.yml
================================================
# Based on https://github.com/actions-rs/meta/blob/master/recipes/matrix.md

on: [ push, pull_request ]

name: Tests

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    strategy:
      matrix:
        rust:
          - stable
          - beta
          - nightly
    steps:
      - name: Checkout sources
        uses: actions/checkout@v2

      - name: Install stable toolchain
        uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: ${{ matrix.rust }}
          override: true
          components: rustfmt, clippy

      - uses: Swatinem/rust-cache@v2

      - name: Install cargo-expand
        uses: actions-rs/cargo@v1
        with:
          command: install
          args: --locked --version 1.0.118 cargo-expand

      - name: Build
        uses: actions-rs/cargo@v1
        with:
          command: build
          args: --all --all-features

      - name: Test
        uses: actions-rs/cargo@v1
        with:
          command: test

      - name: Lint
        uses: actions-rs/cargo@v1
        with:
          command: clippy
          args: -- -D warnings

      - name: Formatting
        uses: actions-rs/cargo@v1
        with:
          command: fmt
          args: --all -- --check


================================================
FILE: .gitignore
================================================
/target
**/*.rs.bk
Cargo.lock


================================================
FILE: .release-plz.toml
================================================
[workspace]
release_always = false
pr_branch_prefix = "release-"
pr_labels = ["release"]
semver_check = false


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

## [0.13.5](https://github.com/Kobzol/rust-delegate/compare/v0.13.4...v0.13.5) - 2025-11-17

### New features

- Implement support for delegating to fields (#88 from JRRudy1).

### Internal

- Start using [release-plz](https://release-plz.dev/) for releases, together with crates.io Trusted Publishing.

# 0.13.4 (14. 7. 2025)

- Do not explicitly forward lifetime arguments when calling delegated functions (https://github.com/Kobzol/rust-delegate/issues/85).

# 0.13.3 (25. 3. 2025)

- Add `#[const(path::to::Trait::CONST)]` attribute to delegate associated constants via a getter (implemented by @vic1707).
- Add `#[expr(<$ template>)]` attribute to modify delegated call using custom code (implemented by @vic1707).

# 0.13.2 (14. 1. 2025)

- Correctly parse attributes with segmented paths (e.g. `#[a::b::c]`) (https://github.com/Kobzol/rust-delegate/issues/77).

# 0.13.1 (9. 10. 2024)

- Correctly pass generic method type and lifetime arguments to the delegated method.

# 0.13.0 (2. 9. 2024)

- Generalize match arms handling. You can now combine a match expression target with annotations like `#[into]` and
  others:

```rust
struct A;

impl A {
    pub fn callable(self) -> Self {
        self
    }
}

struct B;

impl B {
    pub fn callable(self) -> Self {
        self
    }
}

enum Common {
    A(A),
    B(B),
}

impl From<A> for Common {
    fn from(inner: A) -> Self {
        Self::A(inner)
    }
}

impl From<B> for Common {
    fn from(inner: B) -> Self {
        Self::B(inner)
    }
}

impl Common {
    delegate! {
        to match self {
        // ---------- `match` arms have incompatible types
            Common::A(inner) => inner;
            Common::B(inner) => inner;
        } {
            #[into]
            pub fn callable(self) -> Self;
        }
    }

    // Generates
    // pub fn callable(self) -> Self {
    //     match self {
    //         Common::A(inner) => inner.callable().into(),
    //         Common::B(inner) => inner.callable().into(),
    //     }
    // }
}
```

- The crate should be `#[no_std]` compatible again (https://github.com/Kobzol/rust-delegate/pull/74).

# 0.12.0 (22. 12. 2023)

- Add new `#[newtype]` function parameter modifier ([#64](https://github.com/Kobzol/rust-delegate/pull/64)).
  Implemented by [Techassi](https://github.com/Techassi)

- Allow passing arbitrary attributes to delegation segments:

```rust
impl Foo {
    delegate! {
    #[inline(always)]
    to self.0 { ... }
  }
}
```

- Change the default inlining mode from `#[inline(always)]`
  to `#[inline]` (https://github.com/Kobzol/rust-delegate/issues/61).

# 0.11.0 (4. 12. 2023)

- Allow delegating an associated function (not just a method).

```rust
struct A {}

impl A {
    fn foo(a: u32) -> u32 {
        a + 1
    }
}

struct B;

impl B {
    delegate! {
        to A {
            fn foo(a: u32) -> u32;
        }
    }
}
```

# 0.10.0 (29. 6. 2023)

- Allow specifying certain attributes (e.g. `#[into]` or `#[unwrap]`) on delegated segments.
  The attribute will then be applied to all methods in that segment (unless it is overwritten on the method itself).

```rust
delegate! {
  #[unwrap]
  to self.inner {
    fn foo(&self) -> u32; // calls self.inner.foo().unwrap()
    fn bar(&self) -> u32; // calls self.inner.bar().unwrap()
  }
}
```

- Add new `#[unwrap]` method modifier. Adding it on top of a delegated method will cause the generated
  code to `.unwrap()` the result.

```rust
#[unwrap]
fn foo(&self) -> u32;  // foo().unwrap()
```

- Add new `#[through(<trait>)]` method modifier. Adding it on top of a delegated method will cause the generated
  code to call the method through the provided trait
  using [UFCS](https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls).

```rust
#[through(MyTrait)]
delegate! {
  to &self.inner {
    #[through(MyTrait)]
    fn foo(&self) -> u32;  // MyTrait::foo(&self.inner)
  }
}
```

- Removed `#[try_into(unwrap)]`. It can now be replaced with the combination of `#[try_into]` and `#[unwrap]`:

```rust
#[try_into]
#[unwrap]
fn foo(&self) -> u32;  // TryInto::try_into(foo()).unwrap()
```

- Add the option to specify explicit type path to the `#[into]` expression modifier:

```rust
#[into(u64)]
fn foo(&self) -> u64; // Into::<u64>::into(foo())
```

- Expression modifiers `#[into]`, `#[try_into]` and `#[unwrap]` can now be used multiple times. The order
  of their usage dictates in what order they will be applied:

```rust
#[into]
#[unwrap]
fn foo(&self) -> u32;  // Into::into(foo()).unwrap()

#[unwrap]
#[into]
fn foo(&self) -> u32;  // Into::into(foo().unwrap())
```

# 0.9.0 (16. 1. 2023)

- Add new `#[as_ref]` function parameter modifier ([#47](https://github.com/Kobzol/rust-delegate/pull/47)).
  Implemented by [trueegorletov](https://github.com/trueegorletov).

# 0.8.0 (7. 9. 2022)

- Allow simple delegation to enum variants ([#45](https://github.com/Kobzol/rust-delegate/pull/45)).
  Implemented by [gfreezy](https://github.com/gfreezy).

# 0.7.0 (6. 6. 2022)

- Add new `#[into]` attribute for delegated function parameters. If specified, the parameter will be
  converted using the `From` trait before being passed as an argument to the called function.
- Add new `#[try_from]` attribute to delegated functions. You can use it to convert the delegated
  expression using the `TryFrom` trait. You can also use `#[try_from(unwrap)]` to unwrap the result of
  the conversion.

# 0.6.2 (31. 1. 2022)

- Add new `#[await(true/false)]` attribute to delegated functions. You can use it to control whether
  `.await` will be appended to the delegated expression. It will be generated by default if the delegation
  method signature is `async`.

# 0.6.1 (25. 7. 2021)

- add support for `async` functions. The delegated call will now use `.await`.

# 0.6.0 (7. 7. 2021)

- add the option to specify inline expressions that will be used as arguments for the delegated
  call (https://github.com/kobzol/rust-delegate/pull/34)
- removed `append_args` attribute, which is superseded by the mentioned expression in signature support

# 0.5.2 (16. 6. 2021)

- add the `append_args` attribute to append attributes to delegated
  calls (https://github.com/kobzol/rust-delegate/pull/31)

# 0.5.1 (6. 1. 2021)

- fix breaking change caused by using `syn` private API (https://github.com/kobzol/rust-delegate/issues/28)

# 0.5.0 (16. 11. 2020)

- `self` can now be used as the delegation target
- Rust 1.46 introduced a change that makes it a bit difficult to use `rust-delegate` implementations
  generated by macros. If you have this use case, please
  use [this workaround](https://github.com/kobzol/rust-delegate/issues/25#issuecomment-716774685).


================================================
FILE: Cargo.toml
================================================
[package]
name = "delegate"
description = "Method delegation with less boilerplate"
version = "0.13.5"
authors = ["Godfrey Chan <godfreykfc@gmail.com>", "Jakub Beránek <berykubik@gmail.com>"]
repository = "https://github.com/kobzol/rust-delegate"
readme = "README.md"
license = "MIT OR Apache-2.0"
edition = "2018"
include = [
    "src/*.rs",
    "Cargo.toml",
    "README.md"
]

[dependencies]
syn = { version = "2", features = ["full", "visit-mut"] }
quote = "1"
proc-macro2 = "1"

[lib]
proc-macro = true

[dev-dependencies]
async-trait = "0.1.50"
futures = "0.3.16"
tokio = { version = "1.16.1", features = ["sync"] }
macrotest = "1.0.12"


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

   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.


================================================
FILE: LICENSE-MIT
================================================
Copyright (c) 2018 The Rust Delegate Crate Developers

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
================================================
# Method delegation with less boilerplate

[![Build Status](https://github.com/kobzol/rust-delegate/workflows/Tests/badge.svg)](https://github.com/kobzol/rust-delegate/actions)
[![Crates.io](https://img.shields.io/crates/v/delegate.svg)](https://crates.io/crates/delegate)

This crate removes some boilerplate for structs that simply delegate some of
their methods to one or more of their fields.

It gives you the `delegate!` macro, which delegates method calls to selected
expressions (usually inner fields).

## Example:

A Stack data structure implemented using an inner Vec via delegation.

```rust
use delegate::delegate;

#[derive(Clone, Debug)]
struct Stack<T> {
    inner: Vec<T>,
}
impl<T> Stack<T> {
    pub fn new() -> Self <T> {
        Self { inner: vec![] }
    }

    delegate! {
        to self.inner {
            pub fn is_empty(&self) -> bool;
            pub fn push(&mut self, value: T);
            pub fn pop(&mut self) -> Option<T>;
            pub fn clear(&mut self);

            #[call(len)]
            pub fn size(&self) -> usize;

            #[call(last)]
            pub fn peek(&self) -> Option<&T>;

        }
    }
}
```

## Features

### Delegate to a method with a different name
```rust
struct Stack {
    inner: Vec<u32>
}
impl Stack {
    delegate! {
        to self.inner {
            #[call(push)]
            pub fn add(&mut self, value: u32);
        }
    }
}
```

### Use an arbitrary inner field expression
```rust
struct Wrapper {
    inner: Rc<RefCell<Vec<u32>>>
}
impl Wrapper {
    delegate! {
        to self.inner.deref().borrow_mut() {
            pub fn push(&mut self, val: u32);
        }
    }
}
```

### Delegate to enum variants
```rust
use delegate::delegate;

enum Enum {
    A(A),
    B(B),
    C { v: C },
}

struct A {
    val: usize,
}

impl A {
    fn dbg_inner(&self) -> usize {
        dbg!(self.val);
        1
    }
}
struct B {
    val_a: String,
}

impl B {
    fn dbg_inner(&self) -> usize {
        dbg!(self.val_a.clone());
        2
    }
}

struct C {
    val_c: f64,
}

impl C {
    fn dbg_inner(&self) -> usize {
        dbg!(self.val_c);
        3
    }
}

impl Enum {
    delegate! {
        // transformed to
        //
        // ```rust
        // match self {
        //     Enum::A(a) => a.dbg_inner(),
        //     Enum::B(b) => { println!("i am b"); b }.dbg_inner(),
        //     Enum::C { v: c } => { c }.dbg_inner(),
        // }
        // ```
        to match self {
            Enum::A(a) => a,
            Enum::B(b) => { println!("i am b"); b },
            Enum::C { v: c } => { c },
        } {
            fn dbg_inner(&self) -> usize;
        }
    }
}
```

### Use modifiers that alter the generated method body
```rust
use delegate::delegate;
struct Inner;
impl Inner {
    pub fn method(&self, num: u32) -> u32 { num }
    pub fn method_res(&self, num: u32) -> Result<u32, ()> { Ok(num) }
}
struct Wrapper {
    inner: Inner
}
impl Wrapper {
    delegate! {
        to self.inner {
            // calls method, converts result to u64 using `From`
            #[into]
            pub fn method(&self, num: u32) -> u64;

            // calls method, returns ()
            #[call(method)]
            pub fn method_noreturn(&self, num: u32);

            // calls method, converts result to i6 using `TryFrom`
            #[try_into]
            #[call(method)]
            pub fn method2(&self, num: u32) -> Result<u16, std::num::TryFromIntError>;

            // calls method_res, unwraps the result
            #[unwrap]
            pub fn method_res(&self, num: u32) -> u32;

            // calls method_res, unwraps the result, then calls into
            #[unwrap]
            #[into]
            #[call(method_res)]
            pub fn method_res_into(&self, num: u32) -> u64;

            // specify explicit type for into
            #[into(u64)]
            #[call(method)]
            pub fn method_into_explicit(&self, num: u32) -> u64;
        }
    }
}
```

### Custom called expression

The `#[expr()]` attribute can be used to modify the delegated call. You can use the `$` sigil as a placeholder for what delegate would normally expand to, and wrap that expression with custom code.

_Note:_ the `$` placeholder isn't required and can be present multiple times if you want.

```rust
struct A(Vec<u8>);

impl A {
    delegate! {
        to self.0 {
            #[expr(*$.unwrap())]
            /// Here `$` == `self.0.get(idx)`
            /// Will expand to `*self.0.get(idx).unwrap()`
            fn get(&self, idx: usize) -> u8;

            #[call(get)]
            #[expr($?.checked_pow(2))]
            /// Here `$` == `self.0.get(idx)`
            /// Will expand to `self.0.get(idx)?.checked_pow(2)`
            fn get_checked_pow_2(&self, idx: usize) -> Option<u8>;
        }
    }
}
```

### Add additional arguments to method
```rust
struct Inner(u32);
impl Inner {
    pub fn new(m: u32) -> Self {
        // some "very complex" constructing work
        Self(m)
    }
    pub fn method(&self, n: u32) -> u32 {
        self.0 + n
    }
}

struct Wrapper {
    inner: OnceCell<Inner>,
}

impl Wrapper {
    pub fn new() -> Self {
        Self {
            inner: OnceCell::new(),
        }
    }
    fn content(&self, val: u32) -> &Inner {
        self.inner.get_or_init(|| Inner(val))
    }
    delegate! {
        to |k: u32| self.content(k) {
            // `wrapper.method(k, num)` will call `self.content(k).method(num)`
            pub fn method(&self, num: u32) -> u32;
        }
    }
}
```

### Call `await` on async functions
```rust
struct Inner;
impl Inner {
    pub async fn method(&self, num: u32) -> u32 { num }
}
struct Wrapper {
    inner: Inner
}
impl Wrapper {
    delegate! {
        to self.inner {
            // calls method(num).await, returns impl Future<Output = u32>
            pub async fn method(&self, num: u32) -> u32;
            // calls method(num).await.into(), returns impl Future<Output = u64>
            #[into]
            #[call(method)]
            pub async fn method_into(&self, num: u32) -> u64;
        }
    }
}
```

You can use the `#[await(true/false)]` attribute on delegated methods to specify
if `.await` should be generated after the delegated expression. It will be
generated by default if the delegated method is `async`.

### Delegate to multiple fields
```rust
struct MultiStack {
    left: Vec<u32>,
    right: Vec<u32>,
}
impl MultiStack {
    delegate! {
        to self.left {
            /// Push an item to the top of the left stack
            #[call(push)]
            pub fn push_left(&mut self, value: u32);
        }
        to self.right {
            /// Push an item to the top of the right stack
            #[call(push)]
            pub fn push_right(&mut self, value: u32);
        }
    }
}
```

### Inline attributes
`rust-delegate` inserts `#[inline(always)]` automatically. You can override that decision by specifying `#[inline]`
manually on the delegated method.

### Segment attributes
You can use an attribute on a whole delegation segment to automatically apply it to all methods in that segment:

```rust
struct Wrapper {
    inner: Inner
}

impl Wrapper {
    delegate! {
   #[unwrap]
   to self.inner {
     fn foo(&self) -> u32; // calls self.inner.foo().unwrap()
     fn bar(&self) -> u32; // calls self.inner.bar().unwrap()
   }
 }
}
```

### Adding additional arguments
You can specify expressions in the signature that will be used as delegated arguments:

```rust
use delegate::delegate;

struct Inner;
impl Inner {
    pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 {
        a + x * x + b * y + c
    }
}
struct Wrapper {
    inner: Inner,
    a: i32,
    b: i32,
    c: i32
}
impl Wrapper {
    delegate! {
        to self.inner {
            // Calls `polynomial` on `inner` with `self.a`, `self.b` and
            // `self.c` passed as arguments `a`, `b`, and `c`, effectively
            // calling `polynomial(self.a, x, self.b, y, self.c)`.
            pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ;
            // Calls `polynomial` on `inner` with `0`s passed for arguments
            // `a` and `x`, and `self.b` and `self.c` for `b` and `c`,
            // effectively calling `polynomial(0, 0, self.b, y, self.c)`.
            #[call(polynomial)]
            pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ;
        }
    }
}
```

### Parameter modifiers
You can modify how will an input parameter be passed to the delegated method with parameter attribute modifiers. Currently, the following modifiers are supported:
- `#[into]`: Calls `.into()` on the parameter passed to the delegated method.
- `#[as_ref]`: Calls `.as_ref()` on the parameter passed to the delegated method.
- `#[newtype]`: Accesses the first tuple element (`.0`) of the parameter passed to the delegated method.

> Note that these modifiers might be removed in the future, try to use the more general `#[expr]` mechanism to achieve this functionality.

```rust
use delegate::delegate;

struct InnerType {}
impl InnerType {
    fn foo(&self, other: Self) {}
}

impl From<Wrapper> for InnerType {
    fn from(wrapper: Wrapper) -> Self {
        wrapper.0
    }
}

struct Wrapper(InnerType);
impl Wrapper {
    delegate! {
        to self.0 {
            // Calls `self.0.foo(other.into());`
            pub fn foo(&self, #[into] other: Self);
            // Calls `self.0.bar(other.0);`
            pub fn bar(&self, #[newtype] other: Self);
        }
    }
}
```

### Delegate associated functions
```rust
use delegate::delegate;

struct A {}
impl A {
    fn foo(a: u32) -> u32 {
        a + 1
    }
}

struct B;

impl B {
    delegate! {
        to A {
            fn foo(a: u32) -> u32;
        }
    }
}

assert_eq!(B::foo(1), 2);
```

### Delegate associated constants
```rust
use delegate::delegate;

trait WithConst {
    const TOTO: u8;
}

struct A;
impl WithConst for A {
    const TOTO: u8 = 1;
}

struct B;
impl WithConst for B {
    const TOTO: u8 = 2;
}
struct C;
impl WithConst for C {
    const TOTO: u8 = 2;
}

enum Enum {
    A(A),
    B(B),
    C(C),
}

impl Enum {
    delegate! {
        to match self {
            Self::A(a) => a,
            Self::B(b) => b,
            Self::C(c) => { println!("hello from c"); c },
        } {
            #[const(WithConst::TOTO)]
            fn get_toto(&self) -> u8;
        }
    }
}

assert_eq!(Enum::A(A).get_toto(), <A as WithConst>::TOTO);
```

### Delegate to fields
```rust
use delegate::delegate;

struct Datum {
    value: u32,
    error: u32,
}

struct DatumWrapper(Datum);

impl DatumWrapper {
    delegate! {
        to self.0 {
            /// Get the value of a nested field with the same name
            #[field]
            fn value(&self) -> u32;

            /// Get the value of a nested field with a different name
            #[field(value)]
            fn renamed_value(&self) -> u32;

            /// Get shared reference to a nested field
            #[field(&value)]
            fn value_ref(&self) -> &u32;

            /// Get mutable reference to a nested field
            #[field(&mut value)]
            fn value_ref_mut(&mut self) -> &mut u32;

            /// Get mutable reference to a nested field with the same name
            #[field(&)]
            fn error(&self) -> &u32;
        }
    }
}
```

## Development

This project uses a standard test suite for quality control, as well as a set of
"expansion" tests that utilize the `macrotest` crate to ensure the macro expands
as expected. PRs implementing new features should add both standard and expansion
tests where appropriate.

To add an expansion test, place a Rust source file in the `tests/expand/` directory
with methods demonstrating the new feature. Next, run `cargo test` to run the test
suite and generate a `*.expanded.rs` file in the same directory. Next, carefully
inspect the contents of the generated file to confirm that all methods expanded as
expected. Finally, commit both files to the git repository. Future test suite runs
will now include expanding the source file and comparing it to the expanded file.

## License

Licensed under either of

- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
  http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

## Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

## Conduct

Please follow the [Rust Code of Conduct]. For escalation or moderation issues
please contact the crate author(s) listed in [`Cargo.toml`](./Cargo.toml).

[Rust Code of Conduct]: https://www.rust-lang.org/conduct.html


================================================
FILE: src/attributes.rs
================================================
use proc_macro2::{Delimiter, TokenStream, TokenTree};
use quote::ToTokens;
use std::collections::VecDeque;
use std::ops::Not;
use syn::parse::ParseStream;
use syn::{Attribute, Error, Meta, Path, PathSegment, Token, TypePath};

pub struct CallMethodAttribute {
    name: syn::Ident,
}

impl syn::parse::Parse for CallMethodAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        Ok(CallMethodAttribute {
            name: input.parse()?,
        })
    }
}

#[derive(Default, Clone)]
pub struct GetFieldAttribute {
    reference: Option<(Token![&], Option<Token![mut]>)>,
    member: Option<syn::Member>,
}

impl GetFieldAttribute {
    pub fn reference_tokens(&self) -> Option<TokenStream> {
        let (ref_, mut_) = self.reference.as_ref()?;
        let mut tokens = ref_.to_token_stream();
        mut_.to_tokens(&mut tokens);
        Some(tokens)
    }
}

impl syn::parse::Parse for GetFieldAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let mut reference = None;
        if let Ok(ref_) = input.parse::<syn::Token![&]>() {
            reference = Some((ref_, None));
        }
        if let Some((_, mut_)) = &mut reference {
            *mut_ = input.parse::<syn::Token![mut]>().ok();
        }
        let member = input.is_empty().not().then(|| input.parse()).transpose()?;
        Ok(GetFieldAttribute { reference, member })
    }
}

struct GenerateAwaitAttribute {
    literal: syn::LitBool,
}

impl syn::parse::Parse for GenerateAwaitAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        Ok(GenerateAwaitAttribute {
            literal: input.parse()?,
        })
    }
}

struct IntoAttribute {
    type_path: Option<TypePath>,
}

impl syn::parse::Parse for IntoAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let type_path: TypePath = input.parse().map_err(|error| {
            Error::new(
                input.span(),
                format!("{error}\nExpected type name, e.g. #[into(u32)]"),
            )
        })?;

        Ok(IntoAttribute {
            type_path: Some(type_path),
        })
    }
}

pub struct AssociatedConstant {
    pub const_name: PathSegment,
    pub trait_path: Path,
}

impl syn::parse::Parse for AssociatedConstant {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let mut path = input.parse::<syn::Path>().map_err(|error| {
            Error::new(
                input.span(),
                format!(
                    "{error}\nExpected const path, e.g. #[const(path::to::MyTrait::CONST_NAME)]"
                ),
            )
        })?;

        let const_name = path.segments.pop().ok_or_else(|| {
            Error::new_spanned(
                &path,
                "Expected a path. e.g. #[const(path::to::MyTrait::CONST_NAME)]",
            )
        })?;
        // poping a segment leads to trailing `::`
        path.segments.pop_punct().ok_or_else(|| {
            Error::new_spanned(
                &path,
                "Expected a multipart path. e.g. #[const(path::to::MyTrait::CONST_NAME)]",
            )
        })?;

        Ok(Self {
            const_name: const_name.into_value(),
            trait_path: path,
        })
    }
}

#[derive(Clone)]
/// Represent the placeholder `$` found inside an expr attribute's template
pub struct ExprPlaceHolder;

impl syn::parse::Parse for ExprPlaceHolder {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<syn::Token![$]>()?;
        Ok(Self)
    }
}

/// Kind of allowed placeholders in an `expr` attribute template
#[derive(Clone)]
enum Placeholder {
    ExprPlaceholder(ExprPlaceHolder),
}

#[derive(Clone)]
/// Tokens found in the expr attribute's template
/// Token are either
/// - a replacable pattern (placeholder)
/// - a normal token
/// - a group containing a recursive representation of template tokens
enum TemplateToken {
    Normal(TokenTree),
    Placeholder(Placeholder),
    Group(Delimiter, TemplateExpr),
}

impl TemplateToken {
    /// Replace relevant placeholder tokens with the provided tokens
    fn replace(&self, replacement: &TokenStream) -> TokenStream {
        match self {
            Self::Group(del, template) => {
                let replaced_tokens = template
                    .tokens
                    .iter()
                    .map(|token| token.replace(replacement));
                proc_macro2::Group::new(*del, quote::quote! { #(#replaced_tokens)* })
                    .to_token_stream()
            }
            Self::Normal(token_tree) => token_tree.to_token_stream(),
            Self::Placeholder(_) => replacement.clone(),
        }
    }
}

#[derive(Clone)]
/// An expr attribute's template
pub struct TemplateExpr {
    tokens: Vec<TemplateToken>,
}

impl syn::parse::Parse for TemplateExpr {
    /// Parsing a template means storing the raw template while differenciating
    /// placeholders and "normal" tokens
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut tokens = Vec::new();
        while !input.is_empty() {
            if input.fork().parse::<ExprPlaceHolder>().is_ok() {
                let placeholder = input.parse()?;
                tokens.push(TemplateToken::Placeholder(Placeholder::ExprPlaceholder(
                    placeholder,
                )));
                continue;
            }

            match input.parse()? {
                TokenTree::Group(group) => {
                    let inner_stream = group.stream();
                    let inner_expr = syn::parse2(inner_stream)?;
                    tokens.push(TemplateToken::Group(group.delimiter(), inner_expr));
                }
                other => {
                    tokens.push(TemplateToken::Normal(other));
                }
            }
        }

        Ok(TemplateExpr { tokens })
    }
}

impl TemplateExpr {
    /// returns the template after expanding the relevant placeholders
    pub fn expand_template(&self, replacement: &TokenStream) -> TokenStream {
        self.tokens.iter().fold(TokenStream::new(), |mut ts, tok| {
            ts.extend(tok.replace(replacement));
            ts
        })
    }
}

pub struct TraitTarget {
    type_path: TypePath,
}

impl syn::parse::Parse for TraitTarget {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let type_path: TypePath = input.parse().map_err(|error| {
            Error::new(
                input.span(),
                format!("{error}\nExpected trait path, e.g. #[through(foo::MyTrait)]"),
            )
        })?;

        Ok(TraitTarget { type_path })
    }
}

#[derive(Clone)]
pub enum ReturnExpression {
    Into(Option<TypePath>),
    TryInto,
    Unwrap,
}

pub enum TargetSpecifier {
    Field(GetFieldAttribute),
    Method(CallMethodAttribute),
}

impl TargetSpecifier {
    pub fn get_member(&self, default: &syn::Ident) -> syn::Member {
        match self {
            Self::Field(GetFieldAttribute {
                member: Some(member),
                ..
            }) => member.clone(),
            Self::Field(_) => default.clone().into(),
            Self::Method(method) => method.name.clone().into(),
        }
    }
}

enum ParsedAttribute {
    ReturnExpression(ReturnExpression),
    Await(bool),
    TargetSpecifier(TargetSpecifier),
    ThroughTrait(TraitTarget),
    ConstantAccess(AssociatedConstant),
    Expr(TemplateExpr),
}

fn parse_attributes(
    attrs: &[Attribute],
) -> (
    impl Iterator<Item = ParsedAttribute> + '_,
    impl Iterator<Item = &Attribute>,
) {
    let (parsed, other): (Vec<_>, Vec<_>) = attrs
        .iter()
        .map(|attribute| {
            let parsed = if let syn::AttrStyle::Outer = attribute.style {
                let name = attribute
                    .path()
                    .get_ident()
                    .map(|i| i.to_string())
                    .unwrap_or_default();
                match name.as_str() {
                    "call" => {
                        let target = attribute
                            .parse_args::<CallMethodAttribute>()
                            .expect("Cannot parse `call` attribute");
                        let spec = TargetSpecifier::Method(target);
                        Some(ParsedAttribute::TargetSpecifier(spec))
                    }
                    "field" => {
                        let target = if let syn::Meta::Path(_) = &attribute.meta {
                            GetFieldAttribute::default()
                        } else {
                            attribute
                                .parse_args::<GetFieldAttribute>()
                                .expect("Cannot parse `field` attribute")
                        };
                        let spec = TargetSpecifier::Field(target);
                        Some(ParsedAttribute::TargetSpecifier(spec))
                    }
                    "into" => {
                        let into = match &attribute.meta {
                            Meta::NameValue(_) => {
                                panic!("Cannot parse `into` attribute: expected parentheses")
                            }
                            Meta::Path(_) => IntoAttribute { type_path: None },
                            Meta::List(meta) => meta
                                .parse_args::<IntoAttribute>()
                                .expect("Cannot parse `into` attribute"),
                        };
                        Some(ParsedAttribute::ReturnExpression(ReturnExpression::Into(
                            into.type_path,
                        )))
                    }
                    "try_into" => {
                        if let Meta::List(meta) = &attribute.meta {
                            meta.parse_nested_meta(|meta| {
                                if meta.path.is_ident("unwrap") {
                                    panic!(
                                        "Replace #[try_into(unwrap)] with\n#[try_into]\n#[unwrap]",
                                    );
                                }
                                Ok(())
                            })
                            .expect("Invalid `try_into` arguments");
                        }
                        Some(ParsedAttribute::ReturnExpression(ReturnExpression::TryInto))
                    }
                    "unwrap" => Some(ParsedAttribute::ReturnExpression(ReturnExpression::Unwrap)),
                    "await" => {
                        let generate = attribute
                            .parse_args::<GenerateAwaitAttribute>()
                            .expect("Cannot parse `await` attribute");
                        Some(ParsedAttribute::Await(generate.literal.value))
                    }
                    "through" => Some(ParsedAttribute::ThroughTrait(
                        attribute
                            .parse_args::<TraitTarget>()
                            .expect("Cannot parse `through` attribute"),
                    )),
                    "const" => Some(ParsedAttribute::ConstantAccess(
                        attribute
                            .parse_args::<AssociatedConstant>()
                            .expect("Cannot parse `const` attribute"),
                    )),
                    "expr" => Some(ParsedAttribute::Expr(
                        attribute
                            .parse_args::<TemplateExpr>()
                            .expect("Cannot parse `expr` attribute"),
                    )),
                    _ => None,
                }
            } else {
                None
            };

            (parsed, attribute)
        })
        .partition(|(parsed, _)| parsed.is_some());
    (
        parsed.into_iter().map(|(parsed, _)| parsed.unwrap()),
        other.into_iter().map(|(_, attr)| attr),
    )
}

pub struct MethodAttributes<'a> {
    pub attributes: Vec<&'a Attribute>,
    pub target_specifier: Option<TargetSpecifier>,
    pub expressions: VecDeque<ReturnExpression>,
    pub generate_await: Option<bool>,
    pub target_trait: Option<TypePath>,
    pub associated_constant: Option<AssociatedConstant>,
    pub expr_attr: Option<TemplateExpr>,
}

/// Iterates through the attributes of a method and filters special attributes.
/// - call => sets the name of the target method to call
/// - into => generates a `into()` call after the delegated expression
/// - try_into => generates a `try_into()` call after the delegated expression
/// - await => generates an `.await` expression after the delegated expression
/// - unwrap => generates a `unwrap()` call after the delegated expression
/// - through => generates a UFCS call (`Target::method(&<expr>, ...)`) around the delegated expression
/// - const => generates a getter to a trait associated constant
pub fn parse_method_attributes<'a>(
    attrs: &'a [Attribute],
    method: &syn::TraitItemFn,
) -> MethodAttributes<'a> {
    let mut target_spec: Option<TargetSpecifier> = None;
    let mut expressions: Vec<ReturnExpression> = vec![];
    let mut generate_await: Option<bool> = None;
    let mut target_trait: Option<TraitTarget> = None;
    let mut associated_constant: Option<AssociatedConstant> = None;
    let mut expr_attr: Option<TemplateExpr> = None;

    let (parsed, other) = parse_attributes(attrs);
    for attr in parsed {
        match attr {
            ParsedAttribute::ReturnExpression(expr) => expressions.push(expr),
            ParsedAttribute::Await(value) => {
                if generate_await.is_some() {
                    panic!(
                        "Multiple `await` attributes specified for {}",
                        method.sig.ident
                    )
                }
                generate_await = Some(value);
            }
            ParsedAttribute::TargetSpecifier(spec) => {
                if target_spec.is_some() {
                    panic!(
                        "Multiple field/call attributes specified for {}",
                        method.sig.ident
                    )
                }
                target_spec = Some(spec);
            }
            ParsedAttribute::ThroughTrait(target) => {
                if target_trait.is_some() {
                    panic!(
                        "Multiple through attributes specified for {}",
                        method.sig.ident
                    )
                }
                target_trait = Some(target);
            }
            ParsedAttribute::ConstantAccess(const_attr) => {
                if associated_constant.is_some() {
                    panic!(
                        "Multiple const attributes specified for {}",
                        method.sig.ident
                    )
                }
                associated_constant = Some(const_attr);
            }
            ParsedAttribute::Expr(token_tree) => {
                if expr_attr.is_some() {
                    panic!(
                        "Multiple expr attributes specified for {}",
                        method.sig.ident
                    )
                }
                expr_attr = Some(token_tree);
            }
        }
    }

    if associated_constant.is_some() && target_spec.is_some() {
        panic!("Cannot use both `call`/`field` and `const` attributes.");
    }

    MethodAttributes {
        attributes: other.into_iter().collect(),
        target_specifier: target_spec,
        generate_await,
        expressions: expressions.into(),
        target_trait: target_trait.map(|t| t.type_path),
        associated_constant,
        expr_attr,
    }
}

pub struct SegmentAttributes {
    pub expressions: Vec<ReturnExpression>,
    pub generate_await: Option<bool>,
    pub target_trait: Option<TypePath>,
    pub other_attrs: Vec<Attribute>,
    pub expr_attr: Option<TemplateExpr>,
}

pub fn parse_segment_attributes(attrs: &[Attribute]) -> SegmentAttributes {
    let mut expressions: Vec<ReturnExpression> = vec![];
    let mut generate_await: Option<bool> = None;
    let mut target_trait: Option<TraitTarget> = None;
    let mut expr_attr: Option<TemplateExpr> = None;

    let (parsed, other) = parse_attributes(attrs);

    for attribute in parsed {
        match attribute {
            ParsedAttribute::ReturnExpression(expr) => expressions.push(expr),
            ParsedAttribute::Await(value) => {
                if generate_await.is_some() {
                    panic!("Multiple `await` attributes specified for segment");
                }
                generate_await = Some(value);
            }
            ParsedAttribute::ThroughTrait(target) => {
                if target_trait.is_some() {
                    panic!("Multiple `through` attributes specified for segment");
                }
                target_trait = Some(target);
            }
            ParsedAttribute::TargetSpecifier(_) => {
                panic!("Field/call attribute cannot be specified on a `to <expr>` segment.");
            }
            ParsedAttribute::ConstantAccess(_) => {
                panic!("Const attribute cannot be specified on a `to <expr>` segment.");
            }
            ParsedAttribute::Expr(token_tree) => {
                if expr_attr.is_some() {
                    panic!("Multiple `expr` attributes specified for segment");
                }
                expr_attr = Some(token_tree);
            }
        }
    }
    SegmentAttributes {
        expressions,
        generate_await,
        target_trait: target_trait.map(|t| t.type_path),
        other_attrs: other.cloned().collect::<Vec<_>>(),
        expr_attr,
    }
}

/// Applies default values from the segment and adds them to the method attributes.
pub fn combine_attributes<'a>(
    mut method_attrs: MethodAttributes<'a>,
    segment_attrs: &'a SegmentAttributes,
) -> MethodAttributes<'a> {
    let SegmentAttributes {
        expressions,
        generate_await,
        target_trait,
        other_attrs,
        expr_attr,
    } = segment_attrs;

    if method_attrs.generate_await.is_none() {
        method_attrs.generate_await = *generate_await;
    }

    if method_attrs.target_trait.is_none() {
        method_attrs.target_trait.clone_from(target_trait);
    }

    if method_attrs.expr_attr.is_none() {
        method_attrs.expr_attr.clone_from(expr_attr);
    }

    for expr in expressions {
        match expr {
            ReturnExpression::Into(path) => {
                if !method_attrs
                    .expressions
                    .iter()
                    .any(|expr| matches!(expr, ReturnExpression::Into(_)))
                {
                    method_attrs
                        .expressions
                        .push_front(ReturnExpression::Into(path.clone()));
                }
            }
            _ => method_attrs.expressions.push_front(expr.clone()),
        }
    }

    for other_attr in other_attrs {
        if !method_attrs
            .attributes
            .iter()
            .any(|attr| attr.path().get_ident() == other_attr.path().get_ident())
        {
            method_attrs.attributes.push(other_attr);
        }
    }

    method_attrs
}


================================================
FILE: src/lib.rs
================================================
//! This crate removes some boilerplate for structs that simply delegate
//! some of their methods to one or more of their fields.
//!
//! It gives you the `delegate!` macro, which delegates method calls to selected expressions (usually inner fields).
//!
//! ## Features:
//! - Delegate to a method with a different name
//! ```rust
//! use delegate::delegate;
//!
//! struct Stack { inner: Vec<u32> }
//! impl Stack {
//!     delegate! {
//!         to self.inner {
//!             #[call(push)]
//!             pub fn add(&mut self, value: u32);
//!         }
//!     }
//! }
//! ```
//! - Use an arbitrary inner field expression
//! ```rust
//! use delegate::delegate;
//!
//! use std::rc::Rc;
//! use std::cell::RefCell;
//! use std::ops::Deref;
//!
//! struct Wrapper { inner: Rc<RefCell<Vec<u32>>> }
//! impl Wrapper {
//!     delegate! {
//!         to self.inner.deref().borrow_mut() {
//!             pub fn push(&mut self, val: u32);
//!         }
//!     }
//! }
//! ```
//!
//! - Delegate to enum variants
//!
//! ```rust
//! use delegate::delegate;
//!
//! enum Enum {
//!     A(A),
//!     B(B),
//!     C { v: C },
//! }
//!
//! struct A {
//!     val: usize,
//! }
//!
//! impl A {
//!     fn dbg_inner(&self) -> usize {
//!         dbg!(self.val);
//!         1
//!     }
//! }
//! struct B {
//!     val_a: String,
//! }
//!
//! impl B {
//!     fn dbg_inner(&self) -> usize {
//!         dbg!(self.val_a.clone());
//!         2
//!     }
//! }
//!
//! struct C {
//!     val_c: f64,
//! }
//!
//! impl C {
//!     fn dbg_inner(&self) -> usize {
//!         dbg!(self.val_c);
//!         3
//!     }
//! }
//!
//! impl Enum {
//!     delegate! {
//!         // transformed to
//!         //
//!         // ```rust
//!         // match self {
//!         //     Enum::A(a) => a.dbg_inner(),
//!         //     Enum::B(b) => { println!("i am b"); b }.dbg_inner(),
//!         //     Enum::C { v: c } => { c }.dbg_inner(),
//!         // }
//!         // ```
//!         to match self {
//!             Enum::A(a) => a,
//!             Enum::B(b) => { println!("i am b"); b },
//!             Enum::C { v: c } => { c },
//!         } {
//!             fn dbg_inner(&self) -> usize;
//!         }
//!     }
//! }
//! ```
//!
//! - Use modifiers that alter the generated method body
//! ```rust
//! use delegate::delegate;
//! struct Inner;
//! impl Inner {
//!     pub fn method(&self, num: u32) -> u32 { num }
//!     pub fn method_res(&self, num: u32) -> Result<u32, ()> { Ok(num) }
//! }
//! struct Wrapper { inner: Inner }
//! impl Wrapper {
//!     delegate! {
//!         to self.inner {
//!             // calls method, converts result to u64 using `From`
//!             #[into]
//!             pub fn method(&self, num: u32) -> u64;
//!
//!             // calls method, returns ()
//!             #[call(method)]
//!             pub fn method_noreturn(&self, num: u32);
//!
//!             // calls method, converts result to i6 using `TryFrom`
//!             #[try_into]
//!             #[call(method)]
//!             pub fn method2(&self, num: u32) -> Result<u16, std::num::TryFromIntError>;
//!
//!             // calls method_res, unwraps the result
//!             #[unwrap]
//!             pub fn method_res(&self, num: u32) -> u32;
//!
//!             // calls method_res, unwraps the result, then calls into
//!             #[unwrap]
//!             #[into]
//!             #[call(method_res)]
//!             pub fn method_res_into(&self, num: u32) -> u64;
//!
//!             // specify explicit type for into
//!             #[into(u64)]
//!             #[call(method)]
//!             pub fn method_into_explicit(&self, num: u32) -> u64;
//!         }
//!     }
//! }
//! ```
//!
//! - Custom called expression
//!
//! The `#[expr()]` attribute can be used to modify the delegated call. You can use the `$` sigil as a placeholder for what delegate would normally expand to, and wrap that expression with custom code.
//!
//! _Note:_ the `$` placeholder isn't required and can be present multiple times if you want.
//!
//! ```rs
//! struct A(Vec<u8>);
//!
//! impl A {
//!     delegate! {
//!         to self.0 {
//!             #[expr(*$.unwrap())]
//!             /// Here `$` == `self.0.get(idx)`
//!             /// Will expand to `*self.0.get(idx).unwrap()`
//!             fn get(&self, idx: usize) -> u8;
//!
//!             #[call(get)]
//!             #[expr($?.checked_pow(2))]
//!             /// Here `$` == `self.0.get(idx)`
//!             /// Will expand to `self.0.get(idx)?.checked_pow(2)`
//!             fn get_checked_pow_2(&self, idx: usize) -> Option<u8>;
//!         }
//!     }
//! }
//! ```
//!
//! - Call `await` on async functions
//! ```rust
//! use delegate::delegate;
//!
//! struct Inner;
//! impl Inner {
//!     pub async fn method(&self, num: u32) -> u32 { num }
//! }
//! struct Wrapper { inner: Inner }
//! impl Wrapper {
//!     delegate! {
//!         to self.inner {
//!             // calls method(num).await, returns impl Future<Output = u32>
//!             pub async fn method(&self, num: u32) -> u32;
//!
//!             // calls method(num).await.into(), returns impl Future<Output = u64>
//!             #[into]
//!             #[call(method)]
//!             pub async fn method_into(&self, num: u32) -> u64;
//!         }
//!     }
//! }
//! ```
//! You can use the `#[await(true/false)]` attribute on delegated methods to specify if `.await` should
//! be generated after the delegated expression. It will be generated by default if the delegated
//! method is `async`.
//! - Delegate to multiple fields
//! ```rust
//! use delegate::delegate;
//!
//! struct MultiStack {
//!     left: Vec<u32>,
//!     right: Vec<u32>,
//! }
//! impl MultiStack {
//!     delegate! {
//!         to self.left {
//!             // Push an item to the top of the left stack
//!             #[call(push)]
//!             pub fn push_left(&mut self, value: u32);
//!         }
//!         to self.right {
//!             // Push an item to the top of the right stack
//!             #[call(push)]
//!             pub fn push_right(&mut self, value: u32);
//!         }
//!     }
//! }
//! ```
//! - Inserts `#[inline(always)]` automatically (unless you specify `#[inline]` manually on the method)
//! - You can use an attribute on a whole segment to automatically apply it to all methods in that
//!   segment:
//! ```rust
//! use delegate::delegate;
//!
//! struct Inner;
//!
//! impl Inner {
//!   fn foo(&self) -> Result<u32, ()> { Ok(0) }
//!   fn bar(&self) -> Result<u32, ()> { Ok(1) }
//! }
//!
//! struct Wrapper { inner: Inner }
//!
//! impl Wrapper {
//!   delegate! {
//!     #[unwrap]
//!     to self.inner {
//!       fn foo(&self) -> u32; // calls self.inner.foo().unwrap()
//!       fn bar(&self) -> u32; // calls self.inner.bar().unwrap()
//!     }
//!   }
//! }
//! ```
//! - Specify expressions in the signature that will be used as delegated arguments
//! ```rust
//! use delegate::delegate;
//! struct Inner;
//! impl Inner {
//!     pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 {
//!         a + x * x + b * y + c
//!     }
//! }
//! struct Wrapper { inner: Inner, a: i32, b: i32, c: i32 }
//! impl Wrapper {
//!     delegate! {
//!         to self.inner {
//!             // Calls `polynomial` on `inner` with `self.a`, `self.b` and
//!             // `self.c` passed as arguments `a`, `b`, and `c`, effectively
//!             // calling `polynomial(self.a, x, self.b, y, self.c)`.
//!             pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ;
//!             // Calls `polynomial` on `inner` with `0`s passed for arguments
//!             // `a` and `x`, and `self.b` and `self.c` for `b` and `c`,
//!             // effectively calling `polynomial(0, 0, self.b, y, self.c)`.
//!             #[call(polynomial)]
//!             pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ;
//!         }
//!     }
//! }
//! ```
//! - Modify how will an input parameter be passed to the delegated method with parameter attribute modifiers.
//!   Currently, the following modifiers are supported:
//!     - `#[into]`: Calls `.into()` on the parameter passed to the delegated method.
//!     - `#[as_ref]`: Calls `.as_ref()` on the parameter passed to the delegated method.
//!     - `#[newtype]`: Calls `.0` on the parameter passed to the delegated method.
//! ```rust
//! use delegate::delegate;
//!
//! struct InnerType {}
//! impl InnerType {
//!     fn foo(&self, other: Self) {}
//! }
//!
//! impl From<Wrapper> for InnerType {
//!     fn from(wrapper: Wrapper) -> Self {
//!         wrapper.0
//!     }
//! }
//!
//! struct Wrapper(InnerType);
//! impl Wrapper {
//!     delegate! {
//!         to self.0 {
//!             // Calls `self.0.foo(other.into());`
//!             pub fn foo(&self, #[into] other: Self);
//!         }
//!     }
//! }
//! ```
//! - Specify a trait through which will the delegated method be called
//!   (using [UFCS](https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls).
//! ```rust
//! use delegate::delegate;
//!
//! struct InnerType {}
//! impl InnerType {
//!     
//! }
//!
//! trait MyTrait {
//!   fn foo(&self);
//! }
//! impl MyTrait for InnerType {
//!   fn foo(&self) {}
//! }
//!
//! struct Wrapper(InnerType);
//! impl Wrapper {
//!     delegate! {
//!         to &self.0 {
//!             // Calls `MyTrait::foo(&self.0)`
//!             #[through(MyTrait)]
//!             pub fn foo(&self);
//!         }
//!     }
//! }
//! ```
//!
//! - Add additional arguments to method
//!
//!  ```rust
//!  use delegate::delegate;
//!  use std::cell::OnceCell;
//!  struct Inner(u32);
//!  impl Inner {
//!      pub fn new(m: u32) -> Self {
//!          // some "very complex" constructing work
//!          Self(m)
//!      }
//!      pub fn method(&self, n: u32) -> u32 {
//!          self.0 + n
//!      }
//!  }
//!  
//!  struct Wrapper {
//!      inner: OnceCell<Inner>,
//!  }
//!  
//!  impl Wrapper {
//!      pub fn new() -> Self {
//!          Self {
//!              inner: OnceCell::new(),
//!          }
//!      }
//!      fn content(&self, val: u32) -> &Inner {
//!          self.inner.get_or_init(|| Inner(val))
//!      }
//!      delegate! {
//!          to |k: u32| self.content(k) {
//!              // `wrapper.method(k, num)` will call `self.content(k).method(num)`
//!              pub fn method(&self, num: u32) -> u32;
//!          }
//!      }
//!  }
//!  ```
//! - Delegate associated functions
//!   ```rust
//!   use delegate::delegate;
//!
//!   struct A {}
//!   impl A {
//!       fn foo(a: u32) -> u32 {
//!           a + 1
//!       }
//!   }
//!
//!   struct B;
//!
//!   impl B {
//!       delegate! {
//!           to A {
//!               fn foo(a: u32) -> u32;
//!           }
//!       }
//!   }
//!
//!   assert_eq!(B::foo(1), 2);
//!   ```
//! - Delegate associated constants
//!
//! ```rust
//! use delegate::delegate;
//!
//! trait WithConst {
//!     const TOTO: u8;
//! }
//!
//! struct A;
//! impl WithConst for A {
//!     const TOTO: u8 = 1;
//! }
//!
//! struct B;
//! impl WithConst for B {
//!     const TOTO: u8 = 2;
//! }
//! struct C;
//! impl WithConst for C {
//!     const TOTO: u8 = 2;
//! }
//!
//! enum Enum {
//!     A(A),
//!     B(B),
//!     C(C),
//! }
//!
//! impl Enum {
//!     delegate! {
//!         to match self {
//!             Self::A(a) => a,
//!             Self::B(b) => b,
//!             Self::C(c) => { println!("hello from c"); c },
//!         } {
//!             #[const(WithConst::TOTO)]
//!             fn get_toto(&self) -> u8;
//!         }
//!     }
//! }
//!
//! assert_eq!(Enum::A(A).get_toto(), <A as WithConst>::TOTO);
//! ```
//!
//! - Delegate to fields
//! ```rust
//! use delegate::delegate;
//!
//! struct Datum {
//!     value: u32,
//!     error: u32,
//! }
//!
//! struct DatumWrapper(Datum);
//!
//! impl DatumWrapper {
//!     delegate! {
//!         to self.0 {
//!             /// Get the value of a nested field with the same name
//!             #[field]
//!             fn value(&self) -> u32;
//!
//!             /// Get the value of a nested field with a different name
//!             #[field(value)]
//!             fn renamed_value(&self) -> u32;
//!
//!             /// Get shared reference to a nested field
//!             #[field(&value)]
//!             fn value_ref(&self) -> &u32;
//!
//!             /// Get mutable reference to a nested field
//!             #[field(&mut value)]
//!             fn value_ref_mut(&mut self) -> &mut u32;
//!
//!             /// Get mutable reference to a nested field with the same name
//!             #[field(&)]
//!             fn error(&self) -> &u32;
//!         }
//!     }
//! }
//! ```

extern crate proc_macro;
use std::mem;

use attributes::AssociatedConstant;
use proc_macro::TokenStream;

use proc_macro2::Ident;
use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::visit_mut::VisitMut;
use syn::{parse_quote, Error, Expr, ExprField, ExprMethodCall, FnArg, GenericParam, Meta};

use crate::attributes::{
    combine_attributes, parse_method_attributes, parse_segment_attributes, ReturnExpression,
    SegmentAttributes, TargetSpecifier,
};

mod attributes;

mod kw {
    syn::custom_keyword!(to);
    syn::custom_keyword!(target);
}

#[derive(Clone)]
enum ArgumentModifier {
    Into,
    AsRef,
    Newtype,
}

#[derive(Clone)]
enum DelegatedInput {
    Input {
        parameter: syn::FnArg,
        modifier: Option<ArgumentModifier>,
    },
    Argument(syn::Expr),
}

fn get_argument_modifier(attribute: syn::Attribute) -> Result<ArgumentModifier, Error> {
    if let Meta::Path(mut path) = attribute.meta {
        if path.segments.len() == 1 {
            let segment = path.segments.pop().unwrap();
            if segment.value().arguments.is_empty() {
                let ident = segment.value().ident.to_string();
                let ident = ident.as_str();

                match ident {
                    "into" => return Ok(ArgumentModifier::Into),
                    "as_ref" => return Ok(ArgumentModifier::AsRef),
                    "newtype" => return Ok(ArgumentModifier::Newtype),
                    _ => (),
                }
            }
        }
    };

    panic!("The attribute argument has to be `into` or `as_ref`, like this: `#[into] a: u32`.")
}

impl syn::parse::Parse for DelegatedInput {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let lookahead = input.lookahead1();
        if lookahead.peek(syn::token::Bracket) {
            let content;
            let _bracket_token = syn::bracketed!(content in input);
            let expression: syn::Expr = content.parse()?;
            Ok(Self::Argument(expression))
        } else {
            let (input, modifier) = if lookahead.peek(syn::token::Pound) {
                let mut attributes = input.call(tolerant_outer_attributes)?;
                if attributes.len() > 1 {
                    panic!("You can specify at most a single attribute for each parameter in a delegated method");
                }
                let modifier = get_argument_modifier(attributes.pop().unwrap())
                    .expect("Could not parse argument modifier attribute");

                let input: syn::FnArg = input.parse()?;
                (input, Some(modifier))
            } else {
                (input.parse()?, None)
            };

            Ok(Self::Input {
                parameter: input,
                modifier,
            })
        }
    }
}

struct DelegatedMethod {
    method: syn::TraitItemFn,
    attributes: Vec<syn::Attribute>,
    visibility: syn::Visibility,
    arguments: syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>,
}

// Given an input parameter from a function signature, create a function
// argument used to call the delegate function: omit receiver, extract an
// identifier from a typed input parameter (and wrap it in an `Expr`).
fn parse_input_into_argument_expression(
    function_name: &Ident,
    input: &syn::FnArg,
) -> Option<syn::Expr> {
    match input {
        // Parse inputs of the form `x: T` to retrieve their identifiers.
        syn::FnArg::Typed(typed) => {
            match &*typed.pat {
                // This should not happen, I think. If it does,
                // it will be ignored as if it were the
                // receiver.
                syn::Pat::Ident(ident) if ident.ident == "self" => None,
                // Expression in the form `x: T`. Extract the
                // identifier, wrap it in Expr for type compatibility with bracketed expressions,
                // and append it
                // to the argument list.
                syn::Pat::Ident(ident) => {
                    let path_segment = syn::PathSegment {
                        ident: ident.ident.clone(),
                        arguments: syn::PathArguments::None,
                    };
                    let mut segments = syn::punctuated::Punctuated::new();
                    segments.push(path_segment);
                    let path = syn::Path {
                        leading_colon: None,
                        segments,
                    };
                    let ident_as_expr = syn::Expr::from(syn::ExprPath {
                        attrs: Vec::new(),
                        qself: None,
                        path,
                    });
                    Some(ident_as_expr)
                }
                // Other more complex argument expressions are not covered.
                _ => panic!(
                    "You have to use simple identifiers for delegated method parameters ({})",
                    function_name // The signature is not constructed yet. We make due.
                ),
            }
        }
        // Skip any `self`/`&self`/`&mut self` argument, since
        // it does not appear in the argument list and it's
        // already added to the parameter list.
        syn::FnArg::Receiver(_receiver) => None,
    }
}

impl syn::parse::Parse for DelegatedMethod {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let attributes = input.call(tolerant_outer_attributes)?;
        let visibility = input.call(syn::Visibility::parse)?;

        // Unchanged from Parse from TraitItemMethod
        let constness: Option<syn::Token![const]> = input.parse()?;
        let asyncness: Option<syn::Token![async]> = input.parse()?;
        let unsafety: Option<syn::Token![unsafe]> = input.parse()?;
        let abi: Option<syn::Abi> = input.parse()?;
        let fn_token: syn::Token![fn] = input.parse()?;
        let ident: Ident = input.parse()?;
        let generics: syn::Generics = input.parse()?;

        let content;
        let paren_token = syn::parenthesized!(content in input);

        // Parse inputs (method parameters) and arguments. The parameters
        // constitute the parameter list of the signature of the delegating
        // method so it must include all inputs, except bracketed expressions.
        // The argument list constitutes the list of arguments used to call the
        // delegated function. It must include all inputs, excluding the
        // receiver (self-type) input. The arguments must all be parsed to
        // retrieve the expressions inside of the brackets as well as variable
        // identifiers of ordinary inputs. The arguments must preserve the order
        // of the inputs.
        let delegated_inputs = content.parse_terminated(DelegatedInput::parse, syn::Token![,])?;
        let mut inputs: syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]> =
            syn::punctuated::Punctuated::new();
        let mut arguments: syn::punctuated::Punctuated<syn::Expr, syn::Token![,]> =
            syn::punctuated::Punctuated::new();

        // First, combine the cases for pairs with cases for end, to remove
        // redundancy below.
        delegated_inputs
            .into_pairs()
            .map(|punctuated_pair| match punctuated_pair {
                syn::punctuated::Pair::Punctuated(item, comma) => (item, Some(comma)),
                syn::punctuated::Pair::End(item) => (item, None),
            })
            .for_each(|pair| match pair {
                // This input is a bracketed argument (eg. `[ self.x ]`). It
                // is omitted in the signature of the delegator, but the
                // expression inside the brackets is used in the body of the
                // delegator, as an arugnment to the delegated function (eg.
                // `self.x`). The argument needs to be generated in the
                // appropriate position with respect other arguments and non-
                // argument inputs. As long as inputs are added to the
                // `arguments` vector in order of occurance, this is trivial.
                (DelegatedInput::Argument(argument), maybe_comma) => {
                    arguments.push_value(argument);
                    if let Some(comma) = maybe_comma {
                        arguments.push_punct(comma)
                    }
                }
                // The input is a standard function parameter with a name and
                // a type (eg. `x: T`). This input needs to be reflected in
                // the delegator signature as is (eg. `x: T`). The identifier
                // also needs to be included in the argument list in part
                // (eg. `x`). The argument list needs to preserve the order of
                // the inputs with relation to arguments (see above), so the
                // parsing is best done here (previously it was done at
                // generation).
                (
                    DelegatedInput::Input {
                        parameter,
                        modifier,
                    },
                    maybe_comma,
                ) => {
                    inputs.push_value(parameter.clone());
                    if let Some(comma) = maybe_comma {
                        inputs.push_punct(comma);
                    }
                    let maybe_argument = parse_input_into_argument_expression(&ident, &parameter);
                    if let Some(mut argument) = maybe_argument {
                        let span = argument.span();

                        if let Some(modifier) = modifier {
                            let method_call = |name: &str| {
                                syn::Expr::from(ExprMethodCall {
                                    attrs: vec![],
                                    receiver: Box::new(argument.clone()),
                                    dot_token: Default::default(),
                                    method: Ident::new(name, span),
                                    turbofish: None,
                                    paren_token,
                                    args: Default::default(),
                                })
                            };

                            let field_call = || {
                                syn::Expr::from(ExprField {
                                    attrs: vec![],
                                    base: Box::new(argument.clone()),
                                    dot_token: Default::default(),
                                    member: syn::Member::Unnamed(0.into()),
                                })
                            };

                            match modifier {
                                ArgumentModifier::Into => {
                                    argument = method_call("into");
                                }
                                ArgumentModifier::AsRef => {
                                    argument = method_call("as_ref");
                                }
                                ArgumentModifier::Newtype => argument = field_call(),
                            }
                        }

                        arguments.push(argument);
                        if let Some(comma) = maybe_comma {
                            arguments.push_punct(comma);
                        }
                    }
                }
            });

        // Unchanged from Parse from TraitItemMethod
        let output: syn::ReturnType = input.parse()?;
        let where_clause: Option<syn::WhereClause> = input.parse()?;

        // This needs to be generated manually, because inputs need to be
        // separated into actual inputs that go in the signature (the
        // parameters) and the additional expressions in square brackets which
        // go into the arguments vector (artguments of the call on the method
        // on the inner object).
        let signature = syn::Signature {
            constness,
            asyncness,
            unsafety,
            abi,
            fn_token,
            ident,
            paren_token,
            inputs,
            output,
            variadic: None,
            generics: syn::Generics {
                where_clause,
                ..generics
            },
        };

        // Check if the input contains a semicolon or a brace. If it contains
        // a semicolon, we parse it (to retain token location information) and
        // continue. However, if it contains a brace, this indicates that
        // there is a default definition of the method. This is not supported,
        // so in that case we error out.
        let lookahead = input.lookahead1();
        let semi_token: Option<syn::Token![;]> = if lookahead.peek(syn::Token![;]) {
            Some(input.parse()?)
        } else {
            panic!(
                "Do not include implementation of delegated functions ({})",
                signature.ident
            );
        };

        // This needs to be populated from scratch because of the signature above.
        let method = syn::TraitItemFn {
            // All attributes are attached to `DelegatedMethod`, since they
            // presumably pertain to the process of delegation, not the
            // signature of the delegator.
            attrs: Vec::new(),
            sig: signature,
            default: None,
            semi_token,
        };

        Ok(DelegatedMethod {
            method,
            attributes,
            visibility,
            arguments,
        })
    }
}

struct DelegatedSegment {
    delegator: syn::Expr,
    methods: Vec<DelegatedMethod>,
    segment_attrs: SegmentAttributes,
}

impl syn::parse::Parse for DelegatedSegment {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let attributes = input.call(tolerant_outer_attributes)?;
        let segment_attrs = parse_segment_attributes(&attributes);

        if let Ok(keyword) = input.parse::<kw::target>() {
            return Err(Error::new(keyword.span(), "You are using the old `target` expression, which is deprecated. Please replace `target` with `to`."));
        } else {
            input.parse::<kw::to>()?;
        }

        syn::Expr::parse_without_eager_brace(input).and_then(|delegator| {
            let content;
            syn::braced!(content in input);

            let mut methods = vec![];
            while !content.is_empty() {
                methods.push(
                    content
                        .parse::<DelegatedMethod>()
                        .expect("Cannot parse delegated method"),
                );
            }

            Ok(DelegatedSegment {
                delegator,
                methods,
                segment_attrs,
            })
        })
    }
}

struct DelegationBlock {
    segments: Vec<DelegatedSegment>,
}

impl syn::parse::Parse for DelegationBlock {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let mut segments = vec![];
        while !input.is_empty() {
            segments.push(input.parse()?);
        }

        Ok(DelegationBlock { segments })
    }
}

/// Returns true if there are any `inline` attributes in the input.
fn has_inline_attribute(attrs: &[&syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        if let syn::AttrStyle::Outer = attr.style {
            attr.path().is_ident("inline")
        } else {
            false
        }
    })
}

struct MatchVisitor<F>(F);

impl<F: Fn(&Expr) -> proc_macro2::TokenStream> VisitMut for MatchVisitor<F> {
    fn visit_arm_mut(&mut self, arm: &mut syn::Arm) {
        let transformed = self.0(&arm.body);
        arm.body = parse_quote!(#transformed);
    }
}

#[proc_macro]
pub fn delegate(tokens: TokenStream) -> TokenStream {
    let block: DelegationBlock = syn::parse_macro_input!(tokens);
    let sections = block.segments.iter().map(|delegator| {
        let delegated_expr = &delegator.delegator;
        let functions = delegator.methods.iter().map(|method| {
            let input = &method.method;
            let mut signature = input.sig.clone();
            if let Expr::Closure(closure) = delegated_expr {
                let additional_inputs: Vec<FnArg> = closure
                    .inputs
                    .iter()
                    .map(|input| {
                        if let syn::Pat::Type(pat_type) = input {
                            syn::parse_quote!(#pat_type)
                        } else {
                            panic!(
                                "Use a type pattern (`a: u32`) for delegation closure arguments"
                            );
                        }
                    })
                    .collect();
                let mut origin_inputs = mem::take(&mut signature.inputs).into_iter();
                // When delegating methods, `first_input` should be self or similar receivers
                // Then we need to move it to first
                // When delegating associated methods, it may be a trivial argument or does not even exist
                // We just keep the origin order.
                let first_input = origin_inputs.next();
                match first_input {
                    Some(FnArg::Receiver(receiver)) => {
                        signature.inputs.push(FnArg::Receiver(receiver));
                        signature.inputs.extend(additional_inputs);
                    }
                    Some(first_input) => {
                        signature.inputs.extend(additional_inputs);
                        signature.inputs.push(first_input);
                    }
                    _ => {
                        signature.inputs.extend(additional_inputs);
                    }
                }
                signature.inputs.extend(origin_inputs);
            }
            let attributes = parse_method_attributes(&method.attributes, input);
            let attributes = combine_attributes(attributes, &delegator.segment_attrs);
            if input.default.is_some() {
                panic!(
                    "Do not include implementation of delegated functions ({})",
                    signature.ident
                );
            }

            // Generate an argument vector from Punctuated list.
            let args: Vec<Expr> = method.arguments.clone().into_iter().collect();

            // Get name (or index) of the target method or field
            let name = match &attributes.target_specifier {
                Some(target) => target.get_member(&input.sig.ident),
                None => input.sig.ident.clone().into(),
            };

            let inline = if has_inline_attribute(&attributes.attributes) {
                quote!()
            } else {
                quote! { #[inline] }
            };
            let visibility = &method.visibility;

            let is_method = method.method.sig.receiver().is_some();
            let associated_const = &attributes.associated_constant;
            let expr_attr = &attributes.expr_attr;

            // Use the body of a closure (like `|k: u32| <body>`) as the delegation expression
            let delegated_body = if let Expr::Closure(closure) = delegated_expr {
                &closure.body
            } else {
                delegated_expr
            };

            let span = input.span();
            let generate_await = attributes
                .generate_await
                .unwrap_or_else(|| method.method.sig.asyncness.is_some());

            // fn method<'a, A, B> -> method::<A, B>
            let generic_params = &method.method.sig.generics.params;
            let generics = if generic_params.is_empty() {
                quote::quote! {}
            } else {
                let span = generic_params.span();
                let mut params: syn::punctuated::Punctuated<
                    proc_macro2::TokenStream,
                    syn::Token![,],
                > = syn::punctuated::Punctuated::new();
                for param in generic_params.iter() {
                    let token = match param {
                        GenericParam::Lifetime(_) => {
                            // Do not pass lifetimes to generic arguments explicitly to avoid
                            // things like https://doc.rust-lang.org/error_codes/E0794.html
                            // See https://github.com/Kobzol/rust-delegate/issues/85.
                            continue;
                        }
                        GenericParam::Type(t) => {
                            let token = &t.ident;
                            let span = t.span();
                            quote::quote_spanned! {span=> #token }
                        }
                        GenericParam::Const(c) => {
                            let token = &c.ident;
                            let span = c.span();
                            quote::quote_spanned! {span=> #token }
                        }
                    };
                    params.push(token);
                }
                quote::quote_spanned! {span=> ::<#params> }
            };

            let modify_expr = |expr: &Expr| {
                let body = if let Some(target_trait) = &attributes.target_trait {
                    quote::quote! { #target_trait::#name#generics(#expr, #(#args),*) }
                } else if let Some(AssociatedConstant {
                    const_name,
                    trait_path,
                }) = associated_const
                {
                    let return_type = &signature.output;
                    quote::quote! {{
                        const fn get_const<T: #trait_path>(t: &T) #return_type {
                            <T as #trait_path>::#const_name
                        }
                        get_const(#expr)
                    }}
                } else if is_method {
                    match &attributes.target_specifier {
                        None | Some(TargetSpecifier::Method(_)) => {
                            quote::quote! { #expr.#name#generics(#(#args),*) }
                        }
                        Some(TargetSpecifier::Field(target)) => {
                            let reference = target.reference_tokens();
                            quote::quote! { #reference#expr.#name }
                        }
                    }
                } else {
                    quote::quote! { #expr::#name#generics(#(#args),*) }
                };

                let mut body = if generate_await {
                    quote::quote! { #body.await }
                } else {
                    body
                };

                for expression in &attributes.expressions {
                    match expression {
                        ReturnExpression::Into(type_name) => {
                            body = match type_name {
                                Some(name) => {
                                    quote::quote! { ::core::convert::Into::<#name>::into(#body) }
                                }
                                None => quote::quote! { ::core::convert::Into::into(#body) },
                            };
                        }
                        ReturnExpression::TryInto => {
                            body = quote::quote! { ::core::convert::TryInto::try_into(#body) };
                        }
                        ReturnExpression::Unwrap => {
                            body = quote::quote! { #body.unwrap() };
                        }
                    }
                }
                body
            };
            let mut body = if let Expr::Match(expr_match) = delegated_body {
                let mut expr_match = expr_match.clone();
                MatchVisitor(modify_expr).visit_expr_match_mut(&mut expr_match);
                expr_match.into_token_stream()
            } else {
                modify_expr(delegated_body)
            };

            if let syn::ReturnType::Default = &signature.output {
                body = quote::quote! { #body; };
            };

            if let Some(expr_template) = expr_attr {
                body = expr_template.expand_template(&body);
            }

            let attrs = &attributes.attributes;
            quote::quote_spanned! {span=>
                #(#attrs)*
                #inline
                #visibility #signature {
                    #body
                }
            }
        });

        quote! { #(#functions)* }
    });

    let result = quote! {
        #(#sections)*
    };
    result.into()
}

// we cannot use `Attributes::parse_outer` directly, because it does not allow keywords to appear
// in meta path positions, i.e., it does not accept `#[await(true)]`.
// related issue: https://github.com/dtolnay/syn/issues/1458
fn tolerant_outer_attributes(input: ParseStream) -> syn::Result<Vec<syn::Attribute>> {
    use proc_macro2::{Delimiter, TokenTree};
    use syn::{
        bracketed,
        ext::IdentExt,
        parse::discouraged::Speculative,
        token::{Brace, Bracket, Paren},
        AttrStyle, Attribute, ExprLit, Lit, MacroDelimiter, MetaList, MetaNameValue, Path, Result,
        Token,
    };

    fn tolerant_attr(input: ParseStream) -> Result<Attribute> {
        let content;
        Ok(Attribute {
            pound_token: input.parse()?,
            style: AttrStyle::Outer,
            bracket_token: bracketed!(content in input),
            meta: content.call(tolerant_meta)?,
        })
    }

    // adapted from `impl Parse for Meta`
    fn tolerant_meta(input: ParseStream) -> Result<Meta> {
        // Try to parse as Meta
        if let Ok(meta) = input.call(Meta::parse) {
            Ok(meta)
        } else {
            // If it's not possible, try to parse it as any identifier, to support #[await]
            let path = Path::from(input.call(Ident::parse_any)?);
            if input.peek(Paren) || input.peek(Bracket) || input.peek(Brace) {
                // adapted from the private `syn::attr::parse_meta_after_path`
                input.step(|cursor| {
                    if let Some((TokenTree::Group(g), rest)) = cursor.token_tree() {
                        let span = g.delim_span();
                        let delimiter = match g.delimiter() {
                            Delimiter::Parenthesis => MacroDelimiter::Paren(Paren(span)),
                            Delimiter::Brace => MacroDelimiter::Brace(Brace(span)),
                            Delimiter::Bracket => MacroDelimiter::Bracket(Bracket(span)),
                            Delimiter::None => {
                                return Err(cursor.error("expected delimiter"));
                            }
                        };
                        Ok((
                            Meta::List(MetaList {
                                path,
                                delimiter,
                                tokens: g.stream(),
                            }),
                            rest,
                        ))
                    } else {
                        Err(cursor.error("expected delimiter"))
                    }
                })
            } else if input.peek(Token![=]) {
                // adapted from the private `syn::attr::parse_meta_name_value_after_path`
                let eq_token = input.parse()?;
                let ahead = input.fork();
                let value = match ahead.parse::<Option<Lit>>()? {
                    // this branch is probably for speeding up the parsing for doc comments etc.
                    Some(lit) if ahead.is_empty() => {
                        input.advance_to(&ahead);
                        Expr::Lit(ExprLit {
                            attrs: Vec::new(),
                            lit,
                        })
                    }
                    _ => input.parse()?,
                };
                Ok(Meta::NameValue(MetaNameValue {
                    path,
                    eq_token,
                    value,
                }))
            } else {
                Ok(Meta::Path(path))
            }
        }
    }

    let mut attrs = Vec::new();
    while input.peek(Token![#]) {
        attrs.push(input.call(tolerant_attr)?);
    }
    Ok(attrs)
}


================================================
FILE: tests/argument_modifier.rs
================================================
use delegate::delegate;

struct MyNewU32(u32);

trait Foo {
    fn bar(&self, x: Self);
}

impl Foo for u32 {
    fn bar(&self, x: Self) {}
}

impl From<MyNewU32> for u32 {
    fn from(value: MyNewU32) -> Self {
        value.0
    }
}

impl Foo for MyNewU32 {
    delegate! {
        to self.0 {
            fn bar(&self, #[into] x: Self);
        }
    }
}

struct Bar {
    foo: String,
}

impl<T> PartialEq<T> for Bar
where
    T: AsRef<str> + ?Sized,
{
    delegate! {
        to self.foo {
            fn eq(&self, #[as_ref] other: &T) -> bool;
        }
    }
}

struct Baz(Vec<u32>);

impl Baz {
    delegate! {
        to self.0 {
            fn extend(&mut self, #[newtype] other: Baz);
        }
    }
}


================================================
FILE: tests/associated_const_delegation.rs
================================================
extern crate delegate;
use delegate::delegate;

#[test]
fn test_delegate_constant() {
    trait WithConst {
        const TOTO: u8;
    }

    struct A;
    impl WithConst for A {
        const TOTO: u8 = 1;
    }

    struct B;
    impl WithConst for B {
        const TOTO: u8 = 2;
    }
    struct C;
    impl WithConst for C {
        const TOTO: u8 = 2;
    }

    enum Enum {
        A(A),
        B(B),
        C(C),
    }

    impl Enum {
        delegate! {
            to match self {
                Self::A(a) => a,
                Self::B(b) => b,
                Self::C(c) => { println!("hello from c"); c },
            } {
                #[const(WithConst::TOTO)]
                fn get_toto(&self) -> u8;
            }
        }
    }

    let a = Enum::A(A);
    assert_eq!(a.get_toto(), <A as WithConst>::TOTO);
    let b = Enum::B(B);
    assert_eq!(b.get_toto(), <B as WithConst>::TOTO);
    let c = Enum::C(C);
    assert_eq!(c.get_toto(), <C as WithConst>::TOTO);
}

#[test]
fn multiple_consts() {
    trait Foo {
        const A: u32;
        const B: u32;
    }

    struct A;
    impl Foo for A {
        const A: u32 = 1;
        const B: u32 = 2;
    }

    struct Wrapper(A);
    impl Wrapper {
        delegate! {
            to &self.0 {
                #[const(Foo::A)]
                fn a(&self) -> u32;

                #[const(Foo::B)]
                fn b(&self) -> u32;
            }
        }
    }

    let wrapper = Wrapper(A);
    assert_eq!(wrapper.a(), <A as Foo>::A);
    assert_eq!(wrapper.b(), <A as Foo>::B);
}


================================================
FILE: tests/async_await.rs
================================================
extern crate delegate;

use delegate::delegate;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

#[test]
fn test_async_await() {
    struct Inner;
    impl Inner {
        pub async fn method(&self, num: u32) -> u32 {
            num
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                pub(crate) async fn method(&self, num: u32) -> u32;

                #[call(method)]
                pub(crate) async fn unit(&self, num: u32);

                #[into]
                #[call(method)]
                pub(crate) async fn with_into(&self, num: u32) -> u64;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(::futures::executor::block_on(wrapper.method(3)), 3);
    assert_eq!(::futures::executor::block_on(wrapper.unit(3)), ());
    assert_eq!(::futures::executor::block_on(wrapper.with_into(3)), 3_u64);
}

#[test]
fn test_async_trait() {
    use async_trait::async_trait;

    #[async_trait]
    trait Inner {
        async fn method(&self, num: u32) -> u32;
    }

    struct InnerImpl;
    #[async_trait]
    impl Inner for InnerImpl {
        async fn method(&self, num: u32) -> u32 {
            num
        }
    }

    struct Wrapper<T> {
        inner: T,
    }

    impl<T: Inner> Wrapper<T> {
        delegate! {
            to self.inner {
                pub(crate) async fn method(&self, num: u32) -> u32;

                #[call(method)]
                pub(crate) async fn unit(&self, num: u32);

                #[into]
                #[call(method)]
                pub(crate) async fn with_into(&self, num: u32) -> u64;
            }
        }
    }

    let wrapper = Wrapper { inner: InnerImpl };

    assert_eq!(::futures::executor::block_on(wrapper.method(3)), 3);
    assert_eq!(::futures::executor::block_on(wrapper.unit(3)), ());
    assert_eq!(::futures::executor::block_on(wrapper.with_into(3)), 3_u64);
}

#[test]
fn test_bridge_async_to_sync() {
    struct UserRepo;
    impl UserRepo {
        fn foo(&self) {}
    }

    struct SharedRepo(tokio::sync::Mutex<UserRepo>);

    impl SharedRepo {
        delegate! {
            to self.0.lock().await {
                #[await(false)]
                async fn foo(&self);
            }
        }
    }
}

#[test]
fn test_bridge_sync_to_async() {
    struct Fut;
    impl Future for Fut {
        type Output = u32;

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            todo!()
        }
    }

    struct UserRepo;
    impl UserRepo {
        fn foo(&self) -> Fut {
            Fut
        }
    }

    struct SharedRepo(UserRepo);

    impl SharedRepo {
        delegate! {
            to self.0 {
                #[await(true)]
                async fn foo(&self) -> u32;
            }
        }
    }
}


================================================
FILE: tests/closure.rs
================================================
use delegate::delegate;
use std::cell::OnceCell;

#[test]
fn test_delegate_closure() {
    struct Inner(u32);
    impl Inner {
        fn method(&self, n: u32) -> u32 {
            self.0 + n
        }

        fn method2(&self, n: u32) -> u32 {
            self.0 - n
        }
    }

    struct Wrapper {
        inner: OnceCell<Inner>,
    }

    impl Wrapper {
        pub fn new() -> Self {
            Self {
                inner: OnceCell::new(),
            }
        }
        fn content(&self, val: u32) -> &Inner {
            self.inner.get_or_init(|| Inner(val))
        }
        delegate! {
            to |k: u32| self.content(k) {
                pub fn method(&self, num: u32) -> u32;
                pub fn method2(&self, num: u32) -> u32;
            }
        }
    }

    let wrapper = Wrapper::new();
    assert_eq!(wrapper.method(1, 2), 3);
    assert_eq!(wrapper.method2(1, 1), 0);
    assert_eq!(wrapper.method(1, 3), 4);
    assert_eq!(wrapper.method2(1, 0), 1);
}

#[test]
fn test_delegate_closure_associated_function() {
    struct Inner;
    impl Inner {
        fn method(n: u32) -> u32 {
            n + 1
        }

        fn method2(n: u32) -> u32 {
            n - 1
        }
    }

    struct Wrapper;

    impl Wrapper {
        // Doesn't really make sense, but should compile
        delegate! {
            to |k: u32| Inner {
                pub fn method(num: u32) -> u32;
                pub fn method2(num: u32) -> u32;
            }
        }
    }

    assert_eq!(Wrapper::method(1, 2), 3);
    assert_eq!(Wrapper::method2(1, 1), 0);
    assert_eq!(Wrapper::method(1, 3), 4);
    assert_eq!(Wrapper::method(1, 0), 1);
}


================================================
FILE: tests/delegate_to_enum.rs
================================================
use delegate::delegate;

enum Enum {
    A(A),
    B(B),
    C { v: C },
}

struct A {
    val: usize,
}

impl A {
    fn dbg_inner(&self) -> usize {
        dbg!(self.val);
        1
    }

    fn into_num(&self) -> u8 {
        1
    }
}
struct B {
    val_a: String,
}

impl B {
    fn dbg_inner(&self) -> usize {
        dbg!(self.val_a.clone());
        2
    }

    fn into_num(&self) -> u64 {
        2
    }
}

struct C {
    val_c: f64,
}

impl C {
    fn dbg_inner(&self) -> usize {
        dbg!(self.val_c);
        3
    }

    fn into_num(&self) -> usize {
        3
    }
}

impl Enum {
    delegate! {
        to match self {
            Enum::A(a) => a,
            Enum::B(b) => { println!("i am b"); b },
            Enum::C { v: c } => { c },
        } {
            fn dbg_inner(&self) -> usize;

            #[into]
            fn into_num(&self) -> IntoUsize;
        }
    }
}

#[derive(Eq, PartialEq, Debug)]
struct IntoUsize(usize);

impl From<usize> for IntoUsize {
    fn from(value: usize) -> Self {
        Self(value)
    }
}
impl From<u64> for IntoUsize {
    fn from(value: u64) -> Self {
        Self(value as usize)
    }
}
impl From<u8> for IntoUsize {
    fn from(value: u8) -> Self {
        Self(value as usize)
    }
}

#[test]
fn test_delegate_enum_method() {
    let a = Enum::A(A { val: 1 });
    assert_eq!(a.dbg_inner(), 1);
    let b = Enum::B(B {
        val_a: "a".to_string(),
    });
    assert_eq!(b.dbg_inner(), 2);
    let c = Enum::C {
        v: C { val_c: 1.0 },
    };
    assert_eq!(c.dbg_inner(), 3);
}

#[test]
fn test_delegate_enum_into() {
    let a = Enum::A(A { val: 1 });
    assert_eq!(a.into_num(), IntoUsize(1));
    let b = Enum::B(B {
        val_a: "".to_string(),
    });
    assert_eq!(b.into_num(), IntoUsize(2));
    let c = Enum::C {
        v: C { val_c: 0.0 },
    };
    assert_eq!(c.into_num(), IntoUsize(3));
}


================================================
FILE: tests/delegation.rs
================================================
use delegate::delegate;

#[test]
fn test_expansions() {
    macrotest::expand("tests/expand/*.rs");
}

#[test]
fn test_delegation() {
    struct Inner;

    impl Inner {
        fn fun_generic<S: Copy>(self, s: S) -> S {
            s
        }
        fn fun1(self, a: u32, b: u32) -> u32 {
            a + b
        }
        fn fun2(mut self, a: u32, b: u32) -> u32 {
            a + b
        }
        fn fun3(&self, a: u32, b: u32) -> u32 {
            a + b
        }
        fn fun4(&mut self, a: u32, b: u32) -> u32 {
            a + b
        }
        fn fun5(self: Self, a: u32, b: u32) -> u32 {
            a + b
        }
        fn fun6(mut self: Self, a: u32, b: u32) -> u32 {
            a + b
        }
    }

    struct Outer {
        inner: Inner,
        inner2: Inner,
    }

    impl Outer {
        pub fn new() -> Outer {
            Outer {
                inner: Inner,
                inner2: Inner,
            }
        }

        delegate! {
            to self.inner {
                fn fun_generic<S: Copy>(self, s: S) -> S;
                fn fun1(self, a: u32, b: u32) -> u32;
                fn fun2(mut self, a: u32, b: u32) -> u32;
                fn fun3(&self, a: u32, b: u32) -> u32;
            }
            to self.inner2 {
                fn fun4(&mut self, a: u32, b: u32) -> u32;
                fn fun5(self: Self, a: u32, b: u32) -> u32;
                fn fun6(mut self: Self, a: u32, b: u32) -> u32;
            }
        }
    }

    assert_eq!(Outer::new().fun_generic(5), 5);
    assert_eq!(Outer::new().fun1(1, 2), 3);
    assert_eq!(Outer::new().fun2(1, 2), 3);
    assert_eq!(Outer::new().fun3(1, 2), 3);
    assert_eq!(Outer::new().fun4(1, 2), 3);
    assert_eq!(Outer::new().fun5(1, 2), 3);
    assert_eq!(Outer::new().fun6(1, 2), 3);
}

#[test]
fn test_delegate_self() {
    trait Foo {
        fn foo(&self) -> u32;
    }

    struct S;

    impl S {
        fn foo(&self) -> u32 {
            1
        }
    }

    impl Foo for S {
        delegate! {
            to self {
                fn foo(&self) -> u32;
            }
        }
    }

    let s = S;
    assert_eq!(Foo::foo(&s), 1);
}

#[test]
fn test_delegate_tuple() {
    trait Foo {
        fn foo(&self) -> u32;
    }

    struct S;
    impl S {
        fn foo(&self) -> u32 {
            1
        }
    }

    struct T(S);

    impl Foo for T {
        delegate! {
            to self.0 {
                fn foo(&self) -> u32;
            }
        }
    }

    let s = S;
    let t = T(s);
    assert_eq!(Foo::foo(&t), 1);
}


================================================
FILE: tests/expand/fields.expanded.rs
================================================
use delegate::delegate;
struct Datum {
    value: u32,
    error: u32,
    xy: (f32, f32),
}
struct DatumWrapper(Datum);
impl DatumWrapper {
    fn get_inner(&self) -> &Datum {
        &self.0
    }
    /// Expands to `self.0.value`
    #[inline]
    fn value(&self) -> u32 {
        self.0.value
    }
    /// Expands to `self.0.value`
    #[inline]
    fn renamed_value(&self) -> u32 {
        self.0.value
    }
    /// Expands to `&self.0.value`
    #[inline]
    fn renamed_value_ref(&self) -> &u32 {
        &self.0.value
    }
    /// Expands to `&mut self.0.value`
    #[inline]
    fn renamed_value_ref_mut(&mut self) -> &mut u32 {
        &mut self.0.value
    }
    /// Expands to `&self.0.error` (demonstrates `&` without a field name)
    #[inline]
    fn error(&self) -> &u32 {
        &self.0.error
    }
    /// Expands to `self.0.xy.0` (demonstrates unnamed field access by value)
    #[inline]
    fn x(&self) -> f32 {
        self.0.xy.0
    }
    /// Expands to `&self.0.xy.1` (demonstrates unnamed field access by reference)
    #[inline]
    fn y(&self) -> &f32 {
        &self.0.xy.1
    }
    /// Expands to `&self.get_inner().value`
    #[inline]
    fn value_ref_via_get_inner(&self) -> &u32 {
        &self.get_inner().value
    }
}


================================================
FILE: tests/expand/fields.rs
================================================

use delegate::delegate;

struct Datum {
    value: u32,
    error: u32,
    xy: (f32, f32)
}

struct DatumWrapper(Datum);

impl DatumWrapper {
    fn get_inner(&self) -> &Datum {
        &self.0
    }
    delegate! {
        to self.0 {
            /// Expands to `self.0.value`
            #[field]
            fn value(&self) -> u32;

            /// Expands to `self.0.value`
            #[field(value)]
            fn renamed_value(&self) -> u32;

            /// Expands to `&self.0.value`
            #[field(&value)]
            fn renamed_value_ref(&self) -> &u32;

            /// Expands to `&mut self.0.value`
            #[field(&mut value)]
            fn renamed_value_ref_mut(&mut self) -> &mut u32;

            /// Expands to `&self.0.error` (demonstrates `&` without a field name)
            #[field(&)]
            fn error(&self) -> &u32;
        }
        to self.0.xy {
            /// Expands to `self.0.xy.0` (demonstrates unnamed field access by value)
            #[field(0)]
            fn x(&self) -> f32;
            /// Expands to `&self.0.xy.1` (demonstrates unnamed field access by reference)
            #[field(&1)]
            fn y(&self) -> &f32;
        }
        to self.get_inner() {
            /// Expands to `&self.get_inner().value`
            #[field(&value)]
            fn value_ref_via_get_inner(&self) -> &u32;
        }
    }
}


================================================
FILE: tests/expr.rs
================================================
use delegate::delegate;
use std::sync::Mutex;

struct Inner;
impl Inner {
    pub fn method(&self, num: u32) -> u32 {
        num
    }
    pub fn method2(&self, num: u32) -> u32 {
        num
    }
}

struct Wrapper {
    inner: Mutex<Inner>,
}

fn global_fn() -> Inner {
    Inner
}

impl Wrapper {
    delegate! {
        to self.inner.lock().unwrap() {
            pub(crate) fn method(&self, num: u32) -> u32;
        }
        to global_fn() {
            pub(crate) fn method2(&self, num: u32) -> u32;
        }
    }
}

#[test]
fn test_mutex() {
    let wrapper = Wrapper {
        inner: Mutex::new(Inner),
    };

    assert_eq!(wrapper.method(3), 3);
    assert_eq!(wrapper.method2(3), 3);
}

#[test]
fn test_index() {
    struct Inner;
    impl Inner {
        pub fn method(&self, num: u32) -> u32 {
            num
        }
    }

    struct Wrapper {
        index: usize,
        items: Vec<Inner>,
    }

    impl Wrapper {
        delegate! {
            to self.items[self.index] {
                fn method(&self, num: u32) -> u32;
            }
        }
    }

    let wrapper = Wrapper {
        index: 0,
        items: vec![Inner],
    };

    assert_eq!(wrapper.method(3), 3);
}


================================================
FILE: tests/expr_attribute.rs
================================================
extern crate delegate;
use delegate::delegate;

#[test]
fn delegate_with_custom_expr() {
    struct A(Vec<u8>);

    impl A {
        delegate! {
            to self.0 {
                #[expr(*$.unwrap())]
                fn get(&self, idx: usize) -> u8;

                #[call(get)]
                #[expr($?.checked_pow(2))]
                fn get_checked_pow_2(&self, idx: usize) -> Option<u8>;
            }
        }
    }

    let a = A(vec![2, 3, 4, 5]);

    assert_eq!(a.get(0), 2);
    assert_eq!(a.get_checked_pow_2(0), Some(4));

    // out-of-bounds behavior
    assert!(std::panic::catch_unwind(|| a.get(4)).is_err());
    assert_eq!(a.get_checked_pow_2(4), None);
}

#[test]
fn delegate_without_placeholder() {
    struct A(Vec<u8>);

    impl A {
        delegate! {
            to self.0 {
                #[expr(Some("test"))]
                fn get_name(&self) -> Option<&'static str>;
            }
        }
    }

    let a = A(vec![2, 3, 4, 5]);

    assert_eq!(a.get_name(), Some("test"));
}


================================================
FILE: tests/fields.rs
================================================
use delegate::delegate;

struct Datum {
    value: u32,
    error: u32,
    xy: (f32, f32),
}

struct DatumWrapper(Datum);

impl DatumWrapper {
    fn get_inner(&self) -> &Datum {
        &self.0
    }
    delegate! {
        to self.0 {
            /// Expands to `self.0.value`
            #[field]
            fn value(&self) -> u32;

            /// Expands to `self.0.value`
            #[field(value)]
            fn renamed_value(&self) -> u32;

            /// Expands to `&self.0.value`
            #[field(&value)]
            fn renamed_value_ref(&self) -> &u32;

            /// Expands to `&mut self.0.value`
            #[field(&mut value)]
            fn renamed_value_ref_mut(&mut self) -> &mut u32;

            /// Expands to `&self.0.error` (demonstrates `&` without a field name)
            #[field(&)]
            fn error(&self) -> &u32;
        }
        to self.0.xy {
            /// Expands to `self.0.xy.0` (demonstrates unnamed field access by value)
            #[field(0)]
            fn x(&self) -> f32;
            /// Expands to `&self.0.xy.1` (demonstrates unnamed field access by reference)
            #[field(&1)]
            fn y(&self) -> &f32;
        }
        to self.get_inner() {
            /// Expands to `&self.get_inner().value`
            #[field(&value)]
            fn value_ref_via_get_inner(&self) -> &u32;
        }
    }
}

#[test]
fn test_fields() {
    let mut wrapper = DatumWrapper(Datum {
        value: 1,
        error: 2,
        xy: (3.0, 4.0),
    });
    assert_eq!(wrapper.value(), wrapper.0.value);
    assert_eq!(wrapper.renamed_value(), wrapper.0.value);
    assert_eq!(wrapper.renamed_value_ref(), &wrapper.0.value);
    assert_eq!(wrapper.renamed_value_ref_mut(), &mut 1);
    assert_eq!(wrapper.value_ref_via_get_inner(), &1);
    assert_eq!(wrapper.error(), &wrapper.0.error);
    assert_eq!(wrapper.x(), wrapper.0.xy.0);
    assert_eq!(wrapper.y(), &wrapper.0.xy.1);
}


================================================
FILE: tests/function.rs
================================================
use delegate::delegate;

#[test]
fn test_delegate_function() {
    struct A {}
    impl A {
        fn foo(a: u32) -> u32 {
            a + 1
        }
    }

    struct B;

    impl B {
        delegate! {
            to A {
                fn foo(a: u32) -> u32;
            }
        }
    }

    assert_eq!(B::foo(1), 2);
}


================================================
FILE: tests/generic.rs
================================================
use delegate::delegate;
use std::collections::HashSet;
use std::hash::Hash;

#[test]
fn test_generics_method() {
    struct Foo;
    impl Foo {
        fn foo<'a, P, X>(&self) {}
    }

    struct Bar(Foo);
    impl Bar {
        delegate! {
            to &self.0 {
                fn foo<'a, P, X>(&self);
            }
        }
    }
}

#[test]
fn test_generics_function() {
    struct Foo;
    impl Foo {
        fn foo<P, X>() {}
    }

    struct Bar(Foo);
    impl Bar {
        delegate! {
            to Foo {
                fn foo<P, X>();
            }
        }
    }
}

#[test]
fn test_generics_through_trait() {
    trait A {
        fn f<P>(&self) -> u32;
    }

    struct Foo;

    impl A for Foo {
        fn f<P>(&self) -> u32 {
            0
        }
    }

    struct Bar(Foo);

    impl Bar {
        delegate! {
            to &self.0 {
                #[through(A)]
                fn f<P>(&self) -> u32;
            }
        }
    }

    let bar = Bar(Foo);
    assert_eq!(bar.f::<u32>(), 0);
}

#[test]
fn test_generics_complex() {
    struct Foo;
    impl Foo {
        fn foo<'a: 'static, X: Copy, #[allow(unused)] T>(&self) {}
    }

    struct Bar(Foo);
    impl Bar {
        delegate! {
            to &self.0 {
                fn foo<'a: 'static, X: Copy, #[allow(unused)] T>(&self);
            }
        }
    }
}

#[test]
fn test_lifetime_late_bound() {
    trait QSet<T>
    where
        T: PartialEq,
    {
        fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T>
        where
            Self: Sized,
            T: 'a;
    }

    impl<T: Eq + Hash> QSet<T> for HashSet<T> {
        delegate! {
            to self {
                #[through(HashSet)]
                fn iter<'a>(&'a self) -> impl Iterator<Item = &T>
                where
                    Self: Sized, T: 'a;
            }
        }
    }
}


================================================
FILE: tests/in_macro_expansion.rs
================================================
///
/// Tests that a macro can expand into a delegate block,
/// where the target comes from a macro variable.
///
use delegate::delegate;

trait Trait {
    fn method_to_delegate(&self) -> bool;
}

struct Struct1();
impl Trait for Struct1 {
    fn method_to_delegate(&self) -> bool {
        true
    }
}

struct Struct2(pub Struct1);

// We use a macro to impl 'Trait' for 'Struct2' such that
// the target is a variable in the macro.
macro_rules! some_macro {
    (|$self:ident| $delegate_to:expr) => {
        impl Trait for Struct2 {
            delegate! {
                // '$delegate_to' will expand to 'self.0' before ´delegate!' is expanded.
                to $delegate_to {
                    fn method_to_delegate(&$self) -> bool;
                }
            }
        }
    };
}
some_macro! { |self | self.0 }

#[test]
fn test() {
    assert!(Struct2(Struct1()).method_to_delegate());
}


================================================
FILE: tests/inline_args.rs
================================================
use delegate::delegate;

#[test]
fn test_inline_args() {
    struct Inner;

    impl Inner {
        fn fun_generic<S: Copy>(self, s: S) -> S {
            s
        }
        fn fun0(self) -> u32 {
            42
        }
        fn fun1(self, a: u32) -> u32 {
            a
        }
        fn fun2(self, a: u32, b: u32) -> u32 {
            a + b
        }
        fn fun3(&self, a: u32, b: u32, c: u32) -> u32 {
            a + b + c
        }
    }

    struct Outer {
        inner: Inner,
        value: u32,
    }

    impl Outer {
        pub fn new() -> Outer {
            Outer {
                inner: Inner,
                value: 42,
            }
        }

        delegate! {
            to self.inner {
                #[call(fun_generic)]
                fn fun_generic(self, [ 42 ]) -> u32;
                #[call(fun1)]
                fn fun1_with_0(self, [ 0 ]) -> u32;
                #[call(fun1)]
                fn fun1_with_0_no_spaces(self, [0]) -> u32;
                #[call(fun1)]
                fn fun1_with_def(self, [ self.value ] ) -> u32;
                fn fun2(self, [ 0 ], b: u32) -> u32;
            }
        }
    }

    assert_eq!(Outer::new().fun_generic(), 42);
    assert_eq!(Outer::new().fun1_with_0(), 0);
    assert_eq!(Outer::new().fun1_with_0_no_spaces(), 0);
    assert_eq!(Outer::new().fun1_with_def(), 42);
    assert_eq!(Outer::new().fun2(2), 2);
}

#[test]
fn test_mixed_args() {
    use delegate::delegate;
    struct Inner;
    impl Inner {
        pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 {
            a + x * x + b * y + c
        }
    }
    struct Wrapper {
        inner: Inner,
        a: i32,
        b: i32,
        c: i32,
    }
    impl Wrapper {
        delegate! {
            to self.inner {
                pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ;

                #[call(polynomial)]
                pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ;
            }
        }

        pub fn new() -> Wrapper {
            Wrapper {
                inner: Inner,
                a: 1,
                b: 3,
                c: 5,
            }
        }
    }

    assert_eq!(Wrapper::new().polynomial(2, 3), 19i32);
    assert_eq!(Wrapper::new().linear(3), 14i32);
}


================================================
FILE: tests/nested.rs
================================================
use delegate::delegate;

struct Inner;
impl Inner {
    pub fn method(&self, num: u32) -> u32 {
        num
    }
}

struct Inner2 {
    inner: Inner,
}

struct Wrapper {
    inner: Inner2,
}

impl Wrapper {
    delegate! {
        to self.inner.inner {
            pub(crate) fn method(&self, num: u32) -> u32;
        }
    }
}

#[test]
fn test_nested() {
    let wrapper = Wrapper {
        inner: Inner2 { inner: Inner },
    };

    assert_eq!(wrapper.method(3), 3);
}


================================================
FILE: tests/returntype.rs
================================================
use delegate::delegate;
use std::convert::TryFrom;

#[test]
fn test_generic_returntype() {
    trait TestTrait {
        fn create(num: u32) -> Self;
    }
    impl TestTrait for u32 {
        fn create(num: u32) -> Self {
            num
        }
    }

    struct Inner;
    impl Inner {
        pub fn method<T: TestTrait>(&self) -> T {
            T::create(0)
        }
    }

    struct Wrapper<T> {
        inner: Inner,
        s: T,
    }

    impl<T: TestTrait> Wrapper<T> {
        delegate! {
            to self.inner {
                pub(crate) fn method(&self) -> T;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner, s: 3 };

    assert_eq!(wrapper.method(), 0);
}

#[test]
fn test_into() {
    struct Inner;
    impl Inner {
        pub fn method(&self, num: u32) -> u32 {
            num
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                pub(crate) fn method(&self, num: u32);

                #[into]
                #[call(method)]
                pub(crate) fn method_conv(&self, num: u32) -> u64;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(3), ());
    assert_eq!(wrapper.method_conv(3), 3u64);
}

#[test]
fn test_try_into() {
    struct A;

    #[derive(Debug, PartialEq)]
    struct B;

    impl TryFrom<A> for B {
        type Error = u32;

        fn try_from(_value: A) -> Result<Self, Self::Error> {
            Ok(B)
        }
    }

    struct Inner;
    impl Inner {
        pub fn method(&self) -> A {
            A
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                #[try_into]
                fn method(&self) -> Result<B, u32>;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(), Ok(B));
}

#[test]
fn test_try_into_unwrap() {
    struct A;

    #[derive(Debug, PartialEq)]
    struct B;

    impl TryFrom<A> for B {
        type Error = u32;

        fn try_from(_value: A) -> Result<Self, Self::Error> {
            Ok(B)
        }
    }

    struct Inner;
    impl Inner {
        pub fn method(&self) -> A {
            A
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                #[try_into]
                #[unwrap]
                fn method(&self) -> B;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(), B);
}

#[test]
fn test_unwrap_result() {
    struct Inner;
    impl Inner {
        pub fn method(&self) -> Result<u32, ()> {
            Ok(0)
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                #[unwrap]
                fn method(&self) -> u32;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(), 0);
}

#[test]
fn test_unwrap_option() {
    struct Inner;
    impl Inner {
        pub fn method(&self) -> Option<u32> {
            Some(0)
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                #[unwrap]
                fn method(&self) -> u32;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(), 0);
}

#[test]
#[should_panic]
fn test_unwrap_no_return() {
    struct Inner;
    impl Inner {
        pub fn method(&self) -> Result<u32, ()> {
            Err(())
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                #[unwrap]
                fn method(&self);
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };
    wrapper.method();
}

#[test]
fn test_unwrap_into() {
    struct A(u32);

    impl From<u32> for A {
        fn from(value: u32) -> Self {
            A(value)
        }
    }

    struct Inner;
    impl Inner {
        pub fn method(&self) -> Result<u32, ()> {
            Ok(0)
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                #[unwrap]
                #[into]
                fn method(&self) -> A;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert!(matches!(wrapper.method(), A(0)));
}

#[test]
fn test_into_unwrap() {
    struct A(u32);

    impl From<A> for Result<u32, ()> {
        fn from(value: A) -> Self {
            Ok(value.0)
        }
    }

    struct Inner;
    impl Inner {
        pub fn method(&self) -> A {
            A(0)
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            to self.inner {
                #[into(Result<u32, ()>)]
                #[unwrap]
                fn method(&self) -> u32;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(), 0);
}


================================================
FILE: tests/segment_attributes.rs
================================================
use delegate::delegate;
use std::convert::TryFrom;

#[test]
fn test_segment_unwrap() {
    struct Inner;

    impl Inner {
        fn foo(&self, a: u32) -> Result<u32, ()> {
            Ok(a)
        }
        fn bar(&self, a: u32) -> Result<u32, ()> {
            Ok(a)
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            #[unwrap]
            to self.inner {
                fn foo(&self, a: u32) -> u32;
                fn bar(&self, a: u32) -> u32;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };
    assert_eq!(wrapper.foo(1), 1);
    assert_eq!(wrapper.bar(2), 2);
}

#[test]
fn test_segment_try_into() {
    struct A;

    #[derive(Debug, PartialEq)]
    struct B;

    impl TryFrom<A> for B {
        type Error = u32;

        fn try_from(_value: A) -> Result<Self, Self::Error> {
            Ok(B)
        }
    }

    struct Inner;
    impl Inner {
        pub fn method(&self) -> A {
            A
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            #[try_into]
            to self.inner {
                fn method(&self) -> Result<B, u32>;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };
    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(), Ok(B));
}

#[test]
fn test_segment_into() {
    struct A(u32);

    impl From<A> for Result<u32, ()> {
        fn from(value: A) -> Self {
            Ok(value.0)
        }
    }

    impl From<A> for u64 {
        fn from(value: A) -> Self {
            value.0 as u64
        }
    }

    struct Inner;
    impl Inner {
        pub fn method(&self) -> A {
            A(0)
        }
    }

    struct Wrapper {
        inner: Inner,
    }

    impl Wrapper {
        delegate! {
            #[into(Result<u32, ()>)]
            to self.inner {
                #[unwrap]
                fn method(&self) -> u32;

                #[into]
                #[call(method)]
                fn method2(&self) -> u64;
            }
        }
    }

    let wrapper = Wrapper { inner: Inner };

    assert_eq!(wrapper.method(), 0);
    assert_eq!(wrapper.method2(), 0);
}

#[test]
fn test_segment_await() {
    struct UserRepo;
    impl UserRepo {
        fn foo(&self) {}
        async fn bar(&self) -> u32 {
            1
        }
    }

    struct SharedRepo(tokio::sync::Mutex<UserRepo>);

    impl SharedRepo {
        delegate! {
            #[await(false)]
            to self.0.lock().await {
                async fn foo(&self);
                #[await(true)]
                async fn bar(&self) -> u32;
            }
        }
    }
}

#[test]
fn test_segment_through_trait() {
    trait A {
        fn f(&self) -> u32;
    }

    trait B {
        fn f(&self) -> u32;
    }

    struct Foo;

    impl A for Foo {
        fn f(&self) -> u32 {
            0
        }
    }
    impl B for Foo {
        fn f(&self) -> u32 {
            1
        }
    }

    struct Bar(Foo);

    impl Bar {
        delegate! {
            #[through(A)]
            to &self.0 {
                fn f(&self) -> u32;
                #[call(f)]
                #[through(B)]
                fn f2(&self) -> u32;
            }
        }
    }

    let bar = Bar(Foo);
    assert_eq!(bar.f(), 0);
    assert_eq!(bar.f2(), 1);
}

#[test]
fn test_segment_inline() {
    struct Foo;

    impl Foo {
        fn f(&self) -> u32 {
            0
        }
    }

    struct Bar(Foo);

    impl Bar {
        delegate! {
            #[inline(always)]
            to self.0 {
                fn f(&self) -> u32;
            }
        }
    }

    let bar = Bar(Foo);
    assert_eq!(bar.f(), 0);
}

#[test]
fn test_attribute_with_path() {
    struct Foo;

    impl Foo {
        fn f(&self) -> u32 {
            0
        }
    }

    struct Bar(Foo);

    impl Bar {
        delegate! {
            #[diagnostic::on_unimplemented]
            to self.0 {
                fn f(&self) -> u32;
            }
        }
    }

    let bar = Bar(Foo);
    assert_eq!(bar.f(), 0);
}


================================================
FILE: tests/stack.rs
================================================
use delegate::delegate;

#[derive(Clone, Debug)]
struct Stack<T> {
    inner: Vec<T>,
}

impl<T> Stack<T> {
    /// Allocate an empty stack
    pub fn new() -> Stack<T> {
        Stack { inner: vec![] }
    }

    delegate! {
        to self.inner {
            #[inline(never)]
            #[call(len)]
            pub(crate) fn size(&self) -> usize;

            /// doc comment
            fn is_empty(&self) -> bool;

            #[inline(never)]
            fn push(&mut self, v: T);
            pub fn pop(&mut self) -> Option<T>;

            #[call(last)]
            #[inline(never)]
            fn peek(&self) -> Option<&T>;
            fn clear(&mut self);
            fn into_boxed_slice(self) -> Box<[T]>;
        }
    }
}

#[test]
fn test_stack() {
    let mut stack: Stack<u32> = Stack::new();

    assert_eq!(stack.size(), 0);
    assert_eq!(stack.is_empty(), true);
    assert_eq!(stack.peek(), None);

    stack.clear();

    assert_eq!(stack.size(), 0);
    assert_eq!(stack.is_empty(), true);
    assert_eq!(stack.peek(), None);

    assert_eq!(stack.pop(), None);

    assert_eq!(stack.size(), 0);
    assert_eq!(stack.is_empty(), true);
    assert_eq!(stack.peek(), None);

    stack.push(1);

    assert_eq!(stack.size(), 1);
    assert_eq!(stack.is_empty(), false);
    assert_eq!(stack.peek(), Some(&1));

    assert_eq!(stack.pop(), Some(1));

    assert_eq!(stack.size(), 0);
    assert_eq!(stack.is_empty(), true);
    assert_eq!(stack.peek(), None);

    stack.push(1);
    stack.push(2);
    stack.push(3);

    assert_eq!(stack.size(), 3);
    assert_eq!(stack.is_empty(), false);
    assert_eq!(stack.peek(), Some(&3));

    assert_eq!(stack.clone().into_boxed_slice().into_vec(), stack.inner);

    assert_eq!(stack.pop(), Some(3));

    assert_eq!(stack.size(), 2);
    assert_eq!(stack.is_empty(), false);
    assert_eq!(stack.peek(), Some(&2));

    stack.clear();

    assert_eq!(stack.size(), 0);
    assert_eq!(stack.is_empty(), true);
    assert_eq!(stack.peek(), None);
}


================================================
FILE: tests/through_trait.rs
================================================
use delegate::delegate;

#[test]
fn test_call_through_trait() {
    trait A {
        fn f(&self) -> u32;
    }

    trait B {
        fn f(&self) -> u32;
    }

    struct Foo;

    impl A for Foo {
        fn f(&self) -> u32 {
            0
        }
    }
    impl B for Foo {
        fn f(&self) -> u32 {
            1
        }
    }

    struct Bar(Foo);

    impl Bar {
        delegate! {
            to &self.0 {
                #[through(A)]
                fn f(&self) -> u32;
                #[call(f)]
                #[through(B)]
                fn f2(&self) -> u32;
            }
        }
    }

    let bar = Bar(Foo);
    assert_eq!(bar.f(), 0);
    assert_eq!(bar.f2(), 1);
}
Download .txt
gitextract_6vrwi07n/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       ├── nightly-build.yml
│       ├── publish.yml
│       └── test.yml
├── .gitignore
├── .release-plz.toml
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── src/
│   ├── attributes.rs
│   └── lib.rs
└── tests/
    ├── argument_modifier.rs
    ├── associated_const_delegation.rs
    ├── async_await.rs
    ├── closure.rs
    ├── delegate_to_enum.rs
    ├── delegation.rs
    ├── expand/
    │   ├── fields.expanded.rs
    │   └── fields.rs
    ├── expr.rs
    ├── expr_attribute.rs
    ├── fields.rs
    ├── function.rs
    ├── generic.rs
    ├── in_macro_expansion.rs
    ├── inline_args.rs
    ├── nested.rs
    ├── returntype.rs
    ├── segment_attributes.rs
    ├── stack.rs
    └── through_trait.rs
Download .txt
SYMBOL INDEX (148 symbols across 22 files)

FILE: src/attributes.rs
  type CallMethodAttribute (line 8) | pub struct CallMethodAttribute {
    method parse (line 13) | fn parse(input: ParseStream) -> Result<Self, Error> {
  type GetFieldAttribute (line 21) | pub struct GetFieldAttribute {
    method reference_tokens (line 27) | pub fn reference_tokens(&self) -> Option<TokenStream> {
    method parse (line 36) | fn parse(input: ParseStream) -> Result<Self, Error> {
  type GenerateAwaitAttribute (line 49) | struct GenerateAwaitAttribute {
    method parse (line 54) | fn parse(input: ParseStream) -> Result<Self, Error> {
  type IntoAttribute (line 61) | struct IntoAttribute {
    method parse (line 66) | fn parse(input: ParseStream) -> Result<Self, Error> {
  type AssociatedConstant (line 80) | pub struct AssociatedConstant {
    method parse (line 86) | fn parse(input: ParseStream) -> Result<Self, Error> {
  type ExprPlaceHolder (line 119) | pub struct ExprPlaceHolder;
    method parse (line 122) | fn parse(input: ParseStream) -> syn::Result<Self> {
  type Placeholder (line 130) | enum Placeholder {
  type TemplateToken (line 140) | enum TemplateToken {
    method replace (line 148) | fn replace(&self, replacement: &TokenStream) -> TokenStream {
  type TemplateExpr (line 166) | pub struct TemplateExpr {
    method parse (line 173) | fn parse(input: ParseStream) -> syn::Result<Self> {
    method expand_template (line 202) | pub fn expand_template(&self, replacement: &TokenStream) -> TokenStream {
  type TraitTarget (line 210) | pub struct TraitTarget {
    method parse (line 215) | fn parse(input: ParseStream) -> Result<Self, Error> {
  type ReturnExpression (line 228) | pub enum ReturnExpression {
  type TargetSpecifier (line 234) | pub enum TargetSpecifier {
    method get_member (line 240) | pub fn get_member(&self, default: &syn::Ident) -> syn::Member {
  type ParsedAttribute (line 252) | enum ParsedAttribute {
  function parse_attributes (line 261) | fn parse_attributes(
  type MethodAttributes (line 360) | pub struct MethodAttributes<'a> {
  function parse_method_attributes (line 378) | pub fn parse_method_attributes<'a>(
  type SegmentAttributes (line 456) | pub struct SegmentAttributes {
  function parse_segment_attributes (line 464) | pub fn parse_segment_attributes(attrs: &[Attribute]) -> SegmentAttributes {
  function combine_attributes (line 511) | pub fn combine_attributes<'a>(

FILE: src/lib.rs
  type ArgumentModifier (line 502) | enum ArgumentModifier {
  type DelegatedInput (line 509) | enum DelegatedInput {
    method parse (line 539) | fn parse(input: ParseStream) -> Result<Self, Error> {
  function get_argument_modifier (line 517) | fn get_argument_modifier(attribute: syn::Attribute) -> Result<ArgumentMo...
  type DelegatedMethod (line 569) | struct DelegatedMethod {
    method parse (line 628) | fn parse(input: ParseStream) -> Result<Self, Error> {
  function parse_input_into_argument_expression (line 579) | fn parse_input_into_argument_expression(
  type DelegatedSegment (line 807) | struct DelegatedSegment {
    method parse (line 814) | fn parse(input: ParseStream) -> Result<Self, Error> {
  type DelegationBlock (line 846) | struct DelegationBlock {
    method parse (line 851) | fn parse(input: ParseStream) -> Result<Self, Error> {
  function has_inline_attribute (line 862) | fn has_inline_attribute(attrs: &[&syn::Attribute]) -> bool {
  type MatchVisitor (line 872) | struct MatchVisitor<F>(F);
  method visit_arm_mut (line 875) | fn visit_arm_mut(&mut self, arm: &mut syn::Arm) {
  function delegate (line 882) | pub fn delegate(tokens: TokenStream) -> TokenStream {
  function tolerant_outer_attributes (line 1092) | fn tolerant_outer_attributes(input: ParseStream) -> syn::Result<Vec<syn:...

FILE: tests/argument_modifier.rs
  type MyNewU32 (line 3) | struct MyNewU32(u32);
  type Foo (line 5) | trait Foo {
    method bar (line 6) | fn bar(&self, x: Self);
    method bar (line 10) | fn bar(&self, x: Self) {}
  function from (line 14) | fn from(value: MyNewU32) -> Self {
  type Bar (line 27) | struct Bar {
  type Baz (line 42) | struct Baz(Vec<u32>);

FILE: tests/associated_const_delegation.rs
  function test_delegate_constant (line 5) | fn test_delegate_constant() {
  function multiple_consts (line 52) | fn multiple_consts() {

FILE: tests/async_await.rs
  function test_async_await (line 9) | fn test_async_await() {
  function test_async_trait (line 44) | fn test_async_trait() {
  function test_bridge_async_to_sync (line 87) | fn test_bridge_async_to_sync() {
  function test_bridge_sync_to_async (line 106) | fn test_bridge_sync_to_async() {

FILE: tests/closure.rs
  function test_delegate_closure (line 5) | fn test_delegate_closure() {
  function test_delegate_closure_associated_function (line 46) | fn test_delegate_closure_associated_function() {

FILE: tests/delegate_to_enum.rs
  type Enum (line 3) | enum Enum {
  type A (line 9) | struct A {
    method dbg_inner (line 14) | fn dbg_inner(&self) -> usize {
    method into_num (line 19) | fn into_num(&self) -> u8 {
  type B (line 23) | struct B {
    method dbg_inner (line 28) | fn dbg_inner(&self) -> usize {
    method into_num (line 33) | fn into_num(&self) -> u64 {
  type C (line 38) | struct C {
    method dbg_inner (line 43) | fn dbg_inner(&self) -> usize {
    method into_num (line 48) | fn into_num(&self) -> usize {
  type IntoUsize (line 69) | struct IntoUsize(usize);
    method from (line 72) | fn from(value: usize) -> Self {
    method from (line 77) | fn from(value: u64) -> Self {
    method from (line 82) | fn from(value: u8) -> Self {
  function test_delegate_enum_method (line 88) | fn test_delegate_enum_method() {
  function test_delegate_enum_into (line 102) | fn test_delegate_enum_into() {

FILE: tests/delegation.rs
  function test_expansions (line 4) | fn test_expansions() {
  function test_delegation (line 9) | fn test_delegation() {
  function test_delegate_self (line 74) | fn test_delegate_self() {
  function test_delegate_tuple (line 100) | fn test_delegate_tuple() {

FILE: tests/expand/fields.expanded.rs
  type Datum (line 2) | struct Datum {
  type DatumWrapper (line 7) | struct DatumWrapper(Datum);
    method get_inner (line 9) | fn get_inner(&self) -> &Datum {
    method value (line 14) | fn value(&self) -> u32 {
    method renamed_value (line 19) | fn renamed_value(&self) -> u32 {
    method renamed_value_ref (line 24) | fn renamed_value_ref(&self) -> &u32 {
    method renamed_value_ref_mut (line 29) | fn renamed_value_ref_mut(&mut self) -> &mut u32 {
    method error (line 34) | fn error(&self) -> &u32 {
    method x (line 39) | fn x(&self) -> f32 {
    method y (line 44) | fn y(&self) -> &f32 {
    method value_ref_via_get_inner (line 49) | fn value_ref_via_get_inner(&self) -> &u32 {

FILE: tests/expand/fields.rs
  type Datum (line 4) | struct Datum {
  type DatumWrapper (line 10) | struct DatumWrapper(Datum);
    method get_inner (line 13) | fn get_inner(&self) -> &Datum {

FILE: tests/expr.rs
  type Inner (line 4) | struct Inner;
    method method (line 6) | pub fn method(&self, num: u32) -> u32 {
    method method2 (line 9) | pub fn method2(&self, num: u32) -> u32 {
  type Wrapper (line 14) | struct Wrapper {
  function global_fn (line 18) | fn global_fn() -> Inner {
  function test_mutex (line 34) | fn test_mutex() {
  function test_index (line 44) | fn test_index() {

FILE: tests/expr_attribute.rs
  function delegate_with_custom_expr (line 5) | fn delegate_with_custom_expr() {
  function delegate_without_placeholder (line 32) | fn delegate_without_placeholder() {

FILE: tests/fields.rs
  type Datum (line 3) | struct Datum {
  type DatumWrapper (line 9) | struct DatumWrapper(Datum);
    method get_inner (line 12) | fn get_inner(&self) -> &Datum {
  function test_fields (line 54) | fn test_fields() {

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

FILE: tests/generic.rs
  function test_generics_method (line 6) | fn test_generics_method() {
  function test_generics_function (line 23) | fn test_generics_function() {
  function test_generics_through_trait (line 40) | fn test_generics_through_trait() {
  function test_generics_complex (line 69) | fn test_generics_complex() {
  function test_lifetime_late_bound (line 86) | fn test_lifetime_late_bound() {

FILE: tests/in_macro_expansion.rs
  type Trait (line 7) | trait Trait {
    method method_to_delegate (line 8) | fn method_to_delegate(&self) -> bool;
    method method_to_delegate (line 13) | fn method_to_delegate(&self) -> bool {
  type Struct1 (line 11) | struct Struct1();
  type Struct2 (line 18) | struct Struct2(pub Struct1);
  function test (line 37) | fn test() {

FILE: tests/inline_args.rs
  function test_inline_args (line 4) | fn test_inline_args() {
  function test_mixed_args (line 61) | fn test_mixed_args() {

FILE: tests/nested.rs
  type Inner (line 3) | struct Inner;
    method method (line 5) | pub fn method(&self, num: u32) -> u32 {
  type Inner2 (line 10) | struct Inner2 {
  type Wrapper (line 14) | struct Wrapper {
  function test_nested (line 27) | fn test_nested() {

FILE: tests/returntype.rs
  function test_generic_returntype (line 5) | fn test_generic_returntype() {
  function test_into (line 41) | fn test_into() {
  function test_try_into (line 72) | fn test_try_into() {
  function test_try_into_unwrap (line 112) | fn test_try_into_unwrap() {
  function test_unwrap_result (line 153) | fn test_unwrap_result() {
  function test_unwrap_option (line 180) | fn test_unwrap_option() {
  function test_unwrap_no_return (line 208) | fn test_unwrap_no_return() {
  function test_unwrap_into (line 234) | fn test_unwrap_into() {
  function test_into_unwrap (line 270) | fn test_into_unwrap() {

FILE: tests/segment_attributes.rs
  function test_segment_unwrap (line 5) | fn test_segment_unwrap() {
  function test_segment_try_into (line 37) | fn test_segment_try_into() {
  function test_segment_into (line 78) | fn test_segment_into() {
  function test_segment_await (line 125) | fn test_segment_await() {
  function test_segment_through_trait (line 149) | fn test_segment_through_trait() {
  function test_segment_inline (line 191) | fn test_segment_inline() {
  function test_attribute_with_path (line 216) | fn test_attribute_with_path() {

FILE: tests/stack.rs
  type Stack (line 4) | struct Stack<T> {
  function new (line 10) | pub fn new() -> Stack<T> {
  function test_stack (line 37) | fn test_stack() {

FILE: tests/through_trait.rs
  function test_call_through_trait (line 4) | fn test_call_through_trait() {
Condensed preview — 33 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (140K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 15,
    "preview": "github: Kobzol\n"
  },
  {
    "path": ".github/workflows/nightly-build.yml",
    "chars": 629,
    "preview": "on:\n  schedule:\n    - cron: \"0 0 * * *\"\n  workflow_dispatch:\n\nname: Nightly Build\n\njobs:\n  test:\n    name: Build\n    run"
  },
  {
    "path": ".github/workflows/publish.yml",
    "chars": 1811,
    "preview": "name: Publish new release\n\non:\n  push:\n    branches:\n      - main\n\njobs:\n  test:\n    name: Release test\n    runs-on: ubu"
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 1253,
    "preview": "# Based on https://github.com/actions-rs/meta/blob/master/recipes/matrix.md\n\non: [ push, pull_request ]\n\nname: Tests\n\njo"
  },
  {
    "path": ".gitignore",
    "chars": 30,
    "preview": "/target\n**/*.rs.bk\nCargo.lock\n"
  },
  {
    "path": ".release-plz.toml",
    "chars": 110,
    "preview": "[workspace]\nrelease_always = false\npr_branch_prefix = \"release-\"\npr_labels = [\"release\"]\nsemver_check = false\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 6964,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
  },
  {
    "path": "Cargo.toml",
    "chars": 643,
    "preview": "[package]\nname = \"delegate\"\ndescription = \"Method delegation with less boilerplate\"\nversion = \"0.13.5\"\nauthors = [\"Godfr"
  },
  {
    "path": "LICENSE-APACHE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "LICENSE-MIT",
    "chars": 1078,
    "preview": "Copyright (c) 2018 The Rust Delegate Crate Developers\n\nPermission is hereby granted, free of charge, to any\nperson obtai"
  },
  {
    "path": "README.md",
    "chars": 12911,
    "preview": "# Method delegation with less boilerplate\n\n[![Build Status](https://github.com/kobzol/rust-delegate/workflows/Tests/badg"
  },
  {
    "path": "src/attributes.rs",
    "chars": 19176,
    "preview": "use proc_macro2::{Delimiter, TokenStream, TokenTree};\nuse quote::ToTokens;\nuse std::collections::VecDeque;\nuse std::ops:"
  },
  {
    "path": "src/lib.rs",
    "chars": 41107,
    "preview": "//! This crate removes some boilerplate for structs that simply delegate\n//! some of their methods to one or more of the"
  },
  {
    "path": "tests/argument_modifier.rs",
    "chars": 715,
    "preview": "use delegate::delegate;\n\nstruct MyNewU32(u32);\n\ntrait Foo {\n    fn bar(&self, x: Self);\n}\n\nimpl Foo for u32 {\n    fn bar"
  },
  {
    "path": "tests/associated_const_delegation.rs",
    "chars": 1561,
    "preview": "extern crate delegate;\nuse delegate::delegate;\n\n#[test]\nfn test_delegate_constant() {\n    trait WithConst {\n        cons"
  },
  {
    "path": "tests/async_await.rs",
    "chars": 2897,
    "preview": "extern crate delegate;\n\nuse delegate::delegate;\nuse std::future::Future;\nuse std::pin::Pin;\nuse std::task::{Context, Pol"
  },
  {
    "path": "tests/closure.rs",
    "chars": 1669,
    "preview": "use delegate::delegate;\nuse std::cell::OnceCell;\n\n#[test]\nfn test_delegate_closure() {\n    struct Inner(u32);\n    impl I"
  },
  {
    "path": "tests/delegate_to_enum.rs",
    "chars": 1891,
    "preview": "use delegate::delegate;\n\nenum Enum {\n    A(A),\n    B(B),\n    C { v: C },\n}\n\nstruct A {\n    val: usize,\n}\n\nimpl A {\n    f"
  },
  {
    "path": "tests/delegation.rs",
    "chars": 2556,
    "preview": "use delegate::delegate;\n\n#[test]\nfn test_expansions() {\n    macrotest::expand(\"tests/expand/*.rs\");\n}\n\n#[test]\nfn test_d"
  },
  {
    "path": "tests/expand/fields.expanded.rs",
    "chars": 1260,
    "preview": "use delegate::delegate;\nstruct Datum {\n    value: u32,\n    error: u32,\n    xy: (f32, f32),\n}\nstruct DatumWrapper(Datum);"
  },
  {
    "path": "tests/expand/fields.rs",
    "chars": 1380,
    "preview": "\nuse delegate::delegate;\n\nstruct Datum {\n    value: u32,\n    error: u32,\n    xy: (f32, f32)\n}\n\nstruct DatumWrapper(Datum"
  },
  {
    "path": "tests/expr.rs",
    "chars": 1206,
    "preview": "use delegate::delegate;\nuse std::sync::Mutex;\n\nstruct Inner;\nimpl Inner {\n    pub fn method(&self, num: u32) -> u32 {\n  "
  },
  {
    "path": "tests/expr_attribute.rs",
    "chars": 1018,
    "preview": "extern crate delegate;\nuse delegate::delegate;\n\n#[test]\nfn delegate_with_custom_expr() {\n    struct A(Vec<u8>);\n\n    imp"
  },
  {
    "path": "tests/fields.rs",
    "chars": 1946,
    "preview": "use delegate::delegate;\n\nstruct Datum {\n    value: u32,\n    error: u32,\n    xy: (f32, f32),\n}\n\nstruct DatumWrapper(Datum"
  },
  {
    "path": "tests/function.rs",
    "chars": 328,
    "preview": "use delegate::delegate;\n\n#[test]\nfn test_delegate_function() {\n    struct A {}\n    impl A {\n        fn foo(a: u32) -> u3"
  },
  {
    "path": "tests/generic.rs",
    "chars": 1862,
    "preview": "use delegate::delegate;\nuse std::collections::HashSet;\nuse std::hash::Hash;\n\n#[test]\nfn test_generics_method() {\n    str"
  },
  {
    "path": "tests/in_macro_expansion.rs",
    "chars": 905,
    "preview": "///\n/// Tests that a macro can expand into a delegate block,\n/// where the target comes from a macro variable.\n///\nuse d"
  },
  {
    "path": "tests/inline_args.rs",
    "chars": 2346,
    "preview": "use delegate::delegate;\n\n#[test]\nfn test_inline_args() {\n    struct Inner;\n\n    impl Inner {\n        fn fun_generic<S: C"
  },
  {
    "path": "tests/nested.rs",
    "chars": 474,
    "preview": "use delegate::delegate;\n\nstruct Inner;\nimpl Inner {\n    pub fn method(&self, num: u32) -> u32 {\n        num\n    }\n}\n\nstr"
  },
  {
    "path": "tests/returntype.rs",
    "chars": 5225,
    "preview": "use delegate::delegate;\nuse std::convert::TryFrom;\n\n#[test]\nfn test_generic_returntype() {\n    trait TestTrait {\n       "
  },
  {
    "path": "tests/segment_attributes.rs",
    "chars": 4115,
    "preview": "use delegate::delegate;\nuse std::convert::TryFrom;\n\n#[test]\nfn test_segment_unwrap() {\n    struct Inner;\n\n    impl Inner"
  },
  {
    "path": "tests/stack.rs",
    "chars": 2014,
    "preview": "use delegate::delegate;\n\n#[derive(Clone, Debug)]\nstruct Stack<T> {\n    inner: Vec<T>,\n}\n\nimpl<T> Stack<T> {\n    /// Allo"
  },
  {
    "path": "tests/through_trait.rs",
    "chars": 696,
    "preview": "use delegate::delegate;\n\n#[test]\nfn test_call_through_trait() {\n    trait A {\n        fn f(&self) -> u32;\n    }\n\n    tra"
  }
]

About this extraction

This page contains the full source code of the chancancode/rust-delegate GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 33 files (130.0 KB), approximately 32.1k tokens, and a symbol index with 148 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!