Skip to main content

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