Skip to content

Instantly share code, notes, and snippets.

@shivshank
Last active July 20, 2017 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shivshank/1f93a722ead418cb67e089d68bd22623 to your computer and use it in GitHub Desktop.
Save shivshank/1f93a722ead418cb67e089d68bd22623 to your computer and use it in GitHub Desktop.
Parses (a very specific subset) of syn::ConstExpr for use with procedural macros
fn evaluate_bin_sum(expr: &syn::ConstExpr) -> u64 {
match expr {
// TODO: Fix the pattern (first match is left == literal, right == binary op, second match should be both are literals)
&syn::ConstExpr::Binary(syn::BinOp::Add, ref left, ref right) => {
extract_int_value(left) + evaluate_bin_sum(right)
},
&syn::ConstExpr::Binary(syn::BinOp::Add, ref left, ref right) => {
extract_int_value(left) + extract_int_value(right)
},
_ => {
panic!("Expected a binary expression such as 0 + 1 + 1 + 1")
}
}
}
fn extract_int_value(lit: &syn::ConstExpr) -> u64 {
match lit {
&syn::ConstExpr::Lit(syn::Lit::Int(val, _)) => {
val
},
_ => panic!("Expected a literal")
}
}
@shivshank
Copy link
Author

I had written this when I thought I needed to parse a 0 + 1 + 1 ... const expr (which was generated by a macro...) in a proc macro, but ended up not needing this... should take 60 seconds to fix the matching bug!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment