mirror of
https://github.com/FairRootGroup/FairMQ.git
synced 2026-11-25 13:11:36 +00:00
feat(docs): add the documentation site
- Astro and Starlight site in docs/ for https://fairrootgroup.github.io/FairMQ/ - 64 pages in eight groups: start, concepts, guides, shared memory, examples, tools, reference and project - API reference and source browser from the Doxygen XML of fairmq/ - Code samples are snippets of the repository files; the build fails when a snippet does not match - Option tables take the names, types and defaults from the code - Interactive diagrams: state machine, zero-copy transfer, region acknowledgements, session objects, topology and channel anatomy - The 404 page sends the URLs of the Doxygen site to the new pages - scripts/check-pages.mjs checks pages, snippets and links without a build; scripts/check-links.mjs checks all links in dist/ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
776
docs/scripts/api.mjs
Normal file
776
docs/scripts/api.mjs
Normal file
@@ -0,0 +1,776 @@
|
||||
// Turns the Doxygen XML into the model for the API and source pages.
|
||||
//
|
||||
// The API pages show the types of the installed headers (FAIRMQ_PUBLIC_HEADER_FILES in
|
||||
// fairmq/CMakeLists.txt). The source pages show all files in fairmq/. A Doxygen reference
|
||||
// to a public symbol links to its API page; a reference to another symbol links to the
|
||||
// line in the source browser.
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { parseXmlFile, tagOf, isText, kids, attr, children, child, find, textOf, escapeHtml } from './xml.mjs';
|
||||
|
||||
const ENTITIES = {
|
||||
ndash: '–', mdash: '—', nbsp: ' ', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”', hellip: '…',
|
||||
copy: '©', trade: '™', reg: '®', plusmn: '±', times: '×', divide: '÷', larr: '←', rarr: '→', harr: '↔',
|
||||
uarr: '↑', darr: '↓', lArr: '⇐', rArr: '⇒', hArr: '⇔', laquo: '«', raquo: '»', deg: '°', micro: 'µ',
|
||||
middot: '·', bull: '•', le: '≤', ge: '≥', ne: '≠', minus: '−', infin: '∞', sect: '§', para: '¶',
|
||||
apos: "'", quot: '"', zwj: '', zwnj: '', shy: '',
|
||||
};
|
||||
|
||||
const KEYWORDS =
|
||||
/\b(template|typename|class|struct|union|enum|const|constexpr|static|virtual|explicit|inline|noexcept|override|final|void|bool|int|unsigned|signed|char|short|long|float|double|auto|using|typedef|friend|operator|default|delete|volatile|mutable|decltype|sizeof|true|false|nullptr)\b/g;
|
||||
|
||||
const OPERATOR_NAMES = {
|
||||
'=': 'assign', '==': 'eq', '!=': 'ne', '<': 'lt', '>': 'gt', '<=': 'le', '>=': 'ge', '<<': 'shl', '>>': 'shr',
|
||||
'[]': 'index', '()': 'call', '!': 'not', '+': 'plus', '-': 'minus', '*': 'deref', '&': 'and', '|': 'or',
|
||||
'->': 'arrow', '++': 'inc', '--': 'dec', '+=': 'plus-assign', '-=': 'minus-assign', '<=>': 'cmp',
|
||||
bool: 'bool',
|
||||
};
|
||||
|
||||
/** The headers that `cmake --install` puts into include/fairmq. */
|
||||
export function readPublicHeaders(repoRoot) {
|
||||
const text = readFileSync(path.join(repoRoot, 'fairmq', 'CMakeLists.txt'), 'utf8');
|
||||
const m = /set\(FAIRMQ_PUBLIC_HEADER_FILES([\s\S]*?)\)/.exec(text);
|
||||
if (!m) throw new Error('FAIRMQ_PUBLIC_HEADER_FILES not found in fairmq/CMakeLists.txt');
|
||||
return new Set(
|
||||
m[1]
|
||||
.split(/\s+/)
|
||||
.filter((s) => s && !s.startsWith('#') && !s.startsWith('$'))
|
||||
.map((s) => `fairmq/${s}`),
|
||||
);
|
||||
}
|
||||
|
||||
/** All C++ files in fairmq/, sorted by directory, then by name. */
|
||||
export function listSourceFiles(repoRoot) {
|
||||
const out = [];
|
||||
const walk = (rel) => {
|
||||
for (const e of readdirSync(path.join(repoRoot, rel), { withFileTypes: true })) {
|
||||
const p = `${rel}/${e.name}`;
|
||||
if (e.isDirectory()) walk(p);
|
||||
else if (/\.(h|cxx)$/.test(e.name)) out.push(p);
|
||||
}
|
||||
};
|
||||
walk('fairmq');
|
||||
return out.sort((a, b) => {
|
||||
const da = path.posix.dirname(a);
|
||||
const db = path.posix.dirname(b);
|
||||
if (da !== db) return da.localeCompare(db);
|
||||
return path.posix.basename(a).localeCompare(path.posix.basename(b), 'en', { sensitivity: 'base' });
|
||||
});
|
||||
}
|
||||
|
||||
function slugPath(name) {
|
||||
return name.split('::').join('/');
|
||||
}
|
||||
|
||||
/** A readable, stable anchor for a member name. */
|
||||
export function anchorFor(name) {
|
||||
let n = name.trim();
|
||||
if (n.startsWith('~')) return 'dtor';
|
||||
const op = /^operator\s*(.*)$/.exec(n);
|
||||
if (op) {
|
||||
const sym = op[1].replace(/\s+/g, '');
|
||||
return 'operator-' + (OPERATOR_NAMES[sym] ?? sym.replace(/[^A-Za-z0-9_]/g, (c) => c.charCodeAt(0).toString(16)));
|
||||
}
|
||||
return n.replace(/[^A-Za-z0-9_-]/g, '-');
|
||||
}
|
||||
|
||||
function normalizeTypeText(s) {
|
||||
return s
|
||||
.replace(/<\s+/g, '<')
|
||||
.replace(/\s+>/g, '>')
|
||||
.replace(/\s+([&*]+)/g, '$1')
|
||||
.replace(/\s+,/g, ',')
|
||||
.replace(/\(\s+/g, '(')
|
||||
.replace(/\s+\)/g, ')');
|
||||
}
|
||||
|
||||
function highlightKeywords(escaped) {
|
||||
return escaped.replace(KEYWORDS, '<span class="k">$1</span>');
|
||||
}
|
||||
|
||||
export function buildModel({ xmlDir, repoRoot, base = '' }) {
|
||||
const publicHeaders = readPublicHeaders(repoRoot);
|
||||
const sourceFiles = listSourceFiles(repoRoot);
|
||||
const sourceSet = new Set(sourceFiles);
|
||||
|
||||
/** @type {Map<string, any>} */
|
||||
const defs = new Map();
|
||||
for (const f of readdirSync(xmlDir)) {
|
||||
if (!f.endsWith('.xml') || f === 'index.xml' || f === 'Doxyfile.xml') continue;
|
||||
const doc = find(parseXmlFile(path.join(xmlDir, f)), 'doxygen');
|
||||
for (const cd of children(doc, 'compounddef')) defs.set(attr(cd, 'id'), cd);
|
||||
}
|
||||
|
||||
const compounds = new Map(); // id -> class/struct/union/namespace record
|
||||
const members = new Map(); // id -> member record
|
||||
const files = new Map(); // path -> file record
|
||||
const targets = new Map(); // refid -> { href, kind, name, sig, loc }
|
||||
|
||||
// ---------- Pass 1: records ----------
|
||||
for (const [id, cd] of defs) {
|
||||
const kind = attr(cd, 'kind');
|
||||
const name = textOf(child(cd, 'compoundname')).trim();
|
||||
const loc = child(cd, 'location');
|
||||
const file = attr(loc, 'file');
|
||||
if (kind === 'file') {
|
||||
if (!sourceSet.has(file)) continue;
|
||||
files.set(file, { id, path: file, node: cd, defines: [] });
|
||||
continue;
|
||||
}
|
||||
if (kind === 'dir' || kind === 'page' || kind === 'example' || kind === 'group') continue;
|
||||
if (name.includes('@')) continue;
|
||||
const isType = kind === 'class' || kind === 'struct' || kind === 'union';
|
||||
if (!isType && kind !== 'namespace') continue;
|
||||
const parts = name.split('::');
|
||||
const rec = {
|
||||
id,
|
||||
kind,
|
||||
name,
|
||||
short: parts[parts.length - 1],
|
||||
scope: parts.slice(0, -1).join('::'),
|
||||
file,
|
||||
line: Number(attr(loc, 'line')) || 1,
|
||||
prot: attr(cd, 'prot') ?? 'public',
|
||||
node: cd,
|
||||
url: `${base}/api/${slugPath(name)}/`,
|
||||
public: false,
|
||||
members: [],
|
||||
inner: children(cd, 'innerclass').map((n) => attr(n, 'refid')),
|
||||
innerNamespaces: children(cd, 'innernamespace').map((n) => attr(n, 'refid')),
|
||||
};
|
||||
if (isType) {
|
||||
rec.public = !!file && publicHeaders.has(file) && name.startsWith('fair::mq') && rec.prot === 'public';
|
||||
const inc = child(cd, 'includes');
|
||||
rec.include = inc ? textOf(inc).trim() : file;
|
||||
}
|
||||
compounds.set(id, rec);
|
||||
}
|
||||
|
||||
// Nested classes of a non-public class are not public either.
|
||||
for (const rec of compounds.values()) {
|
||||
if (rec.kind === 'namespace' || !rec.public) continue;
|
||||
const parent = [...compounds.values()].find((c) => c.name === rec.scope);
|
||||
if (parent && parent.kind !== 'namespace' && !parent.public) rec.public = false;
|
||||
}
|
||||
|
||||
// Members. Namespace members also appear in file compounds with the same id; the
|
||||
// namespace (or class) is the owner.
|
||||
const ownerOrder = (cd) => (attr(cd, 'kind') === 'file' ? 1 : 0);
|
||||
const sortedDefs = [...defs.values()].sort((a, b) => ownerOrder(a) - ownerOrder(b));
|
||||
for (const cd of sortedDefs) {
|
||||
const ownerId = attr(cd, 'id');
|
||||
const owner = compounds.get(ownerId);
|
||||
const fileRec = attr(cd, 'kind') === 'file' ? files.get(attr(child(cd, 'location'), 'file')) : undefined;
|
||||
if (!owner && !fileRec) continue;
|
||||
for (const sec of children(cd, 'sectiondef')) {
|
||||
const secKind = attr(sec, 'kind');
|
||||
for (const md of children(sec, 'memberdef')) {
|
||||
const mid = attr(md, 'id');
|
||||
if (members.has(mid)) continue;
|
||||
const loc = child(md, 'location');
|
||||
const m = {
|
||||
id: mid,
|
||||
kind: attr(md, 'kind'),
|
||||
name: textOf(child(md, 'name')).trim(),
|
||||
qualified: textOf(child(md, 'qualifiedname')).trim(),
|
||||
prot: attr(md, 'prot'),
|
||||
static: attr(md, 'static') === 'yes',
|
||||
constexpr: attr(md, 'constexpr') === 'yes',
|
||||
explicit: attr(md, 'explicit') === 'yes',
|
||||
virt: attr(md, 'virt'),
|
||||
strong: attr(md, 'strong') === 'yes',
|
||||
section: secKind,
|
||||
// A namespace function that a .cxx file defines has the .cxx file as location and
|
||||
// the header as declfile. The declaration in the header is the API.
|
||||
file: attr(loc, 'declfile') || attr(loc, 'file'),
|
||||
line: Number(attr(loc, 'declline') || attr(loc, 'line')) || 1,
|
||||
owner: owner ? owner.id : null,
|
||||
fileOwner: fileRec ? fileRec.path : null,
|
||||
node: md,
|
||||
};
|
||||
if (!m.qualified) m.qualified = owner ? `${owner.name}::${m.name}` : m.name;
|
||||
members.set(mid, m);
|
||||
if (owner) owner.members.push(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Pass 2: URLs and link targets ----------
|
||||
const sourceHref = (file, line) =>
|
||||
file && sourceSet.has(file) ? `${base}/source/${file}/${line ? `#L${line}` : ''}` : null;
|
||||
|
||||
for (const f of files.values()) {
|
||||
targets.set(f.id, { href: `${base}/source/${f.path}/`, kind: 'file', name: f.path, sig: f.path, loc: f.path });
|
||||
}
|
||||
|
||||
// Namespaces get a page when they hold public types or public members.
|
||||
for (const ns of compounds.values()) {
|
||||
if (ns.kind !== 'namespace') continue;
|
||||
const hasTypes = ns.inner.some((id) => compounds.get(id)?.public);
|
||||
// A name with :: is an explicit instantiation of a member template (extern template).
|
||||
const pubMembers = ns.members.filter((m) => publicHeaders.has(m.file) && m.kind !== 'define' && !m.name.includes('::'));
|
||||
ns.public = ns.name.startsWith('fair::mq') && (hasTypes || pubMembers.length > 0);
|
||||
// C++ has no access control in namespaces. Doxygen marks some functions of .cxx files private.
|
||||
for (const m of pubMembers) m.prot = 'public';
|
||||
ns.publicMembers = pubMembers;
|
||||
}
|
||||
|
||||
// Anchors per owner, with numbers for overloads.
|
||||
const assignAnchors = (list) => {
|
||||
const used = new Map();
|
||||
for (const m of list) {
|
||||
const a = anchorFor(m.name);
|
||||
const n = (used.get(a) ?? 0) + 1;
|
||||
used.set(a, n);
|
||||
m.anchor = n === 1 ? a : `${a}-${n}`;
|
||||
m.overload = n;
|
||||
}
|
||||
};
|
||||
|
||||
for (const rec of compounds.values()) {
|
||||
if (rec.kind === 'namespace') {
|
||||
if (!rec.public) continue;
|
||||
const list = rec.publicMembers;
|
||||
const enums = list.filter((m) => m.kind === 'enum');
|
||||
const rest = list.filter((m) => m.kind !== 'enum');
|
||||
assignAnchors(rest);
|
||||
for (const m of rest) m.href = `${rec.url}#${m.anchor}`;
|
||||
for (const e of enums) {
|
||||
e.anchor = anchorFor(e.name);
|
||||
e.page = `${rec.url}${e.name}/`;
|
||||
e.href = e.page;
|
||||
}
|
||||
} else if (rec.public) {
|
||||
const visible = rec.members.filter((m) => m.prot !== 'private');
|
||||
assignAnchors(visible);
|
||||
for (const m of visible) m.href = `${rec.url}#${m.anchor}`;
|
||||
}
|
||||
}
|
||||
|
||||
const kindLabel = (m) => {
|
||||
if (m.kind === 'function') {
|
||||
const owner = m.owner && compounds.get(m.owner);
|
||||
if (owner && owner.kind !== 'namespace') {
|
||||
if (m.name === owner.short) return 'constructor';
|
||||
if (m.name === `~${owner.short}`) return 'destructor';
|
||||
return m.static ? 'static member function' : 'member function';
|
||||
}
|
||||
return 'function';
|
||||
}
|
||||
if (m.kind === 'variable') return m.owner && compounds.get(m.owner)?.kind !== 'namespace' ? 'data member' : 'variable';
|
||||
if (m.kind === 'typedef') return 'type alias';
|
||||
if (m.kind === 'enum') return m.strong ? 'enum class' : 'enum';
|
||||
return m.kind;
|
||||
};
|
||||
|
||||
for (const rec of compounds.values()) {
|
||||
const href = rec.public ? rec.url : sourceHref(rec.file, rec.line);
|
||||
if (!href) continue;
|
||||
targets.set(rec.id, {
|
||||
href,
|
||||
kind: rec.kind,
|
||||
name: rec.name,
|
||||
sig: `${rec.kind} ${rec.name}`,
|
||||
loc: `${rec.file}:${rec.line}`,
|
||||
});
|
||||
}
|
||||
for (const m of members.values()) {
|
||||
const href = m.href ?? sourceHref(m.file, m.line);
|
||||
if (!href) continue;
|
||||
targets.set(m.id, { href, kind: kindLabel(m), name: m.qualified, sig: '', loc: `${m.file}:${m.line}`, member: m });
|
||||
if (m.kind === 'enum') {
|
||||
for (const ev of children(m.node, 'enumvalue')) {
|
||||
const evName = textOf(child(ev, 'name')).trim();
|
||||
targets.set(attr(ev, 'id'), {
|
||||
href: m.page ? `${m.page}#${anchorFor(evName)}` : m.href ? `${m.href}` : href,
|
||||
kind: 'enumerator',
|
||||
name: `${m.qualified}::${evName}`,
|
||||
sig: `${m.qualified}::${evName}${textOf(child(ev, 'initializer')) ? ' ' + textOf(child(ev, 'initializer')).trim() : ''}`,
|
||||
loc: `${m.file}:${m.line}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Rendering helpers ----------
|
||||
const link = (refid, innerHtml) => {
|
||||
const t = targets.get(refid);
|
||||
if (!t) return innerHtml;
|
||||
return `<a href="${escapeHtml(t.href)}">${innerHtml}</a>`;
|
||||
};
|
||||
|
||||
/** Linked text (types, initializers): text and <ref> only. */
|
||||
const linked = (node, { type = false, keywords = true } = {}) => {
|
||||
if (!node) return '';
|
||||
const parts = [];
|
||||
for (const n of kids(node)) {
|
||||
if (isText(n)) {
|
||||
const raw = type ? normalizeTypeText(n['#text']) : n['#text'];
|
||||
const t = escapeHtml(raw);
|
||||
parts.push(keywords ? highlightKeywords(t) : t);
|
||||
} else if (tagOf(n) === 'ref') {
|
||||
parts.push(link(attr(n, 'refid'), escapeHtml(textOf(n))));
|
||||
} else if (tagOf(n) === 'sp') {
|
||||
parts.push(' ');
|
||||
} else {
|
||||
parts.push(linked(n, { type, keywords }));
|
||||
}
|
||||
}
|
||||
return parts.join('').replace(/\s+/g, ' ').trim();
|
||||
};
|
||||
|
||||
const plain = (node, type = false) => {
|
||||
const t = textOf(node).replace(/\s+/g, ' ').trim();
|
||||
return type ? normalizeTypeText(t) : t;
|
||||
};
|
||||
|
||||
const renderInline = (n) => {
|
||||
if (isText(n)) return escapeHtml(n['#text']);
|
||||
const t = tagOf(n);
|
||||
if (ENTITIES[t] !== undefined) return ENTITIES[t];
|
||||
switch (t) {
|
||||
case 'sp':
|
||||
return ' ';
|
||||
case 'ref':
|
||||
return link(attr(n, 'refid'), kids(n).map(renderInline).join(''));
|
||||
case 'computeroutput':
|
||||
return `<code>${kids(n).map(renderInline).join('')}</code>`;
|
||||
case 'emphasis':
|
||||
return `<em>${kids(n).map(renderInline).join('')}</em>`;
|
||||
case 'bold':
|
||||
return `<strong>${kids(n).map(renderInline).join('')}</strong>`;
|
||||
case 's':
|
||||
case 'strike':
|
||||
case 'del':
|
||||
return `<del>${kids(n).map(renderInline).join('')}</del>`;
|
||||
case 'underline':
|
||||
case 'ins':
|
||||
return `<u>${kids(n).map(renderInline).join('')}</u>`;
|
||||
case 'subscript':
|
||||
return `<sub>${kids(n).map(renderInline).join('')}</sub>`;
|
||||
case 'superscript':
|
||||
return `<sup>${kids(n).map(renderInline).join('')}</sup>`;
|
||||
case 'small':
|
||||
return `<small>${kids(n).map(renderInline).join('')}</small>`;
|
||||
case 'ulink':
|
||||
return `<a href="${escapeHtml(attr(n, 'url') ?? '#')}">${kids(n).map(renderInline).join('')}</a>`;
|
||||
case 'linebreak':
|
||||
return '<br>';
|
||||
case 'nonbreakablespace':
|
||||
return ' ';
|
||||
case 'anchor':
|
||||
return '';
|
||||
case 'formula':
|
||||
return `<code>${escapeHtml(textOf(n))}</code>`;
|
||||
case 'emoji':
|
||||
return attr(n, 'unicode') ?? '';
|
||||
case 'image':
|
||||
case 'htmlonly':
|
||||
case 'manonly':
|
||||
case 'xmlonly':
|
||||
case 'rtfonly':
|
||||
case 'latexonly':
|
||||
case 'docbookonly':
|
||||
case 'dot':
|
||||
case 'msc':
|
||||
case 'plantuml':
|
||||
case 'indexentry':
|
||||
return '';
|
||||
default:
|
||||
return kids(n).map(renderInline).join('');
|
||||
}
|
||||
};
|
||||
|
||||
const codeOf = (n) =>
|
||||
children(n, 'codeline')
|
||||
.map((cl) => textOf(cl))
|
||||
.join('\n');
|
||||
|
||||
const unwrapP = (html) => {
|
||||
const m = /^<p>([\s\S]*)<\/p>$/.exec(html);
|
||||
return m && !m[1].includes('<p>') ? m[1] : html;
|
||||
};
|
||||
|
||||
/** Renders a description into HTML. Parameters, return values and notes go into `out`. */
|
||||
const renderBlocks = (nodes, out) => {
|
||||
let html = '';
|
||||
for (const n of nodes) {
|
||||
if (isText(n)) {
|
||||
if (n['#text'].trim()) html += `<p>${escapeHtml(n['#text'].trim())}</p>`;
|
||||
continue;
|
||||
}
|
||||
const t = tagOf(n);
|
||||
if (t === 'para') html += renderPara(n, out);
|
||||
else if (t === 'sect1' || t === 'sect2' || t === 'sect3' || t === 'internal') {
|
||||
const title = child(n, 'title');
|
||||
if (title) html += `<p class="doc-h">${kids(title).map(renderInline).join('')}</p>`;
|
||||
html += renderBlocks(
|
||||
kids(n).filter((k) => tagOf(k) !== 'title'),
|
||||
out,
|
||||
);
|
||||
} else html += renderPara({ para: [n] }, out);
|
||||
}
|
||||
return html;
|
||||
};
|
||||
|
||||
const listItems = (n, out) =>
|
||||
children(n, 'listitem')
|
||||
.map((li) => `<li>${unwrapP(renderBlocks(kids(li), out).trim())}</li>`)
|
||||
.join('');
|
||||
|
||||
const renderPara = (para, out) => {
|
||||
let html = '';
|
||||
let inline = [];
|
||||
const flush = () => {
|
||||
const text = inline.join('').replace(/\s+/g, ' ').trim();
|
||||
if (text) html += `<p>${text}</p>`;
|
||||
inline = [];
|
||||
};
|
||||
for (const n of kids(para)) {
|
||||
if (isText(n)) {
|
||||
inline.push(escapeHtml(n['#text']));
|
||||
continue;
|
||||
}
|
||||
const t = tagOf(n);
|
||||
switch (t) {
|
||||
case 'parameterlist': {
|
||||
flush();
|
||||
const kind = attr(n, 'kind');
|
||||
for (const item of children(n, 'parameteritem')) {
|
||||
const names = children(child(item, 'parameternamelist'), 'parametername').map((pn) => ({
|
||||
name: textOf(pn).trim(),
|
||||
dir: attr(pn, 'direction'),
|
||||
}));
|
||||
const desc = unwrapP(renderBlocks(kids(child(item, 'parameterdescription')), out).trim());
|
||||
for (const { name, dir } of names) {
|
||||
const entry = { name, dir, html: desc };
|
||||
if (kind === 'templateparam') out.tparams.push(entry);
|
||||
else if (kind === 'retval') out.retvals.push(entry);
|
||||
else if (kind === 'exception') out.throws.push(entry);
|
||||
else out.params.push(entry);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'simplesect': {
|
||||
flush();
|
||||
const kind = attr(n, 'kind');
|
||||
const body = renderBlocks(
|
||||
kids(n).filter((k) => tagOf(k) !== 'title'),
|
||||
out,
|
||||
).trim();
|
||||
if (kind === 'return') out.returns = out.returns ? `${out.returns} ${unwrapP(body)}` : unwrapP(body);
|
||||
else if (kind === 'see') out.see.push(unwrapP(body));
|
||||
else if (kind === 'since') out.since = textOf(n).trim();
|
||||
else if (kind === 'note' || kind === 'remark' || kind === 'attention' || kind === 'important')
|
||||
html += `<div class="doc-aside note"><b>Note</b>${body}</div>`;
|
||||
else if (kind === 'warning') html += `<div class="doc-aside caution"><b>Caution</b>${body}</div>`;
|
||||
else if (kind === 'pre') html += `<p><strong>Precondition:</strong> ${unwrapP(body)}</p>`;
|
||||
else if (kind === 'post') html += `<p><strong>Postcondition:</strong> ${unwrapP(body)}</p>`;
|
||||
else if (kind === 'invariant') html += `<p><strong>Invariant:</strong> ${unwrapP(body)}</p>`;
|
||||
else if (kind === 'par') {
|
||||
const title = child(n, 'title');
|
||||
const label = title ? kids(title).map(renderInline).join('').trim() : '';
|
||||
html += `<div class="doc-aside note"><b>${label || 'Note'}</b>${body}</div>`;
|
||||
}
|
||||
// author, authors, version, date, copyright: not shown
|
||||
break;
|
||||
}
|
||||
case 'xrefsect': {
|
||||
flush();
|
||||
const title = textOf(child(n, 'xreftitle')).trim();
|
||||
const body = renderBlocks(kids(child(n, 'xrefdescription')), out).trim();
|
||||
if (/deprecated/i.test(title)) out.deprecated = unwrapP(body) || 'Deprecated.';
|
||||
else html += `<div class="doc-aside note"><b>${escapeHtml(title)}</b>${body}</div>`;
|
||||
break;
|
||||
}
|
||||
case 'itemizedlist':
|
||||
flush();
|
||||
html += `<ul>${listItems(n, out)}</ul>`;
|
||||
break;
|
||||
case 'orderedlist':
|
||||
flush();
|
||||
html += `<ol>${listItems(n, out)}</ol>`;
|
||||
break;
|
||||
case 'programlisting':
|
||||
flush();
|
||||
html += `<pre class="doc-code"><code>${escapeHtml(codeOf(n))}</code></pre>`;
|
||||
break;
|
||||
case 'verbatim':
|
||||
case 'preformatted':
|
||||
flush();
|
||||
html += `<pre class="doc-code"><code>${escapeHtml(textOf(n))}</code></pre>`;
|
||||
break;
|
||||
case 'heading':
|
||||
flush();
|
||||
html += `<p class="doc-h">${kids(n).map(renderInline).join('')}</p>`;
|
||||
break;
|
||||
case 'blockquote':
|
||||
flush();
|
||||
html += `<blockquote>${renderBlocks(kids(n), out)}</blockquote>`;
|
||||
break;
|
||||
case 'hruler':
|
||||
flush();
|
||||
html += '<hr>';
|
||||
break;
|
||||
case 'table': {
|
||||
flush();
|
||||
const rows = children(n, 'row')
|
||||
.map((r) => {
|
||||
const cells = children(r, 'entry')
|
||||
.map((e) => {
|
||||
const tag = attr(e, 'thead') === 'yes' ? 'th' : 'td';
|
||||
return `<${tag}>${unwrapP(renderBlocks(kids(e), out).trim())}</${tag}>`;
|
||||
})
|
||||
.join('');
|
||||
return `<tr>${cells}</tr>`;
|
||||
})
|
||||
.join('');
|
||||
html += `<div class="doc-table"><table>${rows}</table></div>`;
|
||||
break;
|
||||
}
|
||||
case 'variablelist': {
|
||||
flush();
|
||||
let dl = '';
|
||||
for (const k of kids(n)) {
|
||||
if (tagOf(k) === 'varlistentry') dl += `<dt>${kids(child(k, 'term')).map(renderInline).join('')}</dt>`;
|
||||
if (tagOf(k) === 'listitem') dl += `<dd>${unwrapP(renderBlocks(kids(k), out).trim())}</dd>`;
|
||||
}
|
||||
html += `<dl>${dl}</dl>`;
|
||||
break;
|
||||
}
|
||||
case 'para':
|
||||
flush();
|
||||
html += renderPara(n, out);
|
||||
break;
|
||||
default:
|
||||
inline.push(renderInline(n));
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return html;
|
||||
};
|
||||
|
||||
const newOut = () => ({ params: [], tparams: [], retvals: [], throws: [], returns: '', see: [], since: '', deprecated: '' });
|
||||
|
||||
const describe = (node) => {
|
||||
const out = newOut();
|
||||
const briefNode = child(node, 'briefdescription');
|
||||
const brief = briefNode
|
||||
? children(briefNode, 'para')
|
||||
.map((p) => unwrapP(renderPara(p, out)))
|
||||
.join(' ')
|
||||
.trim()
|
||||
: '';
|
||||
const detailNode = child(node, 'detaileddescription');
|
||||
const detail = detailNode ? renderBlocks(kids(detailNode), out).trim() : '';
|
||||
const documented =
|
||||
!!brief ||
|
||||
!!detail ||
|
||||
out.params.some((p) => p.html) ||
|
||||
!!out.returns ||
|
||||
out.retvals.length > 0 ||
|
||||
!!out.deprecated;
|
||||
return { brief, detail, ...out, documented };
|
||||
};
|
||||
|
||||
const tparamList = (node) => {
|
||||
const tpl = child(node, 'templateparamlist');
|
||||
if (!tpl) return null;
|
||||
const ps = children(tpl, 'param').map((p) => {
|
||||
const type = linked(child(p, 'type'), { type: true });
|
||||
const decl = textOf(child(p, 'declname')).trim();
|
||||
const defval = child(p, 'defval');
|
||||
let s = type;
|
||||
if (decl && !new RegExp(`\\b${decl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`).test(plain(child(p, 'type')))) s += ` ${escapeHtml(decl)}`;
|
||||
if (defval) s += ` = ${linked(defval, { type: true })}`;
|
||||
return s;
|
||||
});
|
||||
return `<span class="k">template</span><${ps.join(', ')}>`;
|
||||
};
|
||||
|
||||
/** The text after the parameter list in an argsstring, e.g. "const", "noexcept=default". */
|
||||
const qualifiersOf = (args) => {
|
||||
const s = args ?? '';
|
||||
const start = s.indexOf('(');
|
||||
if (start < 0) return s.trim();
|
||||
let depth = 0;
|
||||
for (let i = start; i < s.length; i++) {
|
||||
if (s[i] === '(') depth++;
|
||||
else if (s[i] === ')') {
|
||||
depth--;
|
||||
if (depth === 0) return s.slice(i + 1).trim();
|
||||
}
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const formatQualifiers = (q) =>
|
||||
q
|
||||
.replace(/\s*=\s*(default|delete|0)\s*$/, ' = $1')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
|
||||
const signature = (m) => {
|
||||
const node = m.node;
|
||||
const name = `<b>${escapeHtml(m.name)}</b>`;
|
||||
const tpl = tparamList(node);
|
||||
const typeHtml = linked(child(node, 'type'), { type: true });
|
||||
const typeText = plain(child(node, 'type'), true);
|
||||
// Doxygen keeps some specifiers in the type text; do not repeat them.
|
||||
const typeWords = new Set(typeText.split(/\s+/).slice(0, 4));
|
||||
const pre = [];
|
||||
if (m.kind === 'friend' && !typeWords.has('friend')) pre.push('friend');
|
||||
if (m.static && !typeWords.has('static')) pre.push('static');
|
||||
if (m.constexpr && !typeWords.has('constexpr')) pre.push('constexpr');
|
||||
if (m.explicit && !typeWords.has('explicit')) pre.push('explicit');
|
||||
if ((m.virt === 'virtual' || m.virt === 'pure-virtual') && !typeWords.has('virtual')) pre.push('virtual');
|
||||
const preHtml = pre.map((p) => `<span class="k">${p}</span> `).join('');
|
||||
const argsstring = textOf(child(node, 'argsstring'));
|
||||
let body;
|
||||
let text;
|
||||
if (m.kind === 'function' || (m.kind === 'friend' && argsstring.includes('('))) {
|
||||
const params = children(node, 'param').map((p) => {
|
||||
const ptype = linked(child(p, 'type'), { type: true });
|
||||
const decl = textOf(child(p, 'declname')).trim();
|
||||
const arr = textOf(child(p, 'array')).trim();
|
||||
const defval = child(p, 'defval');
|
||||
let s = ptype;
|
||||
if (decl) s += `${ptype ? ' ' : ''}${escapeHtml(decl)}`;
|
||||
if (arr) s += escapeHtml(arr);
|
||||
if (defval) s += ` = ${linked(defval)}`;
|
||||
return s;
|
||||
});
|
||||
const paramText = children(node, 'param').map((p) => {
|
||||
let s = plain(child(p, 'type'), true);
|
||||
const decl = textOf(child(p, 'declname')).trim();
|
||||
if (decl) s += ` ${decl}`;
|
||||
if (child(p, 'defval')) s += ` = ${plain(child(p, 'defval'))}`;
|
||||
return s;
|
||||
});
|
||||
const qual = formatQualifiers(qualifiersOf(argsstring));
|
||||
const qualHtml = qual ? ' ' + highlightKeywords(escapeHtml(qual)) : '';
|
||||
const oneLine = `${pre.join(' ')} ${typeText} ${m.name}(${paramText.join(', ')}) ${qual}`.trim();
|
||||
const multi = oneLine.length > 78 && params.length > 1;
|
||||
const paramsHtml = multi ? `\n ${params.join(',\n ')}\n` : params.join(', ');
|
||||
// "void" as the only parameter type with no name means no parameters.
|
||||
body = `${preHtml}${typeHtml ? typeHtml + ' ' : ''}${name}(${paramsHtml})${qualHtml}`;
|
||||
text = `${pre.length ? pre.join(' ') + ' ' : ''}${typeText ? typeText + ' ' : ''}${m.name}(${paramText.join(', ')})${qual ? ' ' + qual : ''}`;
|
||||
} else if (m.kind === 'variable') {
|
||||
const init = child(node, 'initializer');
|
||||
const initHtml = init ? ' ' + linked(init) : '';
|
||||
body = `${preHtml}${typeHtml} ${name}${escapeHtml(argsstring)}${initHtml}`;
|
||||
text = `${pre.join(' ')} ${typeText} ${m.name}${argsstring}${init ? ' ' + plain(init) : ''}`.trim();
|
||||
} else if (m.kind === 'typedef') {
|
||||
const def = textOf(child(node, 'definition')).trim();
|
||||
if (def.startsWith('using')) {
|
||||
body = `<span class="k">using</span> ${name} = ${typeHtml}`;
|
||||
text = `using ${m.name} = ${typeText}`;
|
||||
} else {
|
||||
body = `<span class="k">typedef</span> ${typeHtml} ${name}${escapeHtml(argsstring)}`;
|
||||
text = `typedef ${typeText} ${m.name}${argsstring}`;
|
||||
}
|
||||
} else if (m.kind === 'enum') {
|
||||
const under = typeHtml ? ` : ${typeHtml}` : '';
|
||||
body = `<span class="k">enum</span>${m.strong ? ' <span class="k">class</span>' : ''} ${name}${under}`;
|
||||
text = `enum${m.strong ? ' class' : ''} ${m.name}${typeText ? ' : ' + typeText : ''}`;
|
||||
} else if (m.kind === 'friend') {
|
||||
body = `<span class="k">friend</span> ${typeHtml} ${name}`;
|
||||
text = `friend ${typeText} ${m.name}`;
|
||||
} else if (m.kind === 'define') {
|
||||
body = `<span class="k">#define</span> ${name}${escapeHtml(argsstring)}`;
|
||||
text = `#define ${m.name}${argsstring}`;
|
||||
} else {
|
||||
body = `${typeHtml} ${name}${escapeHtml(argsstring)}`;
|
||||
text = `${typeText} ${m.name}${argsstring}`;
|
||||
}
|
||||
return { html: tpl ? `${tpl}\n${body}` : body, text: text.replace(/\s+/g, ' ').trim(), template: !!tpl };
|
||||
};
|
||||
|
||||
// ---------- Pass 3: render public records ----------
|
||||
for (const m of members.values()) {
|
||||
const sig = signature(m);
|
||||
m.sigHtml = sig.html;
|
||||
m.sigText = sig.text;
|
||||
m.template = sig.template;
|
||||
const t = targets.get(m.id);
|
||||
if (t) t.sig = sig.text;
|
||||
}
|
||||
|
||||
const renderMember = (m) => {
|
||||
Object.assign(m, describe(m.node));
|
||||
if (m.kind === 'enum') {
|
||||
m.values = children(m.node, 'enumvalue').map((ev) => {
|
||||
const out = newOut();
|
||||
const b = child(ev, 'briefdescription');
|
||||
const d = child(ev, 'detaileddescription');
|
||||
const brief = b ? children(b, 'para').map((p) => unwrapP(renderPara(p, out))).join(' ').trim() : '';
|
||||
const detail = d ? renderBlocks(kids(d), out).trim() : '';
|
||||
return {
|
||||
name: textOf(child(ev, 'name')).trim(),
|
||||
anchor: anchorFor(textOf(child(ev, 'name')).trim()),
|
||||
init: plain(child(ev, 'initializer')).replace(/^=\s*/, ''),
|
||||
html: [brief, unwrapP(detail)].filter(Boolean).join(' '),
|
||||
};
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
for (const rec of compounds.values()) {
|
||||
if (!rec.public) continue;
|
||||
Object.assign(rec, describe(rec.node));
|
||||
rec.templ = tparamList(rec.node);
|
||||
rec.final = attr(rec.node, 'final') === 'yes';
|
||||
rec.abstract = attr(rec.node, 'abstract') === 'yes';
|
||||
rec.bases = children(rec.node, 'basecompoundref').map((b) => ({
|
||||
html: attr(b, 'refid') ? link(attr(b, 'refid'), escapeHtml(textOf(b).trim())) : escapeHtml(textOf(b).trim()),
|
||||
prot: attr(b, 'prot'),
|
||||
virt: attr(b, 'virt'),
|
||||
}));
|
||||
rec.derived = children(rec.node, 'derivedcompoundref').map((b) => ({
|
||||
html: attr(b, 'refid') ? link(attr(b, 'refid'), escapeHtml(textOf(b).trim())) : escapeHtml(textOf(b).trim()),
|
||||
id: attr(b, 'refid'),
|
||||
}));
|
||||
const list = rec.kind === 'namespace' ? rec.publicMembers : rec.members.filter((m) => m.prot !== 'private');
|
||||
for (const m of list) renderMember(m);
|
||||
rec.visible = list;
|
||||
}
|
||||
|
||||
// Which types and members each file defines, for the source pages.
|
||||
for (const rec of compounds.values()) {
|
||||
if (rec.kind !== 'namespace' && files.has(rec.file)) files.get(rec.file).defines.push(rec);
|
||||
}
|
||||
|
||||
return {
|
||||
base,
|
||||
publicHeaders,
|
||||
sourceFiles,
|
||||
compounds,
|
||||
members,
|
||||
files,
|
||||
targets,
|
||||
link,
|
||||
/** Public classes, structs and unions. */
|
||||
types: () => [...compounds.values()].filter((c) => c.public && c.kind !== 'namespace'),
|
||||
/** Namespaces with a page. */
|
||||
namespaces: () => [...compounds.values()].filter((c) => c.public && c.kind === 'namespace'),
|
||||
/** Enums at namespace scope, which get their own pages. */
|
||||
namespaceEnums: () =>
|
||||
[...compounds.values()]
|
||||
.filter((c) => c.public && c.kind === 'namespace')
|
||||
.flatMap((ns) => ns.visible.filter((m) => m.kind === 'enum').map((e) => ({ ns, e }))),
|
||||
compoundByName: (name) => [...compounds.values()].find((c) => c.name === name),
|
||||
};
|
||||
}
|
||||
|
||||
let cached;
|
||||
let cachedKey;
|
||||
/** The model, built once per build. */
|
||||
export function getModel(opts) {
|
||||
const key = JSON.stringify(opts);
|
||||
if (!cached || cachedKey !== key) {
|
||||
cached = buildModel(opts);
|
||||
cachedKey = key;
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
26
docs/scripts/base-links.mjs
Normal file
26
docs/scripts/base-links.mjs
Normal file
@@ -0,0 +1,26 @@
|
||||
// Sätteri hast plugin: prefixes root-relative links and images in Markdown and MDX
|
||||
// with the site base, so that pages can link to `/concepts/channels/`
|
||||
// instead of `/FairMQ/concepts/channels/`.
|
||||
|
||||
function prefix(url, base) {
|
||||
if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//')) return url;
|
||||
if (url === base || url.startsWith(base + '/')) return url;
|
||||
return base + url;
|
||||
}
|
||||
|
||||
export default function baseLinks({ base }) {
|
||||
const b = base.replace(/\/$/, '');
|
||||
return {
|
||||
name: 'fairmq-base-links',
|
||||
element: {
|
||||
filter: ['a', 'img'],
|
||||
visit(node, ctx) {
|
||||
if (!b) return;
|
||||
const key = node.tagName === 'a' ? 'href' : 'src';
|
||||
const value = node.properties?.[key];
|
||||
const next = prefix(value, b);
|
||||
if (next !== value) ctx.setProperty(node, key, next);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
37
docs/scripts/build-info.mjs
Normal file
37
docs/scripts/build-info.mjs
Normal file
@@ -0,0 +1,37 @@
|
||||
// Version and commit of the FairMQ checkout that the site is built from.
|
||||
import { execFileSync } from 'node:child_process';
|
||||
|
||||
function git(cwd, ...args) {
|
||||
try {
|
||||
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function buildInfo(cwd = process.cwd()) {
|
||||
const commit = process.env.GITHUB_SHA || git(cwd, 'rev-parse', 'HEAD') || 'unknown';
|
||||
const commitShort = commit.slice(0, 7);
|
||||
const date = git(cwd, 'show', '-s', '--format=%cs', 'HEAD');
|
||||
const branch = process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME || git(cwd, 'rev-parse', '--abbrev-ref', 'HEAD');
|
||||
// `git describe` gives e.g. v1.11.0-23-ge366c40; a checkout without tags gives nothing.
|
||||
const describe = git(cwd, 'describe', '--tags', '--match', 'v[0-9]*', '--long');
|
||||
const m = /^v(\d+)\.(\d+)\.(\d+)-(\d+)-g[0-9a-f]+$/.exec(describe);
|
||||
const release = m ? `v${m[1]}.${m[2]}.${m[3]}` : '';
|
||||
const ahead = m ? Number(m[4]) : -1;
|
||||
let label;
|
||||
if (m && ahead === 0) label = release;
|
||||
else if (m) label = `v${m[1]}.${m[2]}`;
|
||||
else label = 'dev';
|
||||
return {
|
||||
commit,
|
||||
commitShort,
|
||||
date,
|
||||
branch,
|
||||
release,
|
||||
ahead,
|
||||
label,
|
||||
unreleased: ahead !== 0,
|
||||
repo: 'https://github.com/FairRootGroup/FairMQ',
|
||||
};
|
||||
}
|
||||
75
docs/scripts/check-links.mjs
Normal file
75
docs/scripts/check-links.mjs
Normal file
@@ -0,0 +1,75 @@
|
||||
// Checks all internal links and anchors in the built site (dist/).
|
||||
// node scripts/check-links.mjs [distDir]
|
||||
// Exit code 1 if a link points to a missing page or a missing anchor.
|
||||
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const dist = path.resolve(process.argv[2] ?? new URL('../dist', import.meta.url).pathname);
|
||||
const base = '/FairMQ';
|
||||
|
||||
function walk(dir, out = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const p = path.join(dir, name);
|
||||
if (statSync(p).isDirectory()) walk(p, out);
|
||||
else if (name.endsWith('.html')) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const pages = walk(dist);
|
||||
const ids = new Map();
|
||||
const links = [];
|
||||
const idRe = /\sid="([^"]+)"/g;
|
||||
const linkRe = /\s(href|src)="([^"]+)"/g;
|
||||
for (const file of pages) {
|
||||
const html = readFileSync(file, 'utf8');
|
||||
ids.set(file, new Set([...html.matchAll(idRe)].map((m) => m[1])));
|
||||
// Skip the content of <script> blocks: their strings are not links.
|
||||
const text = html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g, '');
|
||||
for (const m of text.matchAll(linkRe)) links.push({ file, attr: m[1], url: m[2].replace(/&/g, '&') });
|
||||
}
|
||||
|
||||
const resolve = (url) => {
|
||||
const p = decodeURIComponent(url.slice(base.length)) || '/';
|
||||
const candidates = [path.join(dist, p), path.join(dist, p, 'index.html'), path.join(dist, p + '.html')];
|
||||
return candidates.find((c) => existsSync(c) && statSync(c).isFile());
|
||||
};
|
||||
|
||||
const bad = [];
|
||||
for (const { file, url } of links) {
|
||||
if (/^(https?:|mailto:|data:|javascript:)/.test(url) || url.startsWith('//')) continue;
|
||||
const from = '/' + path.relative(dist, file);
|
||||
let [target, hash] = url.split('#');
|
||||
if (!target) {
|
||||
if (hash && !ids.get(file).has(hash)) bad.push(`${from}: missing anchor #${hash}`);
|
||||
continue;
|
||||
}
|
||||
if (!target.startsWith('/')) {
|
||||
bad.push(`${from}: relative link ${url}`);
|
||||
continue;
|
||||
}
|
||||
if (!target.startsWith(base + '/') && target !== base) {
|
||||
bad.push(`${from}: link without the base ${url}`);
|
||||
continue;
|
||||
}
|
||||
const t = resolve(target.split('?')[0]);
|
||||
if (!t) {
|
||||
bad.push(`${from}: missing page ${url}`);
|
||||
continue;
|
||||
}
|
||||
if (hash && t.endsWith('.html') && !ids.get(t)?.has(hash) && !/^L\d+(-L\d+)?$/.test(hash)) bad.push(`${from}: missing anchor ${url}`);
|
||||
if (hash && /^L(\d+)(?:-L(\d+))?$/.test(hash)) {
|
||||
const [, a, b] = /^L(\d+)(?:-L(\d+))?$/.exec(hash);
|
||||
for (const n of [a, b].filter(Boolean)) if (!ids.get(t)?.has('L' + n)) bad.push(`${from}: missing line ${url}`);
|
||||
}
|
||||
}
|
||||
|
||||
const unique = [...new Set(bad)];
|
||||
console.log(`Checked ${links.length} links in ${pages.length} pages.`);
|
||||
if (unique.length) {
|
||||
console.log(unique.slice(0, 200).join('\n'));
|
||||
if (unique.length > 200) console.log(`… and ${unique.length - 200} more`);
|
||||
console.log(`${unique.length} broken links.`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('All links are valid.');
|
||||
181
docs/scripts/check-pages.mjs
Normal file
181
docs/scripts/check-pages.mjs
Normal file
@@ -0,0 +1,181 @@
|
||||
// Fast checks of the docs pages, without a build: frontmatter, MDX syntax, imports, links,
|
||||
// anchors of API and source pages, and <Snippet> ranges.
|
||||
// node scripts/check-pages.mjs all pages
|
||||
// node scripts/check-pages.mjs src/content/docs/concepts/states.mdx …
|
||||
// Exit code 1 if a page has an error. Run `npm run build` and `npm run check` for the full check.
|
||||
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { parse as parseYaml } from 'yaml';
|
||||
import { mdxToJs } from 'satteri';
|
||||
import GithubSlugger from 'github-slugger';
|
||||
import { getModel } from './api.mjs';
|
||||
import { extractSnippet } from './snippet.mjs';
|
||||
import { deviceOptions, readOptions } from './options.mjs';
|
||||
|
||||
const docsDir = path.resolve(new URL('..', import.meta.url).pathname);
|
||||
const repoRoot = path.resolve(docsDir, '..');
|
||||
const contentDir = path.join(docsDir, 'src/content/docs');
|
||||
|
||||
const walk = (dir, out = []) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const p = path.join(dir, name);
|
||||
if (statSync(p).isDirectory()) walk(p, out);
|
||||
else if (/\.mdx?$/.test(name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const allPages = walk(contentDir);
|
||||
const files = process.argv.slice(2).length ? process.argv.slice(2).map((f) => path.resolve(f)) : allPages;
|
||||
|
||||
const model = getModel({ xmlDir: path.join(docsDir, 'build/doxygen/xml'), repoRoot, base: '' });
|
||||
const api = new Map();
|
||||
const addAnchors = (url, recs) => {
|
||||
if (!api.has(url)) api.set(url, new Set());
|
||||
for (const x of recs) if (x?.anchor) api.get(url).add(x.anchor);
|
||||
};
|
||||
for (const t of model.types()) addAnchors(t.url, t.visible ?? []);
|
||||
for (const ns of model.namespaces()) addAnchors(ns.url, ns.visible ?? []);
|
||||
for (const { e } of model.namespaceEnums()) addAnchors(e.page, e.values ?? []);
|
||||
api.set('/api/', new Set());
|
||||
const sources = new Set(model.sourceFiles);
|
||||
const lineCount = (f) => readFileSync(path.join(repoRoot, f), 'utf8').replace(/\n$/, '').split('\n').length;
|
||||
|
||||
const pageUrl = (abs) => {
|
||||
const rel = path.relative(contentDir, abs).replace(/\.mdx?$/, '');
|
||||
return rel === 'index' ? '/' : '/' + rel.replace(/\/index$/, '') + '/';
|
||||
};
|
||||
const pages = new Map(allPages.map((p) => [pageUrl(p), p]));
|
||||
const slugCache = new Map();
|
||||
const slugsOf = (abs) => {
|
||||
if (slugCache.has(abs)) return slugCache.get(abs);
|
||||
const src = readFileSync(abs, 'utf8').replace(/```[\s\S]*?```/g, '');
|
||||
const slugger = new GithubSlugger();
|
||||
const set = new Set(['_top']);
|
||||
for (const m of src.matchAll(/^#{2,6}\s+(.+?)\s*$/gm)) set.add(slugger.slug(m[1].replace(/`/g, '').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')));
|
||||
for (const m of src.matchAll(/\sid="([^"]+)"/g)) set.add(m[1]);
|
||||
// Rows of <OptionsTable />: #<id>-<option>, id "opt" by default.
|
||||
for (const m of src.matchAll(/<OptionsTable\b([^>]*?)\/>/g)) {
|
||||
const attrs = m[1];
|
||||
const file = /\bfile="([^"]+)"/.exec(attrs)?.[1];
|
||||
const id = /\bid="([^"]+)"/.exec(attrs)?.[1] ?? 'opt';
|
||||
const groups = /\bgroups=\{\[([^\]]*)\]\}/.exec(attrs)?.[1].match(/'[^']*'|"[^"]*"/g)?.map((g) => g.slice(1, -1));
|
||||
let options = file ? readOptions(repoRoot, [{ file, source: path.basename(file), group: 'Options' }]) : deviceOptions(repoRoot);
|
||||
if (groups) options = options.filter((o) => groups.includes(o.group));
|
||||
for (const o of options) set.add(`${id}-${o.name}`);
|
||||
}
|
||||
slugCache.set(abs, set);
|
||||
return set;
|
||||
};
|
||||
|
||||
let errors = 0;
|
||||
let warnings = 0;
|
||||
const report = (file, line, msg, warn = false) => {
|
||||
if (warn) warnings++;
|
||||
else errors++;
|
||||
console.log(`${path.relative(docsDir, file)}:${line}: ${warn ? 'warning' : 'error'}: ${msg}`);
|
||||
};
|
||||
const lineOf = (src, index) => src.slice(0, index).split('\n').length;
|
||||
|
||||
function checkLink(file, src, index, url) {
|
||||
const line = lineOf(src, index);
|
||||
if (url.startsWith('/FairMQ/')) return report(file, line, `remove the base /FairMQ from the link ${url}`);
|
||||
const [p, hash] = url.split('#');
|
||||
if (!p.endsWith('/')) return report(file, line, `the link ${url} must end with a slash before the anchor`);
|
||||
if (p.startsWith('/api/')) {
|
||||
if (!api.has(p)) return report(file, line, `no API page ${p} (see node scripts/print-api.mjs)`);
|
||||
if (hash && !api.get(p).has(hash)) report(file, line, `no anchor #${hash} on ${p} (see node scripts/print-api.mjs <Name> --members)`);
|
||||
return;
|
||||
}
|
||||
if (p.startsWith('/source/')) {
|
||||
const f = p.slice('/source/'.length, -1);
|
||||
if (!f) return;
|
||||
if (!sources.has(f)) return report(file, line, `no source page for ${f}`);
|
||||
if (hash) {
|
||||
const m = /^L(\d+)(?:-L(\d+))?$/.exec(hash);
|
||||
if (!m) return report(file, line, `use #L<n> or #L<a>-L<b> on source pages, not #${hash}`);
|
||||
const n = lineCount(f);
|
||||
if (Number(m[2] ?? m[1]) > n) report(file, line, `${f} has only ${n} lines`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const target = pages.get(p);
|
||||
if (!target) return report(file, line, `no page ${p}`);
|
||||
if (hash && !slugsOf(target).has(hash)) report(file, line, `no heading #${hash} on ${p}`);
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
if (!existsSync(file)) {
|
||||
report(file, 0, 'file not found');
|
||||
continue;
|
||||
}
|
||||
const src = readFileSync(file, 'utf8');
|
||||
const fmMatch = /^---\n([\s\S]*?)\n---\n/.exec(src);
|
||||
if (!fmMatch) {
|
||||
report(file, 1, 'no frontmatter');
|
||||
continue;
|
||||
}
|
||||
let fm;
|
||||
try {
|
||||
fm = parseYaml(fmMatch[1]) ?? {};
|
||||
} catch (e) {
|
||||
report(file, 1, `frontmatter: ${e.message}`);
|
||||
continue;
|
||||
}
|
||||
if (!fm.title) report(file, 1, 'frontmatter: no title');
|
||||
if (!fm.description) report(file, 1, 'frontmatter: no description');
|
||||
for (const c of fm.code ?? []) if (!sources.has(c)) report(file, 1, `frontmatter code: ${c} is not a page of the source browser (fairmq/**/*.h or .cxx)`);
|
||||
for (const g of fm.guides ?? []) if (!g?.label || !g?.link) report(file, 1, 'frontmatter guides: each entry needs label and link');
|
||||
for (const g of fm.guides ?? []) if (g?.link) checkLink(file, src, 0, g.link);
|
||||
if (fm.hero?.actions) for (const a of fm.hero.actions) if (a.link?.startsWith('/FairMQ/')) checkLink(file, src, 0, a.link.slice('/FairMQ'.length));
|
||||
|
||||
const fmLines = fmMatch[0].split('\n').length - 1;
|
||||
const body = src.slice(fmMatch[0].length);
|
||||
if (file.endsWith('.mdx')) {
|
||||
try {
|
||||
await mdxToJs(body);
|
||||
} catch (e) {
|
||||
const m = /^(\d+):(\d+)/.exec(e.message);
|
||||
report(file, m ? Number(m[1]) + fmLines : fmLines, `MDX: ${e.message}`);
|
||||
}
|
||||
}
|
||||
for (const m of src.matchAll(/^import\s+[\s\S]*?\s+from\s+['"]([^'"]+)['"]/gm)) {
|
||||
const spec = m[1];
|
||||
if (spec.startsWith('.') && !existsSync(path.resolve(path.dirname(file), spec))) report(file, lineOf(src, m.index), `import not found: ${spec}`);
|
||||
}
|
||||
const noCode = src.replace(/```[\s\S]*?```/g, (s) => s.replace(/[^\n]/g, ' ')).replace(/`[^`\n]*`/g, (s) => ' '.repeat(s.length));
|
||||
if (file.endsWith('.mdx')) {
|
||||
// MDX fails at render time for a component without an import.
|
||||
const imported = new Set();
|
||||
for (const m of src.matchAll(/^import\s+([\s\S]*?)\s+from\s+['"][^'"]+['"]/gm)) {
|
||||
for (const n of m[1].matchAll(/[A-Za-z_$][\w$]*/g)) imported.add(n[0]);
|
||||
}
|
||||
const missing = new Set();
|
||||
for (const m of noCode.matchAll(/<([A-Z][\w$]*)[\s/>]/g)) {
|
||||
if (!imported.has(m[1]) && !missing.has(m[1])) {
|
||||
missing.add(m[1]);
|
||||
report(file, lineOf(src, m.index), `component <${m[1]}> has no import`);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const m of noCode.matchAll(/\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g)) {
|
||||
const url = m[1];
|
||||
if (/^(https?:|mailto:|#)/.test(url)) continue;
|
||||
if (!url.startsWith('/')) report(file, lineOf(src, m.index), `use a root-relative link like /concepts/states/, not ${url}`);
|
||||
else checkLink(file, src, m.index, url);
|
||||
}
|
||||
for (const m of noCode.matchAll(/\shref=["'](\/[^"']*)["']/g)) checkLink(file, src, m.index, m[1]);
|
||||
for (const m of src.matchAll(/<Snippet\b([\s\S]*?)\/>/g)) {
|
||||
const attrs = Object.fromEntries([...m[1].matchAll(/(\w+)=(?:"([^"]*)"|'([^']*)')/g)].map((a) => [a[1], a[2] ?? a[3]]));
|
||||
if (/\{/.test(m[1].replace(/(\w+)=(?:"[^"]*"|'[^']*')/g, ''))) continue; // props with expressions: checked by the build
|
||||
try {
|
||||
extractSnippet(repoRoot, attrs);
|
||||
} catch (e) {
|
||||
report(file, lineOf(src, m.index), e.message);
|
||||
}
|
||||
}
|
||||
for (const m of noCode.matchAll(/\b(simply|just|easily|obviously|basically|very|really|please)\b/gi))
|
||||
report(file, lineOf(src, m.index), `style: avoid "${m[1]}"`, true);
|
||||
if (/This page is a stub\./.test(src)) report(file, 1, 'the page is still a stub', true);
|
||||
}
|
||||
console.log(`${files.length} pages: ${errors} errors, ${warnings} warnings.`);
|
||||
process.exit(errors ? 1 : 0);
|
||||
77
docs/scripts/integration.mjs
Normal file
77
docs/scripts/integration.mjs
Normal file
@@ -0,0 +1,77 @@
|
||||
// Astro integration that prepares the data for the generated pages.
|
||||
//
|
||||
// 1. It runs Doxygen when the XML is missing or older than a file in fairmq/.
|
||||
// 2. It gives the pages a virtual module `virtual:fairmq/data` with the build
|
||||
// info (version, commit) and the absolute paths of the repository.
|
||||
import { existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { buildInfo } from './build-info.mjs';
|
||||
|
||||
const VIRTUAL_ID = 'virtual:fairmq/data';
|
||||
const RESOLVED_ID = '\0' + VIRTUAL_ID;
|
||||
|
||||
function newestMtime(dir) {
|
||||
let newest = 0;
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) newest = Math.max(newest, newestMtime(p));
|
||||
else if (/\.(h|cxx)$/.test(entry.name)) newest = Math.max(newest, statSync(p).mtimeMs);
|
||||
}
|
||||
return newest;
|
||||
}
|
||||
|
||||
function runDoxygen({ docsDir, repoRoot, xmlDir, logger }) {
|
||||
const index = path.join(xmlDir, 'index.xml');
|
||||
const sources = path.join(repoRoot, 'fairmq');
|
||||
if (existsSync(index) && statSync(index).mtimeMs > newestMtime(sources)) {
|
||||
logger.info('Doxygen XML is up to date');
|
||||
return;
|
||||
}
|
||||
mkdirSync(path.join(docsDir, 'build', 'doxygen'), { recursive: true });
|
||||
const start = Date.now();
|
||||
try {
|
||||
execFileSync('doxygen', ['Doxyfile'], { cwd: docsDir, stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
throw new Error('Doxygen is not installed. Install it (for example `apt install doxygen`) and build again.');
|
||||
}
|
||||
throw new Error(`Doxygen failed: ${err.stderr?.toString() ?? err.message}`);
|
||||
}
|
||||
logger.info(`Doxygen XML written in ${((Date.now() - start) / 1000).toFixed(1)} s`);
|
||||
}
|
||||
|
||||
export default function fairmqData() {
|
||||
return {
|
||||
name: 'fairmq-data',
|
||||
hooks: {
|
||||
'astro:config:setup': ({ config, updateConfig, logger }) => {
|
||||
const docsDir = fileURLToPath(config.root);
|
||||
const repoRoot = path.resolve(docsDir, '..');
|
||||
const xmlDir = path.join(docsDir, 'build', 'doxygen', 'xml');
|
||||
runDoxygen({ docsDir, repoRoot, xmlDir, logger });
|
||||
const info = buildInfo(repoRoot);
|
||||
logger.info(`Building docs for ${info.label} (${info.branch} @ ${info.commitShort})`);
|
||||
const source =
|
||||
`export const build = ${JSON.stringify(info)};\n` +
|
||||
`export const paths = ${JSON.stringify({ docsDir, repoRoot, xmlDir })};\n`;
|
||||
updateConfig({
|
||||
vite: {
|
||||
plugins: [
|
||||
{
|
||||
name: 'fairmq-data',
|
||||
resolveId(id) {
|
||||
if (id === VIRTUAL_ID) return RESOLVED_ID;
|
||||
},
|
||||
load(id) {
|
||||
if (id === RESOLVED_ID) return source;
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
24
docs/scripts/nowrap-code.mjs
Normal file
24
docs/scripts/nowrap-code.mjs
Normal file
@@ -0,0 +1,24 @@
|
||||
// Sätteri hast plugin: marks short inline code with the class `nw`, so that the browser does not
|
||||
// break it at a hyphen. A line break in `--print-options` or `fair::mq::Device` misleads the reader.
|
||||
// Long inline code can still wrap, so that it fits on a phone.
|
||||
|
||||
const MAX = 32;
|
||||
|
||||
const textOf = (node) =>
|
||||
(node.children ?? []).map((c) => (c.type === 'text' ? c.value : textOf(c))).join('');
|
||||
|
||||
export default function nowrapCode() {
|
||||
return {
|
||||
name: 'fairmq-nowrap-code',
|
||||
element: {
|
||||
filter: ['code'],
|
||||
visit(node, ctx) {
|
||||
if (ctx.parent?.(node)?.tagName === 'pre') return;
|
||||
const cls = node.properties?.className ?? [];
|
||||
if ([].concat(cls).some((c) => String(c).startsWith('language-'))) return;
|
||||
if (textOf(node).length > MAX) return;
|
||||
ctx.setProperty(node, 'className', [...[].concat(cls), 'nw']);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
159
docs/scripts/options.mjs
Normal file
159
docs/scripts/options.mjs
Normal file
@@ -0,0 +1,159 @@
|
||||
// Reads the command-line options of FairMQ from the C++ sources:
|
||||
// the `add_options()` chains of boost::program_options.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** Splits `s` at top-level commas (outside parentheses, brackets and strings). */
|
||||
function splitTop(s) {
|
||||
const out = [];
|
||||
let depth = 0;
|
||||
let cur = '';
|
||||
let str = false;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i];
|
||||
if (str) {
|
||||
cur += c;
|
||||
if (c === '\\') cur += s[++i];
|
||||
else if (c === '"') str = false;
|
||||
continue;
|
||||
}
|
||||
if (c === '"') {
|
||||
str = true;
|
||||
cur += c;
|
||||
continue;
|
||||
}
|
||||
if (c === '(' || c === '[' || c === '{') depth++;
|
||||
if (c === ')' || c === ']' || c === '}') depth--;
|
||||
if (c === ',' && depth === 0) {
|
||||
out.push(cur.trim());
|
||||
cur = '';
|
||||
} else cur += c;
|
||||
}
|
||||
if (cur.trim()) out.push(cur.trim());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Concatenates adjacent C++ string literals: "a" "b" -> ab. */
|
||||
function cString(s) {
|
||||
const parts = [...s.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) =>
|
||||
m[1].replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\t/g, '\t').replace(/\\\\/g, '\\'),
|
||||
);
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/** The groups `("...", ...)` of an add_options() chain that starts at `start`. */
|
||||
function groupsAfter(text, start) {
|
||||
const groups = [];
|
||||
let i = text.indexOf('add_options()', start) + 'add_options()'.length;
|
||||
for (;;) {
|
||||
while (i < text.length && /\s/.test(text[i])) i++;
|
||||
if (text[i] !== '(') break;
|
||||
let depth = 0;
|
||||
let str = false;
|
||||
let j = i;
|
||||
for (; j < text.length; j++) {
|
||||
const c = text[j];
|
||||
if (str) {
|
||||
if (c === '\\') j++;
|
||||
else if (c === '"') str = false;
|
||||
continue;
|
||||
}
|
||||
if (c === '"') str = true;
|
||||
else if (c === '/' && text[j + 1] === '/') {
|
||||
j = text.indexOf('\n', j);
|
||||
continue;
|
||||
} else if (c === '(') depth++;
|
||||
else if (c === ')') {
|
||||
depth--;
|
||||
if (depth === 0) break;
|
||||
}
|
||||
}
|
||||
groups.push({ text: text.slice(i + 1, j), line: text.slice(0, i).split('\n').length });
|
||||
i = j + 1;
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function parseValue(spec) {
|
||||
const out = { type: '', default: undefined, implicit: undefined, multitoken: false, composing: false, required: false, switch: false };
|
||||
const t = /po::value\s*<\s*(.+?)\s*>\s*\(/.exec(spec) ?? /value\s*<\s*(.+?)\s*>\s*\(/.exec(spec);
|
||||
if (t) out.type = t[1].replace(/\s+/g, ' ').replace(/^std::/, '');
|
||||
if (/po::bool_switch|bool_switch\(/.test(spec)) {
|
||||
out.type = 'bool';
|
||||
out.switch = true;
|
||||
}
|
||||
const d = /->\s*default_value\((.*?)\)(?=\s*(->|$))/s.exec(spec);
|
||||
if (d) out.default = d[1].trim();
|
||||
const im = /->\s*implicit_value\((.*?)\)(?=\s*(->|$))/s.exec(spec);
|
||||
if (im) out.implicit = im[1].trim();
|
||||
out.multitoken = /->\s*multitoken\(\)/.test(spec);
|
||||
out.composing = /->\s*composing\(\)/.test(spec);
|
||||
out.required = /->\s*required\(\)/.test(spec);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Makes a C++ default value readable: "2ULL << 30" -> "2147483648", "\"zeromq\"" -> "zeromq". */
|
||||
export function displayValue(v) {
|
||||
if (v === undefined) return undefined;
|
||||
let s = v.trim();
|
||||
const shift = /^(\d+)U?L*L*\s*<<\s*(\d+)$/.exec(s);
|
||||
if (shift) return String(BigInt(shift[1]) << BigInt(shift[2]));
|
||||
if (/^".*"$/.test(s)) return cString(s);
|
||||
if (/^-?\d+\.$/.test(s)) return s.slice(0, -1);
|
||||
if (/^-?\d+\.0+$/.test(s)) return s.replace(/\.0+$/, '');
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Reads the option chains of the given files. `files` maps a path to a group label. */
|
||||
export function readOptions(repoRoot, files) {
|
||||
const options = [];
|
||||
for (const { file, group, source } of files) {
|
||||
const text = readFileSync(path.join(repoRoot, file), 'utf8');
|
||||
let at = 0;
|
||||
while ((at = text.indexOf('add_options()', at)) >= 0) {
|
||||
for (const g of groupsAfter(text, at)) {
|
||||
const parts = splitTop(g.text);
|
||||
const names = cString(parts[0]);
|
||||
const [long, short] = names.split(',');
|
||||
const rest = parts.slice(1);
|
||||
let spec = '';
|
||||
let desc = '';
|
||||
if (rest.length === 1) desc = cString(rest[0]);
|
||||
else if (rest.length >= 2) {
|
||||
spec = rest[0];
|
||||
desc = cString(rest.slice(1).join(','));
|
||||
}
|
||||
const value = spec ? parseValue(spec) : { type: '', switch: true };
|
||||
const grp = typeof group === 'function' ? group(long) : group;
|
||||
options.push({
|
||||
name: long,
|
||||
short: short || '',
|
||||
type: value.type,
|
||||
default: displayValue(value.default),
|
||||
implicit: displayValue(value.implicit),
|
||||
multitoken: !!value.multitoken,
|
||||
composing: !!value.composing,
|
||||
flag: !spec,
|
||||
description: desc.trim(),
|
||||
group: grp,
|
||||
source,
|
||||
file,
|
||||
line: g.line,
|
||||
});
|
||||
}
|
||||
at += 'add_options()'.length;
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/** The options that every device made with runDevice.h has. */
|
||||
export function deviceOptions(repoRoot) {
|
||||
const logging = new Set(['severity', 'file-severity', 'verbosity', 'color', 'log-to-file']);
|
||||
return readOptions(repoRoot, [
|
||||
{ file: 'fairmq/ProgOptions.cxx', source: 'ProgOptions', group: (n) => (logging.has(n) ? 'Logging' : 'General') },
|
||||
{ file: 'fairmq/plugins/config/Config.cxx', source: 'config plugin', group: (n) => (/^(shm|bad-alloc|shmid)/.test(n) ? 'Shared memory' : 'Device') },
|
||||
{ file: 'fairmq/plugins/control/Control.cxx', source: 'control plugin', group: 'Control' },
|
||||
{ file: 'fairmq/PluginManager.cxx', source: 'PluginManager', group: 'Plugins' },
|
||||
]);
|
||||
}
|
||||
40
docs/scripts/print-api.mjs
Normal file
40
docs/scripts/print-api.mjs
Normal file
@@ -0,0 +1,40 @@
|
||||
// Prints the API pages and their member anchors, for links from the docs pages.
|
||||
// node scripts/print-api.mjs all types, namespaces and enums
|
||||
// node scripts/print-api.mjs Channel only names that contain "Channel"
|
||||
// node scripts/print-api.mjs Device --members with the member anchors
|
||||
// Links in pages leave out the base: /api/fair/mq/Device/#ConditionalRun
|
||||
import path from 'node:path';
|
||||
import { getModel } from './api.mjs';
|
||||
|
||||
const docsDir = path.resolve(new URL('..', import.meta.url).pathname);
|
||||
const m = getModel({ xmlDir: path.join(docsDir, 'build/doxygen/xml'), repoRoot: path.resolve(docsDir, '..'), base: '' });
|
||||
const args = process.argv.slice(2);
|
||||
const members = args.includes('--members');
|
||||
const filter = args.find((a) => !a.startsWith('--'));
|
||||
const show = (name) => !filter || name.includes(filter);
|
||||
|
||||
const out = [];
|
||||
const list = (rec) => {
|
||||
const seen = new Set();
|
||||
for (const x of rec.visible ?? []) {
|
||||
if (!x.anchor || seen.has(x.anchor)) continue;
|
||||
seen.add(x.anchor);
|
||||
out.push(` #${x.anchor} ${x.prot !== 'public' ? `(${x.prot}) ` : ''}${x.sigText.replace(/\s+/g, ' ')}`);
|
||||
}
|
||||
};
|
||||
for (const ns of m.namespaces()) {
|
||||
if (!show(ns.name)) continue;
|
||||
out.push(`namespace ${ns.name} ${ns.url}`);
|
||||
if (members) list(ns);
|
||||
}
|
||||
for (const t of m.types()) {
|
||||
if (!show(t.name)) continue;
|
||||
out.push(`${t.kind} ${t.name} ${t.url} (${t.file}:${t.line})`);
|
||||
if (members) list(t);
|
||||
}
|
||||
for (const { e } of m.namespaceEnums()) {
|
||||
if (!show(e.qualified)) continue;
|
||||
out.push(`enum ${e.qualified} ${e.page}`);
|
||||
if (members) for (const v of e.values) out.push(` #${v.anchor} ${v.name}${v.init ? ' ' + v.init : ''}`);
|
||||
}
|
||||
console.log(out.join('\n'));
|
||||
82
docs/scripts/snippet.mjs
Normal file
82
docs/scripts/snippet.mjs
Normal file
@@ -0,0 +1,82 @@
|
||||
// Takes lines out of a file of the repository for the Snippet component and the page check.
|
||||
// The options select a region, a line range, or a start line (and an end line). See Snippet.astro.
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** Returns { code, first, last } or throws an Error that names the problem. */
|
||||
export function extractSnippet(repoRoot, { file, region, lines, start, end }) {
|
||||
const abs = path.join(repoRoot, file);
|
||||
if (!existsSync(abs)) throw new Error(`Snippet: file not found: ${file}`);
|
||||
const all = readFileSync(abs, 'utf8').replace(/\r\n/g, '\n').split('\n');
|
||||
let first = 1;
|
||||
let body;
|
||||
if (region) {
|
||||
const marker = new RegExp(`^\\s*(//!|#!|//) \\[${region.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\]\\s*$`);
|
||||
const idx = all.flatMap((l, i) => (marker.test(l) ? [i] : []));
|
||||
if (idx.length < 2) throw new Error(`Snippet: region "${region}" not found twice in ${file}`);
|
||||
body = all.slice(idx[0] + 1, idx[1]);
|
||||
first = idx[0] + 2;
|
||||
} else if (start) {
|
||||
const matcher = (pat) => {
|
||||
const re = /^\/(.+)\/$/.exec(pat);
|
||||
if (re) {
|
||||
const rx = new RegExp(re[1]);
|
||||
return (l) => rx.test(l);
|
||||
}
|
||||
return (l) => l.includes(pat);
|
||||
};
|
||||
const isStart = matcher(start);
|
||||
const a = all.findIndex(isStart);
|
||||
if (a < 0) throw new Error(`Snippet: no line with "${start}" in ${file}`);
|
||||
let b = -1;
|
||||
if (end) {
|
||||
const isEnd = end.startsWith('^') ? (l) => new RegExp(end).test(l) : matcher(end);
|
||||
b = all.findIndex((l, i) => i > a && isEnd(l));
|
||||
if (b < 0) throw new Error(`Snippet: no line with "${end}" after "${start}" in ${file}`);
|
||||
} else {
|
||||
// Up to the line that closes the first brace at or after the start line.
|
||||
let depth = 0;
|
||||
let open = false;
|
||||
for (let i = a; i < all.length && b < 0; i++) {
|
||||
const code = all[i].replace(/\/\/.*$/, '').replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '');
|
||||
for (const c of code) {
|
||||
if (c === '{') {
|
||||
depth++;
|
||||
open = true;
|
||||
} else if (c === '}') depth--;
|
||||
}
|
||||
if (open && depth <= 0) b = i;
|
||||
}
|
||||
if (b < 0) throw new Error(`Snippet: no closing brace after "${start}" in ${file}`);
|
||||
}
|
||||
body = all.slice(a, b + 1);
|
||||
first = a + 1;
|
||||
} else if (lines) {
|
||||
const m = /^(\d+)-(\d+)$/.exec(lines);
|
||||
if (!m) throw new Error(`Snippet: bad lines "${lines}" for ${file}`);
|
||||
const a = Number(m[1]);
|
||||
const b = Number(m[2]);
|
||||
if (b > all.length || a < 1 || a > b) throw new Error(`Snippet: lines ${lines} out of range for ${file} (${all.length} lines)`);
|
||||
body = all.slice(a - 1, b);
|
||||
first = a;
|
||||
} else {
|
||||
// Drop the license block at the top and the blank lines after it.
|
||||
let i = 0;
|
||||
if (/^\s*\/\*{5,}/.test(all[0] ?? '')) {
|
||||
while (i < all.length && !/\*\/\s*$/.test(all[i])) i++;
|
||||
i++;
|
||||
} else {
|
||||
while (i < all.length && /^\s*#/.test(all[i]) && /copyright|license|\*{5,}|^#\s*$/i.test(all[i])) i++;
|
||||
}
|
||||
while (i < all.length && all[i].trim() === '') i++;
|
||||
body = all.slice(i);
|
||||
first = i + 1;
|
||||
}
|
||||
// Remove nested markers and the common indentation.
|
||||
body = body.filter((l) => !/^\s*(\/\/!|#!) \[[\w-]+\]\s*$/.test(l));
|
||||
while (body.length && body[body.length - 1].trim() === '') body.pop();
|
||||
const indent = Math.min(...body.filter((l) => l.trim()).map((l) => (l.match(/^ */) ?? [''])[0].length));
|
||||
if (Number.isFinite(indent) && indent > 0) body = body.map((l) => l.slice(indent));
|
||||
|
||||
return { code: body.join('\n'), first, last: first + body.length - 1 };
|
||||
}
|
||||
163
docs/scripts/source.mjs
Normal file
163
docs/scripts/source.mjs
Normal file
@@ -0,0 +1,163 @@
|
||||
// Renders a file of fairmq/ for the source browser: Shiki colours, line anchors,
|
||||
// and links on the symbols that Doxygen found in the file.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHighlighter } from 'shiki';
|
||||
import { kids, tagOf, isText, attr, children, child, textOf, escapeHtml } from './xml.mjs';
|
||||
|
||||
// The colours of src/styles/code-theme.json, as classes. Unknown colours stay inline.
|
||||
const COLOR_CLASS = {
|
||||
'#8d96a5': 't-c',
|
||||
'#fabe5d': 't-k',
|
||||
'#8cc8ef': 't-t',
|
||||
'#ffffff': 't-f',
|
||||
'#a8d99b': 't-s',
|
||||
'#f4a597': 't-n',
|
||||
'#e5b3d3': 't-p',
|
||||
'#c3c8d1': 't-o',
|
||||
'#e6e8ec': '',
|
||||
};
|
||||
|
||||
let highlighter;
|
||||
async function getHighlighter(theme) {
|
||||
highlighter ??= createHighlighter({ themes: [theme], langs: ['cpp'] });
|
||||
return highlighter;
|
||||
}
|
||||
|
||||
/** Doxygen references per line: [{ start, end, refid, text }]. */
|
||||
function refsByLine(fileRec) {
|
||||
const map = new Map();
|
||||
if (!fileRec) return map;
|
||||
const listing = child(fileRec.node, 'programlisting');
|
||||
for (const cl of children(listing, 'codeline')) {
|
||||
const n = Number(attr(cl, 'lineno'));
|
||||
let pos = 0;
|
||||
const refs = [];
|
||||
const walk = (node) => {
|
||||
for (const k of kids(node)) {
|
||||
if (isText(k)) pos += String(k['#text']).length;
|
||||
else if (tagOf(k) === 'sp') pos += 1;
|
||||
else if (tagOf(k) === 'ref') {
|
||||
const text = textOf(k);
|
||||
refs.push({ start: pos, end: pos + text.length, refid: attr(k, 'refid'), text });
|
||||
pos += text.length;
|
||||
} else walk(k);
|
||||
}
|
||||
};
|
||||
walk(cl);
|
||||
if (refs.length) map.set(n, refs);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function classFor(token) {
|
||||
const color = (token.color ?? '').toLowerCase();
|
||||
const cls = COLOR_CLASS[color];
|
||||
if (cls !== undefined) return { cls, style: '' };
|
||||
return { cls: '', style: color ? `color:${color}` : '' };
|
||||
}
|
||||
|
||||
function span(seg) {
|
||||
const text = escapeHtml(seg.text);
|
||||
if (seg.cls) return `<span class="${seg.cls}">${text}</span>`;
|
||||
if (seg.style) return `<span style="${seg.style}">${text}</span>`;
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders one file. Returns the rows as HTML, the number of lines, and the symbol
|
||||
* table for the hover cards: [{ k: kind, n: name, s: signature, l: location, h: href }].
|
||||
*/
|
||||
export async function renderSourceFile(model, filePath, { theme, repoRoot }) {
|
||||
const raw = readFileSync(path.join(repoRoot, filePath), 'utf8');
|
||||
const code = raw.replace(/\n$/, '');
|
||||
const lines = code.split('\n');
|
||||
const hl = await getHighlighter(theme);
|
||||
const tokenLines = hl.codeToTokensBase(code, { lang: 'cpp', theme: theme.name });
|
||||
const refs = refsByLine(model.files.get(filePath));
|
||||
|
||||
const symbols = [];
|
||||
const symbolIndex = new Map();
|
||||
const symbolFor = (refid) => {
|
||||
if (symbolIndex.has(refid)) return symbolIndex.get(refid);
|
||||
const t = model.targets.get(refid);
|
||||
if (!t) return -1;
|
||||
const i = symbols.length;
|
||||
symbols.push({ k: t.kind, n: t.name, s: t.sig, l: t.loc, h: t.href });
|
||||
symbolIndex.set(refid, i);
|
||||
return i;
|
||||
};
|
||||
|
||||
const rows = tokenLines.map((tokens, i) => {
|
||||
const n = i + 1;
|
||||
const lineText = lines[i] ?? '';
|
||||
// Keep the references whose text is at the same place in the file. Search close by
|
||||
// when Doxygen counted a character differently.
|
||||
const lineRefs = [];
|
||||
let last = 0;
|
||||
for (const r of refs.get(n) ?? []) {
|
||||
let start = lineText.slice(r.start, r.end) === r.text ? r.start : lineText.indexOf(r.text, Math.max(last, r.start - 8));
|
||||
if (start < last || start < 0) continue;
|
||||
if (symbolFor(r.refid) < 0) continue;
|
||||
lineRefs.push({ start, end: start + r.text.length, refid: r.refid });
|
||||
last = start + r.text.length;
|
||||
}
|
||||
|
||||
// Split the tokens at the borders of the references.
|
||||
const segs = [];
|
||||
let pos = 0;
|
||||
for (const tok of tokens) {
|
||||
const { cls, style } = classFor(tok);
|
||||
const text = tok.content;
|
||||
const end = pos + text.length;
|
||||
const cuts = [];
|
||||
for (const r of lineRefs) {
|
||||
if (r.start > pos && r.start < end) cuts.push(r.start);
|
||||
if (r.end > pos && r.end < end) cuts.push(r.end);
|
||||
}
|
||||
cuts.sort((a, b) => a - b);
|
||||
let s0 = pos;
|
||||
for (const c of [...cuts, end]) {
|
||||
if (c > s0) segs.push({ start: s0, end: c, text: text.slice(s0 - pos, c - pos), cls, style });
|
||||
s0 = c;
|
||||
}
|
||||
pos = end;
|
||||
}
|
||||
|
||||
// Emit, with an <a> around each reference and merged spans of the same colour.
|
||||
let html = '';
|
||||
let ri = 0;
|
||||
let open = null;
|
||||
let buf = null;
|
||||
const flush = () => {
|
||||
if (buf) html += span(buf);
|
||||
buf = null;
|
||||
};
|
||||
for (const seg of segs) {
|
||||
if (!open && ri < lineRefs.length && seg.start === lineRefs[ri].start) {
|
||||
flush();
|
||||
open = lineRefs[ri];
|
||||
const s = symbolFor(open.refid);
|
||||
html += `<a class="sym" href="${escapeHtml(symbols[s].h)}" data-s="${s}">`;
|
||||
}
|
||||
if (buf && buf.cls === seg.cls && buf.style === seg.style) {
|
||||
buf.text += seg.text;
|
||||
buf.end = seg.end;
|
||||
} else {
|
||||
flush();
|
||||
buf = { ...seg };
|
||||
}
|
||||
if (open && seg.end === open.end) {
|
||||
flush();
|
||||
html += '</a>';
|
||||
open = null;
|
||||
ri++;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
if (open) html += '</a>';
|
||||
return `<span class="row" id="L${n}"><a class="ln" href="#L${n}" aria-label="Line ${n}">${n}</a><span class="lc">${html || ' '}</span></span>`;
|
||||
});
|
||||
|
||||
return { html: rows.join(''), lines: lines.length, symbols };
|
||||
}
|
||||
68
docs/scripts/xml.mjs
Normal file
68
docs/scripts/xml.mjs
Normal file
@@ -0,0 +1,68 @@
|
||||
// Small helpers around fast-xml-parser in `preserveOrder` mode.
|
||||
// A node is either { '#text': string } or { tag: [children], ':@': { attributes } }.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { XMLParser } from 'fast-xml-parser';
|
||||
|
||||
const parser = new XMLParser({
|
||||
preserveOrder: true,
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '',
|
||||
trimValues: false,
|
||||
parseTagValue: false,
|
||||
parseAttributeValue: false,
|
||||
processEntities: true,
|
||||
htmlEntities: true,
|
||||
});
|
||||
|
||||
export function parseXmlFile(file) {
|
||||
return parser.parse(readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
export function tagOf(node) {
|
||||
for (const k of Object.keys(node)) if (k !== ':@') return k;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function isText(node) {
|
||||
return Object.prototype.hasOwnProperty.call(node, '#text');
|
||||
}
|
||||
|
||||
export function kids(node) {
|
||||
if (!node) return [];
|
||||
const t = tagOf(node);
|
||||
return t && t !== '#text' && Array.isArray(node[t]) ? node[t] : [];
|
||||
}
|
||||
|
||||
export function attr(node, name) {
|
||||
return node && node[':@'] ? node[':@'][name] : undefined;
|
||||
}
|
||||
|
||||
export function children(node, name) {
|
||||
return kids(node).filter((n) => tagOf(n) === name);
|
||||
}
|
||||
|
||||
export function child(node, name) {
|
||||
return kids(node).find((n) => tagOf(n) === name);
|
||||
}
|
||||
|
||||
export function find(nodes, name) {
|
||||
for (const n of nodes) if (tagOf(n) === name) return n;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Plain text of a node, with Doxygen's <sp/> as spaces. */
|
||||
export function textOf(node) {
|
||||
if (!node) return '';
|
||||
if (isText(node)) return String(node['#text']);
|
||||
const t = tagOf(node);
|
||||
if (t === 'sp') return ' ';
|
||||
return kids(node).map(textOf).join('');
|
||||
}
|
||||
|
||||
export function escapeHtml(s) {
|
||||
return String(s)
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"');
|
||||
}
|
||||
Reference in New Issue
Block a user