Replace String by str.

This commit is contained in:
chriseth
2023-03-08 13:56:52 +01:00
parent 4e7966c9cf
commit 517f16f00a
13 changed files with 78 additions and 83 deletions

View File

@@ -284,7 +284,7 @@ impl PILContext {
fn handle_polynomial_definition(
&mut self,
source: SourceRef,
name: &String,
name: &str,
array_size: &Option<ast::Expression>,
polynomial_type: PolynomialType,
value: Option<&ast::FunctionDefinition>,
@@ -396,7 +396,7 @@ impl PILContext {
fn handle_macro_definition(
&mut self,
source: SourceRef,
name: &String,
name: &str,
params: &[String],
statements: &[ast::Statement],
expression: &Option<ast::Expression>,
@@ -404,7 +404,7 @@ impl PILContext {
let is_new = self
.macros
.insert(
name.clone(),
name.to_string(),
MacroDefinition {
source,
absolute_name: self.namespaced(name),
@@ -417,11 +417,11 @@ impl PILContext {
assert!(is_new);
}
fn namespaced(&self, name: &String) -> String {
fn namespaced(&self, name: &str) -> String {
self.namespaced_ref(&None, name)
}
fn namespaced_ref(&self, namespace: &Option<String>, name: &String) -> String {
fn namespaced_ref(&self, namespace: &Option<String>, name: &str) -> String {
format!("{}.{name}", namespace.as_ref().unwrap_or(&self.namespace))
}
@@ -493,7 +493,7 @@ impl PILContext {
fn process_macro_call(
&mut self,
name: &String,
name: &str,
arguments: &[ast::Expression],
) -> Option<Expression> {
let arguments = Some(self.process_expressions(arguments));

View File

@@ -102,7 +102,7 @@ impl ASMPILConverter {
fn handle_register_declaration(
&mut self,
flags: &Option<RegisterFlag>,
name: &String,
name: &str,
start: &usize,
) {
let mut conditioned_updates = vec![];
@@ -110,8 +110,9 @@ impl ASMPILConverter {
match flags {
Some(RegisterFlag::IsPC) => {
assert_eq!(self.pc_name, None);
self.pc_name = Some(name.clone());
self.line_lookup.push((name.clone(), "line".to_string()));
self.pc_name = Some(name.to_string());
self.line_lookup
.push((name.to_string(), "line".to_string()));
// This might be superfluous but makes it easier to determine that the PC needs to
// be zero in the first row.
self.pil.push(Statement::PolynomialIdentity(
@@ -125,7 +126,7 @@ impl ASMPILConverter {
}
Some(RegisterFlag::IsDefaultAssignment) => {
assert_eq!(self.default_assignment, None);
self.default_assignment = Some(name.clone());
self.default_assignment = Some(name.to_string());
}
None => {
let write_flag = format!("reg_write_{name}");
@@ -149,7 +150,7 @@ impl ASMPILConverter {
}
};
self.registers.insert(
name.clone(),
name.to_string(),
Register {
conditioned_updates,
default_update,
@@ -162,7 +163,7 @@ impl ASMPILConverter {
&mut self,
start: &usize,
body: &Vec<InstructionBodyElement>,
name: &String,
name: &str,
params: &Vec<InstructionParam>,
) {
let instruction_flag = format!("instr_{name}");
@@ -220,7 +221,7 @@ impl ASMPILConverter {
let instr = Instruction {
params: params.clone(),
};
self.instructions.insert(name.clone(), instr);
self.instructions.insert(name.to_string(), instr);
}
fn handle_assignment(
@@ -240,7 +241,7 @@ impl ASMPILConverter {
})
}
fn handle_instruction(&mut self, instr_name: &String, args: &Vec<Expression>) {
fn handle_instruction(&mut self, instr_name: &str, args: &Vec<Expression>) {
let instr = &self.instructions[instr_name];
assert_eq!(instr.params.len(), args.len());
let mut value = vec![];
@@ -280,7 +281,7 @@ impl ASMPILConverter {
assert_eq!(instruction_literal_args.len(), instr.params.len());
self.code_lines.push(CodeLine {
write_reg,
instruction: Some(instr_name.clone()),
instruction: Some(instr_name.to_string()),
value,
instruction_literal_args,
..Default::default()
@@ -680,8 +681,11 @@ fn substitute_vec(input: &[Expression], substitution: &HashMap<String, String>)
input.iter().map(|e| substitute(e, substitution)).collect()
}
fn substitute_string(input: &String, substitution: &HashMap<String, String>) -> String {
substitution.get(input).unwrap_or(input).clone()
fn substitute_string(input: &str, substitution: &HashMap<String, String>) -> String {
substitution
.get(input)
.cloned()
.unwrap_or_else(|| input.to_string())
}
#[cfg(test)]

View File

@@ -100,7 +100,7 @@ impl AffineExpression {
.map(|(i, c)| {
let name = namer.name(i);
if *c == 1.into() {
name.clone()
name.to_string()
} else if *c == (-1).into() {
format!("-{name}")
} else {

View File

@@ -20,7 +20,7 @@ where
machines: Vec<Box<dyn Machine>>,
query_callback: Option<QueryCallback>,
/// Maps the witness polynomial names to optional parameter and query string.
witness_cols: BTreeMap<&'a String, &'a WitnessColumn<'a>>,
witness_cols: BTreeMap<&'a str, &'a WitnessColumn<'a>>,
/// Values of the witness polynomials
current: Vec<Option<AbstractNumberType>>,
/// Values of the witness polynomials in the next row
@@ -126,7 +126,7 @@ where
.iter()
.enumerate()
.filter_map(|(i, v)| if v.is_none() {
Some(self.fixed_data.witness_cols[i].name.clone())
Some(self.fixed_data.witness_cols[i].name.to_string())
} else {
None
})
@@ -322,7 +322,8 @@ where
let rhs_row = if let Expression::PolynomialReference(poly) = right_key {
// TODO we really need a search index on this.
self.fixed_data.fixed_cols
.get(&poly.name)
.get(poly.name.as_str())
.cloned()
.and_then(|values| values.iter().position(|v| *v == left_key))
.ok_or_else(|| {
format!(
@@ -425,7 +426,7 @@ where
fn contains_next_ref(&self, expr: &Expression) -> bool {
match expr {
Expression::PolynomialReference(poly) => {
poly.next && self.witness_cols.contains_key(&poly.name)
poly.next && self.witness_cols.contains_key(poly.name.as_str())
}
Expression::Tuple(items) => items.iter().any(|e| self.contains_next_ref(e)),
Expression::BinaryOperation(l, _, r) => {
@@ -453,11 +454,11 @@ struct EvaluationData<'a> {
}
impl<'a> SymbolicVariables for EvaluationData<'a> {
fn constant(&self, name: &String) -> Result<AffineExpression, EvalError> {
fn constant(&self, name: &str) -> Result<AffineExpression, EvalError> {
Ok(self.fixed_data.constants[name].clone().into())
}
fn value(&self, name: &String, next: bool) -> Result<AffineExpression, EvalError> {
fn value(&self, name: &str, next: bool) -> Result<AffineExpression, EvalError> {
// TODO arrays
if let Some(id) = self.fixed_data.witness_ids.get(name) {
// TODO we could also work with both p and p' as symoblic variables and only eliminate them at the end.

View File

@@ -6,9 +6,9 @@ use super::eval_error::{self, EvalError};
pub trait SymbolicVariables {
/// Acutal constant, not fixed polynomial
fn constant(&self, name: &String) -> Result<AffineExpression, EvalError>;
fn constant(&self, name: &str) -> Result<AffineExpression, EvalError>;
/// Value of a polynomial (fixed or witness).
fn value(&self, name: &String, next: bool) -> Result<AffineExpression, EvalError>;
fn value(&self, name: &str, next: bool) -> Result<AffineExpression, EvalError>;
fn format(&self, expr: AffineExpression) -> String;
}

View File

@@ -13,7 +13,7 @@ pub trait Machine {
// fn try_new(
// fixed_data: &'a FixedData<'a>,
// identities: Vec<&'a Identity>,
// witness_names: HashSet<&'a String>,
// witness_names: HashSet<&'a str>,
// ) -> Option<Box<Self>>;
/// Process o plookup. Not all values on the LHS need to be available.

View File

@@ -52,18 +52,18 @@ pub fn split_out_machines<'a>(
/// Extracts all references to any of the given names
/// in expressions and identities.
struct ReferenceExtractor<'a> {
names: HashSet<&'a String>,
names: HashSet<&'a str>,
}
impl<'a> ReferenceExtractor<'a> {
pub fn new(names: HashSet<&'a String>) -> Self {
pub fn new(names: HashSet<&'a str>) -> Self {
ReferenceExtractor { names }
}
pub fn in_identity(&self, identity: &'a Identity) -> HashSet<&'a String> {
pub fn in_identity(&self, identity: &'a Identity) -> HashSet<&'a str> {
&self.in_selected_expressions(&identity.left)
| &self.in_selected_expressions(&identity.right)
}
pub fn in_selected_expressions(&self, selexpr: &'a SelectedExpressions) -> HashSet<&'a String> {
pub fn in_selected_expressions(&self, selexpr: &'a SelectedExpressions) -> HashSet<&'a str> {
selexpr
.expressions
.iter()
@@ -72,12 +72,12 @@ impl<'a> ReferenceExtractor<'a> {
.reduce(|l, r| &l | &r)
.unwrap_or_default()
}
pub fn in_expression(&self, expr: &'a Expression) -> HashSet<&'a String> {
pub fn in_expression(&self, expr: &'a Expression) -> HashSet<&'a str> {
match expr {
Expression::Constant(_) => todo!(),
Expression::PolynomialReference(p) => {
if self.names.contains(&p.name) {
[&p.name].into()
if self.names.contains(p.name.as_str()) {
[p.name.as_str()].into()
} else {
HashSet::default()
}
@@ -92,7 +92,7 @@ impl<'a> ReferenceExtractor<'a> {
| Expression::String(_) => HashSet::default(),
}
}
pub fn in_expressions(&self, exprs: &'a [Expression]) -> HashSet<&'a String> {
pub fn in_expressions(&self, exprs: &'a [Expression]) -> HashSet<&'a str> {
exprs
.iter()
.map(|e| self.in_expression(e))

View File

@@ -20,10 +20,10 @@ mod util;
pub fn generate<'a>(
analyzed: &'a Analyzed,
degree: DegreeType,
fixed_cols: &[(&String, Vec<AbstractNumberType>)],
fixed_cols: &[(&str, Vec<AbstractNumberType>)],
query_callback: Option<impl FnMut(&str) -> Option<AbstractNumberType>>,
verbose: bool,
) -> Vec<(&'a String, Vec<AbstractNumberType>)> {
) -> Vec<(&'a str, Vec<AbstractNumberType>)> {
let witness_cols: Vec<WitnessColumn> = analyzed
.committed_polys_in_source_order()
.iter()
@@ -47,7 +47,7 @@ pub fn generate<'a>(
machine_extractor::split_out_machines(&fixed, &analyzed.identities, &witness_cols);
let mut evaluator = evaluator::Evaluator::new(&fixed, identities, machines, query_callback);
let mut values: Vec<(&String, Vec<AbstractNumberType>)> =
let mut values: Vec<(&str, Vec<AbstractNumberType>)> =
witness_cols.iter().map(|p| (p.name, Vec::new())).collect();
for row in 0..degree as DegreeType {
let row_values = evaluator.compute_next_row(row);
@@ -62,7 +62,7 @@ pub fn generate<'a>(
}
}
for (name, data) in evaluator.machine_witness_col_values() {
let (_, col) = values.iter_mut().find(|(n, _)| *n == &name).unwrap();
let (_, col) = values.iter_mut().find(|(n, _)| *n == name).unwrap();
*col = data;
}
values
@@ -76,9 +76,9 @@ type EvalResult = Result<Vec<(usize, AbstractNumberType)>, EvalError>;
pub struct FixedData<'a> {
degree: DegreeType,
constants: &'a HashMap<String, AbstractNumberType>,
fixed_cols: HashMap<&'a String, &'a Vec<AbstractNumberType>>,
fixed_cols: HashMap<&'a str, &'a Vec<AbstractNumberType>>,
witness_cols: &'a Vec<WitnessColumn<'a>>,
witness_ids: HashMap<&'a String, usize>,
witness_ids: HashMap<&'a str, usize>,
verbose: bool,
}
@@ -86,9 +86,9 @@ impl<'a> FixedData<'a> {
pub fn new(
degree: DegreeType,
constants: &'a HashMap<String, AbstractNumberType>,
fixed_cols: HashMap<&'a String, &'a Vec<AbstractNumberType>>,
fixed_cols: HashMap<&'a str, &'a Vec<AbstractNumberType>>,
witness_cols: &'a Vec<WitnessColumn<'a>>,
witness_ids: HashMap<&'a String, usize>,
witness_ids: HashMap<&'a str, usize>,
verbose: bool,
) -> Self {
FixedData {
@@ -103,21 +103,21 @@ impl<'a> FixedData<'a> {
}
impl<'a> WitnessColumnNamer for FixedData<'a> {
fn name(&self, i: usize) -> &String {
fn name(&self, i: usize) -> &str {
self.witness_cols[i].name
}
}
pub struct WitnessColumn<'a> {
id: usize,
name: &'a String,
name: &'a str,
query: Option<&'a Expression>,
}
impl<'a> WitnessColumn<'a> {
pub fn new(
id: usize,
name: &'a String,
name: &'a str,
value: &'a Option<FunctionValueDefinition>,
) -> WitnessColumn<'a> {
let query = if let Some(FunctionValueDefinition::Query(query)) = value {

View File

@@ -13,7 +13,7 @@ pub struct SortedWitnesses {
_identities: Vec<Identity>,
/// Maps the witness polynomial names to their IDs internal to this component
/// and optional parameter and query string.
//witness_cols: BTreeMap<&'a String, &'a WitnessColumn<'a>>,
//witness_cols: BTreeMap<&'a str, &'a WitnessColumn<'a>>,
witness_names: HashSet<String>,
// TODO this is specific to the sorted write-once memory machine.
@@ -24,7 +24,7 @@ impl SortedWitnesses {
pub fn try_new(
_fixed_data: &FixedData,
identities: &[&Identity],
witness_names: &HashSet<&String>,
witness_names: &HashSet<&str>,
) -> Option<Box<Self>> {
// TODO we should check the identities and select certain machines
// based on patterns (and just return an object that implements a trait).
@@ -33,7 +33,7 @@ impl SortedWitnesses {
Some(Box::new(SortedWitnesses {
_identities: identities.iter().map(|&i| i.clone()).collect(),
witness_names: witness_names.iter().map(|&w| w.clone()).collect(),
witness_names: witness_names.iter().map(|&w| w.to_string()).collect(),
data: Default::default(),
}))
}

View File

@@ -1,3 +1,3 @@
pub trait WitnessColumnNamer {
fn name(&self, i: usize) -> &String;
fn name(&self, i: usize) -> &str;
}

View File

@@ -141,7 +141,7 @@ fn compile(
fn write_polys_file(
file: &mut impl Write,
degree: DegreeType,
polys: &Vec<(&String, Vec<AbstractNumberType>)>,
polys: &Vec<(&str, Vec<AbstractNumberType>)>,
) {
for i in 0..degree as usize {
for (_name, constant) in polys {

View File

@@ -8,7 +8,7 @@ use crate::number::{abstract_to_degree, AbstractNumberType, DegreeType};
/// Generates the constant polynomial values for all constant polynomials
/// that are defined (and not just declared).
/// @returns the values (in source order) and the degree of the polynomials.
pub fn generate(analyzed: &Analyzed) -> (Vec<(&String, Vec<AbstractNumberType>)>, DegreeType) {
pub fn generate(analyzed: &Analyzed) -> (Vec<(&str, Vec<AbstractNumberType>)>, DegreeType) {
let mut degree = None;
let mut other_constants = HashMap::new();
for (poly, value) in analyzed.constant_polys_in_source_order() {
@@ -24,8 +24,8 @@ pub fn generate(analyzed: &Analyzed) -> (Vec<(&String, Vec<AbstractNumberType>)>
}
let mut values = Vec::new();
for (poly, _) in analyzed.constant_polys_in_source_order() {
if let Some(v) = other_constants.get_mut(&poly.absolute_name) {
values.push((&poly.absolute_name, std::mem::take(v)));
if let Some(v) = other_constants.get_mut(poly.absolute_name.as_str()) {
values.push((poly.absolute_name.as_str(), std::mem::take(v)));
};
}
(values, degree.unwrap_or_default())
@@ -35,7 +35,7 @@ fn generate_values(
analyzed: &Analyzed,
degree: DegreeType,
body: &FunctionValueDefinition,
other_constants: &HashMap<&String, Vec<AbstractNumberType>>,
other_constants: &HashMap<&str, Vec<AbstractNumberType>>,
) -> Vec<AbstractNumberType> {
match body {
FunctionValueDefinition::Mapping(body) => (0..degree)
@@ -67,7 +67,7 @@ fn generate_values(
struct Evaluator<'a> {
analyzed: &'a Analyzed,
other_constants: &'a HashMap<&'a String, Vec<AbstractNumberType>>,
other_constants: &'a HashMap<&'a str, Vec<AbstractNumberType>>,
variables: &'a [AbstractNumberType],
}
@@ -88,7 +88,7 @@ impl<'a> Evaluator<'a> {
Expression::FunctionCall(name, args) => {
let arg_values = args.iter().map(|a| self.evaluate(a)).collect::<Vec<_>>();
assert!(arg_values.len() == 1);
let values = &self.other_constants[name];
let values = &self.other_constants[name.as_str()];
values[abstract_to_degree(&arg_values[0]) as usize % values.len()].clone()
}
}
@@ -157,7 +157,7 @@ mod test {
assert_eq!(degree, 8);
assert_eq!(
constants,
vec![(&"F.LAST".to_string(), convert(vec![0, 0, 0, 0, 0, 0, 0, 1]))]
vec![("F.LAST", convert(vec![0, 0, 0, 0, 0, 0, 0, 1]))]
);
}
@@ -173,10 +173,7 @@ mod test {
assert_eq!(degree, 8);
assert_eq!(
constants,
vec![(
&"F.EVEN".to_string(),
convert(vec![-2, 0, 2, 4, 6, 8, 10, 12])
)]
vec![("F.EVEN", convert(vec![-2, 0, 2, 4, 6, 8, 10, 12]))]
);
}
@@ -193,10 +190,7 @@ mod test {
assert_eq!(degree, 8);
assert_eq!(
constants,
vec![(
&"F.EVEN".to_string(),
convert(vec![-2, 0, 2, 4, 6, 8, 10, 12])
)]
vec![("F.EVEN", convert(vec![-2, 0, 2, 4, 6, 8, 10, 12]))]
);
}
@@ -218,7 +212,7 @@ mod test {
assert_eq!(
constants,
vec![(
&"F.TEN".to_string(),
"F.TEN",
convert([[0; 10].to_vec(), [1, 0].to_vec()].concat())
)]
);
@@ -240,29 +234,26 @@ mod test {
assert_eq!(constants.len(), 4);
assert_eq!(
constants[0],
(
&"F.seq".to_string(),
convert((0..=9i32).collect::<Vec<_>>())
)
("F.seq", convert((0..=9i32).collect::<Vec<_>>()))
);
assert_eq!(
constants[1],
(
&"F.doub".to_string(),
"F.doub",
convert([1i32, 3, 5, 7, 9, 1, 3, 5, 7, 9].to_vec())
)
);
assert_eq!(
constants[2],
(
&"F.half_nibble".to_string(),
"F.half_nibble",
convert([0i32, 1, 2, 3, 4, 5, 6, 7, 0, 1].to_vec())
)
);
assert_eq!(
constants[3],
(
&"F.doubled_half_nibble".to_string(),
"F.doubled_half_nibble",
convert([0i32, 0, 1, 1, 2, 2, 3, 3, 4, 4].to_vec())
)
);
@@ -283,19 +274,13 @@ mod test {
assert_eq!(constants.len(), 3);
assert_eq!(
constants[0],
(
&"F.alt".to_string(),
convert([0i32, 1, 0, 1, 0, 1, 0, 0, 0, 0].to_vec())
)
);
assert_eq!(
constants[1],
(&"F.empty".to_string(), convert([0i32; 10].to_vec()))
("F.alt", convert([0i32, 1, 0, 1, 0, 1, 0, 0, 0, 0].to_vec()))
);
assert_eq!(constants[1], ("F.empty", convert([0i32; 10].to_vec())));
assert_eq!(
constants[2],
(
&"F.ref_other".to_string(),
"F.ref_other",
convert([9i32, 1, 8, 0, 0, 0, 0, 0, 0, 0].to_vec())
)
);

View File

@@ -1,5 +1,6 @@
// Verfies that a sum in the input has been computed properly.
// Input: sum, cnt, x_1, x_2, ..., x_cnt
// ?, 4, 1, 2, 3, 4
// This input is assumed to be present in a minirust variable called "input"
// of type "Vec<FieldElement>"
@@ -15,6 +16,10 @@ reg CNT;
pil{
col witness XInv;
col witness XIsZero;
// assume X = 7
// XisZero * 7 = 0 -> XIzZero = 0
// 0 = 1 - 7 * XInv
// => XInv = 1/7 (finite field)
XIsZero = 1 - X * XInv;
XIsZero * X = 0;
XIsZero * (1 - XIsZero) = 0;