Skip to content

Commit

Permalink
Fix duplicated warnings in nested functions
Browse files Browse the repository at this point in the history
Unreachable variable access and unreachable code checks could be
executed several times in nested functions.
  • Loading branch information
mpeterv committed Oct 31, 2015
1 parent ae2eb0e commit 15c7b67
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
32 changes: 32 additions & 0 deletions spec/check_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,19 @@ end
]])
end)

it("detects unreachable code in nested function", function()
assert.same({
{code = "511", line = 4, column = 7, end_column = 12}
}, check[[
return function()
return function()
do return end
return
end
end
]])
end)

it("detects accessing uninitialized variables", function()
assert.same({
{code = "113", name = "get", line = 6, column = 8, end_column = 10},
Expand All @@ -456,6 +469,25 @@ return a
]])
end)

it("detects accessing uninitialized variables in nested functions", function()
assert.same({
{code = "113", name = "get", line = 7, column = 8, end_column = 10},
{code = "321", name = "a", line = 7, column = 12, end_column = 12}
}, check[[
return function() return function(...)
local a
if ... then
a = 5
else
a = get(a)
end
return a
end end
]])
end)

it("does not detect accessing unitialized variables incorrectly in loops", function()
assert.same({
{code = "113", name = "get", line = 4, column = 8, end_column = 10}
Expand Down
10 changes: 5 additions & 5 deletions src/luacheck/reachability.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ local reachability

local function noop_callback() end

local function reachability_callback(_, _, item, chstate)
local function reachability_callback(_, _, item, chstate, nested)
if not item then
return true
end

if item.lines then
if not nested and item.lines then
for _, subline in ipairs(item.lines) do
reachability(chstate, subline)
reachability(chstate, subline, true)
end
end

Expand All @@ -29,9 +29,9 @@ local function reachability_callback(_, _, item, chstate)
end

-- Emits warnings: unreachable code, uninitialized access.
function reachability(chstate, line)
function reachability(chstate, line, nested)
local reachable_indexes = {}
core_utils.walk_line_once(line, reachable_indexes, 1, reachability_callback, chstate)
core_utils.walk_line_once(line, reachable_indexes, 1, reachability_callback, chstate, nested)

for i, item in ipairs(line.items) do
if not reachable_indexes[i] then
Expand Down

0 comments on commit 15c7b67

Please sign in to comment.