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 name, how many arguments it takes,
117 /// and where to go. Sorted by the first two, which is what [`Node::branch`] needs.
118 pub heads: &'static [(&'static str, usize, u32)],
119 /// The branches taken on the value of a subterm that is a constant, sorted by the value.
120 pub ints: &'static [(i128, u32)],
121 /// The branches taken when the subterm is the same thing as a binding this pattern already
122 /// made, named by which binding it is. A pattern writes one where it writes a name for the
123 /// second time, so this is how `x & x` is told apart from `x & y`. In the order the rules
124 /// were written, because two of them can match one subterm.
125 pub same: &'static [(usize, u32)],
126 /// The branch that takes anything, and the name the first rule to reach it gave that hole.
127 pub wildcard: Option<(&'static str, u32)>,
128 /// The rules that end here, in the order the rule file writes them. The first whose guard
129 /// holds is the one that fires, so every one of them but the last has a guard, which the rule
130 /// compiler checks.
131 pub accept: &'static [u32],
132}
133
134impl Node {
135 /// The branch for a term with this head and this many arguments, if the node has one.
136 ///
137 /// A binary search, which is the whole point of the list being sorted. At most one branch can
138 /// answer, so nothing about which rule fires depends on the list being in this order rather
139 /// than in the order the rules were written.
140 #[must_use]
141 pub fn branch(&self, head: &str, arity: usize) -> Option<u32> {
142 let found = self
143 .heads
144 .binary_search_by(|(have, count, _)| have.cmp(&head).then(count.cmp(&arity)))
145 .ok()?;
146 Some(self.heads[found].2)
147 }
148
149 /// The branch for a constant of this value, if the node has one.
150 #[must_use]
151 pub fn literal(&self, value: i128) -> Option<u32> {
152 let found = self.ints.binary_search_by(|(have, _)| have.cmp(&value)).ok()?;
153 Some(self.ints[found].1)
154 }
155}
156
157/// One piece of a replacement, in the pre-order that builds it.
158#[derive(Debug)]
159pub enum Piece {
160 /// Whatever the pattern bound at this position.
161 Var {
162 /// The name the rule gave it, for anything that has to say what it did.
163 name: &'static str,
164 /// Which binding of the match it is.
165 index: usize,
166 },
167 /// A constant written in the rule.
168 Int(i128),
169 /// A constant the rule works out from the ones the pattern matched.
170 ///
171 /// This is what lets a rule be written once per width rather than once per constant. A shift
172 /// that stands in for a multiplication by a power of two shifts by the log of that power, and
173 /// the log is a number no rule can write down until it has seen which power it matched.
174 Computed {
175 /// The computation as the rule file writes it, for anything that has to say what it did.
176 text: &'static str,
177 /// What it works out.
178 work: Computation,
179 },
180 /// A term the rule writes, which is an instruction once the caller has built it.
181 App {
182 /// The name in head position.
183 head: &'static str,
184 /// How many arguments it takes.
185 arity: usize,
186 },
187}
188
189/// A condition on the constants a pattern matched.
190///
191/// It is handed one entry per binding, holding the value of that binding when it has one. A
192/// guard about a binding that is not a constant is false, which is how a rule about a number
193/// declines an operand that is a register.
194pub type Guard = fn(&[Option<i128>]) -> bool;
195
196/// A number worked out from the constants a pattern matched.
197///
198/// Handed one entry per binding, the same as a [`Guard`] is, and for the same reason: the
199/// computation is written in the names the pattern bound and those are positions by the time it
200/// runs. It gives nothing back when a binding it reads is not a constant, which is the answer a
201/// guard gives as false, and the rule does not fire.
202pub type Computation = fn(&[Option<i128>]) -> Option<i128>;
203
204/// One rule, as much of it as matching needs.
205#[derive(Debug)]
206pub struct Rule {
207 /// The pattern as it is written in the rule file, for diagnostics and for tests.
208 pub pattern: &'static str,
209 /// What to put in the matched term's place, flattened into pre-order.
210 pub replacement: &'static [Piece],
211 /// The condition on the match, if the rule has one.
212 pub guard: Option<Guard>,
213 /// The line of the rule file this rule starts on.
214 pub line: u32,
215}
216
217impl Rule {
218 /// The head of the replacement, which is what this rule writes.
219 #[must_use]
220 pub fn head(&self) -> Option<&'static str> {
221 match self.replacement.first() {
222 Some(Piece::App { head, .. }) => Some(head),
223 _ => None,
224 }
225 }
226}
227
228/// A set of rules, as an automaton over their patterns.
229#[derive(Debug)]
230pub struct Table {
231 /// The rule file this was built from, so that anything said about a rule can name a file
232 /// somebody can open.
233 pub source: &'static str,
234 /// The trie. Node zero is the root.
235 pub nodes: &'static [Node],
236 /// The rules, in the order the file writes them.
237 pub rules: &'static [Rule],
238}
239
240/// What a successful match found.
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct Match<N> {
243 /// Which rule of the table fired.
244 pub rule: usize,
245 /// What the pattern bound, in the order it binds it.
246 pub bindings: Vec<N>,
247}
248
249impl Table {
250 /// The rule that fires on this term, and what it bound.
251 ///
252 /// The term is matched as a whole. Finding the terms in a function worth matching is the
253 /// caller's job and not this one's.
254 #[must_use]
255 pub fn find<S: Subject>(&self, subject: &S, term: S::Node) -> Option<Match<S::Node>> {
256 let mut bindings = Vec::new();
257 let rule = self.run(subject, 0, vec![term], &mut bindings)?;
258 Some(Match { rule, bindings })
259 }
260
261 /// The rule a match found, which is the one thing every caller wants out of it.
262 #[must_use]
263 pub fn rule<N>(&self, found: &Match<N>) -> &Rule {
264 &self.rules[found.rule]
265 }
266
267 /// Walk the trie and the subject together.
268 ///
269 /// `left` is the subterms still to be matched, innermost last, so that popping gives the
270 /// pre-order the patterns were flattened in.
271 fn run<S: Subject>(
272 &self,
273 subject: &S,
274 at: usize,
275 mut left: Vec<S::Node>,
276 bindings: &mut Vec<S::Node>,
277 ) -> Option<usize> {
278 let Some(term) = left.pop() else {
279 return self.accept(subject, at, bindings);
280 };
281 let node = &self.nodes[at];
282 let head = subject.head(term);
283
284 // The head of the term, which is the question nearly every branch of nearly every node
285 // is about and the one that has to be found rather than looked for.
286 if let Some(next) = head.and_then(|(name, arity)| node.branch(name, arity)) {
287 if let Some(rule) = self.take(subject, next, (term, head), &left, bindings) {
288 return Some(rule);
289 }
290 }
291
292 // Its value, if it is a constant and if this node asks about one. The emptiness is
293 // checked first because asking the subject for a value costs something and most nodes
294 // have nothing to compare it against.
295 if !node.ints.is_empty() {
296 if let Some(next) = subject.int(term).and_then(|value| node.literal(value)) {
297 if let Some(rule) = self.take(subject, next, (term, head), &left, bindings) {
298 return Some(rule);
299 }
300 }
301 }
302
303 // A repeat of an earlier binding. The binding is always there, because a pattern only
304 // writes a name for the second time after it has written it once and the trie keeps that
305 // order.
306 for &(index, next) in node.same {
307 if bindings.get(index).is_some_and(|&bound| subject.same(bound, term)) {
308 if let Some(rule) = self.take(subject, next, (term, head), &left, bindings) {
309 return Some(rule);
310 }
311 }
312 }
313
314 // The wildcard is last, which is the whole of what specificity order means here.
315 let (_, next) = node.wildcard.as_ref()?;
316 let depth = bindings.len();
317 bindings.push(term);
318 if let Some(rule) = self.run(subject, *next as usize, left, bindings) {
319 return Some(rule);
320 }
321 bindings.truncate(depth);
322 None
323 }
324
325 /// Follow one branch, and give the bindings back as they were if it led nowhere.
326 ///
327 /// What goes on the stack is the arguments of the term, innermost last, whenever the term has
328 /// any. That is the same for every kind of branch, because what a branch decided is that this
329 /// subterm is matched and the walk carries on into what is under it.
330 fn take<S: Subject>(
331 &self,
332 subject: &S,
333 next: u32,
334 term: (S::Node, Option<(&str, usize)>),
335 left: &[S::Node],
336 bindings: &mut Vec<S::Node>,
337 ) -> Option<usize> {
338 let (term, head) = term;
339 let mut deeper = left.to_vec();
340 if let Some((_, arity)) = head {
341 for index in (0..arity).rev() {
342 deeper.push(subject.arg(term, index));
343 }
344 }
345 let depth = bindings.len();
346 if let Some(rule) = self.run(subject, next as usize, deeper, bindings) {
347 return Some(rule);
348 }
349 bindings.truncate(depth);
350 None
351 }
352
353 /// The first rule that ends at this node whose guard holds, if there is one.
354 fn accept<S: Subject>(&self, subject: &S, at: usize, bindings: &[S::Node]) -> Option<usize> {
355 // The values are collected once and only when a guard asks, because most rules have no
356 // guard and would pay for it every time.
357 let mut values: Option<Vec<Option<i128>>> = None;
358 for &rule in self.nodes[at].accept {
359 let rule = rule as usize;
360 let Some(guard) = self.rules[rule].guard else { return Some(rule) };
361 let values = values
362 .get_or_insert_with(|| bindings.iter().map(|&node| subject.int(node)).collect());
363 if guard(values) {
364 return Some(rule);
365 }
366 }
367 None
368 }
369}
370
371#[cfg(test)]
372mod tests {
373 use super::{Match, Node, Piece, Rule, Subject, Table};
374
375 /// A term, in the only shape a test needs: a flat arena, because that is the shape the IR
376 /// has and answering the questions out of one is what the callers will be doing.
377 #[derive(Debug)]
378 enum Held {
379 Int(i128),
380 App(String, Vec<usize>),
381 }
382
383 #[derive(Debug, Default)]
384 struct Terms {
385 nodes: Vec<Held>,
386 }
387
388 impl Terms {
389 fn constant(&mut self, value: i128) -> usize {
390 self.nodes.push(Held::Int(value));
391 self.nodes.len() - 1
392 }
393
394 fn app(&mut self, head: &str, args: &[usize]) -> usize {
395 self.nodes.push(Held::App(head.to_owned(), args.to_vec()));
396 self.nodes.len() - 1
397 }
398 }
399
400 impl Subject for Terms {
401 type Node = usize;
402
403 fn head(&self, node: usize) -> Option<(&str, usize)> {
404 match &self.nodes[node] {
405 Held::App(head, args) => Some((head.as_str(), args.len())),
406 Held::Int(_) => None,
407 }
408 }
409
410 fn arg(&self, node: usize, index: usize) -> usize {
411 match &self.nodes[node] {
412 Held::App(_, args) => args[index],
413 Held::Int(_) => unreachable!("a constant has no arguments"),
414 }
415 }
416
417 fn int(&self, node: usize) -> Option<i128> {
418 match self.nodes[node] {
419 Held::Int(value) => Some(value),
420 Held::App(..) => None,
421 }
422 }
423
424 // An index into the arena is the identity of a term here, so two places are the same
425 // thing when they point at the same entry. A subject over the IR answers this out of the
426 // value each place holds instead, which is the same question asked of a different shape.
427 fn same(&self, a: usize, b: usize) -> bool {
428 a == b
429 }
430 }
431
432 /// A table written by hand, in the shape `rucc-rules` emits.
433 ///
434 /// Three rules over `(add x k)`: the first wants the constant to be zero, the second takes
435 /// any constant that is not negative, and the third, on the same node as the second, takes
436 /// one below minus ten. That is enough to exercise everything the walk does, which is a
437 /// concrete test before a wildcard, a guard that can refuse, the next rule on the node being
438 /// asked when it does, and the search carrying on after all of them have. A fourth rule,
439 /// `(and x x)`, is the one that writes a name twice.
440 /// A node with nothing on it, so that the ones below say only what they are about.
441 const NOTHING: Node = Node { heads: &[], ints: &[], same: &[], wildcard: None, accept: &[] };
442
443 static NODES: &[Node] = &[
444 // 0, the root.
445 Node { heads: &[("add", 2, 1), ("and", 2, 5)], ..NOTHING },
446 // 1, the first operand.
447 Node { wildcard: Some(("x", 2)), ..NOTHING },
448 // 2, the second operand.
449 Node { ints: &[(0, 3)], wildcard: Some(("k", 4)), ..NOTHING },
450 // 3, an addition of zero.
451 Node { accept: &[0], ..NOTHING },
452 // 4, an addition of anything, if one of the two guards holds.
453 Node { accept: &[1, 3], ..NOTHING },
454 // 5, the first operand of the conjunction, which is the one that binds.
455 Node { wildcard: Some(("x", 6)), ..NOTHING },
456 // 6, the second operand, which has to be what the first one bound.
457 Node { same: &[(0, 7)], ..NOTHING },
458 // 7, a conjunction of one thing with itself.
459 Node { accept: &[2], ..NOTHING },
460 ];
461
462 fn not_negative(bound: &[Option<i128>]) -> bool {
463 let Some(Some(k)) = bound.get(1).copied() else { return false };
464 k >= 0
465 }
466
467 fn far_below(bound: &[Option<i128>]) -> bool {
468 let Some(Some(k)) = bound.get(1).copied() else { return false };
469 k < -10
470 }
471
472 static RULES: &[Rule] = &[
473 Rule {
474 pattern: "(add x 0)",
475 replacement: &[Piece::Var { name: "x", index: 0 }],
476 guard: None,
477 line: 1,
478 },
479 Rule {
480 pattern: "(add x k)",
481 replacement: &[
482 Piece::App { head: "add_immediate", arity: 2 },
483 Piece::Var { name: "x", index: 0 },
484 Piece::Var { name: "k", index: 1 },
485 ],
486 guard: Some(not_negative),
487 line: 2,
488 },
489 Rule {
490 pattern: "(and x x)",
491 replacement: &[Piece::Var { name: "x", index: 0 }],
492 guard: None,
493 line: 3,
494 },
495 Rule {
496 pattern: "(add x k)",
497 replacement: &[
498 Piece::App { head: "add_far", arity: 2 },
499 Piece::Var { name: "x", index: 0 },
500 Piece::Var { name: "k", index: 1 },
501 ],
502 guard: Some(far_below),
503 line: 4,
504 },
505 ];
506
507 static TABLE: Table = Table { source: "rules/test.rules", nodes: NODES, rules: RULES };
508
509 fn add(terms: &mut Terms, second: usize) -> usize {
510 let first = terms.app("v0", &[]);
511 terms.app("add", &[first, second])
512 }
513
514 /// The concrete test is tried before the wildcard, so the rule about zero wins over the rule
515 /// about any constant even though both of them match. That is the whole of what specificity
516 /// order means here, and it falls out of the shape of the trie.
517 #[test]
518 fn the_rule_that_names_the_operand_beats_the_rule_that_takes_anything() {
519 let mut terms = Terms::default();
520 let zero = terms.constant(0);
521 let term = add(&mut terms, zero);
522 let found = TABLE.find(&terms, term).expect("a rule fires");
523 assert_eq!(TABLE.rule(&found).pattern, "(add x 0)");
524 }
525
526 /// The bindings come back in the order the pattern binds them, which is the pre-order the
527 /// replacement was flattened in, so a `Piece::Var` can be read as an index into them.
528 #[test]
529 fn a_match_gives_back_what_the_pattern_bound_in_the_order_it_bound_it() {
530 let mut terms = Terms::default();
531 let seven = terms.constant(7);
532 let term = add(&mut terms, seven);
533 let found = TABLE.find(&terms, term).expect("a rule fires");
534 let rule = TABLE.rule(&found);
535 assert_eq!(rule.pattern, "(add x k)");
536 assert_eq!(rule.head(), Some("add_immediate"));
537 assert_eq!(found.bindings.len(), 2);
538 assert_eq!(found.bindings[1], seven);
539 assert_eq!(terms.int(found.bindings[1]), Some(7));
540 }
541
542 /// A guard that does not hold is a rule that did not match, and there is nothing else to
543 /// try, so the answer is nothing rather than the wrong rule.
544 #[test]
545 fn a_guard_that_refuses_takes_its_rule_out_of_the_running() {
546 let mut terms = Terms::default();
547 let negative = terms.constant(-1);
548 let term = add(&mut terms, negative);
549 assert_eq!(TABLE.find(&terms, term), None);
550 }
551
552 /// Two rules with one pattern, and the second is asked when the first one's guard refuses.
553 #[test]
554 fn a_rule_that_shares_its_pattern_fires_when_the_one_before_it_refuses() {
555 let mut terms = Terms::default();
556 let far = terms.constant(-20);
557 let term = add(&mut terms, far);
558 let found = TABLE.find(&terms, term).expect("a rule fires");
559 assert_eq!(TABLE.rule(&found).head(), Some("add_far"));
560 let near = terms.constant(20);
561 let term = add(&mut terms, near);
562 let found = TABLE.find(&terms, term).expect("a rule fires");
563 assert_eq!(TABLE.rule(&found).head(), Some("add_immediate"));
564 }
565
566 /// The same guard against an operand that is not a constant at all. A guard is a claim about
567 /// a number, so a register makes it false rather than an error.
568 #[test]
569 fn a_guard_about_a_number_refuses_an_operand_that_is_not_one() {
570 let mut terms = Terms::default();
571 let other = terms.app("v1", &[]);
572 let term = add(&mut terms, other);
573 assert_eq!(TABLE.find(&terms, term), None);
574 }
575
576 #[test]
577 fn a_term_no_rule_covers_finds_no_rule() {
578 let mut terms = Terms::default();
579 let x = terms.app("v0", &[]);
580 let y = terms.app("v1", &[]);
581 let term = terms.app("no.such.head", &[x, y]);
582 assert_eq!(TABLE.find(&terms, term), None);
583 }
584
585 /// The rule that writes one name twice. Both operands are the same term, so the test that
586 /// they are holds and the rule fires, and what comes back is the one binding the pattern
587 /// made rather than two.
588 #[test]
589 fn a_pattern_that_names_one_hole_twice_matches_a_term_that_has_one_thing_in_both() {
590 let mut terms = Terms::default();
591 let x = terms.app("v0", &[]);
592 let term = terms.app("and", &[x, x]);
593 let found = TABLE.find(&terms, term).expect("a rule fires");
594 assert_eq!(TABLE.rule(&found).pattern, "(and x x)");
595 assert_eq!(found.bindings, vec![x]);
596 }
597
598 /// The same rule against two different terms. There is no wildcard beside the test, so a
599 /// conjunction of two things is a conjunction no rule covers rather than one this rule
600 /// wrongly claims.
601 #[test]
602 fn a_pattern_that_names_one_hole_twice_refuses_a_term_that_has_two_things_in_it() {
603 let mut terms = Terms::default();
604 let x = terms.app("v0", &[]);
605 let y = terms.app("v1", &[]);
606 let term = terms.app("and", &[x, y]);
607 assert_eq!(TABLE.find(&terms, term), None);
608 }
609
610 /// The branch is found rather than looked for, which is the thing a node being sorted buys.
611 /// A node as wide as the root of a real rule set answers in the same number of comparisons a
612 /// node with eight branches does, and it answers about the head it was never given by not
613 /// finding one rather than by reading to the end.
614 #[test]
615 fn a_branch_is_found_by_searching_the_node_and_not_by_reading_it() {
616 static WIDE: &[(&str, usize, u32)] = &[
617 ("add.i16", 2, 1),
618 ("add.i32", 2, 2),
619 ("add.i64", 2, 3),
620 ("add.i64", 3, 4),
621 ("sub.i32", 2, 5),
622 ("sub.i64", 2, 6),
623 ("xor.i8", 2, 7),
624 ];
625 let node = Node { heads: WIDE, ..NOTHING };
626 assert!(WIDE.is_sorted(), "the search is only a search if the node is in order");
627 assert_eq!(node.branch("add.i64", 2), Some(3));
628 assert_eq!(node.branch("add.i16", 2), Some(1));
629 assert_eq!(node.branch("xor.i8", 2), Some(7));
630 // The same name at two arities is two branches, and they are told apart.
631 assert_eq!(node.branch("add.i64", 3), Some(4));
632 // A head no branch is about, and one the node has at another arity, are both nothing.
633 assert_eq!(node.branch("mul.i64", 2), None);
634 assert_eq!(node.branch("sub.i32", 3), None);
635 }
636
637 /// The same for a constant, which is the other kind of branch that can be searched.
638 #[test]
639 fn a_literal_is_found_by_searching_too() {
640 let node = Node { ints: &[(-8, 1), (0, 2), (1, 3), (4096, 4)], ..NOTHING };
641 assert_eq!(node.literal(-8), Some(1));
642 assert_eq!(node.literal(0), Some(2));
643 assert_eq!(node.literal(4096), Some(4));
644 assert_eq!(node.literal(7), None);
645 }
646
647 /// The order the kinds of question are asked in, which is the heuristic the module doc
648 /// states. It only decides anything when one node asks two kinds about one place and the
649 /// subject answers both, which is why this needs a subject of its own: the one above answers
650 /// either what a term is called or what number it is, never both, and so does the IR. What is
651 /// asserted is the order that is written down, so that a rule set which starts to depend on
652 /// it gets the answer somebody chose rather than the one that fell out.
653 #[test]
654 fn the_head_is_asked_about_before_the_value_and_the_value_before_a_repeat() {
655 /// `(f a a)`, where each operand is an application and a number at the same time and the
656 /// two of them are one thing. Every question a node can ask is true of them, so which
657 /// one is asked first is the only thing that decides the answer.
658 #[derive(Debug)]
659 struct Both;
660
661 impl Subject for Both {
662 type Node = u8;
663
664 fn head(&self, node: u8) -> Option<(&str, usize)> {
665 if node == 0 { Some(("f", 2)) } else { Some(("k", 0)) }
666 }
667
668 fn int(&self, node: u8) -> Option<i128> {
669 if node == 0 { None } else { Some(7) }
670 }
671
672 fn arg(&self, _: u8, _: usize) -> u8 {
673 1
674 }
675
676 fn same(&self, _: u8, _: u8) -> bool {
677 true
678 }
679 }
680
681 static FOUR: &[Rule] = &[
682 Rule { pattern: "the head", replacement: &[], guard: None, line: 1 },
683 Rule { pattern: "the value", replacement: &[], guard: None, line: 2 },
684 Rule { pattern: "the repeat", replacement: &[], guard: None, line: 3 },
685 Rule { pattern: "the hole", replacement: &[], guard: None, line: 4 },
686 ];
687
688 /// The four ends, and in front of them the node that binds the first operand so that
689 /// there is something for a repeat to be a repeat of.
690 fn table(second: &'static Node) -> Table {
691 let nodes: &'static [Node] = Box::leak(Box::new([
692 Node { heads: &[("f", 2, 1)], ..NOTHING },
693 Node { wildcard: Some(("x", 2)), ..NOTHING },
694 *second,
695 Node { accept: &[0], ..NOTHING },
696 Node { accept: &[1], ..NOTHING },
697 Node { accept: &[2], ..NOTHING },
698 Node { accept: &[3], ..NOTHING },
699 ]));
700 Table { source: "rules/test.rules", nodes, rules: FOUR }
701 }
702
703 // All three kinds on one node, with a hole behind them.
704 static MIXED: Node = Node {
705 heads: &[("k", 0, 3)],
706 ints: &[(7, 4)],
707 same: &[(0, 5)],
708 wildcard: Some(("y", 6)),
709 accept: &[],
710 };
711 assert_eq!(table(&MIXED).find(&Both, 0).map(|found| found.rule), Some(0));
712
713 // The same node without the head, which is what puts the value in front.
714 static WITHOUT_HEAD: Node = Node { heads: &[], ..MIXED };
715 assert_eq!(table(&WITHOUT_HEAD).find(&Both, 0).map(|found| found.rule), Some(1));
716
717 // And without either, which leaves the repeat in front of the hole. That last pair is
718 // the one that is not a heuristic: a concrete question always comes before the hole.
719 static REPEAT: Node = Node { ints: &[], ..WITHOUT_HEAD };
720 assert_eq!(table(&REPEAT).find(&Both, 0).map(|found| found.rule), Some(2));
721
722 // And with nothing concrete left, the hole.
723 static HOLE: Node = Node { same: &[], ..REPEAT };
724 assert_eq!(table(&HOLE).find(&Both, 0).map(|found| found.rule), Some(3));
725 }
726
727 /// A match is what a caller keeps, so it says what it is when a test prints it.
728 #[test]
729 fn a_match_names_the_rule_it_found() {
730 let mut terms = Terms::default();
731 let zero = terms.constant(0);
732 let term = add(&mut terms, zero);
733 assert_eq!(TABLE.find(&terms, term), Some(Match { rule: 0, bindings: vec![term - 1] }));
734 }
735}