@chengzhao-dev/dsh-cpp-workflow 0.6.20 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/README.en.md +23 -32
  2. package/README.md +24 -33
  3. package/cordis.patch.yml +6 -6
  4. package/lib/client.js +35 -23
  5. package/lib/comment-policy.js +15 -6
  6. package/lib/index.js +45 -37
  7. package/lib/workspace.js +10 -32
  8. package/package.json +7 -7
  9. package/skills/building-cpp/SKILL.md +24 -24
  10. package/skills/building-cpp/assets/templates/projects/common/running-build.sh +5 -1
  11. package/skills/building-cpp/project/vscode/01-extensions.md +6 -0
  12. package/skills/building-cpp/project/vscode/02-settings.md +7 -1
  13. package/skills/building-cpp/references/build-script.md +10 -3
  14. package/skills/building-cpp/references/environment.md +8 -1
  15. package/skills/building-cpp/scripts/checking-environment.mjs +11 -13
  16. package/skills/building-cpp/steps/01-build.md +5 -4
  17. package/skills/building-cpp/steps/02-tooling.md +10 -10
  18. package/skills/building-cpp/steps/03-check.md +13 -11
  19. package/skills/developing-cpp/SKILL.md +39 -40
  20. package/skills/developing-cpp/references/comments/comment-rules.md +195 -0
  21. package/skills/developing-cpp/references/comments/comment-style.md +76 -0
  22. package/skills/developing-cpp/references/comments/examples/declaration-class.md +65 -0
  23. package/skills/developing-cpp/references/comments/examples/declaration-constructor.md +22 -0
  24. package/skills/developing-cpp/references/comments/examples/declaration-enum.md +48 -0
  25. package/skills/developing-cpp/{source/07-comments → references/comments}/examples/declaration-file.md +5 -5
  26. package/skills/developing-cpp/references/comments/examples/declaration-function.md +135 -0
  27. package/skills/developing-cpp/references/comments/examples/declaration-member.md +23 -0
  28. package/skills/developing-cpp/{source/07-comments → references/comments}/examples/declaration-predicate.md +3 -2
  29. package/skills/developing-cpp/references/comments/examples/declaration-struct.md +18 -0
  30. package/skills/developing-cpp/references/comments/examples/implementation-body.md +81 -0
  31. package/skills/developing-cpp/references/comments/glossary/comment-terms.md +92 -0
  32. package/skills/developing-cpp/{source/03-design → references/design}/examples/coordinate-table.md +3 -3
  33. package/skills/developing-cpp/{source/03-design → references/design}/examples/header-place.md +1 -1
  34. package/skills/developing-cpp/references/design/examples/move-result.md +48 -0
  35. package/skills/developing-cpp/references/design/examples/preview-read.md +36 -0
  36. package/skills/developing-cpp/references/design/project-design.md +160 -0
  37. package/skills/developing-cpp/{source/01-editing → references/editing}/01-edit-operations.md +5 -3
  38. package/skills/developing-cpp/{source/01-editing → references/editing}/02-rule-priority.md +2 -2
  39. package/skills/developing-cpp/{source/08-exceptions → references/exceptions}/examples/throw-build-mode.md +4 -4
  40. package/skills/developing-cpp/{source/08-exceptions → references/exceptions}/examples/throw-message.md +10 -3
  41. package/skills/developing-cpp/references/exceptions/throw-rules.md +216 -0
  42. package/skills/developing-cpp/{source/05-language → references/language}/glossary/language-terms.md +2 -2
  43. package/skills/developing-cpp/{source/05-language/01-language-basics → references/language/language-basics}/01-objects.md +8 -2
  44. package/skills/developing-cpp/{source/05-language/01-language-basics → references/language/language-basics}/02-initialization.md +8 -1
  45. package/skills/developing-cpp/{source/05-language/01-language-basics → references/language/language-basics}/03-deduction.md +6 -0
  46. package/skills/developing-cpp/references/language/language-basics/04-const.md +25 -0
  47. package/skills/developing-cpp/references/language/language-basics/05-expressions.md +28 -0
  48. package/skills/developing-cpp/references/language/language-basics/06-functions.md +17 -0
  49. package/skills/developing-cpp/{source/05-language/01-language-basics → references/language/language-basics}/07-classes.md +7 -1
  50. package/skills/developing-cpp/references/language/language-basics/08-raii.md +15 -0
  51. package/skills/developing-cpp/{source/05-language/01-language-basics → references/language/language-basics}/09-templates.md +6 -0
  52. package/skills/developing-cpp/{source/05-language/01-language-basics → references/language/language-basics}/10-checklist.md +2 -1
  53. package/skills/developing-cpp/references/language/performance/01-measure.md +22 -0
  54. package/skills/developing-cpp/{source/05-language/04-performance → references/language/performance}/02-complexity.md +6 -0
  55. package/skills/developing-cpp/{source/05-language/04-performance → references/language/performance}/03-memory.md +7 -1
  56. package/skills/developing-cpp/{source/05-language/04-performance → references/language/performance}/04-undefined-behavior.md +9 -1
  57. package/skills/developing-cpp/{source/05-language/04-performance → references/language/performance}/05-pitfalls.md +6 -0
  58. package/skills/developing-cpp/references/language/performance/06-false-optimizations.md +13 -0
  59. package/skills/developing-cpp/{source/05-language/03-standard-library → references/language/standard-library}/01-containers.md +6 -0
  60. package/skills/developing-cpp/references/language/standard-library/02-access.md +14 -0
  61. package/skills/developing-cpp/{source/05-language/03-standard-library → references/language/standard-library}/03-iteration.md +6 -0
  62. package/skills/developing-cpp/{source/05-language/03-standard-library → references/language/standard-library}/04-algorithms.md +6 -0
  63. package/skills/developing-cpp/{source/05-language/03-standard-library → references/language/standard-library}/05-string.md +6 -0
  64. package/skills/developing-cpp/references/language/standard-library/06-format.md +114 -0
  65. package/skills/developing-cpp/references/language/standard-library/07-time.md +13 -0
  66. package/skills/developing-cpp/references/language/standard-library/08-random.md +13 -0
  67. package/skills/developing-cpp/references/language/standard-library/09-files.md +14 -0
  68. package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/01-width.md +6 -0
  69. package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/02-signed.md +7 -1
  70. package/skills/developing-cpp/references/language/value-types/03-integer-roles.md +38 -0
  71. package/skills/developing-cpp/references/language/value-types/04-enum.md +24 -0
  72. package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/06-const-method.md +5 -0
  73. package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/07-nodiscard.md +6 -0
  74. package/skills/developing-cpp/references/language/value-types/08-comparison.md +10 -0
  75. package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/09-subscript.md +2 -1
  76. package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/10-float-bool.md +6 -0
  77. package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/11-checklist.md +1 -1
  78. package/skills/developing-cpp/{source/04-layout → references/layout}/01-source-layout.md +8 -3
  79. package/skills/developing-cpp/{source/04-layout → references/layout}/02-file-template.md +14 -8
  80. package/skills/developing-cpp/references/layout/03-declaration-order.md +141 -0
  81. package/skills/developing-cpp/references/naming/examples/naming-accessor.md +28 -0
  82. package/skills/developing-cpp/references/naming/examples/naming-basic.md +3 -0
  83. package/skills/developing-cpp/references/naming/examples/naming-local.md +45 -0
  84. package/skills/developing-cpp/{source/06-naming → references/naming}/examples/naming-lookup.md +1 -1
  85. package/skills/developing-cpp/references/naming/examples/naming-lower-layer.md +46 -0
  86. package/skills/developing-cpp/references/naming/examples/naming-player-value.md +15 -0
  87. package/skills/developing-cpp/{source/06-naming → references/naming}/examples/naming-predicate.md +1 -1
  88. package/skills/developing-cpp/{source/06-naming → references/naming}/examples/naming-role.md +1 -1
  89. package/skills/developing-cpp/references/naming/examples/naming-state-change.md +70 -0
  90. package/skills/developing-cpp/references/naming/glossary/naming-terms.md +23 -0
  91. package/skills/developing-cpp/references/naming/glossary/position.md +23 -0
  92. package/skills/developing-cpp/references/naming/glossary/square.md +47 -0
  93. package/skills/developing-cpp/references/naming/identifier-names.md +109 -0
  94. package/skills/developing-cpp/{source/02-style/01-google-cpp-style.md → references/style/google-cpp-style.md} +14 -13
  95. package/skills/developing-cpp/scripts/checking-comments.mjs +80 -15
  96. package/skills/developing-cpp/scripts/checking-declaration-order.mjs +383 -0
  97. package/skills/developing-cpp/steps/01-behavior.md +5 -5
  98. package/skills/developing-cpp/steps/02-boundary.md +9 -9
  99. package/skills/developing-cpp/steps/03-declaration.md +16 -14
  100. package/skills/developing-cpp/steps/04-implementation.md +22 -18
  101. package/skills/engineering/SKILL.md +43 -40
  102. package/skills/engineering/{cmake → references/cmake}/assets/CompileSettings.cmake +2 -0
  103. package/skills/engineering/{cmake → references/cmake}/linking/01-libraries.md +6 -0
  104. package/skills/engineering/references/cmake/linking/02-rpath.md +25 -0
  105. package/skills/engineering/{cmake → references/cmake}/linking/03-undefined-reference.md +7 -1
  106. package/skills/engineering/{cmake → references/cmake}/linking/04-inspect.md +6 -0
  107. package/skills/engineering/{cmake/02-modules/01-functions.md → references/cmake/modules/functions.md} +8 -5
  108. package/skills/engineering/{cmake/03-standard → references/cmake}/standards/README.md +12 -12
  109. package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++23/README.md +3 -3
  110. package/skills/engineering/{cmake/03-standard/01-cxx-standard.md → references/cmake/standards/cxx-standard.md} +8 -7
  111. package/skills/engineering/{cmake/01-targets → references/cmake/targets}/examples/target.md +2 -2
  112. package/skills/engineering/{cmake/01-targets/01-rules.md → references/cmake/targets/rules.md} +18 -11
  113. package/skills/engineering/{cmake → references/cmake}/testing/ctest.md +10 -3
  114. package/skills/engineering/{formatting → references/formatting}/01-encoding.md +1 -1
  115. package/skills/engineering/{formatting → references/formatting}/02-clang-format.md +7 -1
  116. package/skills/engineering/{formatting → references/formatting}/03-clang-tidy.md +7 -0
  117. package/skills/engineering/{formatting → references/formatting}/04-clangd.md +7 -0
  118. package/skills/engineering/references/formatting/examples/clang-format.md +38 -0
  119. package/skills/engineering/{formatting → references/formatting}/examples/clang-tidy.md +0 -21
  120. package/skills/engineering/{formatting → references/formatting}/scripts/checking-encoding.mjs +6 -7
  121. package/skills/engineering/{cmake/steps → steps}/01-targets.md +10 -9
  122. package/skills/engineering/{cmake/steps → steps}/02-modules.md +4 -4
  123. package/skills/engineering/{cmake/steps → steps}/03-check.md +5 -3
  124. package/skills/developing-cpp/source/03-design/01-project-design.md +0 -105
  125. package/skills/developing-cpp/source/03-design/examples/move-result.md +0 -39
  126. package/skills/developing-cpp/source/03-design/examples/preview-read.md +0 -40
  127. package/skills/developing-cpp/source/04-layout/03-declaration-order.md +0 -118
  128. package/skills/developing-cpp/source/05-language/01-language-basics/04-const.md +0 -15
  129. package/skills/developing-cpp/source/05-language/01-language-basics/05-expressions.md +0 -8
  130. package/skills/developing-cpp/source/05-language/01-language-basics/06-functions.md +0 -9
  131. package/skills/developing-cpp/source/05-language/01-language-basics/08-raii.md +0 -9
  132. package/skills/developing-cpp/source/05-language/02-value-types/03-integer-roles.md +0 -23
  133. package/skills/developing-cpp/source/05-language/02-value-types/04-enum.md +0 -17
  134. package/skills/developing-cpp/source/05-language/02-value-types/08-comparison.md +0 -4
  135. package/skills/developing-cpp/source/05-language/03-standard-library/02-access.md +0 -8
  136. package/skills/developing-cpp/source/05-language/03-standard-library/06-format.md +0 -44
  137. package/skills/developing-cpp/source/05-language/03-standard-library/07-time.md +0 -3
  138. package/skills/developing-cpp/source/05-language/03-standard-library/08-random.md +0 -3
  139. package/skills/developing-cpp/source/05-language/03-standard-library/09-files.md +0 -4
  140. package/skills/developing-cpp/source/05-language/04-performance/01-measure.md +0 -15
  141. package/skills/developing-cpp/source/05-language/04-performance/06-false-optimizations.md +0 -6
  142. package/skills/developing-cpp/source/06-naming/01-identifier-names.md +0 -78
  143. package/skills/developing-cpp/source/06-naming/examples/naming-accessor.md +0 -17
  144. package/skills/developing-cpp/source/06-naming/examples/naming-basic.md +0 -3
  145. package/skills/developing-cpp/source/06-naming/examples/naming-lower-layer.md +0 -39
  146. package/skills/developing-cpp/source/06-naming/examples/naming-player-mark.md +0 -17
  147. package/skills/developing-cpp/source/06-naming/examples/naming-state-change.md +0 -57
  148. package/skills/developing-cpp/source/07-comments/01-comment-rules.md +0 -239
  149. package/skills/developing-cpp/source/07-comments/examples/declaration-class.md +0 -44
  150. package/skills/developing-cpp/source/07-comments/examples/declaration-constructor.md +0 -22
  151. package/skills/developing-cpp/source/07-comments/examples/declaration-enum.md +0 -24
  152. package/skills/developing-cpp/source/07-comments/examples/declaration-function.md +0 -100
  153. package/skills/developing-cpp/source/07-comments/examples/declaration-member.md +0 -25
  154. package/skills/developing-cpp/source/07-comments/examples/declaration-struct.md +0 -18
  155. package/skills/developing-cpp/source/07-comments/examples/implementation-body.md +0 -42
  156. package/skills/developing-cpp/source/07-comments/glossary/comment-terms.md +0 -75
  157. package/skills/developing-cpp/source/08-exceptions/01-throw-rules.md +0 -160
  158. package/skills/engineering/cmake/linking/02-rpath.md +0 -17
  159. package/skills/engineering/formatting/examples/clang-format.md +0 -17
  160. /package/skills/developing-cpp/{source/07-comments → references/comments}/examples/implementation-todo.md +0 -0
  161. /package/skills/developing-cpp/{source/03-design → references/design}/examples/behavior-sentence.md +0 -0
  162. /package/skills/developing-cpp/{source/03-design → references/design}/examples/library-boundary.md +0 -0
  163. /package/skills/developing-cpp/{source/03-design → references/design}/examples/library-split.md +0 -0
  164. /package/skills/developing-cpp/{source/08-exceptions → references/exceptions}/examples/throw-boundary.md +0 -0
  165. /package/skills/developing-cpp/{source/08-exceptions → references/exceptions}/examples/throw-catch.md +0 -0
  166. /package/skills/developing-cpp/{source/08-exceptions → references/exceptions}/examples/throw-destructor.md +0 -0
  167. /package/skills/developing-cpp/{source/08-exceptions → references/exceptions}/examples/throw-format.md +0 -0
  168. /package/skills/developing-cpp/{source/08-exceptions → references/exceptions}/examples/throw-when.md +0 -0
  169. /package/skills/developing-cpp/{source/05-language/04-performance → references/language/performance}/07-checklist.md +0 -0
  170. /package/skills/developing-cpp/{source/05-language/03-standard-library → references/language/standard-library}/10-checklist.md +0 -0
  171. /package/skills/developing-cpp/{source/05-language/02-value-types → references/language/value-types}/05-strong-type.md +0 -0
  172. /package/skills/developing-cpp/{source/06-naming → references/naming}/examples/naming-current-prefix.md +0 -0
  173. /package/skills/developing-cpp/{source/06-naming → references/naming}/examples/naming-multiple-return.md +0 -0
  174. /package/skills/developing-cpp/{source/06-naming → references/naming}/examples/naming-rename.md +0 -0
  175. /package/skills/developing-cpp/{source/06-naming → references/naming}/examples/naming-responsibility.md +0 -0
  176. /package/skills/engineering/{cmake → references/cmake}/assets/LinkSettings.cmake +0 -0
  177. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++11/README.md +0 -0
  178. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++11/cmake-snippet.cmake +0 -0
  179. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++14/README.md +0 -0
  180. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++14/cmake-snippet.cmake +0 -0
  181. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++17/README.md +0 -0
  182. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++17/cmake-snippet.cmake +0 -0
  183. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++20/README.md +0 -0
  184. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++20/cmake-snippet.cmake +0 -0
  185. /package/skills/engineering/{cmake/03-standard → references/cmake}/standards/c++23/cmake-snippet.cmake +0 -0
  186. /package/skills/engineering/{cmake/03-standard → references/cmake/standards}/examples/standard.md +0 -0
  187. /package/skills/engineering/{cmake/01-targets → references/cmake/targets}/examples/glob.md +0 -0
  188. /package/skills/engineering/{cmake/01-targets → references/cmake/targets}/examples/rpath.md +0 -0
  189. /package/skills/engineering/{formatting → references/formatting}/examples/clangd.md +0 -0
