rsdn / nemerle

Nemerle language. Main repository.
http://nemerle.org
Other
621 stars 89 forks source link

Compiler should produce errors when using disallowed operator overloads #13327

Open ssrmm opened 7 years ago

ssrmm commented 7 years ago

Currently the Nemerle compiler silently accepts any operator overloads, even if they are not possible. For clarity the compiler should generate errors when an attempt is made to overload any of the operators implemented as macros.

VladD2 commented 7 years ago

Give an example, please.

ssrmm commented 7 years ago

For example this compiles fine:

using System.Console;

namespace Test
{
  public module Main
  {
    public Main() : void
    {
      mutable test1 = Test(1);
      def     test2 = Test(2);

      test1 += test2;

      WriteLine($"Result=$(test1.Int)");
      _ = ReadKey();
    }
  }

  [Record]
  public class Test
  {
    public Int : int { get; } 

    // 1st += overload
    public static @+=(left : ref Test, right : Test) : void
    {
      WriteLine("called @+=(ref Test, Test) : void");
      left = Test(left.Int + right.Int)
    }

    // 2nd += overlaod
    public static @+=(left : Test, right : Test) : Test
    {
      WriteLine("called @+=(Test, Test) : Test");
      Test(left.Int + right.Int)
    }

    public static @+(left : Test, right : Test) : Test
    {
      WriteLine("called @+(Test, Test) : Test");
      Test(left.Int + right.Int)
    }
  }
}

Output when running:

called @+(Test, Test) : Test
Result=3

Now that I know that += is implemented as macro, I can easily understand the output.

To me the first version of the overload seems the more logical. The second would rather be def result = test1 += test2;. But in any case the macro just produces test1 = test1 + test2 and neither of the defined overloads can ever be called.

As such it would be good to have an error messages for people that don't know the source code and haven't read Nemerle-for-OOP-Programmers-Week-5#Operator_overloading(the only place it is mentioned AFAICT).

In C# any of my attempts to overload operator += resulted in CS1020.