|
Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file:
-- http://angg.twu.net/LUA/precedenceparser.lua
-- http://angg.twu.net/LUA/precedenceparser.lua.html
-- (find-angg "LUA/precedenceparser.lua")
--
-- (find-lua51manualw3m "")
-- (find-books "__comp/__comp.el" "ierusalimschy")
-- (find-pil2page 8 "Contents")
-- (find-pil2text 8 "Contents")
userocks()
require "re"
Expr = Class {
type = "Expr",
__tostring = function (e) return mapconcat(tostring, e, " ") end,
__index = {
},
}
Aop = Class {
type = "Aop",
__tostring = function (op) return op[4] end,
__index = {
reduce = function (op, stack)
local aop, e = stack[#stack-1], stack[#stack]
local newe = Expr {e, aop}
stack[#stack-1], stack[#stack] = newe, nil
end,
push = function (op, stack)
table.insert(stack, op)
end,
},
}
Bop = Class {
type = "Bop",
__tostring = function (op) return op[4] end,
__index = {
reduce = function (op, stack)
local e1, bop, e2 = stack[#stack-2], stack[#stack-1], stack[#stack]
local newe = Expr {e1, e2, bop}
stack[#stack-2], stack[#stack-1], stack[#stack] = newe, nil
end,
push = function (op, stack)
while #stack > 1 and stack[#stack-1][3] > op[1] do
stack[#stack-1]:reduce(stack)
end
table.insert(stack, op)
end,
},
}
Cop = Class {
type = "Cop",
__tostring = function (op) return op[4] end,
__index = {
reduce = function (op, stack)
local e, cop = stack[#stack-1], stack[#stack]
local newe = Expr {e, cop}
stack[#stack-1], stack[#stack] = newe, nil
end,
push = function (op, stack)
while #stack > 1 and stack[#stack-1][3] > op[1] do
stack[#stack-1]:reduce(stack)
end
table.insert(stack, op)
stack[#stack]:reduce(stack)
end,
},
}
aops = {} -- prefix operators
bops = {} -- binary operators
bops = {} -- postfix operators
newop = function (str)
local l,op,r,forth = unpack(split(str))
l = tonumber(l)
r = tonumber(r)
forth = forth or op
if not l and r then aops[op] = Aop {l,op,r,forth} end
if l and r then bops[op] = Bop {l,op,r,forth} end
if l and not r then cops[op] = Cop {l,op,r,forth} end
-- print(l,op,r,forth)
end
newop "10 + 11"
newop "10 - 11"
newop "20 * 21"
newop "20 / 21"
newop "30 ^ 31"
newop " . - 15 u-"
Stack = Class {
type = "Stack",
__tostring = function (s) return mapconcat(tostring, s, "\n") end,
__index = {
},
}
stk = {}
stk = Stack {}
pa = function (op) aops[op]:push(stk) end
pb = function (op) bops[op]:push(stk) end
pc = function (op) cops[op]:push(stk) end
pn = function (n) table.insert(stk, n) end
--[[
* (eepitch-lua51)
* (eepitch-kill)
* (eepitch-lua51)
dofile "precedenceparser.lua"
PP(bops)
= bops["+"]
stk = {}
stk = Stack {}
pn(2)
pb"*"
pn(3)
pb"+"
pn(4)
pb"*"
pn(5)
= stk
while #stk > 1 do stk[#stk-1]:reduce(stk) end
= stk
--]]
-- Local Variables:
-- coding: raw-text-unix
-- End: