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

تم الإنشاء في: ١٥ نوفمبر ٢٠٢٦

تمت الإجابة باستخدام GPT-6 Thinking بواسطة Chat01

سؤال

评审请求:一份 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 条各自带来的阅读成本,换来的精度是否值得?有没有哪一条在真实代码里会无法满足(即规范与合法写法互相矛盾)?

الفكرة

Assessing semantics and clarity

I’m checking whether the specification matches the implementation, especially unknown landings, conflicting targets, and mixed-state persistence. I’m also evaluating whether the review questions expose real correctness risks without overloading the reader.

Refining review questions

I’m distinguishing genuine semantic risks from repetition. Unknown and conflicting landings both trigger fallback, but claims about separate counters remain conditional, so I’m testing whether each question adds evidence rather than restating code.

Comparing comment options

I’m favoring a concise comment that names both triggers and explains the failure mode. I’m avoiding claims that different blocks always mean different counters; the risk should remain explicitly conditional.

Balancing comment rules

I’m weighing whether the shorter version preserves the causal warning. The strongest option names unknown or divergent landings, explains the possible counter mismatch, and avoids implying that different blocks always guarantee different counters.

Choosing the comment

I’m selecting the concise alternative, but I’d tighten it to name both unknown and differing blocks while keeping the counter mismatch conditional. That preserves the maintenance rationale without repeating the surrounding specification.

Refined and selected balanced review comments

الفكرة

Checking hard contradictions

I’m finding a real tension between rules 4 and 5: symbolic derivations are required, yet symbols are said not to provide grammar. Rule 2 is also too absolute for blocks with multiple inseparable invariants.

Consolidating the recommendation

I’m keeping the concrete loop-body example while removing repeated fallback mechanics. A compact three-line comment can explain both triggers and the conditional mismatch risk without restating nearby code or headers.

Reaching the conclusion

I’m treating rule 5’s symbolic exception as compatible with rule 4 only when explicitly scoped to relations. The clearer hard conflict is rule 2’s “one invariant per block,” which fails when multiple inseparable invariants coexist.

Finalizing the guidance

I’m recommending the three-line version because it preserves the loop-body example, names known divergence, and states the conditional failure mode without repeating the guard or fallback behavior.

Concluding the review

I’m treating rule 2 as too literal for lexical blocks containing multiple inseparable invariants. Rule 5 also needs an explicit formula exception; otherwise it conflicts with rule 4’s symbolic derivations. Rule 6 is a context-dependent rendering claim, not a universal fact.

Comparing comment options

I’m favoring A because it preserves the failure mode without restating the guard. B is too telegraphic; the original is accurate but repeats effects already established nearby.

For maximum precision, I’d use three lines:

cpp
// If the landing block is unknown, a peer may be in the loop body. // Like conflicting landing blocks, this risks using separate counters // for one handshake, assigning ids the peer never waits for.

Checking rule consistency

I’m seeing a literal conflict in rule 2: one lexical block can contain multiple necessary invariants, so “one invariant per block” should mean one coherent comment, not exactly one invariant.

Rule 5 also needs an explicit exception for standalone formulas; otherwise it conflicts with rule 4’s symbolic derivations. Rule 6’s Markdown claim isn’t universal: Doxygen supports Markdown when configured accordingly.

Compared options and finalized guidance after checking contradictions

Searched 4 websites

Worked for 1m 17s

الإجابة

Text version

1. 原注释四行中,哪些信息已经存在,哪些只有注释能说?

应当区分三类:代码直接表达的事实、需要结合头文件才能推知的结果,以及注释独有的安全性理由。

原注释中的信息是否已有判断依据
Landing block 可能无法确定已有getFlagLandingBlock() 声明允许返回 null
不可确定的位置与不同的 landing block 都会使集合失去锚点资格已有if 条件和 entry.mixed = true 直接表达
一旦 mixed 就不再恢复已有前面的 if (entry.mixed) return;
两种情况都退回 loop counter基本已有IdAnchor 和 getMultiBufferIdAnchor() 的声明说明了回退语义
未知 landing block 可能意味着另一端位于 loop body注释独有代码只能证明位置未知,不能解释这种可能性
同一个 handshake 的两端可能使用不同 counter注释独有代码只比较 Block *,没有直接表达 counter 的关系
不同 counter 会导致一端分配的 event id 无人等待注释独有这是跨越事件分配和等待机制的故障模式

最重要的区别是:

!landingBlock 为什么要与已知的 block 不一致受到同样处理?

代码只能回答“它们都变成 mixed”,不能回答“为什么一个未知值也必须保守处理”。

原注释真正不可替代的贡献,是建立下面这条因果链:

未知位置可能掩盖不同的 counter → 同一个 handshake 的两端使用不同 counter → 分配的 event id 与等待的 event id 不匹配。

这条链需要保留;重复 mixed 和回退行为则没有必要。

还有一个精度问题:不同的 Block * 不必然代表不同的 counter。这里成立的是“可能产生不同 counter,因此保守处理”,而不是“不同 block 必然使用不同 counter”。

2. A、B、原文,哪个对维护者最有用?

三选一,我选 A。排序是 A > 原文 > B。但我会采用第四种写法。

A 的优势是保留了真正值得维护者知道的信息:为什么一个未知位置也可能导致 event id 不匹配。它没有重复 mixed 的赋值,也没有重新说明回退结果。

它仍有两个问题:

  • Peer may sit in the loop body 没有明确说这是 !landingBlock 分支的风险,需要读者自行补足。
  • as bad as a diverging landing spot 是结论性比较,没有清楚连接“不同 block”“不同 counter”和“不同 event id”。

原文的因果关系比 A 完整,尤其明确强调了未知位置也必须保守处理。但首尾分别复述了条件的处理结果和头文件中的回退契约。对已经阅读当前函数的维护者,这些是额外阅读成本。

