aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoel Galenson <jgalenson@google.com>2020-10-26 20:16:32 +0000
committerAutomerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>2020-10-26 20:16:32 +0000
commitb98dfa9412daeeab3652e6817d732d6f41e2c780 (patch)
tree4570f1524c3f32329007be72f583bcf5a6681a77
parent12bd55e7a1a7a73ffcb02ff621c81d437258b577 (diff)
parentc1939bb53c1a8355f6ac22110d4b01f5bb0345bb (diff)
downloadtokio-macros-b98dfa9412daeeab3652e6817d732d6f41e2c780.tar.gz
Update to tokio-macros-0.3.0 am: d80e56622a am: 35a44d05d0 am: efb60aee42 am: c1939bb53c
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/tokio-macros/+/1472200 Change-Id: I699caafc9f243e614f4cd7a696b9bfd1164ef74a
-rw-r--r--.cargo_vcs_info.json5
-rw-r--r--Android.bp20
-rw-r--r--CHANGELOG.md25
-rw-r--r--Cargo.toml9
-rw-r--r--Cargo.toml.orig8
-rw-r--r--METADATA14
-rw-r--r--src/entry.rs421
-rw-r--r--src/lib.rs228
8 files changed, 368 insertions, 362 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
deleted file mode 100644
index 6b0eb4d..0000000
--- a/.cargo_vcs_info.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "git": {
- "sha1": "c6fc1db6981733c8bfe90d979132b00cfc03b83b"
- }
-}
diff --git a/Android.bp b/Android.bp
index a7be09a..51f7775 100644
--- a/Android.bp
+++ b/Android.bp
@@ -23,31 +23,11 @@ rust_test_host {
"libproc_macro2",
"libquote",
"libsyn",
- "libtokio",
],
}
// dependent_library ["feature_list"]
-// arc-swap-0.4.7
-// bytes-0.5.6 "default,std"
-// cfg-if-0.1.10
-// fnv-1.0.7 "default,std"
-// futures-core-0.3.6 "alloc,default,std"
-// iovec-0.1.4
-// lazy_static-1.4.0
-// libc-0.2.79 "default,std"
-// log-0.4.11
-// memchr-2.3.3 "default,std"
-// mio-0.6.22 "default,with-deprecated"
-// mio-uds-0.6.8
-// net2-0.2.35 "default,duration"
-// num_cpus-1.13.0
-// pin-project-lite-0.1.11
// proc-macro2-1.0.24 "default,proc-macro"
// quote-1.0.7 "default,proc-macro"
-// signal-hook-registry-1.2.1
-// slab-0.4.2
// syn-1.0.46 "clone-impls,default,derive,full,parsing,printing,proc-macro,quote"
-// tokio-0.2.22 "blocking,default,dns,fnv,fs,full,futures-core,io-driver,io-std,io-util,iovec,lazy_static,libc,macros,memchr,mio,mio-named-pipes,mio-uds,net,num_cpus,process,rt-core,rt-threaded,rt-util,signal,signal-hook-registry,slab,stream,sync,tcp,time,tokio-macros,udp,uds,winapi"
-// tokio-macros-0.2.5
// unicode-xid-0.2.1 "default"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d9edc5d..76afcbe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,15 +1,23 @@
+# 0.3.0 (October 15, 2020)
+
+- Track `tokio` 0.3 release.
+
+### Changed
+- options are renamed to track `tokio` runtime builder fn names.
+- `#[tokio::main]` macro requires `rt-multi-thread` when no `flavor` is specified.
+
# 0.2.5 (February 27, 2019)
### Fixed
-- doc improvements (#2225).
+- doc improvements ([#2225]).
# 0.2.4 (January 27, 2019)
### Fixed
-- generics on `#[tokio::main]` function (#2177).
+- generics on `#[tokio::main]` function ([#2177]).
### Added
-- support for `tokio::select!` (#2152).
+- support for `tokio::select!` ([#2152]).
# 0.2.3 (January 7, 2019)
@@ -19,13 +27,20 @@
# 0.2.2 (January 7, 2019)
### Added
-- General refactoring and inclusion of additional runtime options (#2022 and #2038)
+- General refactoring and inclusion of additional runtime options ([#2022] and [#2038])
# 0.2.1 (December 18, 2019)
### Fixes
-- inherit visibility when wrapping async fn (#1954).
+- inherit visibility when wrapping async fn ([#1954]).
# 0.2.0 (November 26, 2019)
- Initial release
+
+[#2225]: https://github.com/tokio-rs/tokio/pull/2225
+[#2177]: https://github.com/tokio-rs/tokio/pull/2177
+[#2152]: https://github.com/tokio-rs/tokio/pull/2152
+[#2038]: https://github.com/tokio-rs/tokio/pull/2038
+[#2022]: https://github.com/tokio-rs/tokio/pull/2022
+[#1954]: https://github.com/tokio-rs/tokio/pull/1954
diff --git a/Cargo.toml b/Cargo.toml
index 75c1c64..759c0bf 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,11 +13,11 @@
[package]
edition = "2018"
name = "tokio-macros"
-version = "0.2.5"
+version = "0.3.0"
authors = ["Tokio Contributors <team@tokio.rs>"]
description = "Tokio's proc macros.\n"
homepage = "https://tokio.rs"
-documentation = "https://docs.rs/tokio-macros/0.2.5/tokio_macros"
+documentation = "https://docs.rs/tokio-macros/0.3.0/tokio_macros"
categories = ["asynchronous"]
license = "MIT"
repository = "https://github.com/tokio-rs/tokio"
@@ -35,8 +35,7 @@ version = "1"
[dependencies.syn]
version = "1.0.3"
features = ["full"]
-[dev-dependencies.tokio]
-version = "0.2.0"
-features = ["full"]
+
+[dev-dependencies]
[features]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
index 2709212..f93cc3e 100644
--- a/Cargo.toml.orig
+++ b/Cargo.toml.orig
@@ -6,14 +6,14 @@ name = "tokio-macros"
# - Update doc url
# - Cargo.toml
# - Update CHANGELOG.md.
-# - Create "v0.1.x" git tag.
-version = "0.2.5"
+# - Create "v0.3.x" git tag.
+version = "0.3.0"
edition = "2018"
authors = ["Tokio Contributors <team@tokio.rs>"]
license = "MIT"
repository = "https://github.com/tokio-rs/tokio"
homepage = "https://tokio.rs"
-documentation = "https://docs.rs/tokio-macros/0.2.5/tokio_macros"
+documentation = "https://docs.rs/tokio-macros/0.3.0/tokio_macros"
description = """
Tokio's proc macros.
"""
@@ -30,7 +30,7 @@ quote = "1"
syn = { version = "1.0.3", features = ["full"] }
[dev-dependencies]
-tokio = { version = "0.2.0", path = "../tokio", features = ["full"] }
+# tokio = { version = "0.3.0", path = "../tokio", features = ["full"] }
[package.metadata.docs.rs]
all-features = true
diff --git a/METADATA b/METADATA
index 8ded395..228939b 100644
--- a/METADATA
+++ b/METADATA
@@ -1,7 +1,5 @@
name: "tokio-macros"
-description:
- "Tokio's proc macros.\n"
-
+description: "Tokio\'s proc macros."
third_party {
url {
type: HOMEPAGE
@@ -9,9 +7,13 @@ third_party {
}
url {
type: ARCHIVE
- value: "https://static.crates.io/crates/tokio-macros/tokio-macros-0.2.5.crate"
+ value: "https://static.crates.io/crates/tokio-macros/tokio-macros-0.3.0.crate"
}
- version: "0.2.5"
- last_upgrade_date { year: 2020 month: 10 day: 15 }
+ version: "0.3.0"
license_type: NOTICE
+ last_upgrade_date {
+ year: 2020
+ month: 10
+ day: 23
+ }
}
diff --git a/src/entry.rs b/src/entry.rs
index 6a58b79..8eb184a 100644
--- a/src/entry.rs
+++ b/src/entry.rs
@@ -1,18 +1,144 @@
use proc_macro::TokenStream;
+use proc_macro2::Span;
use quote::quote;
-use std::num::NonZeroUsize;
+use syn::spanned::Spanned;
#[derive(Clone, Copy, PartialEq)]
-enum Runtime {
- Basic,
+enum RuntimeFlavor {
+ CurrentThread,
Threaded,
}
+impl RuntimeFlavor {
+ fn from_str(s: &str) -> Result<RuntimeFlavor, String> {
+ match s {
+ "current_thread" => Ok(RuntimeFlavor::CurrentThread),
+ "multi_thread" => Ok(RuntimeFlavor::Threaded),
+ "single_thread" => Err("The single threaded runtime flavor is called `current_thread`.".to_string()),
+ "basic_scheduler" => Err("The `basic_scheduler` runtime flavor has been renamed to `current_thread`.".to_string()),
+ "threaded_scheduler" => Err("The `threaded_scheduler` runtime flavor has been renamed to `multi_thread`.".to_string()),
+ _ => Err(format!("No such runtime flavor `{}`. The runtime flavors are `current_thread` and `multi_thread`.", s)),
+ }
+ }
+}
+
+struct FinalConfig {
+ flavor: RuntimeFlavor,
+ worker_threads: Option<usize>,
+}
+
+struct Configuration {
+ rt_multi_thread_available: bool,
+ default_flavor: RuntimeFlavor,
+ flavor: Option<RuntimeFlavor>,
+ worker_threads: Option<(usize, Span)>,
+}
+
+impl Configuration {
+ fn new(is_test: bool, rt_multi_thread: bool) -> Self {
+ Configuration {
+ rt_multi_thread_available: rt_multi_thread,
+ default_flavor: match is_test {
+ true => RuntimeFlavor::CurrentThread,
+ false => RuntimeFlavor::Threaded,
+ },
+ flavor: None,
+ worker_threads: None,
+ }
+ }
+
+ fn set_flavor(&mut self, runtime: syn::Lit, span: Span) -> Result<(), syn::Error> {
+ if self.flavor.is_some() {
+ return Err(syn::Error::new(span, "`flavor` set multiple times."));
+ }
+
+ let runtime_str = parse_string(runtime, span, "flavor")?;
+ let runtime =
+ RuntimeFlavor::from_str(&runtime_str).map_err(|err| syn::Error::new(span, err))?;
+ self.flavor = Some(runtime);
+ Ok(())
+ }
+
+ fn set_worker_threads(
+ &mut self,
+ worker_threads: syn::Lit,
+ span: Span,
+ ) -> Result<(), syn::Error> {
+ if self.worker_threads.is_some() {
+ return Err(syn::Error::new(
+ span,
+ "`worker_threads` set multiple times.",
+ ));
+ }
+
+ let worker_threads = parse_int(worker_threads, span, "worker_threads")?;
+ if worker_threads == 0 {
+ return Err(syn::Error::new(span, "`worker_threads` may not be 0."));
+ }
+ self.worker_threads = Some((worker_threads, span));
+ Ok(())
+ }
+
+ fn build(&self) -> Result<FinalConfig, syn::Error> {
+ let flavor = self.flavor.unwrap_or(self.default_flavor);
+ use RuntimeFlavor::*;
+ match (flavor, self.worker_threads) {
+ (CurrentThread, Some((_, worker_threads_span))) => Err(syn::Error::new(
+ worker_threads_span,
+ "The `worker_threads` option requires the `multi_thread` runtime flavor.",
+ )),
+ (CurrentThread, None) => Ok(FinalConfig {
+ flavor,
+ worker_threads: None,
+ }),
+ (Threaded, worker_threads) if self.rt_multi_thread_available => Ok(FinalConfig {
+ flavor,
+ worker_threads: worker_threads.map(|(val, _span)| val),
+ }),
+ (Threaded, _) => {
+ let msg = if self.flavor.is_none() {
+ "The default runtime flavor is `multi_thread`, but the `rt-multi-thread` feature is disabled."
+ } else {
+ "The runtime flavor `multi_thread` requires the `rt-multi-thread` feature."
+ };
+ Err(syn::Error::new(Span::call_site(), msg))
+ }
+ }
+ }
+}
+
+fn parse_int(int: syn::Lit, span: Span, field: &str) -> Result<usize, syn::Error> {
+ match int {
+ syn::Lit::Int(lit) => match lit.base10_parse::<usize>() {
+ Ok(value) => Ok(value),
+ Err(e) => Err(syn::Error::new(
+ span,
+ format!("Failed to parse {} as integer: {}", field, e),
+ )),
+ },
+ _ => Err(syn::Error::new(
+ span,
+ format!("Failed to parse {} as integer.", field),
+ )),
+ }
+}
+
+fn parse_string(int: syn::Lit, span: Span, field: &str) -> Result<String, syn::Error> {
+ match int {
+ syn::Lit::Str(s) => Ok(s.value()),
+ syn::Lit::Verbatim(s) => Ok(s.to_string()),
+ _ => Err(syn::Error::new(
+ span,
+ format!("Failed to parse {} as string.", field),
+ )),
+ }
+}
+
fn parse_knobs(
mut input: syn::ItemFn,
args: syn::AttributeArgs,
is_test: bool,
- rt_threaded: bool,
+ rt_multi_thread: bool,
) -> Result<TokenStream, syn::Error> {
let sig = &mut input.sig;
let body = &input.block;
@@ -26,9 +152,12 @@ fn parse_knobs(
sig.asyncness = None;
- let mut runtime = None;
- let mut core_threads = None;
- let mut max_threads = None;
+ let macro_name = if is_test {
+ "tokio::test"
+ } else {
+ "tokio::main"
+ };
+ let mut config = Configuration::new(is_test, rt_multi_thread);
for arg in args {
match arg {
@@ -39,65 +168,18 @@ fn parse_knobs(
return Err(syn::Error::new_spanned(namevalue, msg));
}
match ident.unwrap().to_string().to_lowercase().as_str() {
+ "worker_threads" => {
+ config.set_worker_threads(namevalue.lit.clone(), namevalue.span())?;
+ }
+ "flavor" => {
+ config.set_flavor(namevalue.lit.clone(), namevalue.span())?;
+ }
"core_threads" => {
- if rt_threaded {
- match &namevalue.lit {
- syn::Lit::Int(expr) => {
- let num = expr.base10_parse::<NonZeroUsize>().unwrap();
- if num.get() > 1 {
- runtime = Some(Runtime::Threaded);
- } else {
- runtime = Some(Runtime::Basic);
- }
-
- if let Some(v) = max_threads {
- if v < num {
- return Err(syn::Error::new_spanned(
- namevalue,
- "max_threads cannot be less than core_threads",
- ));
- }
- }
-
- core_threads = Some(num);
- }
- _ => {
- return Err(syn::Error::new_spanned(
- namevalue,
- "core_threads argument must be an int",
- ))
- }
- }
- } else {
- return Err(syn::Error::new_spanned(
- namevalue,
- "core_threads can only be set with rt-threaded feature flag enabled",
- ));
- }
+ let msg = "Attribute `core_threads` is renamed to `worker_threads`";
+ return Err(syn::Error::new_spanned(namevalue, msg));
}
- "max_threads" => match &namevalue.lit {
- syn::Lit::Int(expr) => {
- let num = expr.base10_parse::<NonZeroUsize>().unwrap();
-
- if let Some(v) = core_threads {
- if num < v {
- return Err(syn::Error::new_spanned(
- namevalue,
- "max_threads cannot be less than core_threads",
- ));
- }
- }
- max_threads = Some(num);
- }
- _ => {
- return Err(syn::Error::new_spanned(
- namevalue,
- "max_threads argument must be an int",
- ))
- }
- },
name => {
- let msg = format!("Unknown attribute pair {} is specified; expected one of: `core_threads`, `max_threads`", name);
+ let msg = format!("Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`, `max_threads`", name);
return Err(syn::Error::new_spanned(namevalue, msg));
}
}
@@ -108,16 +190,22 @@ fn parse_knobs(
let msg = "Must have specified ident";
return Err(syn::Error::new_spanned(path, msg));
}
- match ident.unwrap().to_string().to_lowercase().as_str() {
- "threaded_scheduler" => {
- runtime = Some(runtime.unwrap_or_else(|| Runtime::Threaded))
- }
- "basic_scheduler" => runtime = Some(runtime.unwrap_or_else(|| Runtime::Basic)),
+ let name = ident.unwrap().to_string().to_lowercase();
+ let msg = match name.as_str() {
+ "threaded_scheduler" | "multi_thread" => {
+ format!("Set the runtime flavor with #[{}(flavor = \"multi_thread\")].", macro_name)
+ },
+ "basic_scheduler" | "current_thread" | "single_threaded" => {
+ format!("Set the runtime flavor with #[{}(flavor = \"current_thread\")].", macro_name)
+ },
+ "flavor" | "worker_threads" => {
+ format!("The `{}` attribute requires an argument.", name)
+ },
name => {
- let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name);
- return Err(syn::Error::new_spanned(path, msg));
- }
- }
+ format!("Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`", name)
+ },
+ };
+ return Err(syn::Error::new_spanned(path, msg));
}
other => {
return Err(syn::Error::new_spanned(
@@ -128,21 +216,24 @@ fn parse_knobs(
}
}
- let mut rt = quote! { tokio::runtime::Builder::new().basic_scheduler() };
- if rt_threaded && (runtime == Some(Runtime::Threaded) || (runtime.is_none() && !is_test)) {
- rt = quote! { #rt.threaded_scheduler() };
- }
- if let Some(v) = core_threads.map(|v| v.get()) {
- rt = quote! { #rt.core_threads(#v) };
- }
- if let Some(v) = max_threads.map(|v| v.get()) {
- rt = quote! { #rt.max_threads(#v) };
+ let config = config.build()?;
+
+ let mut rt = match config.flavor {
+ RuntimeFlavor::CurrentThread => quote! {
+ tokio::runtime::Builder::new_current_thread()
+ },
+ RuntimeFlavor::Threaded => quote! {
+ tokio::runtime::Builder::new_multi_thread()
+ },
+ };
+ if let Some(v) = config.worker_threads {
+ rt = quote! { #rt.worker_threads(#v) };
}
let header = {
if is_test {
quote! {
- #[test]
+ #[::core::prelude::v1::test]
}
} else {
quote! {}
@@ -165,21 +256,21 @@ fn parse_knobs(
}
#[cfg(not(test))] // Work around for rust-lang/rust#62127
-pub(crate) fn main(args: TokenStream, item: TokenStream, rt_threaded: bool) -> TokenStream {
+pub(crate) fn main(args: TokenStream, item: TokenStream, rt_multi_thread: bool) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let args = syn::parse_macro_input!(args as syn::AttributeArgs);
if input.sig.ident == "main" && !input.sig.inputs.is_empty() {
let msg = "the main function cannot accept arguments";
- return syn::Error::new_spanned(&input.sig.inputs, msg)
+ return syn::Error::new_spanned(&input.sig.ident, msg)
.to_compile_error()
.into();
}
- parse_knobs(input, args, false, rt_threaded).unwrap_or_else(|e| e.to_compile_error().into())
+ parse_knobs(input, args, false, rt_multi_thread).unwrap_or_else(|e| e.to_compile_error().into())
}
-pub(crate) fn test(args: TokenStream, item: TokenStream, rt_threaded: bool) -> TokenStream {
+pub(crate) fn test(args: TokenStream, item: TokenStream, rt_multi_thread: bool) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let args = syn::parse_macro_input!(args as syn::AttributeArgs);
@@ -199,161 +290,5 @@ pub(crate) fn test(args: TokenStream, item: TokenStream, rt_threaded: bool) -> T
.into();
}
- parse_knobs(input, args, true, rt_threaded).unwrap_or_else(|e| e.to_compile_error().into())
-}
-
-pub(crate) mod old {
- use proc_macro::TokenStream;
- use quote::quote;
-
- enum Runtime {
- Basic,
- Threaded,
- Auto,
- }
-
- #[cfg(not(test))] // Work around for rust-lang/rust#62127
- pub(crate) fn main(args: TokenStream, item: TokenStream) -> TokenStream {
- let mut input = syn::parse_macro_input!(item as syn::ItemFn);
- let args = syn::parse_macro_input!(args as syn::AttributeArgs);
-
- let sig = &mut input.sig;
- let name = &sig.ident;
- let inputs = &sig.inputs;
- let body = &input.block;
- let attrs = &input.attrs;
- let vis = input.vis;
-
- if sig.asyncness.is_none() {
- let msg = "the async keyword is missing from the function declaration";
- return syn::Error::new_spanned(sig.fn_token, msg)
- .to_compile_error()
- .into();
- } else if name == "main" && !inputs.is_empty() {
- let msg = "the main function cannot accept arguments";
- return syn::Error::new_spanned(&sig.inputs, msg)
- .to_compile_error()
- .into();
- }
-
- sig.asyncness = None;
-
- let mut runtime = Runtime::Auto;
-
- for arg in args {
- if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = arg {
- let ident = path.get_ident();
- if ident.is_none() {
- let msg = "Must have specified ident";
- return syn::Error::new_spanned(path, msg).to_compile_error().into();
- }
- match ident.unwrap().to_string().to_lowercase().as_str() {
- "threaded_scheduler" => runtime = Runtime::Threaded,
- "basic_scheduler" => runtime = Runtime::Basic,
- name => {
- let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name);
- return syn::Error::new_spanned(path, msg).to_compile_error().into();
- }
- }
- }
- }
-
- let result = match runtime {
- Runtime::Threaded | Runtime::Auto => quote! {
- #(#attrs)*
- #vis #sig {
- tokio::runtime::Runtime::new().unwrap().block_on(async { #body })
- }
- },
- Runtime::Basic => quote! {
- #(#attrs)*
- #vis #sig {
- tokio::runtime::Builder::new()
- .basic_scheduler()
- .enable_all()
- .build()
- .unwrap()
- .block_on(async { #body })
- }
- },
- };
-
- result.into()
- }
-
- pub(crate) fn test(args: TokenStream, item: TokenStream) -> TokenStream {
- let input = syn::parse_macro_input!(item as syn::ItemFn);
- let args = syn::parse_macro_input!(args as syn::AttributeArgs);
-
- let ret = &input.sig.output;
- let name = &input.sig.ident;
- let body = &input.block;
- let attrs = &input.attrs;
- let vis = input.vis;
-
- for attr in attrs {
- if attr.path.is_ident("test") {
- let msg = "second test attribute is supplied";
- return syn::Error::new_spanned(&attr, msg)
- .to_compile_error()
- .into();
- }
- }
-
- if input.sig.asyncness.is_none() {
- let msg = "the async keyword is missing from the function declaration";
- return syn::Error::new_spanned(&input.sig.fn_token, msg)
- .to_compile_error()
- .into();
- } else if !input.sig.inputs.is_empty() {
- let msg = "the test function cannot accept arguments";
- return syn::Error::new_spanned(&input.sig.inputs, msg)
- .to_compile_error()
- .into();
- }
-
- let mut runtime = Runtime::Auto;
-
- for arg in args {
- if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = arg {
- let ident = path.get_ident();
- if ident.is_none() {
- let msg = "Must have specified ident";
- return syn::Error::new_spanned(path, msg).to_compile_error().into();
- }
- match ident.unwrap().to_string().to_lowercase().as_str() {
- "threaded_scheduler" => runtime = Runtime::Threaded,
- "basic_scheduler" => runtime = Runtime::Basic,
- name => {
- let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name);
- return syn::Error::new_spanned(path, msg).to_compile_error().into();
- }
- }
- }
- }
-
- let result = match runtime {
- Runtime::Threaded => quote! {
- #[test]
- #(#attrs)*
- #vis fn #name() #ret {
- tokio::runtime::Runtime::new().unwrap().block_on(async { #body })
- }
- },
- Runtime::Basic | Runtime::Auto => quote! {
- #[test]
- #(#attrs)*
- #vis fn #name() #ret {
- tokio::runtime::Builder::new()
- .basic_scheduler()
- .enable_all()
- .build()
- .unwrap()
- .block_on(async { #body })
- }
- },
- };
-
- result.into()
- }
+ parse_knobs(input, args, true, rt_multi_thread).unwrap_or_else(|e| e.to_compile_error().into())
}
diff --git a/src/lib.rs b/src/lib.rs
index 9fdfb5b..47d780a 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,4 @@
-#![doc(html_root_url = "https://docs.rs/tokio-macros/0.2.5")]
+#![doc(html_root_url = "https://docs.rs/tokio-macros/0.3.0")]
#![allow(clippy::needless_doctest_main)]
#![warn(
missing_debug_implementations,
@@ -6,7 +6,7 @@
rust_2018_idioms,
unreachable_pub
)]
-#![deny(intra_doc_link_resolution_failure)]
+#![cfg_attr(docsrs, deny(broken_intra_doc_links))]
#![doc(test(
no_crate_inject,
attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
@@ -24,13 +24,38 @@ mod select;
use proc_macro::TokenStream;
-/// Marks async function to be executed by selected runtime.
+/// Marks async function to be executed by the selected runtime. This macro helps
+/// set up a `Runtime` without requiring the user to use
+/// [Runtime](../tokio/runtime/struct.Runtime.html) or
+/// [Builder](../tokio/runtime/struct.Builder.html) directly.
///
-/// ## Options:
+/// Note: This macro is designed to be simplistic and targets applications that
+/// do not require a complex setup. If the provided functionality is not
+/// sufficient, you may be interested in using
+/// [Builder](../tokio/runtime/struct.Builder.html), which provides a more
+/// powerful interface.
+///
+/// # Multi-threaded runtime
+///
+/// To use the multi-threaded runtime, the macro can be configured using
+///
+/// ```
+/// #[tokio::main(flavor = "multi_thread", worker_threads = 10)]
+/// # async fn main() {}
+/// ```
///
+/// The `worker_threads` option configures the number of worker threads, and
+/// defaults to the number of cpus on the system. This is the default flavor.
///
-/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
-/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
+/// # Current thread runtime
+///
+/// To use the single-threaded runtime known as the `current_thread` runtime,
+/// the macro can be configured using
+///
+/// ```
+/// #[tokio::main(flavor = "current_thread")]
+/// # async fn main() {}
+/// ```
///
/// ## Function arguments:
///
@@ -38,7 +63,7 @@ use proc_macro::TokenStream;
///
/// ## Usage
///
-/// ### Using default
+/// ### Using the multi-thread runtime
///
/// ```rust
/// #[tokio::main]
@@ -47,61 +72,84 @@ use proc_macro::TokenStream;
/// }
/// ```
///
-/// ### Set number of core threads
+/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
-/// #[tokio::main(core_threads = 1)]
-/// async fn main() {
-/// println!("Hello world");
+/// fn main() {
+/// tokio::runtime::Builder::new_multi_thread()
+/// .enable_all()
+/// .build()
+/// .unwrap()
+/// .block_on(async {
+/// println!("Hello world");
+/// })
/// }
/// ```
-#[proc_macro_attribute]
-#[cfg(not(test))] // Work around for rust-lang/rust#62127
-pub fn main_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
- entry::main(args, item, true)
-}
-
-/// Marks async function to be executed by selected runtime.
///
-/// ## Options:
+/// ### Using current thread runtime
///
-/// - `basic_scheduler` - All tasks are executed on the current thread.
-/// - `threaded_scheduler` - Uses the multi-threaded scheduler. Used by default (requires `rt-threaded` feature).
+/// The basic scheduler is single-threaded.
///
-/// ## Function arguments:
+/// ```rust
+/// #[tokio::main(flavor = "current_thread")]
+/// async fn main() {
+/// println!("Hello world");
+/// }
+/// ```
///
-/// Arguments are allowed for any functions aside from `main` which is special
+/// Equivalent code not using `#[tokio::main]`
///
-/// ## Usage
+/// ```rust
+/// fn main() {
+/// tokio::runtime::Builder::new_current_thread()
+/// .enable_all()
+/// .build()
+/// .unwrap()
+/// .block_on(async {
+/// println!("Hello world");
+/// })
+/// }
+/// ```
///
-/// ### Using default
+/// ### Set number of worker threads
///
/// ```rust
-/// #[tokio::main]
+/// #[tokio::main(worker_threads = 2)]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
-/// ### Select runtime
+/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
-/// #[tokio::main(basic_scheduler)]
-/// async fn main() {
-/// println!("Hello world");
+/// fn main() {
+/// tokio::runtime::Builder::new_multi_thread()
+/// .worker_threads(2)
+/// .enable_all()
+/// .build()
+/// .unwrap()
+/// .block_on(async {
+/// println!("Hello world");
+/// })
/// }
/// ```
+///
+/// ### NOTE:
+///
+/// If you rename the tokio crate in your dependencies this macro will not work.
+/// If you must rename the 0.2 version of tokio because you're also using the
+/// 0.1 version of tokio, you _must_ make the tokio 0.2 crate available as
+/// `tokio` in the module where this macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
- entry::old::main(args, item)
+ entry::main(args, item, true)
}
-/// Marks async function to be executed by selected runtime.
-///
-/// ## Options:
-///
-/// - `max_threads=n` - Sets max threads to `n`.
+/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
+/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
+/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Function arguments:
///
@@ -112,61 +160,47 @@ pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
/// ### Using default
///
/// ```rust
-/// #[tokio::main]
+/// #[tokio::main(flavor = "current_thread")]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
-#[proc_macro_attribute]
-#[cfg(not(test))] // Work around for rust-lang/rust#62127
-pub fn main_basic(args: TokenStream, item: TokenStream) -> TokenStream {
- entry::main(args, item, false)
-}
-
-/// Marks async function to be executed by runtime, suitable to test environment
-///
-/// ## Options:
-///
-/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
-/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
-///
-/// ## Usage
///
-/// ### Select runtime
+/// Equivalent code not using `#[tokio::main]`
///
-/// ```no_run
-/// #[tokio::test(core_threads = 1)]
-/// async fn my_test() {
-/// assert!(true);
+/// ```rust
+/// fn main() {
+/// tokio::runtime::Builder::new_current_thread()
+/// .enable_all()
+/// .build()
+/// .unwrap()
+/// .block_on(async {
+/// println!("Hello world");
+/// })
/// }
/// ```
///
-/// ### Using default
+/// ### NOTE:
///
-/// ```no_run
-/// #[tokio::test]
-/// async fn my_test() {
-/// assert!(true);
-/// }
-/// ```
+/// If you rename the tokio crate in your dependencies this macro
+/// will not work. If you must rename the 0.2 version of tokio because
+/// you're also using the 0.1 version of tokio, you _must_ make the
+/// tokio 0.2 crate available as `tokio` in the module where this
+/// macro is expanded.
#[proc_macro_attribute]
-pub fn test_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
- entry::test(args, item, true)
+#[cfg(not(test))] // Work around for rust-lang/rust#62127
+pub fn main_rt(args: TokenStream, item: TokenStream) -> TokenStream {
+ entry::main(args, item, false)
}
/// Marks async function to be executed by runtime, suitable to test environment
///
-/// ## Options:
-///
-/// - `basic_scheduler` - All tasks are executed on the current thread. Used by default.
-/// - `threaded_scheduler` - Use multi-threaded scheduler (requires `rt-threaded` feature).
-///
/// ## Usage
///
-/// ### Select runtime
+/// ### Multi-thread runtime
///
/// ```no_run
-/// #[tokio::test(threaded_scheduler)]
+/// #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
/// async fn my_test() {
/// assert!(true);
/// }
@@ -174,15 +208,25 @@ pub fn test_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
///
/// ### Using default
///
+/// The default test runtime is multi-threaded.
+///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
/// assert!(true);
/// }
/// ```
+///
+/// ### NOTE:
+///
+/// If you rename the tokio crate in your dependencies this macro
+/// will not work. If you must rename the 0.2 version of tokio because
+/// you're also using the 0.1 version of tokio, you _must_ make the
+/// tokio 0.2 crate available as `tokio` in the module where this
+/// macro is expanded.
#[proc_macro_attribute]
pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
- entry::old::test(args, item)
+ entry::test(args, item, true)
}
/// Marks async function to be executed by runtime, suitable to test environment
@@ -199,11 +243,47 @@ pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
/// assert!(true);
/// }
/// ```
+///
+/// ### NOTE:
+///
+/// If you rename the tokio crate in your dependencies this macro
+/// will not work. If you must rename the 0.2 version of tokio because
+/// you're also using the 0.1 version of tokio, you _must_ make the
+/// tokio 0.2 crate available as `tokio` in the module where this
+/// macro is expanded.
#[proc_macro_attribute]
-pub fn test_basic(args: TokenStream, item: TokenStream) -> TokenStream {
+pub fn test_rt(args: TokenStream, item: TokenStream) -> TokenStream {
entry::test(args, item, false)
}
+/// Always fails with the error message below.
+/// ```text
+/// The #[tokio::main] macro requires rt or rt-multi-thread.
+/// ```
+#[proc_macro_attribute]
+pub fn main_fail(_args: TokenStream, _item: TokenStream) -> TokenStream {
+ syn::Error::new(
+ proc_macro2::Span::call_site(),
+ "The #[tokio::main] macro requires rt or rt-multi-thread.",
+ )
+ .to_compile_error()
+ .into()
+}
+
+/// Always fails with the error message below.
+/// ```text
+/// The #[tokio::test] macro requires rt or rt-multi-thread.
+/// ```
+#[proc_macro_attribute]
+pub fn test_fail(_args: TokenStream, _item: TokenStream) -> TokenStream {
+ syn::Error::new(
+ proc_macro2::Span::call_site(),
+ "The #[tokio::test] macro requires rt or rt-multi-thread.",
+ )
+ .to_compile_error()
+ .into()
+}
+
/// Implementation detail of the `select!` macro. This macro is **not** intended
/// to be used as part of the public API and is permitted to change.
#[proc_macro]