|
Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file:
-- http://angg.twu.net/LUA/Lpeg4.lua.html
-- http://angg.twu.net/LUA/Lpeg4.lua
-- (find-angg "LUA/Lpeg4.lua")
-- Author: Eduardo Ochs <eduardoochs@gmail.com>
--
-- (defun e3 () (interactive) (find-angg "LUA/Lpeg3.lua"))
-- (defun e () (interactive) (find-angg "LUA/Lpeg4.lua"))
lpeg = require("lpeg")
-- (find-es "lpeg" "pegdebug")
Path.prepend("path", "~/usrc/PegDebug/src/?.lua")
pegdebug = require("pegdebug")
-- (find-es "lpeg" "globals")
B,C,P,R,S,V = lpeg.B,lpeg.C,lpeg.P,lpeg.R,lpeg.S,lpeg.V
Cb,Cc,Cf,Cg = lpeg.Cb,lpeg.Cc,lpeg.Cf,lpeg.Cg
Cp,Cs,Ct = lpeg.Cp,lpeg.Cs,lpeg.Ct
Carg,Cmt = lpeg.Carg,lpeg.Cmt
-- (find-angg "LUA/LpegRex1.lua" "rectfromast")
rectfromast = 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 = rectfromast(o[#o]):syn1()
for i=#o-2,1,-2 do
local lowerleft = rectfromast(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
-- Abstract Syntax Trees
Ast = Class {
type = "Ast",
from = function (...) return Ast({...}) end,
fromsimp = function (...)
local L = {...} -- if ... has a single argument
if #L == 1 then return L[1] end -- then return a simplified result.
return Ast.from(...)
end,
__tostring = function (o) return rectfromast(o):tostring() end,
__index = {
},
}
-- (find-es "lpeg" "lpeg-quickref")
pskip = P(" ")^0
pnum = (R("09")^1):C() * pskip
plit = function (str) return P(str) * pskip end
ptok = function (str) return P(str):C() * pskip end
palphanum = R("AZ","az")
Token = Class {
type = "Token",
opstr1 = function (str)
if str:match("^[A-Za-z]+$")
then return (P(str)*-alphanum):C() * pskip
else return P(str):C() * pskip
end
end,
opfromlist = function (A, i, j)
local op = Token.opstr1(A[i])
for k=i+1,j do op = op + Token.opstr1(A[k]) end
return op
end,
assocwith = function (bigstr)
local A = split(bigstr)
local v1 = V(A[1])
local v2 = V(A[2]) * pskip
local op = Token.opfromlist(A, 3, #A)
return (v2 * (op * v2)^0) / Ast.fromsimp
end,
__index = {
},
}
pexpr = P({
"add",
add = Token.assocwith("add mul + -"),
mul = Token.assocwith("mul norp * /"),
norp = pnum + plit("(") * V("add") * plit(")"),
})
--[[
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
dofile "Lpeg4.lua"
= pexpr:match( "1*2 + 3 + 4*5*6 + 7")
= pexpr:match("(1*2 + 3 + 4*5*6 + 7)")
= pexpr:match("(1*2 + 3 + 4*5*6 + 7) * 8")
PPP(pexpr:match( "1*2 + 3 + 4*5*6 + 7"))
--]]
-- Local Variables:
-- coding: utf-8-unix
-- End: