Skip to content

Coding Rules ​

This document is the sole authoritative source for YaoXiang code change rules. It precisely describes the rules, without current-state diagnoses or historical rationale. Execution entry point: HOWTO.md (pre-work self-check) → this document (rules) → PR template (mandatory at submission).

Part One: Three Prohibitions ​

Prohibition One: No Inventing New Concepts ​

Before adding any pub type, enum, constant table, or concept, all four of the following criteria must be satisfied for the change to be compliant. A match on any one of them is a violation:

CriterionRule
A. Overlapping responsibilityThe variant name of the new item overlaps that of an existing item by ≥ half, and their responsibilities overlap → violation
B. Insufficient call sitesThe new pub item has < 2 call sites (only the definition and a single call site) → violation; it cannot be shown to be a concept rather than a local implementation
C. An alias is needed for disambiguationAn alias such as use … as XxxBinOp is needed to distinguish items with the same semantics → violation
D. Differences are bridged with a synonym tableDifferences are papered over through hand-written string matching → violation; exhaustive enumeration or explicit conversion is required instead

Prohibition Two: No Accumulation of Responsibilities ​

A module is responsible for only one category of responsibility. There is no line-count, size, or file-size threshold—scale problems are solved by separating responsibilities, not by numbers.

CriterionRule
A. Responsibility categoryThe new code does not belong to any existing responsibility category of the target module (it would be category 2 or later) → violation; create a new module or move the existing code for that responsibility along with it. Requires human judgment and cannot be mechanized
B. Bypassing the authoritative sourceA table entry is added without updating the sole authoritative source (a hand-written duplicate that bypasses the authoritative table) → violation
C. Boundary erosionAny new cross-layer dependency (L2→L3, L4→L1/L2), include!, or cross-layer pub(crate) leakage is added → violation. Can be mechanized and is checked by CI

Prohibition Three: Do Not Patch a Refactor ​

CriterionRule
A. Synonymous duplicationThe same behavior appears in ≥ 2 places (an alias, conversion, stage wiring, or error mapping) → violation; it must be raised to a shared layer
B. Excessive fan-outA single change requires synchronously modifying ≥ 3 existing synonymous mappings → classified as an architectural change; stop work and follow the design-document process
C. New entryAdding an “Nth entry point / table entry” instead of registering it in the declarative stage table → violation

Part Two: Decision Procedure (D0–D4) ​

Every code change must pass the following five gates in order. Each gate is a decidable Boolean condition; a match ends the process:

D0  门禁本次改动是否触碰任何一张已存在的表(错误码/opcode/类型/入口阶段)?
             ├─ 是 → 能指出该表的唯一权威实现模块吗?
             │        ├─ 能 → 继续
             │        └─ 不能 → ⛔ 停止。先建立权威源
             └─ 否 → 继续
                    ↓
D1  防生造去掉新概念后,能否用「既有概念 + 参数」表达同样的语义?
             ├─ 能 → ⛔ 禁止新增。理由记入 PR
             └─ 不能 → 继续
                    ↓
D2  防并行新概念是否与某既有概念同语义(变体名重合 ≥ 半数)?
             ├─ 是 → 有 From/TryFrom 转换且机检吗?
             │        ├─ 有 → 继续
             │        └─ 无 → ⛔ 合并为一份(禁止用 import 别名区分)
             └─ 否 → 继续
                    ↓
D3  补丁?    依次判定,命中即止:
             1) 同一行为需在 ≥2 处复制?        → 是 → ⛔ 必须提到共享层
             2) 需要新增"第 6 个入口"?         → 是 → ⛔ 禁止手工接线,改为登记进阶段表
             3) 一次修改要改 ≥3 处同义映射?   → 是 → ⛔ 判定为架构变更,停工走设计文档
             4) 以上皆否                       → 允许局部补丁,但必须附带回归测试
                    ↓
D4  职责?    本次新增代码属于目标模块已有的职责类别吗?
             ├─ 否(第 2 类及以上)→ ⛔ 新建模块,或把该职责的现有代码一并搬过去
             └─ 是 → 合规

Trade-off criteria (applying throughout D0–D4): A solution may be rejected only on grounds of correctness and readability; “scope of the change,” “whether a new mechanism is introduced,” and “implementation cost” do not constitute grounds for rejection. This complements Prohibition One without conflict: Prohibition One constrains “whether a concept is duplicated,” whereas this provision constrains “whether the grounds for a trade-off are valid.” Any solution rejected on the grounds of change scope or a new mechanism must be sent back during review.

