divan-macros-0.1.21/.cargo_vcs_info.json 0000644 00000000144 00000000001 0013477 0 ustar {
"git": {
"sha1": "52f9d4983e68b16d1d77f8920df087ef8f8d6ba0"
},
"path_in_vcs": "macros"
} divan-macros-0.1.21/Cargo.lock 0000644 00000002135 00000000001 0011454 0 ustar # This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "divan-macros"
version = "0.1.21"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "syn"
version = "2.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
divan-macros-0.1.21/Cargo.toml 0000644 00000002632 00000000001 0011501 0 ustar # 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 = "2021"
name = "divan-macros"
version = "0.1.21"
authors = ["Nikolai Vazquez"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Macros for Divan, a statistically-comfy benchmarking library."
homepage = "https://github.com/nvzqz/divan"
documentation = "https://docs.rs/divan-macros"
readme = "README.md"
keywords = [
"benchmark",
"criterion",
"instrument",
"measure",
"performance",
]
categories = ["development-tools::profiling"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/nvzqz/divan"
[lib]
name = "divan_macros"
path = "src/lib.rs"
proc-macro = true
[dependencies.proc-macro2]
version = "1"
[dependencies.quote]
version = "1"
default-features = false
[dependencies.syn]
version = "^2.0.18"
features = [
"full",
"clone-impls",
"parsing",
"printing",
"proc-macro",
]
default-features = false
[dev-dependencies]
divan-macros-0.1.21/Cargo.toml.orig 0000644 0000000 0000000 00000001515 10461020230 0015161 0 ustar 0000000 0000000 [package]
name = "divan-macros"
version = "0.1.21"
edition = "2021"
authors = ["Nikolai Vazquez"]
license = "MIT OR Apache-2.0"
description = "Macros for Divan, a statistically-comfy benchmarking library."
repository = "https://github.com/nvzqz/divan"
homepage = "https://github.com/nvzqz/divan"
documentation = "https://docs.rs/divan-macros"
categories = ["development-tools::profiling"]
keywords = ["benchmark", "criterion", "instrument", "measure", "performance"]
readme = "../README.md"
[lib]
proc-macro = true
[dependencies]
proc-macro2 = "1"
quote = { version = "1", default-features = false }
# Versions prior to *.18 fail to parse empty attribute metadata.
syn = { version = "^2.0.18", default-features = false, features = ["full", "clone-impls", "parsing", "printing", "proc-macro"] }
[dev-dependencies]
divan = { workspace = true }
divan-macros-0.1.21/LICENSE-APACHE 0000644 0000000 0000000 00000026136 10461020230 0014224 0 ustar 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
divan-macros-0.1.21/LICENSE-MIT 0000644 0000000 0000000 00000002060 10461020230 0013722 0 ustar 0000000 0000000 MIT License
Copyright (c) 2023 Nikolai Vazquez
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.
divan-macros-0.1.21/README.md 0000644 0000000 0000000 00000007645 10461020230 0013563 0 ustar 0000000 0000000
## Sponsor
If you or your company find Divan valuable, consider [sponsoring on
GitHub](https://github.com/sponsors/nvzqz) or [donating via
PayPal](https://paypal.me/nvzqz). Sponsorships help me progress on what's
possible with benchmarking in Rust.
## Guide
A guide is being worked on. In the meantime, see:
- [Announcement post](https://nikolaivazquez.com/blog/divan/)
- ["Proving Performance" FOSDEM talk](https://youtu.be/P87C4jNakGs)
## Getting Started
Divan `0.1.21` requires Rust `1.80.0` or later.
1. Add the following to your project's [`Cargo.toml`](https://doc.rust-lang.org/cargo/reference/manifest.html):
```toml
[dev-dependencies]
divan = "0.1.21"
[[bench]]
name = "example"
harness = false
```
2. Create a benchmarks file at `benches/example.rs`[^1] with your benchmarking code:
```rust
fn main() {
// Run registered benchmarks.
divan::main();
}
// Register a `fibonacci` function and benchmark it over multiple cases.
#[divan::bench(args = [1, 2, 4, 8, 16, 32])]
fn fibonacci(n: u64) -> u64 {
if n <= 1 {
1
} else {
fibonacci(n - 2) + fibonacci(n - 1)
}
}
```
3. Run your benchmarks with [`cargo bench`](https://doc.rust-lang.org/cargo/commands/cargo-bench.html):
```txt
example fastest │ slowest │ median │ mean │ samples │ iters
╰─ fibonacci │ │ │ │ │
├─ 1 0.626 ns │ 1.735 ns │ 0.657 ns │ 0.672 ns │ 100 │ 819200
├─ 2 2.767 ns │ 3.154 ns │ 2.788 ns │ 2.851 ns │ 100 │ 204800
├─ 4 6.816 ns │ 7.671 ns │ 7.061 ns │ 7.167 ns │ 100 │ 102400
├─ 8 57.31 ns │ 62.51 ns │ 57.96 ns │ 58.55 ns │ 100 │ 12800
├─ 16 2.874 µs │ 3.812 µs │ 2.916 µs │ 3.006 µs │ 100 │ 200
╰─ 32 6.267 ms │ 6.954 ms │ 6.283 ms │ 6.344 ms │ 100 │ 100
```
See [`#[divan::bench]`][bench_attr] for info on benchmark function registration.
## Examples
Practical example benchmarks can be found in the [`examples/benches`](https://github.com/nvzqz/divan/tree/main/examples/benches)
directory. These can be benchmarked locally by running:
```sh
git clone https://github.com/nvzqz/divan.git
cd divan
cargo bench -q -p examples --all-features
```
More thorough usage examples can be found in the [`#[divan::bench]` documentation][bench_attr_examples].
## License
Like the Rust project, this library may be used under either the
[MIT License](https://github.com/nvzqz/divan/blob/main/LICENSE-MIT) or
[Apache License (Version 2.0)](https://github.com/nvzqz/divan/blob/main/LICENSE-APACHE).
[^1]: Within your crate directory, i.e. [`$CARGO_MANIFEST_DIR`](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates)
[bench_attr]: https://docs.rs/divan/latest/divan/attr.bench.html
[bench_attr_examples]: https://docs.rs/divan/latest/divan/attr.bench.html#examples
divan-macros-0.1.21/src/attr_options.rs 0000644 0000000 0000000 00000033117 10461020230 0016157 0 ustar 0000000 0000000 use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{
parse::{Parse, Parser},
spanned::Spanned,
Expr, ExprArray, Ident, Token, Type,
};
use crate::{tokens, Macro};
/// Values from parsed options shared between `#[divan::bench]` and
/// `#[divan::bench_group]`.
///
/// The `crate` option is not included because it is only needed to get proper
/// access to `__private`.
pub(crate) struct AttrOptions {
/// `divan::__private`.
pub private_mod: proc_macro2::TokenStream,
/// Custom name for the benchmark or group.
pub name_expr: Option,
/// `IntoIterator` from which to provide runtime arguments.
pub args_expr: Option,
/// Options for generic functions.
pub generic: GenericOptions,
/// The `BenchOptions.counters` field and its value, followed by a comma.
pub counters: proc_macro2::TokenStream,
/// Options used directly as `BenchOptions` fields.
///
/// Option reuse is handled by the compiler ensuring `BenchOptions` fields
/// are not repeated.
pub bench_options: Vec<(Ident, Expr)>,
}
impl AttrOptions {
pub fn parse(tokens: TokenStream, target_macro: Macro) -> Result {
let macro_name = target_macro.name();
let mut divan_crate = None::;
let mut name_expr = None::;
let mut args_expr = None::;
let mut bench_options = Vec::new();
let mut counters = Vec::<(proc_macro2::TokenStream, Option<&str>)>::new();
let mut counters_ident = None::;
let mut seen_bytes_count = false;
let mut seen_chars_count = false;
let mut seen_cycles_count = false;
let mut seen_items_count = false;
let mut generic = GenericOptions::default();
let attr_parser = syn::meta::parser(|meta| {
macro_rules! error {
($($t:tt)+) => {
return Err(meta.error(format_args!($($t)+)))
};
}
let Some(ident) = meta.path.get_ident() else {
error!("unsupported '{macro_name}' option");
};
let ident_name = ident.to_string();
let ident_name = ident_name.strip_prefix("r#").unwrap_or(&ident_name);
let repeat_error = || error!("repeated '{macro_name}' option '{ident_name}'");
let unsupported_error = || error!("unsupported '{macro_name}' option '{ident_name}'");
macro_rules! parse {
($storage:expr) => {
if $storage.is_none() {
$storage = Some(meta.value()?.parse()?);
} else {
return repeat_error();
}
};
}
match ident_name {
"crate" => parse!(divan_crate),
"name" => parse!(name_expr),
"types" => {
match target_macro {
Macro::Bench { fn_sig } => {
if fn_sig.generics.type_params().next().is_none() {
error!("generic type required for '{macro_name}' option '{ident_name}'");
}
}
_ => return unsupported_error(),
}
parse!(generic.types);
}
"consts" => {
match target_macro {
Macro::Bench { fn_sig } => {
if fn_sig.generics.const_params().next().is_none() {
error!("generic const required for '{macro_name}' option '{ident_name}'");
}
}
_ => return unsupported_error(),
}
parse!(generic.consts);
}
"args" => {
match target_macro {
Macro::Bench { fn_sig } => {
if !matches!(fn_sig.inputs.len(), 1 | 2) {
return Err(meta.error(format_args!("function argument required for '{macro_name}' option '{ident_name}'")));
}
}
_ => return unsupported_error(),
}
parse!(args_expr);
}
"counter" => {
if counters_ident.is_some() {
return repeat_error();
}
let value: Expr = meta.value()?.parse()?;
counters.push((value.into_token_stream(), None));
counters_ident = Some(Ident::new("counters", ident.span()));
}
"counters" => {
if counters_ident.is_some() {
return repeat_error();
}
let values: ExprArray = meta.value()?.parse()?;
counters.extend(
values.elems.into_iter().map(|elem| (elem.into_token_stream(), None)),
);
counters_ident = Some(ident.clone());
}
"bytes_count" if seen_bytes_count => return repeat_error(),
"chars_count" if seen_chars_count => return repeat_error(),
"cycles_count" if seen_cycles_count => return repeat_error(),
"items_count" if seen_items_count => return repeat_error(),
"bytes_count" | "chars_count" | "cycles_count" | "items_count" => {
let name = match ident_name {
"bytes_count" => {
seen_bytes_count = true;
"BytesCount"
}
"chars_count" => {
seen_chars_count = true;
"CharsCount"
}
"cycles_count" => {
seen_cycles_count = true;
"CyclesCount"
}
"items_count" => {
seen_items_count = true;
"ItemsCount"
}
_ => unreachable!(),
};
let value: Expr = meta.value()?.parse()?;
counters.push((value.into_token_stream(), Some(name)));
counters_ident = Some(Ident::new("counters", proc_macro2::Span::call_site()));
}
_ => {
let value: Expr = match meta.value() {
Ok(value) => value.parse()?,
// If the option is missing `=`, use a `true` literal.
Err(_) => Expr::Lit(syn::ExprLit {
lit: syn::LitBool::new(true, meta.path.span()).into(),
attrs: Vec::new(),
}),
};
bench_options.push((ident.clone(), value));
}
}
Ok(())
});
match attr_parser.parse(tokens) {
Ok(()) => {}
Err(error) => return Err(error.into_compile_error().into()),
}
let divan_crate = divan_crate.unwrap_or_else(|| syn::parse_quote!(::divan));
let private_mod = quote! { #divan_crate::__private };
let counters = counters.iter().map(|(expr, type_name)| match type_name {
Some(type_name) => {
let type_name = Ident::new(type_name, proc_macro2::Span::call_site());
quote! {
// We do a scoped import for the expression to override any
// local `From` trait.
{
use ::std::convert::From as _;
#divan_crate::counter::#type_name::from(#expr)
}
}
}
None => expr.to_token_stream(),
});
let counters = counters_ident
.map(|ident| {
quote! {
#ident: #private_mod::new_counter_set() #(.with(#counters))* ,
}
})
.unwrap_or_default();
Ok(Self { private_mod, name_expr, args_expr, generic, counters, bench_options })
}
/// Produces a function expression for creating `LazyLock`.
///
/// If the `#[ignore]` attribute is specified, this be provided its
/// identifier to set `BenchOptions` using its span. Doing this instead of
/// creating the `ignore` identifier ourselves improves compiler error
/// diagnostics.
pub fn bench_options_fn(
&self,
ignore_attr_ident: Option<&syn::Path>,
) -> proc_macro2::TokenStream {
fn is_lit_array(expr: &Expr) -> bool {
let Expr::Array(expr) = expr else {
return false;
};
expr.elems.iter().all(|elem| matches!(elem, Expr::Lit { .. }))
}
let private_mod = &self.private_mod;
let option_some = tokens::option_some();
// Directly set fields on `BenchOptions`. This simplifies things by:
// - Having a single source of truth
// - Making unknown options a compile error
//
// We use `..` (struct update syntax) to ensure that no option is set
// twice, even if raw identifiers are used. This also has the accidental
// benefit of Rust Analyzer recognizing fields and emitting suggestions
// with docs and type info.
if self.bench_options.is_empty() && self.counters.is_empty() && ignore_attr_ident.is_none()
{
tokens::option_none()
} else {
let options_iter = self.bench_options.iter().map(|(option, value)| {
let option_name = option.to_string();
let option_name = option_name.strip_prefix("r#").unwrap_or(&option_name);
let wrapped_value: proc_macro2::TokenStream;
let value: &dyn ToTokens = match option_name {
"threads" => {
wrapped_value = if is_lit_array(value) {
// If array of literals, just use `&[...]`.
quote! { ::std::borrow::Cow::Borrowed(value) }
} else {
quote! { #private_mod::IntoThreads::into_threads(#value) }
};
&wrapped_value
}
// If the option is a `Duration`, use `IntoDuration` to be
// polymorphic over `Duration` or `u64`/`f64` seconds.
"min_time" | "max_time" => {
wrapped_value =
quote! { #private_mod::IntoDuration::into_duration(#value) };
&wrapped_value
}
_ => value,
};
quote! { #option: #option_some(#value), }
});
let ignore = match ignore_attr_ident {
Some(ignore_attr_ident) => quote! { #ignore_attr_ident: #option_some(true), },
None => Default::default(),
};
let counters = &self.counters;
quote! {
#option_some(::std::sync::LazyLock::new(|| {
#[allow(clippy::needless_update)]
#private_mod::BenchOptions {
#(#options_iter)*
// Ignore comes after options so that options take
// priority in compiler error diagnostics.
#ignore
#counters
..::std::default::Default::default()
}
}))
}
}
}
}
/// Options for generic functions.
#[derive(Default)]
pub struct GenericOptions {
/// Generic types over which to instantiate benchmark functions.
pub types: Option,
/// `const` array/slice over which to instantiate benchmark functions.
pub consts: Option,
}
impl GenericOptions {
/// Returns `true` if set exclusively to either:
/// - `types = []`
/// - `consts = []`
pub fn is_empty(&self) -> bool {
match (&self.types, &self.consts) {
(Some(types), None) => types.is_empty(),
(None, Some(Expr::Array(consts))) => consts.elems.is_empty(),
_ => false,
}
}
/// Returns an iterator of multiple `Some` for types, or a single `None` if
/// there are no types.
pub fn types_iter(&self) -> Box> + '_> {
match &self.types {
None => Box::new(std::iter::once(None)),
Some(GenericTypes::List(types)) => {
Box::new(types.iter().map(|t| Some(t as &dyn ToTokens)))
}
}
}
}
/// Generic types over which to instantiate benchmark functions.
pub enum GenericTypes {
/// List of types, e.g. `[i32, String, ()]`.
List(Vec),
}
impl Parse for GenericTypes {
fn parse(input: syn::parse::ParseStream) -> syn::Result {
let content;
syn::bracketed!(content in input);
Ok(Self::List(
content
.parse_terminated(Type::parse, Token![,])?
.into_iter()
.map(|ty| ty.into_token_stream())
.collect(),
))
}
}
impl GenericTypes {
pub fn is_empty(&self) -> bool {
match self {
Self::List(list) => list.is_empty(),
}
}
}
divan-macros-0.1.21/src/lib.rs 0000644 0000000 0000000 00000051051 10461020230 0014175 0 ustar 0000000 0000000 //! Macros for [Divan](https://github.com/nvzqz/divan), a statistically-comfy
//! benchmarking library brought to you by [Nikolai Vazquez](https://hachyderm.io/@nikolai).
//!
//! See [`divan`](https://docs.rs/divan) crate for documentation.
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
mod attr_options;
mod tokens;
use attr_options::*;
use syn::{Expr, FnArg};
#[derive(Clone, Copy)]
enum Macro<'a> {
Bench { fn_sig: &'a syn::Signature },
BenchGroup,
}
impl Macro<'_> {
fn name(&self) -> &'static str {
match self {
Self::Bench { .. } => "bench",
Self::BenchGroup => "bench_group",
}
}
}
/// Lists of comma-separated `#[cfg]` parameters.
mod systems {
use super::*;
pub fn elf() -> proc_macro2::TokenStream {
quote! {
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "haiku",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "wasi",
target_os = "emscripten"
}
}
pub fn mach_o() -> proc_macro2::TokenStream {
quote! {
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos"
}
}
}
/// Attributes applied to a `static` containing a pointer to a function to run
/// before `main`.
fn pre_main_attrs() -> proc_macro2::TokenStream {
let elf = systems::elf();
let mach_o = systems::mach_o();
quote! {
#[used]
#[cfg_attr(windows, link_section = ".CRT$XCU")]
#[cfg_attr(any(#elf), link_section = ".init_array")]
#[cfg_attr(any(#mach_o), link_section = "__DATA,__mod_init_func,mod_init_funcs")]
}
}
fn unsupported_error(attr_name: &str) -> proc_macro2::TokenStream {
let elf = systems::elf();
let mach_o = systems::mach_o();
let error = format!("Unsupported target OS for `#[divan::{attr_name}]`");
quote! {
#[cfg(not(any(windows, #elf, #mach_o)))]
::std::compile_error!(#error);
}
}
#[proc_macro_attribute]
pub fn bench(options: TokenStream, item: TokenStream) -> TokenStream {
let option_none = tokens::option_none();
let option_some = tokens::option_some();
let fn_item = item.clone();
let fn_item = syn::parse_macro_input!(fn_item as syn::ItemFn);
let fn_sig = &fn_item.sig;
let attr = Macro::Bench { fn_sig };
let attr_name = attr.name();
let options = match AttrOptions::parse(options, attr) {
Ok(options) => options,
Err(compile_error) => return compile_error,
};
// Items needed by generated code.
let AttrOptions { private_mod, .. } = &options;
let fn_ident = &fn_sig.ident;
let fn_name = fn_ident.to_string();
let fn_name_pretty = fn_name.strip_prefix("r#").unwrap_or(&fn_name);
// Find any `#[ignore]` attribute so that we can use its span to help
// compiler diagnostics.
let ignore_attr_ident =
fn_item.attrs.iter().map(|attr| attr.meta.path()).find(|path| path.is_ident("ignore"));
// If the function is `extern "ABI"`, it is wrapped in a Rust-ABI function.
let is_extern_abi = fn_sig.abi.is_some();
let fn_args = &fn_sig.inputs;
let type_param: Option<(usize, &syn::TypeParam)> = fn_sig
.generics
.params
.iter()
.enumerate()
.filter_map(|(i, param)| match param {
syn::GenericParam::Type(param) => Some((i, param)),
_ => None,
})
.next();
let const_param: Option<(usize, &syn::ConstParam)> = fn_sig
.generics
.params
.iter()
.enumerate()
.filter_map(|(i, param)| match param {
syn::GenericParam::Const(param) => Some((i, param)),
_ => None,
})
.next();
let is_type_before_const = match (type_param, const_param) {
(Some((t, _)), Some((c, _))) => t < c,
_ => false,
};
// Prefixed with "__" to prevent IDEs from recommending using this symbol.
//
// The static is local to intentionally cause a compile error if this
// attribute is used multiple times on the same function.
let static_ident = syn::Ident::new(
&format!("__DIVAN_BENCH_{}", fn_name_pretty.to_uppercase()),
fn_ident.span(),
);
let meta = entry_meta_expr(&fn_name, &options, ignore_attr_ident);
let bench_entry_runner = quote! { #private_mod::BenchEntryRunner };
// Creates a `__DIVAN_ARGS` global variable to be used in the entry.
let bench_args_global = if options.args_expr.is_some() {
quote! {
static __DIVAN_ARGS: #private_mod::BenchArgs = #private_mod::BenchArgs::new();
}
} else {
Default::default()
};
// The last argument type is used as the only `args` item type because we
// currently only support one runtime argument.
let last_arg_type = if options.args_expr.is_some() {
fn_args.last().map(|arg| match arg {
FnArg::Receiver(arg) => &*arg.ty,
FnArg::Typed(arg) => &*arg.ty,
})
} else {
None
};
let last_arg_type_tokens = last_arg_type
.map(|ty| match ty {
// Remove lifetime from references to not use the lifetime outside
// of its declaration. This allows benchmarks to take arguments with
// lifetimes.
syn::Type::Reference(ty) if ty.lifetime.is_some() => {
let mut ty = ty.clone();
ty.lifetime = None;
ty.to_token_stream()
}
_ => ty.to_token_stream(),
})
.unwrap_or_default();
// Some argument literals need an explicit type.
let arg_return_tokens = options
.args_expr
.as_ref()
.map(|args| match args {
// Empty array.
Expr::Array(args) if args.elems.is_empty() => quote! {
-> [#last_arg_type_tokens; 0]
},
_ => Default::default(),
})
.unwrap_or_default();
// Creates a function expr for the benchmarking function, optionally
// monomorphized with generic parameters.
let make_bench_fn = |generics: &[&dyn ToTokens]| {
let mut fn_expr = if generics.is_empty() {
// Use identifier as-is.
fn_ident.to_token_stream()
} else {
// Apply generic arguments.
quote! { #fn_ident::< #(#generics),* > }
};
// Handle function arguments.
match (fn_args.len(), &options.args_expr) {
// Simple benchmark with no arguments provided.
(0, None) => {
// Wrap in Rust ABI.
if is_extern_abi {
fn_expr = quote! { || #fn_expr() };
}
quote! {
#bench_entry_runner::Plain(|divan /* Bencher */| divan.bench(#fn_expr))
}
}
// `args` option used without function arguments; handled earlier in
// `AttrOptions::parse`.
(0, Some(_)) => unreachable!(),
// `Bencher` function argument.
(1, None) => {
// Wrap in Rust ABI.
if is_extern_abi {
fn_expr = quote! { |divan /* Bencher */| #fn_expr(divan) };
}
quote! { #bench_entry_runner::Plain(#fn_expr) }
}
// Function argument comes from `args` option.
(1, Some(args)) => quote! {
#bench_entry_runner::Args(|| __DIVAN_ARGS.runner(
|| #arg_return_tokens { #args },
|arg| #private_mod::ToStringHelper(arg).to_string(),
|divan, __divan_arg| divan.bench(|| #fn_expr(
#private_mod::Arg::<#last_arg_type_tokens>::get(__divan_arg)
)),
))
},
// `Bencher` and `args` option function arguments.
(2, Some(args)) => quote! {
#bench_entry_runner::Args(|| __DIVAN_ARGS.runner(
|| #arg_return_tokens { #args },
|arg| #private_mod::ToStringHelper(arg).to_string(),
|divan, __divan_arg| #fn_expr(
divan,
#private_mod::Arg::<#last_arg_type_tokens>::get(__divan_arg),
),
))
},
// Ensure `args` is set if arguments are provided after `Bencher`.
(_, None) => quote! {
::std::compile_error!(::std::concat!(
"expected 'args' option containing '",
::std::stringify!(#last_arg_type_tokens),
"'",
))
},
// `args` option used with unsupported number of arguments; handled
// earlier in `AttrOptions::parse`.
(_, Some(_)) => unreachable!(),
}
};
let pre_main_attrs = pre_main_attrs();
let unsupported_error = unsupported_error(attr_name);
// Creates a `GroupEntry` static for generic benchmarks.
let make_generic_group = |generic_benches: proc_macro2::TokenStream| {
let entry = quote! {
#private_mod::GroupEntry {
meta: #meta,
generic_benches: #option_some({ #generic_benches }),
}
};
quote! {
#unsupported_error
// Push this static into `GROUP_ENTRIES` before `main` is called.
static #static_ident: #private_mod::GroupEntry = {
{
// Add `push` to the initializer section.
#pre_main_attrs
static PUSH: extern "C" fn() = push;
extern "C" fn push() {
static NODE: #private_mod::EntryList<#private_mod::GroupEntry>
= #private_mod::EntryList::new(static_ident);
#private_mod::GROUP_ENTRIES.push(&NODE);
}
}
// All generic entries share the same `BenchArgs` instance for
// efficiency and to ensure all entries use the same values, or
// at least the same names in the case of interior mutability.
#bench_args_global
#entry
};
}
};
// Creates a `GenericBenchEntry` expr for a generic benchmark instance.
let make_generic_bench_entry =
|ty: Option<&dyn ToTokens>, const_value: Option<&dyn ToTokens>| {
let generic_const_value = const_value.map(|const_value| quote!({ #const_value }));
let generics: Vec<&dyn ToTokens> = {
let mut generics = Vec::new();
generics.extend(generic_const_value.as_ref().map(|t| t as &dyn ToTokens));
generics.extend(ty);
if is_type_before_const {
generics.reverse();
}
generics
};
let bench_fn = make_bench_fn(&generics);
let type_value = match ty {
Some(ty) => quote! {
#option_some(#private_mod::EntryType::new::<#ty>())
},
None => option_none.clone(),
};
let const_value = match const_value {
Some(const_value) => quote! {
#option_some(#private_mod::EntryConst::new(const_value))
},
None => option_none.clone(),
};
quote! {
#private_mod::GenericBenchEntry {
group: static_ident,
bench: #bench_fn,
ty: #type_value,
const_value: #const_value,
}
}
};
let generated_items: proc_macro2::TokenStream = match &options.generic.consts {
// Only specified `types = []` or `consts = []`; generate nothing.
_ if options.generic.is_empty() => Default::default(),
None => match &options.generic.types {
// No generics; generate a simple benchmark entry.
None => {
let bench_fn = make_bench_fn(&[]);
let entry = quote! {
#private_mod::BenchEntry {
meta: #meta,
bench: #bench_fn,
}
};
quote! {
// Push this static into `BENCH_ENTRIES` before `main` is
// called.
static #static_ident: #private_mod::BenchEntry = {
{
// Add `push` to the initializer section.
#pre_main_attrs
static PUSH: extern "C" fn() = push;
extern "C" fn push() {
static NODE: #private_mod::EntryList<#private_mod::BenchEntry>
= #private_mod::EntryList::new(static_ident);
#private_mod::BENCH_ENTRIES.push(&NODE);
}
}
#bench_args_global
#entry
};
}
}
// Generate a benchmark group entry with generic benchmark entries.
Some(GenericTypes::List(generic_types)) => {
let generic_benches =
generic_types.iter().map(|ty| make_generic_bench_entry(Some(&ty), None));
make_generic_group(quote! {
&[&[#(#generic_benches),*]]
})
}
},
// Generate a benchmark group entry with generic benchmark entries.
Some(Expr::Array(generic_consts)) => {
let consts_count = generic_consts.elems.len();
let const_type = &const_param.unwrap().1.ty;
let generic_benches = options.generic.types_iter().map(|ty| {
let generic_benches = (0..consts_count).map(move |i| {
let const_value = quote! { __DIVAN_CONSTS[#i] };
make_generic_bench_entry(ty, Some(&const_value))
});
// `static` is necessary because `EntryConst` uses interior
// mutability to cache the `ToString` result.
quote! {
static __DIVAN_GENERIC_BENCHES: [#private_mod::GenericBenchEntry; #consts_count] = [#(#generic_benches),*];
&__DIVAN_GENERIC_BENCHES
}
});
make_generic_group(quote! {
// We refer to our own slice because it:
// - Type-checks values, even if `generic_benches` is empty
// because the user set `types = []`
// - Prevents re-computing constants, which can slightly improve
// compile time given that Miri is slow
const __DIVAN_CONSTS: &[#const_type] = generic_consts;
&[#({ #generic_benches }),*]
})
}
// Generate a benchmark group entry with generic benchmark entries over
// an expression of constants.
//
// This is limited to a maximum of 20 because we need some constant to
// instantiate each function instance.
Some(generic_consts) => {
// The maximum number of elements for non-array expressions.
const MAX_EXTERN_COUNT: usize = 20;
let const_type = &const_param.unwrap().1.ty;
let generic_benches = options.generic.types_iter().map(|ty| {
let generic_benches = (0..MAX_EXTERN_COUNT).map(move |i| {
let const_value = quote! {
// Fallback to the first constant if out of bounds.
__DIVAN_CONSTS[if #i < __DIVAN_CONST_COUNT { #i } else { 0 }]
};
make_generic_bench_entry(ty, Some(&const_value))
});
// `static` is necessary because `EntryConst` uses interior
// mutability to cache the `ToString` result.
quote! {
static __DIVAN_GENERIC_BENCHES: [#private_mod::GenericBenchEntry; __DIVAN_CONST_COUNT]
= match #private_mod::shrink_array([#(#generic_benches),*]) {
Some(array) => array,
_ => panic!("external 'consts' cannot contain more than 20 values"),
};
&__DIVAN_GENERIC_BENCHES
}
});
make_generic_group(quote! {
const __DIVAN_CONST_COUNT: usize = __DIVAN_CONSTS.len();
const __DIVAN_CONSTS: &[#const_type] = generic_consts;
&[#({ #generic_benches }),*]
})
}
};
// Append our generated code to the existing token stream.
let mut result = item;
result.extend(TokenStream::from(generated_items));
result
}
#[proc_macro_attribute]
pub fn bench_group(options: TokenStream, item: TokenStream) -> TokenStream {
let attr = Macro::BenchGroup;
let attr_name = attr.name();
let options = match AttrOptions::parse(options, attr) {
Ok(options) => options,
Err(compile_error) => return compile_error,
};
// Items needed by generated code.
let AttrOptions { private_mod, .. } = &options;
let option_none = tokens::option_none();
// TODO: Make module parsing cheaper by parsing only the necessary parts.
let mod_item = item.clone();
let mod_item = syn::parse_macro_input!(mod_item as syn::ItemMod);
let mod_ident = &mod_item.ident;
let mod_name = mod_ident.to_string();
let mod_name_pretty = mod_name.strip_prefix("r#").unwrap_or(&mod_name);
// Find any `#[ignore]` attribute so that we can use its span to help
// compiler diagnostics.
//
// TODO: Fix `unused_attributes` warning when using `#[ignore]` on a module.
let ignore_attr_ident =
mod_item.attrs.iter().map(|attr| attr.meta.path()).find(|path| path.is_ident("ignore"));
// Prefixed with "__" to prevent IDEs from recommending using this symbol.
//
// By having the static be local, we cause a compile error if this attribute
// is used multiple times on the same function.
let static_ident = syn::Ident::new(
&format!("__DIVAN_GROUP_{}", mod_name_pretty.to_uppercase()),
mod_ident.span(),
);
let meta = entry_meta_expr(&mod_name, &options, ignore_attr_ident);
let pre_main_attrs = pre_main_attrs();
let unsupported_error = unsupported_error(attr_name);
let generated_items = quote! {
#unsupported_error
// Push this static into `GROUP_ENTRIES` before `main` is called.
static #static_ident: #private_mod::EntryList<#private_mod::GroupEntry> = {
{
// Add `push` to the initializer section.
#pre_main_attrs
static PUSH: extern "C" fn() = push;
extern "C" fn push() {
#private_mod::GROUP_ENTRIES.push(static_ident);
}
}
#private_mod::EntryList::new({
static #static_ident: #private_mod::GroupEntry = #private_mod::GroupEntry {
meta: #meta,
generic_benches: #option_none,
};
static_ident
})
};
};
// Append our generated code to the existing token stream.
let mut result = item;
result.extend(TokenStream::from(generated_items));
result
}
/// Constructs an `EntryMeta` expression.
fn entry_meta_expr(
raw_name: &str,
options: &AttrOptions,
ignore_attr_ident: Option<&syn::Path>,
) -> proc_macro2::TokenStream {
let AttrOptions { private_mod, .. } = &options;
let raw_name_pretty = raw_name.strip_prefix("r#").unwrap_or(raw_name);
let display_name: &dyn ToTokens = match &options.name_expr {
Some(name) => name,
None => &raw_name_pretty,
};
let bench_options = options.bench_options_fn(ignore_attr_ident);
quote! {
#private_mod::EntryMeta {
raw_name: #raw_name,
display_name: #display_name,
bench_options: #bench_options,
module_path: ::std::module_path!(),
// `Span` location info is nightly-only, so use macros.
location: #private_mod::EntryLocation {
file: ::std::file!(),
line: ::std::line!(),
col: ::std::column!(),
},
}
}
}
divan-macros-0.1.21/src/tokens.rs 0000644 0000000 0000000 00000000606 10461020230 0014732 0 ustar 0000000 0000000 //! Token generation utilities.
//!
//! These use items from the standard library as `::std`. This works unless
//! users do `extern crate x as std`, which is extremely unlikely.
use proc_macro2::TokenStream;
use quote::quote;
pub fn option_some() -> TokenStream {
quote!(::std::option::Option::Some)
}
pub fn option_none() -> TokenStream {
quote!(::std::option::Option::None)
}