Debian Codegraph @

.claude/skills/pr-review/references/review-rules.md

raw
1 # Review Rules
2
3 ## 1. Make ASR explain the program
4
5 The backend should translate explicit ASR, not discover semantic facts from
6 LLVM types and repair them with casts. For each backend branch, ask whether:
7
8 - AST-to-ASR can resolve the decision;
9 - an ASR field, enum, or structured type can record it;
10 - ASR verification can enforce the resulting invariant; or
11 - an ASR pass can canonicalize the representation.
12
13 Type coercion, semantic casts, overload selection, and source-language
14 decisions belong in AST-to-ASR. Backend type inequality is not a semantic
15 predicate.
16
17 ## 2. Prefer explicit state and existing abstractions
18
19 Do not infer intent from strings, argument positions, or backend artifacts.
20 Pass explicit options from the caller that owns the decision. Normalize related
21 types once and share symbol lookup, parent walking, bounds, index creation,
22 element references, and loop construction.
23
24 Identify intrinsic types, modules, and special compiler entities through their
25 structured origin or explicit ASR state. A user declaration can reuse a familiar
26 name, so comparing only `m_name` or module-name strings is not a sound semantic
27 test.
28
29 Distinguish user-visible from compiler-synthesized instances of the same node or
30 symbol kind through explicit provenance. Derive that state from the canonical
31 definition and owner, then store it in ASR when consumers need it. Do not encode
32 internal facts in reserved or mangled name prefixes and scan those strings
33 later.
34
35 Keep utilities at the narrowest reusable layer:
36
37 - use `ASRUtils` for frontend-independent ASR operations;
38 - use `PassUtils` for pass-specific construction and lowering;
39 - use existing codegen helpers for target-specific mechanics;
40 - do not expand a core API solely to serve one local lowering.
41
42 ## 3. Keep errors explicit
43
44 New exceptions move error state outside the type system and force catch-based
45 control flow. Propagate expected compiler failures through `Result` or the
46 established explicit status type. Attach a real source `Location` to
47 diagnostics and preserve it through intermediate processing.
48
49 Do not add broad catches, silent fallbacks, or success-shaped error paths.
50
51 For states that cannot legitimately occur in valid ASR, prefer an assertion or
52 verifier requirement over a defensive conditional. A conditional that silently
53 continues can hide the phase that created invalid state.
54
55 An assertion must test the actual boolean invariant; a descriptive string is a
56 truthy value and never fires. Do not skip a formal/actual count mismatch or
57 similar impossible state with `continue`. Assert it locally, fix the producing
58 phase, and generalize the invariant in ASR verification when it applies
59 globally.
60
61 ## 4. Accept extensions honestly
62
63 When LFortran deliberately accepts useful input that the standard forbids, do
64 not accept it silently and do not reject it merely because it is an extension.
65 Emit a located portability warning that:
66
67 - names the non-conforming construct or constraint;
68 - identifies the behavior as an LFortran extension; and
69 - suggests an actionable standard-conforming alternative.
70
71 Test the warning text and source label in a reference diagnostic. Test runtime
72 behavior separately, using only compiler labels that accept the extension and a
73 short comment explaining any omitted reference compiler.
74
75 Accepting a deliberate extension differs from pretending an unimplemented
76 standard construct works. Do not lower an unsupported construct to a convenient
77 existing node that executes only its body while discarding its semantics.
78 Reject it clearly, or represent the unsupported state explicitly and emit a
79 located warning that behavior is being ignored.
80
81 ## 5. Test semantics and the actual path
82
83 Every test must execute the exact binary, backend, options, and code path
84 changed by the fix. A nearby target or similar configuration is not evidence.
85
86 For each new semantic branch or error:
87
88 - add a compact MRE-derived regression;
89 - prove that it fails without the fix and passes with it;
90 - include the edge case that could disprove the implementation;
91 - cover scalar and array forms, sections, ranks, inheritance, type-bound
92 procedures, nondefault kinds, and target differences when relevant;
93 - register end-to-end tests and use both `gfortran` and `llvm` labels where
94 supported.
95
96 Keep fixtures proportional to the bug. A large unrelated source file is not an
97 acceptable substitute for a minimal regression.
98
99 Put recoverable semantic errors in the appropriate continue-compilation file.
100 Use a complete program that could otherwise build, include multiple independent
101 errors to prove recovery, and temporarily disable each error in turn to verify
102 that every diagnostic branch is genuinely exercised.
103
104 Keep shared error-recovery fixtures append-only: place reusable helper
105 procedures in a module at the top, then append new independent cases at the end.
106 This prevents unrelated diagnostic source locations and reference output from
107 shifting on every addition.
108
109 Differential C interoperability tests must include the toolchain-provided
110 `ISO_Fortran_binding.h` and link the matching runtime. Forcing LFortran's private
111 header or allocator shims into a GFortran or Flang run invalidates the
112 comparison.
113
114 When the test program's own standard legality is uncertain, confirm it against
115 an independent language reference or a second compiler before encoding the
116 behavior as supported. Prefer an established test declaration idiom over
117 inventing a new one.
118
119 Build, generation, and validation steps that can fail must execute on pull
120 requests. Exclude only operations inherently restricted to the main branch,
121 such as publishing with main-only credentials.
122
123 ## 6. Check kinds, layout, targets, and runtime behavior
124
125 Do not assume:
126
127 - the default index kind when `descriptor_index_64` can change it;
128 - host ABI sizes for C interoperable kinds;
129 - compile-time knowledge when a value can be dynamic;
130 - contiguous memory implies equivalent language semantics;
131 - scalar and array physical representations are interchangeable.
132
133 Trace kinds, ranks, ownership, descriptor metadata, record boundaries, and ABI
134 facts from ASR through the changed code.
135
136 In runtime C, distinguish a buffer's capacity from the desired formatted
137 length. Pass the actual capacity to `snprintf`-style APIs, preserve room for
138 terminators according to the allocation contract, and avoid out-of-range
139 floating-to-integer conversions or other undefined behavior. A
140 platform-specific workaround needs a tracked defect, a minimal reproducer, and
141 a focused runtime test.
142
143 When a field has physically different representations selected by a kind or
144 other discriminant, route every read through one discriminant-aware accessor or
145 use distinct explicit fields. A reader that ignores the discriminant silently
146 misinterprets the bits. Do not add a field that duplicates information already
147 available from the type. Do not use floating-point approximations to detect
148 integer overflow; use exact or bounded integer reasoning.
149
150 Whether a derived type has a defined storage layout is a semantic fact. Record
151 properties such as `SEQUENCE` and `BIND(C)` explicitly in ASR, use them to drive
152 member representation, and verify them before code generation. Raw byte
153 operations such as `c_loc`, `storage_size`, `transfer`, and `memcpy` require
154 special scrutiny when an aggregate otherwise uses descriptor-based or
155 compiler-defined layout.
156
157 ## 7. Preserve symbol-reference invariants
158
159 Keep symbol relationships canonical:
160
161 - `ExternalSymbol::m_external` points to the original definition, never another
162 `ExternalSymbol`; resolve through `symbol_get_past_external` before importing.
163 - Symbol creation is idempotent; check the current scope and reuse a compatible
164 existing symbol instead of adding a duplicate.
165 - Parent and owner links identify the actual defining scope.
166 - Only symbol nodes own `SymbolTable`. When a statement introduces local names,
167 place a `Block` or dedicated symbol node in its body and verify that the
168 required scope-bearing node is present.
169 - Replacing an existing symbol-table entry is unsafe because resolved references
170 can still point to the old entry. Skip an equivalent existing definition or
171 assert identity instead of overwriting it.
172
173 Enforce these invariants when importing or constructing symbols. Repairing
174 chains or duplicates later spreads defensive logic across passes and backends
175 and leaves ASR in an ambiguous state.
176
177 ## 8. Choose the earliest correct layer
178
179 Move a decision earlier only when the invariant is true for every input handled
180 at that layer. Centralizing logic in a deep shared function is wrong if that
181 function also handles inputs with different semantics.
182
183 For example, file-level normalization belongs at file-like entry points when a
184 shared preprocessor function also processes inline macro fragments. The narrow
185 entry layer is earlier and safer than changing the deepest shared routine.
186
187 Syntactic distinctions belong in the grammar and AST. Route them through
188 AST-to-ASR into the same canonical semantic form as equivalent syntax rather
189 than adding a backend special case.
190
191 Parser and grammar actions must still construct AST for semantically invalid
192 input. Perform duplicate-name checks, type restrictions, and other semantic
193 validation in AST-to-ASR, where diagnostics have precise entity locations and
194 continue-compilation recovery is available.
195
196 Treat lexer and grammar as one interface. Every newly emitted token needs a
197 matching grammar production and parser-level test in the same change; audit all
198 sibling lexer paths that emit it. When a construct must compose in several list
199 contexts, extend the singular per-item production so all existing list wrappers
200 inherit it rather than patching every concatenation rule.
201
202 ## 9. Add ASR passes selectively
203
204 A new ASR pass is appropriate when it:
205
206 - performs a coherent non-local transformation;
207 - gives several consumers one canonical representation;
208 - replaces duplicated complex algorithms;
209 - establishes a clear, verifiable output invariant; and
210 - has understandable ordering and can be tested independently.
211
212 Prefer an ASR field plus verifier, an existing pass, or direct AST-to-ASR
213 construction for local decisions. Every new pass adds compile time, ordering
214 dependencies, maintenance, and another failure boundary.
215
216 A new ASR node is not reviewable until exhaustive consumers have a minimal,
217 correct case for it: verifier, dependency walkers, serializers, and round-trip
218 printers. A reachable "not implemented" path in one of these consumers is a
219 blocker. Prefer inspecting a new transformation through Fortran regenerated
220 from its output ASR; reserve raw serialized-ASR assertions for narrow details.
221
222 Capability signals are user contracts. Do not change a supported-kind check,
223 sentinel, or intrinsic-module constant to advertise a feature until it works
224 end-to-end on every claimed target. Keep partial support marked unsupported or
225 place it behind an explicit opt-in.
226
227 ## 10. Keep backend changes mechanical
228
229 Some target-specific work cannot move earlier. In that case:
230
231 - keep the branch small and local;
232 - reuse `asr_to_llvm`, `llvm_utils`, `ASRUtils`, and existing helpers;
233 - avoid duplicated loop builders and long one-off blobs;
234 - do not hard-code argument positions or kinds;
235 - make target conditions explicit; and
236 - require ASR to provide every semantic decision the backend needs.
237
238 Hide toolchain-version differences behind one version-independent helper with
239 the conditional isolated inside it. Repeating the same version guard at several
240 call sites is a rework finding. Explain long pointer, descriptor, and stride
241 logic in semantic terms, then shrink it to a few calls or decompose it into
242 named helpers that reuse existing utilities.
243
244 ## 11. Keep changes narrow and reviewable
245
246 Separate behavioral changes from formatting, generated-output churn, broad
247 refactoring, and unrelated cleanup. Avoid shifting a large reference output for
248 one small diagnostic. Make preparatory mechanical changes separately when they
249 would otherwise obscure the behavior under review.
250
251 Be especially careful when weakening safety or CI checks. Add a negative test
252 that proves the check still rejects its target.
253
254 For external-project failures, first identify which compiler, runtime, or
255 dependency fails. Do not import an upstream disable patch or skip broad coverage
256 when the failure belongs to a different toolchain. If quarantine is unavoidable,
257 make it narrow, link it to a tracked defect, and preserve all unaffected
258 coverage.
259
260 Distinguish gratuitous reference churn from necessary serialization changes.
261 Adding an ASR field can legitimately regenerate many outputs; review those
262 changes for mechanical consistency and keep unrelated behavioral changes out of
263 the same regeneration.
264
265 Build-system changes must track the files they consume through dependency lists
266 or reconfigure-on-change mechanisms, quote paths that can contain spaces, and
267 fail during configuration when a required generated artifact cannot exist.
268 Do not commit binary blobs or large generated payloads when a small textual
269 fixture or generated test can exercise the same behavior.
270
271 Comments must describe implemented behavior. A comment claiming a dispatch,
272 delegation, or fallback that does not exist is a defect; recheck comments when a
273 pass is renamed or restructured. Regenerate toolchain-sensitive reference output
274 with the project's pinned or minimum supported toolchain rather than an
275 arbitrary local version. Remove dead code introduced by the change, and move
276 incidental discoveries into separate tracked work instead of expanding scope.
277
278 ## 12. Distinguish blockers from follow-ups
279
280 An acceptable incremental change can still leave bounded debt. Classify it
281 explicitly:
282
283 - **Blocker:** wrong semantics, invalid ASR, regression, unsafe error handling,
284 or untested core behavior.
285 - **Rework:** placement or maintainability problem that shapes the current
286 implementation and should be fixed before merging.
287 - **Follow-up:** bounded debt that does not invalidate the current change.
288
289 State the exact test, invariant, or refactor required by a follow-up. Do not let
290 approval of the overall direction hide a known correctness issue.
291
292 Treat findings from static analyzers and automated review tools as hypotheses.
293 Confirm the failure with an MRE, understand the causal path, and then report the
294 verified defect in the reviewer's own technical explanation.