For trade-offs requiring a user decision—architecture choice, semantic deviation, registration or non-registration, breaking changes, or priority insertion—provide all four items required by the “When Requesting User Adjudication (Mandatory)” section of the repository-root AGENTS.md: situation and evidence, item-by-item pros and cons, a clear recommendation and its cost, and explicit identification of breaking changes.

Semantic-correction routing (the routing criteria in 03-ir-and-criteria): D0–D4 all remain in force, with one additional “error type” label. Classes A/B/C—where the old behavior was unsuccessful: crash or stack overflow, silent failure, silent mismatch, silent no-op, or silently incorrect answer—may be corrected alongside the refactoring, provided that the correction is red before green, does not change the externally observable behavior of programs that previously succeeded, is registered in the same commit, and includes baseline regeneration in the same commit and human review. Classes D/E/F—those that change the observable behavior of programs that previously succeeded, external contract tables, or RFC-level design—require prior user adjudication. See 03 §Semantic Correction Routing for the expanded criteria. Add an “Error Type (A–F)” line to the required PR block.

Part Three: Red Lines (Always Rejected During Review) ​

  1. Do not modify code you have not read—if you have not opened the file being changed or searched for related references, you must not change it
  2. Do not defer core functionality—do not introduce silent discards such as todo!(), unimplemented!(), or Vec::new() // Not implemented yet, or indefinitely defer work to a “separate issue.” Fix it immediately or register it as a task in the current phase
  3. Do not delete tests or relax criteria to obtain a green light—if that is impossible, the implementation is defective; report it truthfully and reassess. Changing the criteria is not a valid response. Test admission and retirement follow Part Seven: a test may be retired only if it fails all three gates (clause, history, proof); “delete it because it is red” is always rejected
  4. Do not use import aliases to reconcile concepts with the same semantics
  5. Do not add include! or new reverse cross-layer dependencies; cross-layer pub(crate) leakage may only decrease, never increase
  6. The required PR block must be completed truthfully—if the authoritative source module name for D0 cannot be provided, the source was not investigated, and the change is rejected outright; a missing “Error Type (A–F, according to the routing criteria in 03-ir-and-criteria)” label, or one that does not match the actual change, is rejected for the same reason

Part Four: Division of Labor Between Machines and Humans ​

Assign mechanical issues to tools; review should focus only on non-mechanical issues.

CategoryExecuted by
Formatting, linting, table consistency, boundary erosion (Prohibition Two C), test wiring, and cross-layer dependenciesTools: cargo fmt / clippy / build.rs gates / scripts/ci/check-*.py
Responsibility-category determination (Prohibition Two A), the D3 “patch or architectural change” judgment, and exemption rationalesHumans: required PR block + review

Apply corrections directly in the text; do not retain old/new comparisons: when documentation or comments do not match reality, change the text directly to match reality and delete the old wording. Do not retain the old text and then append a revision note or a “formerly …, now …” comparison—readers should not encounter the incorrect version before the correct one. Process evidence for corrections (red→green, before/after diff, adjudication number) belongs in the commit message, not in the corrected passage. Work orders and change lists, such as 02 §Change List, are exempt.

Part Five: Exemption Mechanism ​

  • Exemptions from machine-checkable criteria must always use an inline // reason: <reason> comment
  • The exemption count itself is included in the gate report and each exemption is reviewed individually
  • An exemption is proof of an exception, not a routine practice; when the second exemption of the same kind appears, the correct action is to change the rule or criterion, not to add a third exemption

Part Six: Code Review Checklist ​

