JoeStrout / miniscript

source code of both C# and C++ implementations of the MiniScript scripting language
MIT License
280 stars 64 forks source link

Differences in `self` between C# and C++ #98

Open JoeStrout opened 1 year ago

JoeStrout commented 1 year ago

There are optimizations in the C# code that were not ported to the C++ code, resulting in differences in behavior. In general, in C++ one can see self among locals, monkey with its value, etc. In C#, it is stored separately in the call stack and not visible in locals; it's more like a proper keyword. (Though you can still assign to it, this assignment has little effect since self lookups don't look in locals.)

For an example of the difference in behavior, consider this function:

f = function; print self; end function

In C#, this prints null; in C++, this produces an Undefined Identifier error.

So, it's clear the two implementations need to be brought back into agreement. And also that the optimizations are probably worth it for performance. However, we need to think carefully about exactly how we want self (and super for that matter) to behave, in all the edge cases users might subject it to.

JoeStrout commented 10 months ago

OK, after discussion on Discord, here is the proposed behavior:

  1. self is always defined, but it will be null in any context where the code is not inside a method invoked on an object.
  2. Attempts to assign to self will produce a compile-time error.
  3. Same for super (except that super is also null when there is no further superclass).
  4. It will be a compile time error if self is used as a parameter name for anything but the first parameter.

Point 1 is already the behavior in the C# (but not C++) version; C++ could be brought into line now. But points 2-4 are potentially code-breaking changes, and should probably wait for a larger MiniScript update.