Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file: -- http://anggtwu.net/LUA/Pratt2.lua.html -- http://anggtwu.net/LUA/Pratt2.lua -- (find-angg "LUA/Pratt2.lua") -- Author: Eduardo Ochs <eduardoochs@gmail.com> -- -- (defun p2 () (interactive) (find-angg "LUA/Pratt2.lua")) -- (defun e1 () (interactive) (find-angg "LUA/ELpeg1.lua")) -- (find-angg "LUA/ELpeg1.lua") -- (find-angg "LUA/Tree1.lua") -- (find-es "pratt") require "ELpeg1" -- (find-angg "LUA/ELpeg1.lua") ptable = VTable { ["num"] = HTable {lbp="err", rbp="err"}, ["end"] = HTable {lbp=0, rbp="err"}, ["+"] = HTable {lbp=10, rbp=10}, ["*"] = HTable {lbp=20, rbp=20}, ["^"] = HTable {lbp=30, rbp=30}, } mkbin = function (a, op, b) return AST {[0]=op, a, b} end GetTokens = Class { type = "GetTokens", from = function (str) local isnum = function (s) return s:match("^[0-9]+$") end local f = function (s) return isnum(s) and s+0 or s end return GetTokens {pos=1, unpack(map(f, split(str)))} end, __tostring = function (gt) local f = function (i) return format(" %d:%s", i, mytostring(gt[i])) end return format("pos=%d %s", gt.pos, mapconcat(f, seq(1,#gt))) end, __index = { raw = function (gt) return gt[gt.pos] end, here = function (gt) return type(gt:raw())=="number" and "num" or gt:raw() end, pt = function (gt) return ptable[gt:here()] end, lbp = function (gt) return gt:pt().lbp end, -- accept_1 = function (gt) local tk=gt:raw(); gt.pos=gt.pos+1; return tk end, accept_opb = function (gt,rbp) return gt:accept_1(), gt:accept_b(rbp) end, accept_b = function (gt,rbp) return gt:accept_1() end, -- stub accept_a = function (gt,rbp) return gt:add_opbs(rbp, gt:accept_1()) end, -- add_opb = function (gt,rbp,a) local op,b = gt:accept_opb(rbp) return mkbin(a,op,b) end, add_opbs = function (gt,rbp,a) while gt:lbp() > rbp do a = gt:add_opb(rbp,a) end return a end, }, } --[[ * (eepitch-lua51) * (eepitch-kill) * (eepitch-lua51) dofile "Pratt2.lua" = ptable tks = GetTokens.from(" 2 * 3 + 4 ^ 5 end ") = tks = tks:raw() = tks:here() = tks:pt() tks.pos = tks.pos + 1 = tks:raw() tks = GetTokens.from(" 200 * 300 + 400 ^ 500 end ") = tks:accept_a() a0 = tks:accept_1() a0 = tks:add_opbs(0, a0) = a0 = a0 = tks = tks:lbp() a0 = tks:add_opb(0, a0) = tks = tks:lbp() a0 = tks:add_opb(0, a0) = tks:lbp() a0 = tks:add_opb(0, a0) = tks:lbp() a0 = tks:add_opbs(0, a0) = a0 --]] -- Local Variables: -- coding: utf-8-unix -- End: