Skip to content

Commit b526e13

Browse files
committed
better warning + don't remove non-trivial initializer expression for unused variables
1 parent 1860f66 commit b526e13

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

codeOptimizers/src/prog8/optimizer/UnusedCodeRemover.kt

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -120,12 +120,26 @@ class UnusedCodeRemover(private val program: Program,
120120
if(singleUse is AssignTarget) {
121121
val assignment = singleUse.parent as Assignment
122122
if(assignment.origin==AssignmentOrigin.VARINIT) {
123-
if(!decl.definingModule.isLibrary)
124-
errors.warn("removing unused variable '${decl.name}'", decl.position)
125-
return listOf(
126-
IAstModification.Remove(decl, parent as IStatementContainer),
127-
IAstModification.Remove(assignment, assignment.parent as IStatementContainer)
128-
)
123+
if(assignment.value.isSimple) {
124+
// remove the vardecl
125+
if(!decl.definingModule.isLibrary)
126+
errors.warn("removing unused variable '${decl.name}'", decl.position)
127+
return listOf(
128+
IAstModification.Remove(decl, parent as IStatementContainer),
129+
IAstModification.Remove(assignment, assignment.parent as IStatementContainer)
130+
)
131+
} else if(assignment.value is IFunctionCall) {
132+
// replace the unused variable's initializer function call by a void
133+
errors.warn("replaced unused variable '${decl.name}' with void call, maybe this can be removed altogether", decl.position)
134+
val fcall = assignment.value as IFunctionCall
135+
val voidCall = FunctionCallStatement(fcall.target, fcall.args, true, fcall.position)
136+
return listOf(
137+
IAstModification.ReplaceNode(decl, voidCall, parent),
138+
IAstModification.Remove(assignment, assignment.parent as IStatementContainer)
139+
)
140+
} else {
141+
errors.warn("variable '${decl.name}' is unused but has non-trivial initialization assignment. Leaving this in but maybe it can be removed altogether", decl.position)
142+
}
129143
}
130144
}
131145
}

0 commit comments

Comments
 (0)