Skip to content
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

feat: Implement zeroed in the interpreter #5540

Merged
merged 7 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ impl<'a> Interpreter<'a> {
}

if meta.kind != FunctionKind::Normal {
return self.call_builtin(function, arguments, location);
let return_type = meta.return_type().follow_bindings();
return self.call_builtin(function, arguments, return_type, location);
}

let parameters = meta.parameters.0.clone();
Expand All @@ -144,6 +145,7 @@ impl<'a> Interpreter<'a> {
&mut self,
function: FuncId,
arguments: Vec<(Value, Location)>,
return_type: Type,
location: Location,
) -> IResult<Value> {
let attributes = self.interner.function_attributes(&function);
Expand All @@ -152,7 +154,7 @@ impl<'a> Interpreter<'a> {

if let Some(builtin) = func_attrs.builtin() {
let builtin = builtin.clone();
builtin::call_builtin(self.interner, &builtin, arguments, location)
builtin::call_builtin(self.interner, &builtin, arguments, return_type, location)
} else if let Some(foreign) = func_attrs.foreign() {
let item = format!("Comptime evaluation for foreign functions like {foreign}");
Err(InterpreterError::Unimplemented { item, location })
Expand Down
88 changes: 85 additions & 3 deletions compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,25 @@ use std::{

use acvm::{AcirField, FieldElement};
use chumsky::Parser;
use noirc_errors::Location;
use iter_extended::try_vecmap;
use noirc_errors::{Location, Span};
use rustc_hash::FxHashMap as HashMap;

use crate::{
ast::{IntegerBitSize, TraitBound},
hir::comptime::{errors::IResult, InterpreterError, Value},
macros_api::{NodeInterner, Signedness},
macros_api::{NodeInterner, Path, Signedness},
node_interner::FuncId,
parser,
token::{SpannedToken, Token, Tokens},
QuotedType, Type,
QuotedType, Shared, Type,
};

pub(super) fn call_builtin(
interner: &mut NodeInterner,
name: &str,
arguments: Vec<(Value, Location)>,
return_type: Type,
location: Location,
) -> IResult<Value> {
match name {
Expand All @@ -43,6 +47,7 @@ pub(super) fn call_builtin(
"trait_constraint_eq" => trait_constraint_eq(interner, arguments, location),
"trait_constraint_hash" => trait_constraint_hash(interner, arguments, location),
"quoted_as_trait_constraint" => quoted_as_trait_constraint(interner, arguments, location),
"zeroed" => zeroed(return_type, location),
_ => {
let item = format!("Comptime evaluation for builtin function {name}");
Err(InterpreterError::Unimplemented { item, location })
Expand Down Expand Up @@ -393,6 +398,83 @@ fn trait_constraint_eq(
Ok(Value::Bool(constraint_a == constraint_b))
}

// fn zeroed<T>() -> T
fn zeroed(return_type: Type, location: Location) -> IResult<Value> {
match return_type {
Type::FieldElement => Ok(Value::Field(0u128.into())),
Type::Array(length_type, elem) => {
if let Some(length) = length_type.evaluate_to_u32() {
let element = zeroed(elem.as_ref().clone(), location)?;
let array = std::iter::repeat(element).take(length as usize).collect();
Ok(Value::Array(array, Type::Array(length_type, elem)))
} else {
Err(InterpreterError::NonIntegerArrayLength { typ: *length_type, location })
}
}
Type::Slice(_) => Ok(Value::Slice(im::Vector::new(), return_type)),
Type::Integer(sign, bits) => match (sign, bits) {
(Signedness::Unsigned, IntegerBitSize::One) => Ok(Value::U8(0)),
(Signedness::Unsigned, IntegerBitSize::Eight) => Ok(Value::U8(0)),
(Signedness::Unsigned, IntegerBitSize::Sixteen) => Ok(Value::U16(0)),
(Signedness::Unsigned, IntegerBitSize::ThirtyTwo) => Ok(Value::U32(0)),
(Signedness::Unsigned, IntegerBitSize::SixtyFour) => Ok(Value::U64(0)),
(Signedness::Signed, IntegerBitSize::One) => Ok(Value::I8(0)),
(Signedness::Signed, IntegerBitSize::Eight) => Ok(Value::I8(0)),
(Signedness::Signed, IntegerBitSize::Sixteen) => Ok(Value::I16(0)),
(Signedness::Signed, IntegerBitSize::ThirtyTwo) => Ok(Value::I32(0)),
(Signedness::Signed, IntegerBitSize::SixtyFour) => Ok(Value::I64(0)),
},
Type::Bool => Ok(Value::Bool(false)),
Type::String(length_type) => {
if let Some(length) = length_type.evaluate_to_u32() {
Ok(Value::String(Rc::new("\0".repeat(length as usize))))
} else {
Err(InterpreterError::NonIntegerArrayLength { typ: *length_type, location })
}
}
Type::FmtString(_, _) => {
let item = "format strings in a comptime context".into();
Err(InterpreterError::Unimplemented { item, location })
michaeljklein marked this conversation as resolved.
Show resolved Hide resolved
}
Type::Unit => Ok(Value::Unit),
Type::Tuple(fields) => {
Ok(Value::Tuple(try_vecmap(fields, |field| zeroed(field, location))?))
}
Type::Struct(struct_type, generics) => {
let fields = struct_type.borrow().get_fields(&generics);
let mut values = HashMap::default();

for (field_name, field_type) in fields {
let field_value = zeroed(field_type, location)?;
values.insert(Rc::new(field_name), field_value);
}

let typ = Type::Struct(struct_type, generics);
Ok(Value::Struct(values, typ))
}
Type::Alias(alias, generics) => zeroed(alias.borrow().get_type(&generics), location),
Type::Function(_, _, _) => {
Ok(Value::Function(FuncId::dummy_id(), Type::Unit, Default::default()))
}
Type::MutableReference(element) => {
let element = zeroed(*element, location)?;
Ok(Value::Pointer(Shared::new(element), false))
}
Type::Quoted(QuotedType::TraitConstraint) => Ok(Value::TraitConstraint(TraitBound {
trait_path: Path::from_single(String::new(), Span::default()),
trait_id: None,
trait_generics: Vec::new(),
})),
Type::TypeVariable(_, _)
| Type::Forall(_, _)
| Type::Constant(_)
| Type::Quoted(_)
| Type::Error
| Type::TraitAsType(_, _, _)
| Type::NamedGeneric(_, _, _) => Ok(Value::Zeroed(return_type)),
}
}

fn modulus_be_bits(
_interner: &mut NodeInterner,
arguments: Vec<(Value, Location)>,
Expand Down
5 changes: 5 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub enum Value {
TraitDefinition(TraitId),
FunctionDefinition(FuncId),
ModuleDefinition(ModuleId),
Zeroed(Type),
}

impl Value {
Expand Down Expand Up @@ -94,6 +95,7 @@ impl Value {
Value::TraitDefinition(_) => Type::Quoted(QuotedType::TraitDefinition),
Value::FunctionDefinition(_) => Type::Quoted(QuotedType::FunctionDefinition),
Value::ModuleDefinition(_) => Type::Quoted(QuotedType::Module),
Value::Zeroed(typ) => return Cow::Borrowed(typ),
})
}

Expand Down Expand Up @@ -215,6 +217,7 @@ impl Value {
| Value::TraitConstraint(_)
| Value::TraitDefinition(_)
| Value::FunctionDefinition(_)
| Value::Zeroed(_)
michaeljklein marked this conversation as resolved.
Show resolved Hide resolved
| Value::ModuleDefinition(_) => {
return Err(InterpreterError::CannotInlineMacro { value: self, location })
}
Expand Down Expand Up @@ -329,6 +332,7 @@ impl Value {
| Value::TraitConstraint(_)
| Value::TraitDefinition(_)
| Value::FunctionDefinition(_)
| Value::Zeroed(_)
jfecher marked this conversation as resolved.
Show resolved Hide resolved
| Value::ModuleDefinition(_) => {
return Err(InterpreterError::CannotInlineMacro { value: self, location })
}
Expand Down Expand Up @@ -438,6 +442,7 @@ impl Display for Value {
Value::TraitDefinition(_) => write!(f, "(trait definition)"),
Value::FunctionDefinition(_) => write!(f, "(function definition)"),
Value::ModuleDefinition(_) => write!(f, "(module)"),
Value::Zeroed(typ) => write!(f, "(zeroed {typ})"),
}
}
}
Loading