[
  {
    "path": ".github/FUNDING.yml",
    "content": "github: Kobzol\n"
  },
  {
    "path": ".github/workflows/nightly-build.yml",
    "content": "on:\n  schedule:\n    - cron: \"0 0 * * *\"\n  workflow_dispatch:\n\nname: Nightly Build\n\njobs:\n  test:\n    name: Build\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        rust:\n          - stable\n          - beta\n          - nightly\n    steps:\n      - name: Checkout sources\n        uses: actions/checkout@v2\n\n      - name: Install stable toolchain\n        uses: actions-rs/toolchain@v1\n        with:\n          profile: minimal\n          toolchain: ${{ matrix.rust }}\n          override: true\n\n      - name: Build\n        uses: actions-rs/cargo@v1\n        with:\n          command: build\n          args: --all --all-features\n"
  },
  {
    "path": ".github/workflows/publish.yml",
    "content": "name: Publish new release\n\non:\n  push:\n    branches:\n      - main\n\njobs:\n  test:\n    name: Release test\n    runs-on: ubuntu-latest\n    if: ${{ github.repository_owner == 'kobzol' }}\n    steps:\n      - &checkout\n        name: Checkout repository\n        uses: actions/checkout@v5\n        with:\n          fetch-depth: 0\n          persist-credentials: false\n      - &install-rust\n        name: Install Rust toolchain\n        uses: dtolnay/rust-toolchain@stable\n      - name: Install cargo-expand\n        uses: actions-rs/cargo@v1\n        with:\n          command: install\n          args: --locked --version 1.0.118 cargo-expand\n      - run: cargo test\n  # Release unpublished packages.\n  release:\n    name: Release-plz release\n    runs-on: ubuntu-latest\n    if: ${{ github.repository_owner == 'kobzol' }}\n    needs:\n      - test\n    permissions:\n      contents: write\n      id-token: write\n    steps:\n      - *checkout\n      - *install-rust\n      - name: Run release-plz\n        # 0.5.118\n        uses: release-plz/action@01df7609d1a7310c0776a102df00daf509d56e33\n        with:\n          command: release\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n  # Create a PR with the new versions and changelog, preparing the next release.\n  create-release-pr:\n    name: Release-plz PR\n    runs-on: ubuntu-latest\n    if: ${{ github.repository_owner == 'kobzol' }}\n    permissions:\n      contents: write\n      pull-requests: write\n    concurrency:\n      group: release-plz-${{ github.ref }}\n      cancel-in-progress: false\n    steps:\n      - *checkout\n      - *install-rust\n      - name: Run release-plz\n        # 0.5.118\n        uses: release-plz/action@01df7609d1a7310c0776a102df00daf509d56e33\n        with:\n          command: release-pr\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "# Based on https://github.com/actions-rs/meta/blob/master/recipes/matrix.md\n\non: [ push, pull_request ]\n\nname: Tests\n\njobs:\n  test:\n    name: Test\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        rust:\n          - stable\n          - beta\n          - nightly\n    steps:\n      - name: Checkout sources\n        uses: actions/checkout@v2\n\n      - name: Install stable toolchain\n        uses: actions-rs/toolchain@v1\n        with:\n          profile: minimal\n          toolchain: ${{ matrix.rust }}\n          override: true\n          components: rustfmt, clippy\n\n      - uses: Swatinem/rust-cache@v2\n\n      - name: Install cargo-expand\n        uses: actions-rs/cargo@v1\n        with:\n          command: install\n          args: --locked --version 1.0.118 cargo-expand\n\n      - name: Build\n        uses: actions-rs/cargo@v1\n        with:\n          command: build\n          args: --all --all-features\n\n      - name: Test\n        uses: actions-rs/cargo@v1\n        with:\n          command: test\n\n      - name: Lint\n        uses: actions-rs/cargo@v1\n        with:\n          command: clippy\n          args: -- -D warnings\n\n      - name: Formatting\n        uses: actions-rs/cargo@v1\n        with:\n          command: fmt\n          args: --all -- --check\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n**/*.rs.bk\nCargo.lock\n"
  },
  {
    "path": ".release-plz.toml",
    "content": "[workspace]\nrelease_always = false\npr_branch_prefix = \"release-\"\npr_labels = [\"release\"]\nsemver_check = false\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [Unreleased]\n\n## [0.13.5](https://github.com/Kobzol/rust-delegate/compare/v0.13.4...v0.13.5) - 2025-11-17\n\n### New features\n\n- Implement support for delegating to fields (#88 from JRRudy1).\n\n### Internal\n\n- Start using [release-plz](https://release-plz.dev/) for releases, together with crates.io Trusted Publishing.\n\n# 0.13.4 (14. 7. 2025)\n\n- Do not explicitly forward lifetime arguments when calling delegated functions (https://github.com/Kobzol/rust-delegate/issues/85).\n\n# 0.13.3 (25. 3. 2025)\n\n- Add `#[const(path::to::Trait::CONST)]` attribute to delegate associated constants via a getter (implemented by @vic1707).\n- Add `#[expr(<$ template>)]` attribute to modify delegated call using custom code (implemented by @vic1707).\n\n# 0.13.2 (14. 1. 2025)\n\n- Correctly parse attributes with segmented paths (e.g. `#[a::b::c]`) (https://github.com/Kobzol/rust-delegate/issues/77).\n\n# 0.13.1 (9. 10. 2024)\n\n- Correctly pass generic method type and lifetime arguments to the delegated method.\n\n# 0.13.0 (2. 9. 2024)\n\n- Generalize match arms handling. You can now combine a match expression target with annotations like `#[into]` and\n  others:\n\n```rust\nstruct A;\n\nimpl A {\n    pub fn callable(self) -> Self {\n        self\n    }\n}\n\nstruct B;\n\nimpl B {\n    pub fn callable(self) -> Self {\n        self\n    }\n}\n\nenum Common {\n    A(A),\n    B(B),\n}\n\nimpl From<A> for Common {\n    fn from(inner: A) -> Self {\n        Self::A(inner)\n    }\n}\n\nimpl From<B> for Common {\n    fn from(inner: B) -> Self {\n        Self::B(inner)\n    }\n}\n\nimpl Common {\n    delegate! {\n        to match self {\n        // ---------- `match` arms have incompatible types\n            Common::A(inner) => inner;\n            Common::B(inner) => inner;\n        } {\n            #[into]\n            pub fn callable(self) -> Self;\n        }\n    }\n\n    // Generates\n    // pub fn callable(self) -> Self {\n    //     match self {\n    //         Common::A(inner) => inner.callable().into(),\n    //         Common::B(inner) => inner.callable().into(),\n    //     }\n    // }\n}\n```\n\n- The crate should be `#[no_std]` compatible again (https://github.com/Kobzol/rust-delegate/pull/74).\n\n# 0.12.0 (22. 12. 2023)\n\n- Add new `#[newtype]` function parameter modifier ([#64](https://github.com/Kobzol/rust-delegate/pull/64)).\n  Implemented by [Techassi](https://github.com/Techassi)\n\n- Allow passing arbitrary attributes to delegation segments:\n\n```rust\nimpl Foo {\n    delegate! {\n    #[inline(always)]\n    to self.0 { ... }\n  }\n}\n```\n\n- Change the default inlining mode from `#[inline(always)]`\n  to `#[inline]` (https://github.com/Kobzol/rust-delegate/issues/61).\n\n# 0.11.0 (4. 12. 2023)\n\n- Allow delegating an associated function (not just a method).\n\n```rust\nstruct A {}\n\nimpl A {\n    fn foo(a: u32) -> u32 {\n        a + 1\n    }\n}\n\nstruct B;\n\nimpl B {\n    delegate! {\n        to A {\n            fn foo(a: u32) -> u32;\n        }\n    }\n}\n```\n\n# 0.10.0 (29. 6. 2023)\n\n- Allow specifying certain attributes (e.g. `#[into]` or `#[unwrap]`) on delegated segments.\n  The attribute will then be applied to all methods in that segment (unless it is overwritten on the method itself).\n\n```rust\ndelegate! {\n  #[unwrap]\n  to self.inner {\n    fn foo(&self) -> u32; // calls self.inner.foo().unwrap()\n    fn bar(&self) -> u32; // calls self.inner.bar().unwrap()\n  }\n}\n```\n\n- Add new `#[unwrap]` method modifier. Adding it on top of a delegated method will cause the generated\n  code to `.unwrap()` the result.\n\n```rust\n#[unwrap]\nfn foo(&self) -> u32;  // foo().unwrap()\n```\n\n- Add new `#[through(<trait>)]` method modifier. Adding it on top of a delegated method will cause the generated\n  code to call the method through the provided trait\n  using [UFCS](https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls).\n\n```rust\n#[through(MyTrait)]\ndelegate! {\n  to &self.inner {\n    #[through(MyTrait)]\n    fn foo(&self) -> u32;  // MyTrait::foo(&self.inner)\n  }\n}\n```\n\n- Removed `#[try_into(unwrap)]`. It can now be replaced with the combination of `#[try_into]` and `#[unwrap]`:\n\n```rust\n#[try_into]\n#[unwrap]\nfn foo(&self) -> u32;  // TryInto::try_into(foo()).unwrap()\n```\n\n- Add the option to specify explicit type path to the `#[into]` expression modifier:\n\n```rust\n#[into(u64)]\nfn foo(&self) -> u64; // Into::<u64>::into(foo())\n```\n\n- Expression modifiers `#[into]`, `#[try_into]` and `#[unwrap]` can now be used multiple times. The order\n  of their usage dictates in what order they will be applied:\n\n```rust\n#[into]\n#[unwrap]\nfn foo(&self) -> u32;  // Into::into(foo()).unwrap()\n\n#[unwrap]\n#[into]\nfn foo(&self) -> u32;  // Into::into(foo().unwrap())\n```\n\n# 0.9.0 (16. 1. 2023)\n\n- Add new `#[as_ref]` function parameter modifier ([#47](https://github.com/Kobzol/rust-delegate/pull/47)).\n  Implemented by [trueegorletov](https://github.com/trueegorletov).\n\n# 0.8.0 (7. 9. 2022)\n\n- Allow simple delegation to enum variants ([#45](https://github.com/Kobzol/rust-delegate/pull/45)).\n  Implemented by [gfreezy](https://github.com/gfreezy).\n\n# 0.7.0 (6. 6. 2022)\n\n- Add new `#[into]` attribute for delegated function parameters. If specified, the parameter will be\n  converted using the `From` trait before being passed as an argument to the called function.\n- Add new `#[try_from]` attribute to delegated functions. You can use it to convert the delegated\n  expression using the `TryFrom` trait. You can also use `#[try_from(unwrap)]` to unwrap the result of\n  the conversion.\n\n# 0.6.2 (31. 1. 2022)\n\n- Add new `#[await(true/false)]` attribute to delegated functions. You can use it to control whether\n  `.await` will be appended to the delegated expression. It will be generated by default if the delegation\n  method signature is `async`.\n\n# 0.6.1 (25. 7. 2021)\n\n- add support for `async` functions. The delegated call will now use `.await`.\n\n# 0.6.0 (7. 7. 2021)\n\n- add the option to specify inline expressions that will be used as arguments for the delegated\n  call (https://github.com/kobzol/rust-delegate/pull/34)\n- removed `append_args` attribute, which is superseded by the mentioned expression in signature support\n\n# 0.5.2 (16. 6. 2021)\n\n- add the `append_args` attribute to append attributes to delegated\n  calls (https://github.com/kobzol/rust-delegate/pull/31)\n\n# 0.5.1 (6. 1. 2021)\n\n- fix breaking change caused by using `syn` private API (https://github.com/kobzol/rust-delegate/issues/28)\n\n# 0.5.0 (16. 11. 2020)\n\n- `self` can now be used as the delegation target\n- Rust 1.46 introduced a change that makes it a bit difficult to use `rust-delegate` implementations\n  generated by macros. If you have this use case, please\n  use [this workaround](https://github.com/kobzol/rust-delegate/issues/25#issuecomment-716774685).\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"delegate\"\ndescription = \"Method delegation with less boilerplate\"\nversion = \"0.13.5\"\nauthors = [\"Godfrey Chan <godfreykfc@gmail.com>\", \"Jakub Beránek <berykubik@gmail.com>\"]\nrepository = \"https://github.com/kobzol/rust-delegate\"\nreadme = \"README.md\"\nlicense = \"MIT OR Apache-2.0\"\nedition = \"2018\"\ninclude = [\n    \"src/*.rs\",\n    \"Cargo.toml\",\n    \"README.md\"\n]\n\n[dependencies]\nsyn = { version = \"2\", features = [\"full\", \"visit-mut\"] }\nquote = \"1\"\nproc-macro2 = \"1\"\n\n[lib]\nproc-macro = true\n\n[dev-dependencies]\nasync-trait = \"0.1.50\"\nfutures = \"0.3.16\"\ntokio = { version = \"1.16.1\", features = [\"sync\"] }\nmacrotest = \"1.0.12\"\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Copyright (c) 2018 The Rust Delegate Crate Developers\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Method delegation with less boilerplate\n\n[![Build Status](https://github.com/kobzol/rust-delegate/workflows/Tests/badge.svg)](https://github.com/kobzol/rust-delegate/actions)\n[![Crates.io](https://img.shields.io/crates/v/delegate.svg)](https://crates.io/crates/delegate)\n\nThis crate removes some boilerplate for structs that simply delegate some of\ntheir methods to one or more of their fields.\n\nIt gives you the `delegate!` macro, which delegates method calls to selected\nexpressions (usually inner fields).\n\n## Example:\n\nA Stack data structure implemented using an inner Vec via delegation.\n\n```rust\nuse delegate::delegate;\n\n#[derive(Clone, Debug)]\nstruct Stack<T> {\n    inner: Vec<T>,\n}\nimpl<T> Stack<T> {\n    pub fn new() -> Self <T> {\n        Self { inner: vec![] }\n    }\n\n    delegate! {\n        to self.inner {\n            pub fn is_empty(&self) -> bool;\n            pub fn push(&mut self, value: T);\n            pub fn pop(&mut self) -> Option<T>;\n            pub fn clear(&mut self);\n\n            #[call(len)]\n            pub fn size(&self) -> usize;\n\n            #[call(last)]\n            pub fn peek(&self) -> Option<&T>;\n\n        }\n    }\n}\n```\n\n## Features\n\n### Delegate to a method with a different name\n```rust\nstruct Stack {\n    inner: Vec<u32>\n}\nimpl Stack {\n    delegate! {\n        to self.inner {\n            #[call(push)]\n            pub fn add(&mut self, value: u32);\n        }\n    }\n}\n```\n\n### Use an arbitrary inner field expression\n```rust\nstruct Wrapper {\n    inner: Rc<RefCell<Vec<u32>>>\n}\nimpl Wrapper {\n    delegate! {\n        to self.inner.deref().borrow_mut() {\n            pub fn push(&mut self, val: u32);\n        }\n    }\n}\n```\n\n### Delegate to enum variants\n```rust\nuse 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    fn dbg_inner(&self) -> usize {\n        dbg!(self.val);\n        1\n    }\n}\nstruct B {\n    val_a: String,\n}\n\nimpl B {\n    fn dbg_inner(&self) -> usize {\n        dbg!(self.val_a.clone());\n        2\n    }\n}\n\nstruct C {\n    val_c: f64,\n}\n\nimpl C {\n    fn dbg_inner(&self) -> usize {\n        dbg!(self.val_c);\n        3\n    }\n}\n\nimpl Enum {\n    delegate! {\n        // transformed to\n        //\n        // ```rust\n        // match self {\n        //     Enum::A(a) => a.dbg_inner(),\n        //     Enum::B(b) => { println!(\"i am b\"); b }.dbg_inner(),\n        //     Enum::C { v: c } => { c }.dbg_inner(),\n        // }\n        // ```\n        to match self {\n            Enum::A(a) => a,\n            Enum::B(b) => { println!(\"i am b\"); b },\n            Enum::C { v: c } => { c },\n        } {\n            fn dbg_inner(&self) -> usize;\n        }\n    }\n}\n```\n\n### Use modifiers that alter the generated method body\n```rust\nuse delegate::delegate;\nstruct Inner;\nimpl Inner {\n    pub fn method(&self, num: u32) -> u32 { num }\n    pub fn method_res(&self, num: u32) -> Result<u32, ()> { Ok(num) }\n}\nstruct Wrapper {\n    inner: Inner\n}\nimpl Wrapper {\n    delegate! {\n        to self.inner {\n            // calls method, converts result to u64 using `From`\n            #[into]\n            pub fn method(&self, num: u32) -> u64;\n\n            // calls method, returns ()\n            #[call(method)]\n            pub fn method_noreturn(&self, num: u32);\n\n            // calls method, converts result to i6 using `TryFrom`\n            #[try_into]\n            #[call(method)]\n            pub fn method2(&self, num: u32) -> Result<u16, std::num::TryFromIntError>;\n\n            // calls method_res, unwraps the result\n            #[unwrap]\n            pub fn method_res(&self, num: u32) -> u32;\n\n            // calls method_res, unwraps the result, then calls into\n            #[unwrap]\n            #[into]\n            #[call(method_res)]\n            pub fn method_res_into(&self, num: u32) -> u64;\n\n            // specify explicit type for into\n            #[into(u64)]\n            #[call(method)]\n            pub fn method_into_explicit(&self, num: u32) -> u64;\n        }\n    }\n}\n```\n\n### Custom called expression\n\nThe `#[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.\n\n_Note:_ the `$` placeholder isn't required and can be present multiple times if you want.\n\n```rust\nstruct A(Vec<u8>);\n\nimpl A {\n    delegate! {\n        to self.0 {\n            #[expr(*$.unwrap())]\n            /// Here `$` == `self.0.get(idx)`\n            /// Will expand to `*self.0.get(idx).unwrap()`\n            fn get(&self, idx: usize) -> u8;\n\n            #[call(get)]\n            #[expr($?.checked_pow(2))]\n            /// Here `$` == `self.0.get(idx)`\n            /// Will expand to `self.0.get(idx)?.checked_pow(2)`\n            fn get_checked_pow_2(&self, idx: usize) -> Option<u8>;\n        }\n    }\n}\n```\n\n### Add additional arguments to method\n```rust\nstruct Inner(u32);\nimpl Inner {\n    pub fn new(m: u32) -> Self {\n        // some \"very complex\" constructing work\n        Self(m)\n    }\n    pub fn method(&self, n: u32) -> u32 {\n        self.0 + n\n    }\n}\n\nstruct Wrapper {\n    inner: OnceCell<Inner>,\n}\n\nimpl Wrapper {\n    pub fn new() -> Self {\n        Self {\n            inner: OnceCell::new(),\n        }\n    }\n    fn content(&self, val: u32) -> &Inner {\n        self.inner.get_or_init(|| Inner(val))\n    }\n    delegate! {\n        to |k: u32| self.content(k) {\n            // `wrapper.method(k, num)` will call `self.content(k).method(num)`\n            pub fn method(&self, num: u32) -> u32;\n        }\n    }\n}\n```\n\n### Call `await` on async functions\n```rust\nstruct Inner;\nimpl Inner {\n    pub async fn method(&self, num: u32) -> u32 { num }\n}\nstruct Wrapper {\n    inner: Inner\n}\nimpl Wrapper {\n    delegate! {\n        to self.inner {\n            // calls method(num).await, returns impl Future<Output = u32>\n            pub async fn method(&self, num: u32) -> u32;\n            // calls method(num).await.into(), returns impl Future<Output = u64>\n            #[into]\n            #[call(method)]\n            pub async fn method_into(&self, num: u32) -> u64;\n        }\n    }\n}\n```\n\nYou can use the `#[await(true/false)]` attribute on delegated methods to specify\nif `.await` should be generated after the delegated expression. It will be\ngenerated by default if the delegated method is `async`.\n\n### Delegate to multiple fields\n```rust\nstruct MultiStack {\n    left: Vec<u32>,\n    right: Vec<u32>,\n}\nimpl MultiStack {\n    delegate! {\n        to self.left {\n            /// Push an item to the top of the left stack\n            #[call(push)]\n            pub fn push_left(&mut self, value: u32);\n        }\n        to self.right {\n            /// Push an item to the top of the right stack\n            #[call(push)]\n            pub fn push_right(&mut self, value: u32);\n        }\n    }\n}\n```\n\n### Inline attributes\n`rust-delegate` inserts `#[inline(always)]` automatically. You can override that decision by specifying `#[inline]`\nmanually on the delegated method.\n\n### Segment attributes\nYou can use an attribute on a whole delegation segment to automatically apply it to all methods in that segment:\n\n```rust\nstruct Wrapper {\n    inner: Inner\n}\n\nimpl Wrapper {\n    delegate! {\n   #[unwrap]\n   to self.inner {\n     fn foo(&self) -> u32; // calls self.inner.foo().unwrap()\n     fn bar(&self) -> u32; // calls self.inner.bar().unwrap()\n   }\n }\n}\n```\n\n### Adding additional arguments\nYou can specify expressions in the signature that will be used as delegated arguments:\n\n```rust\nuse delegate::delegate;\n\nstruct Inner;\nimpl Inner {\n    pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 {\n        a + x * x + b * y + c\n    }\n}\nstruct Wrapper {\n    inner: Inner,\n    a: i32,\n    b: i32,\n    c: i32\n}\nimpl Wrapper {\n    delegate! {\n        to self.inner {\n            // Calls `polynomial` on `inner` with `self.a`, `self.b` and\n            // `self.c` passed as arguments `a`, `b`, and `c`, effectively\n            // calling `polynomial(self.a, x, self.b, y, self.c)`.\n            pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ;\n            // Calls `polynomial` on `inner` with `0`s passed for arguments\n            // `a` and `x`, and `self.b` and `self.c` for `b` and `c`,\n            // effectively calling `polynomial(0, 0, self.b, y, self.c)`.\n            #[call(polynomial)]\n            pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ;\n        }\n    }\n}\n```\n\n### Parameter modifiers\nYou can modify how will an input parameter be passed to the delegated method with parameter attribute modifiers. Currently, the following modifiers are supported:\n- `#[into]`: Calls `.into()` on the parameter passed to the delegated method.\n- `#[as_ref]`: Calls `.as_ref()` on the parameter passed to the delegated method.\n- `#[newtype]`: Accesses the first tuple element (`.0`) of the parameter passed to the delegated method.\n\n> Note that these modifiers might be removed in the future, try to use the more general `#[expr]` mechanism to achieve this functionality.\n\n```rust\nuse delegate::delegate;\n\nstruct InnerType {}\nimpl InnerType {\n    fn foo(&self, other: Self) {}\n}\n\nimpl From<Wrapper> for InnerType {\n    fn from(wrapper: Wrapper) -> Self {\n        wrapper.0\n    }\n}\n\nstruct Wrapper(InnerType);\nimpl Wrapper {\n    delegate! {\n        to self.0 {\n            // Calls `self.0.foo(other.into());`\n            pub fn foo(&self, #[into] other: Self);\n            // Calls `self.0.bar(other.0);`\n            pub fn bar(&self, #[newtype] other: Self);\n        }\n    }\n}\n```\n\n### Delegate associated functions\n```rust\nuse delegate::delegate;\n\nstruct A {}\nimpl A {\n    fn foo(a: u32) -> u32 {\n        a + 1\n    }\n}\n\nstruct B;\n\nimpl B {\n    delegate! {\n        to A {\n            fn foo(a: u32) -> u32;\n        }\n    }\n}\n\nassert_eq!(B::foo(1), 2);\n```\n\n### Delegate associated constants\n```rust\nuse delegate::delegate;\n\ntrait WithConst {\n    const TOTO: u8;\n}\n\nstruct A;\nimpl WithConst for A {\n    const TOTO: u8 = 1;\n}\n\nstruct B;\nimpl WithConst for B {\n    const TOTO: u8 = 2;\n}\nstruct C;\nimpl WithConst for C {\n    const TOTO: u8 = 2;\n}\n\nenum Enum {\n    A(A),\n    B(B),\n    C(C),\n}\n\nimpl Enum {\n    delegate! {\n        to match self {\n            Self::A(a) => a,\n            Self::B(b) => b,\n            Self::C(c) => { println!(\"hello from c\"); c },\n        } {\n            #[const(WithConst::TOTO)]\n            fn get_toto(&self) -> u8;\n        }\n    }\n}\n\nassert_eq!(Enum::A(A).get_toto(), <A as WithConst>::TOTO);\n```\n\n### Delegate to fields\n```rust\nuse delegate::delegate;\n\nstruct Datum {\n    value: u32,\n    error: u32,\n}\n\nstruct DatumWrapper(Datum);\n\nimpl DatumWrapper {\n    delegate! {\n        to self.0 {\n            /// Get the value of a nested field with the same name\n            #[field]\n            fn value(&self) -> u32;\n\n            /// Get the value of a nested field with a different name\n            #[field(value)]\n            fn renamed_value(&self) -> u32;\n\n            /// Get shared reference to a nested field\n            #[field(&value)]\n            fn value_ref(&self) -> &u32;\n\n            /// Get mutable reference to a nested field\n            #[field(&mut value)]\n            fn value_ref_mut(&mut self) -> &mut u32;\n\n            /// Get mutable reference to a nested field with the same name\n            #[field(&)]\n            fn error(&self) -> &u32;\n        }\n    }\n}\n```\n\n## Development\n\nThis project uses a standard test suite for quality control, as well as a set of\n\"expansion\" tests that utilize the `macrotest` crate to ensure the macro expands\nas expected. PRs implementing new features should add both standard and expansion\ntests where appropriate.\n\nTo add an expansion test, place a Rust source file in the `tests/expand/` directory\nwith methods demonstrating the new feature. Next, run `cargo test` to run the test\nsuite and generate a `*.expanded.rs` file in the same directory. Next, carefully\ninspect the contents of the generated file to confirm that all methods expanded as\nexpected. Finally, commit both files to the git repository. Future test suite runs\nwill now include expanding the source file and comparing it to the expanded file.\n\n## License\n\nLicensed under either of\n\n- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or\n  http://www.apache.org/licenses/LICENSE-2.0)\n- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\nat your option.\n\n## Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be\ndual licensed as above, without any additional terms or conditions.\n\n## Conduct\n\nPlease follow the [Rust Code of Conduct]. For escalation or moderation issues\nplease contact the crate author(s) listed in [`Cargo.toml`](./Cargo.toml).\n\n[Rust Code of Conduct]: https://www.rust-lang.org/conduct.html\n"
  },
  {
    "path": "src/attributes.rs",
    "content": "use proc_macro2::{Delimiter, TokenStream, TokenTree};\nuse quote::ToTokens;\nuse std::collections::VecDeque;\nuse std::ops::Not;\nuse syn::parse::ParseStream;\nuse syn::{Attribute, Error, Meta, Path, PathSegment, Token, TypePath};\n\npub struct CallMethodAttribute {\n    name: syn::Ident,\n}\n\nimpl syn::parse::Parse for CallMethodAttribute {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        Ok(CallMethodAttribute {\n            name: input.parse()?,\n        })\n    }\n}\n\n#[derive(Default, Clone)]\npub struct GetFieldAttribute {\n    reference: Option<(Token![&], Option<Token![mut]>)>,\n    member: Option<syn::Member>,\n}\n\nimpl GetFieldAttribute {\n    pub fn reference_tokens(&self) -> Option<TokenStream> {\n        let (ref_, mut_) = self.reference.as_ref()?;\n        let mut tokens = ref_.to_token_stream();\n        mut_.to_tokens(&mut tokens);\n        Some(tokens)\n    }\n}\n\nimpl syn::parse::Parse for GetFieldAttribute {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let mut reference = None;\n        if let Ok(ref_) = input.parse::<syn::Token![&]>() {\n            reference = Some((ref_, None));\n        }\n        if let Some((_, mut_)) = &mut reference {\n            *mut_ = input.parse::<syn::Token![mut]>().ok();\n        }\n        let member = input.is_empty().not().then(|| input.parse()).transpose()?;\n        Ok(GetFieldAttribute { reference, member })\n    }\n}\n\nstruct GenerateAwaitAttribute {\n    literal: syn::LitBool,\n}\n\nimpl syn::parse::Parse for GenerateAwaitAttribute {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        Ok(GenerateAwaitAttribute {\n            literal: input.parse()?,\n        })\n    }\n}\n\nstruct IntoAttribute {\n    type_path: Option<TypePath>,\n}\n\nimpl syn::parse::Parse for IntoAttribute {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let type_path: TypePath = input.parse().map_err(|error| {\n            Error::new(\n                input.span(),\n                format!(\"{error}\\nExpected type name, e.g. #[into(u32)]\"),\n            )\n        })?;\n\n        Ok(IntoAttribute {\n            type_path: Some(type_path),\n        })\n    }\n}\n\npub struct AssociatedConstant {\n    pub const_name: PathSegment,\n    pub trait_path: Path,\n}\n\nimpl syn::parse::Parse for AssociatedConstant {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let mut path = input.parse::<syn::Path>().map_err(|error| {\n            Error::new(\n                input.span(),\n                format!(\n                    \"{error}\\nExpected const path, e.g. #[const(path::to::MyTrait::CONST_NAME)]\"\n                ),\n            )\n        })?;\n\n        let const_name = path.segments.pop().ok_or_else(|| {\n            Error::new_spanned(\n                &path,\n                \"Expected a path. e.g. #[const(path::to::MyTrait::CONST_NAME)]\",\n            )\n        })?;\n        // poping a segment leads to trailing `::`\n        path.segments.pop_punct().ok_or_else(|| {\n            Error::new_spanned(\n                &path,\n                \"Expected a multipart path. e.g. #[const(path::to::MyTrait::CONST_NAME)]\",\n            )\n        })?;\n\n        Ok(Self {\n            const_name: const_name.into_value(),\n            trait_path: path,\n        })\n    }\n}\n\n#[derive(Clone)]\n/// Represent the placeholder `$` found inside an expr attribute's template\npub struct ExprPlaceHolder;\n\nimpl syn::parse::Parse for ExprPlaceHolder {\n    fn parse(input: ParseStream) -> syn::Result<Self> {\n        input.parse::<syn::Token![$]>()?;\n        Ok(Self)\n    }\n}\n\n/// Kind of allowed placeholders in an `expr` attribute template\n#[derive(Clone)]\nenum Placeholder {\n    ExprPlaceholder(ExprPlaceHolder),\n}\n\n#[derive(Clone)]\n/// Tokens found in the expr attribute's template\n/// Token are either\n/// - a replacable pattern (placeholder)\n/// - a normal token\n/// - a group containing a recursive representation of template tokens\nenum TemplateToken {\n    Normal(TokenTree),\n    Placeholder(Placeholder),\n    Group(Delimiter, TemplateExpr),\n}\n\nimpl TemplateToken {\n    /// Replace relevant placeholder tokens with the provided tokens\n    fn replace(&self, replacement: &TokenStream) -> TokenStream {\n        match self {\n            Self::Group(del, template) => {\n                let replaced_tokens = template\n                    .tokens\n                    .iter()\n                    .map(|token| token.replace(replacement));\n                proc_macro2::Group::new(*del, quote::quote! { #(#replaced_tokens)* })\n                    .to_token_stream()\n            }\n            Self::Normal(token_tree) => token_tree.to_token_stream(),\n            Self::Placeholder(_) => replacement.clone(),\n        }\n    }\n}\n\n#[derive(Clone)]\n/// An expr attribute's template\npub struct TemplateExpr {\n    tokens: Vec<TemplateToken>,\n}\n\nimpl syn::parse::Parse for TemplateExpr {\n    /// Parsing a template means storing the raw template while differenciating\n    /// placeholders and \"normal\" tokens\n    fn parse(input: ParseStream) -> syn::Result<Self> {\n        let mut tokens = Vec::new();\n        while !input.is_empty() {\n            if input.fork().parse::<ExprPlaceHolder>().is_ok() {\n                let placeholder = input.parse()?;\n                tokens.push(TemplateToken::Placeholder(Placeholder::ExprPlaceholder(\n                    placeholder,\n                )));\n                continue;\n            }\n\n            match input.parse()? {\n                TokenTree::Group(group) => {\n                    let inner_stream = group.stream();\n                    let inner_expr = syn::parse2(inner_stream)?;\n                    tokens.push(TemplateToken::Group(group.delimiter(), inner_expr));\n                }\n                other => {\n                    tokens.push(TemplateToken::Normal(other));\n                }\n            }\n        }\n\n        Ok(TemplateExpr { tokens })\n    }\n}\n\nimpl TemplateExpr {\n    /// returns the template after expanding the relevant placeholders\n    pub fn expand_template(&self, replacement: &TokenStream) -> TokenStream {\n        self.tokens.iter().fold(TokenStream::new(), |mut ts, tok| {\n            ts.extend(tok.replace(replacement));\n            ts\n        })\n    }\n}\n\npub struct TraitTarget {\n    type_path: TypePath,\n}\n\nimpl syn::parse::Parse for TraitTarget {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let type_path: TypePath = input.parse().map_err(|error| {\n            Error::new(\n                input.span(),\n                format!(\"{error}\\nExpected trait path, e.g. #[through(foo::MyTrait)]\"),\n            )\n        })?;\n\n        Ok(TraitTarget { type_path })\n    }\n}\n\n#[derive(Clone)]\npub enum ReturnExpression {\n    Into(Option<TypePath>),\n    TryInto,\n    Unwrap,\n}\n\npub enum TargetSpecifier {\n    Field(GetFieldAttribute),\n    Method(CallMethodAttribute),\n}\n\nimpl TargetSpecifier {\n    pub fn get_member(&self, default: &syn::Ident) -> syn::Member {\n        match self {\n            Self::Field(GetFieldAttribute {\n                member: Some(member),\n                ..\n            }) => member.clone(),\n            Self::Field(_) => default.clone().into(),\n            Self::Method(method) => method.name.clone().into(),\n        }\n    }\n}\n\nenum ParsedAttribute {\n    ReturnExpression(ReturnExpression),\n    Await(bool),\n    TargetSpecifier(TargetSpecifier),\n    ThroughTrait(TraitTarget),\n    ConstantAccess(AssociatedConstant),\n    Expr(TemplateExpr),\n}\n\nfn parse_attributes(\n    attrs: &[Attribute],\n) -> (\n    impl Iterator<Item = ParsedAttribute> + '_,\n    impl Iterator<Item = &Attribute>,\n) {\n    let (parsed, other): (Vec<_>, Vec<_>) = attrs\n        .iter()\n        .map(|attribute| {\n            let parsed = if let syn::AttrStyle::Outer = attribute.style {\n                let name = attribute\n                    .path()\n                    .get_ident()\n                    .map(|i| i.to_string())\n                    .unwrap_or_default();\n                match name.as_str() {\n                    \"call\" => {\n                        let target = attribute\n                            .parse_args::<CallMethodAttribute>()\n                            .expect(\"Cannot parse `call` attribute\");\n                        let spec = TargetSpecifier::Method(target);\n                        Some(ParsedAttribute::TargetSpecifier(spec))\n                    }\n                    \"field\" => {\n                        let target = if let syn::Meta::Path(_) = &attribute.meta {\n                            GetFieldAttribute::default()\n                        } else {\n                            attribute\n                                .parse_args::<GetFieldAttribute>()\n                                .expect(\"Cannot parse `field` attribute\")\n                        };\n                        let spec = TargetSpecifier::Field(target);\n                        Some(ParsedAttribute::TargetSpecifier(spec))\n                    }\n                    \"into\" => {\n                        let into = match &attribute.meta {\n                            Meta::NameValue(_) => {\n                                panic!(\"Cannot parse `into` attribute: expected parentheses\")\n                            }\n                            Meta::Path(_) => IntoAttribute { type_path: None },\n                            Meta::List(meta) => meta\n                                .parse_args::<IntoAttribute>()\n                                .expect(\"Cannot parse `into` attribute\"),\n                        };\n                        Some(ParsedAttribute::ReturnExpression(ReturnExpression::Into(\n                            into.type_path,\n                        )))\n                    }\n                    \"try_into\" => {\n                        if let Meta::List(meta) = &attribute.meta {\n                            meta.parse_nested_meta(|meta| {\n                                if meta.path.is_ident(\"unwrap\") {\n                                    panic!(\n                                        \"Replace #[try_into(unwrap)] with\\n#[try_into]\\n#[unwrap]\",\n                                    );\n                                }\n                                Ok(())\n                            })\n                            .expect(\"Invalid `try_into` arguments\");\n                        }\n                        Some(ParsedAttribute::ReturnExpression(ReturnExpression::TryInto))\n                    }\n                    \"unwrap\" => Some(ParsedAttribute::ReturnExpression(ReturnExpression::Unwrap)),\n                    \"await\" => {\n                        let generate = attribute\n                            .parse_args::<GenerateAwaitAttribute>()\n                            .expect(\"Cannot parse `await` attribute\");\n                        Some(ParsedAttribute::Await(generate.literal.value))\n                    }\n                    \"through\" => Some(ParsedAttribute::ThroughTrait(\n                        attribute\n                            .parse_args::<TraitTarget>()\n                            .expect(\"Cannot parse `through` attribute\"),\n                    )),\n                    \"const\" => Some(ParsedAttribute::ConstantAccess(\n                        attribute\n                            .parse_args::<AssociatedConstant>()\n                            .expect(\"Cannot parse `const` attribute\"),\n                    )),\n                    \"expr\" => Some(ParsedAttribute::Expr(\n                        attribute\n                            .parse_args::<TemplateExpr>()\n                            .expect(\"Cannot parse `expr` attribute\"),\n                    )),\n                    _ => None,\n                }\n            } else {\n                None\n            };\n\n            (parsed, attribute)\n        })\n        .partition(|(parsed, _)| parsed.is_some());\n    (\n        parsed.into_iter().map(|(parsed, _)| parsed.unwrap()),\n        other.into_iter().map(|(_, attr)| attr),\n    )\n}\n\npub struct MethodAttributes<'a> {\n    pub attributes: Vec<&'a Attribute>,\n    pub target_specifier: Option<TargetSpecifier>,\n    pub expressions: VecDeque<ReturnExpression>,\n    pub generate_await: Option<bool>,\n    pub target_trait: Option<TypePath>,\n    pub associated_constant: Option<AssociatedConstant>,\n    pub expr_attr: Option<TemplateExpr>,\n}\n\n/// Iterates through the attributes of a method and filters special attributes.\n/// - call => sets the name of the target method to call\n/// - into => generates a `into()` call after the delegated expression\n/// - try_into => generates a `try_into()` call after the delegated expression\n/// - await => generates an `.await` expression after the delegated expression\n/// - unwrap => generates a `unwrap()` call after the delegated expression\n/// - through => generates a UFCS call (`Target::method(&<expr>, ...)`) around the delegated expression\n/// - const => generates a getter to a trait associated constant\npub fn parse_method_attributes<'a>(\n    attrs: &'a [Attribute],\n    method: &syn::TraitItemFn,\n) -> MethodAttributes<'a> {\n    let mut target_spec: Option<TargetSpecifier> = None;\n    let mut expressions: Vec<ReturnExpression> = vec![];\n    let mut generate_await: Option<bool> = None;\n    let mut target_trait: Option<TraitTarget> = None;\n    let mut associated_constant: Option<AssociatedConstant> = None;\n    let mut expr_attr: Option<TemplateExpr> = None;\n\n    let (parsed, other) = parse_attributes(attrs);\n    for attr in parsed {\n        match attr {\n            ParsedAttribute::ReturnExpression(expr) => expressions.push(expr),\n            ParsedAttribute::Await(value) => {\n                if generate_await.is_some() {\n                    panic!(\n                        \"Multiple `await` attributes specified for {}\",\n                        method.sig.ident\n                    )\n                }\n                generate_await = Some(value);\n            }\n            ParsedAttribute::TargetSpecifier(spec) => {\n                if target_spec.is_some() {\n                    panic!(\n                        \"Multiple field/call attributes specified for {}\",\n                        method.sig.ident\n                    )\n                }\n                target_spec = Some(spec);\n            }\n            ParsedAttribute::ThroughTrait(target) => {\n                if target_trait.is_some() {\n                    panic!(\n                        \"Multiple through attributes specified for {}\",\n                        method.sig.ident\n                    )\n                }\n                target_trait = Some(target);\n            }\n            ParsedAttribute::ConstantAccess(const_attr) => {\n                if associated_constant.is_some() {\n                    panic!(\n                        \"Multiple const attributes specified for {}\",\n                        method.sig.ident\n                    )\n                }\n                associated_constant = Some(const_attr);\n            }\n            ParsedAttribute::Expr(token_tree) => {\n                if expr_attr.is_some() {\n                    panic!(\n                        \"Multiple expr attributes specified for {}\",\n                        method.sig.ident\n                    )\n                }\n                expr_attr = Some(token_tree);\n            }\n        }\n    }\n\n    if associated_constant.is_some() && target_spec.is_some() {\n        panic!(\"Cannot use both `call`/`field` and `const` attributes.\");\n    }\n\n    MethodAttributes {\n        attributes: other.into_iter().collect(),\n        target_specifier: target_spec,\n        generate_await,\n        expressions: expressions.into(),\n        target_trait: target_trait.map(|t| t.type_path),\n        associated_constant,\n        expr_attr,\n    }\n}\n\npub struct SegmentAttributes {\n    pub expressions: Vec<ReturnExpression>,\n    pub generate_await: Option<bool>,\n    pub target_trait: Option<TypePath>,\n    pub other_attrs: Vec<Attribute>,\n    pub expr_attr: Option<TemplateExpr>,\n}\n\npub fn parse_segment_attributes(attrs: &[Attribute]) -> SegmentAttributes {\n    let mut expressions: Vec<ReturnExpression> = vec![];\n    let mut generate_await: Option<bool> = None;\n    let mut target_trait: Option<TraitTarget> = None;\n    let mut expr_attr: Option<TemplateExpr> = None;\n\n    let (parsed, other) = parse_attributes(attrs);\n\n    for attribute in parsed {\n        match attribute {\n            ParsedAttribute::ReturnExpression(expr) => expressions.push(expr),\n            ParsedAttribute::Await(value) => {\n                if generate_await.is_some() {\n                    panic!(\"Multiple `await` attributes specified for segment\");\n                }\n                generate_await = Some(value);\n            }\n            ParsedAttribute::ThroughTrait(target) => {\n                if target_trait.is_some() {\n                    panic!(\"Multiple `through` attributes specified for segment\");\n                }\n                target_trait = Some(target);\n            }\n            ParsedAttribute::TargetSpecifier(_) => {\n                panic!(\"Field/call attribute cannot be specified on a `to <expr>` segment.\");\n            }\n            ParsedAttribute::ConstantAccess(_) => {\n                panic!(\"Const attribute cannot be specified on a `to <expr>` segment.\");\n            }\n            ParsedAttribute::Expr(token_tree) => {\n                if expr_attr.is_some() {\n                    panic!(\"Multiple `expr` attributes specified for segment\");\n                }\n                expr_attr = Some(token_tree);\n            }\n        }\n    }\n    SegmentAttributes {\n        expressions,\n        generate_await,\n        target_trait: target_trait.map(|t| t.type_path),\n        other_attrs: other.cloned().collect::<Vec<_>>(),\n        expr_attr,\n    }\n}\n\n/// Applies default values from the segment and adds them to the method attributes.\npub fn combine_attributes<'a>(\n    mut method_attrs: MethodAttributes<'a>,\n    segment_attrs: &'a SegmentAttributes,\n) -> MethodAttributes<'a> {\n    let SegmentAttributes {\n        expressions,\n        generate_await,\n        target_trait,\n        other_attrs,\n        expr_attr,\n    } = segment_attrs;\n\n    if method_attrs.generate_await.is_none() {\n        method_attrs.generate_await = *generate_await;\n    }\n\n    if method_attrs.target_trait.is_none() {\n        method_attrs.target_trait.clone_from(target_trait);\n    }\n\n    if method_attrs.expr_attr.is_none() {\n        method_attrs.expr_attr.clone_from(expr_attr);\n    }\n\n    for expr in expressions {\n        match expr {\n            ReturnExpression::Into(path) => {\n                if !method_attrs\n                    .expressions\n                    .iter()\n                    .any(|expr| matches!(expr, ReturnExpression::Into(_)))\n                {\n                    method_attrs\n                        .expressions\n                        .push_front(ReturnExpression::Into(path.clone()));\n                }\n            }\n            _ => method_attrs.expressions.push_front(expr.clone()),\n        }\n    }\n\n    for other_attr in other_attrs {\n        if !method_attrs\n            .attributes\n            .iter()\n            .any(|attr| attr.path().get_ident() == other_attr.path().get_ident())\n        {\n            method_attrs.attributes.push(other_attr);\n        }\n    }\n\n    method_attrs\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "//! This crate removes some boilerplate for structs that simply delegate\n//! some of their methods to one or more of their fields.\n//!\n//! It gives you the `delegate!` macro, which delegates method calls to selected expressions (usually inner fields).\n//!\n//! ## Features:\n//! - Delegate to a method with a different name\n//! ```rust\n//! use delegate::delegate;\n//!\n//! struct Stack { inner: Vec<u32> }\n//! impl Stack {\n//!     delegate! {\n//!         to self.inner {\n//!             #[call(push)]\n//!             pub fn add(&mut self, value: u32);\n//!         }\n//!     }\n//! }\n//! ```\n//! - Use an arbitrary inner field expression\n//! ```rust\n//! use delegate::delegate;\n//!\n//! use std::rc::Rc;\n//! use std::cell::RefCell;\n//! use std::ops::Deref;\n//!\n//! struct Wrapper { inner: Rc<RefCell<Vec<u32>>> }\n//! impl Wrapper {\n//!     delegate! {\n//!         to self.inner.deref().borrow_mut() {\n//!             pub fn push(&mut self, val: u32);\n//!         }\n//!     }\n//! }\n//! ```\n//!\n//! - Delegate to enum variants\n//!\n//! ```rust\n//! use delegate::delegate;\n//!\n//! enum Enum {\n//!     A(A),\n//!     B(B),\n//!     C { v: C },\n//! }\n//!\n//! struct A {\n//!     val: usize,\n//! }\n//!\n//! impl A {\n//!     fn dbg_inner(&self) -> usize {\n//!         dbg!(self.val);\n//!         1\n//!     }\n//! }\n//! struct B {\n//!     val_a: String,\n//! }\n//!\n//! impl B {\n//!     fn dbg_inner(&self) -> usize {\n//!         dbg!(self.val_a.clone());\n//!         2\n//!     }\n//! }\n//!\n//! struct C {\n//!     val_c: f64,\n//! }\n//!\n//! impl C {\n//!     fn dbg_inner(&self) -> usize {\n//!         dbg!(self.val_c);\n//!         3\n//!     }\n//! }\n//!\n//! impl Enum {\n//!     delegate! {\n//!         // transformed to\n//!         //\n//!         // ```rust\n//!         // match self {\n//!         //     Enum::A(a) => a.dbg_inner(),\n//!         //     Enum::B(b) => { println!(\"i am b\"); b }.dbg_inner(),\n//!         //     Enum::C { v: c } => { c }.dbg_inner(),\n//!         // }\n//!         // ```\n//!         to match self {\n//!             Enum::A(a) => a,\n//!             Enum::B(b) => { println!(\"i am b\"); b },\n//!             Enum::C { v: c } => { c },\n//!         } {\n//!             fn dbg_inner(&self) -> usize;\n//!         }\n//!     }\n//! }\n//! ```\n//!\n//! - Use modifiers that alter the generated method body\n//! ```rust\n//! use delegate::delegate;\n//! struct Inner;\n//! impl Inner {\n//!     pub fn method(&self, num: u32) -> u32 { num }\n//!     pub fn method_res(&self, num: u32) -> Result<u32, ()> { Ok(num) }\n//! }\n//! struct Wrapper { inner: Inner }\n//! impl Wrapper {\n//!     delegate! {\n//!         to self.inner {\n//!             // calls method, converts result to u64 using `From`\n//!             #[into]\n//!             pub fn method(&self, num: u32) -> u64;\n//!\n//!             // calls method, returns ()\n//!             #[call(method)]\n//!             pub fn method_noreturn(&self, num: u32);\n//!\n//!             // calls method, converts result to i6 using `TryFrom`\n//!             #[try_into]\n//!             #[call(method)]\n//!             pub fn method2(&self, num: u32) -> Result<u16, std::num::TryFromIntError>;\n//!\n//!             // calls method_res, unwraps the result\n//!             #[unwrap]\n//!             pub fn method_res(&self, num: u32) -> u32;\n//!\n//!             // calls method_res, unwraps the result, then calls into\n//!             #[unwrap]\n//!             #[into]\n//!             #[call(method_res)]\n//!             pub fn method_res_into(&self, num: u32) -> u64;\n//!\n//!             // specify explicit type for into\n//!             #[into(u64)]\n//!             #[call(method)]\n//!             pub fn method_into_explicit(&self, num: u32) -> u64;\n//!         }\n//!     }\n//! }\n//! ```\n//!\n//! - Custom called expression\n//!\n//! 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.\n//!\n//! _Note:_ the `$` placeholder isn't required and can be present multiple times if you want.\n//!\n//! ```rs\n//! struct A(Vec<u8>);\n//!\n//! impl A {\n//!     delegate! {\n//!         to self.0 {\n//!             #[expr(*$.unwrap())]\n//!             /// Here `$` == `self.0.get(idx)`\n//!             /// Will expand to `*self.0.get(idx).unwrap()`\n//!             fn get(&self, idx: usize) -> u8;\n//!\n//!             #[call(get)]\n//!             #[expr($?.checked_pow(2))]\n//!             /// Here `$` == `self.0.get(idx)`\n//!             /// Will expand to `self.0.get(idx)?.checked_pow(2)`\n//!             fn get_checked_pow_2(&self, idx: usize) -> Option<u8>;\n//!         }\n//!     }\n//! }\n//! ```\n//!\n//! - Call `await` on async functions\n//! ```rust\n//! use delegate::delegate;\n//!\n//! struct Inner;\n//! impl Inner {\n//!     pub async fn method(&self, num: u32) -> u32 { num }\n//! }\n//! struct Wrapper { inner: Inner }\n//! impl Wrapper {\n//!     delegate! {\n//!         to self.inner {\n//!             // calls method(num).await, returns impl Future<Output = u32>\n//!             pub async fn method(&self, num: u32) -> u32;\n//!\n//!             // calls method(num).await.into(), returns impl Future<Output = u64>\n//!             #[into]\n//!             #[call(method)]\n//!             pub async fn method_into(&self, num: u32) -> u64;\n//!         }\n//!     }\n//! }\n//! ```\n//! You can use the `#[await(true/false)]` attribute on delegated methods to specify if `.await` should\n//! be generated after the delegated expression. It will be generated by default if the delegated\n//! method is `async`.\n//! - Delegate to multiple fields\n//! ```rust\n//! use delegate::delegate;\n//!\n//! struct MultiStack {\n//!     left: Vec<u32>,\n//!     right: Vec<u32>,\n//! }\n//! impl MultiStack {\n//!     delegate! {\n//!         to self.left {\n//!             // Push an item to the top of the left stack\n//!             #[call(push)]\n//!             pub fn push_left(&mut self, value: u32);\n//!         }\n//!         to self.right {\n//!             // Push an item to the top of the right stack\n//!             #[call(push)]\n//!             pub fn push_right(&mut self, value: u32);\n//!         }\n//!     }\n//! }\n//! ```\n//! - Inserts `#[inline(always)]` automatically (unless you specify `#[inline]` manually on the method)\n//! - You can use an attribute on a whole segment to automatically apply it to all methods in that\n//!   segment:\n//! ```rust\n//! use delegate::delegate;\n//!\n//! struct Inner;\n//!\n//! impl Inner {\n//!   fn foo(&self) -> Result<u32, ()> { Ok(0) }\n//!   fn bar(&self) -> Result<u32, ()> { Ok(1) }\n//! }\n//!\n//! struct Wrapper { inner: Inner }\n//!\n//! impl Wrapper {\n//!   delegate! {\n//!     #[unwrap]\n//!     to self.inner {\n//!       fn foo(&self) -> u32; // calls self.inner.foo().unwrap()\n//!       fn bar(&self) -> u32; // calls self.inner.bar().unwrap()\n//!     }\n//!   }\n//! }\n//! ```\n//! - Specify expressions in the signature that will be used as delegated arguments\n//! ```rust\n//! use delegate::delegate;\n//! struct Inner;\n//! impl Inner {\n//!     pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 {\n//!         a + x * x + b * y + c\n//!     }\n//! }\n//! struct Wrapper { inner: Inner, a: i32, b: i32, c: i32 }\n//! impl Wrapper {\n//!     delegate! {\n//!         to self.inner {\n//!             // Calls `polynomial` on `inner` with `self.a`, `self.b` and\n//!             // `self.c` passed as arguments `a`, `b`, and `c`, effectively\n//!             // calling `polynomial(self.a, x, self.b, y, self.c)`.\n//!             pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ;\n//!             // Calls `polynomial` on `inner` with `0`s passed for arguments\n//!             // `a` and `x`, and `self.b` and `self.c` for `b` and `c`,\n//!             // effectively calling `polynomial(0, 0, self.b, y, self.c)`.\n//!             #[call(polynomial)]\n//!             pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ;\n//!         }\n//!     }\n//! }\n//! ```\n//! - Modify how will an input parameter be passed to the delegated method with parameter attribute modifiers.\n//!   Currently, the following modifiers are supported:\n//!     - `#[into]`: Calls `.into()` on the parameter passed to the delegated method.\n//!     - `#[as_ref]`: Calls `.as_ref()` on the parameter passed to the delegated method.\n//!     - `#[newtype]`: Calls `.0` on the parameter passed to the delegated method.\n//! ```rust\n//! use delegate::delegate;\n//!\n//! struct InnerType {}\n//! impl InnerType {\n//!     fn foo(&self, other: Self) {}\n//! }\n//!\n//! impl From<Wrapper> for InnerType {\n//!     fn from(wrapper: Wrapper) -> Self {\n//!         wrapper.0\n//!     }\n//! }\n//!\n//! struct Wrapper(InnerType);\n//! impl Wrapper {\n//!     delegate! {\n//!         to self.0 {\n//!             // Calls `self.0.foo(other.into());`\n//!             pub fn foo(&self, #[into] other: Self);\n//!         }\n//!     }\n//! }\n//! ```\n//! - Specify a trait through which will the delegated method be called\n//!   (using [UFCS](https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls).\n//! ```rust\n//! use delegate::delegate;\n//!\n//! struct InnerType {}\n//! impl InnerType {\n//!     \n//! }\n//!\n//! trait MyTrait {\n//!   fn foo(&self);\n//! }\n//! impl MyTrait for InnerType {\n//!   fn foo(&self) {}\n//! }\n//!\n//! struct Wrapper(InnerType);\n//! impl Wrapper {\n//!     delegate! {\n//!         to &self.0 {\n//!             // Calls `MyTrait::foo(&self.0)`\n//!             #[through(MyTrait)]\n//!             pub fn foo(&self);\n//!         }\n//!     }\n//! }\n//! ```\n//!\n//! - Add additional arguments to method\n//!\n//!  ```rust\n//!  use delegate::delegate;\n//!  use std::cell::OnceCell;\n//!  struct Inner(u32);\n//!  impl Inner {\n//!      pub fn new(m: u32) -> Self {\n//!          // some \"very complex\" constructing work\n//!          Self(m)\n//!      }\n//!      pub fn method(&self, n: u32) -> u32 {\n//!          self.0 + n\n//!      }\n//!  }\n//!  \n//!  struct Wrapper {\n//!      inner: OnceCell<Inner>,\n//!  }\n//!  \n//!  impl Wrapper {\n//!      pub fn new() -> Self {\n//!          Self {\n//!              inner: OnceCell::new(),\n//!          }\n//!      }\n//!      fn content(&self, val: u32) -> &Inner {\n//!          self.inner.get_or_init(|| Inner(val))\n//!      }\n//!      delegate! {\n//!          to |k: u32| self.content(k) {\n//!              // `wrapper.method(k, num)` will call `self.content(k).method(num)`\n//!              pub fn method(&self, num: u32) -> u32;\n//!          }\n//!      }\n//!  }\n//!  ```\n//! - Delegate associated functions\n//!   ```rust\n//!   use delegate::delegate;\n//!\n//!   struct A {}\n//!   impl A {\n//!       fn foo(a: u32) -> u32 {\n//!           a + 1\n//!       }\n//!   }\n//!\n//!   struct B;\n//!\n//!   impl B {\n//!       delegate! {\n//!           to A {\n//!               fn foo(a: u32) -> u32;\n//!           }\n//!       }\n//!   }\n//!\n//!   assert_eq!(B::foo(1), 2);\n//!   ```\n//! - Delegate associated constants\n//!\n//! ```rust\n//! use delegate::delegate;\n//!\n//! trait WithConst {\n//!     const TOTO: u8;\n//! }\n//!\n//! struct A;\n//! impl WithConst for A {\n//!     const TOTO: u8 = 1;\n//! }\n//!\n//! struct B;\n//! impl WithConst for B {\n//!     const TOTO: u8 = 2;\n//! }\n//! struct C;\n//! impl WithConst for C {\n//!     const TOTO: u8 = 2;\n//! }\n//!\n//! enum Enum {\n//!     A(A),\n//!     B(B),\n//!     C(C),\n//! }\n//!\n//! impl Enum {\n//!     delegate! {\n//!         to match self {\n//!             Self::A(a) => a,\n//!             Self::B(b) => b,\n//!             Self::C(c) => { println!(\"hello from c\"); c },\n//!         } {\n//!             #[const(WithConst::TOTO)]\n//!             fn get_toto(&self) -> u8;\n//!         }\n//!     }\n//! }\n//!\n//! assert_eq!(Enum::A(A).get_toto(), <A as WithConst>::TOTO);\n//! ```\n//!\n//! - Delegate to fields\n//! ```rust\n//! use delegate::delegate;\n//!\n//! struct Datum {\n//!     value: u32,\n//!     error: u32,\n//! }\n//!\n//! struct DatumWrapper(Datum);\n//!\n//! impl DatumWrapper {\n//!     delegate! {\n//!         to self.0 {\n//!             /// Get the value of a nested field with the same name\n//!             #[field]\n//!             fn value(&self) -> u32;\n//!\n//!             /// Get the value of a nested field with a different name\n//!             #[field(value)]\n//!             fn renamed_value(&self) -> u32;\n//!\n//!             /// Get shared reference to a nested field\n//!             #[field(&value)]\n//!             fn value_ref(&self) -> &u32;\n//!\n//!             /// Get mutable reference to a nested field\n//!             #[field(&mut value)]\n//!             fn value_ref_mut(&mut self) -> &mut u32;\n//!\n//!             /// Get mutable reference to a nested field with the same name\n//!             #[field(&)]\n//!             fn error(&self) -> &u32;\n//!         }\n//!     }\n//! }\n//! ```\n\nextern crate proc_macro;\nuse std::mem;\n\nuse attributes::AssociatedConstant;\nuse proc_macro::TokenStream;\n\nuse proc_macro2::Ident;\nuse quote::{quote, ToTokens};\nuse syn::parse::{Parse, ParseStream};\nuse syn::spanned::Spanned;\nuse syn::visit_mut::VisitMut;\nuse syn::{parse_quote, Error, Expr, ExprField, ExprMethodCall, FnArg, GenericParam, Meta};\n\nuse crate::attributes::{\n    combine_attributes, parse_method_attributes, parse_segment_attributes, ReturnExpression,\n    SegmentAttributes, TargetSpecifier,\n};\n\nmod attributes;\n\nmod kw {\n    syn::custom_keyword!(to);\n    syn::custom_keyword!(target);\n}\n\n#[derive(Clone)]\nenum ArgumentModifier {\n    Into,\n    AsRef,\n    Newtype,\n}\n\n#[derive(Clone)]\nenum DelegatedInput {\n    Input {\n        parameter: syn::FnArg,\n        modifier: Option<ArgumentModifier>,\n    },\n    Argument(syn::Expr),\n}\n\nfn get_argument_modifier(attribute: syn::Attribute) -> Result<ArgumentModifier, Error> {\n    if let Meta::Path(mut path) = attribute.meta {\n        if path.segments.len() == 1 {\n            let segment = path.segments.pop().unwrap();\n            if segment.value().arguments.is_empty() {\n                let ident = segment.value().ident.to_string();\n                let ident = ident.as_str();\n\n                match ident {\n                    \"into\" => return Ok(ArgumentModifier::Into),\n                    \"as_ref\" => return Ok(ArgumentModifier::AsRef),\n                    \"newtype\" => return Ok(ArgumentModifier::Newtype),\n                    _ => (),\n                }\n            }\n        }\n    };\n\n    panic!(\"The attribute argument has to be `into` or `as_ref`, like this: `#[into] a: u32`.\")\n}\n\nimpl syn::parse::Parse for DelegatedInput {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let lookahead = input.lookahead1();\n        if lookahead.peek(syn::token::Bracket) {\n            let content;\n            let _bracket_token = syn::bracketed!(content in input);\n            let expression: syn::Expr = content.parse()?;\n            Ok(Self::Argument(expression))\n        } else {\n            let (input, modifier) = if lookahead.peek(syn::token::Pound) {\n                let mut attributes = input.call(tolerant_outer_attributes)?;\n                if attributes.len() > 1 {\n                    panic!(\"You can specify at most a single attribute for each parameter in a delegated method\");\n                }\n                let modifier = get_argument_modifier(attributes.pop().unwrap())\n                    .expect(\"Could not parse argument modifier attribute\");\n\n                let input: syn::FnArg = input.parse()?;\n                (input, Some(modifier))\n            } else {\n                (input.parse()?, None)\n            };\n\n            Ok(Self::Input {\n                parameter: input,\n                modifier,\n            })\n        }\n    }\n}\n\nstruct DelegatedMethod {\n    method: syn::TraitItemFn,\n    attributes: Vec<syn::Attribute>,\n    visibility: syn::Visibility,\n    arguments: syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>,\n}\n\n// Given an input parameter from a function signature, create a function\n// argument used to call the delegate function: omit receiver, extract an\n// identifier from a typed input parameter (and wrap it in an `Expr`).\nfn parse_input_into_argument_expression(\n    function_name: &Ident,\n    input: &syn::FnArg,\n) -> Option<syn::Expr> {\n    match input {\n        // Parse inputs of the form `x: T` to retrieve their identifiers.\n        syn::FnArg::Typed(typed) => {\n            match &*typed.pat {\n                // This should not happen, I think. If it does,\n                // it will be ignored as if it were the\n                // receiver.\n                syn::Pat::Ident(ident) if ident.ident == \"self\" => None,\n                // Expression in the form `x: T`. Extract the\n                // identifier, wrap it in Expr for type compatibility with bracketed expressions,\n                // and append it\n                // to the argument list.\n                syn::Pat::Ident(ident) => {\n                    let path_segment = syn::PathSegment {\n                        ident: ident.ident.clone(),\n                        arguments: syn::PathArguments::None,\n                    };\n                    let mut segments = syn::punctuated::Punctuated::new();\n                    segments.push(path_segment);\n                    let path = syn::Path {\n                        leading_colon: None,\n                        segments,\n                    };\n                    let ident_as_expr = syn::Expr::from(syn::ExprPath {\n                        attrs: Vec::new(),\n                        qself: None,\n                        path,\n                    });\n                    Some(ident_as_expr)\n                }\n                // Other more complex argument expressions are not covered.\n                _ => panic!(\n                    \"You have to use simple identifiers for delegated method parameters ({})\",\n                    function_name // The signature is not constructed yet. We make due.\n                ),\n            }\n        }\n        // Skip any `self`/`&self`/`&mut self` argument, since\n        // it does not appear in the argument list and it's\n        // already added to the parameter list.\n        syn::FnArg::Receiver(_receiver) => None,\n    }\n}\n\nimpl syn::parse::Parse for DelegatedMethod {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let attributes = input.call(tolerant_outer_attributes)?;\n        let visibility = input.call(syn::Visibility::parse)?;\n\n        // Unchanged from Parse from TraitItemMethod\n        let constness: Option<syn::Token![const]> = input.parse()?;\n        let asyncness: Option<syn::Token![async]> = input.parse()?;\n        let unsafety: Option<syn::Token![unsafe]> = input.parse()?;\n        let abi: Option<syn::Abi> = input.parse()?;\n        let fn_token: syn::Token![fn] = input.parse()?;\n        let ident: Ident = input.parse()?;\n        let generics: syn::Generics = input.parse()?;\n\n        let content;\n        let paren_token = syn::parenthesized!(content in input);\n\n        // Parse inputs (method parameters) and arguments. The parameters\n        // constitute the parameter list of the signature of the delegating\n        // method so it must include all inputs, except bracketed expressions.\n        // The argument list constitutes the list of arguments used to call the\n        // delegated function. It must include all inputs, excluding the\n        // receiver (self-type) input. The arguments must all be parsed to\n        // retrieve the expressions inside of the brackets as well as variable\n        // identifiers of ordinary inputs. The arguments must preserve the order\n        // of the inputs.\n        let delegated_inputs = content.parse_terminated(DelegatedInput::parse, syn::Token![,])?;\n        let mut inputs: syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]> =\n            syn::punctuated::Punctuated::new();\n        let mut arguments: syn::punctuated::Punctuated<syn::Expr, syn::Token![,]> =\n            syn::punctuated::Punctuated::new();\n\n        // First, combine the cases for pairs with cases for end, to remove\n        // redundancy below.\n        delegated_inputs\n            .into_pairs()\n            .map(|punctuated_pair| match punctuated_pair {\n                syn::punctuated::Pair::Punctuated(item, comma) => (item, Some(comma)),\n                syn::punctuated::Pair::End(item) => (item, None),\n            })\n            .for_each(|pair| match pair {\n                // This input is a bracketed argument (eg. `[ self.x ]`). It\n                // is omitted in the signature of the delegator, but the\n                // expression inside the brackets is used in the body of the\n                // delegator, as an arugnment to the delegated function (eg.\n                // `self.x`). The argument needs to be generated in the\n                // appropriate position with respect other arguments and non-\n                // argument inputs. As long as inputs are added to the\n                // `arguments` vector in order of occurance, this is trivial.\n                (DelegatedInput::Argument(argument), maybe_comma) => {\n                    arguments.push_value(argument);\n                    if let Some(comma) = maybe_comma {\n                        arguments.push_punct(comma)\n                    }\n                }\n                // The input is a standard function parameter with a name and\n                // a type (eg. `x: T`). This input needs to be reflected in\n                // the delegator signature as is (eg. `x: T`). The identifier\n                // also needs to be included in the argument list in part\n                // (eg. `x`). The argument list needs to preserve the order of\n                // the inputs with relation to arguments (see above), so the\n                // parsing is best done here (previously it was done at\n                // generation).\n                (\n                    DelegatedInput::Input {\n                        parameter,\n                        modifier,\n                    },\n                    maybe_comma,\n                ) => {\n                    inputs.push_value(parameter.clone());\n                    if let Some(comma) = maybe_comma {\n                        inputs.push_punct(comma);\n                    }\n                    let maybe_argument = parse_input_into_argument_expression(&ident, &parameter);\n                    if let Some(mut argument) = maybe_argument {\n                        let span = argument.span();\n\n                        if let Some(modifier) = modifier {\n                            let method_call = |name: &str| {\n                                syn::Expr::from(ExprMethodCall {\n                                    attrs: vec![],\n                                    receiver: Box::new(argument.clone()),\n                                    dot_token: Default::default(),\n                                    method: Ident::new(name, span),\n                                    turbofish: None,\n                                    paren_token,\n                                    args: Default::default(),\n                                })\n                            };\n\n                            let field_call = || {\n                                syn::Expr::from(ExprField {\n                                    attrs: vec![],\n                                    base: Box::new(argument.clone()),\n                                    dot_token: Default::default(),\n                                    member: syn::Member::Unnamed(0.into()),\n                                })\n                            };\n\n                            match modifier {\n                                ArgumentModifier::Into => {\n                                    argument = method_call(\"into\");\n                                }\n                                ArgumentModifier::AsRef => {\n                                    argument = method_call(\"as_ref\");\n                                }\n                                ArgumentModifier::Newtype => argument = field_call(),\n                            }\n                        }\n\n                        arguments.push(argument);\n                        if let Some(comma) = maybe_comma {\n                            arguments.push_punct(comma);\n                        }\n                    }\n                }\n            });\n\n        // Unchanged from Parse from TraitItemMethod\n        let output: syn::ReturnType = input.parse()?;\n        let where_clause: Option<syn::WhereClause> = input.parse()?;\n\n        // This needs to be generated manually, because inputs need to be\n        // separated into actual inputs that go in the signature (the\n        // parameters) and the additional expressions in square brackets which\n        // go into the arguments vector (artguments of the call on the method\n        // on the inner object).\n        let signature = syn::Signature {\n            constness,\n            asyncness,\n            unsafety,\n            abi,\n            fn_token,\n            ident,\n            paren_token,\n            inputs,\n            output,\n            variadic: None,\n            generics: syn::Generics {\n                where_clause,\n                ..generics\n            },\n        };\n\n        // Check if the input contains a semicolon or a brace. If it contains\n        // a semicolon, we parse it (to retain token location information) and\n        // continue. However, if it contains a brace, this indicates that\n        // there is a default definition of the method. This is not supported,\n        // so in that case we error out.\n        let lookahead = input.lookahead1();\n        let semi_token: Option<syn::Token![;]> = if lookahead.peek(syn::Token![;]) {\n            Some(input.parse()?)\n        } else {\n            panic!(\n                \"Do not include implementation of delegated functions ({})\",\n                signature.ident\n            );\n        };\n\n        // This needs to be populated from scratch because of the signature above.\n        let method = syn::TraitItemFn {\n            // All attributes are attached to `DelegatedMethod`, since they\n            // presumably pertain to the process of delegation, not the\n            // signature of the delegator.\n            attrs: Vec::new(),\n            sig: signature,\n            default: None,\n            semi_token,\n        };\n\n        Ok(DelegatedMethod {\n            method,\n            attributes,\n            visibility,\n            arguments,\n        })\n    }\n}\n\nstruct DelegatedSegment {\n    delegator: syn::Expr,\n    methods: Vec<DelegatedMethod>,\n    segment_attrs: SegmentAttributes,\n}\n\nimpl syn::parse::Parse for DelegatedSegment {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let attributes = input.call(tolerant_outer_attributes)?;\n        let segment_attrs = parse_segment_attributes(&attributes);\n\n        if let Ok(keyword) = input.parse::<kw::target>() {\n            return Err(Error::new(keyword.span(), \"You are using the old `target` expression, which is deprecated. Please replace `target` with `to`.\"));\n        } else {\n            input.parse::<kw::to>()?;\n        }\n\n        syn::Expr::parse_without_eager_brace(input).and_then(|delegator| {\n            let content;\n            syn::braced!(content in input);\n\n            let mut methods = vec![];\n            while !content.is_empty() {\n                methods.push(\n                    content\n                        .parse::<DelegatedMethod>()\n                        .expect(\"Cannot parse delegated method\"),\n                );\n            }\n\n            Ok(DelegatedSegment {\n                delegator,\n                methods,\n                segment_attrs,\n            })\n        })\n    }\n}\n\nstruct DelegationBlock {\n    segments: Vec<DelegatedSegment>,\n}\n\nimpl syn::parse::Parse for DelegationBlock {\n    fn parse(input: ParseStream) -> Result<Self, Error> {\n        let mut segments = vec![];\n        while !input.is_empty() {\n            segments.push(input.parse()?);\n        }\n\n        Ok(DelegationBlock { segments })\n    }\n}\n\n/// Returns true if there are any `inline` attributes in the input.\nfn has_inline_attribute(attrs: &[&syn::Attribute]) -> bool {\n    attrs.iter().any(|attr| {\n        if let syn::AttrStyle::Outer = attr.style {\n            attr.path().is_ident(\"inline\")\n        } else {\n            false\n        }\n    })\n}\n\nstruct MatchVisitor<F>(F);\n\nimpl<F: Fn(&Expr) -> proc_macro2::TokenStream> VisitMut for MatchVisitor<F> {\n    fn visit_arm_mut(&mut self, arm: &mut syn::Arm) {\n        let transformed = self.0(&arm.body);\n        arm.body = parse_quote!(#transformed);\n    }\n}\n\n#[proc_macro]\npub fn delegate(tokens: TokenStream) -> TokenStream {\n    let block: DelegationBlock = syn::parse_macro_input!(tokens);\n    let sections = block.segments.iter().map(|delegator| {\n        let delegated_expr = &delegator.delegator;\n        let functions = delegator.methods.iter().map(|method| {\n            let input = &method.method;\n            let mut signature = input.sig.clone();\n            if let Expr::Closure(closure) = delegated_expr {\n                let additional_inputs: Vec<FnArg> = closure\n                    .inputs\n                    .iter()\n                    .map(|input| {\n                        if let syn::Pat::Type(pat_type) = input {\n                            syn::parse_quote!(#pat_type)\n                        } else {\n                            panic!(\n                                \"Use a type pattern (`a: u32`) for delegation closure arguments\"\n                            );\n                        }\n                    })\n                    .collect();\n                let mut origin_inputs = mem::take(&mut signature.inputs).into_iter();\n                // When delegating methods, `first_input` should be self or similar receivers\n                // Then we need to move it to first\n                // When delegating associated methods, it may be a trivial argument or does not even exist\n                // We just keep the origin order.\n                let first_input = origin_inputs.next();\n                match first_input {\n                    Some(FnArg::Receiver(receiver)) => {\n                        signature.inputs.push(FnArg::Receiver(receiver));\n                        signature.inputs.extend(additional_inputs);\n                    }\n                    Some(first_input) => {\n                        signature.inputs.extend(additional_inputs);\n                        signature.inputs.push(first_input);\n                    }\n                    _ => {\n                        signature.inputs.extend(additional_inputs);\n                    }\n                }\n                signature.inputs.extend(origin_inputs);\n            }\n            let attributes = parse_method_attributes(&method.attributes, input);\n            let attributes = combine_attributes(attributes, &delegator.segment_attrs);\n            if input.default.is_some() {\n                panic!(\n                    \"Do not include implementation of delegated functions ({})\",\n                    signature.ident\n                );\n            }\n\n            // Generate an argument vector from Punctuated list.\n            let args: Vec<Expr> = method.arguments.clone().into_iter().collect();\n\n            // Get name (or index) of the target method or field\n            let name = match &attributes.target_specifier {\n                Some(target) => target.get_member(&input.sig.ident),\n                None => input.sig.ident.clone().into(),\n            };\n\n            let inline = if has_inline_attribute(&attributes.attributes) {\n                quote!()\n            } else {\n                quote! { #[inline] }\n            };\n            let visibility = &method.visibility;\n\n            let is_method = method.method.sig.receiver().is_some();\n            let associated_const = &attributes.associated_constant;\n            let expr_attr = &attributes.expr_attr;\n\n            // Use the body of a closure (like `|k: u32| <body>`) as the delegation expression\n            let delegated_body = if let Expr::Closure(closure) = delegated_expr {\n                &closure.body\n            } else {\n                delegated_expr\n            };\n\n            let span = input.span();\n            let generate_await = attributes\n                .generate_await\n                .unwrap_or_else(|| method.method.sig.asyncness.is_some());\n\n            // fn method<'a, A, B> -> method::<A, B>\n            let generic_params = &method.method.sig.generics.params;\n            let generics = if generic_params.is_empty() {\n                quote::quote! {}\n            } else {\n                let span = generic_params.span();\n                let mut params: syn::punctuated::Punctuated<\n                    proc_macro2::TokenStream,\n                    syn::Token![,],\n                > = syn::punctuated::Punctuated::new();\n                for param in generic_params.iter() {\n                    let token = match param {\n                        GenericParam::Lifetime(_) => {\n                            // Do not pass lifetimes to generic arguments explicitly to avoid\n                            // things like https://doc.rust-lang.org/error_codes/E0794.html\n                            // See https://github.com/Kobzol/rust-delegate/issues/85.\n                            continue;\n                        }\n                        GenericParam::Type(t) => {\n                            let token = &t.ident;\n                            let span = t.span();\n                            quote::quote_spanned! {span=> #token }\n                        }\n                        GenericParam::Const(c) => {\n                            let token = &c.ident;\n                            let span = c.span();\n                            quote::quote_spanned! {span=> #token }\n                        }\n                    };\n                    params.push(token);\n                }\n                quote::quote_spanned! {span=> ::<#params> }\n            };\n\n            let modify_expr = |expr: &Expr| {\n                let body = if let Some(target_trait) = &attributes.target_trait {\n                    quote::quote! { #target_trait::#name#generics(#expr, #(#args),*) }\n                } else if let Some(AssociatedConstant {\n                    const_name,\n                    trait_path,\n                }) = associated_const\n                {\n                    let return_type = &signature.output;\n                    quote::quote! {{\n                        const fn get_const<T: #trait_path>(t: &T) #return_type {\n                            <T as #trait_path>::#const_name\n                        }\n                        get_const(#expr)\n                    }}\n                } else if is_method {\n                    match &attributes.target_specifier {\n                        None | Some(TargetSpecifier::Method(_)) => {\n                            quote::quote! { #expr.#name#generics(#(#args),*) }\n                        }\n                        Some(TargetSpecifier::Field(target)) => {\n                            let reference = target.reference_tokens();\n                            quote::quote! { #reference#expr.#name }\n                        }\n                    }\n                } else {\n                    quote::quote! { #expr::#name#generics(#(#args),*) }\n                };\n\n                let mut body = if generate_await {\n                    quote::quote! { #body.await }\n                } else {\n                    body\n                };\n\n                for expression in &attributes.expressions {\n                    match expression {\n                        ReturnExpression::Into(type_name) => {\n                            body = match type_name {\n                                Some(name) => {\n                                    quote::quote! { ::core::convert::Into::<#name>::into(#body) }\n                                }\n                                None => quote::quote! { ::core::convert::Into::into(#body) },\n                            };\n                        }\n                        ReturnExpression::TryInto => {\n                            body = quote::quote! { ::core::convert::TryInto::try_into(#body) };\n                        }\n                        ReturnExpression::Unwrap => {\n                            body = quote::quote! { #body.unwrap() };\n                        }\n                    }\n                }\n                body\n            };\n            let mut body = if let Expr::Match(expr_match) = delegated_body {\n                let mut expr_match = expr_match.clone();\n                MatchVisitor(modify_expr).visit_expr_match_mut(&mut expr_match);\n                expr_match.into_token_stream()\n            } else {\n                modify_expr(delegated_body)\n            };\n\n            if let syn::ReturnType::Default = &signature.output {\n                body = quote::quote! { #body; };\n            };\n\n            if let Some(expr_template) = expr_attr {\n                body = expr_template.expand_template(&body);\n            }\n\n            let attrs = &attributes.attributes;\n            quote::quote_spanned! {span=>\n                #(#attrs)*\n                #inline\n                #visibility #signature {\n                    #body\n                }\n            }\n        });\n\n        quote! { #(#functions)* }\n    });\n\n    let result = quote! {\n        #(#sections)*\n    };\n    result.into()\n}\n\n// we cannot use `Attributes::parse_outer` directly, because it does not allow keywords to appear\n// in meta path positions, i.e., it does not accept `#[await(true)]`.\n// related issue: https://github.com/dtolnay/syn/issues/1458\nfn tolerant_outer_attributes(input: ParseStream) -> syn::Result<Vec<syn::Attribute>> {\n    use proc_macro2::{Delimiter, TokenTree};\n    use syn::{\n        bracketed,\n        ext::IdentExt,\n        parse::discouraged::Speculative,\n        token::{Brace, Bracket, Paren},\n        AttrStyle, Attribute, ExprLit, Lit, MacroDelimiter, MetaList, MetaNameValue, Path, Result,\n        Token,\n    };\n\n    fn tolerant_attr(input: ParseStream) -> Result<Attribute> {\n        let content;\n        Ok(Attribute {\n            pound_token: input.parse()?,\n            style: AttrStyle::Outer,\n            bracket_token: bracketed!(content in input),\n            meta: content.call(tolerant_meta)?,\n        })\n    }\n\n    // adapted from `impl Parse for Meta`\n    fn tolerant_meta(input: ParseStream) -> Result<Meta> {\n        // Try to parse as Meta\n        if let Ok(meta) = input.call(Meta::parse) {\n            Ok(meta)\n        } else {\n            // If it's not possible, try to parse it as any identifier, to support #[await]\n            let path = Path::from(input.call(Ident::parse_any)?);\n            if input.peek(Paren) || input.peek(Bracket) || input.peek(Brace) {\n                // adapted from the private `syn::attr::parse_meta_after_path`\n                input.step(|cursor| {\n                    if let Some((TokenTree::Group(g), rest)) = cursor.token_tree() {\n                        let span = g.delim_span();\n                        let delimiter = match g.delimiter() {\n                            Delimiter::Parenthesis => MacroDelimiter::Paren(Paren(span)),\n                            Delimiter::Brace => MacroDelimiter::Brace(Brace(span)),\n                            Delimiter::Bracket => MacroDelimiter::Bracket(Bracket(span)),\n                            Delimiter::None => {\n                                return Err(cursor.error(\"expected delimiter\"));\n                            }\n                        };\n                        Ok((\n                            Meta::List(MetaList {\n                                path,\n                                delimiter,\n                                tokens: g.stream(),\n                            }),\n                            rest,\n                        ))\n                    } else {\n                        Err(cursor.error(\"expected delimiter\"))\n                    }\n                })\n            } else if input.peek(Token![=]) {\n                // adapted from the private `syn::attr::parse_meta_name_value_after_path`\n                let eq_token = input.parse()?;\n                let ahead = input.fork();\n                let value = match ahead.parse::<Option<Lit>>()? {\n                    // this branch is probably for speeding up the parsing for doc comments etc.\n                    Some(lit) if ahead.is_empty() => {\n                        input.advance_to(&ahead);\n                        Expr::Lit(ExprLit {\n                            attrs: Vec::new(),\n                            lit,\n                        })\n                    }\n                    _ => input.parse()?,\n                };\n                Ok(Meta::NameValue(MetaNameValue {\n                    path,\n                    eq_token,\n                    value,\n                }))\n            } else {\n                Ok(Meta::Path(path))\n            }\n        }\n    }\n\n    let mut attrs = Vec::new();\n    while input.peek(Token![#]) {\n        attrs.push(input.call(tolerant_attr)?);\n    }\n    Ok(attrs)\n}\n"
  },
  {
    "path": "tests/argument_modifier.rs",
    "content": "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(&self, x: Self) {}\n}\n\nimpl From<MyNewU32> for u32 {\n    fn from(value: MyNewU32) -> Self {\n        value.0\n    }\n}\n\nimpl Foo for MyNewU32 {\n    delegate! {\n        to self.0 {\n            fn bar(&self, #[into] x: Self);\n        }\n    }\n}\n\nstruct Bar {\n    foo: String,\n}\n\nimpl<T> PartialEq<T> for Bar\nwhere\n    T: AsRef<str> + ?Sized,\n{\n    delegate! {\n        to self.foo {\n            fn eq(&self, #[as_ref] other: &T) -> bool;\n        }\n    }\n}\n\nstruct Baz(Vec<u32>);\n\nimpl Baz {\n    delegate! {\n        to self.0 {\n            fn extend(&mut self, #[newtype] other: Baz);\n        }\n    }\n}\n"
  },
  {
    "path": "tests/associated_const_delegation.rs",
    "content": "extern crate delegate;\nuse delegate::delegate;\n\n#[test]\nfn test_delegate_constant() {\n    trait WithConst {\n        const TOTO: u8;\n    }\n\n    struct A;\n    impl WithConst for A {\n        const TOTO: u8 = 1;\n    }\n\n    struct B;\n    impl WithConst for B {\n        const TOTO: u8 = 2;\n    }\n    struct C;\n    impl WithConst for C {\n        const TOTO: u8 = 2;\n    }\n\n    enum Enum {\n        A(A),\n        B(B),\n        C(C),\n    }\n\n    impl Enum {\n        delegate! {\n            to match self {\n                Self::A(a) => a,\n                Self::B(b) => b,\n                Self::C(c) => { println!(\"hello from c\"); c },\n            } {\n                #[const(WithConst::TOTO)]\n                fn get_toto(&self) -> u8;\n            }\n        }\n    }\n\n    let a = Enum::A(A);\n    assert_eq!(a.get_toto(), <A as WithConst>::TOTO);\n    let b = Enum::B(B);\n    assert_eq!(b.get_toto(), <B as WithConst>::TOTO);\n    let c = Enum::C(C);\n    assert_eq!(c.get_toto(), <C as WithConst>::TOTO);\n}\n\n#[test]\nfn multiple_consts() {\n    trait Foo {\n        const A: u32;\n        const B: u32;\n    }\n\n    struct A;\n    impl Foo for A {\n        const A: u32 = 1;\n        const B: u32 = 2;\n    }\n\n    struct Wrapper(A);\n    impl Wrapper {\n        delegate! {\n            to &self.0 {\n                #[const(Foo::A)]\n                fn a(&self) -> u32;\n\n                #[const(Foo::B)]\n                fn b(&self) -> u32;\n            }\n        }\n    }\n\n    let wrapper = Wrapper(A);\n    assert_eq!(wrapper.a(), <A as Foo>::A);\n    assert_eq!(wrapper.b(), <A as Foo>::B);\n}\n"
  },
  {
    "path": "tests/async_await.rs",
    "content": "extern crate delegate;\n\nuse delegate::delegate;\nuse std::future::Future;\nuse std::pin::Pin;\nuse std::task::{Context, Poll};\n\n#[test]\nfn test_async_await() {\n    struct Inner;\n    impl Inner {\n        pub async fn method(&self, num: u32) -> u32 {\n            num\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                pub(crate) async fn method(&self, num: u32) -> u32;\n\n                #[call(method)]\n                pub(crate) async fn unit(&self, num: u32);\n\n                #[into]\n                #[call(method)]\n                pub(crate) async fn with_into(&self, num: u32) -> u64;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(::futures::executor::block_on(wrapper.method(3)), 3);\n    assert_eq!(::futures::executor::block_on(wrapper.unit(3)), ());\n    assert_eq!(::futures::executor::block_on(wrapper.with_into(3)), 3_u64);\n}\n\n#[test]\nfn test_async_trait() {\n    use async_trait::async_trait;\n\n    #[async_trait]\n    trait Inner {\n        async fn method(&self, num: u32) -> u32;\n    }\n\n    struct InnerImpl;\n    #[async_trait]\n    impl Inner for InnerImpl {\n        async fn method(&self, num: u32) -> u32 {\n            num\n        }\n    }\n\n    struct Wrapper<T> {\n        inner: T,\n    }\n\n    impl<T: Inner> Wrapper<T> {\n        delegate! {\n            to self.inner {\n                pub(crate) async fn method(&self, num: u32) -> u32;\n\n                #[call(method)]\n                pub(crate) async fn unit(&self, num: u32);\n\n                #[into]\n                #[call(method)]\n                pub(crate) async fn with_into(&self, num: u32) -> u64;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: InnerImpl };\n\n    assert_eq!(::futures::executor::block_on(wrapper.method(3)), 3);\n    assert_eq!(::futures::executor::block_on(wrapper.unit(3)), ());\n    assert_eq!(::futures::executor::block_on(wrapper.with_into(3)), 3_u64);\n}\n\n#[test]\nfn test_bridge_async_to_sync() {\n    struct UserRepo;\n    impl UserRepo {\n        fn foo(&self) {}\n    }\n\n    struct SharedRepo(tokio::sync::Mutex<UserRepo>);\n\n    impl SharedRepo {\n        delegate! {\n            to self.0.lock().await {\n                #[await(false)]\n                async fn foo(&self);\n            }\n        }\n    }\n}\n\n#[test]\nfn test_bridge_sync_to_async() {\n    struct Fut;\n    impl Future for Fut {\n        type Output = u32;\n\n        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n            todo!()\n        }\n    }\n\n    struct UserRepo;\n    impl UserRepo {\n        fn foo(&self) -> Fut {\n            Fut\n        }\n    }\n\n    struct SharedRepo(UserRepo);\n\n    impl SharedRepo {\n        delegate! {\n            to self.0 {\n                #[await(true)]\n                async fn foo(&self) -> u32;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "tests/closure.rs",
    "content": "use delegate::delegate;\nuse std::cell::OnceCell;\n\n#[test]\nfn test_delegate_closure() {\n    struct Inner(u32);\n    impl Inner {\n        fn method(&self, n: u32) -> u32 {\n            self.0 + n\n        }\n\n        fn method2(&self, n: u32) -> u32 {\n            self.0 - n\n        }\n    }\n\n    struct Wrapper {\n        inner: OnceCell<Inner>,\n    }\n\n    impl Wrapper {\n        pub fn new() -> Self {\n            Self {\n                inner: OnceCell::new(),\n            }\n        }\n        fn content(&self, val: u32) -> &Inner {\n            self.inner.get_or_init(|| Inner(val))\n        }\n        delegate! {\n            to |k: u32| self.content(k) {\n                pub fn method(&self, num: u32) -> u32;\n                pub fn method2(&self, num: u32) -> u32;\n            }\n        }\n    }\n\n    let wrapper = Wrapper::new();\n    assert_eq!(wrapper.method(1, 2), 3);\n    assert_eq!(wrapper.method2(1, 1), 0);\n    assert_eq!(wrapper.method(1, 3), 4);\n    assert_eq!(wrapper.method2(1, 0), 1);\n}\n\n#[test]\nfn test_delegate_closure_associated_function() {\n    struct Inner;\n    impl Inner {\n        fn method(n: u32) -> u32 {\n            n + 1\n        }\n\n        fn method2(n: u32) -> u32 {\n            n - 1\n        }\n    }\n\n    struct Wrapper;\n\n    impl Wrapper {\n        // Doesn't really make sense, but should compile\n        delegate! {\n            to |k: u32| Inner {\n                pub fn method(num: u32) -> u32;\n                pub fn method2(num: u32) -> u32;\n            }\n        }\n    }\n\n    assert_eq!(Wrapper::method(1, 2), 3);\n    assert_eq!(Wrapper::method2(1, 1), 0);\n    assert_eq!(Wrapper::method(1, 3), 4);\n    assert_eq!(Wrapper::method(1, 0), 1);\n}\n"
  },
  {
    "path": "tests/delegate_to_enum.rs",
    "content": "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    fn dbg_inner(&self) -> usize {\n        dbg!(self.val);\n        1\n    }\n\n    fn into_num(&self) -> u8 {\n        1\n    }\n}\nstruct B {\n    val_a: String,\n}\n\nimpl B {\n    fn dbg_inner(&self) -> usize {\n        dbg!(self.val_a.clone());\n        2\n    }\n\n    fn into_num(&self) -> u64 {\n        2\n    }\n}\n\nstruct C {\n    val_c: f64,\n}\n\nimpl C {\n    fn dbg_inner(&self) -> usize {\n        dbg!(self.val_c);\n        3\n    }\n\n    fn into_num(&self) -> usize {\n        3\n    }\n}\n\nimpl Enum {\n    delegate! {\n        to match self {\n            Enum::A(a) => a,\n            Enum::B(b) => { println!(\"i am b\"); b },\n            Enum::C { v: c } => { c },\n        } {\n            fn dbg_inner(&self) -> usize;\n\n            #[into]\n            fn into_num(&self) -> IntoUsize;\n        }\n    }\n}\n\n#[derive(Eq, PartialEq, Debug)]\nstruct IntoUsize(usize);\n\nimpl From<usize> for IntoUsize {\n    fn from(value: usize) -> Self {\n        Self(value)\n    }\n}\nimpl From<u64> for IntoUsize {\n    fn from(value: u64) -> Self {\n        Self(value as usize)\n    }\n}\nimpl From<u8> for IntoUsize {\n    fn from(value: u8) -> Self {\n        Self(value as usize)\n    }\n}\n\n#[test]\nfn test_delegate_enum_method() {\n    let a = Enum::A(A { val: 1 });\n    assert_eq!(a.dbg_inner(), 1);\n    let b = Enum::B(B {\n        val_a: \"a\".to_string(),\n    });\n    assert_eq!(b.dbg_inner(), 2);\n    let c = Enum::C {\n        v: C { val_c: 1.0 },\n    };\n    assert_eq!(c.dbg_inner(), 3);\n}\n\n#[test]\nfn test_delegate_enum_into() {\n    let a = Enum::A(A { val: 1 });\n    assert_eq!(a.into_num(), IntoUsize(1));\n    let b = Enum::B(B {\n        val_a: \"\".to_string(),\n    });\n    assert_eq!(b.into_num(), IntoUsize(2));\n    let c = Enum::C {\n        v: C { val_c: 0.0 },\n    };\n    assert_eq!(c.into_num(), IntoUsize(3));\n}\n"
  },
  {
    "path": "tests/delegation.rs",
    "content": "use delegate::delegate;\n\n#[test]\nfn test_expansions() {\n    macrotest::expand(\"tests/expand/*.rs\");\n}\n\n#[test]\nfn test_delegation() {\n    struct Inner;\n\n    impl Inner {\n        fn fun_generic<S: Copy>(self, s: S) -> S {\n            s\n        }\n        fn fun1(self, a: u32, b: u32) -> u32 {\n            a + b\n        }\n        fn fun2(mut self, a: u32, b: u32) -> u32 {\n            a + b\n        }\n        fn fun3(&self, a: u32, b: u32) -> u32 {\n            a + b\n        }\n        fn fun4(&mut self, a: u32, b: u32) -> u32 {\n            a + b\n        }\n        fn fun5(self: Self, a: u32, b: u32) -> u32 {\n            a + b\n        }\n        fn fun6(mut self: Self, a: u32, b: u32) -> u32 {\n            a + b\n        }\n    }\n\n    struct Outer {\n        inner: Inner,\n        inner2: Inner,\n    }\n\n    impl Outer {\n        pub fn new() -> Outer {\n            Outer {\n                inner: Inner,\n                inner2: Inner,\n            }\n        }\n\n        delegate! {\n            to self.inner {\n                fn fun_generic<S: Copy>(self, s: S) -> S;\n                fn fun1(self, a: u32, b: u32) -> u32;\n                fn fun2(mut self, a: u32, b: u32) -> u32;\n                fn fun3(&self, a: u32, b: u32) -> u32;\n            }\n            to self.inner2 {\n                fn fun4(&mut self, a: u32, b: u32) -> u32;\n                fn fun5(self: Self, a: u32, b: u32) -> u32;\n                fn fun6(mut self: Self, a: u32, b: u32) -> u32;\n            }\n        }\n    }\n\n    assert_eq!(Outer::new().fun_generic(5), 5);\n    assert_eq!(Outer::new().fun1(1, 2), 3);\n    assert_eq!(Outer::new().fun2(1, 2), 3);\n    assert_eq!(Outer::new().fun3(1, 2), 3);\n    assert_eq!(Outer::new().fun4(1, 2), 3);\n    assert_eq!(Outer::new().fun5(1, 2), 3);\n    assert_eq!(Outer::new().fun6(1, 2), 3);\n}\n\n#[test]\nfn test_delegate_self() {\n    trait Foo {\n        fn foo(&self) -> u32;\n    }\n\n    struct S;\n\n    impl S {\n        fn foo(&self) -> u32 {\n            1\n        }\n    }\n\n    impl Foo for S {\n        delegate! {\n            to self {\n                fn foo(&self) -> u32;\n            }\n        }\n    }\n\n    let s = S;\n    assert_eq!(Foo::foo(&s), 1);\n}\n\n#[test]\nfn test_delegate_tuple() {\n    trait Foo {\n        fn foo(&self) -> u32;\n    }\n\n    struct S;\n    impl S {\n        fn foo(&self) -> u32 {\n            1\n        }\n    }\n\n    struct T(S);\n\n    impl Foo for T {\n        delegate! {\n            to self.0 {\n                fn foo(&self) -> u32;\n            }\n        }\n    }\n\n    let s = S;\n    let t = T(s);\n    assert_eq!(Foo::foo(&t), 1);\n}\n"
  },
  {
    "path": "tests/expand/fields.expanded.rs",
    "content": "use delegate::delegate;\nstruct Datum {\n    value: u32,\n    error: u32,\n    xy: (f32, f32),\n}\nstruct DatumWrapper(Datum);\nimpl DatumWrapper {\n    fn get_inner(&self) -> &Datum {\n        &self.0\n    }\n    /// Expands to `self.0.value`\n    #[inline]\n    fn value(&self) -> u32 {\n        self.0.value\n    }\n    /// Expands to `self.0.value`\n    #[inline]\n    fn renamed_value(&self) -> u32 {\n        self.0.value\n    }\n    /// Expands to `&self.0.value`\n    #[inline]\n    fn renamed_value_ref(&self) -> &u32 {\n        &self.0.value\n    }\n    /// Expands to `&mut self.0.value`\n    #[inline]\n    fn renamed_value_ref_mut(&mut self) -> &mut u32 {\n        &mut self.0.value\n    }\n    /// Expands to `&self.0.error` (demonstrates `&` without a field name)\n    #[inline]\n    fn error(&self) -> &u32 {\n        &self.0.error\n    }\n    /// Expands to `self.0.xy.0` (demonstrates unnamed field access by value)\n    #[inline]\n    fn x(&self) -> f32 {\n        self.0.xy.0\n    }\n    /// Expands to `&self.0.xy.1` (demonstrates unnamed field access by reference)\n    #[inline]\n    fn y(&self) -> &f32 {\n        &self.0.xy.1\n    }\n    /// Expands to `&self.get_inner().value`\n    #[inline]\n    fn value_ref_via_get_inner(&self) -> &u32 {\n        &self.get_inner().value\n    }\n}\n"
  },
  {
    "path": "tests/expand/fields.rs",
    "content": "\nuse delegate::delegate;\n\nstruct Datum {\n    value: u32,\n    error: u32,\n    xy: (f32, f32)\n}\n\nstruct DatumWrapper(Datum);\n\nimpl DatumWrapper {\n    fn get_inner(&self) -> &Datum {\n        &self.0\n    }\n    delegate! {\n        to self.0 {\n            /// Expands to `self.0.value`\n            #[field]\n            fn value(&self) -> u32;\n\n            /// Expands to `self.0.value`\n            #[field(value)]\n            fn renamed_value(&self) -> u32;\n\n            /// Expands to `&self.0.value`\n            #[field(&value)]\n            fn renamed_value_ref(&self) -> &u32;\n\n            /// Expands to `&mut self.0.value`\n            #[field(&mut value)]\n            fn renamed_value_ref_mut(&mut self) -> &mut u32;\n\n            /// Expands to `&self.0.error` (demonstrates `&` without a field name)\n            #[field(&)]\n            fn error(&self) -> &u32;\n        }\n        to self.0.xy {\n            /// Expands to `self.0.xy.0` (demonstrates unnamed field access by value)\n            #[field(0)]\n            fn x(&self) -> f32;\n            /// Expands to `&self.0.xy.1` (demonstrates unnamed field access by reference)\n            #[field(&1)]\n            fn y(&self) -> &f32;\n        }\n        to self.get_inner() {\n            /// Expands to `&self.get_inner().value`\n            #[field(&value)]\n            fn value_ref_via_get_inner(&self) -> &u32;\n        }\n    }\n}\n"
  },
  {
    "path": "tests/expr.rs",
    "content": "use delegate::delegate;\nuse std::sync::Mutex;\n\nstruct Inner;\nimpl Inner {\n    pub fn method(&self, num: u32) -> u32 {\n        num\n    }\n    pub fn method2(&self, num: u32) -> u32 {\n        num\n    }\n}\n\nstruct Wrapper {\n    inner: Mutex<Inner>,\n}\n\nfn global_fn() -> Inner {\n    Inner\n}\n\nimpl Wrapper {\n    delegate! {\n        to self.inner.lock().unwrap() {\n            pub(crate) fn method(&self, num: u32) -> u32;\n        }\n        to global_fn() {\n            pub(crate) fn method2(&self, num: u32) -> u32;\n        }\n    }\n}\n\n#[test]\nfn test_mutex() {\n    let wrapper = Wrapper {\n        inner: Mutex::new(Inner),\n    };\n\n    assert_eq!(wrapper.method(3), 3);\n    assert_eq!(wrapper.method2(3), 3);\n}\n\n#[test]\nfn test_index() {\n    struct Inner;\n    impl Inner {\n        pub fn method(&self, num: u32) -> u32 {\n            num\n        }\n    }\n\n    struct Wrapper {\n        index: usize,\n        items: Vec<Inner>,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.items[self.index] {\n                fn method(&self, num: u32) -> u32;\n            }\n        }\n    }\n\n    let wrapper = Wrapper {\n        index: 0,\n        items: vec![Inner],\n    };\n\n    assert_eq!(wrapper.method(3), 3);\n}\n"
  },
  {
    "path": "tests/expr_attribute.rs",
    "content": "extern crate delegate;\nuse delegate::delegate;\n\n#[test]\nfn delegate_with_custom_expr() {\n    struct A(Vec<u8>);\n\n    impl A {\n        delegate! {\n            to self.0 {\n                #[expr(*$.unwrap())]\n                fn get(&self, idx: usize) -> u8;\n\n                #[call(get)]\n                #[expr($?.checked_pow(2))]\n                fn get_checked_pow_2(&self, idx: usize) -> Option<u8>;\n            }\n        }\n    }\n\n    let a = A(vec![2, 3, 4, 5]);\n\n    assert_eq!(a.get(0), 2);\n    assert_eq!(a.get_checked_pow_2(0), Some(4));\n\n    // out-of-bounds behavior\n    assert!(std::panic::catch_unwind(|| a.get(4)).is_err());\n    assert_eq!(a.get_checked_pow_2(4), None);\n}\n\n#[test]\nfn delegate_without_placeholder() {\n    struct A(Vec<u8>);\n\n    impl A {\n        delegate! {\n            to self.0 {\n                #[expr(Some(\"test\"))]\n                fn get_name(&self) -> Option<&'static str>;\n            }\n        }\n    }\n\n    let a = A(vec![2, 3, 4, 5]);\n\n    assert_eq!(a.get_name(), Some(\"test\"));\n}\n"
  },
  {
    "path": "tests/fields.rs",
    "content": "use delegate::delegate;\n\nstruct Datum {\n    value: u32,\n    error: u32,\n    xy: (f32, f32),\n}\n\nstruct DatumWrapper(Datum);\n\nimpl DatumWrapper {\n    fn get_inner(&self) -> &Datum {\n        &self.0\n    }\n    delegate! {\n        to self.0 {\n            /// Expands to `self.0.value`\n            #[field]\n            fn value(&self) -> u32;\n\n            /// Expands to `self.0.value`\n            #[field(value)]\n            fn renamed_value(&self) -> u32;\n\n            /// Expands to `&self.0.value`\n            #[field(&value)]\n            fn renamed_value_ref(&self) -> &u32;\n\n            /// Expands to `&mut self.0.value`\n            #[field(&mut value)]\n            fn renamed_value_ref_mut(&mut self) -> &mut u32;\n\n            /// Expands to `&self.0.error` (demonstrates `&` without a field name)\n            #[field(&)]\n            fn error(&self) -> &u32;\n        }\n        to self.0.xy {\n            /// Expands to `self.0.xy.0` (demonstrates unnamed field access by value)\n            #[field(0)]\n            fn x(&self) -> f32;\n            /// Expands to `&self.0.xy.1` (demonstrates unnamed field access by reference)\n            #[field(&1)]\n            fn y(&self) -> &f32;\n        }\n        to self.get_inner() {\n            /// Expands to `&self.get_inner().value`\n            #[field(&value)]\n            fn value_ref_via_get_inner(&self) -> &u32;\n        }\n    }\n}\n\n#[test]\nfn test_fields() {\n    let mut wrapper = DatumWrapper(Datum {\n        value: 1,\n        error: 2,\n        xy: (3.0, 4.0),\n    });\n    assert_eq!(wrapper.value(), wrapper.0.value);\n    assert_eq!(wrapper.renamed_value(), wrapper.0.value);\n    assert_eq!(wrapper.renamed_value_ref(), &wrapper.0.value);\n    assert_eq!(wrapper.renamed_value_ref_mut(), &mut 1);\n    assert_eq!(wrapper.value_ref_via_get_inner(), &1);\n    assert_eq!(wrapper.error(), &wrapper.0.error);\n    assert_eq!(wrapper.x(), wrapper.0.xy.0);\n    assert_eq!(wrapper.y(), &wrapper.0.xy.1);\n}\n"
  },
  {
    "path": "tests/function.rs",
    "content": "use delegate::delegate;\n\n#[test]\nfn test_delegate_function() {\n    struct A {}\n    impl A {\n        fn foo(a: u32) -> u32 {\n            a + 1\n        }\n    }\n\n    struct B;\n\n    impl B {\n        delegate! {\n            to A {\n                fn foo(a: u32) -> u32;\n            }\n        }\n    }\n\n    assert_eq!(B::foo(1), 2);\n}\n"
  },
  {
    "path": "tests/generic.rs",
    "content": "use delegate::delegate;\nuse std::collections::HashSet;\nuse std::hash::Hash;\n\n#[test]\nfn test_generics_method() {\n    struct Foo;\n    impl Foo {\n        fn foo<'a, P, X>(&self) {}\n    }\n\n    struct Bar(Foo);\n    impl Bar {\n        delegate! {\n            to &self.0 {\n                fn foo<'a, P, X>(&self);\n            }\n        }\n    }\n}\n\n#[test]\nfn test_generics_function() {\n    struct Foo;\n    impl Foo {\n        fn foo<P, X>() {}\n    }\n\n    struct Bar(Foo);\n    impl Bar {\n        delegate! {\n            to Foo {\n                fn foo<P, X>();\n            }\n        }\n    }\n}\n\n#[test]\nfn test_generics_through_trait() {\n    trait A {\n        fn f<P>(&self) -> u32;\n    }\n\n    struct Foo;\n\n    impl A for Foo {\n        fn f<P>(&self) -> u32 {\n            0\n        }\n    }\n\n    struct Bar(Foo);\n\n    impl Bar {\n        delegate! {\n            to &self.0 {\n                #[through(A)]\n                fn f<P>(&self) -> u32;\n            }\n        }\n    }\n\n    let bar = Bar(Foo);\n    assert_eq!(bar.f::<u32>(), 0);\n}\n\n#[test]\nfn test_generics_complex() {\n    struct Foo;\n    impl Foo {\n        fn foo<'a: 'static, X: Copy, #[allow(unused)] T>(&self) {}\n    }\n\n    struct Bar(Foo);\n    impl Bar {\n        delegate! {\n            to &self.0 {\n                fn foo<'a: 'static, X: Copy, #[allow(unused)] T>(&self);\n            }\n        }\n    }\n}\n\n#[test]\nfn test_lifetime_late_bound() {\n    trait QSet<T>\n    where\n        T: PartialEq,\n    {\n        fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T>\n        where\n            Self: Sized,\n            T: 'a;\n    }\n\n    impl<T: Eq + Hash> QSet<T> for HashSet<T> {\n        delegate! {\n            to self {\n                #[through(HashSet)]\n                fn iter<'a>(&'a self) -> impl Iterator<Item = &T>\n                where\n                    Self: Sized, T: 'a;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "tests/in_macro_expansion.rs",
    "content": "///\n/// Tests that a macro can expand into a delegate block,\n/// where the target comes from a macro variable.\n///\nuse delegate::delegate;\n\ntrait Trait {\n    fn method_to_delegate(&self) -> bool;\n}\n\nstruct Struct1();\nimpl Trait for Struct1 {\n    fn method_to_delegate(&self) -> bool {\n        true\n    }\n}\n\nstruct Struct2(pub Struct1);\n\n// We use a macro to impl 'Trait' for 'Struct2' such that\n// the target is a variable in the macro.\nmacro_rules! some_macro {\n    (|$self:ident| $delegate_to:expr) => {\n        impl Trait for Struct2 {\n            delegate! {\n                // '$delegate_to' will expand to 'self.0' before ´delegate!' is expanded.\n                to $delegate_to {\n                    fn method_to_delegate(&$self) -> bool;\n                }\n            }\n        }\n    };\n}\nsome_macro! { |self | self.0 }\n\n#[test]\nfn test() {\n    assert!(Struct2(Struct1()).method_to_delegate());\n}\n"
  },
  {
    "path": "tests/inline_args.rs",
    "content": "use delegate::delegate;\n\n#[test]\nfn test_inline_args() {\n    struct Inner;\n\n    impl Inner {\n        fn fun_generic<S: Copy>(self, s: S) -> S {\n            s\n        }\n        fn fun0(self) -> u32 {\n            42\n        }\n        fn fun1(self, a: u32) -> u32 {\n            a\n        }\n        fn fun2(self, a: u32, b: u32) -> u32 {\n            a + b\n        }\n        fn fun3(&self, a: u32, b: u32, c: u32) -> u32 {\n            a + b + c\n        }\n    }\n\n    struct Outer {\n        inner: Inner,\n        value: u32,\n    }\n\n    impl Outer {\n        pub fn new() -> Outer {\n            Outer {\n                inner: Inner,\n                value: 42,\n            }\n        }\n\n        delegate! {\n            to self.inner {\n                #[call(fun_generic)]\n                fn fun_generic(self, [ 42 ]) -> u32;\n                #[call(fun1)]\n                fn fun1_with_0(self, [ 0 ]) -> u32;\n                #[call(fun1)]\n                fn fun1_with_0_no_spaces(self, [0]) -> u32;\n                #[call(fun1)]\n                fn fun1_with_def(self, [ self.value ] ) -> u32;\n                fn fun2(self, [ 0 ], b: u32) -> u32;\n            }\n        }\n    }\n\n    assert_eq!(Outer::new().fun_generic(), 42);\n    assert_eq!(Outer::new().fun1_with_0(), 0);\n    assert_eq!(Outer::new().fun1_with_0_no_spaces(), 0);\n    assert_eq!(Outer::new().fun1_with_def(), 42);\n    assert_eq!(Outer::new().fun2(2), 2);\n}\n\n#[test]\nfn test_mixed_args() {\n    use delegate::delegate;\n    struct Inner;\n    impl Inner {\n        pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 {\n            a + x * x + b * y + c\n        }\n    }\n    struct Wrapper {\n        inner: Inner,\n        a: i32,\n        b: i32,\n        c: i32,\n    }\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ;\n\n                #[call(polynomial)]\n                pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ;\n            }\n        }\n\n        pub fn new() -> Wrapper {\n            Wrapper {\n                inner: Inner,\n                a: 1,\n                b: 3,\n                c: 5,\n            }\n        }\n    }\n\n    assert_eq!(Wrapper::new().polynomial(2, 3), 19i32);\n    assert_eq!(Wrapper::new().linear(3), 14i32);\n}\n"
  },
  {
    "path": "tests/nested.rs",
    "content": "use delegate::delegate;\n\nstruct Inner;\nimpl Inner {\n    pub fn method(&self, num: u32) -> u32 {\n        num\n    }\n}\n\nstruct Inner2 {\n    inner: Inner,\n}\n\nstruct Wrapper {\n    inner: Inner2,\n}\n\nimpl Wrapper {\n    delegate! {\n        to self.inner.inner {\n            pub(crate) fn method(&self, num: u32) -> u32;\n        }\n    }\n}\n\n#[test]\nfn test_nested() {\n    let wrapper = Wrapper {\n        inner: Inner2 { inner: Inner },\n    };\n\n    assert_eq!(wrapper.method(3), 3);\n}\n"
  },
  {
    "path": "tests/returntype.rs",
    "content": "use delegate::delegate;\nuse std::convert::TryFrom;\n\n#[test]\nfn test_generic_returntype() {\n    trait TestTrait {\n        fn create(num: u32) -> Self;\n    }\n    impl TestTrait for u32 {\n        fn create(num: u32) -> Self {\n            num\n        }\n    }\n\n    struct Inner;\n    impl Inner {\n        pub fn method<T: TestTrait>(&self) -> T {\n            T::create(0)\n        }\n    }\n\n    struct Wrapper<T> {\n        inner: Inner,\n        s: T,\n    }\n\n    impl<T: TestTrait> Wrapper<T> {\n        delegate! {\n            to self.inner {\n                pub(crate) fn method(&self) -> T;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner, s: 3 };\n\n    assert_eq!(wrapper.method(), 0);\n}\n\n#[test]\nfn test_into() {\n    struct Inner;\n    impl Inner {\n        pub fn method(&self, num: u32) -> u32 {\n            num\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                pub(crate) fn method(&self, num: u32);\n\n                #[into]\n                #[call(method)]\n                pub(crate) fn method_conv(&self, num: u32) -> u64;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(3), ());\n    assert_eq!(wrapper.method_conv(3), 3u64);\n}\n\n#[test]\nfn test_try_into() {\n    struct A;\n\n    #[derive(Debug, PartialEq)]\n    struct B;\n\n    impl TryFrom<A> for B {\n        type Error = u32;\n\n        fn try_from(_value: A) -> Result<Self, Self::Error> {\n            Ok(B)\n        }\n    }\n\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> A {\n            A\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                #[try_into]\n                fn method(&self) -> Result<B, u32>;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(), Ok(B));\n}\n\n#[test]\nfn test_try_into_unwrap() {\n    struct A;\n\n    #[derive(Debug, PartialEq)]\n    struct B;\n\n    impl TryFrom<A> for B {\n        type Error = u32;\n\n        fn try_from(_value: A) -> Result<Self, Self::Error> {\n            Ok(B)\n        }\n    }\n\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> A {\n            A\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                #[try_into]\n                #[unwrap]\n                fn method(&self) -> B;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(), B);\n}\n\n#[test]\nfn test_unwrap_result() {\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> Result<u32, ()> {\n            Ok(0)\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                #[unwrap]\n                fn method(&self) -> u32;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(), 0);\n}\n\n#[test]\nfn test_unwrap_option() {\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> Option<u32> {\n            Some(0)\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                #[unwrap]\n                fn method(&self) -> u32;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(), 0);\n}\n\n#[test]\n#[should_panic]\nfn test_unwrap_no_return() {\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> Result<u32, ()> {\n            Err(())\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                #[unwrap]\n                fn method(&self);\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n    wrapper.method();\n}\n\n#[test]\nfn test_unwrap_into() {\n    struct A(u32);\n\n    impl From<u32> for A {\n        fn from(value: u32) -> Self {\n            A(value)\n        }\n    }\n\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> Result<u32, ()> {\n            Ok(0)\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                #[unwrap]\n                #[into]\n                fn method(&self) -> A;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert!(matches!(wrapper.method(), A(0)));\n}\n\n#[test]\nfn test_into_unwrap() {\n    struct A(u32);\n\n    impl From<A> for Result<u32, ()> {\n        fn from(value: A) -> Self {\n            Ok(value.0)\n        }\n    }\n\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> A {\n            A(0)\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            to self.inner {\n                #[into(Result<u32, ()>)]\n                #[unwrap]\n                fn method(&self) -> u32;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(), 0);\n}\n"
  },
  {
    "path": "tests/segment_attributes.rs",
    "content": "use delegate::delegate;\nuse std::convert::TryFrom;\n\n#[test]\nfn test_segment_unwrap() {\n    struct Inner;\n\n    impl Inner {\n        fn foo(&self, a: u32) -> Result<u32, ()> {\n            Ok(a)\n        }\n        fn bar(&self, a: u32) -> Result<u32, ()> {\n            Ok(a)\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            #[unwrap]\n            to self.inner {\n                fn foo(&self, a: u32) -> u32;\n                fn bar(&self, a: u32) -> u32;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n    assert_eq!(wrapper.foo(1), 1);\n    assert_eq!(wrapper.bar(2), 2);\n}\n\n#[test]\nfn test_segment_try_into() {\n    struct A;\n\n    #[derive(Debug, PartialEq)]\n    struct B;\n\n    impl TryFrom<A> for B {\n        type Error = u32;\n\n        fn try_from(_value: A) -> Result<Self, Self::Error> {\n            Ok(B)\n        }\n    }\n\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> A {\n            A\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            #[try_into]\n            to self.inner {\n                fn method(&self) -> Result<B, u32>;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(), Ok(B));\n}\n\n#[test]\nfn test_segment_into() {\n    struct A(u32);\n\n    impl From<A> for Result<u32, ()> {\n        fn from(value: A) -> Self {\n            Ok(value.0)\n        }\n    }\n\n    impl From<A> for u64 {\n        fn from(value: A) -> Self {\n            value.0 as u64\n        }\n    }\n\n    struct Inner;\n    impl Inner {\n        pub fn method(&self) -> A {\n            A(0)\n        }\n    }\n\n    struct Wrapper {\n        inner: Inner,\n    }\n\n    impl Wrapper {\n        delegate! {\n            #[into(Result<u32, ()>)]\n            to self.inner {\n                #[unwrap]\n                fn method(&self) -> u32;\n\n                #[into]\n                #[call(method)]\n                fn method2(&self) -> u64;\n            }\n        }\n    }\n\n    let wrapper = Wrapper { inner: Inner };\n\n    assert_eq!(wrapper.method(), 0);\n    assert_eq!(wrapper.method2(), 0);\n}\n\n#[test]\nfn test_segment_await() {\n    struct UserRepo;\n    impl UserRepo {\n        fn foo(&self) {}\n        async fn bar(&self) -> u32 {\n            1\n        }\n    }\n\n    struct SharedRepo(tokio::sync::Mutex<UserRepo>);\n\n    impl SharedRepo {\n        delegate! {\n            #[await(false)]\n            to self.0.lock().await {\n                async fn foo(&self);\n                #[await(true)]\n                async fn bar(&self) -> u32;\n            }\n        }\n    }\n}\n\n#[test]\nfn test_segment_through_trait() {\n    trait A {\n        fn f(&self) -> u32;\n    }\n\n    trait B {\n        fn f(&self) -> u32;\n    }\n\n    struct Foo;\n\n    impl A for Foo {\n        fn f(&self) -> u32 {\n            0\n        }\n    }\n    impl B for Foo {\n        fn f(&self) -> u32 {\n            1\n        }\n    }\n\n    struct Bar(Foo);\n\n    impl Bar {\n        delegate! {\n            #[through(A)]\n            to &self.0 {\n                fn f(&self) -> u32;\n                #[call(f)]\n                #[through(B)]\n                fn f2(&self) -> u32;\n            }\n        }\n    }\n\n    let bar = Bar(Foo);\n    assert_eq!(bar.f(), 0);\n    assert_eq!(bar.f2(), 1);\n}\n\n#[test]\nfn test_segment_inline() {\n    struct Foo;\n\n    impl Foo {\n        fn f(&self) -> u32 {\n            0\n        }\n    }\n\n    struct Bar(Foo);\n\n    impl Bar {\n        delegate! {\n            #[inline(always)]\n            to self.0 {\n                fn f(&self) -> u32;\n            }\n        }\n    }\n\n    let bar = Bar(Foo);\n    assert_eq!(bar.f(), 0);\n}\n\n#[test]\nfn test_attribute_with_path() {\n    struct Foo;\n\n    impl Foo {\n        fn f(&self) -> u32 {\n            0\n        }\n    }\n\n    struct Bar(Foo);\n\n    impl Bar {\n        delegate! {\n            #[diagnostic::on_unimplemented]\n            to self.0 {\n                fn f(&self) -> u32;\n            }\n        }\n    }\n\n    let bar = Bar(Foo);\n    assert_eq!(bar.f(), 0);\n}\n"
  },
  {
    "path": "tests/stack.rs",
    "content": "use delegate::delegate;\n\n#[derive(Clone, Debug)]\nstruct Stack<T> {\n    inner: Vec<T>,\n}\n\nimpl<T> Stack<T> {\n    /// Allocate an empty stack\n    pub fn new() -> Stack<T> {\n        Stack { inner: vec![] }\n    }\n\n    delegate! {\n        to self.inner {\n            #[inline(never)]\n            #[call(len)]\n            pub(crate) fn size(&self) -> usize;\n\n            /// doc comment\n            fn is_empty(&self) -> bool;\n\n            #[inline(never)]\n            fn push(&mut self, v: T);\n            pub fn pop(&mut self) -> Option<T>;\n\n            #[call(last)]\n            #[inline(never)]\n            fn peek(&self) -> Option<&T>;\n            fn clear(&mut self);\n            fn into_boxed_slice(self) -> Box<[T]>;\n        }\n    }\n}\n\n#[test]\nfn test_stack() {\n    let mut stack: Stack<u32> = Stack::new();\n\n    assert_eq!(stack.size(), 0);\n    assert_eq!(stack.is_empty(), true);\n    assert_eq!(stack.peek(), None);\n\n    stack.clear();\n\n    assert_eq!(stack.size(), 0);\n    assert_eq!(stack.is_empty(), true);\n    assert_eq!(stack.peek(), None);\n\n    assert_eq!(stack.pop(), None);\n\n    assert_eq!(stack.size(), 0);\n    assert_eq!(stack.is_empty(), true);\n    assert_eq!(stack.peek(), None);\n\n    stack.push(1);\n\n    assert_eq!(stack.size(), 1);\n    assert_eq!(stack.is_empty(), false);\n    assert_eq!(stack.peek(), Some(&1));\n\n    assert_eq!(stack.pop(), Some(1));\n\n    assert_eq!(stack.size(), 0);\n    assert_eq!(stack.is_empty(), true);\n    assert_eq!(stack.peek(), None);\n\n    stack.push(1);\n    stack.push(2);\n    stack.push(3);\n\n    assert_eq!(stack.size(), 3);\n    assert_eq!(stack.is_empty(), false);\n    assert_eq!(stack.peek(), Some(&3));\n\n    assert_eq!(stack.clone().into_boxed_slice().into_vec(), stack.inner);\n\n    assert_eq!(stack.pop(), Some(3));\n\n    assert_eq!(stack.size(), 2);\n    assert_eq!(stack.is_empty(), false);\n    assert_eq!(stack.peek(), Some(&2));\n\n    stack.clear();\n\n    assert_eq!(stack.size(), 0);\n    assert_eq!(stack.is_empty(), true);\n    assert_eq!(stack.peek(), None);\n}\n"
  },
  {
    "path": "tests/through_trait.rs",
    "content": "use delegate::delegate;\n\n#[test]\nfn test_call_through_trait() {\n    trait A {\n        fn f(&self) -> u32;\n    }\n\n    trait B {\n        fn f(&self) -> u32;\n    }\n\n    struct Foo;\n\n    impl A for Foo {\n        fn f(&self) -> u32 {\n            0\n        }\n    }\n    impl B for Foo {\n        fn f(&self) -> u32 {\n            1\n        }\n    }\n\n    struct Bar(Foo);\n\n    impl Bar {\n        delegate! {\n            to &self.0 {\n                #[through(A)]\n                fn f(&self) -> u32;\n                #[call(f)]\n                #[through(B)]\n                fn f2(&self) -> u32;\n            }\n        }\n    }\n\n    let bar = Bar(Foo);\n    assert_eq!(bar.f(), 0);\n    assert_eq!(bar.f2(), 1);\n}\n"
  }
]