multiversion-macros-0.8.0/.cargo_vcs_info.json0000644000000001610000000000100150610ustar { "git": { "sha1": "c1a7c68a2c7e3c70b57b05f251c0ade189fe5057" }, "path_in_vcs": "multiversion-macros" }multiversion-macros-0.8.0/Cargo.toml0000644000000025210000000000100130610ustar # 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 = "multiversion-macros" version = "0.8.0" authors = ["Caleb Zulawski "] build = false include = [ "/Cargo.toml", "/LICENSE-APACHE", "/LICENSE-MIT", "/README.md", "/src/**", "/tests/**", ] autobins = false autoexamples = false autotests = false autobenches = false description = "Implementation crate for multiversion" readme = "README.md" categories = [] license = "MIT OR Apache-2.0" repository = "https://github.com/calebzulawski/multiversion" [lib] name = "multiversion_macros" path = "src/lib.rs" proc-macro = true [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.syn] version = "2" features = [ "full", "extra-traits", "visit", "visit-mut", "printing", ] [dependencies.target-features] version = "0.1" [features] default = ["std"] std = [] multiversion-macros-0.8.0/Cargo.toml.orig000064400000000000000000000012331046102023000165410ustar 00000000000000[package] name = "multiversion-macros" version = "0.8.0" authors = ["Caleb Zulawski "] license = "MIT OR Apache-2.0" description = "Implementation crate for multiversion" repository = "https://github.com/calebzulawski/multiversion" categories = [] readme = "README.md" include = [ "/Cargo.toml", "/LICENSE-APACHE", "/LICENSE-MIT", "/README.md", "/src/**", "/tests/**", ] edition = "2021" [lib] proc-macro = true [features] default = ["std"] std = [] [dependencies] syn = { version = "2", features = ["full", "extra-traits", "visit", "visit-mut", "printing"] } quote = "1" proc-macro2 = "1" target-features = "0.1" multiversion-macros-0.8.0/LICENSE-APACHE000064400000000000000000000261361046102023000156070ustar 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 [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. multiversion-macros-0.8.0/LICENSE-MIT000064400000000000000000000020361046102023000153100ustar 00000000000000Copyright 2019 Caleb Zulawski 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. multiversion-macros-0.8.0/README.md000064400000000000000000000001111046102023000151230ustar 00000000000000Implementation crate for [`multiversion`](https://docs.rs/multiversion). multiversion-macros-0.8.0/src/cfg.rs000064400000000000000000000031161046102023000155500ustar 00000000000000use quote::ToTokens; use syn::{parse_quote, punctuated::Punctuated, token::Comma, Expr, Lit, Meta, Result}; fn transform_recursive(features: &[&str], input: Meta) -> Result { match input { Meta::NameValue(nv) => { if nv.path == parse_quote!(target_feature) { if let Expr::Lit(lit) = &nv.value { if let Lit::Str(lit) = &lit.lit { if features.contains(&lit.value().as_str()) { return Ok(parse_quote! { all() }); } } } } Ok(Meta::NameValue(nv)) } Meta::List(mut list) => { let mut metas = list.parse_args_with(Punctuated::::parse_terminated)?; for meta in metas.iter_mut() { *meta = transform_recursive(features, meta.clone())?; } list.tokens = metas.into_token_stream(); Ok(Meta::List(list)) } input => Ok(input), } } pub(crate) fn transform(mut input: Punctuated) -> Result { assert_eq!(input.len(), 2); let features = if let Expr::Lit(features) = &input[0].require_name_value()?.value { if let Lit::Str(features) = &features.lit { Some(features.value()) } else { None } } else { None }; let features = features.expect("couldn't parse first argument"); let features = features.split(',').collect::>(); transform_recursive(&features, input.pop().unwrap().into_value()) } multiversion-macros-0.8.0/src/dispatcher.rs000064400000000000000000000415641046102023000171500ustar 00000000000000use crate::{target::Target, util}; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use std::collections::HashMap; use syn::{ parse_quote, Attribute, Block, Error, Expr, Ident, ItemFn, Result, Signature, Visibility, }; pub(crate) fn feature_fn_name(ident: &Ident, target: Option<&Target>) -> Ident { if let Some(target) = target { if target.has_features_specified() { return Ident::new( &format!("{}_{}_version", ident, target.features_string()), ident.span(), ); } } // If this is a default fn, it doesn't have a dedicated static dispatcher Ident::new(&format!("{ident}_default_version"), ident.span()) } fn unsafe_fn_safe_block(f: ItemFn) -> ItemFn { let safe_fn = ItemFn { vis: Visibility::Inherited, sig: Signature { unsafety: None, ident: Ident::new("__safe_inner", f.sig.ident.span()), ..f.sig.clone() }, ..f.clone() }; let (unsafe_sig, args) = crate::util::normalize_signature(&f.sig); let maybe_await = f.sig.asyncness.map(|_| crate::util::await_tokens()); let safe_ident = &safe_fn.sig.ident; let fn_params = crate::util::fn_params(&unsafe_sig); ItemFn { block: parse_quote! { { #[inline(always)] #safe_fn #safe_ident::<#(#fn_params),*>(#(#args),*)#maybe_await } }, sig: unsafe_sig, ..f } } pub(crate) enum DispatchMethod { Default, Static, Direct, Indirect, } pub(crate) struct Dispatcher { pub dispatcher: DispatchMethod, pub inner_attrs: Vec, pub targets: Vec, pub func: ItemFn, } impl Dispatcher { // Create functions for each target fn feature_fns(&self) -> Result> { let make_block = |target: Option<&Target>| { let block = &self.func.block; let features = target.map(|t| t.features()).unwrap_or(&[]); let features_init = quote! { (multiversion::target_features::CURRENT_TARGET)#(.with_feature_str(#features))* }; let feature_attrs = if let Some(target) = target { target.target_feature() } else { Vec::new() }; let features = if let Some(target) = target { let s = target .features() .iter() .map(String::as_str) .collect::>(); s.join(",") } else { String::new() }; parse_quote! { { #[doc(hidden)] // https://github.com/rust-lang/rust/issues/111415 #[allow(unused)] pub mod __multiversion { pub const FEATURES: multiversion::target::Target = #features_init; macro_rules! inherit_target { { $f:item } => { #(#feature_attrs)* $f } } macro_rules! target_cfg { { [$cfg:meta] $($attached:tt)* } => { #[multiversion::target::target_cfg_impl(target_features = #features, $cfg)] $($attached)* }; } macro_rules! target_cfg_attr { { [$cfg:meta, $attr:meta] $($attached:tt)* } => { #[multiversion::target::target_cfg_attr_impl(target_features = #features, $cfg, $attr)] $($attached)* }; } macro_rules! target_cfg_f { { $cfg:meta } => { multiversion::target::target_cfg_f_impl!(target_features = #features, $cfg) }; } macro_rules! match_target { { $($arms:tt)* } => { multiversion::target::match_target_impl!{ #features $($arms)* } } } pub(crate) use inherit_target; pub(crate) use target_cfg; pub(crate) use target_cfg_attr; pub(crate) use target_cfg_f; pub(crate) use match_target; } #block } } }; let mut fns = Vec::new(); for target in &self.targets { // This function will always be unsafe, regardless of the safety of the multiversioned // function. // // This could accidentally allow unsafe operations to end up in functions that appear // safe, but the deny lint should catch it. // // For now, nest a safe copy in the unsafe version. This is imperfect, but sound. // // When target_feature 1.1 is available, this function can instead use the original // function safety. let mut f = unsafe_fn_safe_block(ItemFn { attrs: self.inner_attrs.clone(), vis: Visibility::Inherited, sig: Signature { ident: feature_fn_name(&self.func.sig.ident, Some(target)), unsafety: parse_quote! { unsafe }, ..self.func.sig.clone() }, block: make_block(Some(target)), }); f.attrs.extend(target.fn_attrs()); fns.push(f); } // Create default fn let mut attrs = self.inner_attrs.clone(); attrs.push(parse_quote! { #[inline(always)] }); let block = make_block(None); fns.push(ItemFn { attrs, vis: self.func.vis.clone(), sig: Signature { ident: feature_fn_name(&self.func.sig.ident, None), ..self.func.sig.clone() }, block, }); Ok(fns) } fn call_target_fn(&self, target: Option<&Target>) -> Expr { let function = feature_fn_name(&self.func.sig.ident, target); let fn_params = util::fn_params(&self.func.sig); let (_, argument_names) = util::normalize_signature(&self.func.sig); let maybe_await = self.func.sig.asyncness.map(|_| util::await_tokens()); parse_quote! { unsafe { #function::<#(#fn_params),*>(#(#argument_names),*)#maybe_await } } } fn static_dispatcher_fn(&self) -> Block { let return_if_detected = self.targets.iter().filter_map(|target| { if target.has_features_specified() { let target_arch = target.target_arch(); let features_enabled = target.features_enabled(); let call = self.call_target_fn(Some(target)); Some(quote! { #target_arch { if #features_enabled { return #call } } }) } else { None } }); let call_default = self.call_target_fn(None); parse_quote! { { #(#return_if_detected)* #call_default } } } fn indirect_dispatcher_fn(&self) -> Result { if !cfg!(feature = "std") { return Err(Error::new( Span::call_site(), "indirect function dispatch only available with the `std` cargo feature", )); } if !util::fn_params(&self.func.sig).is_empty() { return Err(Error::new( Span::call_site(), "indirect function dispatch does not support type generic or const generic parameters", )); } if self.func.sig.asyncness.is_some() { return Err(Error::new( Span::call_site(), "indirect function dispatch does not support async functions", )); } if util::impl_trait_present(&self.func.sig) { return Err(Error::new( Span::call_site(), "indirect function dispatch does not support impl trait", )); } let fn_ty = util::fn_type_from_signature(&Signature { unsafety: parse_quote! { unsafe }, ..self.func.sig.clone() })?; let (normalized_signature, argument_names) = util::normalize_signature(&self.func.sig); let feature_detection = { let return_if_detected = self.targets.iter().filter_map(|target| { if target.has_features_specified() { let target_arch = target.target_arch(); let features_detected = target.features_detected(); let function = feature_fn_name(&self.func.sig.ident, Some(target)); Some(quote! { #target_arch { if #features_detected { return #function } } }) } else { None } }); let default_fn = feature_fn_name(&self.func.sig.ident, None); quote! { fn __get_fn() -> #fn_ty { #(#return_if_detected)* #default_fn }; } }; let resolver_signature = Signature { ident: Ident::new("__resolver_fn", Span::call_site()), ..normalized_signature }; Ok(parse_quote! { { use core::sync::atomic::{AtomicPtr, Ordering}; #[cold] #resolver_signature { #feature_detection let __current_fn = __get_fn(); __DISPATCHED_FN.store(__current_fn as *mut (), Ordering::Relaxed); unsafe { __current_fn(#(#argument_names),*) } } static __DISPATCHED_FN: AtomicPtr<()> = AtomicPtr::new(__resolver_fn as *mut ()); let __current_ptr = __DISPATCHED_FN.load(Ordering::Relaxed); // Safety: the pointer is a fn pointer, so we can transmute it back to its original // representation. #[allow(clippy::undocumented_unsafe_blocks)] unsafe { let __current_fn = core::mem::transmute::<*mut (), #fn_ty>(__current_ptr); __current_fn(#(#argument_names),*) } } }) } fn direct_dispatcher_fn(&self) -> Result { if !cfg!(feature = "std") { return Err(Error::new( Span::call_site(), "direct function dispatch only available with the `std` cargo feature", )); } let ordered_targets = self .targets .iter() .filter(|target| target.has_features_specified()) .collect::>(); let detect_index = { let detect_feature = ordered_targets.iter().enumerate().map(|(index, target)| { let index = index + 1; // 0 is default features let target_arch = target.target_arch(); let features_detected = target.features_detected(); quote! { #target_arch { if #features_detected { return #index } } } }); quote! { fn __detect_index() -> usize { #[cold] fn __detect() -> usize { #(#detect_feature)* 0 } use core::sync::atomic::{AtomicUsize, Ordering}; static SELECTED: AtomicUsize = AtomicUsize::new(usize::MAX); let selected = SELECTED.load(Ordering::Relaxed); if selected == usize::MAX { let selected = __detect(); SELECTED.store(selected, Ordering::Relaxed); selected } else { selected } } } }; let match_arm = ordered_targets.iter().enumerate().map(|(index, target)| { let index = index + 1; // 0 is default features let target_arch = target.target_arch(); let arm = self.call_target_fn(Some(target)); quote! { #target_arch #index => #arm, } }); let call_default = self.call_target_fn(None); Ok(parse_quote! { { #detect_index match __detect_index() { #(#match_arm)* 0 => #call_default, _ => unsafe { core::hint::unreachable_unchecked() }, } } }) } fn create_fn(&self) -> Result { // // First, we determine which dispatcher to use. // // If the dispatcher is unspecified, decide on the following criteria: // * If the std feature is not enabled, dispatch statically, since we can't do CPU feature // detection. // * If the function is generic, async, or has impl Trait, use direct dispatch, since we // can't take a function pointer. // * If any retpoline features are enabled use direct dispatch, since retpolines hurt // performance of indirect dispatch significantly. // * Otherwise, prefer indirect dispatch, since it appears to have better performance on // average. On machines with worse branch prediction, it may be significantly better. // let block = match self.dispatcher { DispatchMethod::Default => { if cfg!(feature = "std") { if !crate::util::fn_params(&self.func.sig).is_empty() || self.func.sig.asyncness.is_some() || util::impl_trait_present(&self.func.sig) || cfg!(retpoline) { self.direct_dispatcher_fn()? } else { self.indirect_dispatcher_fn()? } } else { self.static_dispatcher_fn() } } DispatchMethod::Static => self.static_dispatcher_fn(), DispatchMethod::Direct => self.direct_dispatcher_fn()?, DispatchMethod::Indirect => self.indirect_dispatcher_fn()?, }; // If we already know that the current build target supports the best function choice, we // can skip dispatching entirely. // // Here we check for one of two possibilities: // * If the globally enabled features (the target-feature or target-cpu codegen options) // already support the highest priority function, skip dispatch entirely and call that // function. // * If the current target isn't specified in the multiversioned list at all, we can skip // dispatch entirely and call the default function. // // In these cases, the default function is called instead. let best_targets = self .targets .iter() .rev() .map(|t| (t.arch(), t)) .collect::>(); let mut skips = Vec::new(); for (arch, target) in best_targets.iter() { let feature = target.features(); skips.push(quote! { all(target_arch = #arch, #(target_feature = #feature),*) }); } let specified_arches = best_targets.keys().collect::>(); let call_default = self.call_target_fn(None); let (normalized_signature, _) = util::normalize_signature(&self.func.sig); let feature_fns = self.feature_fns()?; Ok(ItemFn { attrs: self.func.attrs.clone(), vis: self.func.vis.clone(), sig: normalized_signature, block: Box::new(parse_quote! { { #(#feature_fns)* #[cfg(any( not(any(#(target_arch = #specified_arches),*)), #(#skips),* ))] { return #call_default } #[cfg(not(any( not(any(#(target_arch = #specified_arches),*)), #(#skips),* )))] #block } }), }) } } impl ToTokens for Dispatcher { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(match self.create_fn() { Ok(val) => val.into_token_stream(), Err(err) => err.to_compile_error(), }) } } multiversion-macros-0.8.0/src/lib.rs000064400000000000000000000103461046102023000155620ustar 00000000000000//! Implementation crate for `multiversion`. extern crate proc_macro; mod cfg; mod dispatcher; mod match_target; mod multiversion; mod target; mod util; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{parse::Nothing, parse_macro_input, punctuated::Punctuated, ItemFn}; #[proc_macro_attribute] pub fn multiversion( attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let func = parse_macro_input!(input as ItemFn); match multiversion::make_multiversioned_fn(attr.into(), func) { Ok(tokens) => tokens.into_token_stream(), Err(err) => err.to_compile_error(), } .into() } #[proc_macro_attribute] pub fn target( attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let target = parse_macro_input!(attr as syn::LitStr); let func = parse_macro_input!(input as ItemFn); match target::make_target_fn(target, func) { Ok(tokens) => tokens.into_token_stream(), Err(err) => err.to_compile_error(), } .into() } #[proc_macro_attribute] pub fn inherit_target( attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { parse_macro_input!(attr as Nothing); let func = parse_macro_input!(input as ItemFn); quote! { __multiversion::inherit_target! { #func } } .into() } #[proc_macro] pub fn selected_target(input: proc_macro::TokenStream) -> proc_macro::TokenStream { parse_macro_input!(input as Nothing); quote! { __multiversion::FEATURES } .into() } #[proc_macro_attribute] pub fn target_cfg( attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let attr = TokenStream::from(attr); let input = TokenStream::from(input); quote! { __multiversion::target_cfg!{ [#attr] #input } } .into() } #[proc_macro_attribute] pub fn target_cfg_attr( attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let attr = TokenStream::from(attr); let input = TokenStream::from(input); quote! { __multiversion::target_cfg_attr!{ [#attr] #input } } .into() } #[proc_macro] pub fn target_cfg_f(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = TokenStream::from(input); quote! { __multiversion::target_cfg_f!{ #input } } .into() } #[proc_macro_attribute] pub fn target_cfg_impl( attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let meta = parse_macro_input!(attr with Punctuated::parse_terminated); let input = TokenStream::from(input); match cfg::transform(meta) { Ok(meta) => { quote! { #[cfg(#meta)] #input } } Err(err) => err.to_compile_error(), } .into() } #[proc_macro_attribute] pub fn target_cfg_attr_impl( attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let mut meta = parse_macro_input!(attr with Punctuated::parse_terminated); let input = TokenStream::from(input); let attr = meta.pop().unwrap(); match cfg::transform(meta) { Ok(meta) => { quote! { #[cfg_attr(#meta, #attr)] #input } } Err(err) => err.to_compile_error(), } .into() } #[proc_macro] pub fn target_cfg_f_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let meta = parse_macro_input!(input with Punctuated::parse_terminated); match cfg::transform(meta) { Ok(meta) => { quote! { cfg!(#meta) } } Err(err) => err.to_compile_error(), } .into() } #[proc_macro] pub fn match_target(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = TokenStream::from(input); quote! { __multiversion::match_target!{ #input } } .into() } #[proc_macro] pub fn match_target_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let match_target = parse_macro_input!(input as match_target::MatchTarget); match_target.into_token_stream().into() } multiversion-macros-0.8.0/src/match_target.rs000064400000000000000000000064541046102023000174630ustar 00000000000000use crate::target::Target; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::{ parse::{Parse, ParseStream}, parse_quote, spanned::Spanned, Error, Expr, ExprLit, Lit, LitStr, Pat, Result, }; pub struct MatchTarget { features: LitStr, arms: Vec<(Target, Expr)>, default_target: Option, } impl Parse for MatchTarget { fn parse(input: ParseStream<'_>) -> Result { let features = input.parse()?; let mut arms = Vec::new(); let mut default_target = None; while !input.is_empty() { let arm: syn::Arm = input.parse()?; if !arm.attrs.is_empty() { return Err(Error::new(arm.attrs[0].span(), "unexpected attribute")); } let pat = arm.pat; if let Some(guard) = arm.guard { return Err(Error::new(guard.0.span(), "unexpected guard")); } fn parse_target(e: &ExprLit) -> Result { if let Lit::Str(s) = &e.lit { Target::parse(s) } else { Err(Error::new(e.span(), "expected a string literal")) } } match pat { Pat::Lit(lit) => { arms.push((parse_target(&lit)?, *arm.body)); } Pat::Or(or) => { for case in or.cases.iter() { if let Pat::Lit(lit) = case { arms.push((parse_target(lit)?, *arm.body.clone())); } else { return Err(Error::new(case.span(), "expected a string literal")); } } } Pat::Wild(_) => { default_target = Some(*arm.body); if !input.is_empty() { return Err(Error::new(input.span(), "unreachable targets")); } } _ => return Err(Error::new(pat.span(), "expected string literal")), } } Ok(MatchTarget { features, arms, default_target, }) } } impl ToTokens for MatchTarget { fn to_tokens(&self, tokens: &mut TokenStream) { let mut exprs = Vec::new(); let mut not_targets = Vec::new(); for (target, expr) in &self.arms { let arch = target.arch(); let features = target.features(); let selected_features = &self.features; let cfg = crate::cfg::transform( parse_quote! { target_features = #selected_features, all(target_arch = #arch #(, target_feature = #features)*) }, ).unwrap(); exprs.push(quote! { #[cfg(all(#cfg, not(any(#(#not_targets),*))))] { #expr } }); not_targets.push(cfg); } let default_expr = if let Some(expr) = &self.default_target { quote! { #expr } } else { Error::new(Span::call_site(), "no matching target").to_compile_error() }; quote! { { #(#exprs)* #[cfg(not(any(#(#not_targets),*)))] #default_expr } } .to_tokens(tokens) } } multiversion-macros-0.8.0/src/multiversion.rs000064400000000000000000000115001046102023000175450ustar 00000000000000use crate::dispatcher::{DispatchMethod, Dispatcher}; use crate::target::Target; use proc_macro2::TokenStream; use quote::ToTokens; use syn::{ parenthesized, parse::Parser, parse_quote, punctuated::Punctuated, spanned::Spanned, token, Attribute, Error, ItemFn, LitStr, Meta, ReturnType, Type, }; pub(crate) fn make_multiversioned_fn( attr: TokenStream, func: ItemFn, ) -> Result { if let ReturnType::Type(_, ty) = &func.sig.output { if let Type::ImplTrait(_) = **ty { return Err(Error::new( ty.span(), "cannot multiversion function with `impl Trait` return type", )); } } let mut targets: Option> = None; let mut inner_attrs: Option> = None; let mut dispatcher: Option = None; let parser = syn::meta::parser(|meta| { if targets.is_some() && (meta.path.is_ident("targets") || meta.path.is_ident("simd")) { return Err(meta.error("can't specify `targets` or `simd` multiple times")); } if meta.path.is_ident("targets") { if meta.input.peek(token::Paren) { let content; parenthesized!(content in meta.input); targets = Some( Punctuated::::parse_terminated(&content)? .into_iter() .collect(), ); return Ok(()); } else { let value = meta.value()?; let s: LitStr = value.parse()?; if s.value().as_str() == "simd" { let default_targets = [ // "x86_64+avx512f+avx512bw+avx512cd+avx512dq+avx512vl", "x86_64+avx2+fma", "x86_64+sse4.2", // "x86+avx512f+avx512bw+avx512cd+avx512dq+avx512vl", "x86+avx2+fma", "x86+sse4.2", "x86+sse2", "aarch64+neon", // "arm+neon", // "mips+msa", // "mips64+msa", // "powerpc+vsx", // "powerpc+altivec", // "powerpc64+vsx", // "powerpc64+altivec", ]; targets = Some( default_targets .iter() .map(|x| Target::parse(&LitStr::new(x, meta.path.span())).unwrap()) .collect(), ); return Ok(()); } return Err(meta.error("expected a list of features or \"simd\"")); } } if meta.path.is_ident("attrs") { if inner_attrs.is_some() { return Err(meta.error("can't specify `attrs` multiple times")); } inner_attrs = Some(Vec::new()); let content; parenthesized!(content in meta.input); inner_attrs = Some( Punctuated::::parse_terminated(&content)? .into_iter() .map(|meta| parse_quote! { #[#meta] }) .collect(), ); return Ok(()); } if meta.path.is_ident("dispatcher") { if dispatcher.is_some() { return Err(meta.error("can't specify `dispatcher` multiple times")); } let value = meta.value()?; let s: LitStr = value.parse()?; dispatcher = Some(match s.value().as_str() { "default" => DispatchMethod::Default, "static" => DispatchMethod::Static, "direct" => DispatchMethod::Direct, "indirect" => DispatchMethod::Indirect, _ => { return Err(meta.error("expected `default`, `static`, `direct`, or `indirect`")) } }); return Ok(()); }; Err(meta.error("unrecognized option")) }); let span = attr.span(); parser.parse2(attr)?; let targets = if let Some(targets) = targets { for target in targets.iter() { if !target.has_features_specified() { // TODO add span to Target return Err(Error::new(span, "target must have features specified")); } } targets } else { return Err(Error::new(span, "expected `targets`")); }; let inner_attrs = inner_attrs.unwrap_or_default(); let dispatcher = dispatcher.unwrap_or(DispatchMethod::Default); Ok(Dispatcher { targets, func, inner_attrs, dispatcher, } .to_token_stream()) } multiversion-macros-0.8.0/src/target.rs000064400000000000000000000165001046102023000163000ustar 00000000000000use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{ parse::{Parse, ParseStream}, parse_quote, Attribute, Error, ItemFn, Lit, LitStr, Result, }; use target_features::{Architecture, Feature}; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Target { architecture: String, features: Vec, } impl Target { pub(crate) fn parse(s: &LitStr) -> Result { let value = s.value(); let mut it = value.as_str().split('+'); let architecture = it .next() .ok_or_else(|| Error::new(s.span(), "expected architecture specifier"))?; // Architecture can be either "architecture" or "architecture/cpu" let mut maybe_cpu = architecture.splitn(2, '/'); let architecture = maybe_cpu .next() .ok_or_else(|| Error::new(s.span(), "expected architecture specifier"))? .to_string(); let cpu = maybe_cpu.next(); if architecture.is_empty() || !architecture .chars() .all(|x| x.is_alphanumeric() || x == '_') { return Err(Error::new(s.span(), "invalid architecture specifier")); }; let specified_features = it .map(|x| { if x.is_empty() { Err(Error::new(s.span(), "feature string cannot be empty")) } else { Ok(x.to_string()) } }) .collect::>>()?; let target = { let architecture = Architecture::from_str(&architecture); let mut target = if let Some(cpu) = cpu { target_features::Target::from_cpu(architecture, cpu) .map_err(|_| Error::new(s.span(), format!("unknown target CPU: {cpu}")))? } else { target_features::Target::new(architecture) }; for feature in specified_features { target = target.with_feature(Feature::new(architecture, &feature).map_err(|_| { Error::new(s.span(), format!("unknown target feature: {feature}")) })?); } target }; let mut features = target .features() .map(|f| f.name().to_string()) .collect::>(); features.sort_unstable(); Ok(Self { architecture, features, }) } pub fn arch(&self) -> &str { &self.architecture } pub fn features(&self) -> &[String] { self.features.as_ref() } pub fn features_string(&self) -> String { self.features.join("_").replace('.', "") } pub fn has_features_specified(&self) -> bool { !self.features.is_empty() } pub fn target_arch(&self) -> Attribute { let arch = &self.architecture; parse_quote! { #[cfg(target_arch = #arch)] } } pub fn target_feature(&self) -> Vec { self.features .iter() .map(|feature| { parse_quote! { #[target_feature(enable = #feature)] } }) .collect() } pub fn fn_attrs(&self) -> Vec { let mut attrs = self.target_feature(); attrs.push(self.target_arch()); attrs } pub fn features_enabled(&self) -> TokenStream { let feature = self.features.iter(); quote! { true #( && core::cfg!(target_feature = #feature) )* } } pub fn features_detected(&self) -> TokenStream { let feature = self.features.iter(); let is_feature_detected = format_ident!( "is_{}_feature_detected", match self.architecture.as_str() { "x86_64" => "x86", "risv64" => "riscv", f => f, } ); quote! { true #( && std::arch::#is_feature_detected!(#feature) )* } } } impl std::convert::TryFrom<&Lit> for Target { type Error = Error; fn try_from(lit: &Lit) -> Result { match lit { Lit::Str(s) => Self::parse(s), _ => Err(Error::new(lit.span(), "expected literal string")), } } } impl Parse for Target { fn parse(input: ParseStream<'_>) -> Result { Target::parse(&input.parse()?) } } impl ToTokens for Target { fn to_tokens(&self, tokens: &mut TokenStream) { let mut s = self.architecture.clone(); for feature in &self.features { s.push('+'); s.push_str(feature); } LitStr::new(&s, Span::call_site()).to_tokens(tokens); } } pub(crate) fn make_target_fn(target: LitStr, func: ItemFn) -> Result { let target = Target::parse(&target)?; let target_arch = target.target_arch(); let target_feature = target.target_feature(); Ok(parse_quote! { #target_arch #(#target_feature)* #func }) } #[cfg(test)] mod test { use super::*; #[test] fn parse_architecture() {} #[test] fn parse_no_features() { let s = LitStr::new("x86", Span::call_site()); let target = Target::parse(&s).unwrap(); assert_eq!(target.architecture, "x86"); assert!(target.features.is_empty()); } #[test] fn parse_features() { let s = LitStr::new("x86_64+sse4.2+xsave", Span::call_site()); let target = Target::parse(&s).unwrap(); assert_eq!(target.architecture, "x86_64"); assert!(target.features.iter().any(|f| f == "sse4.2")); assert!(target.features.iter().any(|f| f == "xsave")); } #[test] fn parse_extra_plus_start() { let s = LitStr::new("+x86+sse4.2+xsave", Span::call_site()); Target::parse(&s).unwrap_err(); } #[test] fn parse_extra_plus_end() { let s = LitStr::new("x86+sse4.2+xsave+", Span::call_site()); Target::parse(&s).unwrap_err(); } #[test] fn parse_cpu() { let s = LitStr::new("powerpc64/pwr7", Span::call_site()); let target = Target::parse(&s).unwrap(); assert_eq!(target.architecture, "powerpc64"); assert!(target.features.iter().any(|f| f == "altivec")); assert!(target.features.iter().any(|f| f == "vsx")); } #[test] fn parse_cpu_features() { let s = LitStr::new("x86/i686+xsave", Span::call_site()); let target = Target::parse(&s).unwrap(); assert_eq!(target.architecture, "x86"); assert!(target.features.iter().any(|f| f == "sse2")); assert!(target.features.iter().any(|f| f == "xsave")); } #[test] fn generate_target_arch() { let s = LitStr::new("x86+avx", Span::call_site()); let target = Target::parse(&s).unwrap(); assert_eq!( target.target_arch(), parse_quote! { #[cfg(target_arch = "x86")] } ); } #[test] fn generate_target_feature() { let s = LitStr::new("x86+avx+xsave", Span::call_site()); let target = Target::parse(&s).unwrap(); assert!(target .target_feature() .contains(&parse_quote! { #[target_feature(enable = "avx")] })); assert!(target .target_feature() .contains(&parse_quote! { #[target_feature(enable = "xsave")] })); } } multiversion-macros-0.8.0/src/util.rs000064400000000000000000000100611046102023000157630ustar 00000000000000use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{ parse_quote, spanned::Spanned, visit::Visit, visit_mut::VisitMut, BareFnArg, Error, Expr, FnArg, GenericParam, Ident, Lifetime, Pat, PatIdent, PatType, Result, Signature, TypeBareFn, TypeImplTrait, }; pub(crate) fn arg_exprs(sig: &Signature) -> Vec { sig.inputs .iter() .map(|x| match x { FnArg::Receiver(rec) => { let self_token = rec.self_token; parse_quote! { #self_token } } FnArg::Typed(arg) => { if let Pat::Ident(ident) = &*arg.pat { let ident = &ident.ident; parse_quote! { #ident } } else { panic!("pattern should have been ident") } } }) .collect() } pub(crate) fn normalize_signature(sig: &Signature) -> (Signature, Vec) { let args = sig .inputs .iter() .enumerate() .map(|(i, x)| match x { FnArg::Receiver(_) => x.clone(), FnArg::Typed(arg) => FnArg::Typed(PatType { pat: Box::new(Pat::Ident(PatIdent { attrs: Vec::new(), by_ref: None, mutability: None, ident: match arg.pat.as_ref() { Pat::Ident(pat) => pat.ident.clone(), _ => Ident::new(&format!("__multiversion_arg_{i}"), x.span()), }, subpat: None, })), ..arg.clone() }), }) .collect::>(); let sig = Signature { inputs: parse_quote! { #(#args),* }, ..sig.clone() }; let callable_args = arg_exprs(&sig); (sig, callable_args) } pub(crate) fn impl_trait_present(sig: &Signature) -> bool { struct ImplTraitPresent(bool); impl Visit<'_> for ImplTraitPresent { fn visit_type_impl_trait(&mut self, _: &TypeImplTrait) { self.0 = true; } } let mut visitor = ImplTraitPresent(false); visitor.visit_signature(sig); visitor.0 } struct LifetimeRenamer; impl VisitMut for LifetimeRenamer { fn visit_lifetime_mut(&mut self, i: &mut Lifetime) { i.ident = Ident::new(&format!("__mv_inner_{}", i.ident), i.ident.span()); } } pub(crate) fn fn_type_from_signature(sig: &Signature) -> Result { let lifetimes = sig.generics.lifetimes().collect::>(); let args = sig .inputs .iter() .map(|x| { Ok(BareFnArg { attrs: Vec::new(), name: None, ty: match x { FnArg::Receiver(rec) => Err(Error::new( rec.self_token.span, "cannot determine type of associated fn", )), FnArg::Typed(arg) => Ok(arg.ty.as_ref().clone()), }?, }) }) .collect::>>()?; assert!( sig.variadic.is_none(), "cannot multiversion function with variadic arguments" ); let mut fn_ty = TypeBareFn { lifetimes: if lifetimes.is_empty() { None } else { Some(parse_quote! { for<#(#lifetimes),*> }) }, unsafety: sig.unsafety, abi: sig.abi.clone(), fn_token: sig.fn_token, paren_token: sig.paren_token, inputs: parse_quote! { #(#args),* }, variadic: None, output: sig.output.clone(), }; LifetimeRenamer {}.visit_type_bare_fn_mut(&mut fn_ty); Ok(fn_ty) } pub(crate) fn fn_params(sig: &Signature) -> Vec { sig.generics .params .iter() .filter_map(|x| match x { GenericParam::Type(ty) => Some(ty.ident.clone()), GenericParam::Const(c) => Some(c.ident.clone()), _ => None, }) .collect() } pub(crate) fn await_tokens() -> TokenStream { let kw = Ident::new("await", Span::call_site()); quote! { .#kw } }