Skip to content
Draft
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ can-dbc = "8.0.1"
embedded-can = "0.4.1"
heck = "0.5.0"
prettyplease = "0.2.37"
quote = "1.0"
proc-macro2 = "1.0.92"
quote = "1.0.44"
syn = "2.0.114"
typed-builder = "0.23.0"

Expand Down
39 changes: 15 additions & 24 deletions src/feature_config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use std::fmt::Display;
use std::io::Write;

use anyhow::{Error, Result};
use proc_macro2::TokenStream;
use quote::quote;

/// Configuration for including features in the code generator.
///
Expand All @@ -20,31 +18,24 @@ pub enum FeatureConfig<'a> {
}

impl FeatureConfig<'_> {
pub(crate) fn fmt_attr(&self, w: &mut impl Write, attr: impl Display) -> Result<()> {
/// Generate an attribute token stream (like `#[derive(Debug)]`)
pub(crate) fn attr(&self, tokens: &TokenStream) -> TokenStream {
match self {
FeatureConfig::Always => writeln!(w, "#[{attr}]")?,
FeatureConfig::Gated(gate) => writeln!(w, "#[cfg_attr(feature = {gate:?}, {attr})]")?,
FeatureConfig::Never => {}
FeatureConfig::Always => quote! { #[#tokens] },
FeatureConfig::Gated(gate) => quote! { #[cfg_attr(feature = #gate, #tokens)] },
FeatureConfig::Never => quote! {},
}
Ok(())
}

pub(crate) fn fmt_cfg<W: Write, E: Into<Error>>(
&self,
mut w: W,
f: impl FnOnce(W) -> Result<(), E>,
) -> Result<()> {
/// Generate a token stream optionally wrapped in a cfg attribute
pub(crate) fn if_cfg(&self, tokens: TokenStream) -> TokenStream {
match self {
// If config is Never, return immediately without calling `f`
FeatureConfig::Never => return Ok(()),
// If config is Gated, prepend `f` with a cfg guard
FeatureConfig::Gated(gate) => {
writeln!(w, "#[cfg(feature = {gate:?})]")?;
}
// Otherwise, just call `f`
FeatureConfig::Always => {}
FeatureConfig::Always => tokens,
FeatureConfig::Gated(gate) => quote! {
#[cfg(feature = #gate)]
#tokens
},
FeatureConfig::Never => quote! {},
}

f(w).map_err(Into::into)
}
}
Loading
Loading