@@ -1,6 +1,6 @@
1
1
  # Google C++ 风格:本技能采用的版本
2
2
 
3
- 以 [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) 为基线。除「异常政策」和「新工程默认 C++23」两处明确偏离外,排版、命名、头文件、包含顺序、类型和注释都按 Google 原文执行;本地习惯不能悄悄覆盖它。
3
+ 以 [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) 为基线。除「异常政策」「新工程默认 C++23」和「注释格式」三处明确偏离外,排版、命名、头文件、包含顺序和类型都按 Google 原文执行;本地习惯不能悄悄覆盖它。
4
4
 
5
5
  ## 语言版本
6
6
 
@@ -12,10 +12,10 @@
12
12
 
13
13
  ## 头文件
14
14
 
15
- - 每个头文件用 `#define` 守卫,符号由项目源码树全路径生成:`<PROJECT>_<PATH>_<FILE>_H_`,例如 `FOO_BAR_BAZ_H_`。不要用 `#pragma once`,也不要两者并存;模板见 `source/04-layout/02-file-template.md`。
15
+ - 每个头文件用 `#define` 守卫,符号由项目源码树全路径生成:`<PROJECT>_<PATH>_<FILE>_H_`,例如 `FOO_BAR_BAZ_H_`。不要用 `#pragma once`,也不要两者并存;模板见 `references/layout/02-file-template.md`。
16
16
  - 头文件必须自包含:自己用到的类型、宏、标准库头都直接包含,不依赖调用方的包含顺序。
