123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352 | -- This file contains objects that are used to track code positions and incrementally
-- build up generated code, while keeping track of where it came from, and managing
-- indentation levels.
{:insert, :remove, :concat} = table
local LuaCode, NomsuCode, Source
class Source
new: (@filename, @start, @stop)=>
@from_string: (str)=>
filename,start,stop = str\match("^@(.-)%[(%d+):(%d+)%]")
unless filename
filename,start = str\match("^@(.-)%[(%d+)%]")
return @(filename or str, tonumber(start or 1), tonumber(stop))
@is_instance: (x)=> type(x) == 'table' and x.__class == @
__tostring: => "@#{@filename}[#{@start}#{@stop and ':'..@stop or ''}]"
as_lua: => "Source(#{@filename\as_lua!}, #{@start}#{@stop and ', '..@stop or ''})"
__eq: (other)=>
getmetatable(@) == getmetatable(other) and @filename == other.filename and @start == other.start and @stop == other.stop
__lt: (other)=>
assert(@filename == other.filename, "Cannot compare sources from different files")
return if @start == other.start
(@stop or @start) < (other.stop or other.start)
else @start < other.start
__le: (other)=>
assert(@filename == other.filename, "Cannot compare sources from different files")
return if @start == other.start
(@stop or @start) <= (other.stop or other.start)
else @start <= other.start
__add: (offset)=>
if type(self) == 'number'
offset, self = self, offset
else if type(offset) != 'number' then error("Cannot add Source and #{type(offset)}")
return Source(@filename, @start+offset, @stop)
class Code
new: (...)=>
@bits = {}
@add(...)
@from: (source, ...)=>
inst = self(...)
if type(source) == 'string'
source = Source\from_string(source)
inst.source = source
return inst
@is_instance: (x)=> type(x) == 'table' and x.__class == @
text: =>
if @__str == nil
buff, indent = {}, 0
{:match, :gsub, :rep} = string
for i,b in ipairs @bits
if type(b) == 'string'
if spaces = match(b, "\n([ ]*)[^\n]*$")
indent = #spaces
else
b = b\text!
if indent > 0
b = gsub(b, "\n([^\n])", "\n"..rep(" ", indent).."%1")
buff[#buff+1] = b
@__str = concat(buff, "")
return @__str
last: (n)=>
if @__str
return @__str\sub(-n, -1)
last = ""
for i=#@bits,1,-1
b = @bits[i]
last = (type(b) == 'string' and b\sub(-(n-#last)) or b\last(n-#last))..last
break if #last == n
return last
first: (n)=>
if @__str
return @__str\sub(1,n)
first = ""
for b in *@bits
first ..= type(b) == 'string' and b\sub(1,n-#first+1) or b\first(n-#first+1)
break if #first == n
return first
__tostring: => @text!
__len: =>
if @__str
return #@__str
len = 0
for b in *@bits
len += #b
return len
match: (...)=> @text!\match(...)
gmatch: (...)=> @text!\gmatch(...)
dirty: =>
@__str = nil
@_trailing_line_len = nil
-- Multi-line only goes from false->true, since there is no API for removing bits
@_is_multiline = nil if @_is_multiline == false
add: (...)=>
n = select("#",...)
match = string.match
bits = @bits
for i=1,n
b = select(i, ...)
assert(b, "code bit is nil")
assert(not Source\is_instance(b), "code bit is a Source")
if b == '' then continue
bits[#bits+1] = b
@dirty!
trailing_line_len: =>
if @_trailing_line_len == nil
@_trailing_line_len = #@text!\match("[^\n]*$")
return @_trailing_line_len
is_multiline: =>
if @_is_multiline == nil
match = string.match
@_is_multiline = false
for b in *@bits
if type(b) == 'string'
if match(b, '\n')
@_is_multiline = true
break
elseif b\is_multiline!
@_is_multiline = true
break
return @_is_multiline
concat_add: (values, joiner, wrapping_joiner)=>
wrapping_joiner or= joiner
match = string.match
bits = @bits
line_len = 0
for i=1,#values
b = values[i]
if i > 1
if line_len > 80
bits[#bits+1] = wrapping_joiner
line_len = 0
else
bits[#bits+1] = joiner
bits[#bits+1] = b
b.dirty = error if type(b) != 'string'
line = b\match("\n([^\n]*)$")
if line
line_len = #line
else
line_len += #b
@dirty!
prepend: (...)=>
n = select("#",...)
bits = @bits
for i=#bits+n,n+1,-1
bits[i] = bits[i-n]
for i=1,n
b = select(i, ...)
b.dirty = error if type(b) != 'string'
bits[i] = b
@dirty!
parenthesize: =>
@prepend "("
@add ")"
class LuaCode extends Code
__tostring: Code.__tostring
__len: Code.__len
new: (...)=>
super ...
@free_vars = {}
add_free_vars: (vars)=>
return unless #vars > 0
seen = {[v]:true for v in *@free_vars}
for var in *vars
assert type(var) == 'string'
unless seen[var]
@free_vars[#@free_vars+1] = var
seen[var] = true
@dirty!
-- Names of actions this code defines. These are also free variables, but assigning
-- a variable doesn't change an action with the same name in an enclosing scope.
add_action_names: (names)=>
@action_names or= {}
for name in *names
@action_names[#@action_names+1] = name
@add_free_vars names
-- Free variables are tracked up to the nearest function boundary (a node with
-- @is_scope set). Variables inside a function belong to it until declare_locals
-- decides where they live.
remove_free_vars: (vars=nil)=>
vars or= @get_free_vars!
return unless #vars > 0
removals = {}
for var in *vars
assert type(var) == 'string'
removals[var] = true
stack = {self}
while #stack > 0
lua, stack[#stack] = stack[#stack], nil
for i=#lua.free_vars,1,-1
free_var = lua.free_vars[i]
if removals[free_var]
remove lua.free_vars, i
for b in *lua.bits
if type(b) != 'string' and not b.is_scope
stack[#stack+1] = b
@dirty!
get_free_vars: =>
vars, seen = {}, {}
gather_from = =>
for var in *@free_vars
unless seen[var]
seen[var] = true
vars[#vars+1] = var
for bit in *@bits
unless type(bit) == 'string' or bit.is_scope
gather_from bit
gather_from self
return vars
-- Add "local" declarations for this code (normally a whole file). A variable that
-- gets assigned refers to the variable with that name in an enclosing scope, if one
-- has been declared by that point in the code. Otherwise, it's a new local of the
-- function (or file) where it's first assigned. Variables in @forced_locals (from
-- (local:)) are always new locals, and variables in @public_vars (from (public:))
-- live in the module's environment instead of being locals.
declare_locals: (to_declare=nil)=>
if to_declare
if #to_declare > 0
@remove_free_vars to_declare
@prepend "local #{concat to_declare, ", "};\n"
return to_declare
fail = (lua, msg)->
{:fail_at} = require('nomsu_compiler')
if lua.source then fail_at(lua.source, msg)
else error(msg, 0)
-- Whether each visible name is a "var" or an "action"
public = {}
actions_in = (lua, actions={})->
for name in *(lua.action_names or {}) do actions[name] = true
for b in *lua.bits
actions_in(b, actions) unless type(b) == 'string' or b.is_scope
return actions
find_public = (lua, in_function)->
if lua.public_vars
if in_function
fail lua, "Compile error: (public:) can't be used inside an action or "..
"function. Hint: Put it at the top level of the file instead."
actions = actions_in(lua)
for v in *lua.public_vars do public[v] = actions[v] and "action" or "var"
for b in *lua.bits
unless type(b) == 'string'
find_public(b, in_function or b.is_scope)
find_public self, false
declare_scope = (scope, outer_visible)->
visible = setmetatable({}, {__index:outer_visible})
if scope.scope_args
for a in *scope.scope_args do visible[a] = "var"
declared, declared_set = {}, {}
declare = (v, kind)->
unless declared_set[v]
declared[#declared+1] = v
declared_set[v] = true
visible[v] = kind
walk = (lua)->
-- The text of this code is cached, and will change if anything inside
-- it gets declarations added
lua.__str, lua._trailing_line_len, lua._is_multiline = nil, nil, nil
if lua.forced_locals
shadowing = {}
for v in *lua.forced_locals
if public[v] and not scope.is_scope
fail lua, "Compile error: #{v} can't be both local and public."
-- A name that's already visible gets a new local right where the
-- (local:) is, which hides the other one until the end of the
-- enclosing Lua block (like an `if` or loop body)
if visible[v] then shadowing[#shadowing+1] = v
else declare v, "var"
lua\prepend "local #{concat shadowing, ", "};\n" if #shadowing > 0
lua.forced_locals = nil
actions = {name,true for name in *(lua.action_names or {})}
for v in *lua.free_vars
if actions[v]
declare(v, "action") unless visible[v]
elseif visible[v] != "var"
declare(v, "var")
lua.free_vars = {}
for b in *lua.bits
unless type(b) == 'string'
if b.is_scope then declare_scope(b, visible)
else walk(b)
walk scope
if #declared > 0
insert scope.bits, 1, "local #{concat declared, ", "};\n"
return declared
return declare_scope(self, public)
make_offset_table: =>
assert @source, "This code doesn't have a source"
-- Return a mapping from output (lua) character number to input (nomsu) character number
lua_to_nomsu, nomsu_to_lua = {}, {}
walk = (lua, pos)->
for b in *lua.bits
if type(b) == 'string'
if lua.source
lua_to_nomsu[pos] = lua.source.start
nomsu_to_lua[lua.source.start] = pos
else
walk b, pos
pos += #b
walk self, 1
return {
nomsu_filename:@source.filename
lua_filename:tostring(@source)..".lua", lua_file:@text!
:lua_to_nomsu, :nomsu_to_lua
}
parenthesize: =>
@prepend "("
@add ")"
class NomsuCode extends Code
__tostring: Code.__tostring
__len: Code.__len
Code.__base.add_1_joined_with = assert Code.__base.concat_add
Code.__base.add = assert Code.__base.add
return {:Code, :NomsuCode, :LuaCode, :Source}
|