facebook / facebook/hhvm

[ Runtime ] make `is` and `as` checks on enums not do string to int conversion

Open
#8,651 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
18.7k
Forks
3.1k
Avg merge
1h 47m
Merged PRs (30d)
2

Description

**Is your feature request related to a problem? Please describe.**

For backwards compat reasons, HHVM will do `is` and `as` checks on enums weakly.
This has some surprising results.

```HACK
enum Numberz: int {
ZERO = 0;
}

function main(): void {
$zero_as_a_string = '0';
if ($zero_as_a_string is Numberz) { // true
has_a_numberz_typehint($zero_as_a_string); // BOOM
}
}
```

This blows up at runtime, because `'0'` is not an interger.

**Describe the solution you'd like**

Make `is` and `as` checks fail if the runtime type doesn't match. `string <===> int`
We might need a ini setting to turn this to warn mode. (If it doesn't already exist.)

**Describe alternatives you've considered**

Back every enum with `arraykey` in your own code, so it doesn't fail at runtime.
However, this doesn't work for transparent (non-opaque) enums.

```HACK
enum Numbers: arraykey as int { }
```

I want to be able to use a `Numberz` as an integer, but this `arraykey as int` type constraint is invalid.

**Additional context**

[HHVM 3.28.0 release notes](https://hhvm.com/blog/2018/08/28/hhvm-3.28.0.html)
> For enums, the operators will validate that the value is in the given enum. CAUTION: the operators will perform integral key coercion to preserve compatibility with BuiltinEnum::isValid. We will fix this separately in the future.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the enum example from the issue and compare the current behavior with the requested strict string-versus-integer check. The change is done when `is` and `as` reject mismatched runtime types without the documented integral key coercion; the possible warning-mode setting remains an unresolved design question.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.