Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file: -- http://angg.twu.net/LUA/LpegRex2.lua.html -- http://angg.twu.net/LUA/LpegRex2.lua -- (find-angg "LUA/LpegRex2.lua") -- Author: Eduardo Ochs <eduardoochs@gmail.com> -- -- Tests for lpegrex. -- See: (find-es "lpeg" "lpegrex") -- (find-lpegrexpage) -- (find-lpegrextext) -- -- (defun l () (interactive) (find-angg "LUA/LpegRex2.lua")) loadlpegrex() -- (find-angg "LUA/lua50init.lua" "loadlpegrex") -- See: (find-angg "LUA/Rect.lua" "Rect") -- (find-angg "LUA/Rect.lua" "SynTree") Ast = Class { type = "Ast", torect = function (o) if type(o) == "number" then return Rect.from(o) end if type(o) == "string" then return Rect.from(o) end if type(o) == "table" then local out = Ast.torect(o[#o]):syn1() for i=#o-2,1,-2 do local lowerleft = Ast.torect(o[i]) local left = lowerleft:syn1(o[i+1]) local left_ = left:pad0(1, left:width()+2, "_") out = left_ .. out end return out end PP("rectfromast can't handle this", o) end, simplify = function (o) if type(o) ~= "table" then return o end if #o == 1 then return Ast.simplify(o[1]) end return Ast(map(Ast.simplify, o)) end, __tostring = function (o) return o:tostring(o) end, __index = { tostring = function (o) return Ast.torect(o):tostring() end, }, } --[==[ * (eepitch-lua52) * (eepitch-kill) * (eepitch-lua52) dofile "LpegRex2.lua" = Ast.torect(42) = Ast.torect({42}) a = {2, "+", {5, "*", 6}, "-", 4} b = Ast.simplify(a) = b = b[2] = b[3] --]==] __options = {} t0 = function (str) local gram,subj = str:match("^(.-)::%s*(.*)$") local patt = lpegrex.compile(gram, {__options = __options}) ast,errlabel,errpos = patt:match(subj) end t1 = function (str) t0(str); PP(ast) end t2 = function (str) t0(str) asts = ast and Ast.simplify(ast) print(asts) end --[==[ * (eepitch-lua52) * (eepitch-kill) * (eepitch-lua52) dofile "LpegRex2.lua" t2 [=[ top <-- addexpr norp <-- num / "(" addexpr ")" addexpr <== mulexpr ({"+"} mulexpr)* mulexpr <== norp ({"*"} norp)* num <== {%d+} :: (1+2*3*4+5)*6+7*(8*9) ]=] = asts[1] = asts[2] = asts[3] PPPV(ast) PPPV(asts) --]==] -- Local Variables: -- coding: utf-8-unix -- End: