local tl = require("tl")
local L = {}
local SKIP_KEYS = { if_parent = true, type = true, newtype = true, decltuple = true, expected = true }
local function is_node(t)
return type(t) == "table" and type(t.kind) == "string"
end
local orders = setmetatable({}, { __mode = "k" })
local function traverse(root)
local order, seen = {}, {}
local function go(n)
if type(n) ~= "table" or seen[n] then return end
seen[n] = true
if is_node(n) then order[#order + 1] = n end
for i = 1, #n do
if type(n[i]) == "table" then go(n[i]) end
end
for k, v in pairs(n) do
if type(k) ~= "number" and not SKIP_KEYS[k] and type(v) == "table" then go(v) end
end
end
go(root)
return order
end
local function walk(root, visit)
local order = orders[root]
if not order then
order = traverse(root)
orders[root] = order
end
for i = 1, #order do
visit(order[i])
end
end
local function unquote(tk)
if type(tk) ~= "string" then return nil end
local q = tk:sub(1, 1)
if (q == '"' or q == "'") and tk:sub(-1) == q then
return tk:sub(2, -2)
end
return nil
end
local function subject_key(n)
if not is_node(n) then return nil end
if n.kind == "variable" or n.kind == "identifier" then return n.tk end
if n.kind == "op" and n.op and n.op.op == "." then
local a, b = subject_key(n.e1), subject_key(n.e2)
if a and b then return a .. "." .. b end
end
if n.kind == "paren" then return subject_key(n.e1) end
return nil
end
local function collect_allows(src)
local allows = {}
local y = 0
for line in (src .. "\n"):gmatch("(.-)\n") do
y = y + 1
local names = line:match("%-%-%s*htl:%s*allow%(([%w%-:, ]+)%)")
if names then
allows[y] = allows[y] or {}
for name in names:gmatch("[%w%-:]+") do allows[y][name] = true end
end
end
return allows
end
L.collect_allows = collect_allows
local CHAIN_OPS = { ["."] = true, [":"] = true, ["@funcall"] = true, ["@index"] = true }
local CHAIN_WHAT = { ["."] = "field access", [":"] = "method call", ["@funcall"] = "call", ["@index"] = "index" }
local function lint_nil_index(ast, report)
walk(ast, function(n)
if n.kind == "op" and n.op and CHAIN_OPS[n.op.op] then
local base = n.e1
if is_node(base) and base.kind == "op" and base.op and base.op.op == "@index" then
report("nil-index", n.y, n.x,
CHAIN_WHAT[n.op.op] .. " directly on an index result: the value may be nil at runtime; bind it to a local and nil-check first")
end
end
end)
end
local function lint_nil_return(ast, report, extra)
local nilable_at = extra and extra.nilable_at
if not nilable_at then return end
walk(ast, function(n)
if n.kind ~= "op" or not n.op or not CHAIN_OPS[n.op.op] then return end
local call = n.e1
if not is_node(call) or call.kind ~= "op" or not call.op or call.op.op ~= "@funcall" then return end
local callee = call.e1
if not is_node(callee) or not callee.y or not callee.x then return end
if not nilable_at(callee.y, callee.x) then return end
local name = subject_key(callee)
report("nil-return", n.y, n.x,
"call result may be nil at runtime: " .. (name and (name .. " is") or "the function called here is") ..
" marked ---@nilable; bind it to a local and nil-check first")
end)
end
local GUARD_STMT = { ["if"] = true, ["while"] = true, ["repeat"] = true }
local function mentions(n, name)
if not is_node(n) then
if type(n) ~= "table" then return false end
for _, v in pairs(n) do
if type(v) == "table" and mentions(v, name) then return true end
end
return false
end
if (n.kind == "variable" or n.kind == "identifier") and n.tk == name then return true end
for k, v in pairs(n) do
if k ~= "kind" and not SKIP_KEYS[k] and type(v) == "table" and mentions(v, name) then return true end
end
return false
end
local function asserts(n, name)
if not is_node(n) or n.kind ~= "op" or not n.op or n.op.op ~= "@funcall" then return false end
local callee = n.e1
if not is_node(callee) or callee.kind ~= "variable" or callee.tk ~= "assert" then return false end
return mentions(n.e2, name)
end
local function settles(stmt, name)
if not is_node(stmt) then return false end
if GUARD_STMT[stmt.kind] then
if stmt.exp and mentions(stmt.exp, name) then return true end
for _, blk in ipairs(stmt.if_blocks or {}) do
if is_node(blk) and blk.exp and mentions(blk.exp, name) then return true end
end
return false
end
if stmt.kind == "assignment" then
return mentions(stmt.vars, name)
end
if stmt.kind == "op" and stmt.op and stmt.op.op == "@funcall" then
return asserts(stmt, name)
end
return false
end
local function first_chain_on(n, name)
if type(n) ~= "table" then return nil end
if is_node(n) then
if n.kind == "op" and n.op and CHAIN_OPS[n.op.op] then
local base = n.e1
if is_node(base) and base.kind == "variable" and base.tk == name then return n end
end
if n.kind == "op" and n.op and (n.op.op == "and" or n.op.op == "or") and mentions(n.e1, name) then
return first_chain_on(n.e1, name)
end
end
for i = 1, #n do
local hit = first_chain_on(n[i], name)
if hit then return hit end
end
for k, v in pairs(n) do
if type(k) ~= "number" and k ~= "kind" and not SKIP_KEYS[k] and type(v) == "table" then
local hit = first_chain_on(v, name)
if hit then return hit end
end
end
return nil
end
local function nilable_binding(stmt, nilable_at)
if not is_node(stmt) or stmt.kind ~= "local_declaration" then return nil end
local vars, exps = stmt.vars, stmt.exps
if type(vars) ~= "table" or #vars ~= 1 or type(exps) ~= "table" or #exps ~= 1 then return nil end
local var = vars[1]
if not is_node(var) or type(var.tk) ~= "string" then return nil end
local exp = exps[1]
if not is_node(exp) or exp.kind ~= "op" or not exp.op then return nil end
if exp.op.op ~= "@funcall" then return nil end
local callee = exp.e1
if not is_node(callee) or not callee.y or not callee.x then return nil end
if not nilable_at(callee.y, callee.x) then return nil end
return var.tk, subject_key(callee)
end
local function lint_nil_return_unchecked(ast, report, extra)
local nilable_at = extra and extra.nilable_at
if not nilable_at then return end
walk(ast, function(block)
if block.kind ~= "statements" then return end
for i = 1, #block - 1 do
local name, fn = nilable_binding(block[i], nilable_at)
if name then
for j = i + 1, #block do
local stmt = block[j]
if settles(stmt, name) then break end
local hit = first_chain_on(stmt, name)
if hit then
report("nil-return-unchecked", hit.y, hit.x,
"'" .. name .. "' may be nil at runtime: it comes from " ..
(fn and (fn .. ", which is") or "a function") ..
" marked ---@nilable, and nothing checks it before this")
break
end
end
end
end
end)
end
local HTLX_MODULE = "list"
local function index_uses_ok(n, idx)
if type(n) ~= "table" then return true end
if is_node(n) and n.kind == "op" and n.op and n.op.op == "@index"
and is_node(n.e2) and n.e2.kind == "variable" and n.e2.tk == idx then
return index_uses_ok(n.e1, idx)
end
if is_node(n) and n.kind == "variable" and n.tk == idx then return false end
for i = 1, #n do
if not index_uses_ok(n[i], idx) then return false end
end
for k, v in pairs(n) do
if type(k) ~= "number" and k ~= "kind" and not SKIP_KEYS[k] and type(v) == "table" then
if not index_uses_ok(v, idx) then return false end
end
end
return true
end
local function is_element(n, arr, idx)
return is_node(n) and n.kind == "op" and n.op and n.op.op == "@index"
and is_node(n.e1) and n.e1.kind == "variable" and n.e1.tk == arr
and is_node(n.e2) and n.e2.kind == "variable" and n.e2.tk == idx
end
local function append_target(n, idx)
if not (is_node(n) and n.kind == "op" and n.op and n.op.op == "@index") then return nil end
local base, sub = n.e1, n.e2
if not (is_node(base) and base.kind == "variable") then return nil end
local name = base.tk
if is_node(sub) and sub.kind == "variable" and sub.tk == idx then return name end
if is_node(sub) and sub.kind == "op" and sub.op and sub.op.op == "+"
and is_node(sub.e1) and sub.e1.kind == "op" and sub.e1.op and sub.e1.op.op == "#"
and is_node(sub.e1.e1) and sub.e1.e1.kind == "variable" and sub.e1.e1.tk == name
and is_node(sub.e2) and sub.e2.tk == "1" then
return name
end
return nil
end
local function one_arg_call_on_element(n, arr, idx)
if not (is_node(n) and n.kind == "op" and n.op and n.op.op == "@funcall") then return nil end
local args = n.e2
if type(args) ~= "table" or #args ~= 1 or not is_element(args[1], arr, idx) then return nil end
return subject_key(n.e1)
end
local function plain_forward_loop(n)
if not (is_node(n) and n.kind == "fornum") then return nil end
if n.step ~= nil then return nil end
if not (is_node(n.from) and n.from.tk == "1") then return nil end
local to = n.to
if not (is_node(to) and to.kind == "op" and to.op and to.op.op == "#") then return nil end
if not (is_node(to.e1) and to.e1.kind == "variable") then return nil end
if not (is_node(n.var) and type(n.var.tk) == "string") then return nil end
return to.e1.tk, n.var.tk
end
local function declares_empty(stmt)
if not (is_node(stmt) and stmt.kind == "local_declaration") then return nil end
local vars, exps = stmt.vars, stmt.exps
if type(vars) ~= "table" or #vars ~= 1 or type(exps) ~= "table" or #exps ~= 1 then return nil end
local var, exp = vars[1], exps[1]
if not (is_node(var) and type(var.tk) == "string") then return nil end
if not (is_node(exp) and exp.kind == "literal_table" and #exp == 0) then return nil end
return var.tk
end
local function htlx_call_for(loop, arr, idx)
local body = loop.body
if type(body) ~= "table" or #body ~= 1 then return nil end
local stmt = body[1]
if not is_node(stmt) then return nil end
if stmt.kind == "assignment" then
local vars, exps = stmt.vars, stmt.exps
if type(vars) ~= "table" or #vars ~= 1 or type(exps) ~= "table" or #exps ~= 1 then return nil end
local target, value = vars[1], exps[1]
if is_node(target) and target.kind == "op" and target.op and target.op.op == "@index"
and is_node(target.e1) and target.e1.kind == "variable"
and is_element(target.e2, arr, idx)
and is_node(value) and value.kind == "boolean" and value.tk == "true" then
return { acc = target.e1.tk, call = HTLX_MODULE .. ".to_set(" .. arr .. ")" }
end
local acc = append_target(target, idx)
if acc then
local fn = one_arg_call_on_element(value, arr, idx)
if fn then
return { acc = acc, call = HTLX_MODULE .. ".map(" .. arr .. ", " .. fn .. ")" }
end
end
return nil
end
if stmt.kind == "if" then
local blocks = stmt.if_blocks
if type(blocks) ~= "table" or #blocks ~= 1 then return nil end
local blk = blocks[1]
if not is_node(blk) then return nil end
local fn = one_arg_call_on_element(blk.exp, arr, idx)
if not fn then return nil end
local inner = blk.body
if type(inner) ~= "table" or #inner ~= 1 then return nil end
local a = inner[1]
if not (is_node(a) and a.kind == "assignment") then return nil end
local vars, exps = a.vars, a.exps
if type(vars) ~= "table" or #vars ~= 1 or type(exps) ~= "table" or #exps ~= 1 then return nil end
local acc = append_target(vars[1], idx)
if not acc or not is_element(exps[1], arr, idx) then return nil end
return { acc = acc, call = HTLX_MODULE .. ".filter(" .. arr .. ", " .. fn .. ")" }
end
return nil
end
local function lint_htlx_available(ast, report, extra)
local deps = extra and extra.deps
if not (deps and deps.htlx) then return end
walk(ast, function(block)
if block.kind ~= "statements" then return end
for i = 2, #block do
local loop = block[i]
local declared = declares_empty(block[i - 1])
if declared and is_node(loop) then
local arr, idx = plain_forward_loop(loop)
if arr and arr ~= declared and index_uses_ok(loop.body, idx) then
local hit = htlx_call_for(loop, arr, idx)
if hit and hit.acc == declared then
local fix
if loop.yend and loop.xend then
fix = {
applicability = "suggest",
edits = { {
line = loop.y, col = loop.x,
end_line = loop.yend, end_col = loop.xend + 1,
text = hit.acc .. " = " .. hit.call,
} },
}
end
report("htlx-available", loop.y, loop.x,
"this loop is " .. hit.call .. ": htlx is a dependency of this project, "
.. "and `require(\"htlx." .. HTLX_MODULE .. "\")` has it", fix)
end
end
end
end
end)
end
local function collect_enums(ast)
local enums = {}
walk(ast, function(n)
if (n.kind == "local_type" or n.kind == "global_type") and is_node(n.value)
and n.value.newtype and n.value.newtype.def and n.value.newtype.def.typename == "enum" then
local name = n.var and n.var.tk or "?"
enums[name] = n.value.newtype.def.enumset or {}
end
end)
return enums
end
local function literal_tests(exp)
if not is_node(exp) or exp.kind ~= "op" then return nil end
local op = exp.op and exp.op.op
if op == "or" then
local s1, l1, n1 = literal_tests(exp.e1)
local s2, l2 = literal_tests(exp.e2)
if s1 and s2 and s1 == s2 then
for _, v in ipairs(l2) do l1[#l1 + 1] = v end
return s1, l1, n1
end
return nil
end
if op == "==" then
local lit = unquote(exp.e2 and exp.e2.tk)
local subj, node = subject_key(exp.e1), exp.e1
if lit == nil then
lit = unquote(exp.e1 and exp.e1.tk)
subj, node = subject_key(exp.e2), exp.e2
end
if lit and subj then return subj, { lit }, node end
end
return nil
end
local function mark_fallthrough(ast)
local has_next = {}
walk(ast, function(n)
if n.kind ~= "statements" then return end
for i = 1, #n - 1 do
local s = n[i]
if is_node(s) and s.kind == "if" then has_next[s] = true end
end
end)
return has_next
end
local function ends_in_return(body)
if type(body) ~= "table" or #body == 0 then return false end
local last = body[#body]
return is_node(last) and last.kind == "return"
end
local function lint_enum_exhaustive(ast, report, extra)
extra = extra or {}
local enums = collect_enums(ast)
for name, set in pairs(extra.enums or {}) do
if enums[name] == nil then enums[name] = set end
end
local has_next = mark_fallthrough(ast)
walk(ast, function(n)
if n.kind ~= "if" or not n.if_blocks then return end
if #n.if_blocks < 2 then return end
if has_next[n] then
local all_return = true
for _, blk in ipairs(n.if_blocks) do
if not ends_in_return(blk.body) then all_return = false break end
end
if all_return then return end
end
local subject, seen_lits, subject_node = nil, {}, nil
for _, blk in ipairs(n.if_blocks) do
if not blk.exp then return end local s, lits, node = literal_tests(blk.exp)
if not s then return end
if subject and s ~= subject then return end
subject = s
subject_node = subject_node or node
for _, v in ipairs(lits) do seen_lits[v] = true end
end
if not subject then return end
local best_name, best_set
if extra.subject_enum and subject_node then
local set, tname = extra.subject_enum(subject_node.y, subject_node.x, subject)
if set == false then return end if set then best_name, best_set = tname, set end
end
if not best_set then
if next(enums) == nil then return end
local best_size
for name, set in pairs(enums) do
local all, size = true, 0
for _ in pairs(set) do size = size + 1 end
for v in pairs(seen_lits) do
if not set[v] then all = false break end
end
if all and (best_size == nil or size < best_size) then
best_name, best_set, best_size = name, set, size
end
end
end
if not best_name then return end
local missing = {}
for v in pairs(best_set) do
if not seen_lits[v] then missing[#missing + 1] = v end
end
if #missing > 0 then
table.sort(missing)
report("enum-exhaustive", n.y, n.x,
"if-chain on '" .. subject .. "' does not cover enum " .. best_name .. " value(s): "
.. table.concat(missing, ", ") .. "; add a branch or an else")
end
end)
end
local function unparen(n)
while is_node(n) and n.kind == "paren" do n = n.e1 end
return n
end
local function cast_written(n)
local ct = is_node(n.e2) and n.e2.casttype
if type(ct) ~= "table" or type(ct.names) ~= "table" or #ct.names == 0 then return nil end
return table.concat(ct.names, ".")
end
local function lint_enum_cast(ast, report, extra)
local cast_at = extra and extra.cast_at
if not cast_at then return end
walk(ast, function(n)
if n.kind ~= "op" or not n.op or n.op.op ~= "as" then return end
local from = unparen(n.e1)
if not is_node(from) or from.kind == "string" then return end
local target, from_type = cast_at(n.y, n.x, from.y, from.x)
if not target or from_type ~= "string" then return end
local written = cast_written(n) or target.name
report("enum-cast", n.y, n.x,
"`as " .. written .. "` is not checked at run time; look the word up in a table typed {string: "
.. written .. "}, or declare the enum on the host")
end)
end
local LUA_KEYWORDS = {
["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true,
["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["goto"] = true,
["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true,
["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true,
["until"] = true, ["while"] = true,
}
local function entry_key(name)
if name:match("^[%a_][%w_]*$") and not LUA_KEYWORDS[name] then return name end
return "[" .. string.format("%q", name) .. "]"
end
local function entry_text(name)
return entry_key(name) .. " = " .. string.format("%q", name)
end
local function strip_comment(s)
local i, q = 1, nil
while i <= #s do
local c = s:sub(i, i)
if q then
if c == "\\" then i = i + 1
elseif c == q then q = nil end
elseif c == '"' or c == "'" then
q = c
elseif c == "-" and s:sub(i + 1, i + 1) == "-" then
return s:sub(1, i - 1)
end
i = i + 1
end
return s
end
local function table_entry_fix(lines, n, names, opts)
opts = opts or {}
local entry = opts.entry or entry_text
local applicability = opts.applicability or "safe"
if not lines or not n.yend or not n.xend then return nil end
local last_y, last_x
for y = n.yend, n.y, -1 do
local line = lines[y]
if not line then return nil end
local from = (y == n.y) and (n.x + 1) or 1
local to = (y == n.yend) and (n.xend - 1) or #line
if to >= from then
local seg = strip_comment(line:sub(from, to))
local col = seg:match("^.*()%S")
if col then
last_y, last_x = y, from + col - 1
break
end
end
end
if not last_y then
if n.y ~= n.yend or not opts.split then return nil end
local col = n.x + 1
local pad = lines[n.yend]:sub(n.xend - 1, n.xend - 1):match("%s") and "" or " "
local edits = {}
for i, name in ipairs(names) do
edits[#edits + 1] = {
line = n.y, col = col, end_line = n.y, end_col = col,
text = (i == 1 and " " or ", ") .. entry(name) .. (i == #names and pad or ""),
}
end
return { applicability = applicability, edits = edits }
end
local comma = lines[last_y]:sub(last_x, last_x) == "," and "" or ","
if last_y == n.yend then
local col = last_x + 1
local edits = {}
if opts.split then
for i, name in ipairs(names) do
edits[#edits + 1] = {
line = last_y, col = col, end_line = last_y, end_col = col,
text = (i == 1 and comma or ",") .. " " .. entry(name),
}
end
else
local parts = {}
for _, name in ipairs(names) do parts[#parts + 1] = entry(name) end
edits[1] = {
line = last_y, col = col, end_line = last_y, end_col = col,
text = comma .. " " .. table.concat(parts, ", "),
}
end
return { applicability = applicability, edits = edits }
end
local indent = lines[last_y]:match("^(%s*)") or ""
local before = lines[n.yend]:sub(1, n.xend - 1)
local col = before:match("^%s*$") and 1 or n.xend
local edits = {}
if comma ~= "" then
edits[#edits + 1] = {
line = last_y, col = last_x + 1, end_line = last_y, end_col = last_x + 1, text = comma,
}
end
local text = {}
for _, name in ipairs(names) do
local line = indent .. entry(name) .. ",\n"
if opts.split then
edits[#edits + 1] = {
line = n.yend, col = col, end_line = n.yend, end_col = col, text = line,
}
else
text[#text + 1] = line
end
end
if #text > 0 then
edits[#edits + 1] = {
line = n.yend, col = col, end_line = n.yend, end_col = col, text = table.concat(text),
}
end
return { applicability = applicability, edits = edits }
end
local function listed_words(n)
local words, order = {}, {}
for _, item in ipairs(n) do
if type(item) ~= "table" then return nil end
local w
if is_node(item.key) then
if item.key.kind == "string" then
w = unquote(item.key.tk or "")
elseif item.key.kind == "identifier" then
w = item.key.tk
end
end
if not w then return nil end
if not words[w] then
words[w] = true
order[#order + 1] = w
end
end
return words, order
end
local function lint_enum_table(ast, report, extra)
local enum_table_at = extra and extra.enum_table_at
if not enum_table_at then return end
walk(ast, function(n)
if n.kind ~= "literal_table" or not n.y or not n.x then return end
if #n == 0 then return end
local spec = enum_table_at(n.y, n.x)
if not spec then return end
local target, position = spec.key, "key"
if not target then target, position = spec.value, "value" end
if not target then return end
local words, order = listed_words(n)
if not words then return end
local declared = {}
for _, v in ipairs(target.values) do declared[v] = true end
local unknown, covered = {}, 0
for _, w in ipairs(order) do
if declared[w] then covered = covered + 1 else unknown[#unknown + 1] = w end
end
local missing = {}
for _, v in ipairs(target.values) do
if not words[v] then missing[#missing + 1] = v end
end
if position == "value" and covered == 0 then return end
if #missing == 0 and #unknown == 0 then return end
table.sort(unknown)
local parts = {}
if #missing > 0 then
parts[#parts + 1] = "does not list " .. target.name .. " value(s): " .. table.concat(missing, ", ")
end
if #unknown > 0 then
parts[#parts + 1] = "lists word(s) that are not " .. target.name .. " value(s): "
.. table.concat(unknown, ", ")
end
local msg = "table typed " .. spec.name .. " " .. table.concat(parts, ", and ")
local fix
if #missing > 0 then
if position == "value" then
msg = msg .. "; a word it does not list looks up as nil"
fix = table_entry_fix(extra.lines, n, missing)
else
msg = msg .. "; add the entry (what it maps to is not something a fix can invent)"
end
end
report("enum-table", n.y, n.x, msg, fix)
end)
end
local function is_test(exp)
if not is_node(exp) or exp.kind ~= "op" or not exp.op or exp.op.op ~= "is" then
return nil
end
local subject = exp.e1
if not is_node(subject) or subject.kind ~= "variable" or not subject.tk then return nil end
local target = exp.e2
if not is_node(target) then return nil end
local name = target.casttype and target.casttype.names
and target.casttype.names[#target.casttype.names]
name = name or target.tk
if not name then return nil end
return subject.tk, name, subject
end
local function lint_union_exhaustive(ast, report, extra)
extra = extra or {}
local union_at = extra.union_at
if not union_at then return end
local has_next = mark_fallthrough(ast)
walk(ast, function(n)
if n.kind ~= "if" or not n.if_blocks then return end
if #n.if_blocks < 2 then return end
if has_next[n] then
local all_return = true
for _, blk in ipairs(n.if_blocks) do
if not ends_in_return(blk.body) then all_return = false break end
end
if all_return then return end
end
local subject, tested, first = nil, {}, nil
for _, blk in ipairs(n.if_blocks) do
if not blk.exp then return end local s, name, node = is_test(blk.exp)
if not s then return end
if subject and s ~= subject then return end
subject = s
first = first or node
tested[name] = true
end
if not first then return end
local members = union_at(first.y, first.x)
if not members then return end local missing = {}
for name in pairs(members) do
if not tested[name] then missing[#missing + 1] = name end
end
if #missing == 0 then return end
table.sort(missing)
report("union-exhaustive", n.y, n.x,
"if-chain on '" .. subject .. "' does not cover " .. table.concat(missing, ", ")
.. "; add a branch or an else")
end)
end
local function lint_shadow(ast, report)
local scopes = {}
local function push() scopes[#scopes + 1] = {} end
local function pop() scopes[#scopes] = nil end
local function declare(name, y, x, module)
if type(name) ~= "string" or name == "self" or name == "..." or name:sub(1, 1) == "_" then
return
end
for i = #scopes - 1, 1, -1 do
local outer = scopes[i][name]
if outer then
if outer ~= true then
report("shadow-local", y, x,
"local '" .. name .. "' shadows the module '" .. outer.module .. "' required at line "
.. outer.y .. "; inside this scope the module is unreachable, rename the local")
end
break
end
end
scopes[#scopes][name] = module and { y = y, module = module } or true
end
local function required_module(exp)
if is_node(exp) and exp.kind == "op" and exp.op and exp.op.op == "@funcall"
and is_node(exp.e1) and exp.e1.kind == "variable" and exp.e1.tk == "require"
and type(exp.e2) == "table" and is_node(exp.e2[1]) and exp.e2[1].kind == "string" then
return unquote(exp.e2[1].tk)
end
return nil
end
local function declare_args(args)
if type(args) ~= "table" then return end
for _, a in ipairs(args) do
if is_node(a) then declare(a.tk, a.y, a.x) end
end
end
local visit
local function visit_children(n)
for k, v in pairs(n) do
if not SKIP_KEYS[k] and type(v) == "table" then visit(v) end
end
end
local seen = {}
visit = function(n)
if type(n) ~= "table" or seen[n] then return end
seen[n] = true
if not is_node(n) then
visit_children(n)
return
end
local k = n.kind
if k == "statements" then
push()
for _, s in ipairs(n) do visit(s) end
pop()
elseif k == "local_declaration" then
visit(n.exps)
for i, v in ipairs(n.vars or {}) do
if is_node(v) then declare(v.tk, v.y, v.x, required_module(n.exps and n.exps[i])) end
end
elseif k == "local_function" then
if is_node(n.name) then declare(n.name.tk, n.name.y, n.name.x) end
push()
declare_args(n.args)
visit(n.body)
pop()
elseif k == "function" or k == "record_function" or k == "global_function" or k == "macroexp" or k == "local_macroexp" then
push()
declare_args(n.args)
visit(n.body)
pop()
elseif k == "forin" then
visit(n.exps)
push()
for _, v in ipairs(n.vars or {}) do
if is_node(v) then declare(v.tk, v.y, v.x) end
end
visit(n.body)
pop()
elseif k == "fornum" then
visit(n.from); visit(n.to); visit(n.step)
push()
if is_node(n.var) then declare(n.var.tk, n.var.y, n.var.x) end
visit(n.body)
pop()
else
visit_children(n)
end
end
push()
visit(ast)
pop()
end
local GLOBAL_KINDS = { global_declaration = true, global_function = true, global_type = true }
local function lint_no_global(ast, report, extra)
local lines = extra and extra.lines
walk(ast, function(n)
if GLOBAL_KINDS[n.kind] then
local fix
local line = lines and lines[n.y]
local kw = line and line:sub(1, (n.x or 1) - 1):match(".*()global")
if kw then
fix = {
applicability = "unsafe",
edits = { { line = n.y, col = kw, end_line = n.y, end_col = kw + 6, text = "local" } },
}
end
report("no-global", n.y, n.x, "global declaration; prefer a local and return it from the module", fix)
end
end)
end
local function lint_no_any(ast, report)
local seen = {}
local function go(t)
if type(t) ~= "table" or seen[t] then return end
seen[t] = true
if t.typename == "any" and t.y then
report("no-any", t.y, t.x, "explicit 'any' weakens type checking; use a concrete type or a record")
end
for k, v in pairs(t) do
if k ~= "if_parent" and k ~= "type" and k ~= "expected" and type(v) == "table" then go(v) end
end
end
go(ast)
end
local function numeric_literal(exp)
if not is_node(exp) then return nil end
if exp.kind == "integer" then return "integer" end
if exp.kind == "number" then return "number" end
if exp.kind == "op" and exp.op and exp.op.op == "-" and exp.e2 == nil then
return numeric_literal(exp.e1)
end
return nil
end
local function mixes_number(exp)
local hit = false
walk(exp, function(n)
if n.kind == "number" then hit = true end
if n.kind == "op" and n.op and (n.op.op == "/" or n.op.op == "^") then hit = true end
end)
return hit
end
local function lint_explicit_number(ast, report)
local ints = {} walk(ast, function(n)
if n.kind == "local_declaration" and n.vars then
local decl = n.decltuple
local annotated = (decl and decl.tuple and #decl.tuple) or 0
for i, v in ipairs(n.vars) do
if is_node(v) then
if i > annotated and numeric_literal(n.exps and n.exps[i]) == "integer" then
ints[v.tk] = v
else
ints[v.tk] = nil
end
end
end
elseif n.kind == "assignment" and n.vars then
for i, v in ipairs(n.vars) do
if is_node(v) and v.kind == "variable" and ints[v.tk] and n.exps and n.exps[i]
and mixes_number(n.exps[i]) then
local d = ints[v.tk]
ints[v.tk] = nil
local after = d.x + #tostring(v.tk)
report("explicit-number", d.y, d.x,
"'" .. tostring(v.tk) .. "' is inferred as integer from its literal but is assigned a number at line "
.. tostring(n.y) .. "; write `local " .. tostring(v.tk) .. ": number = ...` to fix the numeric type explicitly", {
applicability = "safe",
edits = { { line = d.y, col = after, end_line = d.y, end_col = after, text = ": number" } },
})
end
end
end
end)
end
local function record_meta_walk(t, name, node, report, seen, depth)
if type(t) ~= "table" or seen[t] or depth > 12 then return end
seen[t] = true
if t.def then record_meta_walk(t.def, name, node, report, seen, depth + 1) return end
if t.typename == "record" or t.typename == "interface" then
local metas = {}
for _, m in ipairs(t.meta_field_order or {}) do metas[#metas + 1] = m end
if #metas == 0 and t.meta_fields then
for m in pairs(t.meta_fields) do metas[#metas + 1] = m end
table.sort(metas)
end
if #metas > 0 then
report("class-record", t.y or node.y, t.x or node.x,
"record " .. name .. " declares metamethod(s) " .. table.concat(metas, ", ")
.. ": its behaviour lives in a metatable that serialization and the Rust boundary do not carry; "
.. "keep it out of saved data and host signatures, or make it a plain data record")
end
for fname, ft in pairs(t.fields or {}) do
record_meta_walk(ft, name .. "." .. fname, node, report, seen, depth + 1)
end
end
end
local function lint_class_record(ast, report)
local seen = {}
walk(ast, function(n)
if (n.kind == "local_type" or n.kind == "global_type") and is_node(n.value) and n.value.newtype then
record_meta_walk(n.value.newtype, n.var and n.var.tk or "?", n, report, seen, 0)
end
end)
end
local function within(a, b, bound)
if a == b then return true end
if math.abs(#a - #b) > bound then return false end
local prev2 = nil
local prev = {}
for j = 0, #b do prev[j] = j end
for i = 1, #a do
local cur = { [0] = i }
local best = cur[0]
local ca = a:byte(i)
for j = 1, #b do
local cost = (ca == b:byte(j)) and 0 or 1
local d = math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost)
if i > 1 and j > 1 and ca == b:byte(j - 1) and a:byte(i - 1) == b:byte(j) then
d = math.min(d, prev2[j - 2] + 1)
end
cur[j] = d
if d < best then best = d end
end
if best > bound then return false end
prev2 = prev
prev = cur
end
return prev[#b] <= bound
end
local function near_bound(name)
return #name >= 8 and 2 or 1
end
local function field_placeholder(ty)
if not ty or ty == "" then return "htl_fixme()" end
return "htl_fixme(" .. string.format("%q", ty) .. ")"
end
local function lint_struct_fields(ast, report, extra)
local struct_at = extra and extra.struct_at
if not struct_at then return end
walk(ast, function(n)
if n.kind ~= "literal_table" or not n.y or not n.x then return end
local spec = struct_at(n.y, n.x)
if not spec then return end
local present = {}
for _, item in ipairs(n) do
if type(item) == "table" and item.key then
if item.key.kind == "string" then
present[unquote(item.key.tk or "")] = true
elseif item.key.kind == "identifier" then
present[item.key.tk] = true
end
end
end
local missing = {}
for name in pairs(spec.required) do
if not present[name] then missing[#missing + 1] = name end
end
if #missing == 0 then return end
table.sort(missing)
local stray = {}
for name in pairs(present) do
if not (spec.declared or {})[name] then stray[#stray + 1] = name end
end
table.sort(stray)
local hints, used = {}, {}
for _, want in ipairs(missing) do
for _, got in ipairs(stray) do
if not used[got] and within(want, got, near_bound(want)) then
used[got] = true
hints[#hints + 1] = { want = want, got = got }
break
end
end
end
local tail = " (set it here, or mark the field ---@optional where it is declared)"
if #hints == 1 and #missing == 1 then
tail = (" (the literal sets `%s`)"):format(hints[1].got)
elseif #hints > 0 then
local parts = {}
for _, h in ipairs(hints) do
parts[#parts + 1] = ("`%s` for %s"):format(h.got, h.want)
end
tail = (" (the literal sets %s)"):format(table.concat(parts, ", "))
end
local misspelled = {}
for _, h in ipairs(hints) do misspelled[h.want] = true end
local names, ty = {}, {}
for _, f in ipairs(spec.fields or {}) do
if not present[f.name] and not misspelled[f.name] then
names[#names + 1] = f.name
ty[f.name] = f.type
end
end
local fix
if #names > 0 then
fix = table_entry_fix(extra.lines, n, names, {
applicability = "suggest",
split = true,
entry = function(name)
return entry_key(name) .. " = " .. field_placeholder(ty[name])
end,
})
end
report(
"struct-fields",
n.y,
n.x,
spec.name .. " is built without " .. table.concat(missing, ", ") .. tail,
fix
)
end)
end
local FUNCTION_KINDS = {
["function"] = true, ["local_function"] = true, ["global_function"] = true,
["record_function"] = true, ["macroexp"] = true, ["local_macroexp"] = true,
}
local function fn_written_name(n)
if not is_node(n.name) or not n.name.tk then return nil end
local owners = {}
local owner = n.fn_owner
while is_node(owner) do
if owner.kind == "op" and owner.op and owner.op.op == "." and is_node(owner.e2) then
table.insert(owners, 1, owner.e2.tk or "?")
owner = owner.e1
else
table.insert(owners, 1, owner.tk or "?")
break
end
end
if #owners == 0 then return n.name.tk end
return table.concat(owners, ".") .. (n.is_method and ":" or ".") .. n.name.tk
end
local function fn_allowed(fns, name)
if not name then return false end
local last = name:match("([^.:]+)$") or name
for _, want in ipairs(fns) do
if want == name or (want:match("([^.:]+)$") or want) == last then return true end
end
return false
end
local function lint_sealed_record(ast, report, extra)
local sealed_at = extra and extra.sealed_at
if not sealed_at then return end
local function allowed(spec, fn)
if spec.fns then return spec.here and fn_allowed(spec.fns, fn) end
return spec.here
end
local function complain(spec, n)
local msg = "`" .. spec.name .. "` is sealed: built only in " .. spec.file
if spec.fns then msg = msg .. " by " .. table.concat(spec.fns, " or ") end
report("sealed-record", n.y, n.x, msg)
end
local seen = {}
local function visit(n, fn)
if type(n) ~= "table" or seen[n] then return end
seen[n] = true
if is_node(n) then
if FUNCTION_KINDS[n.kind] then fn = fn_written_name(n) or fn end
if n.kind == "literal_table" and n.y and n.x then
local spec = sealed_at(n.y, n.x)
if spec and not allowed(spec, fn) then complain(spec, n) end
elseif n.kind == "op" and n.op and n.op.op == "as" and n.y and n.x then
local spec = sealed_at(n.y, n.x)
if spec and not allowed(spec, fn) then complain(spec, n) end
end
end
for k, v in pairs(n) do
if not SKIP_KEYS[k] and type(v) == "table" then visit(v, fn) end
end
end
visit(ast, nil)
end
local RULES = {
{ "nil-index", lint_nil_index },
{ "nil-return", lint_nil_return },
{ "nil-return-unchecked", lint_nil_return_unchecked },
{ "htlx-available", lint_htlx_available },
{ "struct-fields", lint_struct_fields },
{ "sealed-record", lint_sealed_record },
{ "enum-exhaustive", lint_enum_exhaustive },
{ "enum-cast", lint_enum_cast },
{ "enum-table", lint_enum_table },
{ "union-exhaustive", lint_union_exhaustive },
{ "shadow-local", lint_shadow },
{ "no-global", lint_no_global },
{ "no-any", lint_no_any },
{ "explicit-number", lint_explicit_number },
{ "class-record", lint_class_record },
}
function L.rule_names()
local out = {}
for _, r in ipairs(RULES) do out[#out + 1] = r[1] end
return out
end
function L.run(src, filename, cfg, extra)
cfg = cfg or {}
local ast, errs = tl.parse(src, filename, "tl")
if not ast or #errs > 0 then
return nil, errs[1] and errs[1].msg or "parse failed"
end
local allows = collect_allows(src)
extra = extra or {}
if not extra.lines then
local lines = {}
for l in (src .. "\n"):gmatch("([^\n]*)\n") do lines[#lines + 1] = l end
extra.lines = lines
end
local out = {}
local function report(rule, y, x, msg, fix)
if allows[y] and allows[y][rule] then return end
out[#out + 1] = { rule = rule, y = y or 0, x = x or 0, msg = msg .. " [htl " .. rule .. "]", fix = fix }
end
local profile = os.getenv("HTL_PROFILE") ~= nil
for _, r in ipairs(RULES) do
if cfg[r[1]] then
local t0 = os.clock()
r[2](ast, report, extra)
if profile then
io.stderr:write(string.format("profile: rule %-16s %7.1f ms %s\n", r[1], (os.clock() - t0) * 1000, filename))
end
end
end
table.sort(out, function(a, b)
if a.y ~= b.y then return a.y < b.y end
return a.x < b.x
end)
return out
end
return L