@chengzhao-dev/dsh-cpp-workflow 0.7.9 → 0.7.11

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 (126) hide show
  1. package/README.en.md +8 -7
  2. package/README.md +5 -4
  3. package/cordis.patch.yml +2 -2
  4. package/icon.svg +5 -5
  5. package/lib/client.js +542 -538
  6. package/lib/comment-policy.js +37 -33
  7. package/lib/workspace.js +8 -10
  8. package/locale/en.json +4 -4
  9. package/locale/zh.json +4 -4
  10. package/package.json +100 -100
  11. package/skills/building-cpp/SKILL.md +5 -5
  12. package/skills/building-cpp/assets/config/.clang-tidy +4 -5
  13. package/skills/building-cpp/assets/config/.clangd +5 -7
  14. package/skills/building-cpp/assets/config/.vscode/extensions.json +5 -5
  15. package/skills/building-cpp/assets/config/.vscode/settings.json +56 -58
  16. package/skills/building-cpp/examples/environment.md +13 -102
  17. package/skills/building-cpp/references/01-build-script.md +3 -3
  18. package/skills/building-cpp/references/02-environment.md +8 -8
  19. package/skills/building-cpp/scripts/checking-environment.mjs +424 -424
  20. package/skills/building-cpp/steps/01-build.md +10 -10
  21. package/skills/building-cpp/steps/02-tooling.md +6 -6
  22. package/skills/building-cpp/steps/03-check.md +2 -2
  23. package/skills/building-cpp/steps/04-vscode.md +4 -6
  24. package/skills/developing-cpp/SKILL.md +8 -9
  25. package/skills/developing-cpp/references/comments/01-comment-rules.md +50 -26
  26. package/skills/developing-cpp/references/comments/02-style.md +33 -25
  27. package/skills/developing-cpp/references/comments/examples/03-declaration-enum.md +14 -14
  28. package/skills/developing-cpp/references/comments/examples/04-declaration-file.md +12 -8
  29. package/skills/developing-cpp/references/comments/examples/05-declaration-function.md +20 -10
  30. package/skills/developing-cpp/references/comments/examples/06-declaration-member.md +4 -4
  31. package/skills/developing-cpp/references/comments/examples/07-declaration-predicate.md +2 -2
  32. package/skills/developing-cpp/references/comments/examples/08-declaration-struct.md +6 -6
  33. package/skills/developing-cpp/references/comments/examples/09-implementation-body.md +41 -41
  34. package/skills/developing-cpp/references/comments/glossary/01-comment-terms.md +17 -16
  35. package/skills/developing-cpp/references/design/01-project-design.md +21 -10
  36. package/skills/developing-cpp/references/design/02-raii.md +5 -4
  37. package/skills/developing-cpp/references/design/03-third-party.md +2 -2
  38. package/skills/developing-cpp/references/design/examples/02-coordinate-table.md +12 -12
  39. package/skills/developing-cpp/references/design/examples/03-header-place.md +1 -1
  40. package/skills/developing-cpp/references/design/examples/04-library-boundary.md +6 -6
  41. package/skills/developing-cpp/references/design/examples/06-move-result.md +29 -28
  42. package/skills/developing-cpp/references/design/examples/07-preview-read.md +24 -23
  43. package/skills/developing-cpp/references/design/examples/08-screen-enter-exit.md +19 -18
  44. package/skills/developing-cpp/references/design/examples/09-option-menu.md +6 -6
  45. package/skills/developing-cpp/references/design/session-layer.md +13 -22
  46. package/skills/developing-cpp/references/exceptions/01-exception-rules.md +57 -57
  47. package/skills/developing-cpp/references/exceptions/examples/01-throw-boundary.md +7 -20
  48. package/skills/developing-cpp/references/exceptions/examples/02-throw-build-mode.md +10 -11
  49. package/skills/developing-cpp/references/exceptions/examples/03-throw-catch.md +4 -4
  50. package/skills/developing-cpp/references/exceptions/examples/04-throw-destructor.md +9 -5
  51. package/skills/developing-cpp/references/exceptions/examples/07-throw-when.md +2 -2
  52. package/skills/developing-cpp/references/index.md +32 -35
  53. package/skills/developing-cpp/references/language/glossary/01-language-terms.md +3 -2
  54. package/skills/developing-cpp/references/language/language-basics/02-initialization.md +1 -1
  55. package/skills/developing-cpp/references/language/language-basics/05-expressions.md +9 -2
  56. package/skills/developing-cpp/references/language/language-basics/06-functions.md +2 -3
  57. package/skills/developing-cpp/references/language/language-basics/09-templates.md +3 -3
  58. package/skills/developing-cpp/references/language/language-basics/10-language-checklist.md +9 -9
  59. package/skills/developing-cpp/references/language/performance/03-memory.md +1 -1
  60. package/skills/developing-cpp/references/language/performance/07-checklist.md +6 -6
  61. package/skills/developing-cpp/references/language/standard-library/01-containers.md +4 -5
  62. package/skills/developing-cpp/references/language/standard-library/02-access.md +2 -5
  63. package/skills/developing-cpp/references/language/standard-library/05-string.md +1 -1
  64. package/skills/developing-cpp/references/language/standard-library/06-format.md +22 -20
  65. package/skills/developing-cpp/references/language/standard-library/{11-format-ecosystem.md → 07-format-ecosystem.md} +2 -11
  66. package/skills/developing-cpp/references/language/standard-library/{07-time.md → 08-time.md} +1 -1
  67. package/skills/developing-cpp/references/language/standard-library/{09-files.md → 10-files.md} +1 -1
  68. package/skills/developing-cpp/references/language/standard-library/11-library-checklist.md +8 -0
  69. package/skills/developing-cpp/references/language/value-types/02-signed.md +7 -7
  70. package/skills/developing-cpp/references/language/value-types/03-integer-roles.md +14 -2
  71. package/skills/developing-cpp/references/language/value-types/05-strong-type.md +2 -2
  72. package/skills/developing-cpp/references/language/value-types/06-const-method.md +5 -5
  73. package/skills/developing-cpp/references/language/value-types/07-nodiscard.md +1 -1
  74. package/skills/developing-cpp/references/language/value-types/08-comparison.md +1 -1
  75. package/skills/developing-cpp/references/language/value-types/09-subscript.md +1 -1
  76. package/skills/developing-cpp/references/language/value-types/11-checklist.md +7 -7
  77. package/skills/developing-cpp/references/layout/01-source-layout.md +13 -13
  78. package/skills/developing-cpp/references/layout/02-file-template.md +10 -10
  79. package/skills/developing-cpp/references/layout/03-declaration-order.md +83 -42
  80. package/skills/developing-cpp/references/naming/01-identifier-names.md +32 -30
  81. package/skills/developing-cpp/references/naming/examples/06-naming-lower-layer.md +15 -15
  82. package/skills/developing-cpp/references/naming/examples/07-naming-multiple-return.md +2 -2
  83. package/skills/developing-cpp/references/naming/examples/13-naming-state-change.md +24 -23
  84. package/skills/developing-cpp/references/naming/glossary/01-naming-terms.md +3 -3
  85. package/skills/developing-cpp/references/naming/glossary/02-position.md +9 -9
  86. package/skills/developing-cpp/references/naming/glossary/03-selection.md +5 -1
  87. package/skills/developing-cpp/references/naming/glossary/04-square.md +3 -3
  88. package/skills/developing-cpp/references/naming/glossary/05-scoring.md +2 -2
  89. package/skills/developing-cpp/references/naming/glossary/06-difficulty.md +7 -7
  90. package/skills/developing-cpp/references/naming/glossary/07-stream.md +1 -1
  91. package/skills/developing-cpp/references/style/01-google-cpp-style.md +13 -23
  92. package/skills/developing-cpp/scripts/checking-comments.mjs +961 -755
  93. package/skills/developing-cpp/scripts/checking-declaration-order.mjs +512 -515
  94. package/skills/developing-cpp/steps/01-behavior.md +0 -1
  95. package/skills/developing-cpp/steps/02-boundary.md +2 -3
  96. package/skills/developing-cpp/steps/03-declaration.md +9 -10
  97. package/skills/developing-cpp/steps/04-implementation.md +7 -8
  98. package/skills/engineering/SKILL.md +9 -10
  99. package/skills/engineering/references/cmake/assets/LinkSettings.cmake +1 -1
  100. package/skills/engineering/references/cmake/linking/02-rpath.md +5 -6
  101. package/skills/engineering/references/cmake/modules/01-functions.md +9 -9
  102. package/skills/engineering/references/cmake/standards/01-cxx-standard.md +6 -6
  103. package/skills/engineering/references/cmake/standards/index.md +8 -29
  104. package/skills/engineering/references/cmake/targets/01-target-rules.md +14 -13
  105. package/skills/engineering/references/cmake/targets/examples/01-rpath.md +1 -1
  106. package/skills/engineering/references/cmake/testing/01-ctest.md +3 -3
  107. package/skills/engineering/references/formatting/01-encoding.md +5 -5
  108. package/skills/engineering/references/formatting/02-clang-format.md +2 -2
  109. package/skills/engineering/references/formatting/03-clang-tidy.md +5 -5
  110. package/skills/engineering/references/formatting/04-clangd.md +32 -39
  111. package/skills/engineering/references/formatting/05-config-comments.md +88 -0
  112. package/skills/engineering/references/formatting/examples/02-clang-tidy.md +6 -6
  113. package/skills/engineering/references/formatting/examples/03-clangd.md +17 -17
  114. package/skills/engineering/references/index.md +5 -4
  115. package/skills/engineering/scripts/checking-encoding.mjs +369 -369
  116. package/skills/engineering/steps/01-targets.md +3 -3
  117. package/skills/engineering/steps/02-modules.md +1 -2
  118. package/skills/engineering/steps/03-check.md +2 -3
  119. package/templates/cpp-workflow-project/SKILL.md +1 -1
  120. package/templates/cpp-workflow-project/environment.json +4 -4
  121. package/skills/developing-cpp/references/design/examples/05-library-split.md +0 -8
  122. package/skills/developing-cpp/references/language/standard-library/10-library-checklist.md +0 -10
  123. package/skills/developing-cpp/references/naming/examples/02-naming-basic.md +0 -4
  124. package/skills/developing-cpp/references/naming/examples/10-naming-rename.md +0 -6
  125. package/skills/engineering/references/formatting/examples/04-config-comments.md +0 -70
  126. /package/skills/developing-cpp/references/language/standard-library/{08-random.md → 09-random.md} +0 -0