B 最差。 它复制了紧邻的布尔条件,又把 => mixed 写成紧邻赋值的另一种表示。唯一新信息是 peer 可能位于 loop body,却删掉了真正的故障机制。

而且 B 并不符合第 5 条的本意:它不是跨位置的关系摘要,只是把局部代码重新排版成公式。审查者无法从中判断为什么不能删除 !landingBlock。

我的改写:3 行

cpp
// An unknown landing block may hide a peer in the loop body. Like // divergent landing blocks, this can split a handshake across counters // and assign ids that the peer never waits for.

这三行分别承担三个必要的信息功能:

第一行说明为什么“未知”也是风险,并保留 loop body 这个具体场景。

第二行把未知情况与已知 block 分歧连接起来,指出共享的风险是一个 handshake 跨越不同 counter。

第三行给出最终故障:event id 的分配与等待不匹配。

这里的 can 不能随便删。不同 landing block 不必然代表不同 counter,注释应该表达可能发生的危险,而不是声称每次都会发生。

相比原文,这个版本删除了重复的回退说明;相比 A,它又明确说出了未知位置为什么危险。

还有一个与第 7 条有关的真实问题:getMultiBufferIdAnchor() 的头文件说明列举了“无 collector entry”和“flags 位于多个 blocks”,但没有明确列出 landing block 无法确定、从而被标记为 mixed 的情况。如果该括号是穷举回退条件,那么头文件契约本身也有遗漏。即使这次只改函数内注释,也不应把头文件视为完全准确。

3. 第 2、5、6 条的成本与精度是否值得?有无无法满足的规定?

第 2 条:方向值得,但不能按字面强制

它降低了读者从代码与注释中筛选重复信息的成本,对这段函数尤其有价值。

问题在于 one invariant per block 的量词和 block 的含义。

如果 block 指 C++ 词法块,当前 record lambda 就同时包含多个独立且重要的约束:preload 排除、branch scope 的实际 flag 位置、未知或分歧 landing block 的安全性处理。

这些约束不应该为了满足一条注释数量规则而强行合并,也未必可以安全提取成函数,因为它们参与同一个局部状态收集过程。

这是一个按字面解释就可能无法满足的要求。 合法的代码块可能需要零条、一条或多条注释。

建议把约束改为:

One non-obvious reason per comment unit; group comments by logical responsibility, not lexical block boundaries.

即按逻辑责任划分,而不是要求每对花括号恰好对应一个 invariant。

第 5 条:防止电报式注释值得,但符号限制过强

它确实能防止两类问题:用缺乏定义的缩写代替解释,以及把条件式重新抄一遍却不提供新信息。B 正是后者。

但规则同时引入两种成本。

第一,维护者有时需要先把符号翻译为英文,再对照代码恢复原始关系。这未必比直接阅读表达式更准确。

第二,Strip the symbols and re-read 如果作为无例外的检查,会和第 4 条的合法推导发生冲突。

例如规范自己要求的:

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

其中 &&、!、=> 本来就是逻辑语法。去掉后,关系不再可解析。不能一方面要求这种独立符号推导,另一方面要求所有规则去掉符号后仍构成完整自然语言句子。

这个冲突需要明确豁免,而不能靠审查者猜测作者意图。

我建议只对自然语言和符号混写的句子应用“删除符号后重新阅读”的检查;独立公式、case map 和必要的程序标识符不受此检查约束。

这样第 5 条仍然能够拒绝 B 这种重复代码的伪推论,而不误伤真正有信息增量的数学表达式。

第 6 条:目标合理,但包含事实性错误

对于普通 // 注释、diff 审查和机器阅读,我赞同默认使用无需渲染的纯文本。Markdown 装饰不应该成为理解代码的前提。

但“**bold**、*em* 和嵌套列表不会渲染”不能作为通用事实。

Doxygen 官方文档明确支持 Markdown 的粗体、斜体、嵌套列表等语法,并可在文档注释中处理这些格式。(www.doxygen.nl)(www.doxygen.nl)

因此,要区分两件事:

  • 普通 // 注释在源码或 diff 中应当无需渲染即可理解。
  • Doxygen /// 注释可以使用工具配置所支持的标记语法。

如果团队希望所有注释都保持纯文本,那是一条合法的风格选择。但不能把它论证成“Doxygen 不支持 Markdown”。

我会把第 6 条的核心要求改为:

Comments must remain readable without rendering. Use only markup supported by the file's documentation conventions; do not rely on Markdown presentation in ordinary source comments.

这既能维护 diff 阅读体验,又不否定 Doxygen 的实际能力。

总结判断

条款阅读成本换来的收益我的结论
第 2 条减少代码复述,突出局部不变量值得;但 per block 必须改成逻辑划分
第 5 条减少歧义,避免无信息增量的符号复述部分值得;绝对符号限制不值得
第 6 条保证源码与 diff 的可读性值得;必须修正 Markdown 渲染的事实前提

真正需要修的是规范的可执行性,而不只是它的简洁程度。

第 2 条按词法块理解会过度约束合法注释;第 5 条与第 4 条在独立公式上缺少明确的例外边界;第 6 条则把团队风格偏好建立在不正确的工具事实之上。

对于你定义的两类读者,我认为更可靠的评审标准是:

注释是否提供代码和局部契约无法直接给出的信息;这些信息是否足以解释当前实现为什么不能被某种看似合理的修改替代。

在这个真实用例中,最值得保护的不是“遇到 null 要设 mixed”,而是“不能因为没有观察到 block 分歧,就推断两个 handshake 端点可以安全共用一个 counter”。这才是维护者需要记住的约束。

مشاركة هذا السؤال والجواب