aboutsummaryrefslogtreecommitdiff
path: root/src/glum.lua
blob: a50382a0203c7b496221443b9e26577b56e853d2 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
--[[
This moudle allows you to minify gLua code
    Use:
        local x = require("glum.lua")
        local str ="
        --Here is some code to be minified!\n
        for a=1,10,2 do\n
            print(a)\n
        end
        "
        print(x.minify(str))
    Dependencies:
        lua-parser
]]

local strreps = {
    ["\\"] = "\\\\",
    ["\a"] = "\\a",
    ["\b"] = "\\b",
    ["\f"] = "\\f",
    ["\n"] = "\\n",
    ["\r"] = "\\r",
    ["\t"] = "\\t",
    ["\v"] = "\\v",
    ["\""] = "\\\""
}
local function safe_str (str)
    local tep = {}
    --print("--------------Safeing str:" .. str)
    for c in str:gmatch(".") do
        if strreps[c] ~= nil then
            --print(string.format("safeing %s:%s",c,strreps[c]))
        end
        tep[#tep + 1] = strreps[c] or c
    end
    local output = table.concat(tep)
    --print("-------------Returning string:" .. output)
    return output
end


local parser = dofile("../src/parser.lua")
local lpeg = require("lpeg")
lpeg.locale(lpeg)

local glum = {}

--Creates a deep copy of a table
local function deepcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == "table" then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[deepcopy(orig_key)] = deepcopy(orig_value)
        end
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end

--A list of reserved words that cannot be used as variable names
local nonames = {"if","for","end","do","local","then","else","elseif","return","goto","function","nil","false","true","repeat","return","break","and","or","not","in","repeat","until","while","continue"}
local reservednames = {}
for k,v in ipairs(nonames) do
    reservednames[v] = true
end

--A function that generates the next valid variable name from the last valid variable name.
local varchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY"
local function getnextvarname(lname)
    local place = string.find(lname,"[" .. varchars .. "]")
    local length = string.len(lname)
    if place == nil then
        return string.rep("a", length + 1)
    else
        local lbyte = string.byte(lname,place)
        local newchar = string.char(lbyte + (lbyte < 122 and 1 or -57))
        local after = string.sub(lname, place + 1, length)
        local before = string.rep("a", place-1)
        local output = before .. newchar .. after
        while reservednames[output] or _G[output] do
            output = getnextvarname(output)
        end
        return output
    end
end

--A debugging function, a replacement for glua PrintTable
local function printtable(tbl, tabset)
    tabset = tabset or 0
    for k,v in pairs(tbl) do
        for i = 0,tabset do io.write("\t") end
        io.write(k .. ":")
        if type(v) == "table" then
            io.write("\n")
            printtable(v, tabset + 1)
        else
            io.write(tostring(v) .. "\n")
        end
    end
end

local syntax = {}

local function stringfor(ast,tbl)
    if syntax[ast.tag] ~= nil then
        return syntax[ast.tag](ast,tbl)
    else
        error("Attempted to use unknown tag type:" .. ast.tag)
    end
end
--Abandon all hope, ye who enter here
--Refer to the comments at the top of parser.lua for what each function should do.
--If willox ever decides to add new language features, they need to be added to BOTH parser.lua and here.
syntax = {
    ["Call"] = function(ast,tbl)
        local exprname = stringfor(ast[1],tbl)
        local argnames = {}
        local cursor = 2
        while ast[cursor] ~= nil do
            argnames[cursor-1] = stringfor(ast[cursor],tbl)
            cursor = cursor + 1
        end
        local argstring = table.concat(argnames,",")
        local ostring = table.concat({exprname,"(",argstring,")"})
        return ostring
    end,
    ["Invoke"] = function(ast,tbl)
        local func = stringfor(ast[1],tbl)
        local invargs = {}
        for k = 3,#ast do
            invargs[#invargs + 1] = stringfor(ast[k],tbl)
        end
        local output = func
        local inv
        --A short hand if it's a simple thing
        if ast[2].tag == "String" and #ast[2][1] < (#func + 2) then
            inv = ast[2][1]
            output = output .. ":" .. inv .. "("
        else
            inv = stringfor(ast[2],tbl)
            output = output .. "[" .. inv .. "](" .. func .. ","
        end
        output = output .. table.concat(invargs,",")
        output = output .. ")"
        return output
    end,
    ["String"] = function(ast,tbl)
        if tbl.strings[ast[1]] == nil then
            local fsstr = safe_str(ast[1])
            local fstr = string.format("\"%s\"",fsstr)
            --fstr = safe_str(fstr)
            --local lstr = string.format("return %q",ast[1])
            print("Loading string:" .. fstr)
            local rstring = loadstring("return " .. fstr)
            --print("Returning string:")
            --print(ast[1])
            --print("fsstr")
            --print(fsstr)
            --print("formated:")
            --print(string.format("%q",ast[1]))
            local rstrs = rstring()
            --assert(rstrs == ast[1],string.format("%q is not equal to %q",rstrs,ast[1]))
            --print(string.format("%q is equal to %s:%s", rstrs, ast[1],fsstr))
            --print("Returning " .. fstr .. " from " .. ast[1] .. " out of " .. fsstr)
            return fstr
            --return string.format("%q",ast[1])
            --return safe_str(string.format("%q",ast[1]))
            --return string.format("%q",safe_str(ast[1]))
            --[[
            if #ast[1] < 4 then return "\""..ast[1].."\"" end
            local nextvar = getnextvarname(tbl.lname)
            tbl.lname = nextvar
            tbl.strings[ast[1] ] = nextvar
            return nextvar
            ]]
        end
        return tbl.strings[ast[1]]
    end,
    ["Id"] = function(ast,tbl)
        if tbl.ids[ast[1]] == nil then
            return ast[1]
        end
        return tbl.ids[ast[1]]
    end,
    ["Index"] = function(ast,tbl)
        local globalvar = stringfor(ast[1],tbl)
        if ast[2].tag == "String" then
             return table.concat({globalvar, ".", ast[2][1]})
        end
        return table.concat({globalvar, "[", stringfor(ast[2],tbl), "]"})
    end,
    ["Paren"] = function(ast,tbl)
        return table.concat({"(" .. stringfor(ast[1],tbl) .. ")"})
    end,
    ["Dots"] = function(ast,tbl)
        return "..."
    end,
    ["Forin"] = function(ast,tbl)
        local nadd = deepcopy(tbl)
        local nl = stringfor(ast[1],nadd)
        local el = stringfor(ast[2],nadd)
        local code = stringfor(ast[3],nadd)
        local output = table.concat({" for ", nl, " in ", el, " do ", code, " end "})
        return output
    end,
    ["NameList"] = function(ast,tbl)
        local outputtbl = {}
        for k = 1,#ast do
            if ast[k].tag ~= "Id" then
                outputtbl[#outputtbl + 1] = stringfor(ast[k])
            else
                if tbl.ids[ast[k][1]] ~= nil then
                    outputtbl[#outputtbl + 1] = tbl.ids[ast[k][1]]
                else
                    local newvar = getnextvarname(tbl.lname)
                    tbl.lname = newvar
                    tbl.ids[ast[k][1]] = newvar
                    outputtbl[#outputtbl + 1] = newvar
                end
            end
        end
        local output = table.concat(outputtbl, ",")
        return output
    end,
    ["ExpList"] = function(ast,tbl)
        local exprs = {}
        for k = 1,#ast do
            exprs[#exprs + 1] = stringfor(ast[k],tbl)
        end
        return table.concat(exprs,",")
    end,
    ["Nil"] = function(ast,tbl)
        return "nil"
    end,
    ["True"] = function(ast,tbl)
        return "true"
    end,
    ["False"] = function(ast,tbl)
        return "false"
    end,
    ["Return"] = function(ast,tbl)
        local retargs = {}
        for k,v in ipairs(ast) do
            retargs[k] = stringfor(v,tbl)
        end
        return " return " .. table.concat(retargs,",")
    end,
    ["If"] = function(ast,tbl)

        local expr1 = stringfor(ast[1],tbl)
        local block1 = stringfor(ast[2],tbl)
        local codeblocks = {}
        codeblocks[#codeblocks + 1] = table.concat({" if ",expr1," then ",block1})

        for k = 3,#ast-1,2 do
            local expr = stringfor(ast[k],tbl)
            local block = stringfor(ast[k + 1],tbl)
            codeblocks[#codeblocks + 1] = table.concat({" elseif " , expr , " then " , block})
        end

        if #ast % 2 == 1 then
            local block = stringfor(ast[#ast],tbl)
            codeblocks[#codeblocks + 1] = " else " .. block
        end
        codeblocks[#codeblocks + 1] = " end "
        return table.concat(codeblocks)
    end,
    ["Fornum"] = function(ast,tbl)
        local var
        if ast[1].tag == "Id" then
            if tbl.ids[ast[1][1]] ~= nil then
                var = tbl.ids[ast[1][1]]
            else
                local newvar = getnextvarname(tbl.lname)
                tbl.lname = newvar
                tbl.ids[ast[1][1]] = newvar
                var = newvar
            end
        else
            var = stringfor(ast[1],tbl)
        end
        local start = stringfor(ast[2],tbl)
        local endnum = stringfor(ast[3],tbl)
        local incrementer = 1
        local code = ""
        if ast[4].tag ~= "Block" then -- incrementer
            incrementer = stringfor(ast[4],tbl)
            code = stringfor(ast[5],tbl)
        else
            code = stringfor(ast[4],tbl)
        end
        local incstr = incrementer ~= 1 and ("," .. incrementer) or ""
        tbl[var] = nil
        return table.concat({" for ",var,"=",start,",",endnum,incstr," do ",code," end "})
    end,
    ["Op"] = function(ast,tbl)
        local binop = {
            ["or"] = " or ",    ["and"] = " and ",
            ["ne"] = "~=",      ["eq"] = "==",
            ["le"] = "<=",      ["ge"] = ">=",
            ["lt"] = "<",       ["gt"] = ">",
            ["bor"] = "|",      ["bxor"] = "~",
            ["band"] = "&",     ["shl"] = "<<",
            ["shr"] = ">>",     ["concat"] = "..",
            ["add"] = "+",      ["sub"] = "-",
            ["mul"] = "*",      ["div"] = "/",
            ["mod"] = "%",      ["pow"] = "^",
        }
        local uniop = {
            ["len"] = "#",      ["not"] = " not ",
            ["unm"] = "-",      ["bnot"] = "~",
        }
        local opname = ast[1]
        if uniop[opname] ~= nil then
            local rhs = stringfor(ast[2],tbl)
            return uniop[opname] .. rhs
        end
        local lhs = stringfor(ast[2],tbl)
        local rhs = stringfor(ast[3],tbl)
        local output = table.concat({lhs,binop[opname],rhs})
        return output
    end,
    ["Pair"] = function(ast,tbl)
        local lhs = stringfor(ast[1],tbl)
        local rhs = stringfor(ast[2],tbl)
        return table.concat({"[",lhs,"]=",rhs})
    end,
    ["Table"] = function(ast,tbl)
        local fields = {}
        for k = 1, #ast do
            fields[#fields + 1] = stringfor(ast[k],tbl)
        end
        local fieldstr = table.concat(fields,",")
        return table.concat({"{",fieldstr,"}"})
    end,
    ["Number"] = function(ast,tbl)
        return ast[1]
    end,
    ["Local"] = function(ast,tbl)
        local tblcpy = tbl
        local lhs,rhs = stringfor(ast[1],tblcpy),nil
        if ast[2].tag ~= nil then
            rhs = stringfor(ast[2],tblcpy)
        end
        local output = "local " .. lhs
        if ast[2].tag ~= nil then
            output = output .. "=" .. rhs .. ";"
        end
        return output
    end,
    ["VarList"] = function(ast,tbl)
        local vars = {}
        for k = 1,#ast do
            vars[#vars + 1] = stringfor(ast[k],tbl)
        end
        return table.concat(vars,",")
    end,
    ["Set"] = function(ast,tbl)
        local lhs = {}
        local a1 = ast[1].tag ~= nil and ast[1] or ast[1][1]
        for k = 1,#ast[1] do
            lhs[#lhs + 1] = stringfor(a1,tbl)
        end
        local rhs = {}
        local a2 = ast[2].tag ~= nil and ast[2] or ast[2][1]
        for k = 1,#ast[2] do
            rhs[#rhs + 1] = stringfor(a2,tbl)
        end
        local ostring = table.concat(lhs,",")
        ostring = ostring .. "=" .. table.concat(rhs,",")
        return ostring .. ";"
    end,
    ["Label"] = function(ast,tbl)
        if tbl.nids[ast[1]] == nil then
            local nextvar = getnextvarname(tbl.lname)
            tbl.lname = nextvar
            tbl.nids[ast[1]] = nextvar
        end
        return "::" .. tbl.nids[ast[1]] .. "::"
    end,
    ["Goto"] = function(ast,tbl)
        if tbl.nids[ast[1]] == nil then
            local nextvar = getnextvarname(tbl.lname)
            tbl.lname = nextvar
            tbl.nids[ast[1]] = nextvar
        end
        return " goto " .. tbl.nids[ast[1]]
    end,
    ["Function"] = function(ast,tbl)
        local funcargs = ast[1].tag ~= nil and stringfor(ast[1],tbl) or ""
        local code = stringfor(ast[2],tbl)
        return table.concat({" function(",funcargs,")",code," end "})
    end,
    ["Localrec"] = function(ast,tbl)
        local ident
        if tbl.ids[ast[1][1]] ~= nil then
            ident = tbl.ids[ast[1][1]]
        else
            local newvar = getnextvarname(tbl.lname)
            tbl.lname = newvar
            tbl.ids[ast[1][1][1]] = newvar
            ident = newvar
        end
        local argstr = ast[2][1][1].tag ~= nil and stringfor(ast[2][1][1],tbl) or ""
        local expr = stringfor(ast[2][1][2],tbl)
        return table.concat({" local function ",ident,"(",argstr,")",expr," end "})
    end,
    ["Continue"] = function(ast,tbl)
        return " continue "
    end,
    ["While"] = function(ast,tbl)
        local expr = stringfor(ast[1],tbl)
        local block = stringfor(ast[2],tbl)
        local output = table.concat({" while " , expr , " do " , block , " end "})
        return output
    end,
    ["Break"] = function(ast,tbl)
        return " break "
    end,
    ["Block"] = function(ast,oldtbl)
        local tbl = deepcopy(oldtbl)
        oldtbl.block = true
        local codeblocks = {}
        for k = 1,#ast do
            codeblocks[#codeblocks + 1] = stringfor(ast[k],tbl)
        end
        local code = table.concat(codeblocks)
        local lhss,rhss = {},{}
        for k,v in pairs(tbl.strings) do
            if oldtbl.strings[k] ~= tbl.strings[k] then
                lhss[#lhss + 1] = v
                rhss[#rhss + 1] = string.format("%q",k)
            end
        end
        local inits = ""
        local lhs = " local " .. table.concat(lhss,",")
        local rhs = table.concat(rhss,",")
        if string.len(rhs) > 0 then
            inits = table.concat({lhs, "=", rhs, ";"})
        end
        return inits .. code
    end,
}



--Removes extra spaces and duplicated ; from a string
local function removespaces(str)
    local removables = {
        {"%s*%)%s*","%)"}, --Spaces before or after )
        {"%s*%(%s*","%("}, --Spaces before or after (
        {"%s*;%s*",";"}, --Spaces before or after ;
        {"%s*,%s*",","}, --Spaces before or after ,
        {";+",";"}, --Multiple ; in a row
        {"^%s*",""}, --Spaces at the beginning of the file
        {"%s*$",""}, --Spaces at the end of the file
        {"%s+"," "}, --Multiple spaces in a row
    }
    --Order is important
    for k,v in ipairs(removables) do
        str = string.gsub(str,v[1],v[2])
    end
    return str
end

--Compress the string, and adds a little decompression code at the top.
local function compress(str)

end

glum.minify = function(str, name)
    name = name or "anonymous"
    local ast, error_msg = parser.parse(str, name)
    if not ast then
        error(error_msg)
    end
    local localvar = {
        ["strings"] = {},
        ["ids"] = {},
        ["lname"] = "",
        ["nids"] = {},
    }
    --printtable(ast)
    return --[[removespaces(]]stringfor(ast,localvar)--)
end

return glum