17
17
  - `.cpp` 第一个包含自己的配对头,然后按下面的顺序包含。
18
- - 包含顺序:配对头 → C 系统头 → C++ 标准库头 → 其他库头 → 本项目头。每组之间空一行,组内按字母序;不要依赖 `clang-format` 的 `IncludeCategories` 自定义分组,本项目不再覆盖 Google 预设。
18
+ - 包含顺序:配对头 → C 系统头 → C++ 标准库头 → 其他库头 → 本项目头。每组之间空一行,组内按字母序。clang-format 的 Google 预设自带 `IncludeCategories`(`^<.*\.h>` 第一组、其余尖括号头第二组、引号头最后)并开了 `IncludeBlocks: Regroup`,配置里不写 `SortIncludes: false` 时这份分组与排序会自动落实。clang-format 按 `IncludeIsMainRegex` 从文件名推断配对头(`board_test.cpp` 配 `board.h`);文件名不遵循 `<name>` 或 `<name>_test` 时要自己把配对头放在第一条。`#include` 之间夹独立注释或 `#if` 会切断分组,这类位置要自己保持次序。需要把第三方库单独成组(例如 `<gtest/gtest.h>` 与标准库之间空一行)时,才在工程 `.clang-format` 里追加优先于 `^<.*` 的类别,并说明理由;预设已覆盖的分组不要重复手写。`clang-tidy` 的 `llvm-include-order` 按 LLVM 分组,与这条不同,不要拿来替代 clang-format。
19
19
  - 本项目头用引号写裸文件名,例如 `#include "logging.h"`。构建时把该组件的 `include/` 加入 include 搜索路径(`target_include_directories(<target> PUBLIC .../include)`),不要写 `"base/logging.h"` 这种从源码根起的长路径。
20
20
  - 公共头文件直接放在组件的 `include/` 下;不要为了「整齐」再加一层命名空间目录。
21
21
  - 跨文件共享的常量用 `inline constexpr`,放在命名空间里并带 `k` 前缀;头文件里不要定义非 inline 的普通全局变量。
@@ -24,7 +24,7 @@
24
24
 
25
25
  ## 命名
26
26
 
27
- 大小写、前缀、成员尾随 `_`、常量与枚举子的 `k` 前缀、命名空间与文件名的完整规则表,以及访问器、谓词、`Try`、映射函数、`current_` 前缀的语义角色,见 `source/06-naming/01-identifier-names.md`。本文只保留两处 Google 原文允许选择、而本项目需要统一的点:
27
+ 大小写、前缀、成员尾随 `_`、常量与枚举子的 `k` 前缀、命名空间与文件名的完整规则表,以及访问器、谓词、`Try`、映射函数、`current_` 前缀的语义角色,见 `references/naming/identifier-names.md`。本文只保留两处 Google 原文允许选择、而本项目需要统一的点:
28
28
 
29
29
  - 访问器、修改器 Google 允许 PascalCase 或 snake_case;本项目统一 PascalCase,同一 API 不混用两套。
30
30
  - 测试名用 PascalCase 描述行为,例如 `RejectsOutOfRangeTask`;测试文件用 snake_case。
@@ -34,12 +34,12 @@
34
34
  - 纯数据聚合用 `struct`;有不变量的类型用 `class`,不变量在构造函数和公共成员函数里维持。
35
35
  - 单参数构造函数写 `explicit`;零参数构造函数不写。
36
36
  - 默认成员初始化写在声明处(NSDMI),不要在构造函数初始化列表里重复。
