Skip to content

Commit

Permalink
codegen+runtime: Add support for casting to enums with underlying types
Browse files Browse the repository at this point in the history
This makes it possible to turn e.g. a u8 into an enum Foo: u8.
  • Loading branch information
alimpfard committed Apr 30, 2023
1 parent 8f552fb commit c682a12
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
7 changes: 7 additions & 0 deletions runtime/lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,12 @@ ALWAYS_INLINE constexpr OutputType infallible_integer_cast(InputType input)
}
}

template<typename OutputType, typename InputType>
ALWAYS_INLINE constexpr OutputType infallible_enum_cast(InputType input)
{
return static_cast<OutputType>(infallible_integer_cast<UnderlyingType<OutputType>>(input));
}

template<AK::Concepts::SpecializationOf<AK::NonnullRefPtr> T, AK::Concepts::SpecializationOf<AK::NonnullRefPtr> U>
inline Optional<T> fallible_class_cast(U const& ptr)
{
Expand Down Expand Up @@ -348,6 +354,7 @@ using JaktInternal::fallible_class_cast;
using JaktInternal::fallible_integer_cast;
using JaktInternal::infallible_class_cast;
using JaktInternal::infallible_integer_cast;
using JaktInternal::infallible_enum_cast;
using JaktInternal::Range;
using JaktInternal::unchecked_add;
using JaktInternal::unchecked_div;
Expand Down
2 changes: 2 additions & 0 deletions selfhost/codegen.jakt
Original file line number Diff line number Diff line change
Expand Up @@ -2092,6 +2092,8 @@ struct CodeGenerator {
cast_type = "infallible_class_cast"
} else if .program.is_integer(type_id) {
cast_type = "infallible_integer_cast"
} else if type is Enum(enum_id) and .program.is_integer(.program.get_enum(enum_id).underlying_type_id) {
cast_type = "infallible_enum_cast"
}
yield cast_type
}
Expand Down

0 comments on commit c682a12

Please sign in to comment.