PythonGCodeCompiler/docs/Compiler.md
2026-11-22 20:24:54 -05:00

1.5 KiB

How the compiler works

The gcode compiler works by reading the bytecode of the python function decorated with @macro. It keeps track of what the stack would be and emitting instructions when certain opcodes are encountered. All gcode generator functions (move, home, macros, etc) have a .gcode_call() function with the same signature as the main function except returning a str. This function is used when compiling to know what gcode to emit for a certain function. For example: move.gcode_call(x=0, y=50, z=0) returns G0 X0 Y50 Z0.

The compiler uses the global variable ret_val to store the return value of macros and other functions

The start of all output gcode encludes a section to ensure ret_val exists and check if each parameter exists, if a parameter does exist then its value is assigned to a variable of the same name. If the parameter doesnt exist then a variable of the same name is either assigned its default value or an error is raised.
We create a variable instead of directly using param.* because it makes code generation a lot easier. Whenever we see an assignment we can directly emit a var x = y instead of having to check (and remember) if we can use param.x

When the compiler sees a LOAD_GLOBAL it checks to see if the global being loaded is the print function, and if it is then it actually loads gcode.echo instead, this so that when writing a macro you can use print and have it compile to an echo command. The echo implementation only supports *args, not kwargs or end.