37
- - 默认用花括号初始化:`int count{};`、`std::vector<int> values{1, 2, 3};`。成员声明处一律写 `{}`;只有需要拷贝初始化或 `auto` 推导时用 `=`;`name = {{` 只用于多行聚合常量表,单个对象和空初始化仍写 `count{}`;成员写 `=` 的例外见 `source/05-language/01-language-basics/02-initialization.md`;不要用 `()` 初始化普通对象。
37
+ - 默认用花括号初始化:`int count{};`、`std::vector<int> values{1, 2, 3};`。成员声明处一律写 `{}`;只有需要拷贝初始化或 `auto` 推导时用 `=`;`name = {{` 只用于多行聚合常量表,单个对象和空初始化仍写 `count{}`;成员写 `=` 的例外见 `references/language/language-basics/02-initialization.md`;不要用 `()` 初始化普通对象。
38
38
  - 类声明顺序:public → protected → private;类型与别名 → 静态常量 → 工厂 → 构造/赋值/析构 → 其他函数 → 数据成员。
39
39
  - 用户声明的拷贝/移动/析构函数在头文件声明、在 `.cpp` 定义;只有零参数且默认实现足够时才写 `= default`。
40
- - 查询成员函数标尾部 `const`;返回结果对象的 API 加 `[[nodiscard]]`,不要给所有非 `void` 函数机械添加。标注位置与 `friend` 的例外见 `source/05-language/02-value-types/07-nodiscard.md`。
40
+ - 查询成员函数标尾部 `const`;返回结果对象的 API 加 `[[nodiscard]]`,不要给所有非 `void` 函数机械添加。标注位置与 `friend` 的例外见 `references/language/value-types/07-nodiscard.md`。
41
41
  - 所有权优先 `std::unique_ptr`;没有共享所有权的理由时不用 `std::shared_ptr`。禁止裸 `new` / `delete`。
42
- - 禁止 C 风格强制转换;用 `static_cast`、`const_cast`、`reinterpret_cast`、`std::bit_cast`,并让 `clang-tidy` 的 `google-readability-casting` 兜底。
42
+ - 禁止 C 风格强制转换;用 `static_cast`、`const_cast`、`reinterpret_cast`,C++20 起可用 `std::bit_cast`,低标准用 `std::memcpy`;并让 `clang-tidy` 的 `google-readability-casting` 兜底。
43
43
  - `.cpp` 里不需要外部引用的 `constexpr` 直接放具名命名空间;仅一个函数使用时才用函数内 `static constexpr`;函数和类型仍放匿名命名空间。
44
44
  - 一个 `.cpp` 只写一个匿名命名空间,公开函数的定义放在它后面。
45
45
  - 常量要出 `.cpp` 时按四步升:1) 其他翻译单元要的是算出来的答案,给类加查询、表留 `.cpp`;2) 要同一份坐标但仍不是公开契约,放组件 `src/` 的私有头;3) 对方必须写 `Board::kLines` 且这是类型的稳定事实,才用类内 `public static constexpr`;不依赖某个对象的公开常量则用命名空间 `inline constexpr`;4) 第二使用方复用同一套坐标时再抽共享组件。
@@ -60,16 +60,16 @@
60
60
  - 半开区间写成两个「变量在左」的比较:`id >= 0 && id < kTaskCount`;不要写 `0 <= id`。
61
61
  - 混合优先级算术加显式括号,消除 `readability-math-missing-parentheses`。
62
62
  - 内建整数默认用 `int`;需要确定宽度时用 `<cstdint>` 的 `std::int32_t`、`std::int64_t` 等(可省略 `std::` 前缀),可能到 2^31 的值用 64 位;`std::size_t` / `std::ptrdiff_t` 只用于大小和指针差。不要用无符号类型表达「这个值不会为负」。
63
- - 封闭状态码用 `enum class`;底层类型默认 `int`,只有确实需要缩小存储时才写固定底层类型并说明理由。枚举值总是带作用域:`OrderResult::kSuccess`。
64
- - 枚举的尾随注释要么全写要么全不写;两种句式与禁止项见 `source/07-comments/01-comment-rules.md`「枚举项与 `struct` 短字段:两种句式」。
63
+ - 封闭状态码用 `enum class`;本项目固定写 `: std::uint8_t` 并逐个写出枚举值(见 `references/language/value-types/04-enum.md`,有意偏离 Google 的默认 `int`),普通枚举用默认底层类型。枚举值总是带作用域:`OrderResult::kSuccess`。
64
+ - 枚举的尾随注释要么全写要么全不写;两种句式与禁止项见 `references/comments/comment-rules.md`「枚举项与 `struct` 短字段:两种句式」。
65
65
  - 浮点不用 `==` 比较计算结果;按量纲给容差,金额用最小货币单位的整数。
66
- - 数值宽度、符号、枚举、强类型、`const` 成员和下标访问的完整规则见 `source/05-language/02-value-types/07-nodiscard.md`;初始化、RAII、移动和模板见 `source/05-language/01-language-basics/`。
66
+ - 数值宽度、符号、整数角色、枚举、强类型、`const` 成员和下标访问的完整规则见 `references/language/value-types/01-width.md`、`02-signed.md`、`03-integer-roles.md`、`04-enum.md`、`05-strong-type.md`、`06-const-method.md`、`09-subscript.md`;初始化、RAII、移动和模板见 `references/language/language-basics/`。
67
67
 
68
68
  ## 异常
69
69
 
70
- Google 原文不使用 C++ 异常;本工作流只在开发阶段的源码指导中按 `source/08-exceptions/01-throw-rules.md` 采用 C++ Core Guidelines 的 Error handling,插件运行时不编译、不执行这套策略。其余条目仍以 Google 原文为准。
70
+ Google 原文不使用 C++ 异常;本工作流只在开发阶段的源码指导中按 `references/exceptions/throw-rules.md` 采用 C++ Core Guidelines 的 Error handling,插件运行时不编译、不执行这套策略。其余条目仍以 Google 原文为准。
71
71
 
72
- 异常消息的组织方式见 `source/08-exceptions/01-throw-rules.md` 的「消息」节。
72
+ 异常消息的组织方式见 `references/exceptions/throw-rules.md` 的「消息」节。
73
73
 
74
74
  ## 输出与格式化
75
75
 
@@ -82,5 +82,6 @@ Google 原文不使用 C++ 异常;本工作流只在开发阶段的源码指
82
82
  ## 注释
83
83
 
84
84
  - 注释写意图、契约、取舍,不复述代码。
85
- - 文件头、声明注释、实现注释与配置注释的格式见 `source/07-comments/01-comment-rules.md`。
85
+ - 注释格式是本项目的第三处偏离:用 Doxygen 的 `///` 加 `@file`、`@brief`、`@param` 组织,Google 原文用 `//` 散文、文件头放 license boilerplate;本项目源码不带 license 头,分发或开源前补上。
86
+ - 文件头、声明注释、实现注释与配置注释的格式见 `references/comments/comment-style.md`,写什么见 `comment-rules.md`。
86
87
  - TODO 统一写 `// TODO: <阶段或 issue> - <要做什么>`;不要写 `@todo`、`FIXME` 或只有「参考」没有动作的占位。
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // 只读注释审计:按 source/07-comments/01-comment-rules.md 的硬规则检查 C/C++ 源文件。
2
+ // 只读注释审计:按 references/comments/comment-rules.md 的硬规则检查 C/C++ 源文件。
3
3
  //
4
4
  // 检查项:Doxygen 文件头、注释行宽度、列表缩进、标签、标签间空行、注释与声明的贴合、
5
- // 类型注释存在性、成员功能清单、设计论证(方案对比)、否定式边界、领域尺寸、谓词首句、@param 完整性、枚举成员注释一致性、枚举行尾句式、数据成员主注释位置。
5
+ // 类型注释存在性、成员功能清单、设计论证(方案对比)、否定式边界、领域尺寸、谓词首句、@param 完整性、摘要裸参数名、枚举成员注释一致性、枚举行尾句式、数据成员主注释位置。
6
6
  // 不重写任何文件。
