Last active
July 20, 2017 03:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!