-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcompile.lua
More file actions
54 lines (47 loc) · 1.81 KB
/
compile.lua
File metadata and controls
54 lines (47 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
local lex_setup = require('sci-lang.lexer')
local parse = require('sci-lang.parser')
local ast = require('sci-lang.lua-ast').New()
local reader = require('sci-lang.reader')
local transform = require ('sci-lang.transform')
-- Two kind of backend can be used to generate the code from the AST:
-- - "generator", generates LuaJIT bytecode
-- - "luacode-generator", generates Lua code
--
-- Both can be used interchangeably, they take the AST tree and produce
-- a string that can be passed to the function "loadstring".
-- In the case of the bytecode generator the string will be actually a
-- binary blob that corresponds to the generated bytecode.
local function lang_toolkit_error(msg)
if string.sub(msg, 1, 9) == "LLT-ERROR" then
return false, "luajit-lang-toolkit: " .. string.sub(msg, 10)
else
error(msg)
end
end
local function compile(reader, filename, options)
local generator
if options and options.code then
generator = require('sci-lang.luacode-generator')
else
generator = require('sci-lang.generator')
end
local ls = lex_setup(reader, filename)
local parse_success, tree = pcall(parse, ast, ls)
if not parse_success then
return lang_toolkit_error(tree)
end
local ttree = transform.root(tree)
ttree = ttree or tree -- If nothing is returned, it's in-place transform.
local success, luacode = pcall(generator, ttree, filename)
if not success then
return lang_toolkit_error(luacode)
end
return true, luacode
end
local function lang_loadstring(src, filename, options)
return compile(reader.string(src), filename or "stdin", options)
end
local function lang_loadfile(filename, options)
return compile(reader.file(filename), filename or "stdin", options)
end
return { string = lang_loadstring, file = lang_loadfile }