7
7
  //
8
8
  // 用法:
@@ -33,13 +33,17 @@ const DOXY_BRIEF = /^\/\/\/\s*@brief\s+\S/
33
33
  const BLOCK_FILE = /^@file\s+\S/
34
34
  const BLOCK_BRIEF = /^@brief\s+\S/
35
35
  const MEMBER_LIST = /提供[^。]{0,40}、[^。]{0,40}(的功能|的能力|的接口)|功能[::]/
36
+ const CALLER_LIST = /调用/
37
+ const MEMBER_REF = /`(?:Get|Set|Clear|Is|Has|Can|Completes|Would|Check|ToIndex|Place|Undo|Choose)[A-Za-z0-9_]*`/
36
38
  const RATIONALE = /而不是|而非|代价.{0,4}忽略|只留一份|与其|比.{0,12}更|更(?:安全|快|清楚|直接|好写|难写)/
37
39
  const FORWARD_REF = /(?:留在|归|交给|由)\s*`?[A-Z][A-Za-z0-9_]*`?/
38
40
  const TYPE_SYSTEM = /值语义|自由拷贝/
39
41
  const NEGATED_BOUNDARY = /只保存|不拥有|不含/
40
42
  const NEGATIVE_SCOPE = /不(?:检查|校验|验证|负责|判断)/
41
43
  const DOMAIN_SIZE = /\d+\s*[×xX]\s*\d+|九格|九个格子/
