|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * Checks the content of the XML documentation comments (`///`) in the C# and C++ sources. |
| 5 | + * |
| 6 | + * The C# compiler (CS1591 with -warnaserror) and Doxygen (.github/scripts/check-doxygen-coverage.sh) |
| 7 | + * prove that every public and protected member is documented and that every parameter and return |
| 8 | + * value is described. They accept placeholder text, though, so this script checks what they cannot: |
| 9 | + * |
| 10 | + * - every comment is well-formed and has a <summary> (or <inheritdoc/>); |
| 11 | + * - <summary>, <remarks>, <param>, <typeparam>, <returns>, <value> and <exception> consist of |
| 12 | + * <para> paragraphs, in English first and then in Russian, as in all LinksPlatform libraries; |
| 13 | + * - no <para> is empty; |
| 14 | + * - every generic type parameter of a documented class, method or C++ template is described |
| 15 | + * with <typeparam>, and no <typeparam> names a parameter that does not exist. |
| 16 | + * |
| 17 | + * Usage: node .github/scripts/check-xml-docs.mjs [file or directory ...] |
| 18 | + * Without arguments it checks csharp/, cpp/ and examples/ of this repository. |
| 19 | + * VERBOSE=1 prints every checked comment. |
| 20 | + */ |
| 21 | + |
| 22 | +import { readdirSync, readFileSync, statSync } from "node:fs"; |
| 23 | +import { extname, join, relative, resolve } from "node:path"; |
| 24 | +import { fileURLToPath } from "node:url"; |
| 25 | + |
| 26 | +const repositoryRoot = resolve(fileURLToPath(new URL("../../", import.meta.url))); |
| 27 | +const sourceExtensions = new Set([".cs", ".h", ".hpp", ".cpp"]); |
| 28 | +const skippedDirectories = new Set(["bin", "obj", "build", "node_modules", ".git"]); |
| 29 | +const bilingualElements = new Set(["summary", "remarks", "param", "typeparam", "returns", "value", "exception"]); |
| 30 | +const cyrillic = /[\u0400-\u04FF]/; |
| 31 | +const latin = /[A-Za-z]/; |
| 32 | +const verbose = process.env.VERBOSE === "1"; |
| 33 | + |
| 34 | +/** Lists the source files of the given files and directories. */ |
| 35 | +export const listSources = (paths) => |
| 36 | + paths.flatMap((path) => { |
| 37 | + if (statSync(path).isDirectory()) { |
| 38 | + return readdirSync(path, { withFileTypes: true }) |
| 39 | + .filter((entry) => !(entry.isDirectory() && skippedDirectories.has(entry.name))) |
| 40 | + .sort((first, second) => first.name.localeCompare(second.name)) |
| 41 | + .flatMap((entry) => listSources([join(path, entry.name)])); |
| 42 | + } |
| 43 | + return sourceExtensions.has(extname(path)) ? [path] : []; |
| 44 | + }); |
| 45 | + |
| 46 | +/** Splits a source into its `///` comments, each with the declaration that follows it. */ |
| 47 | +export const findComments = (source) => { |
| 48 | + const lines = source.split(/\r?\n/); |
| 49 | + const comments = []; |
| 50 | + for (let index = 0; index < lines.length; index++) { |
| 51 | + if (!/^\s*\/\/\/(?!\/)/.test(lines[index])) { |
| 52 | + continue; |
| 53 | + } |
| 54 | + const start = index; |
| 55 | + const text = []; |
| 56 | + while (index < lines.length && /^\s*\/\/\/(?!\/)/.test(lines[index])) { |
| 57 | + text.push(lines[index].replace(/^\s*\/\/\/ ?/, "")); |
| 58 | + index++; |
| 59 | + } |
| 60 | + comments.push({ line: start + 1, text: text.join("\n"), declaration: readDeclaration(lines, index) }); |
| 61 | + index--; |
| 62 | + } |
| 63 | + return comments; |
| 64 | +}; |
| 65 | + |
| 66 | +/** Reads the declaration after a comment, up to its body, initializer or terminating semicolon. */ |
| 67 | +const readDeclaration = (lines, index) => { |
| 68 | + const parts = []; |
| 69 | + let depth = 0; |
| 70 | + for (; index < lines.length && parts.length < 20; index++) { |
| 71 | + const line = lines[index].replace(/\/\/.*$/, "").trim(); |
| 72 | + if (line === "" || (parts.length === 0 && /^\[.*\]$/.test(line))) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + let end = -1; |
| 76 | + for (let position = 0; position < line.length && end < 0; position++) { |
| 77 | + const character = line[position]; |
| 78 | + if (character === "(") depth++; |
| 79 | + else if (character === ")") depth--; |
| 80 | + else if (depth === 0 && (character === "{" || character === ";" || line.startsWith("=>", position))) end = position; |
| 81 | + } |
| 82 | + parts.push(end < 0 ? line : line.slice(0, end)); |
| 83 | + if (end >= 0) { |
| 84 | + break; |
| 85 | + } |
| 86 | + } |
| 87 | + return parts.join(" ").trim(); |
| 88 | +}; |
| 89 | + |
| 90 | +/** Parses the XML of a comment into a tree of elements and text nodes. */ |
| 91 | +export const parseXml = (text) => { |
| 92 | + const root = { name: "#root", attributes: {}, children: [] }; |
| 93 | + const stack = [root]; |
| 94 | + const pattern = /<!--[\s\S]*?-->|<(\/?)([A-Za-z][\w-]*)((?:\s+[\w-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|<|[^<]+/g; |
| 95 | + for (const match of text.matchAll(pattern)) { |
| 96 | + const [token, closing, name, attributeText, selfClosing] = match; |
| 97 | + const parent = stack.at(-1); |
| 98 | + if (token.startsWith("<!--")) { |
| 99 | + continue; |
| 100 | + } |
| 101 | + if (token === "<") { |
| 102 | + throw new Error("contains '<' that does not start a valid tag; write < instead"); |
| 103 | + } |
| 104 | + if (name === undefined) { |
| 105 | + parent.children.push({ text: token }); |
| 106 | + } else if (closing) { |
| 107 | + if (parent.name !== name) { |
| 108 | + throw new Error(`closes <${name}> while <${parent.name}> is open`); |
| 109 | + } |
| 110 | + stack.pop(); |
| 111 | + } else { |
| 112 | + const attributes = Object.fromEntries( |
| 113 | + [...attributeText.matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map(([, key, double, single]) => [key, double ?? single]), |
| 114 | + ); |
| 115 | + const element = { name, attributes, children: [] }; |
| 116 | + parent.children.push(element); |
| 117 | + if (!selfClosing) { |
| 118 | + stack.push(element); |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + if (stack.length > 1) { |
| 123 | + throw new Error(`does not close <${stack.at(-1).name}>`); |
| 124 | + } |
| 125 | + return root; |
| 126 | +}; |
| 127 | + |
| 128 | +/** Returns the text of a node, including the names that <see>, <paramref> and similar tags refer to. */ |
| 129 | +const textOf = (node) => |
| 130 | + node.text ?? |
| 131 | + [node.attributes.cref, node.attributes.name, node.attributes.langword, node.attributes.href] |
| 132 | + .filter(Boolean) |
| 133 | + .concat(node.children.map(textOf)) |
| 134 | + .join(" "); |
| 135 | + |
| 136 | +const elementsOf = (node, name) => node.children.filter((child) => child.name === name); |
| 137 | + |
| 138 | +/** Lists every element of a tree, depth first. */ |
| 139 | +const descendants = (node) => (node.children ?? []).flatMap((child) => (child.name ? [child, ...descendants(child)] : [])); |
| 140 | + |
| 141 | +/** Finds the generic type parameters that a declaration introduces. */ |
| 142 | +export const findTypeParameters = (declaration) => { |
| 143 | + const names = (list) => |
| 144 | + splitTopLevel(list) |
| 145 | + .map((parameter) => parameter.replace(/=.*$/, "").trim()) |
| 146 | + .filter((parameter) => !parameter.includes("...")) |
| 147 | + .map((parameter) => /(\w+)$/.exec(parameter)?.[1]) |
| 148 | + .filter(Boolean); |
| 149 | + const template = /^(?:(?:public|protected|private)\s*:\s*)?template\s*<((?:[^<>]|<[^<>]*>)*)>\s*(?:class|struct|union|[\w:<>,\s*&]+\()/.exec(declaration); |
| 150 | + if (template) { |
| 151 | + return names(template[1]); |
| 152 | + } |
| 153 | + const csharpType = /\b(?:class|struct|interface|record|delegate\s+[\w.<>?,\s]+?)\s+\w+\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/.exec(declaration); |
| 154 | + if (csharpType) { |
| 155 | + return names(csharpType[1]); |
| 156 | + } |
| 157 | + const csharpMethod = /\b\w+\s*<([^<>()]*(?:<[^<>()]*>[^<>()]*)*)>\s*\(/.exec(declaration); |
| 158 | + if (csharpMethod && !/^template\b/.test(declaration)) { |
| 159 | + return names(csharpMethod[1]); |
| 160 | + } |
| 161 | + return []; |
| 162 | +}; |
| 163 | + |
| 164 | +/** Splits a parameter list on the commas that are not nested in brackets. */ |
| 165 | +const splitTopLevel = (list) => { |
| 166 | + const parts = [""]; |
| 167 | + let depth = 0; |
| 168 | + for (const character of list) { |
| 169 | + if ("<([".includes(character)) depth++; |
| 170 | + if (">)]".includes(character)) depth--; |
| 171 | + if (character === "," && depth === 0) parts.push(""); |
| 172 | + else parts[parts.length - 1] += character; |
| 173 | + } |
| 174 | + return parts.filter((part) => part.trim() !== ""); |
| 175 | +}; |
| 176 | + |
| 177 | +/** Checks one comment and returns the problems it has. */ |
| 178 | +export const checkComment = ({ text, declaration }) => { |
| 179 | + let tree; |
| 180 | + try { |
| 181 | + tree = parseXml(text); |
| 182 | + } catch (error) { |
| 183 | + return [`The XML documentation comment ${error.message}.`]; |
| 184 | + } |
| 185 | + const problems = []; |
| 186 | + const all = descendants(tree); |
| 187 | + if (elementsOf(tree, "inheritdoc").length > 0) { |
| 188 | + return problems; |
| 189 | + } |
| 190 | + if (elementsOf(tree, "summary").length !== 1) { |
| 191 | + problems.push("The XML documentation comment must have exactly one <summary>."); |
| 192 | + } |
| 193 | + for (const node of tree.children) { |
| 194 | + if (node.text !== undefined && node.text.trim() !== "") { |
| 195 | + problems.push(`Text outside of a tag: "${node.text.trim().slice(0, 40)}".`); |
| 196 | + } |
| 197 | + } |
| 198 | + for (const element of tree.children.filter((child) => bilingualElements.has(child.name))) { |
| 199 | + const label = element.attributes.name ? `<${element.name} name="${element.attributes.name}">` : `<${element.name}>`; |
| 200 | + const paragraphs = elementsOf(element, "para"); |
| 201 | + const loose = element.children.filter((child) => child.name !== "para" && textOf(child).trim() !== ""); |
| 202 | + if (loose.length > 0) { |
| 203 | + problems.push(`${label} must keep all of its text in <para> paragraphs.`); |
| 204 | + } |
| 205 | + const texts = paragraphs.map((paragraph) => textOf(paragraph).trim()); |
| 206 | + const englishIndex = texts.findIndex((value) => latin.test(value) && !cyrillic.test(value)); |
| 207 | + const russianIndex = texts.findIndex((value) => cyrillic.test(value)); |
| 208 | + if (englishIndex < 0) { |
| 209 | + problems.push(`${label} must have a paragraph in English.`); |
| 210 | + } |
| 211 | + if (russianIndex < 0) { |
| 212 | + problems.push(`${label} must have a paragraph in Russian.`); |
| 213 | + } |
| 214 | + if (englishIndex >= 0 && russianIndex >= 0 && russianIndex < englishIndex) { |
| 215 | + problems.push(`${label} must have its English paragraphs before the Russian ones.`); |
| 216 | + } |
| 217 | + } |
| 218 | + if (all.some((element) => element.name === "para" && textOf(element).trim() === "")) { |
| 219 | + problems.push("The XML documentation comment has an empty <para>."); |
| 220 | + } |
| 221 | + const declared = findTypeParameters(declaration); |
| 222 | + const documented = elementsOf(tree, "typeparam").map((element) => element.attributes.name); |
| 223 | + for (const name of declared.filter((parameter) => !documented.includes(parameter))) { |
| 224 | + problems.push(`The type parameter ${name} has no <typeparam name="${name}">.`); |
| 225 | + } |
| 226 | + for (const name of documented.filter((parameter) => !declared.includes(parameter))) { |
| 227 | + problems.push(`<typeparam name="${name}"> describes no type parameter of: ${declaration.slice(0, 120)}`); |
| 228 | + } |
| 229 | + return problems; |
| 230 | +}; |
| 231 | + |
| 232 | +/** Checks the files and returns every problem with its location. */ |
| 233 | +export const checkFiles = (files, root = repositoryRoot) => |
| 234 | + files.flatMap((file) => |
| 235 | + findComments(readFileSync(file, "utf8")).flatMap((comment) => { |
| 236 | + const problems = checkComment(comment); |
| 237 | + if (verbose) { |
| 238 | + console.log(`${relative(root, file)}:${comment.line}: ${problems.length === 0 ? "ok" : "failed"} ${comment.declaration}`); |
| 239 | + } |
| 240 | + return problems.map((message) => ({ file: relative(root, file), line: comment.line, message })); |
| 241 | + }), |
| 242 | + ); |
| 243 | + |
| 244 | +if (process.argv[1] === fileURLToPath(import.meta.url)) { |
| 245 | + const arguments_ = process.argv.slice(2); |
| 246 | + const paths = arguments_.length > 0 |
| 247 | + ? arguments_.map((path) => resolve(path)) |
| 248 | + : ["csharp", "cpp", "examples"].map((path) => join(repositoryRoot, path)); |
| 249 | + const files = listSources(paths); |
| 250 | + const problems = checkFiles(files); |
| 251 | + for (const { file, line, message } of problems) { |
| 252 | + if (process.env.GITHUB_ACTIONS === "true") { |
| 253 | + console.log(`::error file=${file},line=${line}::${message.replaceAll("%", "%25").replaceAll("\n", "%0A")}`); |
| 254 | + } else { |
| 255 | + console.error(`${file}:${line}: ${message}`); |
| 256 | + } |
| 257 | + } |
| 258 | + if (problems.length > 0) { |
| 259 | + console.error(`${problems.length} XML documentation problem(s) found in ${files.length} files.`); |
| 260 | + process.exitCode = 1; |
| 261 | + } else { |
| 262 | + console.log(`Checked the XML documentation comments of ${files.length} files.`); |
| 263 | + } |
| 264 | +} |
0 commit comments