wurstscript / WurstScript

Programming language and toolkit to create Warcraft III Maps
https://wurstlang.org
Apache License 2.0
225 stars 30 forks source link

Temporary index variable for shorthand assignments #1061

Closed Jampi0n closed 2 years ago

Jampi0n commented 2 years ago

Addresses #998 .

rewrites test[getIndex()]++ to

let tmp = getIndex()
test[tmp] = test[tmp] + 1

Few remarks:

Integer literals and variables don't use temporary variables: test[4]++ -> test[4] = test[4] + 1 test[myInt]++ -> test[myInt] = test[myInt] + 1 When using expression that can be evaluated to constants, the optimizer will take care of that and you end up with a case like above. Right now integer arrays are also stored in temporary variables: test[myIntArray[0]]++ ->

let tmp = myIntArray[0]
test[tmp] = test[tmp] + 1

In theory one could leave integer arrays, as long as the index itself is again constant, but if enough integer arrays are used, using a temporary variable will be faster. Could probably add a cutoff and say if it's less than x nested integer arrays, keep them, otherwise use temp variable.

Frotty commented 2 years ago

Thanks for the PR.

I rewrote transformStatement so it returns a list of statements rather than a single one in order to add the temporary variables before the set statement. Maybe there is a way to combine multiple statements in a single one?

Could be fine but I think the current implementation might could be improved, as it currently would mean a list allocation for every statement, regardless whether it needs more than 1 return statement.

I used tmpArrayIndex_ combined with the line number as name for the temporary variable which should avoid conflicts, but if there is a function to get a unique identifier that would be better.

Yea might be better to use NameProvider or something.

In theory one could leave integer arrays, as long as the index itself is again constant, but if enough integer arrays are used, using a temporary variable will be faster. Could probably add a cutoff and say if it's less than x nested integer arrays, keep them, otherwise use temp variable.

Yea could be a later optimization but doesn't have to be in this PR.

Frotty commented 2 years ago

Very nice, thank you 👍