summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJason Macnak <natsu@google.com>2020-03-18 01:44:41 +0000
committerJason Macnak <natsu@google.com>2020-04-06 10:35:09 -0700
commit413790afee04213ea0901a945427cc1d397e1ca3 (patch)
tree5feb66a100c3263e45af504d30b4b8ad9d2a6158
parentf69663a185a8b7d20a8d814ce1c14939bea04b30 (diff)
downloadfutures-macro-413790afee04213ea0901a945427cc1d397e1ca3.tar.gz
Import 'futures-macro' rust crate version 0.3.4
Bug: b/151760391 Test: m crosvm.experimental Change-Id: I8169563a9a5da3508965ddca4d9d5e12b8bdb340
-rw-r--r--Android.bp23
-rw-r--r--Cargo.toml39
-rw-r--r--Cargo.toml.orig23
l---------LICENSE1
-rw-r--r--LICENSE-APACHE202
-rw-r--r--LICENSE-MIT26
-rw-r--r--METADATA17
-rw-r--r--MODULE_LICENSE_APACHE20
l---------NOTICE1
-rw-r--r--src/join.rs170
-rw-r--r--src/lib.rs46
-rw-r--r--src/select.rs345
12 files changed, 893 insertions, 0 deletions
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..a442b34
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,23 @@
+// This file is generated by cargo2android.py.
+
+rust_proc_macro {
+ name: "libfutures_macro",
+ crate_name: "futures_macro",
+ srcs: ["src/lib.rs"],
+ edition: "2018",
+ rlibs: [
+ "libproc_macro2",
+ "libquote",
+ "libsyn",
+ ],
+ proc_macros: [
+ "libproc_macro_hack",
+ ],
+}
+
+// dependent_library ["feature_list"]
+// proc-macro-hack-0.5.11
+// proc-macro2-1.0.9 "default,proc-macro"
+// quote-1.0.3 "default,proc-macro"
+// syn-1.0.16 "clone-impls,default,derive,full,parsing,printing,proc-macro,quote"
+// unicode-xid-0.2.0 "default"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..14dfe71
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,39 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+edition = "2018"
+name = "futures-macro"
+version = "0.3.4"
+authors = ["Taylor Cramer <cramertj@google.com>", "Taiki Endo <te316e89@gmail.com>"]
+description = "The futures-rs procedural macro implementations.\n"
+homepage = "https://rust-lang.github.io/futures-rs"
+documentation = "https://docs.rs/futures-macro/0.3.0"
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/rust-lang/futures-rs"
+
+[lib]
+proc-macro = true
+[dependencies.proc-macro-hack]
+version = "0.5.9"
+
+[dependencies.proc-macro2]
+version = "1.0"
+
+[dependencies.quote]
+version = "1.0"
+
+[dependencies.syn]
+version = "1.0"
+features = ["full"]
+
+[features]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..ccc1715
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,23 @@
+[package]
+name = "futures-macro"
+edition = "2018"
+version = "0.3.4"
+authors = ["Taylor Cramer <cramertj@google.com>", "Taiki Endo <te316e89@gmail.com>"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/rust-lang/futures-rs"
+homepage = "https://rust-lang.github.io/futures-rs"
+documentation = "https://docs.rs/futures-macro/0.3.0"
+description = """
+The futures-rs procedural macro implementations.
+"""
+
+[lib]
+proc-macro = true
+
+[features]
+
+[dependencies]
+proc-macro2 = "1.0"
+proc-macro-hack = "0.5.9"
+quote = "1.0"
+syn = { version = "1.0", features = ["full"] }
diff --git a/LICENSE b/LICENSE
new file mode 120000
index 0000000..6b579aa
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1 @@
+LICENSE-APACHE \ No newline at end of file
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..9eb0b09
--- /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 (c) 2016 Alex Crichton
+Copyright (c) 2017 The Tokio Authors
+
+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..8ad082e
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,26 @@
+Copyright (c) 2016 Alex Crichton
+Copyright (c) 2017 The Tokio Authors
+
+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/METADATA b/METADATA
new file mode 100644
index 0000000..a29b746
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,17 @@
+name: "futures-macro"
+description:
+ "The futures-rs procedural macro implementations."
+
+third_party {
+ url {
+ type: HOMEPAGE
+ value: "https://crates.io/crates/futures-macro"
+ }
+ url {
+ type: GIT
+ value: "https://github.com/rust-lang/futures-rs"
+ }
+ version: "0.3.4"
+ last_upgrade_date { year: 2020 month: 3 day: 17 }
+ license_type: NOTICE
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/NOTICE b/NOTICE
new file mode 120000
index 0000000..7a694c9
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1 @@
+LICENSE \ No newline at end of file
diff --git a/src/join.rs b/src/join.rs
new file mode 100644
index 0000000..2a7b11c
--- /dev/null
+++ b/src/join.rs
@@ -0,0 +1,170 @@
+//! The futures-rs `join! macro implementation.
+
+use proc_macro::TokenStream;
+use proc_macro2::{Span, TokenStream as TokenStream2};
+use quote::{format_ident, quote};
+use syn::parse::{Parse, ParseStream};
+use syn::{parenthesized, parse_quote, Expr, Ident, Token};
+
+mod kw {
+ syn::custom_keyword!(futures_crate_path);
+}
+
+#[derive(Default)]
+struct Join {
+ futures_crate_path: Option<syn::Path>,
+ fut_exprs: Vec<Expr>,
+}
+
+impl Parse for Join {
+ fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
+ let mut join = Join::default();
+
+ // When `futures_crate_path(::path::to::futures::lib)` is provided,
+ // it sets the path through which futures library functions will be
+ // accessed.
+ if input.peek(kw::futures_crate_path) {
+ input.parse::<kw::futures_crate_path>()?;
+ let content;
+ parenthesized!(content in input);
+ join.futures_crate_path = Some(content.parse()?);
+ }
+
+ while !input.is_empty() {
+ join.fut_exprs.push(input.parse::<Expr>()?);
+
+ if !input.is_empty() {
+ input.parse::<Token![,]>()?;
+ }
+ }
+
+ Ok(join)
+ }
+}
+
+fn bind_futures(
+ futures_crate: &syn::Path,
+ fut_exprs: Vec<Expr>,
+ span: Span,
+) -> (Vec<TokenStream2>, Vec<Ident>) {
+ let mut future_let_bindings = Vec::with_capacity(fut_exprs.len());
+ let future_names: Vec<_> = fut_exprs
+ .into_iter()
+ .enumerate()
+ .map(|(i, expr)| {
+ let name = format_ident!("_fut{}", i, span = span);
+ future_let_bindings.push(quote! {
+ // Move future into a local so that it is pinned in one place and
+ // is no longer accessible by the end user.
+ let mut #name = #futures_crate::future::maybe_done(#expr);
+ });
+ name
+ })
+ .collect();
+
+ (future_let_bindings, future_names)
+}
+
+/// The `join!` macro.
+pub(crate) fn join(input: TokenStream) -> TokenStream {
+ let parsed = syn::parse_macro_input!(input as Join);
+
+ let futures_crate = parsed
+ .futures_crate_path
+ .unwrap_or_else(|| parse_quote!(::futures_util));
+
+ // should be def_site, but that's unstable
+ let span = Span::call_site();
+
+ let (future_let_bindings, future_names) = bind_futures(&futures_crate, parsed.fut_exprs, span);
+
+ let poll_futures = future_names.iter().map(|fut| {
+ quote! {
+ __all_done &= #futures_crate::core_reexport::future::Future::poll(
+ unsafe { #futures_crate::core_reexport::pin::Pin::new_unchecked(&mut #fut) }, __cx).is_ready();
+ }
+ });
+ let take_outputs = future_names.iter().map(|fut| {
+ quote! {
+ unsafe { #futures_crate::core_reexport::pin::Pin::new_unchecked(&mut #fut) }.take_output().unwrap(),
+ }
+ });
+
+ TokenStream::from(quote! { {
+ #( #future_let_bindings )*
+
+ #futures_crate::future::poll_fn(move |__cx: &mut #futures_crate::task::Context<'_>| {
+ let mut __all_done = true;
+ #( #poll_futures )*
+ if __all_done {
+ #futures_crate::core_reexport::task::Poll::Ready((
+ #( #take_outputs )*
+ ))
+ } else {
+ #futures_crate::core_reexport::task::Poll::Pending
+ }
+ }).await
+ } })
+}
+
+/// The `try_join!` macro.
+pub(crate) fn try_join(input: TokenStream) -> TokenStream {
+ let parsed = syn::parse_macro_input!(input as Join);
+
+ let futures_crate = parsed
+ .futures_crate_path
+ .unwrap_or_else(|| parse_quote!(::futures_util));
+
+ // should be def_site, but that's unstable
+ let span = Span::call_site();
+
+ let (future_let_bindings, future_names) = bind_futures(&futures_crate, parsed.fut_exprs, span);
+
+ let poll_futures = future_names.iter().map(|fut| {
+ quote! {
+ if #futures_crate::core_reexport::future::Future::poll(
+ unsafe { #futures_crate::core_reexport::pin::Pin::new_unchecked(&mut #fut) }, __cx).is_pending()
+ {
+ __all_done = false;
+ } else if unsafe { #futures_crate::core_reexport::pin::Pin::new_unchecked(&mut #fut) }.output_mut().unwrap().is_err() {
+ // `.err().unwrap()` rather than `.unwrap_err()` so that we don't introduce
+ // a `T: Debug` bound.
+ // Also, for an error type of ! any code after `err().unwrap()` is unreachable.
+ #[allow(unreachable_code)]
+ return #futures_crate::core_reexport::task::Poll::Ready(
+ #futures_crate::core_reexport::result::Result::Err(
+ unsafe { #futures_crate::core_reexport::pin::Pin::new_unchecked(&mut #fut) }.take_output().unwrap().err().unwrap()
+ )
+ );
+ }
+ }
+ });
+ let take_outputs = future_names.iter().map(|fut| {
+ quote! {
+ // `.ok().unwrap()` rather than `.unwrap()` so that we don't introduce
+ // an `E: Debug` bound.
+ // Also, for an ok type of ! any code after `ok().unwrap()` is unreachable.
+ #[allow(unreachable_code)]
+ unsafe { #futures_crate::core_reexport::pin::Pin::new_unchecked(&mut #fut) }.take_output().unwrap().ok().unwrap(),
+ }
+ });
+
+ TokenStream::from(quote! { {
+ #( #future_let_bindings )*
+
+ #[allow(clippy::diverging_sub_expression)]
+ #futures_crate::future::poll_fn(move |__cx: &mut #futures_crate::task::Context<'_>| {
+ let mut __all_done = true;
+ #( #poll_futures )*
+ if __all_done {
+ #futures_crate::core_reexport::task::Poll::Ready(
+ #futures_crate::core_reexport::result::Result::Ok((
+ #( #take_outputs )*
+ ))
+ )
+ } else {
+ #futures_crate::core_reexport::task::Poll::Pending
+ }
+ }).await
+ } })
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..932ec2e
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,46 @@
+//! The futures-rs procedural macro implementations.
+
+#![recursion_limit = "128"]
+#![warn(rust_2018_idioms, unreachable_pub)]
+// It cannot be included in the published code because this lints have false positives in the minimum required version.
+#![cfg_attr(test, warn(single_use_lifetimes))]
+#![warn(clippy::all)]
+
+#![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))]
+
+#![doc(html_root_url = "https://docs.rs/futures-join-macro/0.3.0")]
+
+// Since https://github.com/rust-lang/cargo/pull/7700 `proc_macro` is part of the prelude for
+// proc-macro crates, but to support older compilers we still need this explicit `extern crate`.
+#[allow(unused_extern_crates)]
+extern crate proc_macro;
+
+use proc_macro::TokenStream;
+use proc_macro_hack::proc_macro_hack;
+
+mod join;
+mod select;
+
+/// The `join!` macro.
+#[proc_macro_hack]
+pub fn join(input: TokenStream) -> TokenStream {
+ crate::join::join(input)
+}
+
+/// The `try_join!` macro.
+#[proc_macro_hack]
+pub fn try_join(input: TokenStream) -> TokenStream {
+ crate::join::try_join(input)
+}
+
+/// The `select!` macro.
+#[proc_macro_hack]
+pub fn select(input: TokenStream) -> TokenStream {
+ crate::select::select(input)
+}
+
+/// The `select_biased!` macro.
+#[proc_macro_hack]
+pub fn select_biased(input: TokenStream) -> TokenStream {
+ crate::select::select_biased(input)
+}
diff --git a/src/select.rs b/src/select.rs
new file mode 100644
index 0000000..f7f688b
--- /dev/null
+++ b/src/select.rs
@@ -0,0 +1,345 @@
+//! The futures-rs `select! macro implementation.
+
+use proc_macro::TokenStream;
+use proc_macro2::Span;
+use quote::{format_ident, quote};
+use syn::{parenthesized, parse_quote, Expr, Ident, Pat, Token};
+use syn::parse::{Parse, ParseStream};
+
+mod kw {
+ syn::custom_keyword!(complete);
+ syn::custom_keyword!(futures_crate_path);
+}
+
+struct Select {
+ futures_crate_path: Option<syn::Path>,
+ // span of `complete`, then expression after `=> ...`
+ complete: Option<Expr>,
+ default: Option<Expr>,
+ normal_fut_exprs: Vec<Expr>,
+ normal_fut_handlers: Vec<(Pat, Expr)>,
+}
+
+#[allow(clippy::large_enum_variant)]
+enum CaseKind {
+ Complete,
+ Default,
+ Normal(Pat, Expr),
+}
+
+impl Parse for Select {
+ fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
+ let mut select = Select {
+ futures_crate_path: None,
+ complete: None,
+ default: None,
+ normal_fut_exprs: vec![],
+ normal_fut_handlers: vec![],
+ };
+
+ // When `futures_crate_path(::path::to::futures::lib)` is provided,
+ // it sets the path through which futures library functions will be
+ // accessed.
+ if input.peek(kw::futures_crate_path) {
+ input.parse::<kw::futures_crate_path>()?;
+ let content;
+ parenthesized!(content in input);
+ select.futures_crate_path = Some(content.parse()?);
+ }
+
+ while !input.is_empty() {
+ let case_kind = if input.peek(kw::complete) {
+ // `complete`
+ if select.complete.is_some() {
+ return Err(input.error("multiple `complete` cases found, only one allowed"));
+ }
+ input.parse::<kw::complete>()?;
+ CaseKind::Complete
+ } else if input.peek(Token![default]) {
+ // `default`
+ if select.default.is_some() {
+ return Err(input.error("multiple `default` cases found, only one allowed"));
+ }
+ input.parse::<Ident>()?;
+ CaseKind::Default
+ } else {
+ // `<pat> = <expr>`
+ let pat = input.parse()?;
+ input.parse::<Token![=]>()?;
+ let expr = input.parse()?;
+ CaseKind::Normal(pat, expr)
+ };
+
+ // `=> <expr>`
+ input.parse::<Token![=>]>()?;
+ let expr = input.parse::<Expr>()?;
+
+ // Commas after the expression are only optional if it's a `Block`
+ // or it is the last branch in the `match`.
+ let is_block = match expr { Expr::Block(_) => true, _ => false };
+ if is_block || input.is_empty() {
+ input.parse::<Option<Token![,]>>()?;
+ } else {
+ input.parse::<Token![,]>()?;
+ }
+
+ match case_kind {
+ CaseKind::Complete => select.complete = Some(expr),
+ CaseKind::Default => select.default = Some(expr),
+ CaseKind::Normal(pat, fut_expr) => {
+ select.normal_fut_exprs.push(fut_expr);
+ select.normal_fut_handlers.push((pat, expr));
+ },
+ }
+ }
+
+ Ok(select)
+ }
+}
+
+// Enum over all the cases in which the `select!` waiting has completed and the result
+// can be processed.
+//
+// `enum __PrivResult<_1, _2, ...> { _1(_1), _2(_2), ..., Complete }`
+fn declare_result_enum(
+ result_ident: Ident,
+ variants: usize,
+ complete: bool,
+ span: Span
+) -> (Vec<Ident>, syn::ItemEnum) {
+ // "_0", "_1", "_2"
+ let variant_names: Vec<Ident> =
+ (0..variants)
+ .map(|num| format_ident!("_{}", num, span = span))
+ .collect();
+
+ let type_parameters = &variant_names;
+ let variants = &variant_names;
+
+ let complete_variant = if complete {
+ Some(quote!(Complete))
+ } else {
+ None
+ };
+
+ let enum_item = parse_quote! {
+ enum #result_ident<#(#type_parameters,)*> {
+ #(
+ #variants(#type_parameters),
+ )*
+ #complete_variant
+ }
+ };
+
+ (variant_names, enum_item)
+}
+
+/// The `select!` macro.
+pub(crate) fn select(input: TokenStream) -> TokenStream {
+ select_inner(input, true)
+}
+
+/// The `select_biased!` macro.
+pub(crate) fn select_biased(input: TokenStream) -> TokenStream {
+ select_inner(input, false)
+}
+
+fn select_inner(input: TokenStream, random: bool) -> TokenStream {
+ let parsed = syn::parse_macro_input!(input as Select);
+
+ let futures_crate: syn::Path = parsed.futures_crate_path.unwrap_or_else(|| parse_quote!(::futures_util));
+
+ // should be def_site, but that's unstable
+ let span = Span::call_site();
+
+ let enum_ident = Ident::new("__PrivResult", span);
+
+ let (variant_names, enum_item) = declare_result_enum(
+ enum_ident.clone(),
+ parsed.normal_fut_exprs.len(),
+ parsed.complete.is_some(),
+ span,
+ );
+
+ // bind non-`Ident` future exprs w/ `let`
+ let mut future_let_bindings = Vec::with_capacity(parsed.normal_fut_exprs.len());
+ let bound_future_names: Vec<_> = parsed.normal_fut_exprs.into_iter()
+ .zip(variant_names.iter())
+ .map(|(expr, variant_name)| {
+ match expr {
+ syn::Expr::Path(path) => {
+ // Don't bind futures that are already a path.
+ // This prevents creating redundant stack space
+ // for them.
+ // Passing Futures by path requires those Futures to implement Unpin.
+ // We check for this condition here in order to be able to
+ // safely use Pin::new_unchecked(&mut #path) later on.
+ future_let_bindings.push(quote! {
+ #futures_crate::async_await::assert_fused_future(&#path);
+ #futures_crate::async_await::assert_unpin(&#path);
+ });
+ path
+ },
+ _ => {
+ // Bind and pin the resulting Future on the stack. This is
+ // necessary to support direct select! calls on !Unpin
+ // Futures. The Future is not explicitly pinned here with
+ // a Pin call, but assumed as pinned. The actual Pin is
+ // created inside the poll() function below to defer the
+ // creation of the temporary pointer, which would otherwise
+ // increase the size of the generated Future.
+ // Safety: This is safe since the lifetime of the Future
+ // is totally constraint to the lifetime of the select!
+ // expression, and the Future can't get moved inside it
+ // (it is shadowed).
+ future_let_bindings.push(quote! {
+ let mut #variant_name = #expr;
+ });
+ parse_quote! { #variant_name }
+ }
+ }
+ })
+ .collect();
+
+ // For each future, make an `&mut dyn FnMut(&mut Context<'_>) -> Option<Poll<__PrivResult<...>>`
+ // to use for polling that individual future. These will then be put in an array.
+ let poll_functions = bound_future_names.iter().zip(variant_names.iter())
+ .map(|(bound_future_name, variant_name)| {
+ // Below we lazily create the Pin on the Future below.
+ // This is done in order to avoid allocating memory in the generator
+ // for the Pin variable.
+ // Safety: This is safe because one of the following condition applies:
+ // 1. The Future is passed by the caller by name, and we assert that
+ // it implements Unpin.
+ // 2. The Future is created in scope of the select! function and will
+ // not be moved for the duration of it. It is thereby stack-pinned
+ quote! {
+ let mut #variant_name = |__cx: &mut #futures_crate::task::Context<'_>| {
+ let mut #bound_future_name = unsafe {
+ ::core::pin::Pin::new_unchecked(&mut #bound_future_name)
+ };
+ if #futures_crate::future::FusedFuture::is_terminated(&#bound_future_name) {
+ None
+ } else {
+ Some(#futures_crate::future::FutureExt::poll_unpin(
+ &mut #bound_future_name,
+ __cx,
+ ).map(#enum_ident::#variant_name))
+ }
+ };
+ let #variant_name: &mut dyn FnMut(
+ &mut #futures_crate::task::Context<'_>
+ ) -> Option<#futures_crate::task::Poll<_>> = &mut #variant_name;
+ }
+ });
+
+ let none_polled = if parsed.complete.is_some() {
+ quote! {
+ #futures_crate::task::Poll::Ready(#enum_ident::Complete)
+ }
+ } else {
+ quote! {
+ panic!("all futures in select! were completed,\
+ but no `complete =>` handler was provided")
+ }
+ };
+
+ let branches = parsed.normal_fut_handlers.into_iter()
+ .zip(variant_names.iter())
+ .map(|((pat, expr), variant_name)| {
+ quote! {
+ #enum_ident::#variant_name(#pat) => { #expr },
+ }
+ });
+ let branches = quote! { #( #branches )* };
+
+ let complete_branch = parsed.complete.map(|complete_expr| {
+ quote! {
+ #enum_ident::Complete => { #complete_expr },
+ }
+ });
+
+ let branches = quote! {
+ #branches
+ #complete_branch
+ };
+
+ let await_select_fut = if parsed.default.is_some() {
+ // For select! with default this returns the Poll result
+ quote! {
+ __poll_fn(&mut #futures_crate::task::Context::from_waker(
+ #futures_crate::task::noop_waker_ref()
+ ))
+ }
+ } else {
+ quote! {
+ #futures_crate::future::poll_fn(__poll_fn).await
+ }
+ };
+
+ let execute_result_expr = if let Some(default_expr) = &parsed.default {
+ // For select! with default __select_result is a Poll, otherwise not
+ quote! {
+ match __select_result {
+ #futures_crate::task::Poll::Ready(result) => match result {
+ #branches
+ },
+ _ => #default_expr
+ }
+ }
+ } else {
+ quote! {
+ match __select_result {
+ #branches
+ }
+ }
+ };
+
+ let shuffle = if random {
+ quote! {
+ #futures_crate::async_await::shuffle(&mut __select_arr);
+ }
+ } else {
+ quote!()
+ };
+
+ TokenStream::from(quote! { {
+ #enum_item
+
+ let __select_result = {
+ #( #future_let_bindings )*
+
+ let mut __poll_fn = |__cx: &mut #futures_crate::task::Context<'_>| {
+ let mut __any_polled = false;
+
+ #( #poll_functions )*
+
+ let mut __select_arr = [#( #variant_names ),*];
+ #shuffle
+ for poller in &mut __select_arr {
+ let poller: &mut &mut dyn FnMut(
+ &mut #futures_crate::task::Context<'_>
+ ) -> Option<#futures_crate::task::Poll<_>> = poller;
+ match poller(__cx) {
+ Some(x @ #futures_crate::task::Poll::Ready(_)) =>
+ return x,
+ Some(#futures_crate::task::Poll::Pending) => {
+ __any_polled = true;
+ }
+ None => {}
+ }
+ }
+
+ if !__any_polled {
+ #none_polled
+ } else {
+ #futures_crate::task::Poll::Pending
+ }
+ };
+
+ #await_select_fut
+ };
+
+ #execute_result_expr
+ } })
+}