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 // Both start with room for a pattern of the usual size. Starting them empty grew them a
294 // few times on every instruction selected, and that was most of what the walk allocated.
295 let mut left = Vec::with_capacity(16);
296 let mut bindings = Vec::with_capacity(8);
297 let rule = self.find_in(subject, term, &mut left, &mut bindings)?;
298 Some(Match { rule, bindings })
299 }
300
301 /// [`Table::find`] with the two stacks the walk needs handed in, for a caller that asks more
302 /// than once and would rather not pay for them every time.
303 ///
304 /// Both are emptied before the walk. What `bindings` holds afterwards is what the pattern
305 /// bound when a rule fired, and nothing anybody reads when none did.
306 pub fn find_in<S: Subject>(
307 &self,
308 subject: &S,
309 term: S::Node,
310 left: &mut Vec<S::Node>,
311 bindings: &mut Vec<S::Node>,
312 ) -> Option<usize> {
313 left.clear();
314 left.push(term);
315 bindings.clear();
316 self.run(subject, 0, left, bindings)
317 }
318
319 /// The rule a match found, which is the one thing every caller wants out of it.
320 #[must_use]
321 pub fn rule<N>(&self, found: &Match<N>) -> &Rule {
322 &self.rules[found.rule]
323 }
324
325 /// Walk the trie and the subject together.
326 ///
327 /// `left` is the subterms still to be matched, innermost last, so that popping gives the
328 /// pre-order the patterns were flattened in. It is one stack for the whole walk rather than a
329 /// copy per branch, so a walk that finds nothing puts back what it took: the term it popped,
330 /// and through [`Table::take`] the arguments it pushed. What is on it after a match is not
331 /// anything anybody reads.
332 fn run<S: Subject>(
333 &self,
334 subject: &S,
335 at: usize,
336 left: &mut Vec<S::Node>,
337 bindings: &mut Vec<S::Node>,
338 ) -> Option<usize> {
339 let Some(term) = left.pop() else {
340 return self.accept(subject, at, bindings);
341 };
342 let node = &self.nodes[at];
343 let head = subject.head(term);
344
345 // The head of the term, which is the question nearly every branch of nearly every node
346 // is about and the one that has to be found rather than looked for.
347 if let Some(next) = head.and_then(|(name, arity)| node.branch(name, arity)) {
348 if let Some(rule) = self.take(subject, next, (term, head), left, bindings) {
349 return Some(rule);
350 }
351 }
352
353 // Its value, if it is a constant and if this node asks about one. The emptiness is
354 // checked first because asking the subject for a value costs something and most nodes
355 // have nothing to compare it against.
356 if !node.ints.is_empty() {
357 if let Some(next) = subject.int(term).and_then(|value| node.literal(value)) {
358 if let Some(rule) = self.take(subject, next, (term, head), left, bindings) {
359 return Some(rule);
360 }
361 }
362 }
363
364 // A repeat of an earlier binding. The binding is always there, because a pattern only
365 // writes a name for the second time after it has written it once and the trie keeps that
366 // order.
367 for &(index, next) in node.same {
368 if bindings.get(index).is_some_and(|&bound| subject.same(bound, term)) {
369 if let Some(rule) = self.take(subject, next, (term, head), left, bindings) {
370 return Some(rule);
371 }
372 }
373 }
374
375 // The wildcard is last, which is the whole of what specificity order means here.
376 if let Some((_, next)) = node.wildcard {
377 let depth = bindings.len();
378 bindings.push(term);
379 if let Some(rule) = self.run(subject, next as usize, left, bindings) {
380 return Some(rule);
381 }
382 bindings.truncate(depth);
383 }
384 left.push(term);
385 None
386 }
387
388 /// Follow one branch, and give the stack and the bindings back as they were if it led nowhere.
389 ///
390 /// What goes on the stack is the arguments of the term, innermost last, whenever the term has
391 /// any. That is the same for every kind of branch, because what a branch decided is that this
392 /// subterm is matched and the walk carries on into what is under it.
393 fn take<S: Subject>(
394 &self,
395 subject: &S,
396 next: u32,
397 term: (S::Node, Option<(&str, usize)>),
398 left: &mut Vec<S::Node>,
399 bindings: &mut Vec<S::Node>,
400 ) -> Option<usize> {
401 let (term, head) = term;
402 let height = left.len();
403 if let Some((_, arity)) = head {
404 for index in (0..arity).rev() {
405 left.push(subject.arg(term, index));
406 }
407 }
408 let depth = bindings.len();
409 if let Some(rule) = self.run(subject, next as usize, left, bindings) {
410 return Some(rule);
411 }
412 left.truncate(height);
413 bindings.truncate(depth);
414 None
415 }
416
417 /// The first rule that ends at this node whose guard holds, if there is one.
418 fn accept<S: Subject>(&self, subject: &S, at: usize, bindings: &[S::Node]) -> Option<usize> {
419 // The values are collected once and only when a guard asks, because most rules have no
420 // guard and would pay for it every time.
421 let mut values: Option<Vec<Option<i128>>> = None;
422 for &rule in self.nodes[at].accept {
423 let rule = rule as usize;
424 let Some(guard) = self.rules[rule].guard else { return Some(rule) };
425 let values = values
426 .get_or_insert_with(|| bindings.iter().map(|&node| subject.int(node)).collect());
427 if guard(values) {
428 return Some(rule);
429 }
430 }
431 None
432 }
433}
434
435#[cfg(test)]
436mod tests {
437 use super::{Match, Node, Piece, Rule, Subject, Table};
438
439 /// A term, in the only shape a test needs: a flat arena, because that is the shape the IR
440 /// has and answering the questions out of one is what the callers will be doing.
441 #[derive(Debug)]
442 enum Held {
443 Int(i128),
444 App(String, Vec<usize>),
445 }
446
447 #[derive(Debug, Default)]
448 struct Terms {
449 nodes: Vec<Held>,
450 }
451
452 impl Terms {
453 fn constant(&mut self, value: i128) -> usize {
454 self.nodes.push(Held::Int(value));
455 self.nodes.len() - 1
456 }
457
458 fn app(&mut self, head: &str, args: &[usize]) -> usize {
459 self.nodes.push(Held::App(head.to_owned(), args.to_vec()));
460 self.nodes.len() - 1
461 }
462 }
463
464 impl Subject for Terms {
465 type Node = usize;
466
467 fn head(&self, node: usize) -> Option<(&str, usize)> {
468 match &self.nodes[node] {
469 Held::App(head, args) => Some((head.as_str(), args.len())),
470 Held::Int(_) => None,
471 }
472 }
473
474 fn arg(&self, node: usize, index: usize) -> usize {
475 match &self.nodes[node] {
476 Held::App(_, args) => args[index],
477 Held::Int(_) => unreachable!("a constant has no arguments"),
478 }
479 }
480
481 fn int(&self, node: usize) -> Option<i128> {
482 match self.nodes[node] {
483 Held::Int(value) => Some(value),
484 Held::App(..) => None,
485 }
486 }
487
488 // An index into the arena is the identity of a term here, so two places are the same
489 // thing when they point at the same entry. A subject over the IR answers this out of the
490 // value each place holds instead, which is the same question asked of a different shape.
491 fn same(&self, a: usize, b: usize) -> bool {
492 a == b
493 }
494 }
495
496 /// A table written by hand, in the shape `rucc-rules` emits.
497 ///
498 /// Three rules over `(add x k)`: the first wants the constant to be zero, the second takes
499 /// any constant that is not negative, and the third, on the same node as the second, takes
500 /// one below minus ten. That is enough to exercise everything the walk does, which is a
501 /// concrete test before a wildcard, a guard that can refuse, the next rule on the node being
502 /// asked when it does, and the search carrying on after all of them have. A fourth rule,
503 /// `(and x x)`, is the one that writes a name twice.
504 /// A node with nothing on it, so that the ones below say only what they are about.
505 const NOTHING: Node = Node { heads: &[], ints: &[], same: &[], wildcard: None, accept: &[] };
506
507 /// A branch on a head, with the key a generated table would give it.
508 const fn head(name: &'static str, arity: usize, next: u32) -> (u128, &'static str, usize, u32) {
509 (Node::key(name), name, arity, next)
510 }
511
512 static NODES: &[Node] = &[
513 // 0, the root.
514 Node { heads: &[head("add", 2, 1), head("and", 2, 5)], ..NOTHING },
515 // 1, the first operand.
516 Node { wildcard: Some(("x", 2)), ..NOTHING },
517 // 2, the second operand.
518 Node { ints: &[(0, 3)], wildcard: Some(("k", 4)), ..NOTHING },
519 // 3, an addition of zero.
520 Node { accept: &[0], ..NOTHING },
521 // 4, an addition of anything, if one of the two guards holds.
522 Node { accept: &[1, 3], ..NOTHING },
523 // 5, the first operand of the conjunction, which is the one that binds.
524 Node { wildcard: Some(("x", 6)), ..NOTHING },
525 // 6, the second operand, which has to be what the first one bound.
526 Node { same: &[(0, 7)], ..NOTHING },
527 // 7, a conjunction of one thing with itself.
528 Node { accept: &[2], ..NOTHING },
529 ];
530
531 fn not_negative(bound: &[Option<i128>]) -> bool {
532 let Some(Some(k)) = bound.get(1).copied() else { return false };
533 k >= 0
534 }
535
536 fn far_below(bound: &[Option<i128>]) -> bool {
537 let Some(Some(k)) = bound.get(1).copied() else { return false };
538 k < -10
539 }
540
541 static RULES: &[Rule] = &[
542 Rule {
543 pattern: "(add x 0)",
544 replacement: &[Piece::Var { name: "x", index: 0 }],
545 guard: None,
546 line: 1,
547 },
548 Rule {
549 pattern: "(add x k)",
550 replacement: &[
551 Piece::App { head: "add_immediate", arity: 2 },
552 Piece::Var { name: "x", index: 0 },
553 Piece::Var { name: "k", index: 1 },
554 ],
555 guard: Some(not_negative),
556 line: 2,
557 },
558 Rule {
559 pattern: "(and x x)",
560 replacement: &[Piece::Var { name: "x", index: 0 }],
561 guard: None,
562 line: 3,
563 },
564 Rule {
565 pattern: "(add x k)",
566 replacement: &[
567 Piece::App { head: "add_far", arity: 2 },
568 Piece::Var { name: "x", index: 0 },
569 Piece::Var { name: "k", index: 1 },
570 ],
571 guard: Some(far_below),
572 line: 4,
573 },
574 ];
575
576 static TABLE: Table = Table { source: "rules/test.rules", nodes: NODES, rules: RULES };
577
578 fn add(terms: &mut Terms, second: usize) -> usize {
579 let first = terms.app("v0", &[]);
580 terms.app("add", &[first, second])
581 }
582
583 /// The concrete test is tried before the wildcard, so the rule about zero wins over the rule
584 /// about any constant even though both of them match. That is the whole of what specificity
585 /// order means here, and it falls out of the shape of the trie.
586 #[test]
587 fn the_rule_that_names_the_operand_beats_the_rule_that_takes_anything() {
588 let mut terms = Terms::default();
589 let zero = terms.constant(0);
590 let term = add(&mut terms, zero);
591 let found = TABLE.find(&terms, term).expect("a rule fires");
592 assert_eq!(TABLE.rule(&found).pattern, "(add x 0)");
593 }
594
595 /// The bindings come back in the order the pattern binds them, which is the pre-order the
596 /// replacement was flattened in, so a `Piece::Var` can be read as an index into them.
597 #[test]
598 fn a_match_gives_back_what_the_pattern_bound_in_the_order_it_bound_it() {
599 let mut terms = Terms::default();
600 let seven = terms.constant(7);
601 let term = add(&mut terms, seven);
602 let found = TABLE.find(&terms, term).expect("a rule fires");
603 let rule = TABLE.rule(&found);
604 assert_eq!(rule.pattern, "(add x k)");
605 assert_eq!(rule.head(), Some("add_immediate"));
606 assert_eq!(found.bindings.len(), 2);
607 assert_eq!(found.bindings[1], seven);
608 assert_eq!(terms.int(found.bindings[1]), Some(7));
609 }
610
611 /// A guard that does not hold is a rule that did not match, and there is nothing else to
612 /// try, so the answer is nothing rather than the wrong rule.
613 #[test]
614 fn a_guard_that_refuses_takes_its_rule_out_of_the_running() {
615 let mut terms = Terms::default();
616 let negative = terms.constant(-1);
617 let term = add(&mut terms, negative);
618 assert_eq!(TABLE.find(&terms, term), None);
619 }
620
621 /// Two rules with one pattern, and the second is asked when the first one's guard refuses.
622 #[test]
623 fn a_rule_that_shares_its_pattern_fires_when_the_one_before_it_refuses() {
624 let mut terms = Terms::default();
625 let far = terms.constant(-20);
626 let term = add(&mut terms, far);
627 let found = TABLE.find(&terms, term).expect("a rule fires");
628 assert_eq!(TABLE.rule(&found).head(), Some("add_far"));
629 let near = terms.constant(20);
630 let term = add(&mut terms, near);
631 let found = TABLE.find(&terms, term).expect("a rule fires");
632 assert_eq!(TABLE.rule(&found).head(), Some("add_immediate"));
633 }
634
635 /// The same guard against an operand that is not a constant at all. A guard is a claim about
636 /// a number, so a register makes it false rather than an error.
637 #[test]
638 fn a_guard_about_a_number_refuses_an_operand_that_is_not_one() {
639 let mut terms = Terms::default();
640 let other = terms.app("v1", &[]);
641 let term = add(&mut terms, other);
642 assert_eq!(TABLE.find(&terms, term), None);
643 }
644
645 #[test]
646 fn a_term_no_rule_covers_finds_no_rule() {
647 let mut terms = Terms::default();
648 let x = terms.app("v0", &[]);
649 let y = terms.app("v1", &[]);
650 let term = terms.app("no.such.head", &[x, y]);
651 assert_eq!(TABLE.find(&terms, term), None);
652 }
653
654 /// The rule that writes one name twice. Both operands are the same term, so the test that
655 /// they are holds and the rule fires, and what comes back is the one binding the pattern
656 /// made rather than two.
657 #[test]
658 fn a_pattern_that_names_one_hole_twice_matches_a_term_that_has_one_thing_in_both() {
659 let mut terms = Terms::default();
660 let x = terms.app("v0", &[]);
661 let term = terms.app("and", &[x, x]);
662 let found = TABLE.find(&terms, term).expect("a rule fires");
663 assert_eq!(TABLE.rule(&found).pattern, "(and x x)");
664 assert_eq!(found.bindings, vec![x]);
665 }
666
667 /// The same rule against two different terms. There is no wildcard beside the test, so a
668 /// conjunction of two things is a conjunction no rule covers rather than one this rule
669 /// wrongly claims.
670 #[test]
671 fn a_pattern_that_names_one_hole_twice_refuses_a_term_that_has_two_things_in_it() {
672 let mut terms = Terms::default();
673 let x = terms.app("v0", &[]);
674 let y = terms.app("v1", &[]);
675 let term = terms.app("and", &[x, y]);
676 assert_eq!(TABLE.find(&terms, term), None);
677 }
678
679 /// The branch is found rather than looked for, which is the thing a node being sorted buys.
680 /// A node as wide as the root of a real rule set answers in the same number of comparisons a
681 /// node with eight branches does, and it answers about the head it was never given by not
682 /// finding one rather than by reading to the end.
683 #[test]
684 fn a_branch_is_found_by_searching_the_node_and_not_by_reading_it() {
685 static WIDE: &[(u128, &str, usize, u32)] = &[
686 head("add.i16", 2, 1),
687 head("add.i32", 2, 2),
688 head("add.i64", 2, 3),
689 head("add.i64", 3, 4),
690 head("sub.i32", 2, 5),
691 head("sub.i64", 2, 6),
692 head("xor.i8", 2, 7),
693 ];
694 let node = Node { heads: WIDE, ..NOTHING };
695 assert!(WIDE.is_sorted(), "the search is only a search if the node is in order");
696 assert_eq!(node.branch("add.i64", 2), Some(3));
697 assert_eq!(node.branch("add.i16", 2), Some(1));
698 assert_eq!(node.branch("xor.i8", 2), Some(7));
699 // The same name at two arities is two branches, and they are told apart.
700 assert_eq!(node.branch("add.i64", 3), Some(4));
701 // A head no branch is about, and one the node has at another arity, are both nothing.
702 assert_eq!(node.branch("mul.i64", 2), None);
703 assert_eq!(node.branch("sub.i32", 3), None);
704 }
705
706 /// Names that agree in their first sixteen bytes, and names that run out before that, are
707 /// still told apart, which is what the search has to get right to leave the names alone at
708 /// every step but the last.
709 #[test]
710 fn names_that_share_their_first_sixteen_bytes_are_still_told_apart() {
711 static LONG: &[(u128, &str, usize, u32)] = &[
712 head("load.i64", 1, 1),
713 head("load.i64", 2, 2),
714 head("load.i64.012345678", 1, 3),
715 head("load.i64.012345679", 1, 4),
716 head("load.i64.01234567x", 1, 5),
717 head("load.i64x", 1, 6),
718 head("load.i8", 1, 7),
719 ];
720 let node = Node { heads: LONG, ..NOTHING };
721 assert!(LONG.is_sorted(), "the search is only a search if the node is in order");
722 for &(_, name, arity, next) in LONG {
723 assert_eq!(node.branch(name, arity), Some(next), "{name} with {arity}");
724 }
725 for name in ["load.i6", "load.i64.", "load.i64.0123456", "load.i64.01234567", "load"] {
726 assert_eq!(node.branch(name, 1), None, "{name}");
727 }
728 assert_eq!(node.branch("load.i64.012345677", 1), None);
729 }
730
731 /// The same for a constant, which is the other kind of branch that can be searched.
732 #[test]
733 fn a_literal_is_found_by_searching_too() {
734 let node = Node { ints: &[(-8, 1), (0, 2), (1, 3), (4096, 4)], ..NOTHING };
735 assert_eq!(node.literal(-8), Some(1));
736 assert_eq!(node.literal(0), Some(2));
737 assert_eq!(node.literal(4096), Some(4));
738 assert_eq!(node.literal(7), None);
739 }
740
741 /// The order the kinds of question are asked in, which is the heuristic the module doc
742 /// states. It only decides anything when one node asks two kinds about one place and the
743 /// subject answers both, which is why this needs a subject of its own: the one above answers
744 /// either what a term is called or what number it is, never both, and so does the IR. What is
745 /// asserted is the order that is written down, so that a rule set which starts to depend on
746 /// it gets the answer somebody chose rather than the one that fell out.
747 #[test]
748 fn the_head_is_asked_about_before_the_value_and_the_value_before_a_repeat() {
749 /// `(f a a)`, where each operand is an application and a number at the same time and the
750 /// two of them are one thing. Every question a node can ask is true of them, so which
751 /// one is asked first is the only thing that decides the answer.
752 #[derive(Debug)]
753 struct Both;
754
755 impl Subject for Both {
756 type Node = u8;
757
758 fn head(&self, node: u8) -> Option<(&str, usize)> {
759 if node == 0 { Some(("f", 2)) } else { Some(("k", 0)) }
760 }
761
762 fn int(&self, node: u8) -> Option<i128> {
763 if node == 0 { None } else { Some(7) }
764 }
765
766 fn arg(&self, _: u8, _: usize) -> u8 {
767 1
768 }
769
770 fn same(&self, _: u8, _: u8) -> bool {
771 true
772 }
773 }
774
775 static FOUR: &[Rule] = &[
776 Rule { pattern: "the head", replacement: &[], guard: None, line: 1 },
777 Rule { pattern: "the value", replacement: &[], guard: None, line: 2 },
778 Rule { pattern: "the repeat", replacement: &[], guard: None, line: 3 },
779 Rule { pattern: "the hole", replacement: &[], guard: None, line: 4 },
780 ];
781
782 /// The four ends, and in front of them the node that binds the first operand so that
783 /// there is something for a repeat to be a repeat of.
784 fn table(second: &'static Node) -> Table {
785 const F: &[(u128, &str, usize, u32)] = &[head("f", 2, 1)];
786 let nodes: &'static [Node] = Box::leak(Box::new([
787 Node { heads: F, ..NOTHING },
788 Node { wildcard: Some(("x", 2)), ..NOTHING },
789 *second,
790 Node { accept: &[0], ..NOTHING },
791 Node { accept: &[1], ..NOTHING },
792 Node { accept: &[2], ..NOTHING },
793 Node { accept: &[3], ..NOTHING },
794 ]));
795 Table { source: "rules/test.rules", nodes, rules: FOUR }
796 }
797
798 // All three kinds on one node, with a hole behind them.
799 static MIXED: Node = Node {
800 heads: &[head("k", 0, 3)],
801 ints: &[(7, 4)],
802 same: &[(0, 5)],
803 wildcard: Some(("y", 6)),
804 accept: &[],
805 };
806 assert_eq!(table(&MIXED).find(&Both, 0).map(|found| found.rule), Some(0));
807
808 // The same node without the head, which is what puts the value in front.
809 static WITHOUT_HEAD: Node = Node { heads: &[], ..MIXED };
810 assert_eq!(table(&WITHOUT_HEAD).find(&Both, 0).map(|found| found.rule), Some(1));
811
812 // And without either, which leaves the repeat in front of the hole. That last pair is
813 // the one that is not a heuristic: a concrete question always comes before the hole.
814 static REPEAT: Node = Node { ints: &[], ..WITHOUT_HEAD };
815 assert_eq!(table(&REPEAT).find(&Both, 0).map(|found| found.rule), Some(2));
816
817 // And with nothing concrete left, the hole.
818 static HOLE: Node = Node { same: &[], ..REPEAT };
819 assert_eq!(table(&HOLE).find(&Both, 0).map(|found| found.rule), Some(3));
820 }
821
822 /// A match is what a caller keeps, so it says what it is when a test prints it.
823 #[test]
824 fn a_match_names_the_rule_it_found() {
825 let mut terms = Terms::default();
826 let zero = terms.constant(0);
827 let term = add(&mut terms, zero);
828 assert_eq!(TABLE.find(&terms, term), Some(Match { rule: 0, bindings: vec![term - 1] }));
829 }
830}