Skip to content

Commit

Permalink
fix: consider tactic mvar assignments for used variables
Browse files Browse the repository at this point in the history
  • Loading branch information
larsk21 authored and Kha committed Jun 3, 2022
1 parent 11fe65a commit c1fab4d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
30 changes: 28 additions & 2 deletions src/Lean/Linter/Basic.lean
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ def unusedVariables : Linter := fun stx => do
let some stxRange := stx.getRange?
| pure ()

let infoTrees := (← get).infoState.trees.toArray
let fileMap := (← read).fileMap
let refs := findModuleRefs fileMap (← get).infoState.trees.toArray

-- collect references
let refs := findModuleRefs fileMap infoTrees

let mut vars : HashMap FVarId RefInfo := .empty
let mut constDecls : HashSet String.Range := .empty
Expand All @@ -34,6 +37,29 @@ def unusedVariables : Linter := fun stx => do
if let some range := definition.stx.getRange? then
constDecls := constDecls.insert range

-- collect uses from tactic infos
let tacticMVarAssignments : HashMap MVarId Expr :=
infoTrees.foldr (init := .empty) fun tree assignments =>
tree.foldInfo (init := assignments) (fun _ i assignments => match i with
| .ofTacticInfo ti =>
ti.mctxAfter.eAssignment.foldl (init := assignments) fun assignments mvar expr =>
if assignments.contains mvar then
assignments
else
assignments.insert mvar expr
| _ =>
assignments)

let tacticFVarUses : HashSet FVarId ←
tacticMVarAssignments.foldM (init := .empty) fun uses _ expr => do
let (_, s) ← StateT.run (s := uses) <| expr.forEach' (fun expr => do
match expr with
| .fvar id _ => modify (·.insert id)
| _ => pure ()
return false)
return s

-- determine unused variables
for (id, ⟨decl?, uses⟩) in vars.toList do
let some decl := decl?
| continue
Expand Down Expand Up @@ -63,7 +89,7 @@ def unusedVariables : Linter := fun stx => do
if ignoredPatternFns.any (· declStx stack) then
continue

if uses.isEmpty then
if uses.isEmpty && !tacticFVarUses.contains id then
publishMessage s!"unused variable `{localDecl.userName}`" range

return ()
Expand Down
1 change: 0 additions & 1 deletion tests/lean/linterUnusedVariables.lean.expected.out
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
linterUnusedVariables.lean:10:7-10:9: warning: unused variable `HQ`
linterUnusedVariables.lean:16:6-16:7: warning: unused variable `y`
linterUnusedVariables.lean:21:8-21:9: warning: unused variable `x`
linterUnusedVariables.lean:28:2-28:3: warning: unused variable `x`
Expand Down

0 comments on commit c1fab4d

Please sign in to comment.