Review every PR against the following items:

  • [ ] D0: Does the change touch any existing table? Which module is the sole authoritative implementation of that table?
  • [ ] D1: Can the new concept be expressed using existing concepts and parameters? If not, where is the rationale documented?
  • [ ] D2: Is the new concept semantically equivalent to an existing concept? Where is the conversion? Is an import alias needed?
  • [ ] D3: Does the same behavior appear in ≥ 2 places? Was an entry point added instead of being registered in the stage table? Must ≥ 3 synonymous mappings be changed?
  • [ ] D4: Does the newly added code belong to an existing responsibility category of the target module?
  • [ ] Silent channel: For “register-consume” mechanisms—where one side registers data and another consumes it, such as SemanticDB, proof_calls, or the obligation ledger—are the producer-side and consumer-side directly driven tests delivered in the same batch? If a consumer-side test manually constructs registered data while the producer side has no direct-driving evidence, the mechanism exists only on the surface and the data flow never occurred, so the change is rejected (three existing examples: proof_calls, declaration-driven comparison, and the LSP semantic index)
  • [ ] Boundary: Has the boundary been eroded? Have a new cross-layer dependency, include!, or cross-layer pub(crate) leakage been introduced?
  • [ ] Check admission: Which of the three gates in Part Seven did the new test or gate pass? Where is the rationale documented? (For a check that passes the proof gate, also answer: if it were replaced with a different correct implementation, would it turn red?)
  • [ ] Division of labor: Are mechanical issues covered by tools? Is review spending time only on non-mechanical issues?

Part Seven: Admission and Retirement of Checks and Tests ​

A green light proves nothing. Checks have only negative epistemic value: what they prove is that “this time, it did not get this point wrong.” Whether a check is worth keeping depends solely on whether it guards a documented property. If you cannot answer that question, it is not safety; it is a tax on people who follow the rules.

7.1 The Sole Validation: If You Replace It with a Correct Alternative Implementation, Will It Turn Red? ​

ResultMeaningDisposition
It turns redIt freezes an implementation choice (rendered text, message wording, exact line number, or internal structural shape)Characterize it; do not admit it to the gates
It does not turn redIt guards a propertyValid check

Any check that “freezes the current output wholesale,” such as a full snapshot or byte-for-byte comparison, will inevitably turn red when the implementation is replaced with a correct alternative. By definition, it cannot pass this gate.

It follows that the atomic unit of a test is not “one test,” but one falsifiable distinction. Writing N tests with the same code path, the same class of input, and the same assertion intent adds zero incremental information. The mere number “this repository has thousands of tests” does not constitute evidence of anything.

7.2 Admission: Three Gates ​

A new check must pass at least one of the following gates, and its rationale must be documented in a header comment in the test file or in the commit message:

GateWhat must be provided
ClauseThe specific clause of a SPEC / RFC
HistoryA real failure: which change, which defect, and how it surfaced at the time
Proof① What is the property? ② Why it must hold, independently of implementation choices? ③ Why is this test its cheapest observation point?

The three gates are not equivalent: a clause is an external constraint and may be ambiguously worded; history covers only the incident that actually occurred; proof covers the entire class of properties and therefore lasts the longest. Its value lies not in what it has caught, but in the class of violations it blocks.

The third gate must have teeth. Everyone can say, “This is an invariant,” but most things described that way actually freeze the current implementation. All three gates share one validation (7.1): if a check turns red when replaced with a correct alternative implementation, send it back to characterization—it is not proof, but a freeze disguised as proof.

7.3 Retirement: The Burden of Proof Is Reversed ​

Run existing checks through 7.2: keep those that pass any one gate; delete those that fail all of them. There is no “observation period,” “downgrade to advisory,” or “retain after marking as characterization”—all three merely prolong the life of things whose basis cannot be explained.

  • Deletion is not an irreversible operation: history lives in git, and a check can be retrieved by commit when needed. Precisely because it can be retrieved, “delete first and retrieve it when needed” is preferable to “keep everything”;
  • Perform deletions in batches, with one commit per batch that can be reverted as a whole;
  • In each batch’s commit message, record what was deleted, which gate was used to judge it, and whether alternative coverage exists.

7.4 Cost Discipline ​

Cost is unrelated to legitimacy. It must be measurable—using the repository’s existing cost: resource-profiling marker—and included in the gate budget. “CI runs in parallel, so it does not matter” is not a valid reason: parallelism saves wall-clock time, not the time each person spends on local self-checks, which is the cost paid every day.

7.5 Boundary with Red Line 3 ​

Red Line 3 concerns motivation—changing a criterion to make CI green—whereas this part concerns cost and benefit—whether the check is worth keeping. The two do not conflict.

Adjudication order in cases of conflict (mandatory): ① Is it red now because the implementation is wrong, or because the criterion is wrong? ② If that cannot be answered, do not delete it and do not change the criterion; ③ If the criterion is wrong, retire the check through 7.3 rather than changing the assertion.