--[[--
XPath 1.0 子集解释器(跑在 html.lua 的 DOM 上):路径 / // . .. @attr * text() node()、
child descendant self parent ancestor following-sibling preceding-sibling attribute 等轴、
谓词、and/or/比较/加减乘除/并集 |,以及常用函数(contains starts-with not count position last
normalize-space concat substring* translate string-length name 等)。
@module moonsource_legadorule.xpath
--]]
local Html = require("moonsource_legadorule.html")
local XPath = {}
---------------------------------------------------------------- 词法
local function tokenize(src)
local toks, i = {}, 1
local function push(t, v) toks[#toks + 1] = { t = t, v = v } end
while i <= #src do
local c = src:sub(i, i)
if c:find("%s") then
i = i + 1
elseif c == '"' or c == "'" then
local e = src:find(c, i + 1, true)
if not e then error("xpath: unterminated string", 0) end
push("str", src:sub(i + 1, e - 1))
i = e + 1
elseif c:find("%d") or (c == "." and src:sub(i + 1, i + 1):find("%d")) then
local n = src:match("^%d*%.?%d*", i)
push("num", tonumber(n))
i = i + #n
elseif src:sub(i, i + 1) == "//" then push("//"); i = i + 2
elseif src:sub(i, i + 1) == ".." then push(".."); i = i + 2
elseif src:sub(i, i + 1) == "::" then push("::"); i = i + 2
elseif src:sub(i, i + 1) == "!=" or src:sub(i, i + 1) == "<=" or src:sub(i, i + 1) == ">=" then
push(src:sub(i, i + 1)); i = i + 2
elseif c:find("[/%.@%(%)%[%],|=<>%+%-%*]") then
push(c); i = i + 1
elseif c:find("[%a_]") or c:byte() >= 128 then
local name = src:match("^[%w_%-\128-\255]+:?[%w_%-\128-\255]*", i)
-- 轴名后面是 ::,不能吞进名字
local axis = src:match("^([%a%-]+)::", i)
if axis then name = axis end
push("name", name)
i = i + #name
else
error("xpath: unexpected '" .. c .. "'", 0)
end
end
push("eof")
return toks
end
---------------------------------------------------------------- 语法
local P = {}
P.__index = P
function P:peek(k) return self.toks[self.i + (k or 0)] end
function P:next() self.i = self.i + 1; return self.toks[self.i - 1] end
function P:accept(t)
if self:peek().t == t then return self:next() end
end
function P:expect(t)
if not self:accept(t) then error("xpath: expected " .. t, 0) end
end
function P:isOp(name) return self:peek().t == "name" and self:peek().v == name end
local AXES = {
child = 1, descendant = 1, ["descendant-or-self"] = 1, self = 1, parent = 1, ancestor = 1,
["ancestor-or-self"] = 1, ["following-sibling"] = 1, ["preceding-sibling"] = 1, attribute = 1,
following = 1, preceding = 1,
}
function P:step()
if self:accept(".") then return { axis = "self", test = { kind = "node" }, preds = {} } end
if self:accept("..") then return { axis = "parent", test = { kind = "node" }, preds = {} } end
local axis = "child"
if self:accept("@") then
axis = "attribute"
elseif self:peek().t == "name" and self:peek(1).t == "::" then
axis = self:next().v
if not AXES[axis] then error("xpath: unknown axis " .. axis, 0) end
self:next()
end
local test
if self:accept("*") then
test = { kind = "name", name = "*" }
else
local t = self:next()
if t.t ~= "name" then error("xpath: bad step", 0) end
if self:peek().t == "(" and (t.v == "text" or t.v == "node" or t.v == "comment") then
self:next()
self:expect(")")
test = { kind = t.v }
else
test = { kind = "name", name = t.v:lower() }
end
end
local preds = {}
while self:accept("[") do
preds[#preds + 1] = self:expr()
self:expect("]")
end
return { axis = axis, test = test, preds = preds }
end
local DOS = { axis = "descendant-or-self", test = { kind = "node" }, preds = {} }
function P:path()
local steps, absolute = {}, false
if self:peek().t == "/" then
self:next()
absolute = true
local t = self:peek().t
if t ~= "name" and t ~= "*" and t ~= "@" and t ~= "." and t ~= ".." then
return { type = "path", absolute = true, steps = steps }
end
elseif self:accept("//") then
absolute = true
steps[1] = DOS
end
steps[#steps + 1] = self:step()
while true do
if self:accept("/") then
steps[#steps + 1] = self:step()
elseif self:accept("//") then
steps[#steps + 1] = DOS
steps[#steps + 1] = self:step()
else
break
end
end
return { type = "path", absolute = absolute, steps = steps }
end
function P:primary()
local t = self:peek()
if t.t == "str" then self:next(); return { type = "lit", v = t.v } end
if t.t == "num" then self:next(); return { type = "lit", v = t.v } end
if t.t == "(" then
self:next()
local e = self:expr()
self:expect(")")
return e
end
if t.t == "name" and self:peek(1).t == "(" and t.v ~= "text" and t.v ~= "node" and t.v ~= "comment" then
self:next(); self:next()
local args = {}
if not self:accept(")") then
repeat args[#args + 1] = self:expr() until not self:accept(",")
self:expect(")")
end
return { type = "call", name = t.v, args = args }
end
return nil
end
function P:filtered()
local prim = self:primary()
if not prim then return self:path() end
local preds = {}
while self:accept("[") do
preds[#preds + 1] = self:expr()
self:expect("]")
end
local node = prim
if #preds > 0 then node = { type = "filter", base = prim, preds = preds } end
if self:peek().t == "/" or self:peek().t == "//" then
local steps = {}
while true do
if self:accept("/") then
steps[#steps + 1] = self:step()
elseif self:accept("//") then
steps[#steps + 1] = DOS
steps[#steps + 1] = self:step()
else
break
end
end
return { type = "path", base = node, steps = steps }
end
return node
end
function P:union()
local left = self:filtered()
while self:accept("|") do left = { type = "union", a = left, b = self:filtered() } end
return left
end
function P:unary()
if self:accept("-") then return { type = "neg", e = self:unary() } end
return self:union()
end
function P:mul()
local left = self:unary()
while true do
if self:accept("*") then left = { type = "bin", op = "*", a = left, b = self:unary() }
elseif self:isOp("div") then self:next(); left = { type = "bin", op = "/", a = left, b = self:unary() }
elseif self:isOp("mod") then self:next(); left = { type = "bin", op = "%", a = left, b = self:unary() }
else return left end
end
end
function P:add()
local left = self:mul()
while true do
if self:accept("+") then left = { type = "bin", op = "+", a = left, b = self:mul() }
elseif self:accept("-") then left = { type = "bin", op = "-", a = left, b = self:mul() }
else return left end
end
end
function P:rel()
local left = self:add()
while true do
local t = self:peek().t
if t == "<" or t == ">" or t == "<=" or t == ">=" then
self:next()
left = { type = "cmp", op = t, a = left, b = self:add() }
else return left end
end
end
function P:eq()
local left = self:rel()
while true do
local t = self:peek().t
if t == "=" or t == "!=" then
self:next()
left = { type = "cmp", op = t, a = left, b = self:rel() }
else return left end
end
end
function P:andExpr()
local left = self:eq()
while self:isOp("and") do self:next(); left = { type = "and", a = left, b = self:eq() } end
return left
end
function P:expr()
local left = self:andExpr()
while self:isOp("or") do self:next(); left = { type = "or", a = left, b = self:andExpr() } end
return left
end
---------------------------------------------------------------- 求值
local function docOf(n)
while n.parent do n = n.parent end
return n
end
local function attrNode(el, name)
el.attrNodes = el.attrNodes or {}
local a = el.attrNodes[name]
if not a then
local idx = 0
for k, nm in ipairs(el.attrOrder) do if nm == name then idx = k end end
a = { type = "attr", name = name, value = el.attrs[name], parent = el, order = el.order + idx / 10000 }
el.attrNodes[name] = a
end
return a
end
local function stringValue(n)
if n.type == "attr" then return n.value end
return Html.textContent(n)
end
local function isNodeset(v) return type(v) == "table" and v.nodeset end
local function toStr(v)
if isNodeset(v) then return v[1] and stringValue(v[1]) or "" end
if type(v) == "number" then
if v == math.floor(v) and math.abs(v) < 1e15 then return string.format("%d", v) end
return tostring(v)
end
if type(v) == "boolean" then return tostring(v) end
return v
end
local function toNum(v)
if type(v) == "number" then return v end
if type(v) == "boolean" then return v and 1 or 0 end
return tonumber((toStr(v):gsub("^%s+", ""):gsub("%s+$", ""))) or 0 / 0
end
local function toBool(v)
if isNodeset(v) then return #v > 0 end
if type(v) == "string" then return v ~= "" end
if type(v) == "number" then return v ~= 0 and v == v end
return v
end
local function nodeset(list)
list.nodeset = true
return list
end
local function sortUnique(list)
local seen, out = {}, {}
for _, n in ipairs(list) do
if not seen[n] then seen[n] = true; out[#out + 1] = n end
end
table.sort(out, function(a, b) return a.order < b.order end)
return nodeset(out)
end
local function axisNodes(axis, n, out)
if axis == "child" then
for _, c in ipairs(n.children or {}) do out[#out + 1] = c end
elseif axis == "descendant" or axis == "descendant-or-self" then
if axis == "descendant-or-self" then out[#out + 1] = n end
local function walk(x)
for _, c in ipairs(x.children or {}) do
out[#out + 1] = c
walk(c)
end
end
walk(n)
elseif axis == "self" then
out[#out + 1] = n
elseif axis == "parent" then
if n.parent then out[#out + 1] = n.parent end
elseif axis == "ancestor" or axis == "ancestor-or-self" then
if axis == "ancestor-or-self" then out[#out + 1] = n end
local p = n.parent
while p do out[#out + 1] = p; p = p.parent end
elseif axis == "following-sibling" or axis == "preceding-sibling" then
local parent = n.parent
if parent and n.type ~= "attr" then
local sibs, idx = parent.children, 0
for k, s in ipairs(sibs) do if s == n then idx = k end end
if axis == "following-sibling" then
for k = idx + 1, #sibs do out[#out + 1] = sibs[k] end
else
for k = idx - 1, 1, -1 do out[#out + 1] = sibs[k] end
end
end
elseif axis == "attribute" then
if n.type == "el" then
for _, name in ipairs(n.attrOrder) do out[#out + 1] = attrNode(n, name) end
end
elseif axis == "following" or axis == "preceding" then
local all = {}
axisNodes("descendant", docOf(n), all)
for _, x in ipairs(all) do
if axis == "following" and x.order > n.order then
local anc, p = false, x.parent
while p do if p == n then anc = true end p = p.parent end
if not anc then out[#out + 1] = x end
elseif axis == "preceding" and x.order < n.order then
local anc, p = false, n.parent
while p do if p == x then anc = true end p = p.parent end
if not anc then out[#out + 1] = x end
end
end
end
end
local function testNode(test, axis, n)
if test.kind == "node" then return true end
if test.kind == "text" then return n.type == "text" end
if test.kind == "comment" then return false end
if axis == "attribute" then
return n.type == "attr" and (test.name == "*" or n.name == test.name)
end
return n.type == "el" and (test.name == "*" or n.tag == test.name)
end
local eval
local function applyPreds(list, preds, ctx)
for _, pred in ipairs(preds) do
local kept, size = {}, #list
for k, n in ipairs(list) do
local v = eval(pred, { node = n, pos = k, size = size, root = ctx.root })
local ok
if type(v) == "number" then ok = v == k else ok = toBool(v) end
if ok then kept[#kept + 1] = n end
end
list = kept
end
return list
end
local function runSteps(start, steps, ctx)
local current = start
for _, step in ipairs(steps) do
local gathered = {}
for _, n in ipairs(current) do
local cand = {}
axisNodes(step.axis, n, cand)
local filtered = {}
for _, c in ipairs(cand) do
if testNode(step.test, step.axis, c) then filtered[#filtered + 1] = c end
end
filtered = applyPreds(filtered, step.preds, ctx)
for _, c in ipairs(filtered) do gathered[#gathered + 1] = c end
end
current = sortUnique(gathered)
end
return current
end
local function compare(op, a, b)
local function cmp(x, y)
if op == "=" or op == "!=" then
local r
if type(x) == "number" or type(y) == "number" then r = toNum(x) == toNum(y)
elseif type(x) == "boolean" or type(y) == "boolean" then r = toBool(x) == toBool(y)
else r = toStr(x) == toStr(y) end
if op == "=" then return r end
return not r
end
local nx, ny = toNum(x), toNum(y)
if op == "<" then return nx < ny elseif op == ">" then return nx > ny
elseif op == "<=" then return nx <= ny else return nx >= ny end
end
local sa, sb = isNodeset(a), isNodeset(b)
if sa and sb then
for _, x in ipairs(a) do for _, y in ipairs(b) do
if cmp(stringValue(x), stringValue(y)) then return true end
end end
return false
elseif sa then
if type(b) == "boolean" then return cmp(#a > 0, b) end
for _, x in ipairs(a) do if cmp(stringValue(x), b) then return true end end
return false
elseif sb then
if type(a) == "boolean" then return cmp(a, #b > 0) end
for _, y in ipairs(b) do if cmp(a, stringValue(y)) then return true end end
return false
end
return cmp(a, b)
end
local function normalize(s) return (s:gsub("%s+", " "):gsub("^ ", ""):gsub(" $", "")) end
local FN = {
last = function(ctx) return ctx.size end,
position = function(ctx) return ctx.pos end,
count = function(_, v) return #v end,
["not"] = function(_, v) return not toBool(v) end,
["true"] = function() return true end,
["false"] = function() return false end,
boolean = function(_, v) return toBool(v) end,
string = function(ctx, v) if v == nil then return stringValue(ctx.node) end return toStr(v) end,
number = function(ctx, v) if v == nil then return toNum(stringValue(ctx.node)) end return toNum(v) end,
["normalize-space"] = function(ctx, v)
return normalize(v == nil and stringValue(ctx.node) or toStr(v))
end,
["string-length"] = function(ctx, v)
local s = v == nil and stringValue(ctx.node) or toStr(v)
return select(2, s:gsub("[^\128-\191]", ""))
end,
contains = function(_, a, b) return toStr(a):find(toStr(b), 1, true) ~= nil end,
["starts-with"] = function(_, a, b) local t = toStr(b); return toStr(a):sub(1, #t) == t end,
["ends-with"] = function(_, a, b) local t = toStr(b); return t == "" or toStr(a):sub(-#t) == t end,
["substring-before"] = function(_, a, b)
local s, t = toStr(a), toStr(b)
local i = s:find(t, 1, true)
return i and s:sub(1, i - 1) or ""
end,
["substring-after"] = function(_, a, b)
local s, t = toStr(a), toStr(b)
local i, e = s:find(t, 1, true)
return i and s:sub(e + 1) or ""
end,
substring = function(_, a, b, c)
local s = toStr(a)
local from = math.floor(toNum(b) + 0.5)
local to = c and from + math.floor(toNum(c) + 0.5) - 1 or #s
return s:sub(math.max(from, 1), to)
end,
concat = function(_, ...)
local out = {}
for k, v in ipairs({ ... }) do out[k] = toStr(v) end
return table.concat(out)
end,
translate = function(_, a, b, c)
local s, from, to = toStr(a), toStr(b), toStr(c)
return (s:gsub(".", function(ch)
local i = from:find(ch, 1, true)
if not i then return nil end
return to:sub(i, i)
end))
end,
name = function(ctx, v)
local n = v and v[1] or ctx.node
return n.tag or n.name or ""
end,
sum = function(_, v)
local t = 0
for _, n in ipairs(v) do t = t + toNum(stringValue(n)) end
return t
end,
floor = function(_, v) return math.floor(toNum(v)) end,
ceiling = function(_, v) return math.ceil(toNum(v)) end,
round = function(_, v) return math.floor(toNum(v) + 0.5) end,
}
FN["local-name"] = FN.name
function eval(e, ctx)
local t = e.type
if t == "lit" then return e.v end
if t == "path" then
local start
if e.base then
start = eval(e.base, ctx)
if not isNodeset(start) then error("xpath: path on non-nodeset", 0) end
elseif e.absolute then
start = nodeset({ docOf(ctx.node) })
else
start = nodeset({ ctx.node })
end
return runSteps(start, e.steps, ctx)
elseif t == "filter" then
local base = eval(e.base, ctx)
return nodeset(applyPreds(base, e.preds, ctx))
elseif t == "union" then
local a, b = eval(e.a, ctx), eval(e.b, ctx)
local all = {}
for _, n in ipairs(a) do all[#all + 1] = n end
for _, n in ipairs(b) do all[#all + 1] = n end
return sortUnique(all)
elseif t == "and" then
return toBool(eval(e.a, ctx)) and toBool(eval(e.b, ctx))
elseif t == "or" then
return toBool(eval(e.a, ctx)) or toBool(eval(e.b, ctx))
elseif t == "cmp" then
return compare(e.op, eval(e.a, ctx), eval(e.b, ctx))
elseif t == "neg" then
return -toNum(eval(e.e, ctx))
elseif t == "bin" then
local a, b = toNum(eval(e.a, ctx)), toNum(eval(e.b, ctx))
if e.op == "+" then return a + b elseif e.op == "-" then return a - b
elseif e.op == "*" then return a * b elseif e.op == "/" then return a / b end
return a % b
elseif t == "call" then
local fn = FN[e.name]
if not fn then error("xpath: unsupported function " .. e.name, 0) end
local args = {}
for k, a in ipairs(e.args) do args[k] = eval(a, ctx) end
return fn(ctx, unpack(args, 1, #e.args))
end
error("xpath: bad node", 0)
end
local cache = {}
local function compile(src)
local ast = cache[src]
if ast then return ast end
local p = setmetatable({ toks = tokenize(src), i = 1 }, P)
ast = p:expr()
if p:peek().t ~= "eof" then error("xpath: trailing tokens", 0) end
cache[src] = ast
return ast
end
--- 求值。返回 nodes(节点数组,含属性 / 文本节点)或标量(字符串 / 数字 / 布尔)。
--- 表达式语法错误抛字符串错误。
function XPath.evaluate(context, src)
local v = eval(compile(src), { node = context, pos = 1, size = 1 })
if isNodeset(v) then return v, true end
return v, false
end
--- 节点转字符串:属性取值、文本取文本、元素取 textContent。
function XPath.string(n)
return stringValue(n)
end
XPath.toStr = toStr
return XPath