# 代码克隆检测

代码克隆检测是一种软件工程方法，它分析源代码以找出相同或相似的片段，以便对重复逻辑进行重构、跟踪或移除。它对维护很重要，因为在一个克隆片段副本中修复的缺陷必须在其他每个副本中同样修复；否则，随着副本逐渐分化，维护工作量会增加。<sup>[1](https://www.sciencedirect.com/science/article/abs/pii/S1574013722000624)</sup> 检测还支持重构、迁移、克隆维护和遗留系统现代化，<sup>[2](https://dl.acm.org/doi/full/10.1145/3801119.3801133)</sup> 也支持抄袭检测、缺陷检测和版权侵权检测。<sup>[3](https://www.ijcaonline.org/research/volume137/number10/sheneamer-2016-ijca-908896.pdf)</sup>

| 关键事实 | 详情 |
|---|---|
| 克隆类型 | 1型：除注释和空白外完全相同；2型：重命名标识符或字面量；3型：语句被修改、增加或删除；4型：计算相同，语法不同。<sup>[4](https://drops.dagstuhl.de/storage/16dagstuhl-seminar-proceedings/dsp-vol06301/DagSemProc.06301.13/DagSemProc.06301.13.pdf)</sup><sup> • </sup><sup>[5](https://www.cs.usask.ca/~croy/papers/2018/SANER2018/RoyCordyBenchmarkingSANER2018.pdf)</sup> |
| 输出 | 克隆对、克隆类（其中任意两个片段均为克隆的极大集合），以及在某些工具中输出宏体和宏调用等重构候选。<sup>[5](https://www.cs.usask.ca/~croy/papers/2018/SANER2018/RoyCordyBenchmarkingSANER2018.pdf)</sup><sup> • </sup><sup>[6](https://leodemoura.github.io/files/ICSM98.pdf)</sup> |
| 核心流程 | 选择比较单元，将代码转换为中间表示，可选地进行规范化，进行比较，然后过滤并聚合结果。<sup>[7](https://www.cs.usask.ca/faculty/croy/papers/2009/RCK_SCP_Clones.pdf)</sup> |
| 参考基准 | BigCloneBench：来自 25,000 多个项目、3.65 亿行代码的 800 万个人工验证克隆对。<sup>[5](https://www.cs.usask.ca/~croy/papers/2018/SANER2018/RoyCordyBenchmarkingSANER2018.pdf)</sup> |
| 可扩展性示例 | SourcererCC 在单台工作站上于 4.5 天内，在 2.5 亿行代码（250 MLOC；25,000 个项目、300 万个文件）中检测出精确克隆和近似克隆。<sup>[8](https://clones.usask.ca/pubfiles/articles/SajnaniSourcererCCICSE2016.pdf)</sup> |
| 已知不足 | 基于词法单元的工具对1型和2型有效，对3型仅部分有效；4型语义克隆仍然困难。<sup>[9](https://www.mdpi.com/2504-2289/9/2/41)</sup> |

## 工作原理

标准分类体系包含四种类型。1型克隆是完全副本，差异仅限于注释、版式和空白。2型克隆在语法上相同，只是变量、类型或函数标识符（以及字面值）被更改。3型克隆是带有进一步语句级修改的副本：语句被修改、增加或删除。4型克隆执行相同的计算，但由不同的语法变体实现。<sup>[4](https://drops.dagstuhl.de/storage/16dagstuhl-seminar-proceedings/dsp-vol06301/DagSemProc.06301.13/DagSemProc.06301.13.pdf)</sup><sup> • </sup><sup>[5](https://www.cs.usask.ca/~croy/papers/2018/SANER2018/RoyCordyBenchmarkingSANER2018.pdf)</sup><sup> • </sup><sup>[9](https://www.mdpi.com/2504-2289/9/2/41)</sup>

工具以不同粒度报告结果。基本输出是克隆对；克隆对通常被聚合为克隆类，即其中任意两个片段都满足克隆关系的极大片段集合。有些工具报告克隆对，有些报告克隆类，还有些两者都报告；克隆类减少了维护者为重构而必须调查的案例数量。<sup>[5](https://www.cs.usask.ca/~croy/papers/2018/SANER2018/RoyCordyBenchmarkingSANER2018.pdf)</sup><sup> • </sup><sup>[7](https://www.cs.usask.ca/faculty/croy/papers/2009/RCK_SCP_Clones.pdf)</sup> 一个基于抽象语法树（AST）的工具更进一步，生成了克隆移除所需的宏体以及用于替换克隆的宏调用，也就是现成的重构候选。<sup>[6](https://leodemoura.github.io/files/ICSM98.pdf)</sup>

每个检测器都要做同样的三个选择：比较什么、如何表示、如何计算相似度。预处理首先剔除头文件和注释等无关项；随后将代码转换为中间表示，例如词法单元序列、抽象语法树（AST）或程序依赖图（PDG）；最后计算片段之间的相似度，并将相似度超过预定义阈值的片段报告为克隆。<sup>[10](https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0296858)</sup>

主要表示方法族对相似度的定义不同。基于词法单元的方法去除空白和注释，按语言的词法规则将源代码划分为词法单元，并比较得到的词法单元，可以是有序序列、词法单元包或其他表示；CCFinder 是词法单元序列工具，而 dup 是基于行的参数化文本匹配方法。语法方法将整个代码库解析为解析树或 AST，并寻找相似的子树。语义感知方法构建 PDG，其节点是语句和条件，边是控制依赖和数据依赖，然后搜索同构子图。基于度量的方法则比较 begin-end 块的度量值。<sup>[7](https://www.cs.usask.ca/faculty/croy/papers/2009/RCK_SCP_Clones.pdf)</sup><sup> • </sup><sup>[11](https://iopscience.iop.org/article/10.1088/1757-899X/1022/1/012074/pdf)</sup>

## 如何实施

实践者运行包含以下阶段的流水线。<sup>[7](https://www.cs.usask.ca/faculty/croy/papers/2009/RCK_SCP_Clones.pdf)</sup>

1. **选择比较单元与粒度**，例如行、块或函数。
2. **转换**：将源代码转换为选定的中间表示（词法单元、AST、PDG 或度量值）。
3. **规范化**：在工具支持的情况下进行规范化，以消除空白、注释、格式或标识符名称方面的表面差异；规范化范围从简单的注释与空白删除到复杂的源代码变换。
4. **比较**：将单元与索引或其他单元进行比较，收集超过阈值的匹配。克隆对通常记录为一个四元组 \( (L_{\mathrm{Begin}}, L_{\mathrm{End}}, R_{\mathrm{Begin}}, R_{\mathrm{End}}) \)，给出每个片段的起始和结束位置。<sup>[3](https://www.ijcaonline.org/research/volume137/number10/sheneamer-2016-ijca-908896.pdf)</sup>
5. **后处理**：过滤误报，将克隆对聚合为克隆类，并在克隆管理之前对结果进行可视化或人工检查。<sup>[7](https://www.cs.usask.ca/faculty/croy/papers/2009/RCK_SCP_Clones.pdf)</sup><sup> • </sup><sup>[11](https://iopscience.iop.org/article/10.1088/1757-899X/1022/1/012074/pdf)</sup>

SourcererCC 利用针对词法单元的优化[倒排索引](https://www.edgepedia.org/zh/inverted-index)，并采用基于排序的过滤启发式方法，计算查询块与候选之间相似度的实时上界和下界，因此大多数配对无需完整比较即被丢弃。<sup>[8](https://clones.usask.ca/pubfiles/articles/SajnaniSourcererCCICSE2016.pdf)</sup>

## 起源

克隆检测源于针对重复代码的字符串匹配工作。J. [霍华德·约翰逊](https://www.edgepedia.org/zh/howard-johnsons)（J. Howard Johnson）1994 年在 ICSM 上提出的方法，通过[词法分析](https://www.edgepedia.org/zh/lexical-analysis)后进行子串匹配来发现克隆，并指出了一种自然的替代思路：将克隆视为语法树或语义树的匹配子树；该工作还将克隆检测与变更跟踪联系起来。<sup>[12](https://plg.uwaterloo.ca/~migod/846/papers/icsm94-johnson.pdf)</sup> 布伦达·S. 贝克（Brenda S. Baker）的 dup 工具既报告文本完全相同的代码段，也报告除了一组标识符被系统性地替换为另一组之外完全相同的代码段；它采用单行比较粒度上的参数化匹配，因为程序员和编辑器都按行粒度工作。她的期刊论文《字符串中的参数化重复：算法及其在软件维护中的应用》（“Parameterized Duplication in Strings: Algorithms and an Application to Software Maintenance”，《SIAM Journal on Computing》，1997 年）给出了底层算法。<sup>[13](https://www.cs.ucdavis.edu/~devanbu/teaching/289/Schedule_files/baker-wcre95.pdf)</sup><sup> • </sup><sup>[14](https://doi.org/10.1137/s0097539793246707)</sup> 由 T. 神谷（T. Kamiya）、S. 楠本（S. Kusumoto）和 K. 井上（K. Inoue）提出的基于词法单元的系统 CCFinder（《IEEE 软件工程汇刊》，2002 年），将输入源文本的变换与逐词法单元比较结合起来，并提取 C、C++、Java、COBOL 及其他语言中的克隆；其论文将贝克早期的重复代码程序列为先前工作。<sup>[15](https://doi.org/10.1109/tse.2002.1019480)</sup> 由希特什·萨杰纳尼（Hitesh Sajnani）及其同事提出的 SourcererCC（2015 年，arXiv），将基于词法单元的检测扩展到大规模代码。<sup>[16](https://doi.org/10.48550/arxiv.1512.06448)</sup> 由魏华（Wei Hua）及其同事提出的 FCCA（《IEEE 可靠性汇刊》，2020 年），将结合注意力网络的混合代码表示应用于功能克隆检测。<sup>[17](https://doi.org/10.1109/tr.2020.3001918)</sup>

## 变体

这些具名工具的主要差异在于表示方法和匹配策略。SourcererCC 根据从源代码中提取的词法单元检测克隆；NiCad 对代码进行规范化并逐行比较；Deckard 比较 AST，以报告具有相似树结构的克隆。<sup>[18](https://people.cs.vt.edu/~nm8247/publications/icsme-research-118-camera-ready.pdf)</sup> SourcererCC 发布了用于仓库分析的批处理版本，以及与 [Eclipse](https://www.edgepedia.org/zh/eclipse-software) IDE 集成的交互式版本。<sup>[8](https://clones.usask.ca/pubfiles/articles/SajnaniSourcererCCICSE2016.pdf)</sup>

基于学习的变体将克隆检测视为分类问题。CCLearner 将词法单元分为八类，[计算](https://www.edgepedia.org/zh/computing)每个类别的相似度分数，并训练一个深度神经网络二分类器来预测两个方法是否为克隆。<sup>[18](https://people.cs.vt.edu/~nm8247/publications/icsme-research-118-camera-ready.pdf)</sup> 机器学习和深度学习技术越来越多地被专门提出来检测语义克隆。<sup>[11](https://iopscience.iop.org/article/10.1088/1757-899X/1022/1/012074/pdf)</sup>

## 应用

在实践中，检测结果可用于克隆重构或移除、避免克隆、抄袭检测、缺陷检测、代码压缩和版权侵权检测。<sup>[3](https://www.ijcaonline.org/research/volume137/number10/sheneamer-2016-ijca-908896.pdf)</sup> [可扩展性](https://www.edgepedia.org/zh/scalability)因表示方法而异，差异很大：基于词法单元的技术在使用后缀树算法时扩展性良好；基于度量的技术因为只比较 begin-end 块的度量值，扩展性良好；而基于 PDG 的技术由于子图匹配代价高昂，扩展性较差。<sup>[3](https://www.ijcaonline.org/research/volume137/number10/sheneamer-2016-ijca-908896.pdf)</sup>

## 局限与替代方案

BigCloneBench 按相似度细分3型：极强3型（Very-Strongly Type-3，90-100%）、强3型（Strongly Type-3，70-90%）、中等3型（Moderately Type-3，50-70%）和弱3型/4型（Weakly Type-3/Type-4，0-50%）。<sup>[19](https://clones.usask.ca/pubfiles/articles/SvajlenkoEvaluatingToolsICSME2015.pdf)</sup> 基于词法单元的方法在最弱的子区间上失效，因为在每个弱3型/4型（WT3/4）对中，两个方法共同拥有的语句不足 50%。<sup>[18](https://people.cs.vt.edu/~nm8247/publications/icsme-research-118-camera-ready.pdf)</sup> 包括 CCFinder、SourcererCC 和 NiCad 在内的知名工具对1型和2型有效，对3型仅部分有效，因为3型克隆在语句层面存在差异，而4型检测需要深入理解代码。<sup>[9](https://www.mdpi.com/2504-2289/9/2/41)</sup><sup> • </sup><sup>[23](https://wu-yueming.github.io/Files/ASE2020_SCDetector.pdf)</sup>

跨语言检测是另一种失效模式：传统的词法、语法和结构工具难以处理在语法或编程语言上差异显著但语义等价的代码。<sup>[2](https://dl.acm.org/doi/full/10.1145/3801119.3801133)</sup>

近期工作直接针对这些缺口。Rator 是一种基于树的语义检测器，通过节点自由度编码 AST 子树，在 BigCloneBench 上达到 0.99 的 F1 分数，在 [Google Code Jam](https://www.edgepedia.org/zh/google-code-jam) 上达到 0.91。<sup>[20](https://link.springer.com/article/10.1186/s42400-025-00456-4)</sup> 混合方法将 AST 分析与 PDG 表示以及图神经网络结合起来；图神经网络通过消息传递聚合节点信息，以捕获控制依赖和数据依赖，用于4型检测。<sup>[21](https://link.springer.com/article/10.1007/s41870-025-02670-2)</sup> LC3 针对跨语言检测的两个限制：语言无关表示学习不足，以及长代码上的信息损失。<sup>[22](https://ojs.aaai.org/index.php/AAAI/article/view/40410)</sup> 基于大语言模型（LLM）的检测在大多数语言对上保持通常超过 0.90 的精确率；CloneCognition 表明，机器学习模型可以通过验证传统工具产生的候选克隆来减少误报。<sup>[2](https://dl.acm.org/doi/full/10.1145/3801119.3801133)</sup> 已发表的比较研究并未确定克隆检测与代码坏味检测器、重复代码检查器相比孰优孰劣；综述中最接近的比较是一项针对重构任务的适用性评估，评估对象为基于文本、基于词法单元和基于度量的检测器，评判标准为适用性、相关性、置信度和聚焦度。<sup>[4](https://drops.dagstuhl.de/storage/16dagstuhl-seminar-proceedings/dsp-vol06301/DagSemProc.06301.13/DagSemProc.06301.13.pdf)</sup>

## References

1. [A systematic literature review on the use of machine learning in code clone research (ScienceDirect)](https://www.sciencedirect.com/science/article/abs/pii/S1574013722000624)
2. [Comparing Large Language Models and Traditional Clone Detection Tools for Intra- and Cross-Language Code Clone Detection (ACM)](https://dl.acm.org/doi/full/10.1145/3801119.3801133)
3. [A Survey of Software Clone Detection Techniques (Sheneamer & Kalita, IJCA 2016)](https://www.ijcaonline.org/research/volume137/number10/sheneamer-2016-ijca-908896.pdf)
4. [Survey of Research on Software Clones (Dagstuhl Seminar 06301 proceedings)](https://drops.dagstuhl.de/storage/16dagstuhl-seminar-proceedings/dsp-vol06301/DagSemProc.06301.13/DagSemProc.06301.13.pdf)
5. [Benchmarks for Software Clone Detection (Roy & Cordy, SANER 2018)](https://www.cs.usask.ca/~croy/papers/2018/SANER2018/RoyCordyBenchmarkingSANER2018.pdf)
6. [Clone Detection Using Abstract Syntax Trees (Baxter et al., ICSM 1998)](https://leodemoura.github.io/files/ICSM98.pdf)
7. [Comparison and Evaluation of Code Clone Detection Techniques and Tools: A Qualitative Approach (Science of Computer Programming)](https://www.cs.usask.ca/faculty/croy/papers/2009/RCK_SCP_Clones.pdf)
8. [SourcererCC: Scaling Code Clone Detection to Big-Code (ICSE 2016)](https://clones.usask.ca/pubfiles/articles/SajnaniSourcererCCICSE2016.pdf)
9. [Exploring the Boundaries Between LLM Code Clone Detection and Code Similarity Assessment on Human and AI-Generated Code (MDPI, 2025)](https://www.mdpi.com/2504-2289/9/2/41)
10. [A systematic literature review on the applications of recurrent neural networks in code clone research (PLOS One)](https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0296858)
11. [A Systematic Review of Semantic Clone Detection (IOP Conf. Materials Science and Engineering)](https://iopscience.iop.org/article/10.1088/1757-899X/1022/1/012074/pdf)
12. [Substring Matching for Clone Detection and Change Tracking (Johnson, ICSM 1994)](https://plg.uwaterloo.ca/~migod/846/papers/icsm94-johnson.pdf)
13. [On Finding Duplication and Near-Duplication in Large Software Systems (Baker, WCRE 1995)](https://www.cs.ucdavis.edu/~devanbu/teaching/289/Schedule_files/baker-wcre95.pdf)
14. [Brenda S. Baker (1997). Parameterized Duplication in Strings: Algorithms and an Application to Software Maintenance. SIAM Journal on Computing.](https://doi.org/10.1137/s0097539793246707)
15. [T. Kamiya, S. Kusumoto, K. Inoue (2002). CCFinder: a multilinguistic token-based code clone detection system for large scale source code. IEEE Transactions on Software Engineering.](https://doi.org/10.1109/tse.2002.1019480)
16. [Sajnani, Hitesh and colleagues (2015). SourcererCC: Scaling Code Clone Detection to Big Code. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.1512.06448)
17. [Wei Hua and colleagues (2020). FCCA: Hybrid Code Representation for Functional Clone Detection Using Attention Networks. IEEE Transactions on Reliability.](https://doi.org/10.1109/tr.2020.3001918)
18. [CCLearner: A Deep Learning-Based Clone Detection Approach (ICSME)](https://people.cs.vt.edu/~nm8247/publications/icsme-research-118-camera-ready.pdf)
19. [Evaluating Clone Detection Tools with BigCloneBench (ICSME 2015)](https://clones.usask.ca/pubfiles/articles/SvajlenkoEvaluatingToolsICSME2015.pdf)
20. [Rator: detecting fine-grained semantic code clones using tree encoding based on node degrees of freedom (Cybersecurity, Springer, 2025)](https://link.springer.com/article/10.1186/s42400-025-00456-4)
21. [A Semantic-driven approach to detect Type-4 code clones by using AST and PDG (Springer, 2025)](https://link.springer.com/article/10.1007/s41870-025-02670-2)
22. [LC3: Long Cross-Language Code Clone Detection Enhanced by Opcode Sequences and Affinity Aggregation (AAAI)](https://ojs.aaai.org/index.php/AAAI/article/view/40410)
23. [wu-yueming.github.io](https://wu-yueming.github.io/Files/ASE2020_SCDetector.pdf)

---
*Initially written Sep 29, 2026 · Edited: Oct 15, 2026; Oct 25, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software testing and quality

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/code-clone-detection

English original: https://www.edgepedia.org/code-clone-detection
