rucc_base/rules.rs
1//! Matching a set of rules against a term.
2//!
3//! Design: `spec/10-backend.md` section 10.2 and `spec/optimizer/13-rewrite-rules.md`. The rules
4//! themselves are rule files, one per rule set, and the automaton they compile into is generated
5//! by `rucc-rules` when the crate that owns the file is built. What is here is the walk over
6//! that automaton, which is the same walk for every rule set and is written once.
7//!
8//! # Why this is at the bottom of the stack
9//!
10//! Two crates match with a generated table and neither can see the other. `rucc-codegen` lowers
11//! IR to machine terms and `rucc-opt` rewrites IR to IR, and a lowering and a rewrite are the
12//! same claim about two terms, so they are the same trie and the same walk. Putting the walk
13//! here rather than in either of them is what keeps that true rather than merely intended, and
14//! it costs nothing: none of this knows what an instruction is, what a value is, or what C is.
15//!
16//! # What a subject is
17//!
18//! A rule matches a term, and the compiler does not have terms: it has a function full of
19//! instructions, and what a pattern is about is one of them and whatever it was computed from.
20//! So the walk is written against [`Subject`], which is the three questions the automaton asks
21//! of whatever it is matching, and a caller answers them out of the IR without building a term
22//! to be thrown away. A test can answer them out of anything at all, which is what the tests at
23//! the bottom of this file do.
24//!
25//! # What a match gives back
26//!
27//! The rule that fired and what its pattern bound, in the order the pattern binds it. The
28//! bindings are positions rather than names because that is what the walk has, and the rule
29//! carries the names for anything that has to say what it did. Building the replacement out of
30//! [`Piece`] belongs to the caller rather than to this file, because what a replacement becomes
31//! is a machine instruction in one crate and an IR instruction in the other, and this module is
32//! about matching.
33//!
34//! # A name written twice
35//!
36//! A pattern may write one name in two places, which is how `x & x` is said. The second place
37//! becomes a branch in [`Node::same`] rather than a hole, and it asks the subject whether the two
38//! are the same thing rather than comparing nodes, because a node is a place and two places can
39//! hold one value. It is a concrete test, so it is tried before the wildcard for the same reason
40//! every other test is: a rule about one value in both operands is more specific than a rule
41//! about any two.
42//!
43//! # Order
44//!
45//! At every node the concrete tests are tried before the branch that takes anything, so a rule
46//! naming an operand is tried before a rule taking whatever is there. That is the maximal munch
47//! `spec/10-backend.md` asks for, and it falls out of the shape of the trie rather than being
48//! sorted for. Among rules that are equally specific the first one written wins.
49//!
50//! The concrete tests are three kinds of question and they are asked in this order: the head of
51//! the term, then its value as a constant, then whether it is what an earlier binding took.
52//! `spec/optimizer/36-lowering-and-isel.md` section 36.5 asks that the order be stated rather
53//! than left to be read out of what the matcher does, so it is stated here, next to the walk that
54//! applies it. It decides nothing in any rule set shipped today, because deciding something would
55//! need one node to ask two kinds of question about one place and none does, which is a number
56//! `rucc-rules` prints in the header of every table it generates.
57//!
58//! # Finding a branch
59//!
60//! A term has one head and a constant has one value, so at most one head branch and at most one
61//! value branch can match, and the two lists are sorted by the thing they are asked about. That
62//! makes finding the branch a binary search rather than a walk over the node, which is the
63//! difference section 36.5 is about: the widest node of the x86-64 rule set has a hundred and
64//! sixty seven heads on it, and the selector reaches that node once for every instruction in the
65//! program. A repeat of an earlier binding is not searchable, because two of them can hold the
66//! same value, so those stay in the order the rules were written and there are never many.
67//!
68//! A guard is part of deciding whether a rule fires, so a rule whose guard is false is a rule
69//! that did not match, and the walk carries on looking rather than giving up. What that costs is
70//! the search from where the guard failed, which is the price of a guard being allowed to be
71//! about the values rather than only about the shape.
72//!
73//! Two rules can end at the same node when the earlier one has a guard, which is how one pattern
74//! gets a different answer for different constants. They are tried in the order the rule file
75//! writes them and the first whose guard holds fires.
76
77/// The bits of a term the automaton asks about.
78///
79/// A node is whatever the thing doing the matching calls one of its terms: an IR value, an index
80/// into an arena, a pointer. It has to be cheap to copy because the walk keeps a stack of them.
81pub trait Subject {
82 /// What this subject calls one of its terms.
83 type Node: Copy;
84
85 /// The head of a term and how many arguments it has, or nothing if the term is not an
86 /// application. An IR instruction answers with its opcode and its width, spelled the way the
87 /// rule file spells it.
88 fn head(&self, node: Self::Node) -> Option<(&str, usize)>;
89
90 /// One argument of a term, counted from zero. Only ever asked for an argument the answer to
91 /// [`Subject::head`] said was there.
92 fn arg(&self, node: Self::Node, index: usize) -> Self::Node;
93
94 /// The value of a term that is a constant, or nothing if it is not one. This is what a
95 /// pattern matching a literal is asking, and what a guard reads.
96 fn int(&self, node: Self::Node) -> Option<i128>;
97
98 /// Whether two terms are the same thing, which is what a pattern that writes one name in two
99 /// places is asking.
100 ///
101 /// This is a question for the subject rather than something the walk can answer by comparing
102 /// nodes, because a node is a place and two places can hold one value. In
103 /// `(and.i32 (value.i32 x) (value.i32 x))` the two operands are operand zero and operand
104 /// one, which are different places, and what the rule wants to know is whether the same
105 /// value is in both. A subject that cannot tell may answer `false`, which costs the rule a
106 /// match it could have had and never gives it one it should not.
107 fn same(&self, a: Self::Node, b: Self::Node) -> bool;
108}
109
110/// One node of the trie over the patterns.
111///
112/// The branches are held by the kind of question they ask rather than in one list, which is what
113/// lets the two that can be searched be searched.
114#[derive(Debug, Clone, Copy)]
115pub struct Node {
116 /// The branches taken on the head of the subterm, as the [`Node::key`] of the name, the name,
117 /// how many arguments it takes, and where to go. Sorted by the first three, which is what
118 /// [`Node::branch`] needs and is the same order as sorting by the name and the count.
119 pub heads: &'static [(u128, &'static str, usize, u32)],
120 /// The branches taken on the value of a subterm that is a constant, sorted by the value.
121 pub ints: &'static [(i128, u32)],
122 /// The branches taken when the subterm is the same thing as a binding this pattern already
123 /// made, named by which binding it is. A pattern writes one where it writes a name for the
124 /// second time, so this is how `x & x` is told apart from `x & y`. In the order the rules
125 /// were written, because two of them can match one subterm.
126 pub same: &'static [(usize, u32)],
127 /// The branch that takes anything, and the name the first rule to reach it gave that hole.
128 pub wildcard: Option<(&'static str, u32)>,
129 /// The rules that end here, in the order the rule file writes them. The first whose guard
130 /// holds is the one that fires, so every one of them but the last has a guard, which the rule
131 /// compiler checks.
132 pub accept: &'static [u32],
133}
134
135impl Node {
136 /// The branch for a term with this head and this many arguments, if the node has one.
137 ///
138 /// A binary search, which is the whole point of the list being sorted. At most one branch can
139 /// answer, so nothing about which rule fires depends on the list being in this order rather
140 /// than in the order the rules were written.
141 ///
142 /// Each step compares the keys first and only compares the names when the keys agree, which
143 /// for names no longer than sixteen bytes is only on the branch being looked for. Comparing
144 /// the names at every step called `memcmp` at every step, and that was most of what finding a
145 /// branch cost.
146 #[must_use]
147 pub fn branch(&self, head: &str, arity: usize) -> Option<u32> {
148 // The same number as `Node::key`, made with one copy rather than a byte at a time.
149 let mut bytes = [0; 16];
150 let take = head.len().min(16);
151 bytes[..take].copy_from_slice(&head.as_bytes()[..take]);
152 let key = u128::from_be_bytes(bytes);
153 let found = self
154 .heads
155 .binary_search_by(|(first, have, count, _)| {
156 first.cmp(&key).then_with(|| have.cmp(&head)).then(count.cmp(&arity))
157 })
158 .ok()?;
159 Some(self.heads[found].3)
160 }
161
162 /// The first sixteen bytes of a name as one number, padded with zeros, which orders the way
163 /// the names do.
164 ///
165 /// Reading the bytes most significant first makes comparing two of these the same as
166 /// comparing the bytes one at a time. A name never holds a zero byte, so the padding sorts
167 /// below every byte a name does hold and a name that runs out first is the smaller one, as it
168 /// should be. Two names with one key are only known to be equal when neither is longer than
169 /// sixteen bytes, which is why [`Node::branch`] compares the names as well. A table computes
170 /// the key of each of its names when it is compiled.
171 #[must_use]
172 pub const fn key(name: &str) -> u128 {
173 let bytes = name.as_bytes();
174 let mut key = 0;
175 let mut at = 0;
176 while at < 16 {
177 key <<= 8;
178 if at < bytes.len() {
179 key |= bytes[at] as u128;
180 }
181 at += 1;
182 }
183 key
184 }
185
186 /// The branch for a constant of this value, if the node has one.
187 #[must_use]
188 pub fn literal(&self, value: i128) -> Option<u32> {
189 let found = self.ints.binary_search_by(|(have, _)| have.cmp(&value)).ok()?;
190 Some(self.ints[found].1)
191 }
192}
193
194/// One piece of a replacement, in the pre-order that builds it.
195#[derive(Debug)]
196pub enum Piece {
197 /// Whatever the pattern bound at this position.
198 Var {
199 /// The name the rule gave it, for anything that has to say what it did.
200 name: &'static str,
201 /// Which binding of the match it is.
202 index: usize,
203 },
204 /// A constant written in the rule.
205 Int(i128),
206 /// A constant the rule works out from the ones the pattern matched.
207 ///
208 /// This is what lets a rule be written once per width rather than once per constant. A shift
209 /// that stands in for a multiplication by a power of two shifts by the log of that power, and
210 /// the log is a number no rule can write down until it has seen which power it matched.
211 Computed {
212 /// The computation as the rule file writes it, for anything that has to say what it did.
213 text: &'static str,
214 /// What it works out.
215 work: Computation,
216 },
217 /// A term the rule writes, which is an instruction once the caller has built it.
218 App {
219 /// The name in head position.
220 head: &'static str,
221 /// How many arguments it takes.
222 arity: usize,
223 },
224}
225
226/// A condition on the constants a pattern matched.
227///
228/// It is handed one entry per binding, holding the value of that binding when it has one. A
229/// guard about a binding that is not a constant is false, which is how a rule about a number
230/// declines an operand that is a register.
231pub type Guard = fn(&[Option<i128>]) -> bool;
232
233/// A number worked out from the constants a pattern matched.
234///
235/// Handed one entry per binding, the same as a [`Guard`] is, and for the same reason: the
236/// computation is written in the names the pattern bound and those are positions by the time it
237/// runs. It gives nothing back when a binding it reads is not a constant, which is the answer a
238/// guard gives as false, and the rule does not fire.
239pub type Computation = fn(&[Option<i128>]) -> Option<i128>;
240
241/// One rule, as much of it as matching needs.
242#[derive(Debug)]
243pub struct Rule {
244 /// The pattern as it is written in the rule file, for diagnostics and for tests.
245 pub pattern: &'static str,
246 /// What to put in the matched term's place, flattened into pre-order.
247 pub replacement: &'static [Piece],
248 /// The condition on the match, if the rule has one.
249 pub guard: Option<Guard>,
250 /// The line of the rule file this rule starts on.
251 pub line: u32,
252}
253
254impl Rule {
255 /// The head of the replacement, which is what this rule writes.
256 #[must_use]
257 pub fn head(&self) -> Option<&'static str> {
258 match self.replacement.first() {
259 Some(Piece::App { head, .. }) => Some(head),
260 _ => None,
261 }
262 }
263}
264
265/// A set of rules, as an automaton over their patterns.
266#[derive(Debug)]
267pub struct Table {
268 /// The rule file this was built from, so that anything said about a rule can name a file
269 /// somebody can open.
270 pub source: &'static str,
271 /// The trie. Node zero is the root.
272 pub nodes: &'static [Node],
273 /// The rules, in the order the file writes them.
274 pub rules: &'static [Rule],
275}
276
277/// What a successful match found.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct Match<N> {
280 /// Which rule of the table fired.
281 pub rule: usize,
282 /// What the pattern bound, in the order it binds it.
283 pub bindings: Vec<N>,
284}
285
286impl Table {
287 /// The rule that fires on this term, and what it bound.
288 ///
289 /// The term is matched as a whole. Finding the terms in a function worth matching is the
290 /// caller's job and not this one's.
291 #[must_use]
292 pub fn find<S: Subject>(&self, subject: &S, term: S::Node) -> Option<Match<S::Node>> {
293 let mut bindings = Vec::new();
294 let rule = self.run(subject, 0, &mut vec![term], &mut bindings)?;
295 Some(Match { rule, bindings })
296 }
297
298 /// The rule a match found, which is the one thing every caller wants out of it.
299 #[must_use]
300 pub fn rule<N>(&self, found: &Match<N>) -> &Rule {
301 &self.rules[found.rule]
302 }
303
304 /// Walk the trie and the subject together.
305 ///
306 /// `left` is the subterms still to be matched, innermost last, so that popping gives the
307 /// pre-order the patterns were flattened in. It is one stack for the whole walk rather than a
308 /// copy per branch, so a walk that finds nothing puts back what it took: the term it popped,
309 /// and through [`Table::take`] the arguments it pushed. What is on it after a match is not
310 /// anything anybody reads.
311 fn run<S: Subject>(
312 &self,
313 subject: &S,
314 at: usize,
315 left: &mut Vec<S::Node>,
316 bindings: &mut Vec<S::Node>,
317 ) -> Option<usize> {
318 let Some(term) = left.pop() else {
319 return self.accept(subject, at, bindings);
320 };
321 let node = &self.nodes[at];
322 let head = subject.head(term);
323
324 // The head of the term, which is the question nearly every branch of nearly every node
325 // is about and the one that has to be found rather than looked for.
326 if let Some(next) = head.and_then(|(name, arity)| node.branch(name, arity)) {
327 if let Some(rule) = self.take(subject, next, (term, head), left, bindings) {
328 return Some(rule);
329 }
330 }
331
332 // Its value, if it is a constant and if this node asks about one. The emptiness is
333 // checked first because asking the subject for a value costs something and most nodes
334 // have nothing to compare it against.
335 if !node.ints.is_empty() {
336 if let Some(next) = subject.int(term).and_then(|value| node.literal(value)) {
337 if let Some(rule) = self.take(subject, next, (term, head), left, bindings) {
338 return Some(rule);
339 }
340 }
341 }
342
343 // A repeat of an earlier binding. The binding is always there, because a pattern only
344 // writes a name for the second time after it has written it once and the trie keeps that
345 // order.
346 for &(index, next) in node.same {
347 if bindings.get(index).is_some_and(|&bound| subject.same(bound, term)) {
348 if let Some(rule) = self.take(subject, next, (term, head), left, bindings) {
349 return Some(rule);
350 }
351 }
352 }
353
354 // The wildcard is last, which is the whole of what specificity order means here.
355 if let Some((_, next)) = node.wildcard {
356 let depth = bindings.len();
357 bindings.push(term);
358 if let Some(rule) = self.run(subject, next as usize, left, bindings) {
359 return Some(rule);
360 }
361 bindings.truncate(depth);
362 }
363 left.push(term);
364 None
365 }
366
367 /// Follow one branch, and give the stack and the bindings back as they were if it led nowhere.
368 ///
369 /// What goes on the stack is the arguments of the term, innermost last, whenever the term has
370 /// any. That is the same for every kind of branch, because what a branch decided is that this
371 /// subterm is matched and the walk carries on into what is under it.
372 fn take<S: Subject>(
373 &self,
374 subject: &S,
375 next: u32,
376 term: (S::Node, Option<(&str, usize)>),
377 left: &mut Vec<S::Node>,
378 bindings: &mut Vec<S::Node>,
379 ) -> Option<usize> {
380 let (term, head) = term;
381 let height = left.len();
382 if let Some((_, arity)) = head {
383 for index in (0..arity).rev() {
384 left.push(subject.arg(term, index));
385 }
386 }
387 let depth = bindings.len();
388 if let Some(rule) = self.run(subject, next as usize, left, bindings) {
389 return Some(rule);
390 }
391 left.truncate(height);
392 bindings.truncate(depth);
393 None
394 }
395
396 /// The first rule that ends at this node whose guard holds, if there is one.
397 fn accept<S: Subject>(&self, subject: &S, at: usize, bindings: &[S::Node]) -> Option<usize> {
398 // The values are collected once and only when a guard asks, because most rules have no
399 // guard and would pay for it every time.
400 let mut values: Option<Vec<Option<i128>>> = None;
401 for &rule in self.nodes[at].accept {
402 let rule = rule as usize;
403 let Some(guard) = self.rules[rule].guard else { return Some(rule) };
404 let values = values
405 .get_or_insert_with(|| bindings.iter().map(|&node| subject.int(node)).collect());
406 if guard(values) {
407 return Some(rule);
408 }
409 }
410 None
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::{Match, Node, Piece, Rule, Subject, Table};
417
418 /// A term, in the only shape a test needs: a flat arena, because that is the shape the IR
419 /// has and answering the questions out of one is what the callers will be doing.
420 #[derive(Debug)]
421 enum Held {
422 Int(i128),
423 App(String, Vec<usize>),
424 }
425
426 #[derive(Debug, Default)]
427 struct Terms {
428 nodes: Vec<Held>,
429 }
430
431 impl Terms {
432 fn constant(&mut self, value: i128) -> usize {
433 self.nodes.push(Held::Int(value));
434 self.nodes.len() - 1
435 }
436
437 fn app(&mut self, head: &str, args: &[usize]) -> usize {
438 self.nodes.push(Held::App(head.to_owned(), args.to_vec()));
439 self.nodes.len() - 1
440 }
441 }
442
443 impl Subject for Terms {
444 type Node = usize;
445
446 fn head(&self, node: usize) -> Option<(&str, usize)> {
447 match &self.nodes[node] {
448 Held::App(head, args) => Some((head.as_str(), args.len())),
449 Held::Int(_) => None,
450 }
451 }
452
453 fn arg(&self, node: usize, index: usize) -> usize {
454 match &self.nodes[node] {
455 Held::App(_, args) => args[index],
456 Held::Int(_) => unreachable!("a constant has no arguments"),
457 }
458 }
459
460 fn int(&self, node: usize) -> Option<i128> {
461 match self.nodes[node] {
462 Held::Int(value) => Some(value),
463 Held::App(..) => None,
464 }
465 }
466
467 // An index into the arena is the identity of a term here, so two places are the same
468 // thing when they point at the same entry. A subject over the IR answers this out of the
469 // value each place holds instead, which is the same question asked of a different shape.
470 fn same(&self, a: usize, b: usize) -> bool {
471 a == b
472 }
473 }
474
475 /// A table written by hand, in the shape `rucc-rules` emits.
476 ///
477 /// Three rules over `(add x k)`: the first wants the constant to be zero, the second takes
478 /// any constant that is not negative, and the third, on the same node as the second, takes
479 /// one below minus ten. That is enough to exercise everything the walk does, which is a
480 /// concrete test before a wildcard, a guard that can refuse, the next rule on the node being
481 /// asked when it does, and the search carrying on after all of them have. A fourth rule,
482 /// `(and x x)`, is the one that writes a name twice.
483 /// A node with nothing on it, so that the ones below say only what they are about.
484 const NOTHING: Node = Node { heads: &[], ints: &[], same: &[], wildcard: None, accept: &[] };
485
486 /// A branch on a head, with the key a generated table would give it.
487 const fn head(name: &'static str, arity: usize, next: u32) -> (u128, &'static str, usize, u32) {
488 (Node::key(name), name, arity, next)
489 }
490
491 static NODES: &[Node] = &[
492 // 0, the root.
493 Node { heads: &[head("add", 2, 1), head("and", 2, 5)], ..NOTHING },
494 // 1, the first operand.
495 Node { wildcard: Some(("x", 2)), ..NOTHING },
496 // 2, the second operand.
497 Node { ints: &[(0, 3)], wildcard: Some(("k", 4)), ..NOTHING },
498 // 3, an addition of zero.
499 Node { accept: &[0], ..NOTHING },
500 // 4, an addition of anything, if one of the two guards holds.
501 Node { accept: &[1, 3], ..NOTHING },
502 // 5, the first operand of the conjunction, which is the one that binds.
503 Node { wildcard: Some(("x", 6)), ..NOTHING },
504 // 6, the second operand, which has to be what the first one bound.
505 Node { same: &[(0, 7)], ..NOTHING },
506 // 7, a conjunction of one thing with itself.
507 Node { accept: &[2], ..NOTHING },
508 ];
509
510 fn not_negative(bound: &[Option<i128>]) -> bool {
511 let Some(Some(k)) = bound.get(1).copied() else { return false };
512 k >= 0
513 }
514
515 fn far_below(bound: &[Option<i128>]) -> bool {
516 let Some(Some(k)) = bound.get(1).copied() else { return false };
517 k < -10
518 }
519
520 static RULES: &[Rule] = &[
521 Rule {
522 pattern: "(add x 0)",
523 replacement: &[Piece::Var { name: "x", index: 0 }],
524 guard: None,
525 line: 1,
526 },
527 Rule {
528 pattern: "(add x k)",
529 replacement: &[
530 Piece::App { head: "add_immediate", arity: 2 },
531 Piece::Var { name: "x", index: 0 },
532 Piece::Var { name: "k", index: 1 },
533 ],
534 guard: Some(not_negative),
535 line: 2,
536 },
537 Rule {
538 pattern: "(and x x)",
539 replacement: &[Piece::Var { name: "x", index: 0 }],
540 guard: None,
541 line: 3,
542 },
543 Rule {
544 pattern: "(add x k)",
545 replacement: &[
546 Piece::App { head: "add_far", arity: 2 },
547 Piece::Var { name: "x", index: 0 },
548 Piece::Var { name: "k", index: 1 },
549 ],
550 guard: Some(far_below),
551 line: 4,
552 },
553 ];
554
555 static TABLE: Table = Table { source: "rules/test.rules", nodes: NODES, rules: RULES };
556
557 fn add(terms: &mut Terms, second: usize) -> usize {
558 let first = terms.app("v0", &[]);
559 terms.app("add", &[first, second])
560 }
561
562 /// The concrete test is tried before the wildcard, so the rule about zero wins over the rule
563 /// about any constant even though both of them match. That is the whole of what specificity
564 /// order means here, and it falls out of the shape of the trie.
565 #[test]
566 fn the_rule_that_names_the_operand_beats_the_rule_that_takes_anything() {
567 let mut terms = Terms::default();
568 let zero = terms.constant(0);
569 let term = add(&mut terms, zero);
570 let found = TABLE.find(&terms, term).expect("a rule fires");
571 assert_eq!(TABLE.rule(&found).pattern, "(add x 0)");
572 }
573
574 /// The bindings come back in the order the pattern binds them, which is the pre-order the
575 /// replacement was flattened in, so a `Piece::Var` can be read as an index into them.
576 #[test]
577 fn a_match_gives_back_what_the_pattern_bound_in_the_order_it_bound_it() {
578 let mut terms = Terms::default();
579 let seven = terms.constant(7);
580 let term = add(&mut terms, seven);
581 let found = TABLE.find(&terms, term).expect("a rule fires");
582 let rule = TABLE.rule(&found);
583 assert_eq!(rule.pattern, "(add x k)");
584 assert_eq!(rule.head(), Some("add_immediate"));
585 assert_eq!(found.bindings.len(), 2);
586 assert_eq!(found.bindings[1], seven);
587 assert_eq!(terms.int(found.bindings[1]), Some(7));
588 }
589
590 /// A guard that does not hold is a rule that did not match, and there is nothing else to
591 /// try, so the answer is nothing rather than the wrong rule.
592 #[test]
593 fn a_guard_that_refuses_takes_its_rule_out_of_the_running() {
594 let mut terms = Terms::default();
595 let negative = terms.constant(-1);
596 let term = add(&mut terms, negative);
597 assert_eq!(TABLE.find(&terms, term), None);
598 }
599
600 /// Two rules with one pattern, and the second is asked when the first one's guard refuses.
601 #[test]
602 fn a_rule_that_shares_its_pattern_fires_when_the_one_before_it_refuses() {
603 let mut terms = Terms::default();
604 let far = terms.constant(-20);
605 let term = add(&mut terms, far);
606 let found = TABLE.find(&terms, term).expect("a rule fires");
607 assert_eq!(TABLE.rule(&found).head(), Some("add_far"));
608 let near = terms.constant(20);
609 let term = add(&mut terms, near);
610 let found = TABLE.find(&terms, term).expect("a rule fires");
611 assert_eq!(TABLE.rule(&found).head(), Some("add_immediate"));
612 }
613
614 /// The same guard against an operand that is not a constant at all. A guard is a claim about
615 /// a number, so a register makes it false rather than an error.
616 #[test]
617 fn a_guard_about_a_number_refuses_an_operand_that_is_not_one() {
618 let mut terms = Terms::default();
619 let other = terms.app("v1", &[]);
620 let term = add(&mut terms, other);
621 assert_eq!(TABLE.find(&terms, term), None);
622 }
623
624 #[test]
625 fn a_term_no_rule_covers_finds_no_rule() {
626 let mut terms = Terms::default();
627 let x = terms.app("v0", &[]);
628 let y = terms.app("v1", &[]);
629 let term = terms.app("no.such.head", &[x, y]);
630 assert_eq!(TABLE.find(&terms, term), None);
631 }
632
633 /// The rule that writes one name twice. Both operands are the same term, so the test that
634 /// they are holds and the rule fires, and what comes back is the one binding the pattern
635 /// made rather than two.
636 #[test]
637 fn a_pattern_that_names_one_hole_twice_matches_a_term_that_has_one_thing_in_both() {
638 let mut terms = Terms::default();
639 let x = terms.app("v0", &[]);
640 let term = terms.app("and", &[x, x]);
641 let found = TABLE.find(&terms, term).expect("a rule fires");
642 assert_eq!(TABLE.rule(&found).pattern, "(and x x)");
643 assert_eq!(found.bindings, vec![x]);
644 }
645
646 /// The same rule against two different terms. There is no wildcard beside the test, so a
647 /// conjunction of two things is a conjunction no rule covers rather than one this rule
648 /// wrongly claims.
649 #[test]
650 fn a_pattern_that_names_one_hole_twice_refuses_a_term_that_has_two_things_in_it() {
651 let mut terms = Terms::default();
652 let x = terms.app("v0", &[]);
653 let y = terms.app("v1", &[]);
654 let term = terms.app("and", &[x, y]);
655 assert_eq!(TABLE.find(&terms, term), None);
656 }
657
658 /// The branch is found rather than looked for, which is the thing a node being sorted buys.
659 /// A node as wide as the root of a real rule set answers in the same number of comparisons a
660 /// node with eight branches does, and it answers about the head it was never given by not
661 /// finding one rather than by reading to the end.
662 #[test]
663 fn a_branch_is_found_by_searching_the_node_and_not_by_reading_it() {
664 static WIDE: &[(u128, &str, usize, u32)] = &[
665 head("add.i16", 2, 1),
666 head("add.i32", 2, 2),
667 head("add.i64", 2, 3),
668 head("add.i64", 3, 4),
669 head("sub.i32", 2, 5),
670 head("sub.i64", 2, 6),
671 head("xor.i8", 2, 7),
672 ];
673 let node = Node { heads: WIDE, ..NOTHING };
674 assert!(WIDE.is_sorted(), "the search is only a search if the node is in order");
675 assert_eq!(node.branch("add.i64", 2), Some(3));
676 assert_eq!(node.branch("add.i16", 2), Some(1));
677 assert_eq!(node.branch("xor.i8", 2), Some(7));
678 // The same name at two arities is two branches, and they are told apart.
679 assert_eq!(node.branch("add.i64", 3), Some(4));
680 // A head no branch is about, and one the node has at another arity, are both nothing.
681 assert_eq!(node.branch("mul.i64", 2), None);
682 assert_eq!(node.branch("sub.i32", 3), None);
683 }
684
685 /// Names that agree in their first sixteen bytes, and names that run out before that, are
686 /// still told apart, which is what the search has to get right to leave the names alone at
687 /// every step but the last.
688 #[test]
689 fn names_that_share_their_first_sixteen_bytes_are_still_told_apart() {
690 static LONG: &[(u128, &str, usize, u32)] = &[
691 head("load.i64", 1, 1),
692 head("load.i64", 2, 2),
693 head("load.i64.012345678", 1, 3),
694 head("load.i64.012345679", 1, 4),
695 head("load.i64.01234567x", 1, 5),
696 head("load.i64x", 1, 6),
697 head("load.i8", 1, 7),
698 ];
699 let node = Node { heads: LONG, ..NOTHING };
700 assert!(LONG.is_sorted(), "the search is only a search if the node is in order");
701 for &(_, name, arity, next) in LONG {
702 assert_eq!(node.branch(name, arity), Some(next), "{name} with {arity}");
703 }
704 for name in ["load.i6", "load.i64.", "load.i64.0123456", "load.i64.01234567", "load"] {
705 assert_eq!(node.branch(name, 1), None, "{name}");
706 }
707 assert_eq!(node.branch("load.i64.012345677", 1), None);
708 }
709
710 /// The same for a constant, which is the other kind of branch that can be searched.
711 #[test]
712 fn a_literal_is_found_by_searching_too() {
713 let node = Node { ints: &[(-8, 1), (0, 2), (1, 3), (4096, 4)], ..NOTHING };
714 assert_eq!(node.literal(-8), Some(1));
715 assert_eq!(node.literal(0), Some(2));
716 assert_eq!(node.literal(4096), Some(4));
717 assert_eq!(node.literal(7), None);
718 }
719
720 /// The order the kinds of question are asked in, which is the heuristic the module doc
721 /// states. It only decides anything when one node asks two kinds about one place and the
722 /// subject answers both, which is why this needs a subject of its own: the one above answers
723 /// either what a term is called or what number it is, never both, and so does the IR. What is
724 /// asserted is the order that is written down, so that a rule set which starts to depend on
725 /// it gets the answer somebody chose rather than the one that fell out.
726 #[test]
727 fn the_head_is_asked_about_before_the_value_and_the_value_before_a_repeat() {
728 /// `(f a a)`, where each operand is an application and a number at the same time and the
729 /// two of them are one thing. Every question a node can ask is true of them, so which
730 /// one is asked first is the only thing that decides the answer.
731 #[derive(Debug)]
732 struct Both;
733
734 impl Subject for Both {
735 type Node = u8;
736
737 fn head(&self, node: u8) -> Option<(&str, usize)> {
738 if node == 0 { Some(("f", 2)) } else { Some(("k", 0)) }
739 }
740
741 fn int(&self, node: u8) -> Option<i128> {
742 if node == 0 { None } else { Some(7) }
743 }
744
745 fn arg(&self, _: u8, _: usize) -> u8 {
746 1
747 }
748
749 fn same(&self, _: u8, _: u8) -> bool {
750 true
751 }
752 }
753
754 static FOUR: &[Rule] = &[
755 Rule { pattern: "the head", replacement: &[], guard: None, line: 1 },
756 Rule { pattern: "the value", replacement: &[], guard: None, line: 2 },
757 Rule { pattern: "the repeat", replacement: &[], guard: None, line: 3 },
758 Rule { pattern: "the hole", replacement: &[], guard: None, line: 4 },
759 ];
760
761 /// The four ends, and in front of them the node that binds the first operand so that
762 /// there is something for a repeat to be a repeat of.
763 fn table(second: &'static Node) -> Table {
764 const F: &[(u128, &str, usize, u32)] = &[head("f", 2, 1)];
765 let nodes: &'static [Node] = Box::leak(Box::new([
766 Node { heads: F, ..NOTHING },
767 Node { wildcard: Some(("x", 2)), ..NOTHING },
768 *second,
769 Node { accept: &[0], ..NOTHING },
770 Node { accept: &[1], ..NOTHING },
771 Node { accept: &[2], ..NOTHING },
772 Node { accept: &[3], ..NOTHING },
773 ]));
774 Table { source: "rules/test.rules", nodes, rules: FOUR }
775 }
776
777 // All three kinds on one node, with a hole behind them.
778 static MIXED: Node = Node {
779 heads: &[head("k", 0, 3)],
780 ints: &[(7, 4)],
781 same: &[(0, 5)],
782 wildcard: Some(("y", 6)),
783 accept: &[],
784 };
785 assert_eq!(table(&MIXED).find(&Both, 0).map(|found| found.rule), Some(0));
786
787 // The same node without the head, which is what puts the value in front.
788 static WITHOUT_HEAD: Node = Node { heads: &[], ..MIXED };
789 assert_eq!(table(&WITHOUT_HEAD).find(&Both, 0).map(|found| found.rule), Some(1));
790
791 // And without either, which leaves the repeat in front of the hole. That last pair is
792 // the one that is not a heuristic: a concrete question always comes before the hole.
793 static REPEAT: Node = Node { ints: &[], ..WITHOUT_HEAD };
794 assert_eq!(table(&REPEAT).find(&Both, 0).map(|found| found.rule), Some(2));
795
796 // And with nothing concrete left, the hole.
797 static HOLE: Node = Node { same: &[], ..REPEAT };
798 assert_eq!(table(&HOLE).find(&Both, 0).map(|found| found.rule), Some(3));
799 }
800
801 /// A match is what a caller keeps, so it says what it is when a test prints it.
802 #[test]
803 fn a_match_names_the_rule_it_found() {
804 let mut terms = Terms::default();
805 let zero = terms.constant(0);
806 let term = add(&mut terms, zero);
807 assert_eq!(TABLE.find(&terms, term), Some(Match { rule: 0, bindings: vec![term - 1] }));
808 }
809}