cardillan / mindcode

A high level language for Mindustry Logic (mlog) and Mindustry Schematics.
http://mindcode.herokuapp.com/
MIT License
87 stars 13 forks source link

Wrong compilation order of appended files #155

Closed cardillan closed 1 month ago

cardillan commented 1 month ago

When using the --append command line option, the main source file is compiled first, then the additional (library) files. This can cause problems if the library files contain constants. Example

File lib.mnd

const SOME_CONSTANT = 10;

def foo()
    print(SOME_CONSTANT);
end;

File main.mnd

foo();

Now compiling these files with mindcode cm main.mnd --append lib.mnd, both of these files get parsed and then compiled. This is equivalent to compiling this code:

foo();

const SOME_CONSTANT = 10;

def foo()
    print(SOME_CONSTANT);
end;

Now, foo() is called just once, meaning it gets inlined by the compiler. The compiler will see print(SOME_CONSTANT) and will create SOME_CONSTANT as a global variable. Then comes const SOME_CONSTANT = 10;, which causes an error, because it is not possible to redefine a variable as a constant.

To fix this issue temporarily, the parse trees will be put together in an reverse order (first the appended files, then the main file).

The real solution with modules (#149) will combine constants, variables and functions in parse trees in a well defined order, instead of blindly gluing them together the way it is now.