Skip to content

Experimental support for "features" #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,5 @@ proc-macro2 = "1.0.32"
quote = "1.0.10"
syn = "1.0.82"
smallvec = "1.8.0"

[dev-dependencies]
serde = { version = "1.0.130", features = ["derive"] }
serde_json = "1.0.72"
2 changes: 2 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Dummy build.rs to ensure OUT_DIR environment variable is set for tests and examples.
fn main() {}
97 changes: 97 additions & 0 deletions examples/features.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// TODO: make this into a test
use serde::{Deserialize, Serialize};
use superstruct::superstruct;

#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum ForkName {
Bellatrix,
Capella,
Deneb,
Electra,
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum FeatureName {
Merge,
Withdrawals,
Blobs,
EIP6110,
Verge,
EIP7549,
}

#[superstruct(variants_and_features_decl = "FORK_ORDER")]
const FORK_ORDER: &[(ForkName, &[FeatureName])] = &[
(ForkName::Bellatrix, &[FeatureName::Merge]),
(ForkName::Capella, &[FeatureName::Withdrawals]),
(
ForkName::Electra,
&[FeatureName::EIP6110, FeatureName::Verge],
),
];

#[superstruct(feature_dependencies_decl = "FEATURE_DEPENDENCIES")]
const FEATURE_DEPENDENCIES: &[(FeatureName, &[FeatureName])] = &[
(FeatureName::Withdrawals, &[FeatureName::Merge]),
(FeatureName::Blobs, &[FeatureName::Withdrawals]),
(FeatureName::EIP6110, &[FeatureName::Merge]),
(FeatureName::Verge, &[FeatureName::Merge]),
];

#[superstruct(
variants_and_features_from = "FORK_ORDER",
feature_dependencies = "FEATURE_DEPENDENCIES",
variant_type(name = "ForkName", getter = "fork_name"),
feature_type(
name = "FeatureName",
list = "feature_names",
check = "check_feature_enabled"
)
)]
struct Block {
historical_updates: String,
#[superstruct(feature(Withdrawals))]
historical_summaries: String,
#[superstruct(feature(Withdrawals))] // in the Withdrawals fork, and all subsequent
withdrawals: Vec<u64>,
#[superstruct(feature(Blobs))] // if Blobs is not enabled, this is completely disabled
blobs: Vec<u64>,
#[superstruct(feature(EIP6110))]
deposits: Vec<u64>,
}

#[superstruct(
feature(Withdrawals),
variants_and_features_from = "FORK_ORDER",
feature_dependencies = "FEATURE_DEPENDENCIES",
variant_type(name = "ForkName", getter = "fork_name"),
feature_type(
name = "FeatureName",
list = "feature_names",
check = "check_feature_enabled"
)
)]
struct Payload {
transactions: Vec<u64>,
}

fn main() {
let block = Block::Electra(BlockElectra {
historical_updates: "hey".into(),
historical_summaries: "thing".into(),
withdrawals: vec![1, 2, 3],
deposits: vec![0, 0, 0, 0, 0, 0],
});

assert_eq!(block.fork_name(), ForkName::Electra);
assert_eq!(
block.feature_names(),
vec![
FeatureName::Merge,
FeatureName::Withdrawals,
FeatureName::EIP6110,
FeatureName::Verge
]
);
assert!(block.check_feature_enabled(FeatureName::EIP6110));
}
75 changes: 75 additions & 0 deletions src/feature_expr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use darling::{Error, FromMeta};
use syn::{Ident, Meta, NestedMeta};

/// A cfg-like expression in terms of features, which can be evaluated for each fork at each field
/// to determine whether that field is turned on.
#[derive(Debug)]
pub enum FeatureExpr {
And(Box<FeatureExpr>, Box<FeatureExpr>),
Or(Box<FeatureExpr>, Box<FeatureExpr>),
Not(Box<FeatureExpr>),
Literal(Ident),
}

fn parse(meta: NestedMeta) -> Result<FeatureExpr, Error> {
match meta {
// TODO: assert 1 segment
NestedMeta::Meta(Meta::Path(path)) => Ok(FeatureExpr::Literal(
path.segments.last().unwrap().ident.clone(),
)),
NestedMeta::Meta(Meta::List(meta_list)) => {
let segments = &meta_list.path.segments;
assert_eq!(segments.len(), 1);
let operator = &segments.last().unwrap().ident;
match operator.to_string().as_str() {
"and" => {
let mut nested = meta_list.nested;
assert_eq!(nested.len(), 2, "`and` should have exactly 2 operands");
let right_meta = nested.pop().unwrap().into_value();
let left_meta = nested.pop().unwrap().into_value();
Ok(FeatureExpr::And(
Box::new(parse(left_meta)?),
Box::new(parse(right_meta)?),
))
}
"or" => {
let mut nested = meta_list.nested;
assert_eq!(nested.len(), 2, "`or` should have exactly 2 operands");
let right_meta = nested.pop().unwrap().into_value();
let left_meta = nested.pop().unwrap().into_value();
Ok(FeatureExpr::Or(
Box::new(parse(left_meta)?),
Box::new(parse(right_meta)?),
))
}
"not" => {
let mut nested = meta_list.nested;
assert_eq!(nested.len(), 1, "`not` should have exactly 1 operand");
let inner_meta = nested.pop().unwrap().into_value();
Ok(FeatureExpr::Not(Box::new(parse(inner_meta)?)))
}
op => panic!("unsupported operator: {op}"),
}
}
_ => panic!("unexpected feature expr: {meta:?}"),
}
}

