# 评审请求:一份 C++ 注释规范 + 一个真实用例 请只回答文末的三个问题,不必复述规范。你看...

Created on: November 15, 2026

Answered using GPT-6 Thinking by Chat01

Question

评审请求:一份 C++ 注释规范 + 一个真实用例

请只回答文末的三个问题,不必复述规范。你看到的代码是真实工程代码(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,行号保持原样):

cpp
void 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

三、请回答

  1. 就这段函数而言,// An unknowable landing spot … 那四行里,哪些信息是代码(含头文件、上下两处注释)已经说过的,哪些是只有注释能说的?
  2. 候选 A、候选 B、原文三者,哪一个对"只改这一处、之后要维护它的人"最有用?如果你会写成别的样子,请直接给出行数、每行内容与理由。
  3. 规范里第 2、5、6 条各自带来的阅读成本,换来的精度是否值得?有没有哪一条在真实代码里会无法满足(即规范与合法写法互相矛盾)?
  4. 考虑人类的阅读偏好:倾向清晰明确的短句/克制的符号表达,避免长篇大论
  5. 或者描述每一个分支的含义?

Thought

Reviewing branch behavior

我会先区分三类情况:跳过的记录、无法确定落点的记录,以及落到单一或多个基本块的记录。还会特别指出 nullptr 与未知落点会直接触发 mixed,以及注释定义可能需要同步更新。

Evaluating comment options

I’m comparing precision and usefulness: A explains the practical risk but may overstate loop-body behavior; B mirrors the condition too closely. I’ll favor a concise comment describing unknown or divergent landing blocks and their mixed classification.

Refining the rationale

I’m narrowing the explanation to the invariant: if the landing block is unknown or inconsistent, I can’t prove all ends share one counter. That risk justifies marking the set mixed.

Choosing concise wording

I’m favoring a two-line comment that covers both unknown and differing landing blocks, explains the counter split, and states the concrete failure: one end may issue IDs the other never awaits.

Assessing rule tensions

I’m finding a real conflict between rules 4 and 5: rule 4 permits symbolic derivations, while rule 5 requires prose that still reads naturally without symbols. Rule 6 also depends on documentation-tool configuration.

Refined concise rationale for branch behavior and comment options

Thought

Clarifying specification tradeoffs

I’m distinguishing useful precision from rigid rules. Rule 5 conflicts with rule 4 when symbolic derivations are required, while rule 6 overstates documentation-rendering behavior. I’d explain the shared invariant, not restate every branch.

Clarifying branch explanations

I’m noting that the failure conditions can overlap, so a branch-by-branch table would mislead. A single invariant is clearer: unknown or differing landing blocks may split counters and produce unmatched IDs.

Clarified specification tradeoffs and branch explanations

Searched 6 websites

Worked for 1m 10s

Answer

Text version

1. 哪些信息已经说过,哪些只有注释能说?

代码和头文件已经表达的:

  • !landingBlock 和已记录 block 不同,都会导致 entry.mixed = true。
  • getFlagLandingBlock() 返回 null 表示落点暂时不可确定。
  • mixed 的 id set 保留 loop counter,不使用收集的 anchor。
  • 上一处注释已说明 flag 的实际落点可能是 if/else block,而不是 anchor op 所在 block。

只有争议注释提供的:

  • 未知落点可能意味着 peer 位于 loop body。
  • 同一次 handshake 若跨越不同 counter,可能产生对端永远不会等待的 id。
  • 因此,未知落点不能被当作安全落点。这是安全性理由,不只是分类规则。

其中最有价值的是第二点:跨 counter 为什么会出错。

另外,头文件的 mixed 说明并不完整:未知落点也会使 mixed = true,不只是多个不同 block。按第 7 条,后续应修正这个遗漏。

2. A、B、原文哪个最好?

三者原样选择,我选原文;但更推荐改成两行。

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 时,两部分都成立。

注释应描述共同的安全性不变量,而非逐条翻译分支。

3. 第 2、5、6 条的成本是否值得?有没有无法同时满足的要求?

第 2 条:方向正确,但“one invariant per block”太绝对。

成本是读者必须识别逻辑块的边界,作者有时还需要人为拆分代码。

本例的 lambda 同时承担排除 preload、确定落点、合并状态等不同职责。它们各有值得说明的不变量。

若 block 指 C++ 词法作用域,这条就不合理;若指逻辑片段,则基本可行。

建议改成:One reason per comment, placed next to the smallest relevant block.

第 5 条:防止符号电报值得,但规则存在内部冲突。

第 4 条明确允许:

text
prod(s) && !isLast(s) => [Relay]

但第 5 条又要求去掉符号后仍能读成完整规则。

上述合法推论去掉 &&、!、=> 后,逻辑关系就消失了。两项要求不能同时严格执行。

应明确区分:

  • 完整的形式化表达式、case map:允许符号承担逻辑关系。
  • 自然语言注释:不允许用符号代替必要的语法和动词。

这比一律要求“去掉符号还能读通”更准确。

第 6 条:对普通 // 注释值得,对 Doxygen 注释则过度限制。

源码 diff 中,Markdown 装饰确实容易增加视觉噪声。

但规范中“Markdown 不会渲染”的判断并不普遍成立。Doxygen 从 1.8.0 起支持 Markdown,包括强调文本和嵌套列表,具体受配置及语法影响。(www.doxygen.nl)

因此建议分开规定:普通 // 优先纯文本;/// 可以使用经项目工具链验证的 Doxygen/Markdown 格式,但必须保持源码可读。


总体结论:

第 2 条应放宽“每个 block 只能有一个不变量”的字面约束;第 5 条必须为形式化表达式设置例外,否则与第 4 条冲突;第 6 条应区分源码阅读和文档渲染。

对于这个真实用例,最佳取舍就是:两行自然语言,说明共同风险及其后果,不逐分支复述条件,也不重复头文件契约。

Share this Q&A