-
Notifications
You must be signed in to change notification settings - Fork 64
feat: add macro #179
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
Merged
Merged
feat: add macro #179
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
735b912
feat: add macro
tdelabro ae50e10
chore: move macro to own file
tdelabro 9465192
typos
tdelabro fa8c332
extern crate alloc import in test
tdelabro ef5bf3a
unsigned int const expressions OK
tdelabro 4805529
more types handled
tdelabro f71eec8
spaned errors
tdelabro 75ef55d
alloc in tests
tdelabro 80a40e9
review
tdelabro cc61bf3
improve error message
tdelabro File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| name: Typo Check | ||
|
|
||
| on: | ||
| push: | ||
| branches: [ main ] | ||
| pull_request: | ||
| branches: [ main ] | ||
|
|
||
| jobs: | ||
| typos: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: crate-ci/typos@master |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| [workspace] | ||
| members = [ | ||
| "crates/felt-macro", | ||
| "crates/starknet-types-core", | ||
| ] | ||
|
|
||
|
|
||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| [package] | ||
| name = "felt-macro" | ||
| version = "0.1.0" | ||
| edition = "2024" | ||
|
|
||
| [lib] | ||
| proc-macro = true | ||
|
|
||
| [dependencies] | ||
| syn = { version = "2.0", features = ["full"] } | ||
| quote = "1.0" | ||
| proc-macro2 = "1.0" | ||
| lambdaworks-math = { version = "0.13.0", default-features = false } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| use proc_macro::TokenStream; | ||
| use quote::quote; | ||
| use std::ops::Neg; | ||
| use syn::{Error, Expr, ExprLit, ExprUnary, Lit, Result, parse_macro_input}; | ||
|
|
||
| use lambdaworks_math::{ | ||
| field::{ | ||
| element::FieldElement, fields::fft_friendly::stark_252_prime_field::Stark252PrimeField, | ||
| }, | ||
| traits::ByteConversion, | ||
| unsigned_integer::element::UnsignedInteger, | ||
| }; | ||
|
|
||
| type LambdaFieldElement = FieldElement<Stark252PrimeField>; | ||
|
|
||
| enum HandleExprOutput { | ||
| ComptimeFelt(LambdaFieldElement), | ||
| Runtime, | ||
| } | ||
|
|
||
| #[proc_macro] | ||
| pub fn felt(input: TokenStream) -> TokenStream { | ||
| let expr = parse_macro_input!(input as Expr); | ||
|
|
||
| match handle_expr(&expr) { | ||
| Ok(HandleExprOutput::ComptimeFelt(field_element)) => { | ||
| generate_const_felt_token_stream_from_lambda_field_element(field_element).into() | ||
| } | ||
| Ok(HandleExprOutput::Runtime) => quote! { | ||
| match Felt::try_from(#expr) { | ||
| Ok(f) => f, | ||
| Err(e) => panic!("Invalid Felt value: {}", e), | ||
| } | ||
| } | ||
| .into(), | ||
| Err(error) => error.to_compile_error().into(), | ||
| } | ||
| } | ||
|
|
||
| /// Take the lambda class type for field element, extract its limbs and generate the token stream for a const value of itself | ||
| fn generate_const_felt_token_stream_from_lambda_field_element( | ||
| value: LambdaFieldElement, | ||
| ) -> proc_macro2::TokenStream { | ||
| let limbs = value.to_raw().limbs; | ||
| let r0 = limbs[0]; | ||
| let r1 = limbs[1]; | ||
| let r2 = limbs[2]; | ||
| let r3 = limbs[3]; | ||
|
|
||
| quote! { | ||
| { | ||
| const __FELT_VALUE: Felt = Felt::from_raw([#r0, #r1, #r2, #r3]); | ||
| __FELT_VALUE | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn handle_expr(expr: &syn::Expr) -> Result<HandleExprOutput> { | ||
| match expr { | ||
| Expr::Lit(expr_lit) => match &expr_lit.lit { | ||
| Lit::Bool(lit_bool) => Ok(HandleExprOutput::ComptimeFelt(match lit_bool.value() { | ||
| false => LambdaFieldElement::from(&UnsignedInteger::from_u64(0)), | ||
| true => LambdaFieldElement::from(&UnsignedInteger::from_u64(1)), | ||
| })), | ||
|
|
||
| Lit::Int(lit_int) => { | ||
| let value = match lit_int.base10_parse::<u128>() { | ||
| Ok(v) => v, | ||
| Err(_) => { | ||
| return Err(Error::new_spanned( | ||
| lit_int, | ||
| "Invalid integer literal for Felt conversion", | ||
| )); | ||
| } | ||
| }; | ||
|
|
||
| Ok(HandleExprOutput::ComptimeFelt(LambdaFieldElement::from( | ||
| &UnsignedInteger::from(value), | ||
| ))) | ||
| } | ||
|
|
||
| Lit::Str(lit_str) => { | ||
| let value = lit_str.value(); | ||
|
|
||
| let (is_neg, value) = if let Some(striped) = value.strip_prefix('-') { | ||
| (true, striped) | ||
| } else { | ||
| (false, value.as_str()) | ||
| }; | ||
|
|
||
| let lfe = if value.starts_with("0x") || value.starts_with("0X") { | ||
| UnsignedInteger::from_hex(value).map(|x| LambdaFieldElement::from(&x)) | ||
| } else { | ||
| UnsignedInteger::from_dec_str(value).map(|x| LambdaFieldElement::from(&x)) | ||
| }; | ||
|
|
||
| let lfe = match lfe { | ||
| Ok(v) => v, | ||
| Err(_) => { | ||
| return Err(Error::new_spanned( | ||
| lit_str, | ||
| "Invalid string literal for Felt conversion", | ||
| )); | ||
| } | ||
| }; | ||
|
|
||
| Ok(HandleExprOutput::ComptimeFelt(if is_neg { | ||
| lfe.neg() | ||
| } else { | ||
| lfe | ||
| })) | ||
| } | ||
|
|
||
| Lit::ByteStr(lit_byte_str) => { | ||
| let bytes = lit_byte_str.value(); | ||
|
|
||
| if bytes.len() > 31 { | ||
| return Err(Error::new_spanned( | ||
| lit_byte_str, | ||
| "Short string must be at most 31 characters", | ||
| )); | ||
| } | ||
|
|
||
| if !bytes.is_ascii() { | ||
| return Err(Error::new_spanned( | ||
| lit_byte_str, | ||
| "Short string must contain only ASCII characters", | ||
| )); | ||
| } | ||
|
|
||
| let mut buffer = [0u8; 32]; | ||
| buffer[(32 - bytes.len())..].copy_from_slice(&bytes); | ||
|
|
||
| match LambdaFieldElement::from_bytes_be(&buffer) { | ||
| Ok(field_element) => Ok(HandleExprOutput::ComptimeFelt(field_element)), | ||
| Err(_) => Err(Error::new_spanned( | ||
| lit_byte_str, | ||
| "Failed to convert byte string to Felt", | ||
| )), | ||
| } | ||
| } | ||
|
|
||
| Lit::Char(lit_char) => { | ||
| let char = lit_char.value(); | ||
|
|
||
| if !char.is_ascii() { | ||
| return Err(Error::new_spanned( | ||
| lit_char, | ||
| "Only ASCII characters are supported", | ||
| )); | ||
| } | ||
|
|
||
| let mut buffer = [0u8]; | ||
| char.encode_utf8(&mut buffer); | ||
|
|
||
| Ok(HandleExprOutput::ComptimeFelt(LambdaFieldElement::from( | ||
| &UnsignedInteger::from(u16::from(buffer[0])), | ||
| ))) | ||
| } | ||
|
|
||
| Lit::Byte(lit_byte) => { | ||
| let char = lit_byte.value(); | ||
|
|
||
| Ok(HandleExprOutput::ComptimeFelt(LambdaFieldElement::from( | ||
| &UnsignedInteger::from(u16::from(char)), | ||
| ))) | ||
| } | ||
|
|
||
| Lit::CStr(_) | Lit::Float(_) | Lit::Verbatim(_) => { | ||
| Err(Error::new_spanned(expr_lit, "Unsupported literal type")) | ||
| } | ||
|
|
||
| // `Lit` is a non-exhaustive enum | ||
| _ => Err(Error::new_spanned(expr_lit, "Unknown literal type")), | ||
| }, | ||
|
|
||
| // Negative (`-`) prefixed values | ||
| // Can be used before any other expression | ||
| Expr::Unary(ExprUnary { | ||
| attrs: _attrs, | ||
| op: syn::UnOp::Neg(_), | ||
| expr, | ||
| }) => match handle_expr(expr)? { | ||
| HandleExprOutput::ComptimeFelt(field_element) => { | ||
| Ok(HandleExprOutput::ComptimeFelt(field_element.neg())) | ||
| } | ||
| HandleExprOutput::Runtime => Ok(HandleExprOutput::Runtime), | ||
| }, | ||
|
|
||
| // Opposite (`!`) prefixed values | ||
| // Can only be used before literal bool expression and any runtime expression where it is semanticaly valid | ||
| Expr::Unary(ExprUnary { | ||
| attrs: _attrs, | ||
| op: syn::UnOp::Not(_), | ||
| expr, | ||
| }) => match &**expr { | ||
| Expr::Lit(ExprLit { | ||
| lit: Lit::Bool(lit_bool), | ||
| .. | ||
| }) => Ok(HandleExprOutput::ComptimeFelt(match lit_bool.value() { | ||
| false => LambdaFieldElement::from(&UnsignedInteger::from_u64(1)), | ||
| true => LambdaFieldElement::from(&UnsignedInteger::from_u64(0)), | ||
| })), | ||
| Expr::Lit(_) => Err(Error::new_spanned( | ||
| expr, | ||
| "The `!` logical inversion operator is only allowed before booleans in literal expressions", | ||
| )), | ||
| _ => Ok(HandleExprOutput::Runtime), | ||
| }, | ||
|
|
||
| _ => Ok(HandleExprOutput::Runtime), | ||
| } | ||
| } | ||
This file contains hidden or 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
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.