Skip to content

Commit 52b4edf

Browse files
authored
Merge pull request #111 from linksplatform/issue-69-9254ea64
Document every public C# and C++ element in English and Russian, and generate the C++ API documentation
2 parents cc5e711 + 6fc9f8d commit 52b4edf

101 files changed

Lines changed: 9980 additions & 823 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/actions/ci-plan/action.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ outputs:
1616
badges:
1717
description: Validate README, evidence Markdown and benchmark results
1818
value: ${{ steps.plan.outputs.badges }}
19+
xmlDocs:
20+
description: Check the XML documentation of the C# and C++ sources
21+
value: ${{ steps.plan.outputs.xmlDocs }}
1922
runs:
2023
using: composite
2124
steps:

‎.github/scripts/build-cpp-docs.sh‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env bash
2+
3+
# Builds the HTML API documentation of the C++ header library with Doxygen.
4+
# The repository Doxyfile is the base, so the site documents exactly the
5+
# elements that check-doxygen-coverage.sh requires to be documented, and the
6+
# README is the main page as on the C# DocFX site. Any Doxygen warning fails
7+
# the build. doxygen-para-filter.mjs keeps the English and the Russian
8+
# descriptions of parameters and return values on separate lines, because
9+
# Doxygen joins their <para> paragraphs.
10+
#
11+
# Usage: .github/scripts/build-cpp-docs.sh [SITE_DIRECTORY] (default: _site-cpp)
12+
# DOXYGEN selects the Doxygen binary (default: doxygen).
13+
14+
set -euo pipefail
15+
16+
repository=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
17+
site=$(realpath -m "${1:-_site-cpp}")
18+
doxygen=${DOXYGEN:-doxygen}
19+
work=$(mktemp -d)
20+
21+
cleanup() {
22+
rm -rf "$work"
23+
}
24+
trap cleanup EXIT
25+
26+
cd "$repository"
27+
"$doxygen" --version
28+
{
29+
cat Doxyfile
30+
echo "INPUT = cpp/Platform.Collections.Methods README.md"
31+
echo "USE_MDFILE_AS_MAINPAGE = README.md"
32+
echo "STRIP_FROM_PATH = cpp"
33+
echo "INPUT_FILTER = \"node $repository/.github/scripts/doxygen-para-filter.mjs\""
34+
echo "GENERATE_HTML = YES"
35+
echo "HTML_OUTPUT = html"
36+
echo "GENERATE_TREEVIEW = YES"
37+
echo "OUTPUT_DIRECTORY = $work"
38+
echo "WARN_LOGFILE = $work/warnings.log"
39+
echo "WARN_AS_ERROR = FAIL_ON_WARNINGS"
40+
} | "$doxygen" -
41+
42+
if [[ -s "$work/warnings.log" ]]; then
43+
cat "$work/warnings.log" >&2
44+
echo "Doxygen reported warnings while building the C++ documentation." >&2
45+
exit 1
46+
fi
47+
48+
rm -rf "$site"
49+
mkdir -p "$(dirname "$site")"
50+
mv "$work/html" "$site"
51+
echo "Built the C++ API documentation in $site."
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/env bash
2+
# Runs Doxygen with the repository Doxyfile and fails when it reports any warning,
3+
# such as an undocumented public or protected class or member, an undocumented parameter
4+
# or return value, or a documentation error.
5+
# Usage: DOXYGEN=/path/to/doxygen .github/scripts/check-doxygen-coverage.sh
6+
set -euo pipefail
7+
8+
repository_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
9+
doxygen="${DOXYGEN:-doxygen}"
10+
log="$repository_root/doxygen-warnings.log"
11+
12+
cd "$repository_root"
13+
rm -f "$log"
14+
"$doxygen" --version
15+
"$doxygen" Doxyfile
16+
rm -rf "$repository_root/doxygen-output"
17+
18+
if [[ -s "$log" ]]; then
19+
count="$(grep -c 'warning:' "$log" || true)"
20+
while IFS= read -r line; do
21+
if [[ "$line" =~ ^([^:]+):([0-9]+):\ warning:\ (.*)$ ]]; then
22+
file="${BASH_REMATCH[1]#"$repository_root"/}"
23+
if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then
24+
echo "::error file=$file,line=${BASH_REMATCH[2]}::${BASH_REMATCH[3]}"
25+
else
26+
echo "$file:${BASH_REMATCH[2]}: ${BASH_REMATCH[3]}"
27+
fi
28+
else
29+
echo "$line"
30+
fi
31+
done < "$log"
32+
echo "Doxygen reported $count documentation warning(s); see the lines above." >&2
33+
exit 1
34+
fi
35+
echo "Doxygen found every public and protected C# and C++ element documented."

‎.github/scripts/check-xml-docs.mjs‎

Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
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 &lt; 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

Comments
 (0)