neilsf / xc-basic3

A BASIC cross compiler for MOS 6502-based machines
MIT License
44 stars 5 forks source link

Lazy evaluation would be welcome #149

Open fredrikr opened 2 years ago

fredrikr commented 2 years ago

Most languages support lazy evaluation, i.e. a boolean expression is evaluated from left to right and parts that don't need to be evaluated to know the result are skipped, i.e. it's okay to write:

IF a > 0 AND b/a =2 THEN PRINT "b is 2*a";

(If "a > 0" evaluates to false, the value of the entire expression is guaranteed to be false, so "b/a = 2" is not evaulated. Similarly, the right-hand side of an OR expression can be skipped if the left-hand side evalutates to true.)

It would be nice to have this in XC=Basic.

neilsf commented 2 years ago

It's a nice feature but it would add a little overhead. In cases where the left-side expression is evaluated to false, the code would obviously run faster (bc the right side is skipped) but in other cases, where the entire expression is evaluated, it would be slower in total. Only the programmer could tell if it's worth. Or am I wrong?

fredrikr commented 2 years ago

I don't think it would ever need to be slower than the code that is generated today. Is it possible to change code generation like this, i.e. when the result of the lefthand side is determined to be 0, short-circuit the AND operation and just say the result is 0. :

image

neilsf commented 2 years ago

Hmmm.... that's something the optimizer could actually do. I'll try to implement this.

AGPX commented 1 year ago

It would be nice to have, it's what is called "short circuit" and it doesn't slow down the code in any case.