KarolS/millfork

Implement ++ and -- operators in the Millfork language

n1k0m0 opened this issue · 4 comments

The 6502 implements the INC and DEC opcodes, which allow to increment and decrement values directly in memory.
I thought it would be a good idea to also allow the usage of this in Millfork.

Example:
byte i
i++

Could be directly translated to
inc $i (where $i is the address, where the variable i is in Memory)

Instead, as far as I have seen, the "i=i+ 1" are converted using the ADD and ADDC instructions.

Benefits: Besides the maybe more efficient assembler code which is then generated by the Millfork compiler, it would also lead to some nicer Millfork code.

Of course, i-- should be implemented accordingly

As I just learned, the behavior that I described can be achieved by
i += 1 and i -=1
This gets compiled to inc and dec

I, nevertheless, think that implementing i++ and i-- would also help developers, since, coming from the C++, C# and Java world, the i++ first came into my mind. Also the += and -= operators are mainly used for more complex expressions I think.

agg23 commented

I would argue that += is much clearer than ++ due to the expression nature of x++. You could do something like y = x++ or y = ++x and get different results, and often developers don't properly understand what the expression means.

Sorry, Millfork will never have those operators. Millfork explicitly rejects bad parts of syntax of B (I guess it's cool that you can take code from late 60s and compile it as C#, but Millfork is not for that), and these operators are only the tip of the iceberg. In fact, the only reason B had ++ and -- was because the compiler was too dumb to optimize +=1 and -=1, and that incapability trickled down to too many modern languages. Millfork is an optimizing compiler, and +=1 and -=1 are explicitly special-cased to compile to a single INC/DEC when possible.

There are several reasons for not including ++ and --:

  1. Millfork does not have unary operators other than -. This is by design, and even - was only added later.
  2. ++ and -- introduce parsing ambiguity. --a currently means -(-a) and introducing a new -- operator would break that. Similarly with things like a--b, which is currently parsed as a-(-b)
  3. Most languages that have those operators, treat them as expressions, which can cause confusion between preincrement and postincrement variants as @agg23 mentioned in the previous comment. In Millfork, assignments are not expressions, and since they are not, += 1 is fine and readable.
  4. Most instances of ++ are found in C-style loops, but Millfork has range-based loops.
  5. Some languages use ++ and -- for other things.

Further reading:

Thanks, makes 100% sense to me :-)