Skip to content

Commit

Permalink
feat: implement str_as_bytes in the comptime interpreter
Browse files Browse the repository at this point in the history
  • Loading branch information
TomAFrench committed Sep 2, 2024
1 parent 4012429 commit 0967550
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
27 changes: 27 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ impl<'local, 'context> Interpreter<'local, 'context> {
"slice_push_back" => slice_push_back(interner, arguments, location),
"slice_push_front" => slice_push_front(interner, arguments, location),
"slice_remove" => slice_remove(interner, arguments, location, call_stack),
"str_as_bytes" => str_as_bytes(interner, arguments, location),
"struct_def_as_type" => struct_def_as_type(interner, arguments, location),
"struct_def_fields" => struct_def_fields(interner, arguments, location),
"struct_def_generics" => struct_def_generics(interner, arguments, location),
Expand Down Expand Up @@ -242,6 +243,32 @@ fn slice_push_back(
Ok(Value::Slice(values, typ))
}

fn str_as_bytes(
interner: &NodeInterner,
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let (string, string_location) = check_one_argument(arguments, location)?;

match string {
Value::String(string) => {
let string_as_bytes = string.as_bytes();
let bytes_vector: Vec<Value> = string_as_bytes.iter().cloned().map(Value::U8).collect();
let byte_array_type = Type::Array(
Box::new(Type::Constant(string_as_bytes.len() as u32)),
Box::new(Type::Integer(Signedness::Unsigned, IntegerBitSize::Eight)),
);
Ok(Value::Array(bytes_vector.into(), byte_array_type))
}
value => {
let type_var = Box::new(interner.next_type_variable());
let expected = Type::Array(type_var.clone(), type_var);
let actual = value.get_type().into_owned();
Err(InterpreterError::TypeMismatch { expected, actual, location: string_location })
}
}
}

/// fn as_type(self) -> Type
fn struct_def_as_type(
interner: &NodeInterner,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "comptime_str_as_bytes"
type = "bin"
authors = [""]
compiler_version = ">=0.24.0"

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
fn main() {
comptime
{
let hello_world_string = "hello world";
let hello_world_bytes: [u8; 11] = [0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64];

assert_eq(hello_world_string.as_bytes(), hello_world_bytes);
}
}

0 comments on commit 0967550

Please sign in to comment.