42
- const PREDICATE_DECL = /^(?:\[\[nodiscard\]\]\s*)?(?:static\s+)?bool\s+(?:Is|Has|Can|Completes)[A-Za-z0-9_]*\s*\(|operator==/
44
+ const PREDICATE_DECL = /^(?:\[\[nodiscard\]\]\s*)?(?:static\s+)?bool\s+(?:Is|Has|Can|Completes|Would)[A-Za-z0-9_]*\s*\(|operator==/
45
+ const isPredicateFirstOk = (declaration, firstDocLine) =>
46
+ firstDocLine.startsWith('检查') || (declaration.includes('operator==') && firstDocLine.startsWith('相等运算符'))
43
47
  const DECL_KEYWORDS = /^(class|struct|union|enum|namespace|using|typedef|template|#|if|else|for|while|switch|return|case|default)\b/
44
48
 
45
49
  function usage(message) {
@@ -135,16 +139,44 @@ export function displayWidth(text) {
135
139
  return width
136
140
  }
137
141
 
138
- /** 标签块开始后是否出现空行;描述与首个标签之间的空行不算。 */
142
+ const TAG_GROUPS = {
143
+ param: 'param',
144
+ tparam: 'param',
145
+ return: 'return',
146
+ returns: 'return',
147
+ retval: 'return',
148
+ result: 'return',
149
+ throws: 'throws',
150
+ throw: 'throws',
151
+ exception: 'throws',
152
+ note: 'note',
153
+ }
154
+
155
+ /** 取标签所属分组;参数、返回值、异常、说明各成一组。 */
156
+ function tagGroupOf(tag) {
157
+ const name = tag.slice(1).toLowerCase().split(/[\s{[(]/)[0]
158
+ return TAG_GROUPS[name] ?? 'other'
159
+ }
160
+
161
+ /** 分组之间允许空行;同一分组内出现空行才算标签粘连。描述与首个标签之间的空行不算。 */
139
162
  function hasTagGap(contents) {
140
- let seenTag = false
163
+ let lastGroup = null
164
+ let pendingGap = false
141
165
  for (const content of contents) {
142
166
  const trimmed = content.trim()
143
167
  if (trimmed.startsWith('@')) {
144
- seenTag = true
168
+ const group = tagGroupOf(trimmed)
169
+ if (pendingGap && lastGroup === group) return true
170
+ pendingGap = false
171
+ lastGroup = group
145
172
  continue
146
173
  }
147
- if (seenTag && trimmed === '') return true
174
+ if (trimmed === '') {
175
+ if (lastGroup !== null) pendingGap = true
176
+ continue
177
+ }
178
+ // 空行后接正文是标签说明内的段落,不是分组分隔,取消待定空行
179
+ pendingGap = false
148
180
  }
149
181
  return false
150
182
  }
@@ -210,6 +242,23 @@ export function functionParams(declaration) {
210
242
  return splitParams(decl.slice(open + 1, close)).map(paramName).filter(Boolean)
211
243
  }
212
244
 
245
+ /** 取函数注释第一段:遇到空行或 Doxygen 标签就结束。 */
246
+ function summaryParagraph(contents) {
247
+ const paragraph = []
248
+ for (const line of contents) {
249
+ const text = line.trim()
250
+ if (text === '' || text.startsWith('@')) break
251
+ paragraph.push(text)
252
+ }
253
+ return paragraph.join(' ')
254
+ }
255
+
256
+ /** 判断摘要中是否直接出现了参数名。 */
257
+ function mentionsParam(text, name) {
258
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
259
+ return new RegExp(`(^|[^A-Za-z0-9_])${escaped}([^A-Za-z0-9_]|$)`).test(text)
260
+ }
261
+
213
262
  /** 标记每一行是否位于 class/struct 体内,供数据成员注释位置检查使用。 */
214
263
  function classMemberLines(lines) {
215
264
  const flags = new Array(lines.length).fill(false)
@@ -330,7 +379,7 @@ export function checkText(text, options = {}) {
330
379
  }
331
380
  for (const tag of FORBIDDEN_TAGS) {
332
381
  if (options.allowTags?.has(tag.slice(1))) continue
333
- if (trimmed.includes(tag)) add(index + 1, 'forbidden-tag', `禁止使用 ${tag},按 source/07-comments/01-comment-rules.md 的标签表改写`)
382
+ if (trimmed.includes(tag)) add(index + 1, 'forbidden-tag', `禁止使用 ${tag},按 references/comments/comment-rules.md 的标签表改写`)
334
383
  }
335
384
  }
336
385
  }
@@ -344,7 +393,7 @@ export function checkText(text, options = {}) {
344
393
  if (displayWidth(rendered) > width) add(doc.start + 1, 'comment-width', `注释行 ${displayWidth(rendered)} 列,超过 ${width} 列`)
345
394
  for (const tag of FORBIDDEN_TAGS) {
346
395
  if (options.allowTags?.has(tag.slice(1))) continue
347
- if (content.includes(tag)) add(doc.start + 1, 'forbidden-tag', `禁止使用 ${tag},按 source/07-comments/01-comment-rules.md 的标签表改写`)
396
+ if (content.includes(tag)) add(doc.start + 1, 'forbidden-tag', `禁止使用 ${tag},按 references/comments/comment-rules.md 的标签表改写`)
348
397
  }
349
398
  }
350
399
  for (let raw = doc.start; raw <= doc.end; raw += 1) {
@@ -353,7 +402,7 @@ export function checkText(text, options = {}) {
353
402
  }
354
403
  }
355
404
  if (!doc.contents.some((content) => content.includes('@file')) && hasTagGap(doc.contents)) {
356
- add(doc.start + 1, 'tag-gap', 'Doxygen 标签之间有空行:描述与标签组之间空一行,标签之间不空行')
405
+ add(doc.start + 1, 'tag-gap', '同一分组内的 Doxygen 标签之间有空行:参数、返回值、异常、说明各成一组,组间空一行,组内连续')
357
406
  }
358
407
  index = doc.end
359
408
  }
@@ -382,9 +431,12 @@ export function checkText(text, options = {}) {
382
431
  const block = lines.slice(start, end + 1).join('\n')
383
432
  const docContents = lines.slice(start, end + 1).map((line) => line.trim().replace(/^\/\/\/\s?/, ''))
384
433
  if (hasTagGap(docContents)) {
385
- add(start + 1, 'tag-gap', 'Doxygen 标签之间有空行:描述与标签组之间空一行,标签之间不空行')
434
+ add(start + 1, 'tag-gap', '同一分组内的 Doxygen 标签之间有空行:参数、返回值、异常、说明各成一组,组间空一行,组内连续')
386
435
  }
387
436
  const isType = /^(template\s*<[^>]*>\s*)?(class|struct|union|enum)\b/.test(declaration)
437
+ if (!isType && CALLER_LIST.test(block) && MEMBER_REF.test(block)) {
438
+ add(start + 1, 'caller-list', '函数注释在点名调用者:调用关系会随重构过期,只写这个函数做什么、参数、返回值与异常')
439
+ }
388
440
  if (RATIONALE.test(block)) {
389
441
  add(start + 1, 'rationale', '注释在写设计取舍:方案对比与理由移到正文或实现注释,接口注释只留契约')
390
442
  }
@@ -404,14 +456,19 @@ export function checkText(text, options = {}) {
404
456
  add(start + 1, 'negative-scope', '注释用「不检查/不校验/不负责/不判断」写能力边界:改成正向限定,前置条件写「调用方保证…」或 @pre')
405
457
  }
406
458
  if (isType && DOMAIN_SIZE.test(block)) {
407
- add(start + 1, 'domain-size', '类型注释在写领域尺寸:格子数由 cells_ 之类成员声明表达,删掉这句')
459
+ add(start + 1, 'domain-size', '类型注释在写领域尺寸:格子数由 squares_ 之类成员声明表达,删掉这句')
408
460
  }
409
461
  const firstDocLine = lines[start].trim().replace(/^\/\/\/\s*/, '')
410
- if (!isType && PREDICATE_DECL.test(declaration) && !firstDocLine.startsWith('检查')) {
462
+ if (!isType && PREDICATE_DECL.test(declaration) && !isPredicateFirstOk(declaration, firstDocLine)) {
411
463
  add(start + 1, 'predicate-first', '布尔查询或 operator== 的第一句应写「检查…是否…」')
412
464
  }
413
465
  const params = functionParams(declaration)
414
466
  if (!params) continue
467
+ const summary = summaryParagraph(docContents)
468
+ const named = params.filter((name) => mentionsParam(summary, name))
469
+ if (named.length > 0) {
470
+ add(start + 1, 'param-in-summary', `函数摘要直接写了参数名 ${named.join('、')}:改用「指定坐标」「传入的值」这类语义名词,参数名只放在 @param 行`)
471
+ }
415
472
  const documented = [...block.matchAll(/@param(?:\[[^\]]*\])?\s+(\w+)/g)].map((match) => match[1])
416
473
  if (documented.length === 0) continue
417
474
  for (const name of params) {
@@ -440,19 +497,27 @@ export function checkText(text, options = {}) {
440
497
  const declaration = lines[next].trim()
441
498
  const block = doc.contents.join('\n')
442
499
  const isType = /^(template\s*<[^>]*>\s*)?(class|struct|union|enum)\b/.test(declaration)
500
+ if (!isType && CALLER_LIST.test(block) && MEMBER_REF.test(block)) {
501
+ add(doc.start + 1, 'caller-list', '函数注释在点名调用者:调用关系会随重构过期,只写这个函数做什么、参数、返回值与异常')
502
+ }
443
503
  if (RATIONALE.test(block)) add(doc.start + 1, 'rationale', '注释在写设计取舍:方案对比与理由移到正文或实现注释,接口注释只留契约')
444
504
  if (isType && MEMBER_LIST.test(block)) add(doc.start + 1, 'member-list', '类型注释在罗列成员功能,应改写为概念与使用约定')
445
505
  if (isType && FORWARD_REF.test(block)) add(doc.start + 1, 'forward-ref', '类型注释在交代别的类型负责什么:只写本类型的契约,删掉这句,不要挪到文件头')
446
506
  if (isType && TYPE_SYSTEM.test(block)) add(doc.start + 1, 'type-system', '类型注释在复述类型系统已表达的性质:可拷贝与 const 查询由声明给出,删掉这句')
447
507
  if (isType && NEGATED_BOUNDARY.test(block)) add(doc.start + 1, 'negated-boundary', '类型注释用「只保存/不拥有/不含」写否定式边界:改成名词短语,边界交给成员类型表达')
448
508
  if (NEGATIVE_SCOPE.test(block)) add(doc.start + 1, 'negative-scope', '注释用「不检查/不校验/不负责/不判断」写能力边界:改成正向限定,前置条件写「调用方保证…」或 @pre')
449
- if (isType && DOMAIN_SIZE.test(block)) add(doc.start + 1, 'domain-size', '类型注释在写领域尺寸:格子数由 cells_ 之类成员声明表达,删掉这句')
509
+ if (isType && DOMAIN_SIZE.test(block)) add(doc.start + 1, 'domain-size', '类型注释在写领域尺寸:格子数由 squares_ 之类成员声明表达,删掉这句')
450
510
  const firstDocLine = doc.contents[0] ?? ''
451
- if (!isType && PREDICATE_DECL.test(declaration) && !firstDocLine.startsWith('检查')) {
511
+ if (!isType && PREDICATE_DECL.test(declaration) && !isPredicateFirstOk(declaration, firstDocLine)) {
452
512
  add(doc.start + 1, 'predicate-first', '布尔查询或 operator== 的第一句应写「检查…是否…」')
453
513
  }
454
514
  const params = functionParams(declaration)
455
515
  if (!params) continue
516
+ const summary = summaryParagraph(doc.contents)
517
+ const named = params.filter((name) => mentionsParam(summary, name))
518
+ if (named.length > 0) {
519
+ add(doc.start + 1, 'param-in-summary', `函数摘要直接写了参数名 ${named.join('、')}:改用「指定坐标」「传入的值」这类语义名词,参数名只放在 @param 行`)
520
+ }
456
521
  const documented = [...block.matchAll(/@param(?:\[[^\]]*\])?\s+(\w+)/g)].map((match) => match[1])
457
522
  if (documented.length === 0) continue
458
523
  for (const name of params) {
@@ -0,0 +1,383 @@
1
+ #!/usr/bin/env node
2
+ // 只读检查 `.cpp` 中成员函数的定义顺序是否跟随配对头文件的声明顺序。
3
+ //
4
+ // 规则见 references/layout/03-declaration-order.md「`.cpp` 的定义顺序」:
5
+ // 先类型常量、再自由函数、再成员函数;成员按类内声明顺序;构造函数、析构函数、
6
+ // 拷贝与移动放在成员组最前;不为先编译而重排。
7
+ //
8
+ // 本脚本只比较能在配对头文件里找到声明的类成员;自由函数与匿名命名空间不参与,
9
+ // 头文件里没有声明的定义直接跳过,避免把另一个头文件的实现误报成乱序。
10
+ //
11
+ // 用法:
12
+ // node checking-declaration-order.mjs [--root DIR] [--json] [--quiet]
13
+ //
14
+ // 退出码:0 无问题,1 发现乱序,2 用法或读取错误。
15
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
16
+ import path from 'node:path'
17
+ import { pathToFileURL } from 'node:url'
18
+
19
+ export const EXIT = { ok: 0, issues: 1, usage: 2 }
20
+
21
+ const HEADER_EXT = new Set(['.h', '.hh', '.hpp', '.hxx', '.h++', '.inl', '.ipp', '.tpp'])
22
+ const SOURCE_EXT = new Set(['.cpp', '.cc', '.cxx', '.c++'])
23
+ const SKIP_DIR = new Set([
24
+ '.git', '.hg', '.svn', 'build', 'build-release', 'out', 'node_modules', '_book', '.quarto',
25
+ '.cache', '.tmp', 'temp', 'third_party', 'third-party', 'external', 'vendor', 'deps',
26
+ 'cmake-build-debug', 'cmake-build-release', '.vs', '.idea',
27
+ ])
28
+ const PREDICATE_NAME = /^(?:Is|Has|Can|Completes|Would)[A-Za-z0-9_]*$/
29
+
30
+ function usage(message) {
31
+ if (message) process.stderr.write(`错误:${message}\n`)
32
+ process.stderr.write('用法:node checking-declaration-order.mjs [--root DIR] [--json] [--quiet]\n')
33
+ return EXIT.usage
34
+ }
35
+
36
+ function parseArgs(argv) {
37
+ const options = { root: undefined, json: false, quiet: false, help: false }
38
+ for (let index = 0; index < argv.length; index += 1) {
39
+ const arg = argv[index]
40
+ if (arg === '--root') {
41
+ options.root = argv[index + 1]
42
+ if (!options.root) throw new Error('--root 需要目录')
43
+ index += 1
44
+ } else if (arg === '--json') {
45
+ options.json = true
46
+ } else if (arg === '--quiet') {
47
+ options.quiet = true
48
+ } else if (arg === '--help' || arg === '-h') {
49
+ options.help = true
50
+ } else {
51
+ throw new Error(`未知参数:${arg}`)
52
+ }
53
+ }
54
+ return options
55
+ }
56
+
57
+ /** 去掉注释与字符串,保留换行,便于按行号定位。 */
58
+ export function stripCommentsAndStrings(text) {
59
+ const out = text.split('')
60
+ let index = 0
61
+ while (index < text.length) {
62
+ const char = text[index]
63
+ const next = text[index + 1]
64
+ if (char === '/' && next === '/') {
65
+ while (index < text.length && text[index] !== '\n') out[index++] = ' '
66
+ continue
67
+ }
68
+ if (char === '/' && next === '*') {
69
+ out[index++] = ' '
70
+ out[index++] = ' '
71
+ while (index < text.length && !(text[index] === '*' && text[index + 1] === '/')) {
72
+ if (text[index] !== '\n') out[index] = ' '
73
+ index += 1
74
+ }
75
+ if (index < text.length) {
76
+ out[index++] = ' '
77
+ out[index++] = ' '
78
+ }
79
+ continue
80
+ }
81
+ if (char === 'R' && next === '"') {
82
+ const open = text.indexOf('(', index + 2)
83
+ if (open !== -1) {
84
+ const delimiter = text.slice(index + 2, open)
85
+ const close = text.indexOf(`)${delimiter}"`, open + 1)
86
+ const end = close === -1 ? text.length : close + delimiter.length + 2
87
+ for (; index < end; index += 1) if (text[index] !== '\n') out[index] = ' '
88
+ continue
89
+ }
90
+ }
91
+ if (char === '"' || char === "'") {
92
+ const quote = char
93
+ out[index++] = ' '
94
+ while (index < text.length) {
95
+ if (text[index] === '\\') {
96
+ out[index++] = ' '
97
+ if (index < text.length) out[index++] = ' '
98
+ continue
99
+ }
100
+ if (text[index] === quote) {
101
+ out[index++] = ' '
102
+ break
103
+ }
104
+ if (text[index] !== '\n') out[index] = ' '
105
+ index += 1
106
+ }
107
+ continue
108
+ }
109
+ index += 1
110
+ }
111
+ return out.join('')
112
+ }
113
+
114
+ function lineAt(text, index) {
115
+ let line = 1
116
+ for (let cursor = 0; cursor < index && cursor < text.length; cursor += 1) {
117
+ if (text[cursor] === '\n') line += 1
118
+ }
119
+ return line
120
+ }
121
+
122
+ function matchBrace(text, open) {
123
+ let depth = 0
124
+ for (let index = open; index < text.length; index += 1) {
125
+ if (text[index] === '{') depth += 1
126
+ else if (text[index] === '}') {
127
+ depth -= 1
128
+ if (depth === 0) return index
129
+ }
130
+ }
131
+ return -1
132
+ }
133
+
134
+ /** 收集头文件里的 class/struct 名称与类体范围。 */
135
+ export function findClasses(text) {
136
+ const code = stripCommentsAndStrings(text)
137
+ const classes = []
138
+ const pattern = /\b(class|struct)\s+([A-Za-z_]\w*)\b[^;{}]*\{/g
139
+ let match
140
+ while ((match = pattern.exec(code)) !== null) {
141
+ const keyword = match[1]
142
+ const name = match[2]
143
+ const before = code.slice(Math.max(0, match.index - 6), match.index)
144
+ if (keyword === 'class' && /enum\s*$/.test(before)) continue
145
+ const open = code.indexOf('{', match.index)
146
+ const close = matchBrace(code, open)
147
+ if (close === -1) continue
148
+ classes.push({ name, body: code.slice(open + 1, close), bodyStart: open + 1 })
149
+ pattern.lastIndex = close + 1
150
+ }
151
+ return classes
152
+ }
153
+
154
+ function normalizeStatement(statement) {
155
+ return statement
156
+ .replace(/\[\[[^\]]*\]\]/g, ' ')
157
+ .replace(/\s+/g, ' ')
158
+ .trim()
159
+ }
160
+
161
+ /** 从一个类体里按声明顺序提取可定义的成员函数名。 */
162
+ export function classMembers(body) {
163
+ const clean = body.replace(/\b(public|private|protected)\s*:/g, ' ')
164
+ const members = []
165
+ let index = 0
166
+ while (index < clean.length) {
167
+ while (index < clean.length && /\s/.test(clean[index])) index += 1
168
+ if (index >= clean.length) break
169
+ if (clean[index] === '{') {
170
+ const close = matchBrace(clean, index)
171
+ if (close === -1) break
172
+ index = close + 1
173
+ while (index < clean.length && /[\s;]/.test(clean[index])) index += 1
174
+ continue
175
+ }
176
+ const start = index
177
+ let paren = 0
178
+ let angle = 0
179
+ let brace = 0
180
+ for (; index < clean.length; index += 1) {
181
+ const char = clean[index]
182
+ if (char === '(') paren += 1
183
+ else if (char === ')') paren = Math.max(0, paren - 1)
184
+ else if (char === '<') angle += 1
185
+ else if (char === '>') angle = Math.max(0, angle - 1)
186
+ else if (char === '{') brace += 1
187
+ else if (char === '}') {
188
+ if (brace === 0) break
189
+ brace -= 1
190
+ } else if (char === ';' && paren === 0 && brace === 0) break
191
+ }
192
+ const statement = clean.slice(start, index)
193
+ index += 1
194
+ const text = normalizeStatement(statement)
195
+ if (!text || /^(using|typedef|friend\s+class|static_assert|enum|class|struct|union|namespace)\b/.test(text)) {
196
+ continue
197
+ }
198
+ if (!text.includes('(')) continue
199
+ const name = memberName(text)
200
+ if (name) members.push({ name, text })
201
+ }
202
+ return members
203
+ }
204
+
205
+ function memberName(text) {
206
+ let value = text
207
+ .replace(/^template\s*<[^>]*>\s*/, '')
208
+ .replace(/^(?:static|inline|virtual|constexpr|consteval|explicit|friend|extern)\s+/g, '')
209
+ .trim()
210
+ const operator = /(?:^|\s)(operator\s*[^\s(]+)\s*\(/.exec(value)
211
+ if (operator) return operator[1].replace(/\s+/g, ' ')
212
+ const destructor = /(?:^|\s)(~[A-Za-z_]\w*)\s*\(/.exec(value)
213
+ if (destructor) return destructor[1]
214
+ const constructor = /(?:^|\s)([A-Za-z_]\w*)\s*\(/.exec(value)
215
+ if (constructor && (value.startsWith(`${constructor[1]}(`) || /\bexplicit\s+$/.test(value.slice(0, constructor.index + 1)))) {
216
+ return constructor[1]
217
+ }
218
+ const fn = /([A-Za-z_]\w*)\s*\(/.exec(value)
219
+ return fn ? fn[1] : undefined
220
+ }
221
+
222
+ /** 找出 `.cpp` 中形如 `Type Class::Name(` 的定义及其行号。 */
223
+ export function cppDefinitions(text) {
224
+ const code = stripCommentsAndStrings(text)
225
+ const definitions = []
226
+ const lines = code.split('\n')
227
+ for (let index = 0; index < lines.length; index += 1) {
228
+ const line = lines[index]
229
+ const match = /^\s*(?:template\s*<[^>]*>\s*)?(?:[A-Za-z_][\w:<>,\s*&]*?\s+)?([A-Za-z_]\w*)::(~?[A-Za-z_]\w*|operator\s*[^\s(]+)\s*\(/.exec(line)
230
+ if (!match) continue
231
+ definitions.push({
232
+ className: match[1],
233
+ name: match[2].replace(/\s+/g, ' '),
234
+ line: index + 1,
235
+ text: line.trim(),
236
+ })
237
+ }
238
+ return definitions
239
+ }
240
+
241
+ /** 检查头文件类内谓词是否排在 Get 之后。 */
242
+ export function checkHeaderOrder(headerText) {
243
+ const classes = findClasses(headerText)
244
+ const issues = []
245
+ for (const item of classes) {
246
+ const members = classMembers(item.body)
247
+ let seenGet = false
248
+ for (const member of members) {
249
+ if (member.name.startsWith('Get')) {
250
+ seenGet = true
251
+ continue
252
+ }
253
+ if (!seenGet || !PREDICATE_NAME.test(member.name)) continue
254
+ const index = headerText.search(new RegExp(`\\b${member.name}\\s*\\(`))
255
+ const line = index === -1 ? 1 : headerText.slice(0, index).split('\n').length
256
+ issues.push({
257
+ line,
258
+ rule: 'header-order',
259
+ message: `${item.name}::${member.name} 是谓词,却排在 Get 之后;谓词 Is / Has / Can / Completes / Would 应放在 Get 之前。`,
260
+ })
261
+ }
262
+ }
263
+ return issues
264
+ }
265
+
266
+ /** 比较一个头文件与一个实现文件;返回乱序问题。 */
267
+ export function checkPair(headerText, cppText, fileName = '') {
268
+ const classes = findClasses(headerText)
269
+ const definitions = cppDefinitions(cppText)
270
+ const issues = checkHeaderOrder(headerText)
271
+ for (const item of classes) {
272
+ const members = classMembers(item.body)
273
+ if (members.length === 0) continue
274
+ const declared = members.map((member) => member.name)
275
+ const defined = definitions.filter((definition) => definition.className === item.name)
276
+ let cursor = 0
277
+ let previous
278
+ for (const definition of defined) {
279
+ let found = declared.indexOf(definition.name, cursor)
280
+ if (found === -1 && declared.includes(definition.name)) {
281
+ issues.push({
282
+ line: definition.line,
283
+ rule: 'definition-order',
284
+ message: `${item.name}::${definition.name} 出现在 ${previous ? `${item.name}::${previous} 之后` : '成员组开头'};头文件声明的顺序是 ${declared.join(' → ')}。`,
285
+ })
286
+ continue
287
+ }
288
+ if (found === -1) continue
289
+ cursor = found + 1
290
+ previous = definition.name
291
+ }
292
+ }
293
+ return issues.map((issue) => ({ file: fileName, ...issue }))
294
+ }
295
+
296
+ function collectFiles(root) {
297
+ const files = { headers: [], sources: [] }
298
+ const walk = (dir) => {
299
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
300
+ const full = path.join(dir, entry.name)
301
+ if (entry.isDirectory()) {
302
+ if (SKIP_DIR.has(entry.name.toLowerCase()) || entry.name.startsWith('.')) continue
303
+ walk(full)
304
+ continue
305
+ }
306
+ if (!entry.isFile()) continue
307
+ const extension = path.extname(entry.name).toLowerCase()
308
+ if (HEADER_EXT.has(extension)) files.headers.push(full)
309
+ if (SOURCE_EXT.has(extension)) files.sources.push(full)
310
+ }
311
+ }
312
+ if (statSync(root).isFile()) {
313
+ const extension = path.extname(root).toLowerCase()
314
+ if (HEADER_EXT.has(extension)) files.headers.push(root)
315
+ if (SOURCE_EXT.has(extension)) files.sources.push(root)
316
+ } else {
317
+ walk(root)
318
+ }
319
+ files.headers.sort()
320
+ files.sources.sort()
321
+ return files
322
+ }
323
+
324
+ export function checkRoot(root) {
325
+ const files = collectFiles(root)
326
+ const headers = new Map()
327
+ for (const file of files.headers) {
328
+ const stem = path.basename(file, path.extname(file))
329
+ const bucket = headers.get(stem) ?? []
330
+ bucket.push(file)
331
+ headers.set(stem, bucket)
332
+ }
333
+ const pairs = []
334
+ const issues = []
335
+ for (const file of files.sources) {
336
+ const stem = path.basename(file, path.extname(file))
337
+ const candidates = headers.get(stem) ?? []
338
+ if (candidates.length !== 1) continue
339
+ const header = candidates[0]
340
+ const headerText = readFileSync(header, 'utf8')
341
+ const cppText = readFileSync(file, 'utf8')
342
+ const relative = path.relative(root, file) || file
343
+ const found = checkPair(headerText, cppText, relative)
344
+ pairs.push({ header, source: file, issues: found })
345
+ issues.push(...found)
346
+ }
347
+ return { pairs, issues }
348
+ }
349
+
350
+ function main(argv) {
351
+ let options
352
+ try {
353
+ options = parseArgs(argv)
354
+ } catch (error) {
355
+ return usage(error.message)
356
+ }
357
+ if (options.help) return usage()
358
+ const root = options.root ? path.resolve(options.root) : process.cwd()
359
+ try {
360
+ statSync(root)
361
+ } catch {
362
+ return usage(`根目录不存在或无法读取:${root}`)
363
+ }
364
+ let result
365
+ try {
366
+ result = checkRoot(root)
367
+ } catch (error) {
368
+ return usage(`读取 ${root} 失败:${error.message}`)
369
+ }
370
+ if (options.json) {
371
+ process.stdout.write(`${JSON.stringify({ root, pairs: result.pairs.length, issues: result.issues }, null, 2)}\n`)
372
+ } else if (result.issues.length > 0) {
373
+ for (const issue of result.issues) process.stdout.write(`${issue.file}:${issue.line}: [${issue.rule}] ${issue.message}\n`)
374
+ process.stdout.write(`发现 ${result.issues.length} 处定义顺序问题。\n`)
375
+ } else if (!options.quiet) {
376
+ process.stdout.write(`定义顺序检查通过:${result.pairs.length} 对头文件与实现文件。\n`)
377
+ }
378
+ return result.issues.length === 0 ? EXIT.ok : EXIT.issues
379
+ }
380
+
381
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
382
+ process.exitCode = main(process.argv.slice(2))
383
+ }