evanw / skew

A web-first, cross-platform programming language with an optimizing compiler
https://evanw.github.io/skew-lang.org/
MIT License
413 stars 16 forks source link

String subscript in C# should be converted to int #19

Open dubek opened 7 years ago

dubek commented 7 years ago

Consider this Skew program:

@entry
def main {
  var s = "ABCDEF"
  switch s[0] {
    case 'A' { assert(true) }
    default { assert(false) }
  }
}

It compiles to JS and runs OK (no assertion). However, when compiling to C# and then to exe, the Mono compiler mcs yells:

t.cs(16,18): error CS0031: Constant value `65' cannot be converted to a `char'
Compilation failed: 1 error(s), 0 warnings

The resulting C# program is:

using System.Diagnostics;

public class Globals
{
    public static void assert(bool truth)
    {
        Debug.Assert(truth);
    }

    public static void Main()
    {
        string s = "ABCDEF";

        switch (s[0])
        {
            case 65:
            {
                Globals.assert(true);
                break;
            }

            default:
            {
                Globals.assert(false);
                break;
            }
        }
    }
}

The problem is that s[0] in C# returns a char; inside the case statement this is not automatically casted to int (whereas in == expressions it is). Maybe instead of s[0] skewc should emit something along the lines of Javascript's s.charCodeAt(0) (I don't know C#, sorry).

mingodad commented 7 years ago

Trying to understand how skew code generation works I did this change to csharp.sk:

        case .SWITCH {
          var switchValue = node.switchValue
          _emit(_indent + "switch (")
      if switchValue.kind == .INDEX {
        _emit("(int)")
      }
          _emitExpression(switchValue, .LOWEST)
          _emit(")\n" + _indent + "{\n")
          _increaseIndent

But probably it also need to cast in other places a string index is used (like in comparisons and assignments).