From 9946b863b4e8816a46b6186047dfb617acb4d96e Mon Sep 17 00:00:00 2001 From: chriseth Date: Tue, 28 Nov 2023 15:00:50 +0100 Subject: [PATCH] Remove macros. --- analysis/src/lib.rs | 19 +- analysis/src/macro_expansion.rs | 211 ----------------------- asm_to_pil/src/vm_to_constrained.rs | 2 - ast/src/parsed/display.rs | 13 -- ast/src/parsed/mod.rs | 7 - ast/src/parsed/visitor.rs | 2 - book/src/SUMMARY.md | 1 - book/src/pil/macros.md | 34 ---- compiler/tests/asm.rs | 8 - compiler/tests/pil.rs | 8 - executor/src/constant_evaluator/mod.rs | 26 +-- parser/src/lib.rs | 54 +----- parser/src/powdr.lalrpop | 6 - pil_analyzer/src/pil_analyzer.rs | 10 +- std/binary.asm | 5 +- std/shift.asm | 2 +- test_data/asm/macros_in_instructions.asm | 29 ---- test_data/pil/block_lookup_or.pil | 12 +- test_data/pil/fib_macro.pil | 36 ---- test_data/pil/global.pil | 9 +- test_data/pil/sum_via_witness_query.pil | 11 +- 21 files changed, 18 insertions(+), 487 deletions(-) delete mode 100644 analysis/src/macro_expansion.rs delete mode 100644 book/src/pil/macros.md delete mode 100644 test_data/asm/macros_in_instructions.asm delete mode 100644 test_data/pil/fib_macro.pil diff --git a/analysis/src/lib.rs b/analysis/src/lib.rs index 9de1633311..758ac3d1ad 100644 --- a/analysis/src/lib.rs +++ b/analysis/src/lib.rs @@ -1,12 +1,8 @@ #![deny(clippy::print_stdout)] mod block_enforcer; -mod macro_expansion; mod vm; -/// expose the macro expander for use in the pil_analyzer -pub use macro_expansion::MacroExpander; - use ast::{asm_analysis::AnalysisASMFile, parsed::asm::ASMProgram, DiffMonitor}; use number::FieldElement; @@ -22,9 +18,6 @@ pub fn analyze( file: ASMProgram, monitor: &mut DiffMonitor, ) -> Result, Vec> { - // expand macros - log::debug!("Run expand analysis step"); - let file = macro_expansion::expand(file); // type check log::debug!("Run type-check analysis step"); let file = type_check::check(file)?; @@ -68,20 +61,12 @@ pub mod utils { #[cfg(test)] mod test_util { - use ast::{asm_analysis::AnalysisASMFile, parsed::asm::ASMProgram}; + use ast::asm_analysis::AnalysisASMFile; use number::FieldElement; use parser::parse_asm; - use crate::macro_expansion; - - /// A test utility to process a source file until after macro expansion - pub fn expand_str(source: &str) -> ASMProgram { - let file = parse_asm(None, source).unwrap(); - macro_expansion::expand(file) - } - /// A test utility to process a source file until after type checking pub fn typecheck_str(source: &str) -> Result, Vec> { - type_check::check(expand_str(source)) + type_check::check(parse_asm(None, source).unwrap()) } } diff --git a/analysis/src/macro_expansion.rs b/analysis/src/macro_expansion.rs deleted file mode 100644 index e3404793ea..0000000000 --- a/analysis/src/macro_expansion.rs +++ /dev/null @@ -1,211 +0,0 @@ -use std::{ - collections::{HashMap, HashSet}, - convert::Infallible, -}; - -use ast::parsed::{ - asm::{ASMProgram, Instruction, InstructionBody, Machine, MachineStatement}, - folder::Folder, - visitor::ExpressionVisitable, - Expression, FunctionCall, FunctionDefinition, NamespacedPolynomialReference, PilStatement, -}; -use number::FieldElement; - -pub fn expand(program: ASMProgram) -> ASMProgram { - match MacroExpander::default().fold_program(program) { - Ok(p) => p, - Err(_) => unreachable!(), - } -} - -#[derive(Debug, Default)] -pub struct MacroExpander { - macros: HashMap>, - arguments: Vec>, - parameter_names: HashMap, - shadowing_locals: HashSet, - statements: Vec>, -} - -impl Folder for MacroExpander { - // macro expansion cannot fail - type Error = Infallible; - - fn fold_machine(&mut self, mut machine: Machine) -> Result, Self::Error> { - machine.statements = machine - .statements - .into_iter() - .flat_map(|s| match s { - MachineStatement::InstructionDeclaration( - start, - name, - Instruction { body, params }, - ) => { - let body = match body { - InstructionBody::Local(body) => { - InstructionBody::Local(self.expand_macros(body)) - } - // there is nothing to expand in a callable ref - InstructionBody::CallableRef(r) => InstructionBody::CallableRef(r), - }; - vec![MachineStatement::InstructionDeclaration( - start, - name, - Instruction { body, params }, - )] - } - MachineStatement::Pil(start, statement) => self - .expand_macros(vec![statement]) - .into_iter() - .map(|s| MachineStatement::Pil(start, s)) - .collect(), - s => { - vec![s] - } - }) - .collect(); - - Ok(machine) - } -} - -#[derive(Debug)] -struct MacroDefinition { - pub parameters: Vec, - pub identities: Vec>, - pub expression: Option>, -} - -impl MacroExpander -where - T: FieldElement, -{ - /// Expands all macro references inside the statements and also adds - /// any macros defined therein to the list of macros. - /// - /// Note that macros are not namespaced! - pub fn expand_macros(&mut self, statements: Vec>) -> Vec> { - assert!(self.statements.is_empty()); - for statement in statements { - self.handle_statement(statement); - } - std::mem::take(&mut self.statements) - } - - fn handle_statement(&mut self, mut statement: PilStatement) { - let mut added_locals = false; - if let PilStatement::PolynomialConstantDefinition(_, _, f) - | PilStatement::PolynomialCommitDeclaration(_, _, Some(f)) = &statement - { - if let FunctionDefinition::Query(params, _) = f { - assert!(self.shadowing_locals.is_empty()); - self.shadowing_locals.extend(params.iter().cloned()); - added_locals = true; - } - } - - match &mut statement { - PilStatement::Expression(_start, e) => match e { - Expression::FunctionCall(FunctionCall { - function, - arguments, - }) => { - let mac = self.find_macro(function).unwrap_or_else( - || panic!("Macro {} not found - only macros allowed at this point, no fixed columns.", function) - ); - let arguments = std::mem::take(arguments) - .into_iter() - .map(|mut a| { - self.process_expression(&mut a); - a - }) - .collect(); - let returned_expression = self.expand_macro(mac, arguments).is_some(); - assert!( - !returned_expression, - "Invoked a macro in statement context with non-empty expression." - ); - } - _ => panic!("Only function calls or identities allowed at PIL statement level."), - }, - PilStatement::MacroDefinition(_start, name, parameters, statements, expression) => { - // We expand lazily. Is that a mistake? - let is_new = self - .macros - .insert( - std::mem::take(name), - MacroDefinition { - parameters: std::mem::take(parameters), - identities: std::mem::take(statements), - expression: std::mem::take(expression), - }, - ) - .is_none(); - assert!(is_new); - } - _ => { - statement.post_visit_expressions_mut(&mut |e| self.process_expression(e)); - self.statements.push(statement); - } - }; - - if added_locals { - self.shadowing_locals.clear(); - } - } - - fn find_macro<'a>(&self, name: &'a Expression) -> Option<&'a str> { - if let Expression::Reference(NamespacedPolynomialReference { - namespace: None, - name, - }) = name - { - if !self.shadowing_locals.contains(name.as_str()) - && self.macros.contains_key(name.as_str()) - { - return Some(name.as_str()); - } - } - None - } - - fn expand_macro(&mut self, name: &str, arguments: Vec>) -> Option> { - let old_arguments = std::mem::replace(&mut self.arguments, arguments); - - let mac = self.macros.get(name).unwrap(); - let parameters = mac - .parameters - .iter() - .enumerate() - .map(|(i, n)| (n.clone(), i)) - .collect(); - let old_parameters = std::mem::replace(&mut self.parameter_names, parameters); - - let mut expression = mac.expression.clone(); - let identities = mac.identities.clone(); - for identity in identities { - self.handle_statement(identity) - } - if let Some(e) = &mut expression { - e.post_visit_expressions_mut(&mut |e| self.process_expression(e)); - }; - - self.arguments = old_arguments; - self.parameter_names = old_parameters; - expression - } - - fn process_expression(&mut self, e: &mut Expression) { - if let Expression::Reference(poly) = e { - if poly.namespace.is_none() && self.parameter_names.contains_key(&poly.name) { - *e = self.arguments[self.parameter_names[&poly.name]].clone() - } - } else if let Expression::FunctionCall(call) = e { - if let Some(mac) = self.find_macro(&call.function) { - *e = self - .expand_macro(mac, std::mem::take(&mut call.arguments)) - .expect("Invoked a macro in expression context with empty expression.") - } - } - } -} diff --git a/asm_to_pil/src/vm_to_constrained.rs b/asm_to_pil/src/vm_to_constrained.rs index 731e83b5f6..501fc5cddc 100644 --- a/asm_to_pil/src/vm_to_constrained.rs +++ b/asm_to_pil/src/vm_to_constrained.rs @@ -357,8 +357,6 @@ impl ASMPILConverter { let instruction = Instruction { inputs, outputs }; - // First transform into PIL so that we can apply macro expansion. - let res = match s.instruction.body { InstructionBody::Local(mut body) => { // Substitute parameter references by the column names diff --git a/ast/src/parsed/display.rs b/ast/src/parsed/display.rs index 823c75380e..41515c9480 100644 --- a/ast/src/parsed/display.rs +++ b/ast/src/parsed/display.rs @@ -387,19 +387,6 @@ impl Display for PilStatement { PilStatement::ConstantDefinition(_, name, value) => { write!(f, "constant {name} = {value};") } - PilStatement::MacroDefinition(_, name, params, statements, expression) => { - let statements = statements - .iter() - .map(|s| format!("{s}")) - .chain(expression.iter().map(|e| format!("{e}"))) - .collect::>(); - let body = if statements.len() <= 1 { - format!(" {} ", statements.join("")) - } else { - format!("\n {}\n", statements.join("\n ")) - }; - write!(f, "macro {name}({}) {{{body}}};", params.join(", ")) - } PilStatement::Expression(_, e) => { write!(f, "{e};") } diff --git a/ast/src/parsed/mod.rs b/ast/src/parsed/mod.rs index 74bb27b4a0..402ac75dda 100644 --- a/ast/src/parsed/mod.rs +++ b/ast/src/parsed/mod.rs @@ -47,13 +47,6 @@ pub enum PilStatement { ), ConnectIdentity(usize, Vec>, Vec>), ConstantDefinition(usize, String, Expression), - MacroDefinition( - usize, - String, - Vec, - Vec>, - Option>, - ), Expression(usize, Expression), } diff --git a/ast/src/parsed/visitor.rs b/ast/src/parsed/visitor.rs index e27824c9ee..242565413a 100644 --- a/ast/src/parsed/visitor.rs +++ b/ast/src/parsed/visitor.rs @@ -217,7 +217,6 @@ impl ExpressionVisitable> for Pi PilStatement::PolynomialCommitDeclaration(_, _, None) | PilStatement::Include(_, _) | PilStatement::PolynomialConstantDeclaration(_, _) - | PilStatement::MacroDefinition(_, _, _, _, _) | PilStatement::LetStatement(_, _, None) => ControlFlow::Continue(()), } } @@ -255,7 +254,6 @@ impl ExpressionVisitable> for Pi PilStatement::PolynomialCommitDeclaration(_, _, None) | PilStatement::Include(_, _) | PilStatement::PolynomialConstantDeclaration(_, _) - | PilStatement::MacroDefinition(_, _, _, _, _) | PilStatement::LetStatement(_, _, None) => ControlFlow::Continue(()), } } diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 4844a5c942..248c8e50a6 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -20,7 +20,6 @@ - [Links](./asm/links.md) - [pil](./pil/README.md) - [Fixed Columns](./pil/fixed_columns.md) - - [Macros](./pil/macros.md) - [Frontends](./frontends/README.md) - [RISCV](./frontends/riscv.md) - [Valida](./frontends/valida.md) diff --git a/book/src/pil/macros.md b/book/src/pil/macros.md deleted file mode 100644 index 56c06b02e8..0000000000 --- a/book/src/pil/macros.md +++ /dev/null @@ -1,34 +0,0 @@ -# Macros - -powdr-pil exposes a macro system which can generate arbitrary powdr-pil code. - -## Definition - -Let's define some macros which generate powdr-pil expressions: - -``` -{{#include ../../../test_data/pil/fib_macro.pil:expression_macro_definitions}} -``` - -In particular, we can generate constraints inside macros: - -``` -{{#include ../../../test_data/pil/fib_macro.pil:constraint_macro_definitions}} -``` - -## Usage - -> Macros currently have global scope - -Usage of the defined macros happens as expected in powdr-pil code: - -``` -{{#include ../../../test_data/pil/fib_macro.pil:expression_macro_usage}} -``` - -Generating constraints: - -``` -{{#include ../../../test_data/pil/fib_macro.pil:constraint_macro_usage}} -``` - diff --git a/compiler/tests/asm.rs b/compiler/tests/asm.rs index 8cd6205e06..be88a5921e 100644 --- a/compiler/tests/asm.rs +++ b/compiler/tests/asm.rs @@ -350,11 +350,3 @@ fn hello_world_asm_fail() { let i = [1]; verify_asm::(f, slice_to_vec(&i)); } - -#[test] -fn test_macros_in_instructions() { - let f = "macros_in_instructions.asm"; - verify_asm::(f, Default::default()); - gen_halo2_proof(f, Default::default()); - gen_estark_proof(f, Default::default()); -} diff --git a/compiler/tests/pil.rs b/compiler/tests/pil.rs index 12facf314c..3aaee10e6f 100644 --- a/compiler/tests/pil.rs +++ b/compiler/tests/pil.rs @@ -91,14 +91,6 @@ fn test_constant_in_identity() { gen_estark_proof(f, Default::default()); } -#[test] -fn test_fibonacci_macro() { - let f = "fib_macro.pil"; - verify_pil(f, None); - gen_halo2_proof(f, Default::default()); - gen_estark_proof(f, Default::default()); -} - #[test] fn fib_arrays() { let f = "fib_arrays.pil"; diff --git a/executor/src/constant_evaluator/mod.rs b/executor/src/constant_evaluator/mod.rs index 5d40cc770f..e58845ffbc 100644 --- a/executor/src/constant_evaluator/mod.rs +++ b/executor/src/constant_evaluator/mod.rs @@ -232,7 +232,7 @@ mod test { let src = r#" constant %N = 8; namespace F(%N); - macro minus_one(X) { X - 1 }; + let minus_one = [|x| x - 1][0]; pol constant EVEN(i) { 2 * minus_one(i) }; "#; let analyzed = analyze_string(src); @@ -244,30 +244,6 @@ mod test { ); } - #[test] - pub fn test_macro_double() { - let src = r#" - constant %N = 12; - namespace F(%N); - macro is_nonzero(X) { match X { 0 => 0, _ => 1, } }; - macro is_zero(X) { 1 - is_nonzero(X) }; - macro is_one(X) { is_zero(1 - X) }; - macro is_equal(A, B) { is_zero(A - B) }; - macro ite(C, T, F) { is_one(C) * T + is_zero(C) * F }; - pol constant TEN(i) { ite(is_equal(i, 10), 1, 0) }; - "#; - let analyzed = analyze_string(src); - assert_eq!(analyzed.degree(), 12); - let constants = generate(&analyzed); - assert_eq!( - constants, - vec![( - "F.TEN", - convert([[0; 10].to_vec(), [1, 0].to_vec()].concat()) - )] - ); - } - #[test] pub fn test_poly_call() { let src = r#" diff --git a/parser/src/lib.rs b/parser/src/lib.rs index 6bcef78770..311ab1f2c6 100644 --- a/parser/src/lib.rs +++ b/parser/src/lib.rs @@ -43,8 +43,7 @@ pub fn parse_module<'a, T: FieldElement>( mod test { use super::*; use ast::parsed::{ - build::direct_reference, BinaryOperator, Expression, PILFile, PilStatement, PolynomialName, - SelectedExpressions, + build::direct_reference, PILFile, PilStatement, PolynomialName, SelectedExpressions, }; use number::GoldilocksField; use parser_util::UnwrapErrToStderr; @@ -151,37 +150,6 @@ mod test { parse_file("polygon-hermez/storage.pil"); } - #[test] - fn simple_macro() { - let parsed = powdr::PILFileParser::new() - .parse::("macro f(x) { x in g; x + 1 };") - .unwrap(); - assert_eq!( - parsed, - PILFile(vec![PilStatement::MacroDefinition( - 0, - "f".to_string(), - vec!["x".to_string()], - vec![PilStatement::PlookupIdentity( - 13, - SelectedExpressions { - selector: None, - expressions: vec![direct_reference("x")] - }, - SelectedExpressions { - selector: None, - expressions: vec![direct_reference("g")] - } - )], - Some(Expression::BinaryOperation( - Box::new(direct_reference("x")), - BinaryOperator::Add, - Box::new(Expression::Number(1.into())) - )) - )]) - ); - } - #[test] fn parse_example_asm_files() { parse_asm_file("asm/simple_sum.asm"); @@ -201,22 +169,14 @@ mod test { constant %N = 16; namespace Fibonacci(%N); constant %last_row = (%N - 1); -macro bool(X) { (X * (1 - X)) = 0; }; -macro is_nonzero(X) { match X { 0 => 0, _ => 1, } }; -macro is_zero(X) { (1 - is_nonzero(X)) }; -macro is_equal(A, B) { is_zero((A - B)) }; -macro is_one(X) { is_equal(X, 1) }; -macro ite(C, A, B) { ((is_nonzero(C) * A) + (is_zero(C) * B)) }; -macro one_hot(i, index) { ite(is_equal(i, index), 1, 0) }; +let bool = [|X| (X * (1 - X))][0]; +let one_hot = |i, which| match i { which => 1, _ => 0, }; pol constant ISLAST(i) { one_hot(i, %last_row) }; +pol commit arr[8]; pol commit x, y; -macro constrain_equal_expr(A, B) { (A - B) }; -macro force_equal_on_last_row(poly, value) { (ISLAST * constrain_equal_expr(poly, value)) = 0; }; -force_equal_on_last_row(x', 1); -force_equal_on_last_row(y', 1); -macro on_regular_row(cond) { ((1 - ISLAST) * cond) = 0; }; -on_regular_row(constrain_equal_expr(x', y)); -on_regular_row(constrain_equal_expr(y', (x + y))); +{ (x + 2), y' } in { ISLAST, 7 }; +y { (x + 2), y' } is ISLAST { ISLAST, 7 }; +((x - 2) * y) = 8; public out = y(%last_row);"#; let printed = format!( "{}", diff --git a/parser/src/powdr.lalrpop b/parser/src/powdr.lalrpop index 67be4b510b..45a776820b 100644 --- a/parser/src/powdr.lalrpop +++ b/parser/src/powdr.lalrpop @@ -61,7 +61,6 @@ pub PilStatement = { PlookupIdentity, PermutationIdentity, ConnectIdentity, - MacroDefinition, ExpressionStatement, }; @@ -156,11 +155,6 @@ ConnectIdentity: PilStatement = { <@L> "{" "}" "connect" "{" "}" => PilStatement::ConnectIdentity(<>) } -MacroDefinition: PilStatement = { - <@L> "macro" "(" ")" "{" <( ";")*> "}" - => PilStatement::MacroDefinition(<>) -} - ExpressionStatement: PilStatement = { <@L> => PilStatement::Expression(<>) } diff --git a/pil_analyzer/src/pil_analyzer.rs b/pil_analyzer/src/pil_analyzer.rs index d118359ba7..64668e0fc0 100644 --- a/pil_analyzer/src/pil_analyzer.rs +++ b/pil_analyzer/src/pil_analyzer.rs @@ -2,8 +2,6 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; -use analysis::MacroExpander; - use ast::parsed::{ self, FunctionDefinition, LambdaExpression, PilStatement, PolynomialName, SelectedExpressions, }; @@ -45,7 +43,6 @@ struct PILAnalyzer { current_file: PathBuf, symbol_counters: BTreeMap, identity_counter: HashMap, - macro_expander: MacroExpander, } impl PILAnalyzer { @@ -94,9 +91,7 @@ impl PILAnalyzer { }); for statement in pil_file.0 { - for statement in self.macro_expander.expand_macros(vec![statement]) { - self.handle_statement(statement); - } + self.handle_statement(statement); } self.current_file = old_current_file; @@ -182,9 +177,6 @@ impl PILAnalyzer { PilStatement::LetStatement(start, name, value) => { self.handle_generic_definition(start, name, value) } - PilStatement::MacroDefinition(_, _, _, _, _) => { - panic!("Macros should have been eliminated."); - } _ => { self.handle_identity_statement(statement); } diff --git a/std/binary.asm b/std/binary.asm index 4274d38ffe..d24be32d1b 100644 --- a/std/binary.asm +++ b/std/binary.asm @@ -10,10 +10,7 @@ machine Binary(latch, operation_id) { col witness operation_id; - macro is_nonzero(X) { match X { 0 => 0, _ => 1, } }; - macro is_zero(X) { 1 - is_nonzero(X) }; - - col fixed latch(i) { is_zero((i % 4) - 3) }; + col fixed latch(i) { (i % 4) == 3 }; col fixed FACTOR(i) { 1 << (((i + 1) % 4) * 8) }; col fixed P_A(i) { i % 256 }; diff --git a/std/shift.asm b/std/shift.asm index cf3094aa76..68efa4db35 100644 --- a/std/shift.asm +++ b/std/shift.asm @@ -7,7 +7,7 @@ machine Shift(latch, operation_id) { col witness operation_id; - col fixed latch(i) { is_zero((i % 4) - 3) }; + col fixed latch(i) { (i % 4) == 3 }; col fixed FACTOR_ROW(i) { (i + 1) % 4 }; col fixed FACTOR(i) { 1 << (((i + 1) % 4) * 8) }; diff --git a/test_data/asm/macros_in_instructions.asm b/test_data/asm/macros_in_instructions.asm deleted file mode 100644 index d48b57030d..0000000000 --- a/test_data/asm/macros_in_instructions.asm +++ /dev/null @@ -1,29 +0,0 @@ -machine MacroAsm { - reg pc[@pc]; - reg X[<=]; - reg Y[<=]; - reg A; - - macro branch_if(condition, target) { - pc' = condition * target + (1 - condition) * (pc + 1); - }; - - col witness XInv; - col witness XIsZero; - XIsZero = 1 - X * XInv; - XIsZero * X = 0; - XIsZero * (1 - XIsZero) = 0; - - instr bz X, target: label { branch_if(XIsZero, target) } - instr fail { X = X + 1 } - instr assert_zero X { XIsZero = 1 } - - function main { - A <=X= 0; - bz A, is_zero; - fail; - is_zero:: - assert_zero A; - return; - } -} \ No newline at end of file diff --git a/test_data/pil/block_lookup_or.pil b/test_data/pil/block_lookup_or.pil index 8789c9377a..cd0b0056f6 100644 --- a/test_data/pil/block_lookup_or.pil +++ b/test_data/pil/block_lookup_or.pil @@ -2,15 +2,7 @@ constant %N = 65536; // ORs two 32-bit numbers, byte-by-byte. namespace Or(%N); - macro is_nonzero(X) { - match X { - 0 => 0, - _ => 1, - } - }; - macro is_zero(X) { 1 - is_nonzero(X) }; - - col fixed RESET(i) { is_zero((i % 4) - 3) }; + col fixed RESET(i) { (i % 4) == 3 }; col fixed FACTOR(i) { 1 << (((i + 1) % 4) * 8) }; col fixed P_A(i) { i % 256 }; @@ -41,7 +33,7 @@ namespace Main(%N); col fixed a(i) { (i + 13) & 0xffffffff }; col fixed b(i) { ((i + 19) * 17) & 0xffffffff }; col witness c; - col fixed NTH(i) { is_zero(i % 32) }; + col fixed NTH(i) { i % 32 == 0 }; NTH {a, b, c} in Or.RESET {Or.A, Or.B, Or.C}; diff --git a/test_data/pil/fib_macro.pil b/test_data/pil/fib_macro.pil deleted file mode 100644 index 35aa4a71ef..0000000000 --- a/test_data/pil/fib_macro.pil +++ /dev/null @@ -1,36 +0,0 @@ -constant %N = 16; - -namespace Fibonacci(%N); - constant %last_row = %N - 1; - - macro bool(X) { X * (1 - X) = 0; }; -// ANCHOR: expression_macro_definitions -macro is_nonzero(X) { match X { 0 => 0, _ => 1, } }; -macro is_zero(X) { 1 - is_nonzero(X) }; -macro is_equal(A, B) { is_zero(A - B) }; -macro is_one(X) { is_equal(X, 1) }; -macro ite(C, A, B) { is_nonzero(C) * A + is_zero(C) * B}; -macro one_hot(i, index) { ite(is_equal(i, index), 1, 0) }; -// ANCHOR_END: expression_macro_definitions - -// ANCHOR: expression_macro_usage -pol constant ISLAST(i) { one_hot(i, %last_row) }; -// ANCHOR_END: expression_macro_usage - pol commit x, y; - -// ANCHOR: constraint_macro_definitions -macro constrain_equal_expr(A, B) { A - B }; -macro force_equal_on_first_row(poly, value) { ISLAST * constrain_equal_expr(poly', value) = 0; }; -// ANCHOR_END: constraint_macro_definitions - -// ANCHOR: constraint_macro_usage -force_equal_on_first_row(x, 1); -// ANCHOR_END: constraint_macro_usage - force_equal_on_first_row(y, 1); - - macro on_regular_row(cond) { (1 - ISLAST) * cond = 0; }; - - on_regular_row(constrain_equal_expr(x', y)); - on_regular_row(constrain_equal_expr(y', x + y)); - - public out = y(%last_row); diff --git a/test_data/pil/global.pil b/test_data/pil/global.pil index 7be2026bee..936590bbd1 100644 --- a/test_data/pil/global.pil +++ b/test_data/pil/global.pil @@ -9,15 +9,8 @@ constant %N = 2**20; namespace Global(%N); - macro is_nonzero(X) { match X { 0 => 0, _ => 1, } }; - macro is_zero(X) { 1 - is_nonzero(X) }; - macro is_equal(A, B) { is_zero(A - B) }; - macro is_one(X) { is_equal(X, 1) }; - macro ite(C, A, B) { is_nonzero(C) * A + is_zero(C) * B}; - macro one_hot(i, index) { ite(is_equal(i, index), 1, 0) }; - col fixed L1 = [1] + [0]*; - col fixed LLAST(i) { one_hot(i, %N - 1) }; + col fixed LLAST(i) { i == %N - 1 }; col fixed BYTE(i) { i & 0xff }; col fixed BYTE2(i) { i & 0xffff }; col fixed BYTE_2A(i) { BYTE2(i) >> 8 }; diff --git a/test_data/pil/sum_via_witness_query.pil b/test_data/pil/sum_via_witness_query.pil index 84c6d1f54e..fddd527bd4 100644 --- a/test_data/pil/sum_via_witness_query.pil +++ b/test_data/pil/sum_via_witness_query.pil @@ -3,15 +3,8 @@ constant %N = 4; namespace Sum(%N); constant %last_row = %N - 1; - macro is_nonzero(X) { match X { 0 => 0, _ => 1, } }; - macro is_zero(X) { 1 - is_nonzero(X) }; - macro is_equal(A, B) { is_zero(A - B) }; - macro ite(C, A, B) { is_nonzero(C) * A + is_zero(C) * B}; - - macro one_hot(i, index) { is_equal(i, index) }; - - pol fixed ISLAST(i) { one_hot(i, %last_row) }; - pol fixed ISALMOSTLAST(i) { one_hot(i, %last_row - 1) }; + pol fixed ISLAST(i) { i == %last_row }; + pol fixed ISALMOSTLAST(i) { i == %last_row - 1 }; pol fixed ISFIRST = [ 1, 0 ] + [0]*; col witness input(i) query ("in", i);