--[[ Lua Assembler Version 0.1 Author: Andre Murbach Maidl ]] -- requires LPeg re module require "re" -- usage message USAGE = [[ usage: %s [options] [filename] Available options are: -h print this help -b big endian (default is little endian) -o name output to file name (default is %s) ]] -- global settings config = {} config.SIGNATURE = "\27Lua" config.VERSION = 81 config.FORMAT = 0 config.ENDIANNESS = 1 config.INT = 4 config.SIZE_T = 8 config.INSTRUCTION = 4 config.LUA_NUMBER = 8 config.INTEGRAL = 0 config.SIZE_C = 9 config.SIZE_B = 9 config.SIZE_Bx = config.SIZE_C + config.SIZE_B config.SIZE_A = 8 config.SIZE_OP = 6 config.POS_OP = 0 config.POS_A = config.POS_OP + config.SIZE_OP config.POS_C = config.POS_A + config.SIZE_A config.POS_B = config.POS_C + config.SIZE_C config.POS_Bx = config.POS_C config.iABC = { config.SIZE_OP, config.SIZE_A, config.SIZE_C, config.SIZE_B } config.MASK_OP = math.ldexp(1, config.SIZE_OP) config.MASK_A = math.ldexp(1, config.SIZE_A) config.MASK_B = math.ldexp(1, config.SIZE_B) config.MASK_C = math.ldexp(1, config.SIZE_C) config.MASK_Bx = math.ldexp(1, config.SIZE_Bx) config.MAXARG_sBx = math.floor((config.MASK_Bx - 1) / 2) config.BITRK = math.ldexp(1, config.SIZE_B - 1) -- global types types = {} types.LUA_TNIL = 0 types.LUA_TBOOLEAN = 1 types.LUA_TNUMBER = 3 types.LUA_TSTRING = 4 -- opcodes opcode = {} opcode = { ["MOVE"] = 0, ["LOADK"] = 1, ["LOADBOOL"] = 2, ["LOADNIL"] = 3, ["GETUPVAL"] = 4, ["GETGLOBAL"] = 5, ["GETTABLE"] = 6, ["SETGLOBAL"] = 7, ["SETUPVAL"] = 8, ["SETTABLE"] = 9, ["NEWTABLE"] = 10, ["SELF"] = 11, ["ADD"] = 12, ["SUB"] = 13, ["MUL"] = 14, ["DIV"] = 15, ["MOD"] = 16, ["POW"] = 17, ["UNM"] = 18, ["NOT"] = 19, ["LEN"] = 20, ["CONCAT"] = 21, ["JMP"] = 22, ["EQ"] = 23, ["LT"] = 24, ["LE"] = 25, ["TEST"] = 26, ["TESTSET"] = 27, ["CALL"] = 28, ["TAILCALL"] = 29, ["RETURN"] = 30, ["FORLOOP"] = 31, ["FORPREP"] = 32, ["TFORLOOP"] = 33, ["SETLIST"] = 34, ["CLOSE"] = 35, ["CLOSURE"] = 36, ["VARARG"] = 37 } -- opcode modes opmode = {} opmode.iABC = 0 opmode.iABx = 1 opmode.iAsBx = 2 -- global options options = {} options.INPUT = nil options.OUTPUT = "d.out" options.GENOUT = true -- table to store parsed data parsed = {} num_par = {} num_par["main"] = 0 -- Assembly grammar grammar = [[ prog <- ( )* -> {} function <-
( )+ -> {} header <- ( %nl )* ( /
) ( %nl )+ user <- ( "function" {} ":" ) main <- ( {"main"} "function" ":" ) number <- / / int <- "-"? [0-9]+ e <- [eE][+-]?[0-9]+ float <- "-"? ([0-9]+"."[0-9]* / "."[0-9]+) ? / "-"? [0-9]+ hex <- "-"? "0"[xX][0-9a-fA-F]+ name <- [a-zA-Z_][a-zA-Z0-9_]* label <- ":" string <- '"' ('\\' / '\"' / !'"' .)* '"' instruction <- ( ( {