rucc_codegen/coverage.rs
1//! Which IR opcodes have somewhere to go, and which do not.
2//!
3//! Design: `spec/10-backend.md` section 10.2, under **Coverage**.
4//!
5//! Every opcode has to be lowered by something or be a hole somebody wrote down. Without this the
6//! way a hole is found is that somebody compiles a program containing one and the selector reports
7//! that it cannot lower an instruction, which is a fine diagnostic and a bad discovery mechanism:
8//! it turns a gap in the rule set into a user's problem rather than a failing build.
9//!
10//! # The three answers
11//!
12//! An opcode is lowered by a rule, or somewhere a rule cannot reach, or nowhere.
13//!
14//! The first is the ordinary answer and the one this can check by itself. [`crate::term`] says
15//! every name a rule could be written at, the table says every name one is written at, and an
16//! opcode is covered when each of its names is in both. That is what makes this a check about
17//! widths rather than about opcodes: an `add` with a rule at four widths and no rule at the fifth
18//! is not covered, and would be reported here as the missing name rather than as a covered opcode.
19//!
20//! The second is a lowering, which is not a gap. `spec/10-backend.md` names five of them and there
21//! are more now, and they are all the same kind of thing: an opcode whose lowering depends on
22//! something no pattern can see. Where a call's arguments go depends on the signature, where a
23//! local lives depends on the frame, an unconditional jump is an edge and edges live on the block,
24//! and a `memcpy` is a run of moves whose length is a constant the pattern would have to count. A
25//! rule matches one term and can say none of that. Which opcodes those are is
26//! [`crate::capability::lowering`] and is not written down here, because it was written down here
27//! and in the lowering group both and the two could disagree.
28//!
29//! The third is [`GAPS`], which is the number `spec/15-testing.md` section 15.8 says we keep. Each
30//! entry names why it is there and the issue that closes it, so that an opcode nobody has written a
31//! rule for is a decision somebody wrote down rather than a surprise.
32//!
33//! [`WIDTHS`] and [`NAMES`] are the same third answer said about something smaller than an opcode.
34//! A width on [`WIDTHS`] has no names at all, so no opcode is missing a rule at it, and a name on
35//! [`NAMES`] is one width of an opcode that lowers at its other widths. Both carry the issue that
36//! closes them for the same reason [`GAPS`] does.
37//!
38//! # What makes the lists honest
39//!
40//! An entry that stops being true fails. An opcode on either list that a rule starts covering is a
41//! stale entry and the tests below say so by name, which is the same rule the exclusion lists in
42//! the compatibility harness are kept under: a list nothing checks is a list that only grows.
43//!
44//! The direction this cannot check is an opcode moving from [`GAPS`] to a hand written lowering
45//! without [`crate::capability::HAND`] following it, because where an opcode is lowered by name is
46//! a `match` arm and there is nothing to ask about a `match` arm from here. What that costs is one
47//! line of a list going out of date; what it does not cost is a gap going unnoticed, since the
48//! opcode is still on a list and still counted.
49//!
50//! # The other question
51//!
52//! All of the above is about the rule set as it is written. [`Fired`] is about the rule set as it
53//! is used: which rules a compilation actually reached. A rule nothing reaches is proved and dead
54//! weight, or it is a construct the corpus does not contain and somebody should know which. The
55//! selector marks a rule as it fires it, the driver writes the marks out under
56//! `-Zrule-coverage=FILE`, and the harness in `tamnd/rucc-compat` unions those files over a corpus,
57//! which is what turns coverage of the rule set into a number. `spec/20-execution-testing.md`
58//! section 20.9 is the design and `tamnd/rucc#261` is the work.
59
60use core::fmt;
61use core::fmt::Write as _;
62
63use rucc_ir::Opcode;
64use rucc_target::Arch;
65
66use crate::capability::{self, pattern_heads};
67use crate::select::Table;
68use crate::term;
69
70/// An opcode nothing lowers, why it is here, and the issue that closes it.
71///
72/// This is the count `spec/15-testing.md` section 15.8 asks for. It is not zero yet and the
73/// spec says it should be, which is the honest reading of where the back end is: every one of
74/// these is a feature nobody has written, and all of them but one are opcodes the front end
75/// cannot produce either, so a program that reaches one of these is a program that reaches an
76/// unimplemented builtin first. The one is the remainder of two floats, which a program writes
77/// with an operator and which is a call to the maths library rather than an instruction.
78pub static GAPS: &[(Opcode, &str, &str)] = &[
79 (Opcode::Splat, "a vector, and no rule is written about a lane count", "tamnd/rucc#200"),
80 (
81 Opcode::TargetIntrinsic,
82 "the same, since what needs one is a vector builtin",
83 "tamnd/rucc#200",
84 ),
85 (
86 Opcode::FRem,
87 "a call to `fmod`, so a link line question as much as a lowering one",
88 "tamnd/rucc#226",
89 ),
90 (
91 Opcode::Fma,
92 "a call or one instruction, depending on what the machine is told it has",
93 "tamnd/rucc#226",
94 ),
95 (Opcode::Bitreverse, "a node nothing writes and nothing lowers", "tamnd/rucc#363"),
96 (Opcode::TailCall, "a terminator nothing writes and nothing lowers", "tamnd/rucc#365"),
97 // Memory safety. These are a gap in a different sense from the rest: nothing emits one yet
98 // either, since the passes that would are milestones S5 and after, so there is no program the
99 // back end can be handed that reaches one. The ones the safety pass lowers are on `HAND`,
100 // and the five that make a capability all left this list without anything emitting them, which
101 // is the whole of tamnd/rucc#1085's lowering half: each has a lowering waiting for the pass that
102 // will write one, because a capability had to be a value the back end could hold before any of
103 // them could be written down at all. The two region markers left the same way and for a
104 // different reason, which is that what they cost is a count rather than a lowering.
105 // What is left is the plane writes, which the runtime does for itself today because the only
106 // ranges anything asks about are the ones its own allocator handed out. A stack object needs
107 // these, since nothing in the runtime sees a frame being set up or torn down.
108 (Opcode::MetaBegin, "a write over a range of the lifetime plane", "tamnd/rucc#856"),
109 (
110 Opcode::MetaEnd,
111 "the same write, with the version bumped past every capability",
112 "tamnd/rucc#856",
113 ),
114 (
115 Opcode::MetaTransfer,
116 "the same, and the state a range is in while a device owns it, which is S2's",
117 "tamnd/rucc#856",
118 ),
119];
120
121/// A width no rule is written at, why, and the issue that closes it.
122///
123/// The other half of coverage, and the half an opcode list cannot say. An opcode is covered when
124/// every name it has is a name a rule is written at, and a width with no name has no names to
125/// check: an `add` of two `__int128`s is not a missing rule for `add`, it is a width the rule
126/// language cannot spell. So the widths are written down here for the same reason the opcodes are
127/// written down above.
128pub static WIDTHS: &[(&str, &str, &str)] = &[
129 (
130 "one bit",
131 "everything but and, or, xor, a constant, and the widening out of one",
132 "tamnd/rucc#352",
133 ),
134 (
135 "a hundred and twenty eight bits",
136 "split into two halves before selection, except a division",
137 "tamnd/rucc#351",
138 ),
139 (
140 "eighty bits",
141 "a long double is on the x87 stack and no rule is about that stack",
142 "tamnd/rucc#326",
143 ),
144 (
145 "a hundred and twenty eight bits of float",
146 "turned into a call before selection, except a conditional move and the conversions \
147 against an integer that wide",
148 "tamnd/rucc#1064",
149 ),
150 (
151 "a vector of any lane count",
152 "a rule at a width says nothing about how many lanes",
153 "tamnd/rucc#200",
154 ),
155];
156
157/// A name a rule could be written at and deliberately is not, why, and the issue that puts it
158/// back.
159///
160/// The third list, and the one that is about a name rather than about an opcode or a width. An
161/// opcode on [`GAPS`] has no lowering at any width and a width on [`WIDTHS`] has no names at all,
162/// and neither of those can say that `add` is lowered at four widths and left alone at two.
163///
164/// This list used to be all of the narrow arithmetic. C promotes the operands of an arithmetic
165/// operator to `int` before the operator is applied, so `char a, b; a + b` is an `int` addition of
166/// two sign extended chars and there is no C program that asks the back end to add two bytes.
167/// Rules were written at those names anyway, ahead of the pass that would reach them, and they sat
168/// proved and never selected: `tamnd/rucc#261` measured that and `tamnd/rucc#368` took them out.
169/// Most of them are back, because the width narrowing pass in `tamnd/rucc#375` is that caller and
170/// it writes a byte add out of the truncation the assignment back to a `char` already was.
171///
172/// What is left is what the pass will not narrow. A divide is not narrowed because the most
173/// negative byte over minus one is a defined hundred and twenty eight at four bytes and is the
174/// overflow that raises at one, so it wants a range analysis saying that pair cannot happen.
175///
176/// Not every narrow name was ever here, because promotion is not the only way a narrow operation
177/// is born. Reading a bitfield is a shift and a mask by constants at the width of the storage
178/// unit, writing one is a mask, a shift and an `or` of two values, and a truth test on a narrow
179/// scalar is an `icmp_ne` at that scalar's width. Those fire, so those always had rules.
180pub static NAMES: &[(&str, &str, &str)] = &[
181 ("sdiv.i8", "a narrow divide, which wants a range analysis before it can be narrowed", NARROW),
182 ("sdiv.i16", "the same", NARROW),
183 ("udiv.i8", "the same", NARROW),
184 ("udiv.i16", "the same", NARROW),
185 ("srem.i8", "the same", NARROW),
186 ("srem.i16", "the same", NARROW),
187 ("urem.i8", "the same", NARROW),
188 ("urem.i16", "the same", NARROW),
189];
190
191/// The issue every entry of [`NAMES`] waits on, since they all wait on the same one.
192const NARROW: &str = "tamnd/rucc#375";
193
194/// What a target's rules cover, and what they do not.
195#[derive(Debug)]
196pub struct Report {
197 /// The rule file this is about, so that anything said about it names a file to open.
198 pub source: &'static str,
199 /// How many opcodes the IR has.
200 pub opcodes: usize,
201 /// The opcodes every name of which a rule is written at.
202 pub by_rule: Vec<Opcode>,
203 /// How many names those are, which is one per opcode and width.
204 pub names: usize,
205 /// A name a rule could be written at and none is, which is what a missing rule looks like.
206 pub uncovered: Vec<(Opcode, &'static str)>,
207 /// A name on [`NAMES`], which is a missing rule somebody decided to be missing.
208 pub deferred: Vec<(Opcode, &'static str)>,
209 /// A name a rule is written at that nothing can ever be called, which is a dead rule.
210 pub unreachable: Vec<&'static str>,
211 /// The opcodes lowered somewhere a rule cannot reach.
212 pub elsewhere: Vec<Opcode>,
213 /// The opcodes nothing lowers.
214 pub gaps: Vec<Opcode>,
215 /// The opcodes on none of the three lists, which is what a new opcode is until somebody says
216 /// where it goes.
217 pub unaccounted: Vec<Opcode>,
218}
219
220impl fmt::Display for Report {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 write!(
223 f,
224 "rucc-codegen: {} lowers {} of the {} IR opcodes by rule at {} names, {} are lowered \
225 where no rule reaches, {} have no lowering yet and {} names are left for later",
226 self.source,
227 self.by_rule.len(),
228 self.opcodes,
229 self.names,
230 self.elsewhere.len(),
231 self.gaps.len(),
232 self.deferred.len()
233 )
234 }
235}
236
237/// What a table covers.
238///
239/// Nothing is executed and nothing is compiled. The rule set and the naming of instructions are
240/// both data, and the answer is a comparison of two lists.
241#[must_use]
242pub fn report(table: &Table) -> Report {
243 let named = term::heads();
244 let patterns = pattern_heads(table);
245
246 let mut by_rule = Vec::new();
247 let mut uncovered = Vec::new();
248 let mut deferred = Vec::new();
249 for &(opcode, name) in &named {
250 if patterns.contains(&name) {
251 by_rule.push(opcode);
252 } else if NAMES.iter().any(|&(deliberate, ..)| deliberate == name) {
253 deferred.push((opcode, name));
254 } else {
255 uncovered.push((opcode, name));
256 }
257 }
258 // An opcode is covered when every name it has is covered, so one missing width takes the
259 // whole opcode off the list however many of its other widths are there. A name on `NAMES` does
260 // not take it off, because the opcode is lowered and the entry says which widths were left for
261 // later and why: that is a narrower claim than the opcode having nowhere to go, and putting it
262 // on `GAPS` instead would say the wrong thing about an `add` that lowers perfectly well at
263 // four widths.
264 for &(opcode, _) in &uncovered {
265 by_rule.retain(|&covered| covered != opcode);
266 }
267 by_rule.sort_unstable();
268 by_rule.dedup();
269
270 let names = named.len() - uncovered.len() - deferred.len();
271 let unreachable: Vec<&'static str> = patterns
272 .iter()
273 .filter(|head| !named.iter().any(|(_, name)| name == *head))
274 .copied()
275 .collect();
276
277 let elsewhere: Vec<Opcode> =
278 Opcode::all().filter(|&opcode| capability::lowering(opcode).is_some()).collect();
279 let gaps: Vec<Opcode> = GAPS.iter().map(|&(opcode, ..)| opcode).collect();
280 let unaccounted: Vec<Opcode> = Opcode::all()
281 .filter(|opcode| {
282 !by_rule.contains(opcode)
283 && !elsewhere.contains(opcode)
284 && !gaps.contains(opcode)
285 && !capability::LIBCALLS.iter().any(|&(at, ..)| at == *opcode)
286 })
287 .collect();
288
289 Report {
290 source: table.source,
291 opcodes: Opcode::all().count(),
292 by_rule,
293 names,
294 uncovered,
295 deferred,
296 unreachable,
297 elsewhere,
298 gaps,
299 unaccounted,
300 }
301}
302
303/// The rules a target lowers by, or `None` where no back end in this crate covers it.
304///
305/// The same question [`crate::pipeline::Machine::for_target`] answers about the rest of a machine,
306/// and it is here as well because a caller that wants to write down what a run covered has a
307/// target and no machine. An architecture that gets a rule file at M6 gets an arm here at the same
308/// time, and until then it has no rules to report coverage of rather than an empty set of them.
309#[must_use]
310pub fn table(arch: Arch) -> Option<&'static Table> {
311 match arch {
312 Arch::X86_64 => Some(&crate::select::x86_64::TABLE),
313 Arch::Aarch64 | Arch::Riscv64 => None,
314 }
315}
316
317/// Which rules fired, over one function or over a whole compilation.
318///
319/// A bit per rule and nothing else. This is on the path of every instruction selected, so what it
320/// costs is paid by every compilation whether or not anybody asked for the number, and the cheapest
321/// thing that answers the question is a flag per rule set once.
322///
323/// The index of a rule is how this is kept and not how it is written down. An index moves the
324/// moment a rule is added above it, so [`Fired::listing`] names the rule file and the line instead:
325/// a line is a place somebody can open, and a report written by one build can still be read against
326/// a rule file that has grown since.
327#[derive(Debug, Clone, Default, PartialEq, Eq)]
328pub struct Fired {
329 /// One entry per rule, true once that rule has fired. It grows to fit the highest index
330 /// marked rather than being sized from a table, so nothing here has to be told which target
331 /// is being compiled for.
332 seen: Vec<bool>,
333}
334
335impl Fired {
336 /// Nothing has fired yet.
337 #[must_use]
338 pub const fn new() -> Fired {
339 Fired { seen: Vec::new() }
340 }
341
342 /// Records that the rule at this index fired.
343 pub fn mark(&mut self, rule: usize) {
344 if self.seen.len() <= rule {
345 self.seen.resize(rule + 1, false);
346 }
347 self.seen[rule] = true;
348 }
349
350 /// Whether the rule at this index fired.
351 #[must_use]
352 pub fn has(&self, rule: usize) -> bool {
353 self.seen.get(rule).copied().unwrap_or(false)
354 }
355
356 /// How many rules fired.
357 #[must_use]
358 pub fn count(&self) -> usize {
359 self.seen.iter().filter(|fired| **fired).count()
360 }
361
362 /// Takes in everything another one recorded.
363 ///
364 /// One compilation is many functions and one command line is many files, and the question is
365 /// about all of them together. Merging rather than writing a file per function is also what
366 /// keeps the answer the same however the work was scheduled.
367 pub fn merge(&mut self, other: &Fired) {
368 if self.seen.len() < other.seen.len() {
369 self.seen.resize(other.seen.len(), false);
370 }
371 for (mine, theirs) in self.seen.iter_mut().zip(&other.seen) {
372 *mine |= *theirs;
373 }
374 }
375
376 /// What `-Zrule-coverage=FILE` writes.
377 ///
378 /// One line per rule in the table, in the order the rule file writes them, each saying whether
379 /// the rule fired and naming the file and line it is written at. Every rule is listed rather
380 /// than only the ones that fired, so that one of these files says what the whole rule set was
381 /// as well as what this compilation reached: a reader unioning them over a corpus needs both
382 /// and would otherwise have to parse the rule file to get the second.
383 ///
384 /// The first line is a comment holding the count, which is the number a person wants and the
385 /// one thing here that is not worth making them add up.
386 #[must_use]
387 pub fn listing(&self, table: &Table) -> String {
388 let fired = table.rules.iter().enumerate().filter(|(index, _)| self.has(*index)).count();
389 let mut out = format!(
390 "# rucc rule coverage: {fired} of {} rules in {} fired\n",
391 table.rules.len(),
392 table.source
393 );
394 for (index, rule) in table.rules.iter().enumerate() {
395 let word = if self.has(index) { "fired" } else { "unused" };
396 let _ = writeln!(out, "{word} {}:{} {}", table.source, rule.line, rule.pattern);
397 }
398 out
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405 use crate::select::x86_64::TABLE;
406
407 /// The claim the whole module is for, in the direction that matters: a name an instruction
408 /// can be called by is a name a rule is written at. This is the width check as much as the
409 /// opcode check, since a name is an opcode and a width together.
410 #[test]
411 fn every_name_an_instruction_can_have_is_one_a_rule_is_written_at() {
412 let report = report(&TABLE);
413 assert!(
414 report.uncovered.is_empty(),
415 "nothing in {} lowers these, and each is an opcode at a width the rule language can \
416 spell: {:?}",
417 report.source,
418 report.uncovered
419 );
420 }
421
422 /// And the other direction, which costs nothing to ask and finds a rule that can never fire.
423 /// A pattern head no instruction is ever called by is a rule written against a name that was
424 /// renamed or misspelled, and it would sit there proved and unreachable.
425 #[test]
426 fn every_name_a_rule_is_written_at_is_one_an_instruction_can_have() {
427 let report = report(&TABLE);
428 assert!(
429 report.unreachable.is_empty(),
430 "{} has rules for these and no instruction is ever called one: {:?}",
431 report.source,
432 report.unreachable
433 );
434 }
435
436 /// Every opcode is one of the three things, so a new opcode in the IR fails this until
437 /// somebody says where it goes. That is the whole point: the answer for a new opcode should
438 /// be written down when it is added rather than discovered by a user compiling a program.
439 #[test]
440 fn every_opcode_is_lowered_or_is_a_gap_somebody_wrote_down() {
441 let report = report(&TABLE);
442 assert!(
443 report.unaccounted.is_empty(),
444 "no rule lowers these, nothing rewrites them before selection, no runtime function \
445 stands for them and `GAPS` does not say why: {:?}",
446 report.unaccounted
447 );
448 }
449
450 /// An entry that starts being covered fails, which is the rule every list in this project is
451 /// kept under. An opcode a rule now lowers is one that should be off both lists, and a list
452 /// that keeps claiming otherwise is a list nobody can read.
453 #[test]
454 fn an_entry_a_rule_now_covers_is_a_stale_entry() {
455 let report = report(&TABLE);
456 for &(opcode, where_) in capability::HAND {
457 assert!(
458 !report.by_rule.contains(&opcode),
459 "`{}` is lowered by a rule now, so the `HAND` entry saying it is lowered by \
460 {where_} is stale",
461 opcode.name()
462 );
463 }
464 for &(opcode, why, issue) in GAPS {
465 assert!(
466 !report.by_rule.contains(&opcode),
467 "`{}` is lowered by a rule now, so the `GAPS` entry saying it is {why} is stale \
468 and {issue} may be closed",
469 opcode.name()
470 );
471 assert!(
472 !report.elsewhere.contains(&opcode),
473 "`{}` is on both lists, so it is both lowered and not lowered",
474 opcode.name()
475 );
476 }
477 }
478
479 /// The same staleness rule one list down. A name a rule is written at is a name that is not
480 /// left for later, and an entry claiming otherwise is one that should have gone when the rule
481 /// arrived. The other direction is checked too: a name no instruction can ever have is a
482 /// misspelling, and it would sit here excusing nothing.
483 #[test]
484 fn a_name_a_rule_is_written_at_is_not_a_name_left_for_later() {
485 let heads = pattern_heads(&TABLE);
486 let named = term::heads();
487 for &(name, why, issue) in NAMES {
488 assert!(
489 !heads.contains(&name),
490 "`{name}` is lowered by a rule now, so the `NAMES` entry saying it is {why} is \
491 stale and {issue} may be closer than it says"
492 );
493 assert!(
494 named.iter().any(|&(_, head)| head == name),
495 "`{name}` is not a name any instruction can have, so the `NAMES` entry excuses \
496 nothing"
497 );
498 }
499 let report = report(&TABLE);
500 assert_eq!(report.deferred.len(), NAMES.len(), "{:?}", report.deferred);
501 }
502
503 /// Every gap names an issue, since a gap with no issue behind it is a gap nobody has decided
504 /// anything about, which is the thing this module exists to stop.
505 #[test]
506 fn every_gap_names_the_issue_that_closes_it() {
507 let issues = GAPS
508 .iter()
509 .map(|&(_, _, issue)| issue)
510 .chain(WIDTHS.iter().map(|&(_, _, issue)| issue))
511 .chain(NAMES.iter().map(|&(_, _, issue)| issue));
512 for issue in issues {
513 let number = issue
514 .strip_prefix("tamnd/rucc#")
515 .unwrap_or_else(|| panic!("{issue} is not an issue in this project's tracker"));
516 assert!(number.parse::<u32>().is_ok(), "{issue} does not name an issue number");
517 }
518 }
519
520 /// The count, which `spec/15-testing.md` section 15.8 says we keep about ourselves. CI runs
521 /// this test with the output shown, so the number lands in a log next to the rule proof
522 /// rather than in a file somebody has to go and read.
523 #[test]
524 fn the_count_is_reported() {
525 let report = report(&TABLE);
526 println!("{report}");
527 for &(opcode, why, issue) in GAPS {
528 println!("rucc-codegen: no lowering for `{}`, which is {why}: {issue}", opcode.name());
529 }
530 for &(width, why, issue) in WIDTHS {
531 println!("rucc-codegen: no rule at {width}, which is {why}: {issue}");
532 }
533 for &(name, why, issue) in NAMES {
534 println!("rucc-codegen: no rule at `{name}`, which is {why}: {issue}");
535 }
536 assert_eq!(report.gaps.len(), GAPS.len());
537 }
538
539 /// What the root of the trie is, which is the assumption [`pattern_heads`] rests on. If the
540 /// rule compiler ever built the trie some other way this would say so, rather than the
541 /// coverage numbers quietly becoming a report about an empty list.
542 #[test]
543 fn the_root_of_the_trie_is_the_head_of_every_pattern() {
544 let heads = pattern_heads(&TABLE);
545 assert!(!heads.is_empty(), "the table has rules and the root of the trie tests nothing");
546 for rule in TABLE.rules {
547 let head = rule
548 .pattern
549 .strip_prefix('(')
550 .and_then(|rest| rest.split([' ', ')']).next())
551 .expect("a pattern is an application");
552 assert!(
553 heads.contains(&head),
554 "line {}: {} is a pattern whose head the root of the trie does not test",
555 rule.line,
556 rule.pattern
557 );
558 }
559 }
560
561 /// The one target with a rule file, and the two that get one at M6. A machine that can be
562 /// compiled for has rules to report the coverage of, and one that cannot has none rather than
563 /// an empty set of them, which are different answers and would read the same as a number.
564 #[test]
565 fn a_target_with_a_back_end_is_a_target_with_a_rule_set() {
566 let x86 = table(Arch::X86_64).expect("x86-64 is what this crate lowers for");
567 assert_eq!(x86.source, TABLE.source);
568 assert!(!x86.rules.is_empty());
569 assert!(table(Arch::Aarch64).is_none(), "there is no aarch64 rule file yet");
570 assert!(table(Arch::Riscv64).is_none(), "there is no riscv64 rule file yet");
571 }
572
573 /// What a rule is called outside this process. The index is not it: a rule added at the top of
574 /// the file moves every index below it, and a report from last week would then be a report
575 /// about the wrong rules. The file and the line do not move that way and are somewhere to look.
576 #[test]
577 fn a_rule_is_written_down_as_the_place_it_is_written_at() {
578 let mut fired = Fired::new();
579 fired.mark(0);
580 let listing = fired.listing(&TABLE);
581 let first =
582 format!("fired {}:{} {}", TABLE.source, TABLE.rules[0].line, TABLE.rules[0].pattern);
583 assert!(listing.contains(&first), "{listing}");
584 assert!(listing.lines().next().is_some_and(|line| line.starts_with('#')), "{listing}");
585 }
586
587 /// Every rule is listed and not only the ones that fired, which is what lets one of these files
588 /// be read on its own. A reader that only got the rules that fired would have to parse the rule
589 /// file to find out what the rest of them were.
590 #[test]
591 fn one_file_says_what_the_whole_rule_set_is() {
592 let listing = Fired::new().listing(&TABLE);
593 let lines: Vec<&str> = listing.lines().collect();
594 assert_eq!(lines.len(), TABLE.rules.len() + 1, "one line per rule and one for the count");
595 assert_eq!(
596 lines.iter().filter(|line| line.starts_with("unused ")).count(),
597 TABLE.rules.len()
598 );
599 assert!(lines[0].contains(&format!("0 of {} rules", TABLE.rules.len())), "{}", lines[0]);
600 }
601
602 /// A compilation is many functions and a command line is many files, and the question is about
603 /// all of them at once. Merging is also what keeps the answer the same however the work was
604 /// scheduled, which is the rule `spec/03-architecture.md` section 3.7 holds everything to.
605 #[test]
606 fn what_two_runs_reached_is_what_either_of_them_reached() {
607 let mut one = Fired::new();
608 one.mark(3);
609 one.mark(3);
610 assert_eq!(one.count(), 1, "a rule that fires twice is one rule");
611 let mut two = Fired::new();
612 two.mark(0);
613 two.mark(9);
614 one.merge(&two);
615 assert_eq!(one.count(), 3);
616 assert!(one.has(0) && one.has(3) && one.has(9));
617 assert!(!one.has(1));
618
619 // The merge is symmetric, since neither order of two files is the right one.
620 let mut back = Fired::new();
621 back.mark(0);
622 back.mark(9);
623 let mut three = Fired::new();
624 three.mark(3);
625 back.merge(&three);
626 assert_eq!(back, one);
627 }
628}