Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ impl<'local, 'context> Interpreter<'local, 'context> {
"type_as_constant" => type_as_constant(arguments, return_type, location),
"type_as_integer" => type_as_integer(arguments, return_type, location),
"type_as_slice" => type_as_slice(arguments, return_type, location),
"type_as_str" => type_as_str(arguments, return_type, location),
"type_as_struct" => type_as_struct(arguments, return_type, location),
"type_as_tuple" => type_as_tuple(arguments, return_type, location),
"type_eq" => type_eq(arguments, location),
Expand Down Expand Up @@ -539,6 +540,21 @@ fn type_as_slice(
})
}

// fn as_str(self) -> Option<Type>
fn type_as_str(
arguments: Vec<(Value, Location)>,
return_type: Type,
location: Location,
) -> IResult<Value> {
type_as(arguments, return_type, location, |typ| {
if let Type::String(n) = typ {
Some(Value::Type(*n))
} else {
None
}
})
}

// fn as_struct(self) -> Option<(StructDefinition, [Type])>
fn type_as_struct(
arguments: Vec<(Value, Location)>,
Expand Down
6 changes: 6 additions & 0 deletions docs/docs/noir/standard_library/meta/typ.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ if the type is signed, as well as the number of bits of this integer type.

If this is a slice type, return the element type of the slice.

### as_str

#include_code as_str noir_stdlib/src/meta/typ.nr rust

If this is a `str<N>` type, returns the length `N` as a type.

### as_struct

#include_code as_struct noir_stdlib/src/meta/typ.nr rust
Expand Down
5 changes: 5 additions & 0 deletions noir_stdlib/src/meta/typ.nr
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ impl Type {
fn as_slice(self) -> Option<Type> {}
// docs:end:as_slice

#[builtin(type_as_str)]
// docs:start:as_str
fn as_str(self) -> Option<Type> {}
// docs:end:as_str

#[builtin(type_as_struct)]
// docs:start:as_struct
fn as_struct(self) -> Option<(StructDefinition, [Type])> {}
Expand Down
5 changes: 5 additions & 0 deletions test_programs/compile_success_empty/comptime_type/src/main.nr
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ fn main() {
assert(!struct_does_not_implement_some_trait.implements(some_trait_field));

let _trait_impl = struct_implements_some_trait.get_trait_impl(some_trait_i32).unwrap();

// Check Type::as_str
let str_type = quote { str<10> }.as_type();
let constant = str_type.as_str().unwrap();
assert_eq(constant.as_constant().unwrap(), 10);
}
}

Expand Down