futures-macro-0.3.17/.cargo_vcs_info.json0000644000000001120000000000100137120ustar { "git": { "sha1": "7caefa51304e78fd5018cd5d2a03f3b9089cc010" } } futures-macro-0.3.17/Cargo.toml0000644000000021740000000000100117220ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "futures-macro" version = "0.3.17" authors = ["Taylor Cramer ", "Taiki Endo "] description = "The futures-rs procedural macro implementations.\n" homepage = "https://rust-lang.github.io/futures-rs" documentation = "https://docs.rs/futures-macro/0.3" 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.19" [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "1.0.56" features = ["full"] [build-dependencies.autocfg] version = "1" [features] futures-macro-0.3.17/Cargo.toml.orig000064400000000000000000000011460072674642500154310ustar 00000000000000[package] name = "futures-macro" edition = "2018" version = "0.3.17" authors = ["Taylor Cramer ", "Taiki Endo "] 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" description = """ The futures-rs procedural macro implementations. """ [lib] proc-macro = true [features] [build-dependencies] autocfg = "1" [dependencies] proc-macro2 = "1.0" proc-macro-hack = "0.5.19" quote = "1.0" syn = { version = "1.0.56", features = ["full"] } futures-macro-0.3.17/LICENSE-APACHE000064400000000000000000000251720072674642500144730ustar 00000000000000 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. futures-macro-0.3.17/LICENSE-MIT000064400000000000000000000021060072674642500141730ustar 00000000000000Copyright (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. futures-macro-0.3.17/build.rs000064400000000000000000000017270072674642500142140ustar 00000000000000#![warn(rust_2018_idioms, single_use_lifetimes)] use autocfg::AutoCfg; // The rustc-cfg strings below are *not* public API. Please let us know by // opening a GitHub issue if your build environment requires some way to enable // these cfgs other than by executing our build script. fn main() { let cfg = match AutoCfg::new() { Ok(cfg) => cfg, Err(e) => { println!( "cargo:warning={}: unable to determine rustc version: {}", env!("CARGO_PKG_NAME"), e ); return; } }; // Function like procedural macros in expressions patterns statements stabilized in Rust 1.45: // https://blog.rust-lang.org/2020/07/16/Rust-1.45.0.html#stabilizing-function-like-procedural-macros-in-expressions-patterns-and-statements if cfg.probe_rustc_version(1, 45) { println!("cargo:rustc-cfg=fn_like_proc_macro"); } println!("cargo:rerun-if-changed=build.rs"); } futures-macro-0.3.17/src/executor.rs000064400000000000000000000034030072674642500155330ustar 00000000000000use proc_macro::TokenStream; use proc_macro2::Span; use quote::{quote, quote_spanned, ToTokens}; pub(crate) fn test(args: TokenStream, item: TokenStream) -> TokenStream { if !args.is_empty() { return syn::Error::new_spanned(proc_macro2::TokenStream::from(args), "invalid argument") .to_compile_error() .into(); } let mut input = syn::parse_macro_input!(item as syn::ItemFn); if input.sig.asyncness.take().is_none() { return syn::Error::new_spanned(input.sig.fn_token, "Only async functions are supported") .to_compile_error() .into(); } // If type mismatch occurs, the current rustc points to the last statement. let (last_stmt_start_span, last_stmt_end_span) = { let mut last_stmt = input .block .stmts .last() .map(ToTokens::into_token_stream) .unwrap_or_default() .into_iter(); // `Span` on stable Rust has a limitation that only points to the first // token, not the whole tokens. We can work around this limitation by // using the first/last span of the tokens like // `syn::Error::new_spanned` does. let start = last_stmt.next().map_or_else(Span::call_site, |t| t.span()); let end = last_stmt.last().map_or(start, |t| t.span()); (start, end) }; let path = quote_spanned! {last_stmt_start_span=> ::futures_test::__private }; let body = &input.block; input.block.stmts = vec![syn::Stmt::Expr( syn::parse2(quote_spanned! {last_stmt_end_span=> #path::block_on(async #body) }) .unwrap(), )]; let gen = quote! { #[::core::prelude::v1::test] #input }; gen.into() } futures-macro-0.3.17/src/join.rs000064400000000000000000000114340072674642500146370ustar 00000000000000//! 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::{Expr, Ident, Token}; #[derive(Default)] struct Join { fut_exprs: Vec, } impl Parse for Join { fn parse(input: ParseStream<'_>) -> syn::Result { let mut join = Self::default(); while !input.is_empty() { join.fut_exprs.push(input.parse::()?); if !input.is_empty() { input.parse::()?; } } Ok(join) } } fn bind_futures(fut_exprs: Vec, span: Span) -> (Vec, Vec) { 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); // should be def_site, but that's unstable let span = Span::call_site(); let (future_let_bindings, future_names) = bind_futures(parsed.fut_exprs, span); let poll_futures = future_names.iter().map(|fut| { quote! { __all_done &= __futures_crate::future::Future::poll( unsafe { __futures_crate::Pin::new_unchecked(&mut #fut) }, __cx).is_ready(); } }); let take_outputs = future_names.iter().map(|fut| { quote! { unsafe { __futures_crate::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::task::Poll::Ready(( #( #take_outputs )* )) } else { __futures_crate::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); // should be def_site, but that's unstable let span = Span::call_site(); let (future_let_bindings, future_names) = bind_futures(parsed.fut_exprs, span); let poll_futures = future_names.iter().map(|fut| { quote! { if __futures_crate::future::Future::poll( unsafe { __futures_crate::Pin::new_unchecked(&mut #fut) }, __cx).is_pending() { __all_done = false; } else if unsafe { __futures_crate::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::task::Poll::Ready( __futures_crate::Err( unsafe { __futures_crate::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::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::task::Poll::Ready( __futures_crate::Ok(( #( #take_outputs )* )) ) } else { __futures_crate::task::Poll::Pending } }).await } }) } futures-macro-0.3.17/src/lib.rs000064400000000000000000000041670072674642500144530ustar 00000000000000//! The futures-rs procedural macro implementations. #![warn(rust_2018_idioms, single_use_lifetimes, unreachable_pub)] #![doc(test( no_crate_inject, attr( deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code, unused_assignments, unused_variables) ) ))] // 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; mod executor; mod join; mod select; mod stream_select; /// The `join!` macro. #[cfg_attr(fn_like_proc_macro, proc_macro)] #[cfg_attr(not(fn_like_proc_macro), proc_macro_hack::proc_macro_hack)] pub fn join_internal(input: TokenStream) -> TokenStream { crate::join::join(input) } /// The `try_join!` macro. #[cfg_attr(fn_like_proc_macro, proc_macro)] #[cfg_attr(not(fn_like_proc_macro), proc_macro_hack::proc_macro_hack)] pub fn try_join_internal(input: TokenStream) -> TokenStream { crate::join::try_join(input) } /// The `select!` macro. #[cfg_attr(fn_like_proc_macro, proc_macro)] #[cfg_attr(not(fn_like_proc_macro), proc_macro_hack::proc_macro_hack)] pub fn select_internal(input: TokenStream) -> TokenStream { crate::select::select(input) } /// The `select_biased!` macro. #[cfg_attr(fn_like_proc_macro, proc_macro)] #[cfg_attr(not(fn_like_proc_macro), proc_macro_hack::proc_macro_hack)] pub fn select_biased_internal(input: TokenStream) -> TokenStream { crate::select::select_biased(input) } // TODO: Change this to doc comment once rustdoc bug fixed. // The `test` attribute. #[proc_macro_attribute] pub fn test_internal(input: TokenStream, item: TokenStream) -> TokenStream { crate::executor::test(input, item) } /// The `stream_select!` macro. #[cfg_attr(fn_like_proc_macro, proc_macro)] #[cfg_attr(not(fn_like_proc_macro), proc_macro_hack::proc_macro_hack)] pub fn stream_select_internal(input: TokenStream) -> TokenStream { crate::stream_select::stream_select(input.into()) .unwrap_or_else(syn::Error::into_compile_error) .into() } futures-macro-0.3.17/src/select.rs000064400000000000000000000264350072674642500151660ustar 00000000000000//! The futures-rs `select! macro implementation. use proc_macro::TokenStream; use proc_macro2::Span; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::{parse_quote, Expr, Ident, Pat, Token}; mod kw { syn::custom_keyword!(complete); } struct Select { // span of `complete`, then expression after `=> ...` complete: Option, default: Option, normal_fut_exprs: Vec, 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 { let mut select = Self { complete: None, default: None, normal_fut_exprs: vec![], normal_fut_handlers: vec![], }; 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::()?; 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::()?; CaseKind::Default } else { // ` = ` let pat = input.parse()?; input.parse::()?; let expr = input.parse()?; CaseKind::Normal(pat, expr) }; // `=> ` input.parse::]>()?; let expr = input.parse::()?; // 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::>()?; } else { input.parse::()?; } 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, syn::ItemEnum) { // "_0", "_1", "_2" let variant_names: Vec = (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); // 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>` // 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 { __futures_crate::Pin::new_unchecked(&mut #bound_future_name) }; if __futures_crate::future::FusedFuture::is_terminated(&#bound_future_name) { __futures_crate::None } else { __futures_crate::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<'_> ) -> __futures_crate::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<'_> ) -> __futures_crate::Option<__futures_crate::task::Poll<_>> = poller; match poller(__cx) { __futures_crate::Some(x @ __futures_crate::task::Poll::Ready(_)) => return x, __futures_crate::Some(__futures_crate::task::Poll::Pending) => { __any_polled = true; } __futures_crate::None => {} } } if !__any_polled { #none_polled } else { __futures_crate::task::Poll::Pending } }; #await_select_fut }; #execute_result_expr } }) } futures-macro-0.3.17/src/stream_select.rs000064400000000000000000000122460072674642500165340ustar 00000000000000use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{parse::Parser, punctuated::Punctuated, Expr, Index, Token}; /// The `stream_select!` macro. pub(crate) fn stream_select(input: TokenStream) -> Result { let args = Punctuated::::parse_terminated.parse2(input)?; if args.len() < 2 { return Ok(quote! { compile_error!("stream select macro needs at least two arguments.") }); } let generic_idents = (0..args.len()).map(|i| format_ident!("_{}", i)).collect::>(); let field_idents = (0..args.len()).map(|i| format_ident!("__{}", i)).collect::>(); let field_idents_2 = (0..args.len()).map(|i| format_ident!("___{}", i)).collect::>(); let field_indices = (0..args.len()).map(Index::from).collect::>(); let args = args.iter().map(|e| e.to_token_stream()); Ok(quote! { { #[derive(Debug)] struct StreamSelect<#(#generic_idents),*> (#(Option<#generic_idents>),*); enum StreamEnum<#(#generic_idents),*> { #( #generic_idents(#generic_idents) ),*, None, } impl __futures_crate::stream::Stream for StreamEnum<#(#generic_idents),*> where #(#generic_idents: __futures_crate::stream::Stream + ::std::marker::Unpin,)* { type Item = ITEM; fn poll_next(mut self: ::std::pin::Pin<&mut Self>, cx: &mut __futures_crate::task::Context<'_>) -> __futures_crate::task::Poll> { match self.get_mut() { #( Self::#generic_idents(#generic_idents) => ::std::pin::Pin::new(#generic_idents).poll_next(cx) ),*, Self::None => panic!("StreamEnum::None should never be polled!"), } } } impl __futures_crate::stream::Stream for StreamSelect<#(#generic_idents),*> where #(#generic_idents: __futures_crate::stream::Stream + ::std::marker::Unpin,)* { type Item = ITEM; fn poll_next(mut self: ::std::pin::Pin<&mut Self>, cx: &mut __futures_crate::task::Context<'_>) -> __futures_crate::task::Poll> { let Self(#(ref mut #field_idents),*) = self.get_mut(); #( let mut #field_idents_2 = false; )* let mut any_pending = false; { let mut stream_array = [#(#field_idents.as_mut().map(|f| StreamEnum::#generic_idents(f)).unwrap_or(StreamEnum::None)),*]; __futures_crate::async_await::shuffle(&mut stream_array); for mut s in stream_array { if let StreamEnum::None = s { continue; } else { match __futures_crate::stream::Stream::poll_next(::std::pin::Pin::new(&mut s), cx) { r @ __futures_crate::task::Poll::Ready(Some(_)) => { return r; }, __futures_crate::task::Poll::Pending => { any_pending = true; }, __futures_crate::task::Poll::Ready(None) => { match s { #( StreamEnum::#generic_idents(_) => { #field_idents_2 = true; } ),*, StreamEnum::None => panic!("StreamEnum::None should never be polled!"), } }, } } } } #( if #field_idents_2 { *#field_idents = None; } )* if any_pending { __futures_crate::task::Poll::Pending } else { __futures_crate::task::Poll::Ready(None) } } fn size_hint(&self) -> (usize, Option) { let mut s = (0, Some(0)); #( if let Some(new_hint) = self.#field_indices.as_ref().map(|s| s.size_hint()) { s.0 += new_hint.0; // We can change this out for `.zip` when the MSRV is 1.46.0 or higher. s.1 = s.1.and_then(|a| new_hint.1.map(|b| a + b)); } )* s } } StreamSelect(#(Some(#args)),*) } }) }