--[[-- CSS 选择器(jsoup 方言):标签 / #id / .class / 属性 [a=v ^= $= *= ~=(正则) !=] / 组合符 空格 > + ~ / 伪类 :contains :containsOwn :matches :has :not :first-child :last-child :nth-child :nth-of-type :eq :lt :gt :first :last :empty 等。 @module moonsource_legadorule.css --]] local Html = require("moonsource_legadorule.html") local Regex = require("moonsource_legadorule.regex") local Css = {} local IDENT = "^[%w_%-\128-\255]+" local function elems(parent) if parent.elems then return parent.elems end local list = {} for _, c in ipairs(parent.children) do if c.type == "el" then list[#list + 1] = c c.eidx = #list end end parent.elems = list return list end local function position(el, ofType, fromEnd) local parent = el.parent if not parent then return 1, 1 end local list = elems(parent) local pos, total = 0, 0 for _, e in ipairs(list) do if not ofType or e.tag == el.tag then total = total + 1 if e == el then pos = total end end end if fromEnd then return total - pos + 1, total end return pos, total end local function nth(expr) expr = expr:gsub("%s", ""):lower() if expr == "odd" then return 2, 1 end if expr == "even" then return 2, 0 end local a, b = expr:match("^([+-]?%d*)n([+-]?%d*)$") if a then a = (a == "" or a == "+") and 1 or (a == "-" and -1 or tonumber(a)) return a, tonumber(b) or 0 end return 0, tonumber(expr) or 0 end local function nthMatch(pos, a, b) if a == 0 then return pos == b end local n = (pos - b) / a return n >= 0 and n == math.floor(n) end local compileList local function pseudo(name, arg) local function own(el) return Html.ownText(el):lower() end if name == "contains" then local t = arg:lower() return function(el) return Html.text(el):lower():find(t, 1, true) ~= nil end elseif name == "containsown" then local t = arg:lower() return function(el) return own(el):find(t, 1, true) ~= nil end elseif name == "matches" then return function(el) return Regex.test(arg, Html.text(el)) end elseif name == "matchesown" then return function(el) return Regex.test(arg, Html.ownText(el)) end elseif name == "not" then local inner = compileList(arg) return function(el) return not Css.matches(el, inner) end elseif name == "has" then local inner = compileList(arg) return function(el) local found = false local function walk(n) for _, c in ipairs(n.children or {}) do if found then return end if c.type == "el" then if Css.matches(c, inner) then found = true return end walk(c) end end end walk(el) return found end elseif name == "first-child" or name == "first" then return function(el) return (position(el)) == 1 end elseif name == "last-child" or name == "last" then return function(el) return (position(el, false, true)) == 1 end elseif name == "only-child" then return function(el) local _, t = position(el); return t == 1 end elseif name == "first-of-type" then return function(el) return (position(el, true)) == 1 end elseif name == "last-of-type" then return function(el) return (position(el, true, true)) == 1 end elseif name == "nth-child" or name == "nth-last-child" or name == "nth-of-type" or name == "nth-last-of-type" then local a, b = nth(arg) local ofType, fromEnd = name:find("of%-type") ~= nil, name:find("last") ~= nil return function(el) return nthMatch((position(el, ofType, fromEnd)), a, b) end elseif name == "eq" or name == "nth" then local n = tonumber(arg) or 0 return function(el) return position(el) - 1 == n end elseif name == "lt" then local n = tonumber(arg) or 0 return function(el) return position(el) - 1 < n end elseif name == "gt" then local n = tonumber(arg) or 0 return function(el) return position(el) - 1 > n end elseif name == "empty" then return function(el) for _, c in ipairs(el.children) do if c.type == "el" or (c.type == "text" and c.text:find("%S")) then return false end end return true end elseif name == "root" then return function(el) return el.parent and el.parent.type == "doc" end end error("selector: unsupported :" .. name, 0) end local function attrTest(body) local name, op, value = body:match("^%s*([^%s=~^$*!|]+)%s*([~^$*!|]?=)%s*(.-)%s*$") if not name then return function(el) return el.attrs[(body:gsub("%s", ""):lower())] ~= nil end end name = name:lower() value = value:gsub("^([\"'])(.*)%1$", "%2") local lower = value:lower() return function(el) local v = el.attrs[name] if v == nil then return op == "!=" end local lv = v:lower() if op == "=" then return lv == lower elseif op == "^=" then return lv:sub(1, #lower) == lower elseif op == "$=" then return lower == "" or lv:sub(-#lower) == lower elseif op == "*=" then return lv:find(lower, 1, true) ~= nil elseif op == "!=" then return lv ~= lower elseif op == "|=" then return lv == lower or lv:sub(1, #lower + 1) == lower .. "-" else return Regex.test(value, v) end end end -- 读到与 open 配对的右括号,返回括号内文本与下一位置 local function balanced(s, i, open, close) local depth, j, q = 0, i, nil while j <= #s do local c = s:sub(j, j) if q then if c == q then q = nil end elseif c == '"' or c == "'" then q = c elseif c == open then depth = depth + 1 elseif c == close then depth = depth - 1 if depth == 0 then return s:sub(i + 1, j - 1), j + 1 end end j = j + 1 end error("selector: unbalanced " .. open, 0) end local function splitTop(s) local out, depth, q, start = {}, 0, nil, 1 for i = 1, #s do local c = s:sub(i, i) if q then if c == q then q = nil end elseif c == '"' or c == "'" then q = c elseif c == "(" or c == "[" then depth = depth + 1 elseif c == ")" or c == "]" then depth = depth - 1 elseif c == "," and depth == 0 then out[#out + 1] = s:sub(start, i - 1) start = i + 1 end end out[#out + 1] = s:sub(start) return out end local function compileComplex(sel) local parts, i, comb = {}, 1, " " sel = sel:gsub("^%s+", ""):gsub("%s+$", "") while i <= #sel do local tests, tag = {}, nil local start = i while i <= #sel do local c = sel:sub(i, i) if c == "*" then i = i + 1 elseif c == "#" then local id = sel:match(IDENT, i + 1) if not id then error("selector: bad #", 0) end i = i + 1 + #id tests[#tests + 1] = function(el) return el.attrs.id == id end elseif c == "." then local cls = sel:match(IDENT, i + 1) if not cls then error("selector: bad .", 0) end i = i + 1 + #cls tests[#tests + 1] = function(el) local v = el.attrs.class return v ~= nil and (" " .. v:gsub("%s+", " ") .. " "):find(" " .. cls .. " ", 1, true) ~= nil end elseif c == "[" then local body body, i = balanced(sel, i, "[", "]") tests[#tests + 1] = attrTest(body) elseif c == ":" then local name = sel:match("^[%w_%-]+", i + 1) if not name then error("selector: bad :", 0) end i = i + 1 + #name local arg = "" if sel:sub(i, i) == "(" then arg, i = balanced(sel, i, "(", ")") end arg = arg:gsub("^%s+", ""):gsub("%s+$", "") arg = arg:gsub("^([\"'])(.*)%1$", "%2") tests[#tests + 1] = pseudo(name:lower(), arg) else local t = sel:match(IDENT, i) if not t or i ~= start then break end tag = t:lower() i = i + #t end end if i == start then error("selector: unexpected '" .. sel:sub(i, i) .. "'", 0) end parts[#parts + 1] = { comb = comb, tag = tag, tests = tests } -- 组合符 local ws = sel:match("^%s*", i) i = i + #ws local c = sel:sub(i, i) if c == ">" or c == "+" or c == "~" then comb = c i = i + 1 i = i + #sel:match("^%s*", i) elseif i <= #sel then comb = " " end end return parts end function compileList(sel) local list = {} for _, g in ipairs(splitTop(sel)) do if g:find("%S") then list[#list + 1] = compileComplex(g) end end if #list == 0 then error("selector: empty", 0) end return list end local function compoundMatch(el, part) if el.type ~= "el" then return false end if part.tag and el.tag ~= part.tag then return false end for _, t in ipairs(part.tests) do if not t(el) then return false end end return true end local function matchAt(el, parts, k) if not compoundMatch(el, parts[k]) then return false end if k == 1 then return true end local comb = parts[k].comb if comb == ">" then local p = el.parent return p ~= nil and p.type == "el" and matchAt(p, parts, k - 1) elseif comb == " " then local p = el.parent while p and p.type == "el" do if matchAt(p, parts, k - 1) then return true end p = p.parent end return false end local parent = el.parent if not parent then return false end local list = elems(parent) local idx = el.eidx or (elems(parent) and el.eidx) if comb == "+" then local prev = list[idx - 1] return prev ~= nil and matchAt(prev, parts, k - 1) end for j = idx - 1, 1, -1 do if matchAt(list[j], parts, k - 1) then return true end end return false end --- el 是否命中已编译选择器。 function Css.matches(el, compiled) for _, parts in ipairs(compiled) do if matchAt(el, parts, #parts) then return true end end return false end local cache = {} --- 编译选择器;语法错误抛错(字符串)。 function Css.compile(sel) local c = cache[sel] if not c then c = compileList(sel) cache[sel] = c end return c end --- root 的所有后代里命中 sel 的元素,文档顺序。 function Css.select(root, sel) local compiled = Css.compile(sel) local out = {} local function walk(n) for _, c in ipairs(n.children or {}) do if c.type == "el" then if Css.matches(c, compiled) then out[#out + 1] = c end walk(c) end end end -- jsoup 的 select 把根元素自己也算进候选 if root.type == "el" and Css.matches(root, compiled) then out[1] = root end walk(root) return out end return Css