@@ -3,8 +3,9 @@
3
3
  //
4
4
  // 规则见 references/layout/03-declaration-order.md「`.cpp` 的定义顺序」与
5
5
  // 「声明与定义的签名」:先类型常量、再自由函数、再成员函数;成员按类内声明顺序;
6
- // 构造函数、析构函数、拷贝与移动放在成员组最前;参数类型、限定符与返回类型必须
7
- // 与声明一致;不为先编译而重排。
6
+ // 构造函数、析构函数、拷贝与移动通常放在成员组最前(校验对 `Is*` / `Check*` 前置时
7
+ // 例外,见该文档「校验对的位置」);参数类型、限定符与返回类型必须与声明一致;
8
+ // 不为先编译而重排。
8
9
  //
9
10
  // 本脚本只比较配对头文件里存在的类;自由函数与匿名命名空间不参与。类内没有声明
10
11
  // 的成员定义报 definition-undeclared,签名不一致报 definition-signature。
@@ -22,634 +23,630 @@ export const EXIT = { ok: 0, issues: 1, usage: 2 }
22
23
  const HEADER_EXT = new Set(['.h', '.hh', '.hpp', '.hxx', '.h++', '.inl', '.ipp', '.tpp'])
23
24
  const SOURCE_EXT = new Set(['.cpp', '.cc', '.cxx', '.c++'])
24
25
  const SKIP_DIR = new Set([
25
- '.git', '.hg', '.svn', 'build', 'build-release', 'out', 'node_modules', '_book', '.quarto',
26
- '.cache', '.tmp', 'temp', 'third_party', 'third-party', 'external', 'vendor', 'deps',
27
- 'cmake-build-debug', 'cmake-build-release', '.vs', '.idea',
26
+ '.git', '.hg', '.svn', 'build', 'build-release', 'out', 'node_modules', '_book', '.quarto',
27
+ '.cache', '.tmp', 'temp', 'third_party', 'third-party', 'external', 'vendor', 'deps',
28
+ 'cmake-build-debug', 'cmake-build-release', '.vs', '.idea',
28
29
  ])
29
30
  const PREDICATE_NAME = /^(?:Is|Has|Can|Completes|Would)[A-Za-z0-9_]*$/
30
31
 
32
+ const USAGE = '用法:node checking-declaration-order.mjs [--root DIR] [--json] [--quiet] [--help]\n'
33
+
31
34
  function usage(message) {
32
- if (message) process.stderr.write(`错误:${message}\n`)
33
- process.stderr.write('用法:node checking-declaration-order.mjs [--root DIR] [--json] [--quiet]\n')
34
- return EXIT.usage
35
+ if (message) process.stderr.write(`错误:${message}\n`)
36
+ process.stderr.write(USAGE)
37
+ return EXIT.usage
38
+ }
39
+
40
+ function help() {
41
+ process.stdout.write(USAGE)
42
+ return EXIT.ok
35
43
  }
36
44
 
