target_cpu_macro/
lib.rs

1//! A crate used to query the current target CPU for a crate.
2//!
3//! Provides macros for fetching the target CPU name, and custom
4//! attributes that can be used to conditionally enable code
5//! based on that CPU.
6//!
7//! Uses the crate [target-cpu-fetch](https://crates.io/crates/target-cpu-fetch) to
8//! drive the logic.
9
10#![feature(proc_macro_hygiene)]
11
12extern crate proc_macro;
13
14use target_cpu_fetch as fetch_cpu;
15mod macro_impl;
16
17use proc_macro::*;
18
19/// Expands into a `&'static str` string literal containing the current CPU name.
20#[proc_macro]
21pub fn cpu_name(input: proc_macro::TokenStream) -> TokenStream {
22    ensure_empty_stream(input);
23
24    match fetch_cpu::target_cpu().expect("failed to fetch target CPU name") {
25        Some(cpu_name) => format!("\"{}\"", cpu_name).parse().unwrap(),
26        None => {
27            panic!("target CPU is not available");
28        },
29    }
30}
31
32/// Expands into a `Option<&'static str>` containing the current CPU name.
33#[proc_macro]
34pub fn maybe_cpu_name(input: proc_macro::TokenStream) -> TokenStream {
35    ensure_empty_stream(input);
36
37    match fetch_cpu::target_cpu() {
38        Ok(Some(cpu_name)) => format!("Some(\"{}\")", cpu_name).parse().unwrap(),
39        _ => "None".parse().unwrap(),
40    }
41}
42
43/// Conditionally enables a piece of code if the target CPU has the specified name.
44#[proc_macro_attribute]
45pub fn cfg_target_cpu_eq(args: TokenStream, input: TokenStream) -> TokenStream {
46    macro_impl::cfg_target_cpu(args, input, macro_impl::Condition::Equal)
47}
48
49/// Conditionally enables a piece of code if the target CPU does not have the specified name.
50#[proc_macro_attribute]
51pub fn cfg_target_cpu_neq(args: TokenStream, input: TokenStream) -> TokenStream {
52    macro_impl::cfg_target_cpu(args, input, macro_impl::Condition::NotEqual)
53}
54
55fn ensure_empty_stream(input: proc_macro::TokenStream) {
56    if !input.is_empty() {
57        panic!("no arguments expected to target CPU name macro");
58    }
59
60}