Skip to content

Commit

Permalink
fix: Replace expects in interpreter with errors (#5383)
Browse files Browse the repository at this point in the history
# Description

## Problem\*

Resolves <!-- Link to GitHub Issue -->

## Summary\*



## Additional Context



## Documentation\*

Check one:
- [x] No documentation needed.
- [ ] Documentation included in this PR.
- [ ] **[For Experimental Features]** Documentation to be submitted in a
separate PR.

# PR Checklist\*

- [x] I have tested the changes locally.
- [x] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
jfecher authored Jul 2, 2024
1 parent 7b77bbf commit ac738b2
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,10 @@ impl<'a> Interpreter<'a> {

let index = match index {
Value::Field(value) => {
value.try_to_u64().expect("index could not fit into u64") as usize
value.try_to_u64().and_then(|value| value.try_into().ok()).ok_or_else(|| {
let typ = Type::default_int_type();
InterpreterError::IntegerOutOfRangeForType { value, typ, location }
})?
}
Value::I8(value) => value as usize,
Value::I16(value) => value as usize,
Expand Down Expand Up @@ -1209,8 +1212,15 @@ impl<'a> Interpreter<'a> {
}
}
HirLValue::MemberAccess { object, field_name, field_index, typ: _, location } => {
let index = field_index.expect("The field index should be set after type checking");
match self.evaluate_lvalue(&object)? {
let object_value = self.evaluate_lvalue(&object)?;

let index = field_index.ok_or_else(|| {
let value = object_value.clone();
let field_name = field_name.to_string();
InterpreterError::ExpectedStructToHaveField { value, field_name, location }
})?;

match object_value {
Value::Tuple(mut fields) => {
fields[index] = rhs;
self.store_lvalue(*object, Value::Tuple(fields))
Expand Down Expand Up @@ -1254,9 +1264,16 @@ impl<'a> Interpreter<'a> {
}
}
HirLValue::MemberAccess { object, field_name, field_index, typ: _, location } => {
let index = field_index.expect("The field index should be set after type checking");
let object_value = self.evaluate_lvalue(object)?;

let index = field_index.ok_or_else(|| {
let value = object_value.clone();
let field_name = field_name.to_string();
let location = *location;
InterpreterError::ExpectedStructToHaveField { value, field_name, location }
})?;

match self.evaluate_lvalue(object)? {
match object_value {
Value::Tuple(mut values) => Ok(values.swap_remove(index)),
Value::Struct(fields, _) => Ok(fields[&field_name.0.contents].clone()),
value => Err(InterpreterError::NonTupleOrStructInMemberAccess {
Expand Down

0 comments on commit ac738b2

Please sign in to comment.