37
45
  function parseArgs(argv) {
38
- const options = { root: undefined, json: false, quiet: false, help: false }
39
- for (let index = 0; index < argv.length; index += 1) {
40
- const arg = argv[index]
41
- if (arg === '--root') {
42
- options.root = argv[index + 1]
43
- if (!options.root) throw new Error('--root 需要目录')
44
- index += 1
45
- } else if (arg === '--json') {
46
- options.json = true
47
- } else if (arg === '--quiet') {
48
- options.quiet = true
49
- } else if (arg === '--help' || arg === '-h') {
50
- options.help = true
51
- } else {
52
- throw new Error(`未知参数:${arg}`)
46
+ const options = { root: undefined, json: false, quiet: false, help: false }
47
+ for (let index = 0; index < argv.length; index += 1) {
48
+ const arg = argv[index]
49
+ if (arg === '--root') {
50
+ options.root = argv[index + 1]
51
+ if (!options.root) throw new Error('--root 需要目录')
52
+ index += 1
53
+ } else if (arg === '--json') {
54
+ options.json = true
55
+ } else if (arg === '--quiet') {
56
+ options.quiet = true
57
+ } else if (arg === '--help' || arg === '-h') {
58
+ options.help = true
59
+ } else {
60
+ throw new Error(`未知参数:${arg}`)
61
+ }
53
62
  }
54
- }
55
- return options
63
+ return options
56
64
  }
57
65
 
58
66
  /** 去掉注释与字符串,保留换行,便于按行号定位。 */
59
67
  export function stripCommentsAndStrings(text) {
60
- const out = text.split('')
61
- let index = 0
62
- while (index < text.length) {
63
- const char = text[index]
64
- const next = text[index + 1]
65
- if (char === '/' && next === '/') {
66
- while (index < text.length && text[index] !== '\n') out[index++] = ' '
67
- continue
68
- }
69
- if (char === '/' && next === '*') {
70
- out[index++] = ' '
71
- out[index++] = ' '
72
- while (index < text.length && !(text[index] === '*' && text[index + 1] === '/')) {
73
- if (text[index] !== '\n') out[index] = ' '
74
- index += 1
75
- }
76
- if (index < text.length) {
77
- out[index++] = ' '
78
- out[index++] = ' '
79
- }
80
- continue
81
- }
82
- if (char === 'R' && next === '"') {
83
- const open = text.indexOf('(', index + 2)
84
- if (open !== -1) {
85
- const delimiter = text.slice(index + 2, open)
86
- const close = text.indexOf(`)${delimiter}"`, open + 1)
87
- const end = close === -1 ? text.length : close + delimiter.length + 2
88
- for (; index < end; index += 1) if (text[index] !== '\n') out[index] = ' '
89
- continue
90
- }
91
- }
92
- if (char === '"' || char === "'") {
93
- const quote = char
94
- out[index++] = ' '
95
- while (index < text.length) {
96
- if (text[index] === '\\') {
97
- out[index++] = ' '
98
- if (index < text.length) out[index++] = ' '
99
- continue
68
+ const out = text.split('')
69
+ let index = 0
70
+ while (index < text.length) {
71
+ const char = text[index]
72
+ const next = text[index + 1]
73
+ if (char === '/' && next === '/') {
74
+ while (index < text.length && text[index] !== '\n') out[index++] = ' '
75
+ continue
76
+ }
77
+ if (char === '/' && next === '*') {
78
+ out[index++] = ' '
79
+ out[index++] = ' '
80
+ while (index < text.length && !(text[index] === '*' && text[index + 1] === '/')) {
81
+ if (text[index] !== '\n') out[index] = ' '
82
+ index += 1
83
+ }
84
+ if (index < text.length) {
85
+ out[index++] = ' '
86
+ out[index++] = ' '
87
+ }
88
+ continue
89
+ }
90
+ if (char === 'R' && next === '"') {
91
+ const open = text.indexOf('(', index + 2)
92
+ if (open !== -1) {
93
+ const delimiter = text.slice(index + 2, open)
94
+ const close = text.indexOf(`)${delimiter}"`, open + 1)
95
+ const end = close === -1 ? text.length : close + delimiter.length + 2
96
+ for (; index < end; index += 1) if (text[index] !== '\n') out[index] = ' '
97
+ continue
98
+ }
100
99
  }
101
- if (text[index] === quote) {
102
- out[index++] = ' '
103
- break
100
+ if (char === '"' || char === "'") {
101
+ const quote = char
102
+ out[index++] = ' '
103
+ while (index < text.length) {
104
+ if (text[index] === '\\') {
105
+ out[index++] = ' '
106
+ if (index < text.length) out[index++] = ' '
107
+ continue
108
+ }
109
+ if (text[index] === quote) {
110
+ out[index++] = ' '
111
+ break
112
+ }
113
+ if (text[index] !== '\n') out[index] = ' '
114
+ index += 1
115
+ }
116
+ continue
104
117
  }
105
- if (text[index] !== '\n') out[index] = ' '
106
118
  index += 1
107
- }
108
- continue
109
119
  }
110
- index += 1
111
- }
112
- return out.join('')
120
+ return out.join('')
113
121
  }
114
122
 
115
123
  function lineAt(text, index) {
116
- let line = 1
117
- for (let cursor = 0; cursor < index && cursor < text.length; cursor += 1) {
118
- if (text[cursor] === '\n') line += 1
119
- }
120
- return line
124
+ let line = 1
125
+ for (let cursor = 0; cursor < index && cursor < text.length; cursor += 1) {
126
+ if (text[cursor] === '\n') line += 1
127
+ }
128
+ return line
121
129
  }
122
130
 
123
131
  function matchBrace(text, open) {
124
- let depth = 0
125
- for (let index = open; index < text.length; index += 1) {
126
- if (text[index] === '{') depth += 1
127
- else if (text[index] === '}') {
128
- depth -= 1
129
- if (depth === 0) return index
132
+ let depth = 0
133
+ for (let index = open; index < text.length; index += 1) {
134
+ if (text[index] === '{') depth += 1
135
+ else if (text[index] === '}') {
136
+ depth -= 1
137
+ if (depth === 0) return index
138
+ }
130
139
  }
131
- }
132
- return -1
140
+ return -1
133
141
  }
134
142
 
135
143
  /** 收集头文件里的 class/struct 名称与类体范围。 */
136
144
  export function findClasses(text) {
137
- const code = stripCommentsAndStrings(text)
138
- const classes = []
139
- const pattern = /\b(class|struct)\s+([A-Za-z_]\w*)\b[^;{}]*\{/g
140
- let match
141
- while ((match = pattern.exec(code)) !== null) {
142
- const keyword = match[1]
143
- const name = match[2]
144
- const before = code.slice(Math.max(0, match.index - 6), match.index)
145
- if (keyword === 'class' && /enum\s*$/.test(before)) continue
146
- const open = code.indexOf('{', match.index)
147
- const close = matchBrace(code, open)
148
- if (close === -1) continue
149
- classes.push({ name, body: code.slice(open + 1, close), bodyStart: open + 1 })
150
- pattern.lastIndex = close + 1
151
- }
152
- return classes
145
+ const code = stripCommentsAndStrings(text)
146
+ const classes = []
147
+ const pattern = /\b(class|struct)\s+([A-Za-z_]\w*)\b[^;{}]*\{/g
148
+ let match
149
+ while ((match = pattern.exec(code)) !== null) {
150
+ const keyword = match[1]
151
+ const name = match[2]
152
+ const before = code.slice(Math.max(0, match.index - 6), match.index)
153
+ if (keyword === 'class' && /enum\s*$/.test(before)) continue
154
+ const open = code.indexOf('{', match.index)
155
+ const close = matchBrace(code, open)
156
+ if (close === -1) continue
157
+ classes.push({ name, body: code.slice(open + 1, close), bodyStart: open + 1 })
158
+ pattern.lastIndex = close + 1
159
+ }
160
+ return classes
153
161
  }
154
162
 
155
163
  function normalizeStatement(statement) {
156
- return statement
157
- .replace(/\[\[[^\]]*\]\]/g, ' ')
158
- .replace(/\s+/g, ' ')
159
- .trim()
164
+ return statement
165
+ .replace(/\[\[[^\]]*\]\]/g, ' ')
166
+ .replace(/\s+/g, ' ')
167
+ .trim()
160
168
  }
161
169
 
162
170
  /** 从一个类体里按声明顺序提取可定义的成员函数名。 */
163
171
  export function classMembers(body) {
164
- const clean = body.replace(/\b(public|private|protected)\s*:/g, ' ')
165
- const members = []
166
- let index = 0
167
- while (index < clean.length) {
168
- while (index < clean.length && /\s/.test(clean[index])) index += 1
169
- if (index >= clean.length) break
170
- if (clean[index] === '{') {
171
- const close = matchBrace(clean, index)
172
- if (close === -1) break
173
- index = close + 1
174
- while (index < clean.length && /[\s;]/.test(clean[index])) index += 1
175
- continue
176
- }
177
- const start = index
178
- let paren = 0
179
- let angle = 0
180
- let brace = 0
181
- for (; index < clean.length; index += 1) {
182
- const char = clean[index]
183
- if (char === '(') paren += 1
184
- else if (char === ')') paren = Math.max(0, paren - 1)
185
- else if (char === '<') angle += 1
186
- else if (char === '>') angle = Math.max(0, angle - 1)
187
- else if (char === '{') brace += 1
188
- else if (char === '}') {
189
- if (brace === 0) break
190
- brace -= 1
191
- } else if (char === ';' && paren === 0 && brace === 0) break
192
- }
193
- const statement = clean.slice(start, index)
194
- index += 1
195
- const text = normalizeStatement(statement)
196
- if (!text || /^(using|typedef|friend\s+class|static_assert|enum|class|struct|union|namespace)\b/.test(text)) {
197
- continue
172
+ const clean = body.replace(/\b(public|private|protected)\s*:/g, ' ')
173
+ const members = []
174
+ let index = 0
175
+ while (index < clean.length) {
176
+ while (index < clean.length && /\s/.test(clean[index])) index += 1
177
+ if (index >= clean.length) break
178
+ if (clean[index] === '{') {
179
+ const close = matchBrace(clean, index)
180
+ if (close === -1) break
181
+ index = close + 1
182
+ while (index < clean.length && /[\s;]/.test(clean[index])) index += 1
183
+ continue
184
+ }
185
+ const start = index
186
+ let paren = 0
187
+ let angle = 0
188
+ let brace = 0
189
+ for (; index < clean.length; index += 1) {
190
+ const char = clean[index]
191
+ if (char === '(') paren += 1
192
+ else if (char === ')') paren = Math.max(0, paren - 1)
193
+ else if (char === '<') angle += 1
194
+ else if (char === '>') angle = Math.max(0, angle - 1)
195
+ else if (char === '{') brace += 1
196
+ else if (char === '}') {
197
+ if (brace === 0) break
198
+ brace -= 1
199
+ } else if (char === ';' && paren === 0 && brace === 0) break
200
+ }
201
+ const statement = clean.slice(start, index)
202
+ index += 1
203
+ const text = normalizeStatement(statement)
204
+ if (!text || /^(using|typedef|friend\s+class|static_assert|enum|class|struct|union|namespace)\b/.test(text)) {
205
+ continue
206
+ }
207
+ if (!text.includes('(')) continue
208
+ const name = memberName(text)
209
+ if (name) members.push({ name, text })
198
210
  }
199
- if (!text.includes('(')) continue
200
- const name = memberName(text)
201
- if (name) members.push({ name, text })
202
- }
203
- return members
211
+ return members
204
212
  }
205
213
 
206
214
  function memberName(text) {
207
- let value = text
208
- .replace(/^template\s*<[^>]*>\s*/, '')
209
- .replace(/^(?:static|inline|virtual|constexpr|consteval|explicit|friend|extern)\s+/g, '')
210
- .trim()
211
- const operator = /(?:^|\s)(operator\s*[^\s(]+)\s*\(/.exec(value)
212
- if (operator) return operator[1].replace(/\s+/g, ' ')
213
- const destructor = /(?:^|\s)(~[A-Za-z_]\w*)\s*\(/.exec(value)
214
- if (destructor) return destructor[1]
215
- const constructor = /(?:^|\s)([A-Za-z_]\w*)\s*\(/.exec(value)
216
- if (constructor && (value.startsWith(`${constructor[1]}(`) || /\bexplicit\s+$/.test(value.slice(0, constructor.index + 1)))) {
217
- return constructor[1]
218
- }
219
- const fn = /([A-Za-z_]\w*)\s*\(/.exec(value)
220
- return fn ? fn[1] : undefined
215
+ let value = text
216
+ .replace(/^template\s*<[^>]*>\s*/, '')
217
+ .replace(/^(?:static|inline|virtual|constexpr|consteval|explicit|friend|extern)\s+/g, '')
218
+ .trim()
219
+ const operator = /(?:^|\s)(operator\s*[^\s(]+)\s*\(/.exec(value)
220
+ if (operator) return operator[1].replace(/\s+/g, ' ')
221
+ const destructor = /(?:^|\s)(~[A-Za-z_]\w*)\s*\(/.exec(value)
222
+ if (destructor) return destructor[1]
223
+ const constructor = /(?:^|\s)([A-Za-z_]\w*)\s*\(/.exec(value)
224
+ if (constructor && (value.startsWith(`${constructor[1]}(`) || /\bexplicit\s+$/.test(value.slice(0, constructor.index + 1)))) {
225
+ return constructor[1]
226
+ }
227
+ const fn = /([A-Za-z_]\w*)\s*\(/.exec(value)
228
+ return fn ? fn[1] : undefined
221
229
  }
222
230
 
223
231
  /** 找出 `.cpp` 中形如 `Type Class::Name(` 的定义及其行号。 */
224
232
  export function cppDefinitions(text) {
225
- const code = stripCommentsAndStrings(text)
226
- const definitions = []
227
- const lines = code.split('\n')
228
- const lineStarts = []
229
- let offset = 0
230
- for (const line of lines) {
231
- lineStarts.push(offset)
232
- offset += line.length + 1
233
- }
234
- for (let index = 0; index < lines.length; index += 1) {
235
- const line = lines[index]
236
- const match = /^(\s*)(.*?)\b([A-Za-z_]\w*)::(~?[A-Za-z_]\w*|operator\s*[^\s(]+)\s*\(/.exec(line)
237
- if (!match) continue
238
- if (/^\s*(?:return|if|while|for|switch|throw|case|else|do)\b/.test(match[2])) continue
239
- const open = lineStarts[index] + match.index + match[0].lastIndexOf('(')
240
- const close = matchParen(code, open)
241
- if (close === -1) continue
242
- let suffixEnd = close + 1
243
- let depth = 0
244
- for (let cursor = close + 1; cursor < code.length; cursor += 1) {
245
- const char = code[cursor]
246
- if (char === '(') depth += 1
247
- else if (char === ')') depth = Math.max(0, depth - 1)
248
- else if (depth === 0 && (char === '{' || char === ';' || char === ':')) {
249
- suffixEnd = cursor
250
- break
251
- }
233
+ const code = stripCommentsAndStrings(text)
234
+ const definitions = []
235
+ const lines = code.split('\n')
236
+ const lineStarts = []
237
+ let offset = 0
238
+ for (const line of lines) {
239
+ lineStarts.push(offset)
240
+ offset += line.length + 1
241
+ }
242
+ for (let index = 0; index < lines.length; index += 1) {
243
+ const line = lines[index]
244
+ const match = /^(\s*)(.*?)\b([A-Za-z_]\w*)::(~?[A-Za-z_]\w*|operator\s*[^\s(]+)\s*\(/.exec(line)
245
+ if (!match) continue
246
+ if (/^\s*(?:return|if|while|for|switch|throw|case|else|do)\b/.test(match[2])) continue
247
+ const open = lineStarts[index] + match.index + match[0].lastIndexOf('(')
248
+ const close = matchParen(code, open)
249
+ if (close === -1) continue
250
+ let suffixEnd = close + 1
251
+ let depth = 0
252
+ for (let cursor = close + 1; cursor < code.length; cursor += 1) {
253
+ const char = code[cursor]
254
+ if (char === '(') depth += 1
255
+ else if (char === ')') depth = Math.max(0, depth - 1)
256
+ else if (depth === 0 && (char === '{' || char === ';' || char === ':')) {
257
+ suffixEnd = cursor
258
+ break
259
+ }
260
+ }
261
+ definitions.push({
262
+ className: match[3],
263
+ name: match[4].replace(/\s+/g, ' '),
264
+ line: index + 1,
265
+ text: line.trim(),
266
+ params: code.slice(open + 1, close),
267
+ suffix: code.slice(close + 1, suffixEnd),
268
+ returnType: match[2],
269
+ })
270
+ const closeLine = code.slice(0, close).split('\n').length - 1
271
+ if (closeLine > index) index = closeLine
252
272
  }
253
- definitions.push({
254
- className: match[3],
255
- name: match[4].replace(/\s+/g, ' '),
256
- line: index + 1,
257
- text: line.trim(),
258
- params: code.slice(open + 1, close),
259
- suffix: code.slice(close + 1, suffixEnd),
260
- returnType: match[2],
261
- })
262
- const closeLine = code.slice(0, close).split('\n').length - 1
263
- if (closeLine > index) index = closeLine
264
- }
265
- return definitions
273
+ return definitions
266
274
  }
267
275
 
268
276
  const PARAM_TYPE_WORDS = new Set([
269
- 'auto', 'bool', 'char', 'char8_t', 'char16_t', 'char32_t', 'double', 'float',
270
- 'int', 'long', 'short', 'signed', 'unsigned', 'void', 'volatile', 'const',
271
- 'wchar_t',
277
+ 'auto', 'bool', 'char', 'char8_t', 'char16_t', 'char32_t', 'double', 'float',
278
+ 'int', 'long', 'short', 'signed', 'unsigned', 'void', 'volatile', 'const',
279
+ 'wchar_t',
272
280
  ])
273
281
 
274
282
  function matchParen(text, open) {
275
- let depth = 0
276
- for (let index = open; index < text.length; index += 1) {
277
- if (text[index] === '(') depth += 1
278
- else if (text[index] === ')') {
279
- depth -= 1
280
- if (depth === 0) return index
283
+ let depth = 0
284
+ for (let index = open; index < text.length; index += 1) {
285
+ if (text[index] === '(') depth += 1
286
+ else if (text[index] === ')') {
287
+ depth -= 1
288
+ if (depth === 0) return index
289
+ }
281
290
  }
282
- }
283
- return -1
291
+ return -1
284
292
  }
285
293
 
286
294
  function splitTopLevel(text, separator = ',') {
287
- const parts = []
288
- let depth = 0
289
- let start = 0
290
- for (let index = 0; index < text.length; index += 1) {
291
- const char = text[index]
292
- if (char === '(' || char === '<' || char === '[' || char === '{') depth += 1
293
- else if (char === ')' || char === '>' || char === ']' || char === '}') {
294
- depth = Math.max(0, depth - 1)
295
- } else if (char === separator && depth === 0) {
296
- parts.push(text.slice(start, index))
297
- start = index + 1
295
+ const parts = []
296
+ let depth = 0
297
+ let start = 0
298
+ for (let index = 0; index < text.length; index += 1) {
299
+ const char = text[index]
300
+ if (char === '(' || char === '<' || char === '[' || char === '{') depth += 1
301
+ else if (char === ')' || char === '>' || char === ']' || char === '}') {
302
+ depth = Math.max(0, depth - 1)
303
+ } else if (char === separator && depth === 0) {
304
+ parts.push(text.slice(start, index))
305
+ start = index + 1
306
+ }
298
307
  }
299
- }
300
- parts.push(text.slice(start))
301
- return parts
308
+ parts.push(text.slice(start))
309
+ return parts
302
310
  }
303
311
 
304
312
  function stripParamName(parameter) {
305
- let text = parameter.replace(/\[\[[^\]]*\]\]/g, ' ').replace(/\s+/g, ' ').trim()
306
- const equal = text.indexOf('=')
307
- if (equal !== -1) text = text.slice(0, equal).trim()
308
- text = text.replace(/\s+([A-Za-z_]\w*)\s*((?:\[[^\]]*\]\s*)+)$/, (match, name, suffix) =>
309
- PARAM_TYPE_WORDS.has(name) ? match : ` ${suffix.trim()}`,
310
- )
311
- text = text.replace(/([&*])\s*([A-Za-z_]\w*)\s*$/, (match, symbol, name) =>
312
- PARAM_TYPE_WORDS.has(name) ? match : symbol,
313
- )
314
- text = text.replace(/\s+([A-Za-z_]\w*)\s*$/, (match, name) =>
315
- PARAM_TYPE_WORDS.has(name) ? match : '',
316
- )
317
- return text
318
- .replace(/\s*([&*])\s*/g, '$1')
319
- .replace(/\s*,\s*/g, ',')
320
- .replace(/\s*<\s*/g, '<')
321
- .replace(/\s*>\s*/g, '>')
322
- .replace(/\s+/g, ' ')
323
- .trim()
313
+ let text = parameter.replace(/\[\[[^\]]*\]\]/g, ' ').replace(/\s+/g, ' ').trim()
314
+ const equal = text.indexOf('=')
315
+ if (equal !== -1) text = text.slice(0, equal).trim()
316
+ text = text.replace(/\s+([A-Za-z_]\w*)\s*((?:\[[^\]]*\]\s*)+)$/, (match, name, suffix) =>
317
+ PARAM_TYPE_WORDS.has(name) ? match : ` ${suffix.trim()}`,
318
+ )
319
+ text = text.replace(/([&*])\s*([A-Za-z_]\w*)\s*$/, (match, symbol, name) =>
320
+ PARAM_TYPE_WORDS.has(name) ? match : symbol,
321
+ )
322
+ text = text.replace(/\s+([A-Za-z_]\w*)\s*$/, (match, name) =>
323
+ PARAM_TYPE_WORDS.has(name) ? match : '',
324
+ )
325
+ return text
326
+ .replace(/\s*([&*])\s*/g, '$1')
327
+ .replace(/\s*,\s*/g, ',')
328
+ .replace(/\s*<\s*/g, '<')
329
+ .replace(/\s*>\s*/g, '>')
330
+ .replace(/\s+/g, ' ')
331
+ .trim()
324
332
  }
325
333
 
326
334
  function normalizeParams(params) {
327
- const text = params.trim()
328
- if (!text || text === 'void') return ''
329
- return splitTopLevel(text)
330
- .map((parameter) => stripParamName(parameter))
331
- .filter(Boolean)
332
- .join(',')
335
+ const text = params.trim()
336
+ if (!text || text === 'void') return ''
337
+ return splitTopLevel(text)
338
+ .map((parameter) => stripParamName(parameter))
339
+ .filter(Boolean)
340
+ .join(',')
333
341
  }
334
342
 
335
343
  function normalizeReturnType(text) {
336
- return text
337
- .replace(/\[\[[^\]]*\]\]/g, ' ')
338
- .replace(/\b(?:static|inline|virtual|explicit|friend|extern|constexpr|consteval)\b/g, ' ')
339
- .replace(/\s*([&*])\s*/g, '$1')
340
- .replace(/\s*<\s*/g, '<')
341
- .replace(/\s*>\s*/g, '>')
342
- .replace(/\s*::\s*/g, '::')
343
- .replace(/\s*,\s*/g, ',')
344
- .replace(/\s+/g, ' ')
345
- .trim()
344
+ return text
345
+ .replace(/\[\[[^\]]*\]\]/g, ' ')
346
+ .replace(/\b(?:static|inline|virtual|explicit|friend|extern|constexpr|consteval)\b/g, ' ')
347
+ .replace(/\s*([&*])\s*/g, '$1')
348
+ .replace(/\s*<\s*/g, '<')
349
+ .replace(/\s*>\s*/g, '>')
350
+ .replace(/\s*::\s*/g, '::')
351
+ .replace(/\s*,\s*/g, ',')
352
+ .replace(/\s+/g, ' ')
353
+ .trim()
346
354
  }
347
355
 
348
356
  function qualifierText(suffix) {
349
- const text = suffix.replace(/=.*$/s, ' ').replace(/\b(?:override|final)\b/g, ' ')
350
- const qualifiers = []
351
- if (/\bconst\b/.test(text)) qualifiers.push('const')
352
- if (/\bvolatile\b/.test(text)) qualifiers.push('volatile')
353
- if (/\bnoexcept\b/.test(text)) qualifiers.push('noexcept')
354
- if (/&&/.test(text)) qualifiers.push('&&')
355
- else if (/(^|[^&])&(?!&)/.test(text)) qualifiers.push('&')
356
- return qualifiers.join(' ')
357
+ const text = suffix.replace(/=.*$/s, ' ').replace(/\b(?:override|final)\b/g, ' ')
358
+ const qualifiers = []
359
+ if (/\bconst\b/.test(text)) qualifiers.push('const')
360
+ if (/\bvolatile\b/.test(text)) qualifiers.push('volatile')
361
+ if (/\bnoexcept\b/.test(text)) qualifiers.push('noexcept')
362
+ if (/&&/.test(text)) qualifiers.push('&&')
363
+ else if (/(^|[^&])&(?!&)/.test(text)) qualifiers.push('&')
364
+ return qualifiers.join(' ')
357
365
  }
358
366
 
359
367
  function declarationSignature(text, className) {
360
- const value = text.replace(/\[\[[^\]]*\]\]/g, ' ').replace(/\s+/g, ' ').trim()
361
- if (!value || value.includes('{')) return undefined
362
- if (/^template\b/.test(value)) return undefined
363
- const match = /(~?[A-Za-z_]\w*|operator\s*[^\s(]+)\s*\(/.exec(value)
364
- if (!match) return undefined
365
- const name = match[1].replace(/\s+/g, ' ')
366
- const open = value.indexOf('(', match.index)
367
- const close = matchParen(value, open)
368
- if (close === -1) return undefined
369
- const before = value.slice(0, match.index)
370
- const suffix = value.slice(close + 1)
371
- const isSpecial = name === className || name === `~${className}`
372
- return {
373
- name,
374
- params: normalizeParams(value.slice(open + 1, close)),
375
- qualifiers: qualifierText(suffix),
376
- returnType: isSpecial ? '' : normalizeReturnType(before),
377
- }
368
+ const value = text.replace(/\[\[[^\]]*\]\]/g, ' ').replace(/\s+/g, ' ').trim()
369
+ if (!value || value.includes('{')) return undefined
370
+ if (/^template\b/.test(value)) return undefined
371
+ const match = /(~?[A-Za-z_]\w*|operator\s*[^\s(]+)\s*\(/.exec(value)
372
+ if (!match) return undefined
373
+ const name = match[1].replace(/\s+/g, ' ')
374
+ const open = value.indexOf('(', match.index)
375
+ const close = matchParen(value, open)
376
+ if (close === -1) return undefined
377
+ const before = value.slice(0, match.index)
378
+ const suffix = value.slice(close + 1)
379
+ const isSpecial = name === className || name === `~${className}`
380
+ return {
381
+ name,
382
+ params: normalizeParams(value.slice(open + 1, close)),
383
+ qualifiers: qualifierText(suffix),
384
+ returnType: isSpecial ? '' : normalizeReturnType(before),
385
+ }
378
386
  }
379
387
 
380
388
  function definitionSignature(definition) {
381
- const arrow = /->\s*([^;{]+)/.exec(definition.suffix)
382
- const baseReturn = normalizeReturnType(definition.returnType)
383
- return {
384
- name: definition.name,
385
- params: normalizeParams(definition.params),
386
- qualifiers: qualifierText(definition.suffix),
387
- returnType: baseReturn === 'auto' && arrow ? normalizeReturnType(arrow[1]) : baseReturn,
388
- }
389
+ const arrow = /->\s*([^;{]+)/.exec(definition.suffix)
390
+ const baseReturn = normalizeReturnType(definition.returnType)
391
+ return {
392
+ name: definition.name,
393
+ params: normalizeParams(definition.params),
394
+ qualifiers: qualifierText(definition.suffix),
395
+ returnType: baseReturn === 'auto' && arrow ? normalizeReturnType(arrow[1]) : baseReturn,
396
+ }
389
397
  }
390
398
 
391
399
  function sameSignature(left, right) {
392
- if (left.params !== right.params || left.qualifiers !== right.qualifiers) return false
393
- if (left.returnType === right.returnType) return true
394
- if (!left.returnType || !right.returnType) return false
395
- return left.returnType === 'auto' || right.returnType === 'auto'
400
+ if (left.params !== right.params || left.qualifiers !== right.qualifiers) return false
401
+ if (left.returnType === right.returnType) return true
402
+ if (!left.returnType || !right.returnType) return false
403
+ return left.returnType === 'auto' || right.returnType === 'auto'
396
404
  }
397
405
 
398
406
  function formatSignature(signature) {
399
- const head = signature.returnType ? `${signature.returnType} ` : ''
400
- const tail = signature.qualifiers ? ` ${signature.qualifiers}` : ''
401
- return `${head}${signature.name}(${signature.params})${tail}`
407
+ const head = signature.returnType ? `${signature.returnType} ` : ''
408
+ const tail = signature.qualifiers ? ` ${signature.qualifiers}` : ''
409
+ return `${head}${signature.name}(${signature.params})${tail}`
402
410
  }
403
411
 
404
412
  /** 检查头文件类内谓词位置:Get/Set 成对相邻,谓词在成对之后;没有 Set 配对时在读取接口之后。 */
405
413
  export function checkHeaderOrder(headerText) {
406
- const classes = findClasses(headerText)
407
- const issues = []
408
- for (const item of classes) {
409
- const members = classMembers(item.body)
410
- const isPredicate = (member) => PREDICATE_NAME.test(member.name) && !/\bstatic\b/.test(member.text)
411
- const isGet = (member) => /^Get[A-Z0-9_]/.test(member.name)
412
- const firstGet = members.findIndex(isGet)
413
- for (let index = 0; index < members.length; index += 1) {
414
- const member = members[index]
415
- if (!isPredicate(member)) continue
416
- const line = memberLine(headerText, member)
417
- if (firstGet !== -1 && index < firstGet) {
418
- issues.push({
419
- line,
420
- rule: 'header-order',
421
- message: `${item.name}::${member.name} 是谓词,却排在读取接口之前;谓词 Is / Has / Can / Completes / Would 应在读取接口之后。`,
422
- })
423
- continue
424
- }
425
- const pair = findGetSetPairAround(members, index)
426
- if (!pair) {
427
- const isConstMember = (member) => {
428
- const declaration = member.text.split('{')[0].trim()
429
- const close = declaration.lastIndexOf(')')
430
- return close !== -1 && declaration.slice(close + 1).trimStart().startsWith('const')
431
- }
432
- const hasAdjacentPair = members.some(
433
- (candidate, candidateIndex) =>
434
- isGet(candidate) &&
435
- candidateIndex + 1 < members.length &&
436
- /^Set[A-Z0-9_]/.test(members[candidateIndex + 1].name) &&
437
- getSetSuffix(candidate.name) === getSetSuffix(members[candidateIndex + 1].name),
438
- )
439
- const modifier = hasAdjacentPair
440
- ? -1
441
- : members.findIndex(
442
- (candidate, candidateIndex) =>
443
- candidateIndex < index &&
444
- !isPredicate(candidate) &&
445
- !isGet(candidate) &&
446
- candidate.text.includes('(') &&
447
- !isConstMember(candidate) &&
448
- members.slice(0, candidateIndex).some(isGet),
449
- )
450
- if (modifier !== -1) {
451
- issues.push({
452
- line,
453
- rule: 'header-order',
454
- message: `${item.name}::${member.name} 是谓词,却排在修改接口 ${members[modifier].name} 之后;没有 Set 配对时,谓词应在读取接口之后、修改接口之前。`,
455
- })
414
+ const classes = findClasses(headerText)
415
+ const issues = []
416
+ for (const item of classes) {
417
+ const members = classMembers(item.body)
418
+ const isPredicate = (member) => PREDICATE_NAME.test(member.name) && !/\bstatic\b/.test(member.text)
419
+ const isGet = (member) => /^Get[A-Z0-9_]/.test(member.name)
420
+ const firstGet = members.findIndex(isGet)
421
+ for (let index = 0; index < members.length; index += 1) {
422
+ const member = members[index]
423
+ if (!isPredicate(member)) continue
424
+ const line = memberLine(headerText, member)
425
+ if (firstGet !== -1 && index < firstGet) {
426
+ issues.push({
427
+ line,
428
+ rule: 'header-order',
429
+ message: `${item.name}::${member.name} 是谓词,却排在读取接口之前;谓词 Is / Has / Can / Completes / Would 应在读取接口之后。`,
430
+ })
431
+ continue
432
+ }
433
+ const pair = findGetSetPairAround(members, index)
434
+ if (!pair) {
435
+ const isConstMember = (member) => {
436
+ const declaration = member.text.split('{')[0].trim()
437
+ const close = declaration.lastIndexOf(')')
438
+ return close !== -1 && declaration.slice(close + 1).trimStart().startsWith('const')
439
+ }
440
+ const isModifier = (member) =>
441
+ !isGet(member) &&
442
+ !/^Set[A-Z0-9_]/.test(member.name) &&
443
+ !member.name.startsWith('operator') &&
444
+ !isConstMember(member)
445
+ const previous = members.slice(0, index).reverse().find((candidate) => !isPredicate(candidate))
446
+ if (previous && isModifier(previous)) {
447
+ issues.push({
448
+ line,
449
+ rule: 'header-order',
450
+ message: `${item.name}::${member.name} 是谓词,却排在修改接口 ${previous.name} 之后;谓词应在读取接口或 Get/Set 成对之后、修改接口之前。`,
451
+ })
452
+ }
453
+ continue
454
+ }
455
+ issues.push({
456
+ line,
457
+ rule: 'header-order',
458
+ message: `${item.name}::${member.name} 是谓词,却排在 ${pair.get.name} 与 ${pair.set.name} 之间;Get/Set 成对相邻,谓词应放在 ${pair.set.name} 之后。`,
459
+ })
456
460
  }
457
- continue
458
- }
459
- issues.push({
460
- line,
461
- rule: 'header-order',
462
- message: `${item.name}::${member.name} 是谓词,却排在 ${pair.get.name} 与 ${pair.set.name} 之间;Get/Set 成对相邻,谓词应放在 ${pair.set.name} 之后。`,
463
- })
464
461
  }
465
- }
466
- return issues
462
+ return issues
467
463
  }
468
464
 
469
465
  function memberLine(headerText, member) {
470
- const position = headerText.search(new RegExp(`\\b${member.name}\\s*\\(`))
471
- return position === -1 ? 1 : headerText.slice(0, position).split('\n').length
466
+ const position = headerText.search(new RegExp(`\\b${member.name}\\s*\\(`))
467
+ return position === -1 ? 1 : headerText.slice(0, position).split('\n').length
472
468
  }
473
469
 
474
470
  function getSetSuffix(name) {
475
- return name.replace(/^(?:Get|Set)/, '')
471
+ return name.replace(/^(?:Get|Set)/, '')
476
472
  }
477
473
 
478
474
  function findGetSetPairAround(members, predicateIndex) {
479
- for (let getIndex = predicateIndex - 1; getIndex >= 0; getIndex -= 1) {
480
- if (!/^Get[A-Z0-9_]/.test(members[getIndex].name)) continue
481
- const suffix = getSetSuffix(members[getIndex].name)
482
- for (let setIndex = predicateIndex + 1; setIndex < members.length; setIndex += 1) {
483
- if (/^Set[A-Z0-9_]/.test(members[setIndex].name) && getSetSuffix(members[setIndex].name) === suffix) {
484
- return { get: members[getIndex], set: members[setIndex] }
485
- }
475
+ for (let getIndex = predicateIndex - 1; getIndex >= 0; getIndex -= 1) {
476
+ if (!/^Get[A-Z0-9_]/.test(members[getIndex].name)) continue
477
+ const suffix = getSetSuffix(members[getIndex].name)
478
+ for (let setIndex = predicateIndex + 1; setIndex < members.length; setIndex += 1) {
479
+ if (/^Set[A-Z0-9_]/.test(members[setIndex].name) && getSetSuffix(members[setIndex].name) === suffix) {
480
+ return { get: members[getIndex], set: members[setIndex] }
481
+ }
482
+ }
486
483
  }
487
- }
488
- return undefined
484
+ return undefined
489
485
  }
490
486
 
491
487
  /** 检查类内定义是否都有声明,且参数与返回类型和声明一致。 */
492
488
  function checkDefinitionSignatures(headerText, cppText) {
493
- const definitions = cppDefinitions(cppText)
494
- const issues = []
495
- for (const item of findClasses(headerText)) {
496
- const members = classMembers(item.body)
497
- const templateNames = new Set(
498
- members
499
- .filter((member) => /^template\b/.test(member.text))
500
- .map((member) => member.name),
501
- )
502
- const declarations = members
503
- .map((member) => ({ ...member, signature: declarationSignature(member.text, item.name) }))
504
- .filter((member) => member.signature)
505
- for (const definition of definitions.filter((entry) => entry.className === item.name)) {
506
- if (templateNames.has(definition.name)) continue
507
- const candidates = declarations.filter((member) => member.signature.name === definition.name)
508
- if (candidates.length === 0) {
509
- issues.push({
510
- line: definition.line,
511
- rule: 'definition-undeclared',
512
- message: `${item.name}::${definition.name} 在配对头文件中没有声明。`,
513
- })
514
- continue
515
- }
516
- const actual = definitionSignature(definition)
517
- if (candidates.some((member) => sameSignature(member.signature, actual))) continue
518
- issues.push({
519
- line: definition.line,
520
- rule: 'definition-signature',
521
- message: `${item.name}::${definition.name} 的定义与头文件声明不一致:声明为 ${formatSignature(candidates[0].signature)},定义为 ${formatSignature(actual)}。`,
522
- })
489
+ const definitions = cppDefinitions(cppText)
490
+ const issues = []
491
+ for (const item of findClasses(headerText)) {
492
+ const members = classMembers(item.body)
493
+ const templateNames = new Set(
494
+ members
495
+ .filter((member) => /^template\b/.test(member.text))
496
+ .map((member) => member.name),
497
+ )
498
+ const declarations = members
499
+ .map((member) => ({ ...member, signature: declarationSignature(member.text, item.name) }))
500
+ .filter((member) => member.signature)
501
+ for (const definition of definitions.filter((entry) => entry.className === item.name)) {
502
+ if (templateNames.has(definition.name)) continue
503
+ const candidates = declarations.filter((member) => member.signature.name === definition.name)
504
+ if (candidates.length === 0) {
505
+ issues.push({
506
+ line: definition.line,
507
+ rule: 'definition-undeclared',
508
+ message: `${item.name}::${definition.name} 在配对头文件中没有声明。`,
509
+ })
510
+ continue
511
+ }
512
+ const actual = definitionSignature(definition)
513
+ if (candidates.some((member) => sameSignature(member.signature, actual))) continue
514
+ issues.push({
515
+ line: definition.line,
516
+ rule: 'definition-signature',
517
+ message: `${item.name}::${definition.name} 的定义与头文件声明不一致:声明为 ${formatSignature(candidates[0].signature)},定义为 ${formatSignature(actual)}。`,
518
+ })
519
+ }
523
520
  }
524
- }
525
- return issues
521
+ return issues
526
522
  }
527
523
 
528
524
  /** 比较一个头文件与一个实现文件;返回乱序与签名问题。 */
529
- export function checkPair(headerText, cppText, fileName = '') {
530
- const classes = findClasses(headerText)
531
- const definitions = cppDefinitions(cppText)
532
- const issues = checkHeaderOrder(headerText)
533
- for (const item of classes) {
534
- const members = classMembers(item.body)
535
- if (members.length === 0) continue
536
- const declared = members.map((member) => member.name)
537
- const defined = definitions.filter((definition) => definition.className === item.name)
538
- let cursor = 0
539
- let previous
540
- for (const definition of defined) {
541
- let found = declared.indexOf(definition.name, cursor)
542
- if (found === -1 && declared.includes(definition.name)) {
543
- issues.push({
544
- line: definition.line,
545
- rule: 'definition-order',
546
- message: `${item.name}::${definition.name} 出现在 ${previous ? `${item.name}::${previous} 之后` : '成员组开头'};头文件声明的顺序是 ${declared.join(' → ')}。`,
547
- })
548
- continue
549
- }
550
- if (found === -1) continue
551
- cursor = found + 1
552
- previous = definition.name
525
+ export function checkPair(headerText, cppText, fileName = '', headerFile = fileName) {
526
+ const classes = findClasses(headerText)
527
+ const definitions = cppDefinitions(cppText)
528
+ const issues = checkHeaderOrder(headerText)
529
+ for (const item of classes) {
530
+ const members = classMembers(item.body)
531
+ if (members.length === 0) continue
532
+ const declared = members.map((member) => member.name)
533
+ const defined = definitions.filter((definition) => definition.className === item.name)
534
+ let cursor = 0
535
+ let previous
536
+ for (const definition of defined) {
537
+ let found = declared.indexOf(definition.name, cursor)
538
+ if (found === -1 && declared.includes(definition.name)) {
539
+ issues.push({
540
+ line: definition.line,
541
+ rule: 'definition-order',
542
+ message: `${item.name}::${definition.name} 出现在 ${previous ? `${item.name}::${previous} 之后` : '成员组开头'};头文件声明的顺序是 ${declared.join(' → ')}。`,
543
+ })
544
+ continue
545
+ }
546
+ if (found === -1) continue
547
+ cursor = found + 1
548
+ previous = definition.name
549
+ }
553
550
  }
554
- }
555
- issues.push(...checkDefinitionSignatures(headerText, cppText))
556
- return issues.map((issue) => ({ file: fileName, ...issue }))
551
+ issues.push(...checkDefinitionSignatures(headerText, cppText))
552
+ return issues.map((issue) => ({ file: issue.rule === 'header-order' ? headerFile : fileName, ...issue }))
557
553
  }
558
554
 
559
555
  function collectFiles(root) {
560
- const files = { headers: [], sources: [] }
561
- const walk = (dir) => {
562
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
563
- const full = path.join(dir, entry.name)
564
- if (entry.isDirectory()) {
565
- if (SKIP_DIR.has(entry.name.toLowerCase()) || entry.name.startsWith('.')) continue
566
- walk(full)
567
- continue
568
- }
569
- if (!entry.isFile()) continue
570
- const extension = path.extname(entry.name).toLowerCase()
571
- if (HEADER_EXT.has(extension)) files.headers.push(full)
572
- if (SOURCE_EXT.has(extension)) files.sources.push(full)
556
+ const files = { headers: [], sources: [] }
557
+ const walk = (dir) => {
558
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
559
+ const full = path.join(dir, entry.name)
560
+ if (entry.isDirectory()) {
561
+ if (SKIP_DIR.has(entry.name.toLowerCase()) || entry.name.startsWith('.')) continue
562
+ walk(full)
563
+ continue
564
+ }
565
+ if (!entry.isFile()) continue
566
+ const extension = path.extname(entry.name).toLowerCase()
567
+ if (HEADER_EXT.has(extension)) files.headers.push(full)
568
+ if (SOURCE_EXT.has(extension)) files.sources.push(full)
569
+ }
570
+ }
571
+ if (statSync(root).isFile()) {
572
+ const extension = path.extname(root).toLowerCase()
573
+ if (HEADER_EXT.has(extension)) files.headers.push(root)
574
+ if (SOURCE_EXT.has(extension)) files.sources.push(root)
575
+ } else {
576
+ walk(root)
573
577
  }
574
- }
575
- if (statSync(root).isFile()) {
576
- const extension = path.extname(root).toLowerCase()
577
- if (HEADER_EXT.has(extension)) files.headers.push(root)
578
- if (SOURCE_EXT.has(extension)) files.sources.push(root)
579
- } else {
580
- walk(root)
581
- }
582
- files.headers.sort()
583
- files.sources.sort()
584
- return files
578
+ files.headers.sort()
579
+ files.sources.sort()
580
+ return files
585
581
  }
586
582
 
587
583
  export function checkRoot(root) {
588
- const files = collectFiles(root)
589
- const headers = new Map()
590
- for (const file of files.headers) {
591
- const stem = path.basename(file, path.extname(file))
592
- const bucket = headers.get(stem) ?? []
593
- bucket.push(file)
594
- headers.set(stem, bucket)
595
- }
596
- const pairs = []
597
- const issues = []
598
- for (const file of files.sources) {
599
- const stem = path.basename(file, path.extname(file))
600
- const candidates = headers.get(stem) ?? []
601
- if (candidates.length === 0) continue
602
- if (candidates.length > 1) {
603
- issues.push({
604
- file: path.relative(root, file) || file,
605
- line: 1,
606
- rule: 'header-ambiguous',
607
- message: `同名头文件不唯一,无法配对:${candidates.map((item) => path.relative(root, item) || item).join('、')}`,
608
- })
609
- continue
584
+ const files = collectFiles(root)
585
+ const headers = new Map()
586
+ for (const file of files.headers) {
587
+ const stem = path.basename(file, path.extname(file))
588
+ const bucket = headers.get(stem) ?? []
589
+ bucket.push(file)
590
+ headers.set(stem, bucket)
610
591
  }
611
- const header = candidates[0]
612
- const headerText = readFileSync(header, 'utf8')
613
- const cppText = readFileSync(file, 'utf8')
614
- const relative = path.relative(root, file) || file
615
- const found = checkPair(headerText, cppText, relative)
616
- pairs.push({ header, source: file, issues: found })
617
- issues.push(...found)
618
- }
619
- return { pairs, issues }
592
+ const pairs = []
593
+ const issues = []
594
+ for (const file of files.sources) {
595
+ const stem = path.basename(file, path.extname(file))
596
+ const candidates = headers.get(stem) ?? []
597
+ if (candidates.length === 0) continue
598
+ if (candidates.length > 1) {
599
+ issues.push({
600
+ file: path.relative(root, file) || file,
601
+ line: 1,
602
+ rule: 'header-ambiguous',
603
+ message: `同名头文件不唯一,无法配对:${candidates.map((item) => path.relative(root, item) || item).join('、')}`,
604
+ })
605
+ continue
606
+ }
607
+ const header = candidates[0]
608
+ const headerText = readFileSync(header, 'utf8')
609
+ const cppText = readFileSync(file, 'utf8')
610
+ const relative = path.relative(root, file) || file
611
+ const headerRelative = path.relative(root, header) || header
612
+ const found = checkPair(headerText, cppText, relative, headerRelative)
613
+ pairs.push({ header, source: file, issues: found })
614
+ issues.push(...found)
615
+ }
616
+ return { pairs, issues }
620
617
  }
621
618
 
622
619
  function main(argv) {
623
- let options
624
- try {
625
- options = parseArgs(argv)
626
- } catch (error) {
627
- return usage(error.message)
628
- }
629
- if (options.help) return usage()
630
- const root = options.root ? path.resolve(options.root) : process.cwd()
631
- try {
632
- statSync(root)
633
- } catch {
634
- return usage(`根目录不存在或无法读取:${root}`)
635
- }
636
- let result
637
- try {
638
- result = checkRoot(root)
639
- } catch (error) {
640
- return usage(`读取 ${root} 失败:${error.message}`)
641
- }
642
- if (options.json) {
643
- process.stdout.write(`${JSON.stringify({ root, pairs: result.pairs.length, issues: result.issues }, null, 2)}\n`)
644
- } else if (result.issues.length > 0) {
645
- for (const issue of result.issues) process.stdout.write(`${issue.file}:${issue.line}: [${issue.rule}] ${issue.message}\n`)
646
- process.stdout.write(`发现 ${result.issues.length} 处声明与定义问题。\n`)
647
- } else if (!options.quiet) {
648
- process.stdout.write(`声明与定义检查通过:${result.pairs.length} 对头文件与实现文件。\n`)
649
- }
650
- return result.issues.length === 0 ? EXIT.ok : EXIT.issues
620
+ let options
621
+ try {
622
+ options = parseArgs(argv)
623
+ } catch (error) {
624
+ return usage(error.message)
625
+ }
626
+ if (options.help) return help()
627
+ const root = options.root ? path.resolve(options.root) : process.cwd()
628
+ try {
629
+ statSync(root)
630
+ } catch {
631
+ return usage(`根目录不存在或无法读取:${root}`)
632
+ }
633
+ let result
634
+ try {
635
+ result = checkRoot(root)
636
+ } catch (error) {
637
+ return usage(`读取 ${root} 失败:${error.message}`)
638
+ }
639
+ if (options.json) {
640
+ process.stdout.write(`${JSON.stringify({ root, pairs: result.pairs.length, issues: result.issues }, null, 2)}\n`)
641
+ } else if (result.issues.length > 0) {
642
+ for (const issue of result.issues) process.stdout.write(`${issue.file}:${issue.line}: [${issue.rule}] ${issue.message}\n`)
643
+ process.stdout.write(`发现 ${result.issues.length} 处声明与定义问题。\n`)
644
+ } else if (!options.quiet) {
645
+ process.stdout.write(`声明与定义检查通过:${result.pairs.length} 对头文件与实现文件。\n`)
646
+ }
647
+ return result.issues.length === 0 ? EXIT.ok : EXIT.issues
651
648
  }
652
649
 
653
650
  if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
654
- process.exitCode = main(process.argv.slice(2))
651
+ process.exitCode = main(process.argv.slice(2))
655
652
  }