Skip to content

Instantly share code, notes, and snippets.

@mpeterv
Created September 27, 2014 08:40
Show Gist options
  • Save mpeterv/65eb04e36f68a866dc58 to your computer and use it in GitHub Desktop.
Save mpeterv/65eb04e36f68a866dc58 to your computer and use it in GitHub Desktop.
Unreachable code detector using luacheck
-- Requires luacheck scm-6
-- Reads a Lua program from stdin, prints warnings for unreachable code in top level closure.
-- Crashes on `break` or `goto` or labels.
local flow = require "luacheck.flow"
local parser = require "metalua.compiler".new()
local src = assert(io.stdin:read("*a"))
local ast = assert(parser:src_to_ast(src))
local intel = {closures = {{stmts = ast}}, gotos = {}}
flow(intel)
local graph = intel.closures[1].flow
local nodes = intel.flow_nodes
local marked = {}
local function mark(node)
marked[node] = true
for i=1, #node.nexts do
if not marked[node.nexts[i]] then
mark(node.nexts[i])
end
end
end
mark(graph)
for i=1, #nodes do
if not marked[nodes[i]] then
if nodes[i].ast_node then
print("Dead code at line "..nodes[i].ast_node.lineinfo.first.line)
mark(nodes[i])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment