assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Enum reverse mappings

Open raddad772 opened this issue 2 years ago • 3 comments

Hey! TypeScript has these handy reverse mappings! From https://www.typescriptlang.org/docs/handbook/enums.html:

enum Enum {
  A,
}
 
let a = Enum.A;
let nameOfA = Enum[a]; // "A"
[Try](https://www.typescriptlang.org/play/#code/KYOwrgtgBAou0G8BQUoEEA0SC+SkBtgAXKAQygF5Z4A6NAbgOKhFImAHkAzNS6yANqkAuvSgB6cVABEaaUA)

TypeScript compiles this down to the following JavaScript:

"use strict";
var Enum;
(function (Enum) {
    Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

could we get us some of these?

raddad772 avatar Jan 13 '23 16:01 raddad772

So far, what AS does is assume const enum for all enums (these don't have reverse mapping in TS as well), since in our case reverse lookups would need a compiler-generated function per enum to map from values to string keys, whereas the string keys will not be useful to do an actual lookup again unless there would be another compiler-generated function to map string keys to values. So to say, currently it's all static, and any form of myEnum[something], where something can be a dynamic input (be it a value or string key), would need dynamic emulation by the compiler that might not even be used. A bit of a slippery slope, since then we'd soon also think about myObject[something] which is not supported as well for similar reasons.

Thoughts?

dcodeIO avatar Jan 13 '23 16:01 dcodeIO

My thoughts are I'm kinda sick of manually generating these functions and it sounds great to me if the compiler would generate them! I often don't even write enums anymore, I write code to generate the enum + reverse mapping.

As for generating unused functions, I guess that could have a compile-time impact. Can we do something like #pragma generate_reverse enum foo { }

and all ones without that pragma can go to a function that just throws an error?

raddad772 avatar Jan 13 '23 16:01 raddad772

The mechanism in TS is that an enum can be a const enum, though most devs typically just write enum even when not using reverse lookups. Now in TS, that only generates the Enum[Enum["A"] = 0] = "A"; parts, whereas in AS there'd be a concrete lookup function. If we'd implement reverse lookups, I guess we'd ideally reuse this mechanism?

dcodeIO avatar Jan 13 '23 16:01 dcodeIO