[fpc-devel] Operator overloading

Bart bartjunk64 at gmail.com
Mon Apr 8 21:39:45 CEST 2019


Hi,

Forgive me for the long introduction before I ask the question.
It is the first time I try to fix a possible error in the compiler itself.

I was delving into https://bugs.freepascal.org/view.php?id=29460
It is impossible to overload = operator for longint = string.

Sample code:
program op;

{$mode objfpc}
{$h+}

operator = (L: Integer; R: String) z: Boolean;
begin
end;

begin
end.

Gives: op.lpr(6,46) Error: Impossible operator overload

I tracked it down to this piece of code on htypechk.pas

in function isbinaryoperatoroverloadable
in the nested function internal_check
this block of code:

case ld.typ of (ld.typ=orddef in this case)
....

orddef, floatdef:
  begin
    allowed:=not (
     (
       (rd.typ in [orddef,floatdef]) and
       (treetyp in order_theoretic_operators)
     ) or
     (
       is_stringlike(rd) and  //<< this block of code forbids it
       (ld.typ=orddef) and
       (treetyp in string_comparison_operators)) or
       { c.f. $(source)\tests\tmacpas5.pp }
       (
         (rd.typ=setdef) and
         (ld.typ=orddef) and
         (treetyp in element_set_operators)
       )
      { This clause may be too restrictive---not all types under
        orddef have a corresponding set type; despite this the
        restriction should be very unlikely to become
        a practical obstacle, and can be relaxed by simply
        adding an extra check on TOrdDef(rd).ordtype }
     );


In MacPas mode you can compare an ordinal to a string (but only with
the ordinal on the left).
See tests/test/tmacpas5.pp for an example.

I added a check for MacPas mode, only forbidding this operator
overload for that mode.
(Patch is in the bugtracker)
This seems to resolve the original issue.

Then I tried to compile the example in MacPas mode, expecting it to
give "op.lpr(6,46) Error: Impossible operator overload" error.
Instead it gave: op.lpr(6,9) Fatal: Syntax error, "BEGIN" expected but
"identifier OPERATOR" found.

Naturally I though my patch caused this, but 3.0.4 gives exactly the
same error message.

This raises for me the following questions:

1.
Is operator overloading possible at all in MacPas mode (does it need
some modeswitch)?

2.
If this is not the case, then why forbid this particular operator
overload at all?

-- 
Bart



More information about the fpc-devel mailing list