nim-lang / RFCs

A repository for your Nim proposals.
135 stars 26 forks source link

Accept cstrings for case selector in JS #350

Closed metagn closed 1 year ago

metagn commented 3 years ago

This code:

let foo = cstring"abc"
case $foo
of "abc": echo "yes"
else: echo "no"

outputs:

var foo_1872002 = "abc";
switch (toJSStr(cstrToNimstr(foo_1872002))) {
case "abc":
  rawEcho(makeNimstrLit("yes"));
  break;
default: 
  rawEcho(makeNimstrLit("no"));
  break;
}

The toJSStr call is always emitted, and if it's a conversion from cstring to string you get a pointless toJSStr(cstrToNimstr(foo)). If the selector could be cstring we would be able to remove the toJSStr call and not have to convert with cstrToNimstr.

This is only relevant to JS so it would only be allowed on it, if this intrudes on consistency between backends (which I really doubt will be much of an issue to anyone) and it's easy to support cstring for the custom string case in C backend, then that could also be done, but if it's not worth it we could just deal with the inconsistency.

Someone might want to mention this even though it's unrelated, it's also very easy for the matcher values in the of branches to accept cstring values as they are the same in the VM, but this is irrelevant to the backend and would not affect performance.

Araq commented 3 years ago

We should also accept cstring for case for the C(++) backend, I've occasionally missed this feature.