✨ (engine): 在本机直接执行 Legado 书源规则(CSS/XPath/JSONPath/正则/URL 构造)

This commit is contained in:
garfield committed 2026-12-04 00:33:36 +08:00
1 parent 485d0160a1
commit f73f9c4f39
13 files changed
+4503

No files matched your search

@@ -0,0 +1,540 @@
--[[--
Java 风格正则(回溯匹配,按 Unicode 码点)。Legado 规则里的 ## 替换、: 正则规则、$1 取组都走这里。
支持:字符类(含 \uXXXX、汉字区间)、分组(捕获 / 非捕获 / 命名)、| 、* + ? {n,m} 及惰性、^ $ \b \A \z、
前后向断言、反向引用、\d\w\s、(?i)(?s)(?m)。不支持 Unicode 属性类与集合交集。
@module moonsource_legadorule.regex
--]]
local Regex = {}
local function decode(s)
local cps, pos, n, i, len = {}, {}, 0, 1, #s
local byte = string.byte
while i <= len do
local c, l, cp = byte(s, i), 1, nil
if c < 0x80 then
cp = c
elseif c >= 0xF0 then
cp = (c % 8) * 0x40000 + ((byte(s, i + 1) or 128) % 64) * 0x1000
+ ((byte(s, i + 2) or 128) % 64) * 64 + (byte(s, i + 3) or 128) % 64
l = 4
elseif c >= 0xE0 then
cp = (c % 16) * 0x1000 + ((byte(s, i + 1) or 128) % 64) * 64 + (byte(s, i + 2) or 128) % 64
l = 3
elseif c >= 0xC0 then
cp = (c % 32) * 64 + (byte(s, i + 1) or 128) % 64
l = 2
else
cp = c
end
n = n + 1
cps[n], pos[n] = cp, i
i = i + l
end
pos[n + 1] = len + 1
return cps, pos, n
end
local function encode(cp)
if cp < 0x80 then return string.char(cp) end
if cp < 0x800 then return string.char(0xC0 + math.floor(cp / 64), 0x80 + cp % 64) end
if cp < 0x10000 then
return string.char(0xE0 + math.floor(cp / 0x1000), 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
end
return string.char(0xF0 + math.floor(cp / 0x40000), 0x80 + math.floor(cp / 0x1000) % 64,
0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
end
local function isDigit(c) return c >= 48 and c <= 57 end
local function isWord(c)
return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
end
local function isSpace(c) return c == 32 or (c >= 9 and c <= 13) or c == 0xA0 or c == 0x3000 end
local function fold(c) if c >= 65 and c <= 90 then return c + 32 end return c end
local CLASS = {
d = isDigit, w = isWord, s = isSpace,
D = function(c) return not isDigit(c) end,
W = function(c) return not isWord(c) end,
S = function(c) return not isSpace(c) end,
}
---------------------------------------------------------------- 解析
local Parser = {}
Parser.__index = Parser
local function perr(msg) error("regex: " .. msg, 0) end
function Parser:peek() return self.p[self.i] end
function Parser:escape()
local c = self.p[self.i]
self.i = self.i + 1
if not c then perr("dangling backslash") end
local ch = encode(c)
if CLASS[ch] then return { class = CLASS[ch] } end
if ch == "n" then return { cp = 10 } end
if ch == "t" then return { cp = 9 } end
if ch == "r" then return { cp = 13 } end
if ch == "f" then return { cp = 12 } end
if ch == "u" then
local hex = ""
for _ = 1, 4 do hex = hex .. encode(self.p[self.i] or 48); self.i = self.i + 1 end
return { cp = tonumber(hex, 16) or 0 }
end
if ch == "x" then
local hex = ""
for _ = 1, 2 do hex = hex .. encode(self.p[self.i] or 48); self.i = self.i + 1 end
return { cp = tonumber(hex, 16) or 0 }
end
return { cp = c, esc = ch }
end
function Parser:set()
local neg = false
if self:peek() == 94 then neg = true; self.i = self.i + 1 end
local items, first = {}, true
while true do
local c = self:peek()
if not c then perr("unclosed [") end
self.i = self.i + 1
if c == 93 and not first then break end
first = false
local item
if c == 92 then
item = self:escape()
if item.esc == "b" then item = { cp = 8 } end
elseif c == 91 then
-- 嵌套集合按并集处理
local inner = self:set()
item = { class = inner.test }
else
item = { cp = c }
end
if item.cp and self:peek() == 45 and self.p[self.i + 1] and self.p[self.i + 1] ~= 93 then
self.i = self.i + 1
local hi = self:peek()
self.i = self.i + 1
if hi == 92 then hi = self:escape().cp end
items[#items + 1] = { lo = item.cp, hi = hi }
elseif item.cp then
items[#items + 1] = { lo = item.cp, hi = item.cp }
else
items[#items + 1] = { class = item.class }
end
end
local icase = self.flags.i
local function raw(c)
for k = 1, #items do
local it = items[k]
if it.class then
if it.class(c) then return true end
elseif c >= it.lo and c <= it.hi then
return true
end
end
return false
end
local function test(c)
local hit = raw(c)
if not hit and icase then
if c >= 97 and c <= 122 then hit = raw(c - 32) elseif c >= 65 and c <= 90 then hit = raw(c + 32) end
end
return hit ~= neg
end
return { type = "set", test = test }
end
function Parser:int()
local s = ""
while self:peek() and isDigit(self:peek()) do s = s .. encode(self:peek()); self.i = self.i + 1 end
return tonumber(s)
end
function Parser:atom()
local c = self.p[self.i]
self.i = self.i + 1
if c == 40 then -- (
local node
if self:peek() == 63 then
self.i = self.i + 1
local d = self:peek()
self.i = self.i + 1
if d == 58 then
node = { type = "group", n = self:alt() }
elseif d == 61 or d == 33 then
node = { type = "look", neg = d == 33, n = self:alt() }
elseif d == 60 and (self:peek() == 61 or self:peek() == 33) then
local neg = self:peek() == 33
self.i = self.i + 1
node = { type = "lookbehind", neg = neg, n = self:alt() }
elseif d == 60 or d == 80 then
if d == 80 then self.i = self.i + 1 end
local name = ""
while self:peek() and self:peek() ~= 62 do name = name .. encode(self:peek()); self.i = self.i + 1 end
self.i = self.i + 1
self.ngroups = self.ngroups + 1
local idx = self.ngroups
self.names[name] = idx
node = { type = "cap", idx = idx, n = self:alt() }
else
-- 行内标志 (?i) (?s:...)
self.i = self.i - 1
local on = true
while self:peek() and self:peek() ~= 41 and self:peek() ~= 58 do
local f = encode(self:peek())
if f == "-" then on = false else self.flags[f] = on or nil end
self.i = self.i + 1
end
if self:peek() == 41 then
self.i = self.i + 1
return { type = "empty" }
end
self.i = self.i + 1
node = { type = "group", n = self:alt() }
end
else
self.ngroups = self.ngroups + 1
local idx = self.ngroups
node = { type = "cap", idx = idx, n = self:alt() }
end
if self:peek() ~= 41 then perr("unclosed (") end
self.i = self.i + 1
return node
elseif c == 91 then
return self:set()
elseif c == 46 then
return { type = "any", dotall = self.flags.s }
elseif c == 94 then
return { type = "bol", multi = self.flags.m }
elseif c == 36 then
return { type = "eol", multi = self.flags.m }
elseif c == 92 then
local e = self:escape()
if e.class then return { type = "set", test = e.class } end
local ch = e.esc
if ch == "b" then return { type = "wordb" } end
if ch == "B" then return { type = "wordb", neg = true } end
if ch == "A" then return { type = "bol" } end
if ch == "z" or ch == "Z" then return { type = "eol" } end
if ch and isDigit(e.cp) and ch ~= "0" then return { type = "backref", idx = tonumber(ch), icase = self.flags.i } end
return { type = "char", cp = e.cp, icase = self.flags.i }
end
return { type = "char", cp = c, icase = self.flags.i }
end
function Parser:quant(node)
local c = self:peek()
local min, max
if c == 42 then min, max = 0, math.huge
elseif c == 43 then min, max = 1, math.huge
elseif c == 63 then min, max = 0, 1
elseif c == 123 then
local save = self.i
self.i = self.i + 1
local a = self:int()
local b = a
if a and self:peek() == 44 then
self.i = self.i + 1
b = self:int() or math.huge
end
if not a or self:peek() ~= 125 then
self.i = save
return node
end
min, max = a, b
else
return node
end
self.i = self.i + 1
local lazy = false
if self:peek() == 63 then lazy = true; self.i = self.i + 1 elseif self:peek() == 43 then self.i = self.i + 1 end
return self:quant({ type = "rep", n = node, min = min, max = max, lazy = lazy })
end
function Parser:seq()
local list = {}
while true do
local c = self:peek()
if not c or c == 124 or c == 41 then break end
local atom = self:atom()
if c == 42 or c == 43 or c == 63 then perr("dangling quantifier") end
list[#list + 1] = self:quant(atom)
end
return { type = "seq", list = list }
end
function Parser:alt()
local branches = { self:seq() }
while self:peek() == 124 do
self.i = self.i + 1
branches[#branches + 1] = self:seq()
end
if #branches == 1 then return branches[1] end
return { type = "alt", list = branches }
end
---------------------------------------------------------------- 编译成闭包
local compile
local function single(node)
local t = node.type
if t == "char" then
local cp = node.cp
if node.icase then
local f = fold(cp)
return function(c) return fold(c) == f end
end
return function(c) return c == cp end
elseif t == "any" then
if node.dotall then return function() return true end end
return function(c) return c ~= 10 and c ~= 13 end
elseif t == "set" then
return node.test
end
end
function compile(node, nxt)
local t = node.type
local test = single(node)
if test then
return function(S, i)
local c = S.c[i]
if c and test(c) then return nxt(S, i + 1) end
end
elseif t == "empty" then
return nxt
elseif t == "seq" then
local m = nxt
for k = #node.list, 1, -1 do m = compile(node.list[k], m) end
return m
elseif t == "group" then
return compile(node.n, nxt)
elseif t == "alt" then
local ms = {}
for k, b in ipairs(node.list) do ms[k] = compile(b, nxt) end
return function(S, i)
for k = 1, #ms do
local r = ms[k](S, i)
if r then return r end
end
end
elseif t == "cap" then
local idx = node.idx
local inner = compile(node.n, function(S, i)
local os, oe = S.s[idx], S.e[idx]
S.s[idx], S.e[idx] = S.ts[idx], i
local r = nxt(S, i)
if not r then S.s[idx], S.e[idx] = os, oe end
return r
end)
return function(S, i)
local old = S.ts[idx]
S.ts[idx] = i
local r = inner(S, i)
if not r then S.ts[idx] = old end
return r
end
elseif t == "rep" then
local min, max, lazy = node.min, node.max, node.lazy
local one = single(node.n)
if one then
return function(S, i)
local c, n = S.c, 0
if lazy then
while n < min do
local x = c[i + n]
if not (x and one(x)) then return end
n = n + 1
end
while true do
local r = nxt(S, i + n)
if r then return r end
local x = c[i + n]
if n >= max or not (x and one(x)) then return end
n = n + 1
end
end
while n < max do
local x = c[i + n]
if not (x and one(x)) then break end
n = n + 1
end
while n >= min do
local r = nxt(S, i + n)
if r then return r end
n = n - 1
end
end
end
local body = compile(node.n, function(S, j)
local k = S.ks[S.kn]
S.kn = S.kn - 1
local r = k(S, j)
S.kn = S.kn + 1
S.ks[S.kn] = k
return r
end)
local function try(S, i, count)
local function more()
if count >= max then return end
local k = function(S2, j)
if j == i and count >= min then return end
return try(S2, j, count + 1)
end
S.kn = S.kn + 1
S.ks[S.kn] = k
local r = body(S, i)
if not r then S.kn = S.kn - 1 end
return r
end
if lazy then
if count >= min then
local r = nxt(S, i)
if r then return r end
end
return more()
end
local r = more()
if r then return r end
if count >= min then return nxt(S, i) end
end
return function(S, i) return try(S, i, 0) end
elseif t == "bol" then
return function(S, i)
if i == 1 or (node.multi and S.c[i - 1] == 10) then return nxt(S, i) end
end
elseif t == "eol" then
return function(S, i)
local n = S.n
if i == n + 1 or (i == n and S.c[i] == 10) or (node.multi and S.c[i] == 10) then return nxt(S, i) end
end
elseif t == "wordb" then
return function(S, i)
local a = i > 1 and isWord(S.c[i - 1])
local b = S.c[i] and isWord(S.c[i])
if ((a and not b) or (b and not a)) ~= (node.neg or false) then return nxt(S, i) end
end
elseif t == "backref" then
local idx = node.idx
return function(S, i)
local s, e = S.s[idx], S.e[idx]
if not s then return end
local len = e - s
for k = 0, len - 1 do
local a, b = S.c[s + k], S.c[i + k]
if not b or (a ~= b and not (node.icase and fold(a) == fold(b))) then return end
end
return nxt(S, i + len)
end
elseif t == "look" then
local sub = compile(node.n, function(_, i) return i end)
return function(S, i)
if (sub(S, i) ~= nil) ~= node.neg then return nxt(S, i) end
end
elseif t == "lookbehind" then
local sub = compile(node.n, function(S, j) if j == S.target then return j end end)
return function(S, i)
local hit = false
local old = S.target
S.target = i
for st = i, 1, -1 do
if sub(S, st) then hit = true; break end
end
S.target = old
if hit ~= node.neg then return nxt(S, i) end
end
end
error("regex: bad node " .. tostring(t))
end
---------------------------------------------------------------- 对外接口
local cache = {}
--- 编译;同一 pattern 缓存。语法错误抛错。
function Regex.compile(pattern)
local hit = cache[pattern]
if hit then return hit end
local p = decode(pattern)
local parser = setmetatable({ p = p, i = 1, flags = {}, ngroups = 0, names = {} }, Parser)
local ast = parser:alt()
if parser.i <= #p then perr("unmatched )") end
local re = {
ngroups = parser.ngroups,
names = parser.names,
run = compile(ast, function(_, i) return i end),
}
cache[pattern] = re
return re
end
local function exec(re, subject, from)
local S = subject
for st = from, S.n + 1 do
S.s, S.e, S.ts, S.ks, S.kn = {}, {}, {}, {}, 0
local stop = re.run(S, st)
if stop then
local m = { s = S.pos[st], e = S.pos[stop], cs = st, ce = stop }
m[0] = S.str:sub(m.s, m.e - 1)
for g = 1, re.ngroups do
if S.s[g] then m[g] = S.str:sub(S.pos[S.s[g]], S.pos[S.e[g]] - 1) end
end
return m
end
end
end
local function prepare(str)
local cps, pos, n = decode(str)
return { c = cps, pos = pos, n = n, str = str }
end
--- 首个匹配;返回 m(m[0] 整体,m[1..] 各组,m.s/m.e 为字节区间 [s,e)),无匹配返回 nil。
function Regex.find(pattern, str)
return exec(Regex.compile(pattern), prepare(str), 1)
end
--- 所有不重叠匹配。
function Regex.all(pattern, str)
local re, S, out, from = Regex.compile(pattern), prepare(str), {}, 1
while from <= S.n + 1 do
local m = exec(re, S, from)
if not m then break end
out[#out + 1] = m
from = m.ce > m.cs and m.ce or m.ce + 1
end
return out
end
--- 展开替换串里的 $n;\$ 取字面量。
local function expand(repl, m)
return (repl:gsub("(\\?)%$(%d)", function(esc, d)
if esc == "\\" then return "$" .. d end
return m[tonumber(d)] or ""
end))
end
--- 替换(只首个或全部)。replacement 里 $1 引用组。
function Regex.replace(pattern, str, repl, first)
local ms = first and { Regex.find(pattern, str) } or Regex.all(pattern, str)
if #ms == 0 then return str end
local out, last = {}, 1
for _, m in ipairs(ms) do
out[#out + 1] = str:sub(last, m.s - 1)
out[#out + 1] = expand(repl, m)
last = m.e
end
out[#out + 1] = str:sub(last)
return table.concat(out)
end
--- 是否整串之内含匹配。
function Regex.test(pattern, str)
return Regex.find(pattern, str) ~= nil
end
return Regex