impl FromMeta for FeatureExpr {
fn from_list(items: &[NestedMeta]) -> Result<Self, Error> {
assert_eq!(items.len(), 1, "feature expr should have 1 part");
let expr_meta = items.first().cloned().unwrap();
parse(expr_meta)
}
}

impl FeatureExpr {
pub fn eval(&self, features: &[Ident]) -> bool {
match self {
Self::Literal(feature_name) => features.contains(&feature_name),
Self::And(left, right) => left.eval(features) && right.eval(features),
Self::Or(left, right) => left.eval(features) || right.eval(features),
Self::Not(inner) => !inner.eval(features),
}
}
}
113 changes: 113 additions & 0 deletions src/feature_getters.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use crate::{FeatureTypeOpts, VariantTypeOpts};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::collections::HashMap;
use syn::Ident;

const DEFAULT_VARIANT_TYPE_GETTER: &str = "variant_type";
const DEFAULT_FEATURE_TYPE_LIST: &str = "list_all_features";
const DEFAULT_FEATURE_TYPE_CHECK: &str = "is_feature_enabled";

pub fn get_feature_getters(
type_name: &Ident,
variant_names: &[Ident],
all_variant_features_opts: Option<HashMap<Ident, Vec<Ident>>>,
variant_type_opts: &Option<VariantTypeOpts>,
feature_type_opts: &Option<FeatureTypeOpts>,
) -> Vec<TokenStream> {
let Some(variant_type) = variant_type_opts else {
return vec![];
};
let Some(feature_type) = feature_type_opts else {
return vec![];
};
let Some(all_variant_features) = all_variant_features_opts else {
return vec![];
};

let mut output = vec![];

output.extend(get_variant_type_getters(
type_name,
variant_names,
variant_type,
));
output.extend(get_feature_type_getters(
type_name,
variant_names,
all_variant_features,
feature_type,
));
output
}

pub fn get_variant_type_getters(
type_name: &Ident,
variant_names: &[Ident],
variant_type: &VariantTypeOpts,
) -> Vec<TokenStream> {
let variant_type_name = &variant_type.name;
let getter_name = variant_type
.getter
.clone()
.unwrap_or_else(|| Ident::new(DEFAULT_VARIANT_TYPE_GETTER, Span::call_site()));
let getter = quote! {
pub fn #getter_name(&self) -> #variant_type_name {
match self {
#(
#type_name::#variant_names(..) => #variant_type_name::#variant_names,
)*
}
}
};
vec![getter.into()]
}

pub fn get_feature_type_getters(
type_name: &Ident,
variant_names: &[Ident],
all_variant_features: HashMap<Ident, Vec<Ident>>,
feature_type: &FeatureTypeOpts,
) -> Vec<TokenStream> {
let feature_type_name = &feature_type.name;
let list_features = feature_type
.list
.clone()
.unwrap_or_else(|| Ident::new(DEFAULT_FEATURE_TYPE_LIST, Span::call_site()));

let mut feature_sets: Vec<Vec<Ident>> = vec![];

for variant in variant_names {
// If not all variants are defined for this type, then skip.
if let Some(feature_set) = all_variant_features.get(variant) {
feature_sets.push(feature_set.clone());
} else {
continue;
}
}

let feature_list = quote! {
pub fn #list_features(&self) -> &'static [#feature_type_name] {
match self {
#(
#type_name::#variant_names(..) => &[#(#feature_type_name::#feature_sets),*],
)*
}
}
};

let check_feature = feature_type
.check
.clone()
.unwrap_or_else(|| Ident::new(DEFAULT_FEATURE_TYPE_CHECK, Span::call_site()));
let feature_check = quote! {
pub fn #check_feature(&self, feature: #feature_type_name) -> bool {
match self {
#(
#type_name::#variant_names(..) => self.#list_features().contains(&feature),
)*
}
}
};
vec![feature_list.into(), feature_check.into()]
}
Loading