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

(&self) -> u32; } struct Foo; impl A for Foo { fn f

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

(&self) -> u32; } } } let bar = Bar(Foo); assert_eq!(bar.f::(), 0); } #[test] fn test_generics_complex() { struct Foo; impl Foo { fn foo<'a: 'static, X: Copy, #[allow(unused)] T>(&self) {} } struct Bar(Foo); impl Bar { delegate! { to &self.0 { fn foo<'a: 'static, X: Copy, #[allow(unused)] T>(&self); } } } } #[test] fn test_lifetime_late_bound() { trait QSet where T: PartialEq, { fn iter<'a>(&'a self) -> impl Iterator where Self: Sized, T: 'a; } impl QSet for HashSet { delegate! { to self { #[through(HashSet)] fn iter<'a>(&'a self) -> impl Iterator where Self: Sized, T: 'a; } } } } ================================================ FILE: tests/in_macro_expansion.rs ================================================ /// /// Tests that a macro can expand into a delegate block, /// where the target comes from a macro variable. /// use delegate::delegate; trait Trait { fn method_to_delegate(&self) -> bool; } struct Struct1(); impl Trait for Struct1 { fn method_to_delegate(&self) -> bool { true } } struct Struct2(pub Struct1); // We use a macro to impl 'Trait' for 'Struct2' such that // the target is a variable in the macro. macro_rules! some_macro { (|$self:ident| $delegate_to:expr) => { impl Trait for Struct2 { delegate! { // '$delegate_to' will expand to 'self.0' before ´delegate!' is expanded. to $delegate_to { fn method_to_delegate(&$self) -> bool; } } } }; } some_macro! { |self | self.0 } #[test] fn test() { assert!(Struct2(Struct1()).method_to_delegate()); } ================================================ FILE: tests/inline_args.rs ================================================ use delegate::delegate; #[test] fn test_inline_args() { struct Inner; impl Inner { fn fun_generic(self, s: S) -> S { s } fn fun0(self) -> u32 { 42 } fn fun1(self, a: u32) -> u32 { a } fn fun2(self, a: u32, b: u32) -> u32 { a + b } fn fun3(&self, a: u32, b: u32, c: u32) -> u32 { a + b + c } } struct Outer { inner: Inner, value: u32, } impl Outer { pub fn new() -> Outer { Outer { inner: Inner, value: 42, } } delegate! { to self.inner { #[call(fun_generic)] fn fun_generic(self, [ 42 ]) -> u32; #[call(fun1)] fn fun1_with_0(self, [ 0 ]) -> u32; #[call(fun1)] fn fun1_with_0_no_spaces(self, [0]) -> u32; #[call(fun1)] fn fun1_with_def(self, [ self.value ] ) -> u32; fn fun2(self, [ 0 ], b: u32) -> u32; } } } assert_eq!(Outer::new().fun_generic(), 42); assert_eq!(Outer::new().fun1_with_0(), 0); assert_eq!(Outer::new().fun1_with_0_no_spaces(), 0); assert_eq!(Outer::new().fun1_with_def(), 42); assert_eq!(Outer::new().fun2(2), 2); } #[test] fn test_mixed_args() { use delegate::delegate; struct Inner; impl Inner { pub fn polynomial(&self, a: i32, x: i32, b: i32, y: i32, c: i32) -> i32 { a + x * x + b * y + c } } struct Wrapper { inner: Inner, a: i32, b: i32, c: i32, } impl Wrapper { delegate! { to self.inner { pub fn polynomial(&self, [ self.a ], x: i32, [ self.b ], y: i32, [ self.c ]) -> i32 ; #[call(polynomial)] pub fn linear(&self, [ 0 ], [ 0 ], [ self.b ], y: i32, [ self.c ]) -> i32 ; } } pub fn new() -> Wrapper { Wrapper { inner: Inner, a: 1, b: 3, c: 5, } } } assert_eq!(Wrapper::new().polynomial(2, 3), 19i32); assert_eq!(Wrapper::new().linear(3), 14i32); } ================================================ FILE: tests/nested.rs ================================================ use delegate::delegate; struct Inner; impl Inner { pub fn method(&self, num: u32) -> u32 { num } } struct Inner2 { inner: Inner, } struct Wrapper { inner: Inner2, } impl Wrapper { delegate! { to self.inner.inner { pub(crate) fn method(&self, num: u32) -> u32; } } } #[test] fn test_nested() { let wrapper = Wrapper { inner: Inner2 { inner: Inner }, }; assert_eq!(wrapper.method(3), 3); } ================================================ FILE: tests/returntype.rs ================================================ use delegate::delegate; use std::convert::TryFrom; #[test] fn test_generic_returntype() { trait TestTrait { fn create(num: u32) -> Self; } impl TestTrait for u32 { fn create(num: u32) -> Self { num } } struct Inner; impl Inner { pub fn method(&self) -> T { T::create(0) } } struct Wrapper { inner: Inner, s: T, } impl Wrapper { delegate! { to self.inner { pub(crate) fn method(&self) -> T; } } } let wrapper = Wrapper { inner: Inner, s: 3 }; assert_eq!(wrapper.method(), 0); } #[test] fn test_into() { struct Inner; impl Inner { pub fn method(&self, num: u32) -> u32 { num } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { pub(crate) fn method(&self, num: u32); #[into] #[call(method)] pub(crate) fn method_conv(&self, num: u32) -> u64; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(3), ()); assert_eq!(wrapper.method_conv(3), 3u64); } #[test] fn test_try_into() { struct A; #[derive(Debug, PartialEq)] struct B; impl TryFrom for B { type Error = u32; fn try_from(_value: A) -> Result { Ok(B) } } struct Inner; impl Inner { pub fn method(&self) -> A { A } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { #[try_into] fn method(&self) -> Result; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(), Ok(B)); } #[test] fn test_try_into_unwrap() { struct A; #[derive(Debug, PartialEq)] struct B; impl TryFrom for B { type Error = u32; fn try_from(_value: A) -> Result { Ok(B) } } struct Inner; impl Inner { pub fn method(&self) -> A { A } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { #[try_into] #[unwrap] fn method(&self) -> B; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(), B); } #[test] fn test_unwrap_result() { struct Inner; impl Inner { pub fn method(&self) -> Result { Ok(0) } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { #[unwrap] fn method(&self) -> u32; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(), 0); } #[test] fn test_unwrap_option() { struct Inner; impl Inner { pub fn method(&self) -> Option { Some(0) } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { #[unwrap] fn method(&self) -> u32; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(), 0); } #[test] #[should_panic] fn test_unwrap_no_return() { struct Inner; impl Inner { pub fn method(&self) -> Result { Err(()) } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { #[unwrap] fn method(&self); } } } let wrapper = Wrapper { inner: Inner }; wrapper.method(); } #[test] fn test_unwrap_into() { struct A(u32); impl From for A { fn from(value: u32) -> Self { A(value) } } struct Inner; impl Inner { pub fn method(&self) -> Result { Ok(0) } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { #[unwrap] #[into] fn method(&self) -> A; } } } let wrapper = Wrapper { inner: Inner }; assert!(matches!(wrapper.method(), A(0))); } #[test] fn test_into_unwrap() { struct A(u32); impl From for Result { fn from(value: A) -> Self { Ok(value.0) } } struct Inner; impl Inner { pub fn method(&self) -> A { A(0) } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { to self.inner { #[into(Result)] #[unwrap] fn method(&self) -> u32; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(), 0); } ================================================ FILE: tests/segment_attributes.rs ================================================ use delegate::delegate; use std::convert::TryFrom; #[test] fn test_segment_unwrap() { struct Inner; impl Inner { fn foo(&self, a: u32) -> Result { Ok(a) } fn bar(&self, a: u32) -> Result { Ok(a) } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { #[unwrap] to self.inner { fn foo(&self, a: u32) -> u32; fn bar(&self, a: u32) -> u32; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.foo(1), 1); assert_eq!(wrapper.bar(2), 2); } #[test] fn test_segment_try_into() { struct A; #[derive(Debug, PartialEq)] struct B; impl TryFrom for B { type Error = u32; fn try_from(_value: A) -> Result { Ok(B) } } struct Inner; impl Inner { pub fn method(&self) -> A { A } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { #[try_into] to self.inner { fn method(&self) -> Result; } } } let wrapper = Wrapper { inner: Inner }; let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(), Ok(B)); } #[test] fn test_segment_into() { struct A(u32); impl From for Result { fn from(value: A) -> Self { Ok(value.0) } } impl From for u64 { fn from(value: A) -> Self { value.0 as u64 } } struct Inner; impl Inner { pub fn method(&self) -> A { A(0) } } struct Wrapper { inner: Inner, } impl Wrapper { delegate! { #[into(Result)] to self.inner { #[unwrap] fn method(&self) -> u32; #[into] #[call(method)] fn method2(&self) -> u64; } } } let wrapper = Wrapper { inner: Inner }; assert_eq!(wrapper.method(), 0); assert_eq!(wrapper.method2(), 0); } #[test] fn test_segment_await() { struct UserRepo; impl UserRepo { fn foo(&self) {} async fn bar(&self) -> u32 { 1 } } struct SharedRepo(tokio::sync::Mutex); impl SharedRepo { delegate! { #[await(false)] to self.0.lock().await { async fn foo(&self); #[await(true)] async fn bar(&self) -> u32; } } } } #[test] fn test_segment_through_trait() { trait A { fn f(&self) -> u32; } trait B { fn f(&self) -> u32; } struct Foo; impl A for Foo { fn f(&self) -> u32 { 0 } } impl B for Foo { fn f(&self) -> u32 { 1 } } struct Bar(Foo); impl Bar { delegate! { #[through(A)] to &self.0 { fn f(&self) -> u32; #[call(f)] #[through(B)] fn f2(&self) -> u32; } } } let bar = Bar(Foo); assert_eq!(bar.f(), 0); assert_eq!(bar.f2(), 1); } #[test] fn test_segment_inline() { struct Foo; impl Foo { fn f(&self) -> u32 { 0 } } struct Bar(Foo); impl Bar { delegate! { #[inline(always)] to self.0 { fn f(&self) -> u32; } } } let bar = Bar(Foo); assert_eq!(bar.f(), 0); } #[test] fn test_attribute_with_path() { struct Foo; impl Foo { fn f(&self) -> u32 { 0 } } struct Bar(Foo); impl Bar { delegate! { #[diagnostic::on_unimplemented] to self.0 { fn f(&self) -> u32; } } } let bar = Bar(Foo); assert_eq!(bar.f(), 0); } ================================================ FILE: tests/stack.rs ================================================ use delegate::delegate; #[derive(Clone, Debug)] struct Stack { inner: Vec, } impl Stack { /// Allocate an empty stack pub fn new() -> Stack { Stack { inner: vec![] } } delegate! { to self.inner { #[inline(never)] #[call(len)] pub(crate) fn size(&self) -> usize; /// doc comment fn is_empty(&self) -> bool; #[inline(never)] fn push(&mut self, v: T); pub fn pop(&mut self) -> Option; #[call(last)] #[inline(never)] fn peek(&self) -> Option<&T>; fn clear(&mut self); fn into_boxed_slice(self) -> Box<[T]>; } } } #[test] fn test_stack() { let mut stack: Stack = Stack::new(); assert_eq!(stack.size(), 0); assert_eq!(stack.is_empty(), true); assert_eq!(stack.peek(), None); stack.clear(); assert_eq!(stack.size(), 0); assert_eq!(stack.is_empty(), true); assert_eq!(stack.peek(), None); assert_eq!(stack.pop(), None); assert_eq!(stack.size(), 0); assert_eq!(stack.is_empty(), true); assert_eq!(stack.peek(), None); stack.push(1); assert_eq!(stack.size(), 1); assert_eq!(stack.is_empty(), false); assert_eq!(stack.peek(), Some(&1)); assert_eq!(stack.pop(), Some(1)); assert_eq!(stack.size(), 0); assert_eq!(stack.is_empty(), true); assert_eq!(stack.peek(), None); stack.push(1); stack.push(2); stack.push(3); assert_eq!(stack.size(), 3); assert_eq!(stack.is_empty(), false); assert_eq!(stack.peek(), Some(&3)); assert_eq!(stack.clone().into_boxed_slice().into_vec(), stack.inner); assert_eq!(stack.pop(), Some(3)); assert_eq!(stack.size(), 2); assert_eq!(stack.is_empty(), false); assert_eq!(stack.peek(), Some(&2)); stack.clear(); assert_eq!(stack.size(), 0); assert_eq!(stack.is_empty(), true); assert_eq!(stack.peek(), None); } ================================================ FILE: tests/through_trait.rs ================================================ use delegate::delegate; #[test] fn test_call_through_trait() { trait A { fn f(&self) -> u32; } trait B { fn f(&self) -> u32; } struct Foo; impl A for Foo { fn f(&self) -> u32 { 0 } } impl B for Foo { fn f(&self) -> u32 { 1 } } struct Bar(Foo); impl Bar { delegate! { to &self.0 { #[through(A)] fn f(&self) -> u32; #[call(f)] #[through(B)] fn f2(&self) -> u32; } } } let bar = Bar(Foo); assert_eq!(bar.f(), 0); assert_eq!(bar.f2(), 1); }