# 评审请求:一份 C++ 注释规范 + 一个真实用例 请只回答文末的三个问题,不必复述规范。你看...
تم الإنشاء في: ١٥ نوفمبر ٢٠٢٦
تمت الإجابة باستخدام GPT-6 Thinking بواسطة Chat01
تم الإنشاء في: ١٥ نوفمبر ٢٠٢٦
تمت الإجابة باستخدام GPT-6 Thinking بواسطة Chat01
请只回答文末的三个问题,不必复述规范。你看到的代码是真实工程代码(MLIR 方言 pass),不是玩具例子。
markdown### Comment Styles Contract at the boundary, bearings inside the body. 1. **Doxygen = contract and edge, skipping what types and names prove**: ownership, lifetime, and the non-obvious non-guarantees ("does not validate `id`; caller passes a live op"). One clause per line (<= 15 words); `key -> value` for maps; for a non-obvious function give its `Effect`, one Pre/Post line, a hazard table. 2. **Inside a function, write bearings, not narration**: one invariant per block -- the non-obvious order, what an opaque step computes, or why a guard exists -- wrapped at the column limit. Leave out what the code beside it already says. 3. **Extract, or keep the invariant**: a block that needs a table or a paragraph is an unnamed concept, so extract it -- unless it mutates surrounding state, fixes an order, or scopes RAII/outer control flow. Then keep it as the invariant it is. 4. **Form follows information**: disjoint cases become one ASCII table, tagged once at the data structure; a derivation becomes one line of logical symbols (`prod(s) && !isLast(s) => [Relay]`). 5. **A symbol carries content, never grammar**: allowed only as a case map (`A -> B`), as a relation the code spreads over two sites or states over a set, or as a quoted identifier. Strip the symbols and re-read: a rule that stops parsing was written as a telegram and needs a verb. Invented predicates stay positive (`isLast(s)`, never `notLast(s)`), never `A1`/`P1`; program identifiers follow the file's convention. 6. **A comment is plain text**: `\p x` and `@param` are the file's own conventions; `**bold**`, `*em*` and bullet nesting are markdown that will not render, so a rule about comments demonstrates in the same plain form it asks for. 7. **Fix a stale comment on sight**: when code and comment disagree, decide which invariant was intended and fix the other one.
被规范管的读者是:日后维护这段 pass 的工程师,以及只拿到 diff + 这份规范的机器审查者。
CodeGenerator::collectCounterAnchors()相关头文件声明(同一个类):
cpp// Counter anchor of a multi-buffer id set, collected from the final flag // positions (see collectCounterAnchors). An id set whose flags land in // several blocks is marked mixed and keeps the loop counter. struct IdAnchor { Block *landingBlock = nullptr; bool mixed = false; }; llvm::DenseMap<LoopLikeOpInterface, std::map<llvm::SmallVector<int64_t>, IdAnchor>> multiBufferIdAnchors; /// Block the flag of \p opBase lands in (see the definition for the mirrored /// placement rules); null when it cannot be known yet. Block *getFlagLandingBlock(OperationBase *opBase); /// Anchor op of \p eventIds of \p multibufferLoop, or null when the set keeps /// the loop counter (no collector entry, or flags in several blocks). Operation *getMultiBufferIdAnchor(LoopLikeOpInterface multibufferLoop, llvm::ArrayRef<int64_t> eventIds);
函数实现(SyncSolverCodeGen.cpp:434-476,行号保持原样):
cppvoid CodeGenerator::collectCounterAnchors() { auto record = [&](OperationBase *opBase, SyncOp *syncOp) { auto *setWaitOp = dyn_cast<SetWaitOp>(syncOp); if (!setWaitOp || setWaitOp->eventIds.size() < 2) return; // Preload pairs key on their cv-pipelining loop and per-end offset, so // they never match an id set collected from the multi-buffer scope: those // keep the loop counter. if (!setWaitOp->eventIdInfo.multiBufferInfo) return; auto *multibufferScope = dyn_cast<Loop>( setWaitOp->eventIdInfo.multiBufferInfo->multibufferScope); if (!multibufferScope || !opBase) return; auto multibufferLoop = dyn_cast<LoopLikeOpInterface>(multibufferScope->op); if (!multibufferLoop) return; // The flag lands where setProperInsertionPoint puts it, which for a branch // scope is the if/else *block* rather than the anchor op's own block. Block *landingBlock = getFlagLandingBlock(opBase); IdAnchor &entry = multiBufferIdAnchors[multibufferLoop][setWaitOp->eventIds]; if (entry.mixed) return; // An unknowable landing spot disqualifies the id set as surely as a // diverging one: the other end may sit in the loop body, and one handshake // split over two counters hands out ids its peer never waits for. Both // cases keep the loop counter for every end. if (!landingBlock || (entry.landingBlock && entry.landingBlock != landingBlock)) { entry.landingBlock = nullptr; entry.mixed = true; return; } entry.landingBlock = landingBlock; }; for (auto &[opBase, syncOps] : syncMapBefore) for (auto &syncOp : syncOps) record(opBase, syncOp.get()); for (auto &[opBase, syncOps] : syncMapAfter) for (auto &syncOp : syncOps) record(opBase, syncOp.get()); }
争议注释是 // An unknowable landing spot … 那四行(第 458-461 行)。
候选改写 A(两行,纯文本,去掉头文件已说过的"退回 loop counter"):
cpp// Peer may sit in the loop body: one handshake over two counters hands out // ids the other end never waits for -- as bad as a diverging landing spot.
候选改写 B(一行推论式):
cpp// !landingBlock || (entry.landingBlock && entry.landingBlock != landingBlock) // => mixed: the peer may sit in the loop body
// An unknowable landing spot … 那四行里,哪些信息是代码(含头文件、上下两处注释)已经说过的,哪些是只有注释能说的?代码和头文件已经表达的:
!landingBlock 和已记录 block 不同,都会导致 entry.mixed = true。getFlagLandingBlock() 返回 null 表示落点暂时不可确定。mixed 的 id set 保留 loop counter,不使用收集的 anchor。只有争议注释提供的:
其中最有价值的是第二点:跨 counter 为什么会出错。
另外,头文件的 mixed 说明并不完整:未知落点也会使 mixed = true,不只是多个不同 block。按第 7 条,后续应修正这个遗漏。
三者原样选择,我选原文;但更推荐改成两行。
A 比原文短,但没有明确连接“未知落点”和风险。末尾的 as bad as a diverging landing spot 也需要读者倒推。
B 最差。它基本复写了紧邻的条件表达式和赋值结果,却省略了跨 counter 导致 id 不匹配这一关键原因。
我的版本:
cpp// Unknown or differing blocks may put peers on separate counters. // One end can then issue ids that the other never waits for.
两行,各有职责:
第一行解释两个 guard 条件共同代表的风险。第二行解释风险的实际后果。
不再重复 mixed、loop counter 等已有信息,也不需要 ASCII 表格或逐分支描述。这里的两个条件甚至不严格互斥:landingBlock == nullptr 且已有 entry.landingBlock 时,两部分都成立。
注释应描述共同的安全性不变量,而非逐条翻译分支。
第 2 条:方向正确,但“one invariant per block”太绝对。
成本是读者必须识别逻辑块的边界,作者有时还需要人为拆分代码。
本例的 lambda 同时承担排除 preload、确定落点、合并状态等不同职责。它们各有值得说明的不变量。
若 block 指 C++ 词法作用域,这条就不合理;若指逻辑片段,则基本可行。
建议改成:One reason per comment, placed next to the smallest relevant block.
第 5 条:防止符号电报值得,但规则存在内部冲突。
第 4 条明确允许:
textprod(s) && !isLast(s) => [Relay]
但第 5 条又要求去掉符号后仍能读成完整规则。
上述合法推论去掉 &&、!、=> 后,逻辑关系就消失了。两项要求不能同时严格执行。
应明确区分:
这比一律要求“去掉符号还能读通”更准确。
第 6 条:对普通 // 注释值得,对 Doxygen 注释则过度限制。
源码 diff 中,Markdown 装饰确实容易增加视觉噪声。
但规范中“Markdown 不会渲染”的判断并不普遍成立。Doxygen 从 1.8.0 起支持 Markdown,包括强调文本和嵌套列表,具体受配置及语法影响。(www.doxygen.nl)
因此建议分开规定:普通 // 优先纯文本;/// 可以使用经项目工具链验证的 Doxygen/Markdown 格式,但必须保持源码可读。
总体结论:
第 2 条应放宽“每个 block 只能有一个不变量”的字面约束;第 5 条必须为形式化表达式设置例外,否则与第 4 条冲突;第 6 条应区分源码阅读和文档渲染。
对于这个真实用例,最佳取舍就是:两行自然语言,说明共同风险及其后果,不逐分支复述条件,也不重复头文件契约。