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

Criado em: 15 de novembro de 2026

Respondido usando GPT-6 Thinking por Chat01

Pergunta

评审请求:一份 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. 或者简单描述每一个子句的含义/隐含不变量/假设,让 reviewer 不需要重新爬上下文?以及维护时也不需要费劲确认为什么应该这么走?

Pensamento

Clarifying landing flags

I’m interpreting this as a request to revise one comment only. I’ll emphasize that unknown or inconsistent landing blocks should mark the entry as mixed, while avoiding unrelated header changes.

Assessing comment options

I’m comparing the alternatives against the requested scope and comment style. The main tension is whether symbolic notation can express the guard clearly without violating the rule that comments should use complete prose.

Finding rule conflicts

I’m identifying genuine contradictions rather than stylistic preferences. The clearest conflict is between allowing symbolic case maps or logical notation and requiring comments to remain fully grammatical after removing those symbols.

Resolving notation conflicts

I’m separating true contradictions from preferences. Rule 5 conflicts with rule 4 when symbolic derivations are allowed but must still parse after removing symbols; rule 6 also overstates plain-text limitations for documented markup.

Refining the invariant

I’m checking whether the comment should emphasize the shared-counter invariant, the unknown-or-divergent landing blocks, or the unmatched-ID failure. A concise three-line explanation can connect all three without overstating the code.

Refined the invariant by resolving notation, rule, and comment conflicts

Pensamento

Connecting the invariant

I’m narrowing the comment to one shared-counter invariant, then linking unknown or differing landing blocks to the concrete failure: one endpoint may issue identifiers that its peer never awaits.

Connected the invariant

Pensamento

Connecting the invariant

I’m preserving the essential causal chain: every handshake endpoint needs one counter; unknown or differing landing blocks undermine that guarantee; anchoring them risks unmatched identifiers.

Linking the invariant

I’m preserving the core reasoning: every handshake end must share one counter; unknown or differing landing blocks undermine that guarantee; anchoring either case could produce IDs that a peer never waits for.

Connected and linked the invariant

判定规则冲突

我确认有两处需要修正:规则 5 会误伤规则 4 明确允许的公式;规则 6 把注释渲染能力说得过于绝对。规则 2 更像启发式要求,适合改成“每个逻辑段聚焦一个主要不变量”。

Identified conflicting decision rules

Searched 12 websites

Worked for 1m 26s

Resposta

Text version

1. 原注释中,哪些信息已经存在,哪些不可替代?

已经由代码、头文件或相邻注释表达的:

  • !landingBlock:flag 的最终落点未知。
  • entry.landingBlock != landingBlock:同一 ID set 的 flag 落在不同 block。
  • entry.mixed = true:以上任一情况都会使该 ID set 失去 block anchor 资格。
  • if (entry.mixed) return:一旦判为 mixed,后续记录不会恢复它。
  • getMultiBufferIdAnchor() 的声明:无法使用 anchor 时,保留 loop counter。
  • 上方注释:必须使用 flag 的实际落点,而非 anchor op 自己所在的 block。

只有争议注释才明确提供的:

  1. 未知落点为什么不安全:另一个 handshake 端点可能位于 loop body。
  2. 不同计数器为什么不安全:同一个 handshake 的两端可能生成不匹配的 event IDs,导致对端等待不到。
  3. 隐含的正确性不变量:同一个 handshake 的所有端点必须使用一致的 counter。

其中第 3 点最重要。它把两个 guard 条件统一为一个正确性要求,而不是两个碰巧都要设置 mixed 的特殊情况。

原文最后一句 “Both cases keep the loop counter for every end” 有少量信息增量:它强调决策作用于整个 ID set,而不是某个端点。但这个行为已能从 map 的 key、mixed 状态及接口契约推知,不必在这里重复。

还有一个值得指出的细节:头文件对 mixed 的解释不完整。 它只提到 flags 落在多个 block,实际实现还包括落点未知的情况。这是契约应当补充的地方,而不是依赖函数内部注释弥补。

