nemerle icon indicating copy to clipboard operation
nemerle copied to clipboard

Compiler should produce errors when using disallowed operator overloads

Open ssrmm opened this issue 8 years ago • 2 comments

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.

ssrmm avatar Nov 30 '16 15:11 ssrmm

Give an example, please.

VladD2 avatar Nov 30 '16 19:11 VladD2

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.

ssrmm avatar Dec 01 '16 09:12 ssrmm