Created
September 27, 2014 08:40
-
-
Save mpeterv/65eb04e36f68a866dc58 to your computer and use it in GitHub Desktop.
Unreachable code detector using luacheck
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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