2. A、B、原文怎么选?我会怎么写?

只在三者中选,我选 A。 它保留了关键失效机制,减少了重复描述。原文稍完整,但冗余较多;B 最差,因为它重新抄写判断条件,却丢失了真正重要的 counter 不变量和 ID 不匹配的后果。

不过,A 的问题是没有直接说清:两个条件为什么属于同一个不变量。

我会改成以下 4 行:

cpp
// All ends of a handshake must share the same counter. // An unknown landing block may hide an end in the loop body. // Different landing blocks may use different counters. // Anchoring either case could produce IDs a peer never waits for.

每行各有明确职责:

  • 第 1 行:不变量。 这是整个 guard 必须维护的正确性条件。
  • 第 2 行:解释 !landingBlock。 未知落点可能意味着某个端点实际使用 loop-body counter。
  • 第 3 行:解释 block 不一致。 不同 block 可能引入不同 counter。
  • 第 4 行:说明失效后果。 错误地选择 anchor 可能导致 peer 等不到对应 ID。

这四行虽然没有比 A 更少,但每行都是短句,没有重复代码执行了什么,也没有要求 reviewer 自己重建因果关系。

我不建议再压缩为一句公式。这里需要保存的是为什么两个条件都不能安全地选择 anchor,而不是把布尔条件换一种记号写出来。

3. 第 2、5、6 条是否值得?是否存在真正的矛盾?

规则阅读成本收益判断
2. Bearings, not narration读者有时需要回溯上下文,重建省略的因果关系避免注释复述代码值得,但不能机械执行
5. Symbols, not grammar读者要解码符号、隐含谓词及关系复杂状态关系表达紧凑部分值得,限制过细
6. Plain text放弃强调、列表等视觉层次diff 中阅读稳定,减少格式噪声适合普通 //,不宜无条件推广

第 2 条:最值得保留

但建议把 one invariant per block 理解成:

一个逻辑单元围绕一个核心不变量;允许解释其条件和失效后果。

否则,合法的复杂控制流可能同时需要说明多个独立约束,而第 3 条又允许由于共享状态、执行顺序或 RAII 而不提取函数。

不能为了满足“一块一个不变量”,强迫工程师拆散本来就需要共同维护的代码。

第 5 条:存在明确的规则冲突

第 4 条明确允许:

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

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

去掉 &&、!、=> 后,这个表达式无法正确解析。符号本身就是形式逻辑的语法,不能同时要求它们只承载内容、不承担语法。

因此第 5 条若按字面强制执行,就会与第 4 条允许的合法写法冲突。

建议把去符号测试限定于自然语言句子,明确排除独立的逻辑表达式和 case map。

B 的问题也不是用了符号,而是符号没有增加代码之外的信息。

第 6 条:需要修正事实前提

Doxygen 本身支持 Markdown,包括强调及嵌套列表;MARKDOWN_SUPPORT 的默认配置也是开启。不能笼统断言这些语法不会渲染。(www.doxygen.nl www.doxygen.nl)

团队当然可以主动禁止 Markdown 装饰,但理由应该是保持源码可读性,而不是声称工具不支持。

建议区分普通 // 注释和文档注释,并以实际项目的渲染配置为准。


最终建议:保留规范的方向,把硬约束改为可检验的阅读目标。

对这个 pass,最有价值的审查标准是:

读者只看当前 guard 和紧邻注释,就应该能回答:为什么需要这个条件、它保护什么不变量、去掉它会造成什么错误。

不是要求每个布尔子表达式都有一条解释,也不是追求最少行数。代码已经回答了“做什么”,注释需要用最短、清楚的因果链回答“为什么必须这样做”。

这比对自然语言、符号数量和行数施加过细限制,更适合真实工程和只看 diff 的机器审查者。

Compartilhar esta Q&A