diff options
| author | 魏曹先生 <1992414357@qq.com> | 2026-07-23 08:08:33 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2026-07-23 14:01:45 +0800 |
| commit | 68a652ed2f51d366bb8033497e6dfe545895410e (patch) | |
| tree | d463833846248410733e196a0939c59cd67ca8a2 | |
feat: scaffold crate structure and implement core macros
Add the project skeleton, LICENSE files, README, Makefile, doc
examples, and the initial implementation of `#[func]`, `invoke!`,
and `select!` procedural macros.
45 files changed, 2134 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e350dc9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# All target directories +target + +.temp/ + +nul diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..38bce0e --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,175 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "might_be_async" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "toml", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c0b3a36 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "might_be_async" +authors = ["Weicao-CatilGrass"] +version = "0.1.0" +edition = "2024" +license = "MIT OR Apache-2.0" +readme = "README.md" +repository = "https://github.com/catilgrass/might_be_async" +description = "A proc macro that gen both async & sync fn, toggle via feature flag." +keywords = ["async", "proc-macro", "macro"] +categories = ["development-tools"] +repository = "https://github.com/catilgrass/might_be_async" + +[lib] +proc-macro = true + +[features] + +# Only a test placeholder, no actual functionality +foo_async = [] +foo_sync = [] + +[package.metadata.might_be_async] +default_feature_name = "foo_async" + +[dependencies] +proc-macro2 = "1.0.106" +quote = "1.0.46" +syn = { version = "2.0.118", features = ["full"] } +toml = "0.8" + +[dev-dependencies] +syn = { version = "2.0.118", features = ["full", "printing"] } diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..51eefef --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + 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 2026 Weicao-CatilGrass + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..4ff38a3 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,9 @@ +# The MIT License (MIT) + +Copyright © 2026 Weicao-CatilGrass + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8176780 --- /dev/null +++ b/Makefile @@ -0,0 +1,50 @@ +.PHONY: check clippy check-lock test-crate test-sync test-async expand fmt-expand lock + +# make check +check: clippy expand fmt-expand test-crate test-sync test-async check-lock + +# make lock +lock: + for f in doc/usage/*_expand.rs; do \ + cp "$$f" "$$f.lock"; \ + done + +# DO NOT RUN THEM + +clippy: + cargo clippy -- -D warnings + +test-crate: + cargo test + +test-sync: + cargo test -p might_be_async_test_sync --manifest-path test/Cargo.toml + +test-async: + cargo test -p might_be_async_test_async --features metadata_async --manifest-path test/Cargo.toml + +expand: + python3 scripts/expand_codes.py + +fmt-expand: + for f in doc/usage/*_expand.rs; do \ + case "$$f" in *.lock) ;; *) rustfmt "$$f" --edition 2024 --config blank_lines_lower_bound=0 ;; esac; \ + done + +check-lock: + errors=0; \ + for lock in doc/usage/*_expand.rs.lock; do \ + [ -f "$$lock" ] || continue; \ + base="$${lock%.lock}"; \ + if [ ! -f "$$base" ]; then \ + echo "ERROR: $$lock has no matching source file"; \ + errors=1; \ + elif git --no-pager diff --no-index --quiet "$$lock" "$$base" 2>/dev/null; then \ + :; \ + else \ + git --no-pager diff --no-index "$$lock" "$$base" || true; \ + echo "ERROR: $$base differs from $$lock"; \ + errors=1; \ + fi; \ + done; \ + exit $$errors diff --git a/README.md b/README.md new file mode 100644 index 0000000..e75cb45 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# might_be_async + +> A proc macro that gen both async & sync fn, toggle via feature flag. + +## Installation + +Add the dependency in `Cargo.toml`: + +```toml +[dependencies] +might_be_async = "0.1.0" +``` + +Or use the `cargo add` command: + +```bash +cargo add might_be_async +``` + +# Usage + +First, choose a feature name for your async toggle. By default `might_be_async` uses the feature name `"async"`, but you can use any name you like. + +```toml +# Cargo.toml + +[package.metadata.might_be_async] +default_feature_name = "async" # Default + +[dependencies] +might_be_async = "0.1.0" +``` + +Now you can annotate your functions with `#[func]`: + +```rust +#[might_be_async::func] +fn greet(name: &str) -> String { + format!("Hello, {name}!") +} +``` + +When the `async` feature is **off**, `greet` remains a plain synchronous `fn`. +When the `async` feature is **on**, `greet` becomes an `async fn` — its signature changes to `async fn greet(name: &str) -> String`. + +## Calling annotated functions + +If one `#[func]` function calls another, use the `invoke!` macro to handle +the `.await` automatically: + +```rust +#[might_be_async::func] +fn double(x: i32) -> i32 { + x * 2 +} + +#[might_be_async::func] +fn compute(a: i32, b: i32) -> i32 { + let sum = a + b; + might_be_async::invoke!(double(sum)) // adds .await in async mode, does nothing in sync mode +} +``` + +## Feature-specific logic with `select!` + +Use `select!` to write code that differs between sync and async modes: + +```rust +#[might_be_async::func] +fn load_data() -> Vec<u8> { + might_be_async::select!("async" => fetch_async().await else ! => fetch_sync()) +} + +async fn fetch_async() -> Vec<u8> { + // ... + vec![] +} + +fn fetch_sync() -> Vec<u8> { + // ... + vec![] +} +``` + +When the feature `"async"` is active, the first branch runs. When it's not, +the second branch (marked with `!`) runs. + +## Switching modes + +Run in sync mode (default): + +```bash +cargo build +cargo run +``` + +Run in async mode: + +```bash +cargo build --features async +cargo run --features async +``` + +## License + +MIT OR Apache-2.0" diff --git a/doc/args/func.md b/doc/args/func.md new file mode 100644 index 0000000..7d718a2 --- /dev/null +++ b/doc/args/func.md @@ -0,0 +1,4 @@ +Arguments parsed from the `#[func]` attribute. + +If the attribute is empty (`#[func]`), defaults to feature name `"async"`. +When a string literal is provided (`#[func("tokio_rt")]`), that value is used. diff --git a/doc/args/invoke.md b/doc/args/invoke.md new file mode 100644 index 0000000..74a1823 --- /dev/null +++ b/doc/args/invoke.md @@ -0,0 +1,8 @@ +Arguments parsed by the `invoke!` macro. + +Two forms: + +| Variant | Form | Behavior | +| ---------- | ------------------------- | ---------------------------------- | +| `Default` | `invoke!(expr)` | Feature name defaults to `"async"` | +| `Explicit` | `invoke!("feat" => expr)` | Uses the given feature name | diff --git a/doc/args/select_arm.md b/doc/args/select_arm.md new file mode 100644 index 0000000..c371d22 --- /dev/null +++ b/doc/args/select_arm.md @@ -0,0 +1,7 @@ +A single arm inside the `select!` macro. + +| Variant | Example | Meaning | +| ---------- | ----------------- | ----------------------------------------------------- | +| `Explicit` | `"async" => expr` | Arm guarded by `feature = "async"` | +| `Not` | `! => expr` | Arm guarded by `not(feature = <other_arm's_feature>)` | +| `Implicit` | `expr` | Feature determined by `.await` detection | diff --git a/doc/func.md b/doc/func.md new file mode 100644 index 0000000..86925d7 --- /dev/null +++ b/doc/func.md @@ -0,0 +1,12 @@ +Attribute macro that generates both a sync and an async version of a function, +gated by a Cargo feature flag. + +The function is written as a regular (non-async) `fn`. The macro duplicates it +internally into two implementations: + +- When the feature is **disabled**: the original `fn` is used as-is. +- When the feature is **enabled**: the function is promoted to `async fn`. + +By default the feature name is `"async"`. A different name can be supplied as +an attribute argument, for example `#[func("tokio_rt")]` to gate on the feature +`"tokio_rt"` instead. diff --git a/doc/invoke.md b/doc/invoke.md new file mode 100644 index 0000000..5784fba --- /dev/null +++ b/doc/invoke.md @@ -0,0 +1,17 @@ +Procedural macro that wraps a call expression, adding `.await` when the async +feature is enabled, and leaving it as a plain call otherwise. + +This macro is designed to be used **inside a `#[func]`-annotated function**. +`#[func]` ensures that the enclosing function is either sync or async depending +on the feature flag. `invoke!` mirrors that same gating on the call site: + +- Feature disabled, enclosing fn is sync → `invoke!(callee(args))` expands to + `callee(args)` — a plain synchronous call. +- Feature enabled, enclosing fn is async → `invoke!(callee(args))` expands to + `callee(args).await` — an awaited asynchronous call. + +Both the callee and the caller should be produced by `#[func]` so that their +sync/async nature changes in lockstep. + +An explicit feature name can be provided with the `=>` syntax. This is useful +when different features control different parts of the pipeline. diff --git a/doc/lib.md b/doc/lib.md new file mode 100644 index 0000000..88715a5 --- /dev/null +++ b/doc/lib.md @@ -0,0 +1,115 @@ +# might_be_async + +A proc-macro crate that generates both synchronous and asynchronous versions of +functions, gated by a Cargo feature flag. + +## Provided macros + +### `#[func]` — Attribute macro + +Generates both synchronous and asynchronous versions of a function, gated by a Cargo feature flag. When the feature is off, the function is a plain `fn`; when on, it becomes an `async fn`. + +Accepts an optional string argument specifying the feature name (defaults to `"async"`). + +```rust +// Uses default feature name "async" +#[might_be_async::func] +fn compute(x: i32) -> i32 { x } + +// Custom feature name +#[might_be_async::func("foo_async")] +fn fetch(url: &str) -> String { "url".into() } +``` + +### `invoke!` — Proc macro + +Wraps a function call, automatically adding `.await` when the feature is enabled. This lets you call `#[func]`-annotated functions without worrying about whether they are sync or async at the call site. + +Accepts an optional feature name before `=>` (defaults to `"async"`). + +```rust +use might_be_async::invoke; +# use std::env::args; +# #[might_be_async::func] +# fn entry() { +# let url = String::default(); + +// Uses default feature name "async" +invoke!(do_stuff(args())); + +// Custom feature name +invoke!("foo_async" => fetch_data(url)); +# } +# #[might_be_async::func] +# fn fetch_data(url: String) {} +# #[might_be_async::func] +# fn do_stuff(url: std::env::Args) {} +``` + +### `select!` — Proc macro + +Chooses between two expressions at compile time based on whether the feature flag is active. The first branch (marked with `"async" =>`) is taken when the feature is enabled; the second branch (marked with `! =>`) is taken otherwise. + +Supports three arm syntaxes: + +```rust +use might_be_async::select; +# #[might_be_async::func("foo_async")] +# fn entry() { + +// Explicit feature name arm and a negation arm +select!("foo_async" => { async_expr().await } else ! => { sync_expr() }); + +// Two explicit feature names (second can use ! prefix) +select!("foo_sync" => expr_a() else "foo_async" => expr_b().await); + +// Implicit arms — auto-detects .await to decide async vs sync +select!({ expr_with_await().await } else { expr_without_await() }); + +# } +# async fn expr_with_await () {} +# fn expr_without_await () {} +# async fn async_expr () {} +# fn sync_expr () {} +# async fn expr_b () {} +# fn expr_a () {} +``` + +## Complete example + +The three macros are designed to work together. `#[func]` keeps a set of +functions in sync: when the feature is off they are all plain `fn`, and when +it is on they are all `async fn`. `invoke!` calls between them automatically +add or omit `.await`, and `select!` picks the correct branch at compile time. + +```rust +use might_be_async::{func, invoke, select}; + +/// A simple computation, gated by the feature flag. +#[func] +fn double(x: i32) -> i32 { + x * 2 +} + +/// Calls `double` through `invoke!` — the call is plain or awaited +/// depending on whether the feature is active. +#[func] +fn add_then_double(a: i32, b: i32) -> i32 { + let sum = a + b; + invoke!(double(sum)) +} + +/// Uses `select!` to return a different value in each mode. +#[func] +fn pick(flag: bool) -> i32 { + if flag { + select!("foo_async" => 100 else ! => 200) + } else { + 0 + } +} + +assert_eq!(add_then_double(3, 4), 14); +assert_eq!(pick(true), 200); +assert_eq!(pick(false), 0); +``` diff --git a/doc/select.md b/doc/select.md new file mode 100644 index 0000000..d2330bd --- /dev/null +++ b/doc/select.md @@ -0,0 +1,22 @@ +Procedural macro that chooses between two expressions based on whether the +async feature is enabled, producing a value. + +## Explicit mode + +Each arm is labelled with a feature name. When the named feature is enabled +that arm is selected; otherwise the other arm is used. Since only one feature +is ever active at a time, the arm labelled `"sync"` effectively acts as an else +branch. + +The `!` token inverts the sense — it selects the arm when the corresponding +feature is **not** enabled. + +## Implicit mode + +Feature names are omitted; the macro inspects the token stream to decide which +expression is async. Whichever arm contains a `.await` call is treated as the +async branch. + +When neither arm contains `.await`, the first expression is assigned to the +async branch and the second to sync. The two branches trade places during +expansion so the correct one is active in each mode. diff --git a/doc/usage/func.rs b/doc/usage/func.rs new file mode 100644 index 0000000..f407019 --- /dev/null +++ b/doc/usage/func.rs @@ -0,0 +1,4 @@ +#[func] +pub fn greet(name: &str) -> String { + "Hello, {name}!".to_string() +} diff --git a/doc/usage/func_async_expand.rs b/doc/usage/func_async_expand.rs new file mode 100644 index 0000000..ac52411 --- /dev/null +++ b/doc/usage/func_async_expand.rs @@ -0,0 +1,3 @@ +pub async fn greet(name: &str) -> String { + "Hello, {name}!".to_string() +} diff --git a/doc/usage/func_async_expand.rs.lock b/doc/usage/func_async_expand.rs.lock new file mode 100644 index 0000000..ac52411 --- /dev/null +++ b/doc/usage/func_async_expand.rs.lock @@ -0,0 +1,3 @@ +pub async fn greet(name: &str) -> String { + "Hello, {name}!".to_string() +} diff --git a/doc/usage/func_expand.rs b/doc/usage/func_expand.rs new file mode 100644 index 0000000..70dee21 --- /dev/null +++ b/doc/usage/func_expand.rs @@ -0,0 +1,3 @@ +pub fn greet(name: &str) -> String { + "Hello, {name}!".to_string() +} diff --git a/doc/usage/func_expand.rs.lock b/doc/usage/func_expand.rs.lock new file mode 100644 index 0000000..70dee21 --- /dev/null +++ b/doc/usage/func_expand.rs.lock @@ -0,0 +1,3 @@ +pub fn greet(name: &str) -> String { + "Hello, {name}!".to_string() +} diff --git a/doc/usage/invoke.rs b/doc/usage/invoke.rs new file mode 100644 index 0000000..0ae90d2 --- /dev/null +++ b/doc/usage/invoke.rs @@ -0,0 +1,10 @@ +#[func] +fn compute(x: i32) -> i32 { + x * 2 +} + +#[func] +fn example() -> i32 { + // invoke! macro should be used with #[func] + invoke!(compute(5)) +} diff --git a/doc/usage/invoke_async_expand.rs b/doc/usage/invoke_async_expand.rs new file mode 100644 index 0000000..4b8d93f --- /dev/null +++ b/doc/usage/invoke_async_expand.rs @@ -0,0 +1,6 @@ +async fn compute(x: i32) -> i32 { + x * 2 +} +async fn example() -> i32 { + { { compute(5).await } } +} diff --git a/doc/usage/invoke_async_expand.rs.lock b/doc/usage/invoke_async_expand.rs.lock new file mode 100644 index 0000000..4b8d93f --- /dev/null +++ b/doc/usage/invoke_async_expand.rs.lock @@ -0,0 +1,6 @@ +async fn compute(x: i32) -> i32 { + x * 2 +} +async fn example() -> i32 { + { { compute(5).await } } +} diff --git a/doc/usage/invoke_expand.rs b/doc/usage/invoke_expand.rs new file mode 100644 index 0000000..3274d77 --- /dev/null +++ b/doc/usage/invoke_expand.rs @@ -0,0 +1,6 @@ +fn compute(x: i32) -> i32 { + x * 2 +} +fn example() -> i32 { + { { compute(5) } } +} diff --git a/doc/usage/invoke_expand.rs.lock b/doc/usage/invoke_expand.rs.lock new file mode 100644 index 0000000..3274d77 --- /dev/null +++ b/doc/usage/invoke_expand.rs.lock @@ -0,0 +1,6 @@ +fn compute(x: i32) -> i32 { + x * 2 +} +fn example() -> i32 { + { { compute(5) } } +} diff --git a/doc/usage/select.rs b/doc/usage/select.rs new file mode 100644 index 0000000..8cffcf8 --- /dev/null +++ b/doc/usage/select.rs @@ -0,0 +1,3 @@ +fn example() { + select! [{ 100 } else { 200 }]; +} diff --git a/doc/usage/select_async_expand.rs b/doc/usage/select_async_expand.rs new file mode 100644 index 0000000..b2553f3 --- /dev/null +++ b/doc/usage/select_async_expand.rs @@ -0,0 +1,5 @@ +fn example() { + { + { { 100 } } + }; +} diff --git a/doc/usage/select_async_expand.rs.lock b/doc/usage/select_async_expand.rs.lock new file mode 100644 index 0000000..b2553f3 --- /dev/null +++ b/doc/usage/select_async_expand.rs.lock @@ -0,0 +1,5 @@ +fn example() { + { + { { 100 } } + }; +} diff --git a/doc/usage/select_expand.rs b/doc/usage/select_expand.rs new file mode 100644 index 0000000..8caed8e --- /dev/null +++ b/doc/usage/select_expand.rs @@ -0,0 +1,5 @@ +fn example() { + { + { { 200 } } + }; +} diff --git a/doc/usage/select_expand.rs.lock b/doc/usage/select_expand.rs.lock new file mode 100644 index 0000000..8caed8e --- /dev/null +++ b/doc/usage/select_expand.rs.lock @@ -0,0 +1,5 @@ +fn example() { + { + { { 200 } } + }; +} diff --git a/scripts/expand_codes.py b/scripts/expand_codes.py new file mode 100644 index 0000000..c6b64a6 --- /dev/null +++ b/scripts/expand_codes.py @@ -0,0 +1,160 @@ +""" +Generate `*_expand.rs` and `*_async_expand.rs` files in `doc/usage/` by running +`cargo expand` on each usage example, once for sync and once for async. + +Requires `cargo-expand` to be installed: + cargo install cargo-expand +""" + +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TEMP = ROOT / ".temp" +USAGE = ROOT / "doc" / "usage" + +EXPAND_BEGIN = "use might_be_async::*;\nconst EXPAND_BEGIN: () = ();" +EXPAND_END = "const EXPAND_END: () = ();" + +CARGO_TOML = """\ +[package] +name = "expander" +version = "0.0.0" +edition = "2024" + +[workspace] + +[features] +async = [] + +[dependencies] +might_be_async = { path = "../.." } +""" + + +def check_cargo_expand() -> None: + """Ensure cargo-expand is installed.""" + try: + subprocess.run( + ["cargo", "expand", "--help"], + capture_output=True, + check=True, + ) + except (FileNotFoundError, subprocess.CalledProcessError): + print("error: `cargo expand` not found. Install it with:") + print(" cargo install cargo-expand") + sys.exit(1) + + +def prepare_temp() -> None: + """Create .temp/sync/ and .temp/async/ skeletons, and placeholder expand files.""" + if TEMP.exists(): + shutil.rmtree(TEMP) + + for variant in ("sync", "async"): + (TEMP / variant / "src").mkdir(parents=True) + (TEMP / variant / "Cargo.toml").write_text(CARGO_TOML) + + # Create placeholder _async_expand.rs files so the main crate can compile + # during cargo expand. They will be overwritten with real content later. + for name in ("func", "invoke", "select"): + placeholder = USAGE / f"{name}_async_expand.rs" + if not placeholder.exists(): + placeholder.write_text( + "// placeholder — will be overwritten by expand script\n" + ) + + +def write_lib_rs(variant: str, source: str) -> None: + """Wrap `source` with EXPAND markers and write to .temp/{variant}/src/lib.rs.""" + (TEMP / variant / "src" / "lib.rs").write_text(f"""\ +#![allow(unused_imports, dead_code)] + +{EXPAND_BEGIN} +{source} +{EXPAND_END} +""") + + +def run_expand(variant: str) -> str: + """Run `cargo expand` in .temp/{variant}/, optionally with --features async.""" + cmd = ["cargo", "expand"] + if variant == "async": + cmd.append("--features") + cmd.append("async") + + try: + result = subprocess.run( + cmd, + cwd=TEMP / variant, + capture_output=True, + text=True, + check=True, + ) + return result.stdout + except subprocess.CalledProcessError as e: + print(f"error: `cargo expand` failed in .temp/{variant}/:", file=sys.stderr) + print(e.stderr, file=sys.stderr) + sys.exit(1) + + +def extract_body(expanded: str) -> str: + """Extract the text between the EXPAND_BEGIN and EXPAND_END markers.""" + lines = expanded.splitlines() + cleaned = "\n".join(line for line in lines if not line.startswith("#!")) + + begin_idx = cleaned.find(EXPAND_BEGIN) + end_idx = cleaned.find(EXPAND_END) + + if begin_idx == -1 or end_idx == -1: + print("error: could not locate EXPAND markers in output", file=sys.stderr) + print("=== expanded output (first 60 lines) ===") + print("\n".join(cleaned.splitlines()[:60])) + sys.exit(1) + + start = begin_idx + len(EXPAND_BEGIN) + body = cleaned[start:end_idx] + return body.strip() + + +def write_expand(name: str, suffix: str, body: str) -> None: + """Write the expanded body to doc/usage/{name}_{suffix}expand.rs.""" + dest = USAGE / f"{name}_{suffix}expand.rs" + dest.write_text(body + "\n") + print(f" → {dest.name}") + + +def main() -> None: + check_cargo_expand() + prepare_temp() + + # Find all input .rs files that are NOT already expanded + inputs = sorted( + p + for p in USAGE.glob("*.rs") + if not p.name.endswith("_expand.rs") and not p.name.endswith("_async_expand.rs") + ) + + if not inputs: + print("No usage examples found in doc/usage/") + sys.exit(0) + + print(f"Expanding {len(inputs)} example(s) with cargo-expand …\n") + + for src in inputs: + stem = src.stem # "func", "invoke", "select" + code = src.read_text() + + for variant, suffix in [("sync", ""), ("async", "async_")]: + write_lib_rs(variant, code) + expanded = run_expand(variant) + body = extract_body(expanded) + write_expand(stem, suffix, body) + + print("\nDone.") + + +if __name__ == "__main__": + main() diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..06aa088 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,38 @@ +use std::path::Path; +use std::sync::OnceLock; + +/// Returns the default feature name configured in the consuming crate's +/// `Cargo.toml` under `[package.metadata.might_be_async.default_feature_name]`. +/// +/// If the metadata key is absent or unreadable, falls back to `"async"`. +pub(crate) fn default_feature_name() -> &'static str { + static DEFAULT: OnceLock<String> = OnceLock::new(); + DEFAULT.get_or_init(read_default_feature_name) +} + +fn read_default_feature_name() -> String { + let manifest_dir = match std::env::var("CARGO_MANIFEST_DIR") { + Ok(dir) => dir, + Err(_) => return "async".to_string(), + }; + + let cargo_toml_path = Path::new(&manifest_dir).join("Cargo.toml"); + let content = match std::fs::read_to_string(cargo_toml_path) { + Ok(c) => c, + Err(_) => return "async".to_string(), + }; + + let value: toml::Value = match content.parse() { + Ok(v) => v, + Err(_) => return "async".to_string(), + }; + + value + .get("package") + .and_then(|p| p.get("metadata")) + .and_then(|m| m.get("might_be_async")) + .and_then(|a| a.get("default_feature_name")) + .and_then(|v| v.as_str()) + .unwrap_or("async") + .to_string() +} diff --git a/src/func.rs b/src/func.rs new file mode 100644 index 0000000..5557992 --- /dev/null +++ b/src/func.rs @@ -0,0 +1,81 @@ +use crate::SynResult; +use crate::config::default_feature_name; +use proc_macro::TokenStream; +use quote::quote; +use syn::{ + ItemFn, LitStr, + parse::{Parse, ParseStream}, + parse_macro_input, +}; + +#[doc = include_str!("../doc/args/func.md")] +pub struct FuncArgs { + pub feature_name: String, +} + +impl Default for FuncArgs { + fn default() -> Self { + FuncArgs { + feature_name: default_feature_name().to_string(), + } + } +} + +impl Parse for FuncArgs { + fn parse(input: ParseStream) -> SynResult<Self> { + if input.is_empty() { + return Ok(FuncArgs::default()); + } + + // Parse: "feature_name" + let feat_lit: LitStr = input.parse()?; + let feature_name = feat_lit.value(); + + Ok(FuncArgs { feature_name }) + } +} + +pub(crate) fn func(attr: TokenStream, item: TokenStream) -> TokenStream { + let args = parse_macro_input!(attr as FuncArgs); + let feature_name = &args.feature_name; + + let input_fn = parse_macro_input!(item as ItemFn); + let attrs = &input_fn.attrs; + let vis = &input_fn.vis; + let sig = &input_fn.sig; + let block = &input_fn.block; + + let expanded = quote! { + #(#attrs)* + #[cfg(not(feature = #feature_name))] + #vis #sig #block + + #(#attrs)* + #[cfg(feature = #feature_name)] + #vis async #sig #block + }; + + TokenStream::from(expanded) +} + +/// Test module for `FuncArgs` parsing. +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_input_defaults_to_async() { + // Input: empty → defaults to "foo_async" + let input = proc_macro2::TokenStream::new(); + let args: FuncArgs = syn::parse2(input).unwrap(); + assert_eq!(args.feature_name, "foo_async"); + } + + #[test] + fn custom_feature_name_parsed() { + // Input: "custom_name" + let input: proc_macro2::TokenStream = "\"custom_name\"".parse().unwrap(); + let args: FuncArgs = syn::parse2(input).unwrap(); + assert_eq!(args.feature_name, "custom_name"); + } +} diff --git a/src/invoke.rs b/src/invoke.rs new file mode 100644 index 0000000..f7da20a --- /dev/null +++ b/src/invoke.rs @@ -0,0 +1,89 @@ +use crate::SynResult; +use crate::TokenStream2; +use crate::config::default_feature_name; +use proc_macro::TokenStream; +use quote::quote; +use syn::{ + LitStr, Token, + parse::{Parse, ParseStream}, + parse_macro_input, +}; + +#[doc = include_str!("../doc/args/invoke.md")] +pub enum InvokeArgs { + /// invoke!(expr) — feature name defaults to "async" + Default(TokenStream2), + + /// invoke!("feat" => expr) — explicit feature name + Explicit(LitStr, TokenStream2), +} + +impl Parse for InvokeArgs { + fn parse(input: ParseStream) -> SynResult<Self> { + if input.peek(LitStr) { + let feat: LitStr = input.parse()?; + input.parse::<Token![=>]>()?; + let expr: TokenStream2 = input.parse()?; + Ok(InvokeArgs::Explicit(feat, expr)) + } else { + let expr: TokenStream2 = input.parse()?; + Ok(InvokeArgs::Default(expr)) + } + } +} + +pub(crate) fn invoke(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as InvokeArgs); + + let expanded = match input { + InvokeArgs::Default(expr) => { + let feat = default_feature_name(); + quote! {{ + #[cfg(feature = #feat)] + { #expr.await } + #[cfg(not(feature = #feat))] + { #expr } + }} + } + InvokeArgs::Explicit(feat, expr) => { + let feat_name = &feat; + quote! {{ + #[cfg(feature = #feat_name)] + { #expr.await } + #[cfg(not(feature = #feat_name))] + { #expr } + }} + } + }; + + TokenStream::from(expanded) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_variant() { + // Input: an expression without feature name → Default variant + let input: proc_macro2::TokenStream = "compute(5)".parse().unwrap(); + let args: InvokeArgs = syn::parse2(input).unwrap(); + match args { + InvokeArgs::Default(_) => {} // expected + _ => panic!("expected Default variant"), + } + } + + #[test] + fn explicit_variant() { + // Input: "my_ft" => expr → Explicit variant with feature "my_ft" + let input: proc_macro2::TokenStream = "\"my_ft\" => compute(5)".parse().unwrap(); + let args: InvokeArgs = syn::parse2(input).unwrap(); + match args { + InvokeArgs::Explicit(feat, _) => { + assert_eq!(feat.value(), "my_ft"); + } + _ => panic!("expected Explicit variant"), + } + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..d6a3c37 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,105 @@ +#![doc = include_str!("../doc/lib.md")] +#![deny(missing_docs)] + +use proc_macro::TokenStream; + +pub(crate) mod config; +pub(crate) mod func; +pub(crate) mod invoke; +pub(crate) mod select; + +pub(crate) use proc_macro2::TokenStream as TokenStream2; +pub(crate) use syn::Result as SynResult; + +#[doc = include_str!("../doc/func.md")] +/// +/// # How to use? +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/func.rs")] +/// ``` +/// +/// # Expanded +/// +/// The above code will be expanded into the following: +/// +/// Sync: +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/func_expand.rs")] +/// ``` +/// +/// Async: +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/func_async_expand.rs")] +/// ``` +#[proc_macro_attribute] +pub fn func(attr: TokenStream, item: TokenStream) -> TokenStream { + func::func(attr, item) +} + +#[doc = include_str!("../doc/invoke.md")] +/// +/// # How to use? +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/invoke.rs")] +/// ``` +/// +/// # Expanded +/// +/// The above code will be expanded into the following: +/// +/// Sync: +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/invoke_expand.rs")] +/// ``` +/// +/// Async: +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/invoke_async_expand.rs")] +/// ``` +#[proc_macro] +pub fn invoke(input: TokenStream) -> TokenStream { + invoke::invoke(input) +} + +#[doc = include_str!("../doc/select.md")] +/// +/// # How to use? +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/select.rs")] +/// ``` +/// +/// # Expanded +/// +/// The above code will be expanded into the following: +/// +/// Sync: +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/select_expand.rs")] +/// ``` +/// +/// Async: +/// +/// ``` +/// # use might_be_async::*; +#[doc = include_str!("../doc/usage/select_async_expand.rs")] +/// ``` +#[proc_macro] +pub fn select(input: TokenStream) -> TokenStream { + select::select(input) +} diff --git a/src/select.rs b/src/select.rs new file mode 100644 index 0000000..1a2f8b3 --- /dev/null +++ b/src/select.rs @@ -0,0 +1,311 @@ +use crate::SynResult; +use crate::TokenStream2; +use crate::config::default_feature_name; +use proc_macro::TokenStream; +use proc_macro2::{Spacing, TokenTree}; +use quote::{ToTokens, quote}; +use syn::parse::{Parse, ParseStream}; +use syn::{Expr, LitStr, Token, parse_macro_input}; + +#[doc = include_str!("../doc/args/select_arm.md")] +pub enum SelectArmArgs { + /// "feat_name" => { expr } + Explicit { feat: LitStr, body: Expr }, + + /// ! => { expr } + Not { body: Expr }, + + /// { expr } (no feature name — auto-detect by .await) + Implicit { body: Expr }, +} + +impl Parse for SelectArmArgs { + fn parse(input: ParseStream) -> SynResult<Self> { + parse_one_arm(input) + } +} + +struct SelectInput { + arm0: SelectArmArgs, + arm1: SelectArmArgs, +} + +impl Parse for SelectInput { + fn parse(input: ParseStream) -> SynResult<Self> { + let arm0 = parse_one_arm(input)?; + input.parse::<Token![else]>()?; + let arm1 = parse_one_arm(input)?; + Ok(SelectInput { arm0, arm1 }) + } +} + +/// Parse one arm: either `"feat" => { expr }`, `! => { expr }`, or `{ expr }`. +pub fn parse_one_arm(input: ParseStream) -> SynResult<SelectArmArgs> { + // Parse an explicit feature arm: "feat_name" => { expr } + if input.peek(LitStr) { + let feat: LitStr = input.parse()?; + input.parse::<Token![=>]>()?; + let body: Expr = input.parse()?; + Ok(SelectArmArgs::Explicit { feat, body }) + } + // Parse a negation arm: ! => { expr } + else if input.peek(Token![!]) { + input.parse::<Token![!]>()?; + input.parse::<Token![=>]>()?; + let body: Expr = input.parse()?; + Ok(SelectArmArgs::Not { body }) + } + // Parse an implicit arm: { expr } (no feature name — will auto-detect by .await) + else { + // Expect a block expression { ... } + let body: Expr = input.parse()?; + Ok(SelectArmArgs::Implicit { body }) + } +} + +pub(crate) fn select(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as SelectInput); + let expanded = input.expand(); + TokenStream::from(expanded) +} + +impl SelectInput { + fn expand(&self) -> TokenStream2 { + let arm0 = &self.arm0; + let arm1 = &self.arm1; + + match (arm0, arm1) { + // Both explicit — use cfg!() since no .await to worry about + ( + SelectArmArgs::Explicit { feat: f0, body: b0 }, + SelectArmArgs::Explicit { feat: f1, body: b1 }, + ) => { + let f0_str = f0.value(); + let f1_str = f1.value(); + + if has_not_prefix(&f0_str) && has_not_prefix(&f1_str) { + cfg_block("e! { #b0 }, "e! { #b1 }) + } else if has_not_prefix(&f0_str) { + let inner = &f0_str[1..]; + cfg_block_with_feat(inner, "e! { #b1 }, "e! { #b0 }) + } else if has_not_prefix(&f1_str) { + cfg_block_with_feat(&f0_str, "e! { #b0 }, "e! { #b1 }) + } else { + both_explicit_block(&f0_str, "e! { #b0 }, &f1_str, "e! { #b1 }) + } + } + + // Explicit + Not — cfg!() safe (no .await) + (SelectArmArgs::Explicit { feat, body }, SelectArmArgs::Not { body: not_body }) => { + let feat_str = feat.value(); + if has_not_prefix(&feat_str) { + let inner = &feat_str[1..]; + cfg_block_with_feat(inner, "e! { #not_body }, "e! { #body }) + } else { + cfg_block_with_feat(&feat_str, "e! { #body }, "e! { #not_body }) + } + } + + // Not + Explicit — cfg!() safe (no .await) + (SelectArmArgs::Not { body: not_body }, SelectArmArgs::Explicit { feat, body }) => { + let feat_str = feat.value(); + if has_not_prefix(&feat_str) { + let inner = &feat_str[1..]; + cfg_block_with_feat(inner, "e! { #body }, "e! { #not_body }) + } else { + cfg_block_with_feat(&feat_str, "e! { #body }, "e! { #not_body }) + } + } + + // Explicit + Implicit — cfg!() safe (arms have no .await from this context) + ( + SelectArmArgs::Explicit { feat, body }, + SelectArmArgs::Implicit { body: imp_body }, + ) => { + let feat_str = feat.value(); + if has_not_prefix(&feat_str) { + let inner = &feat_str[1..]; + cfg_block_with_feat(inner, "e! { #imp_body }, "e! { #body }) + } else { + cfg_block_with_feat(&feat_str, "e! { #body }, "e! { #imp_body }) + } + } + + // Implicit + Explicit — cfg!() safe (arms have no .await from this context) + ( + SelectArmArgs::Implicit { body: imp_body }, + SelectArmArgs::Explicit { feat, body }, + ) => { + let feat_str = feat.value(); + if has_not_prefix(&feat_str) { + let inner = &feat_str[1..]; + cfg_block_with_feat(inner, "e! { #body }, "e! { #imp_body }) + } else { + cfg_block_with_feat(&feat_str, "e! { #body }, "e! { #imp_body }) + } + } + + // Both implicit — use #[cfg] blocks to handle .await correctly + (SelectArmArgs::Implicit { body: b0 }, SelectArmArgs::Implicit { body: b1 }) => { + let b0_has_await = token_stream_has_await(&b0.to_token_stream()); + let b1_has_await = token_stream_has_await(&b1.to_token_stream()); + + match (b0_has_await, b1_has_await) { + (true, false) => cfg_block("e! { #b0 }, "e! { #b1 }), + (false, true) => cfg_block("e! { #b1 }, "e! { #b0 }), + (true, true) => { + let b1_stripped = strip_await_from_tokens(&b1.to_token_stream()); + cfg_block("e! { #b0 }, "e! { #b1_stripped }) + } + (false, false) => cfg_block("e! { #b0 }, "e! { #b1 }), + } + } + + // Not + Implicit + (SelectArmArgs::Not { body: not_body }, SelectArmArgs::Implicit { body: imp_body }) => { + cfg_block("e! { #not_body }, "e! { #imp_body }) + } + + // Implicit + Not — use #[cfg] blocks to handle .await correctly + (SelectArmArgs::Implicit { body: imp_body }, SelectArmArgs::Not { body: not_body }) => { + cfg_block("e! { #not_body }, "e! { #imp_body }) + } + + // Two Not + (SelectArmArgs::Not { body: b0 }, SelectArmArgs::Not { body: b1 }) => { + cfg_block("e! { #b0 }, "e! { #b1 }) + } + } + } +} + +/// Generate a block that uses the default feature name. +/// +/// This function creates a `#[cfg]` block that conditionally compiles one of two branches +/// based on whether the default feature (as returned by [`default_feature_name()`]) is enabled. +fn cfg_block(async_branch: &TokenStream2, sync_branch: &TokenStream2) -> TokenStream2 { + let feat = default_feature_name(); + cfg_block_with_feat(feat, async_branch, sync_branch) +} + +/// Generate a block using a specific feature name. +fn cfg_block_with_feat( + feat: &str, + async_branch: &TokenStream2, + sync_branch: &TokenStream2, +) -> TokenStream2 { + quote! {{ + #[cfg(feature = #feat)] + { #async_branch } + #[cfg(not(feature = #feat))] + { #sync_branch } + }} +} + +/// Generate a block where each arm is gated by its own feature. +fn both_explicit_block( + feat0: &str, + branch0: &TokenStream2, + feat1: &str, + branch1: &TokenStream2, +) -> TokenStream2 { + quote! {{ + #[cfg(feature = #feat0)] + { #branch0 } + #[cfg(feature = #feat1)] + { #branch1 } + }} +} + +/// Checks if the given string has the '!' (not) prefix. +/// This is used to denote negated feature names in select! arms. +fn has_not_prefix(s: &str) -> bool { + s.starts_with('!') +} + +/// Checks if the given token stream contains a `.await` expression. +/// +/// This function traverses the token stream looking for the pattern `. await`, +/// which indicates an `.await` call in Rust syntax. It is used to determine +/// whether an implicit select arm contains async code, which influences how +/// the generated code handles the `cfg` blocks. +/// +/// Returns `true` if `.await` is found, `false` otherwise. +fn token_stream_has_await(ts: &TokenStream2) -> bool { + let mut tokens = ts.clone().into_iter(); + while let Some(token) = tokens.next() { + if let TokenTree::Punct(p) = &token + && p.as_char() == '.' + && p.spacing() == Spacing::Alone + && let Some(TokenTree::Ident(ident)) = tokens.next() + && ident == "await" + { + return true; + } + } + false +} + +/// Strips a trailing `.await` from a token stream. +fn strip_await_from_tokens(ts: &TokenStream2) -> TokenStream2 { + let tokens: Vec<_> = ts.clone().into_iter().collect(); + let len = tokens.len(); + if len >= 2 + && let TokenTree::Punct(p) = &tokens[len - 2] + && p.as_char() == '.' + && let TokenTree::Ident(ident) = &tokens[len - 1] + && ident == "await" + { + return tokens[..len - 2].iter().cloned().collect(); + } + ts.clone() +} + +#[cfg(test)] +mod tests { + use crate::select::SelectArmArgs; + use quote::ToTokens; + + #[test] + fn test_explicit_arm() { + let input: proc_macro2::TokenStream = "\"async\" => { 100 }".parse().unwrap(); + let arm: SelectArmArgs = syn::parse2(input).unwrap(); + match &arm { + SelectArmArgs::Explicit { feat, body } => { + assert_eq!(feat.value(), "async"); + let s = body.to_token_stream().to_string(); + assert!(s.contains("100"), "body should contain 100, got: {s}"); + } + _ => panic!("expected Explicit variant"), + } + } + + #[test] + fn test_not_arm() { + let input: proc_macro2::TokenStream = "! => { 200 }".parse().unwrap(); + let arm: SelectArmArgs = syn::parse2(input).unwrap(); + match &arm { + SelectArmArgs::Not { body } => { + let s = body.to_token_stream().to_string(); + assert!(s.contains("200"), "body should contain 200, got: {s}"); + } + _ => panic!("expected Not variant"), + } + } + + #[test] + fn test_implicit_arm() { + let input: proc_macro2::TokenStream = "{ 1 + 2 }".parse().unwrap(); + let arm: SelectArmArgs = syn::parse2(input).unwrap(); + match &arm { + SelectArmArgs::Implicit { body } => { + let s = body.to_token_stream().to_string(); + assert!( + s.contains("1 + 2") || s.contains("1+2"), + "body should contain 1 + 2, got: {s}" + ); + } + _ => panic!("expected Implicit variant"), + } + } +} diff --git a/test/Cargo.lock b/test/Cargo.lock new file mode 100644 index 0000000..5d4be76 --- /dev/null +++ b/test/Cargo.lock @@ -0,0 +1,290 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "futures" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" + +[[package]] +name = "futures-executor" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a" + +[[package]] +name = "futures-macro" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "futures-sink" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307" + +[[package]] +name = "futures-task" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" + +[[package]] +name = "futures-util" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "might_be_async" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "toml", +] + +[[package]] +name = "might_be_async_test_async" +version = "0.1.0" +dependencies = [ + "futures", + "might_be_async", +] + +[[package]] +name = "might_be_async_test_sync" +version = "0.1.0" +dependencies = [ + "might_be_async", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] diff --git a/test/Cargo.toml b/test/Cargo.toml new file mode 100644 index 0000000..b92b54b --- /dev/null +++ b/test/Cargo.toml @@ -0,0 +1,3 @@ +[workspace] +members = ["sync", "async"] +resolver = "2" diff --git a/test/async/Cargo.toml b/test/async/Cargo.toml new file mode 100644 index 0000000..8184940 --- /dev/null +++ b/test/async/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "might_be_async_test_async" +version = "0.1.0" +edition = "2024" + +[features] +sync = [] +metadata_async = [] +custom_ft = [] +custom_invoke = [] + +[package.metadata.might_be_async] +default_feature_name = "metadata_async" + +[dependencies] +might_be_async = { path = "../.." } +futures = "0.3" diff --git a/test/async/src/lib.rs b/test/async/src/lib.rs new file mode 100644 index 0000000..a5e000a --- /dev/null +++ b/test/async/src/lib.rs @@ -0,0 +1,2 @@ +#![allow(unused)] +include!("../../src/lib.rs"); diff --git a/test/src/lib.rs b/test/src/lib.rs new file mode 100644 index 0000000..5e91425 --- /dev/null +++ b/test/src/lib.rs @@ -0,0 +1,3 @@ +include!("test_func.rs"); +include!("test_invoke.rs"); +include!("test_select.rs"); diff --git a/test/src/test_func.rs b/test/src/test_func.rs new file mode 100644 index 0000000..71fe365 --- /dev/null +++ b/test/src/test_func.rs @@ -0,0 +1,36 @@ +#[might_be_async::func] +fn identity(x: i32) -> i32 { + x +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_func_identity() { + assert_eq!(identity(42), 42); +} + +#[might_be_async::func] +fn first<T: PartialEq + Clone>(a: T, _b: T) -> T +where + T: std::fmt::Debug, +{ + a.clone() +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_func_generic() { + assert_eq!(first(1, 2), 1); + assert_eq!(first("a", "b"), "a"); +} + +#[might_be_async::func("custom_ft")] +fn triple(x: i32) -> i32 { + x * 3 +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_func_custom_feature() { + assert_eq!(triple(3), 9); +} diff --git a/test/src/test_invoke.rs b/test/src/test_invoke.rs new file mode 100644 index 0000000..b8506e9 --- /dev/null +++ b/test/src/test_invoke.rs @@ -0,0 +1,50 @@ +// ─── 测试 1: 默认 feature 名 ───────────────────────────────────────────────── +// +// 不指定 feature → 用 Cargo.toml 的 default_feature_name = "metadata_async" +// +// 展开(feature "metadata_async" 关闭时): +// { #[cfg(feature = "metadata_async")] { double(5).await } +// #[cfg(not(feature = "metadata_async"))] { double(5) } } + +#[cfg(not(feature = "metadata_async"))] +fn double(x: i32) -> i32 { + x * 2 +} + +#[cfg(feature = "metadata_async")] +async fn double(x: i32) -> i32 { + x * 2 +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_invoke_default() { + assert_eq!(might_be_async::invoke!(double(5)), 10); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_invoke_default() { + let result = futures::executor::block_on(async { might_be_async::invoke!(double(5)) }); + assert_eq!(result, 10); +} + +#[might_be_async::func] +fn square(x: i32) -> i32 { + x * x +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_invoke_explicit() { + assert_eq!(might_be_async::invoke!("metadata_async" => square(6)), 36); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_invoke_explicit() { + let result = futures::executor::block_on(async { + might_be_async::invoke!("metadata_async" => square(6)) + }); + assert_eq!(result, 36); +} diff --git a/test/src/test_select.rs b/test/src/test_select.rs new file mode 100644 index 0000000..2cf3bfe --- /dev/null +++ b/test/src/test_select.rs @@ -0,0 +1,92 @@ +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_select_explicit() { + let r = might_be_async::select! { "metadata_async" => { 1 } else ! => { 2 } }; + assert_eq!(r, 2); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_select_explicit() { + let r = might_be_async::select! { "metadata_async" => { 1 } else ! => { 2 } }; + assert_eq!(r, 1); +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_select_not() { + let r = might_be_async::select! { "metadata_async" => { 10 } else ! => { 20 } }; + assert_eq!(r, 20); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_select_not() { + let r = might_be_async::select! { "metadata_async" => { 10 } else ! => { 20 } }; + assert_eq!(r, 10); +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_select_not_first() { + let r = might_be_async::select! { ! => { 30 } else "metadata_async" => { 40 } }; + assert_eq!(r, 30); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_select_not_first() { + let r = might_be_async::select! { ! => { 30 } else "metadata_async" => { 40 } }; + assert_eq!(r, 40); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_select_both_explicit() { + let r = might_be_async::select! { "metadata_async" => { 100 } else "custom_ft" => { 200 } }; + assert_eq!(r, 100); +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_select_implicit() { + let r = might_be_async::select! { { 1 + 2 } else { 3 + 4 } }; + assert_eq!(r, 7); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_select_implicit() { + let r = futures::executor::block_on(async { + might_be_async::select! { { 1 + 2 } else { 3 + 4 } } + }); + assert_eq!(r, 3); +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_select_mixed_explicit_first() { + let r = might_be_async::select! { "metadata_async" => { 100 } else { 200 } }; + assert_eq!(r, 200); +} + +#[cfg(feature = "metadata_async")] +#[test] +fn test_select_mixed_explicit_first() { + let r = might_be_async::select! { "metadata_async" => { 100 } else { 200 } }; + assert_eq!(r, 100); +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_select_metadata_default() { + let r = might_be_async::select! { { 50 } else { 60 } }; + assert_eq!(r, 60); +} + +#[cfg(not(feature = "metadata_async"))] +#[test] +fn test_select_metadata_two_not() { + let r = might_be_async::select! { ! => { 70 } else ! => { 80 } }; + assert_eq!(r, 80); +} diff --git a/test/sync/Cargo.toml b/test/sync/Cargo.toml new file mode 100644 index 0000000..a2491da --- /dev/null +++ b/test/sync/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "might_be_async_test_sync" +version = "0.1.0" +edition = "2024" + +[features] +sync = [] +metadata_async = [] +custom_ft = [] +custom_invoke = [] + +[package.metadata.might_be_async] +default_feature_name = "metadata_async" + +[dependencies] +might_be_async = { path = "../.." } diff --git a/test/sync/src/lib.rs b/test/sync/src/lib.rs new file mode 100644 index 0000000..a5e000a --- /dev/null +++ b/test/sync/src/lib.rs @@ -0,0 +1,2 @@ +#![allow(unused)] +include!("../../src/lib.rs"); |
