When copy-paste goes wrong: Bugs in structurally isomorphic Go code
You might've done this many times: you found code in a project that seemed like a good fit for your task, copied it, replaced the variables or function calls with the ones you needed, and then got behavior you didn't expect when you ran the code. It's likely that you missed something while making those changes. This is exactly how the errors described in this article occur. Introduction…
When copy-pasting code, it is easy to make mistakes that can lead to unexpected behavior. This is especially true when the copied code has similar structures but different variables or function calls. One such error is detected by a new diagnostic rule in PVS-Studio 8.00, which is capable of identifying a specific type of copy-paste bug that may otherwise go unnoticed during a code review.
The error occurs when two if statements in a Go program have identical checks, but with different variables. For example, one if statement checks process.ProcessName, while the other checks process.FuncName. Despite the pattern of checks appearing consistent, the last checks in both if statements are the same, using process.ProcessName. This discrepancy can easily slip past manual review.
To detect such bugs, PVS-Studio uses a heuristic algorithm instead of artificial intelligence. The algorithm works by building a simplified Abstract Syntax Tree (AST) for individual statements or groups of statements within a function. This simplified AST contains only the necessary information to describe the code structure, excluding specific names of variables and functions. The analyzer then groups code fragments based on their simplified AST and compares them within each group.
The algorithm identifies common variables and specific variables that appear in only one fragment. If a common variable occurs less frequently in one fragment than in the other, but at the same relative positions, it is treated as a potential typo. The analyzer then searches for a replacement candidate variable in the second fragment that can substitute the common variable while maintaining the same relative position.
If such a candidate is found, the analyzer performs final checks to ensure the variables can be safely swapped.
While the concept of this diagnostic rule is straightforward, creating it requires extensive teaching and a significant amount of logic to filter out false positives. The rule is only 5% of the task, while filtering out incorrect warnings takes up 95% of the effort. Despite this, the diagnostic rule effectively catches bugs caused by copy-pasting code with minor variations in variable names.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.