Skip to main content

rucc_rules/
matcher.rs

1//! Rules to the automaton that matches them.
2//!
3//! A pattern is a tree and the subject is a tree, and the obvious way to match one against the
4//! other is a chain of conditionals per rule. That is what `spec/10-backend.md` says not to
5//! build: with several hundred rules per target it re-tests the same opcode hundreds of times,
6//! and it puts the order the rules are tried in beyond anybody's control.
7//!
8//! What is built instead is a trie over the patterns, flattened. Every pattern becomes a
9//! sequence of steps read in pre-order, and patterns that begin the same way share the steps
10//! they agree on, so testing that a term is an `add.i64` happens once no matter how many rules
11//! begin with one. Matching walks the subject in the same pre-order, which is what makes the
12//! sequence well defined: at any node of the trie, every rule that reaches it has consumed the
13//! same shape of subject, so there is one stack of remaining subterms rather than one per rule.
14//!
15//! Specificity falls out of the shape rather than being sorted for. At each node the concrete
16//! tests are tried before the wildcard, so a rule that names an operand is always tried before
17//! a rule that takes anything there, which is the maximal munch that document asks for. Among
18//! rules that are equally specific the first one written wins, which is what `-O0` wants and is
19//! what the single-pass mode in section 10.3 is defined to do.
20//!
21//! A name written twice in one pattern is a claim that the two places hold the same thing, which
22//! is how the identities of `spec/optimizer/13-rewrite-rules.md` section 13.4 say `x & x` and
23//! `x - x`. The second occurrence becomes a test rather than a binding, so it costs one
24//! comparison and sits with the other concrete tests, ahead of the wildcard, where a rule about
25//! one value in both operands belongs.
26//!
27//! # Choosing a branch without reading every branch
28//!
29//! `spec/optimizer/36-lowering-and-isel.md` section 36.5 asks for the decision to be on the shape
30//! of the term rather than on the identity of the pattern, which is the difference between a trie
31//! that is a tree and a trie that is a tree with a list at every node. Sharing a prefix already
32//! means the head of a term is tested once rather than once per rule, but it does not say how the
33//! branch is found, and reading a node's branches in the order the rules were written is a scan
34//! over all of them. That costs what the widest node is wide: the x86-64 rule set has a hundred
35//! and sixty seven different heads a pattern can begin with, so choosing the branch for an
36//! `add.i64` meant asking a hundred and sixty six other questions first, once for every
37//! instruction the selector looks at, and a term no rule covers asked all of them.
38//!
39//! So a node holds its branches by the kind of question they ask, and the two kinds that can be
40//! searched are kept sorted: the heads by name and then by how many arguments they take, and the
41//! literals by value. At most one of either can match a subterm, because a term has one head and
42//! a constant has one value, so the order inside those two is not observable and sorting them
43//! costs nothing. Finding the branch is then a binary search, which is eight comparisons at that
44//! widest node rather than a hundred and sixty seven.
45//!
46//! # The order the kinds are tried in
47//!
48//! Which kind is asked first is a heuristic, and section 36.5 is explicit that a heuristic is to
49//! be stated rather than left to be discovered by reading what came out. The order is: the head
50//! of the term, then its value as a literal, then whether it is what an earlier binding took,
51//! then the hole that takes anything. The first three are all concrete and the hole is last,
52//! which is the specificity order above and is the part that decides which rule fires.
53//!
54//! The order among the first three decides nothing in any rule set here, because deciding
55//! something would need one node to ask two kinds of question about one place, and none does: a
56//! literal is only ever written where a pattern has descended into a constant, and a name written
57//! twice is only ever written where the first occurrence put a hole. [`Matcher::shape`] counts
58//! the nodes that mix kinds for exactly this reason, so that a rule set which starts to depend on
59//! the order is a number that changed rather than a surprise in the output.
60
61use std::fmt;
62
63use crate::ast::{Rule, Term, TermKind};
64use crate::error::Error;
65
66/// One step of a flattened pattern.
67#[derive(Debug, Clone, PartialEq, Eq)]
68enum Step {
69    /// The subterm here must be this head applied to this many arguments.
70    App { head: String, arity: usize },
71    /// The subterm here must be this literal.
72    Int(i128),
73    /// Anything goes here, and it is remembered under this name.
74    Bind(String),
75    /// The subterm here must be what this binding of the same pattern already took, which is
76    /// what the second occurrence of a name means.
77    Same(usize),
78}
79
80/// One node of the trie.
81///
82/// The branches are held by the kind of question they ask rather than in one list, which is what
83/// lets the two searchable kinds be searched. A hole is not one of them: it is not a question, it
84/// is what is left when none of the questions was answered.
85#[derive(Debug, Default)]
86pub(crate) struct Node {
87    /// The branches taken on the head of the subterm, sorted by name and then by how many
88    /// arguments it takes.
89    pub(crate) heads: Vec<(String, usize, usize)>,
90    /// The branches taken on the value of a subterm that is a constant, sorted by value.
91    pub(crate) ints: Vec<(i128, usize)>,
92    /// The branches taken when the subterm is what an earlier binding took, in the order the
93    /// rules were written, because two of them can match one subterm.
94    pub(crate) same: Vec<(usize, usize)>,
95    /// The branch that takes anything, and the name it binds it under.
96    pub(crate) wildcard: Option<(String, usize)>,
97    /// The rule that ends here, if one does.
98    pub(crate) accept: Option<usize>,
99}
100
101impl Node {
102    /// Every branch this node has, in the order the walk tries them, which is what printing it
103    /// and counting it are both written against.
104    fn branches(&self) -> impl Iterator<Item = (Shown<'_>, usize)> {
105        let heads = self.heads.iter().map(|(head, arity, next)| (Shown::App(head, *arity), *next));
106        let ints = self.ints.iter().map(|&(value, next)| (Shown::Int(value), next));
107        let same = self.same.iter().map(|&(index, next)| (Shown::Same(index), next));
108        heads.chain(ints).chain(same)
109    }
110
111    /// How many kinds of question this node asks. More than one means the order the kinds are
112    /// tried in decides which rule fires here.
113    fn kinds(&self) -> usize {
114        usize::from(!self.heads.is_empty())
115            + usize::from(!self.ints.is_empty())
116            + usize::from(!self.same.is_empty())
117    }
118}
119
120/// One branch of a node as something to print.
121enum Shown<'a> {
122    App(&'a str, usize),
123    Int(i128),
124    Same(usize),
125}
126
127/// What a rule set costs to match against, which is what the header of a generated table says
128/// and what a test that the tree is a tree asserts.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub struct Shape {
131    /// How many nodes the trie has.
132    pub nodes: usize,
133    /// How many branches the widest node has, which is what a scan over it would cost.
134    pub widest: usize,
135    /// How many comparisons a binary search over that many branches takes.
136    pub search: usize,
137    /// How many nodes ask more than one kind of question, and so depend on the order the kinds
138    /// are tried in. Nothing shipped here does.
139    pub mixed: usize,
140}
141
142/// The automaton a rule set compiles into.
143#[derive(Debug)]
144pub struct Matcher {
145    pub(crate) nodes: Vec<Node>,
146}
147
148/// What a successful match found.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct Match<'t> {
151    /// The index into the rule set of the rule that fired.
152    pub rule: usize,
153    /// What the pattern's variables were bound to, in the order the pattern binds them.
154    pub bindings: Vec<(String, &'t Term)>,
155}
156
157impl<'t> Match<'t> {
158    /// What one name was bound to, or nothing if the pattern never bound it.
159    #[must_use]
160    pub fn get(&self, name: &str) -> Option<&'t Term> {
161        self.bindings.iter().find(|(bound, _)| bound == name).map(|(_, term)| *term)
162    }
163}
164
165impl Matcher {
166    /// Compile a rule set.
167    ///
168    /// # Errors
169    ///
170    /// A rule whose pattern is one an earlier rule already has can never fire, and that is
171    /// reported rather than silently dropped. It is always a mistake: either the second rule was
172    /// meant to say something else, or one of the two should not be there.
173    pub fn build(path: &str, rules: &[Rule]) -> Result<Matcher, Vec<Error>> {
174        let mut matcher = Matcher { nodes: vec![Node::default()] };
175        let mut errors = Vec::new();
176
177        for (index, rule) in rules.iter().enumerate() {
178            let mut at = 0;
179            for step in flatten(&rule.pattern) {
180                at = matcher.follow(at, step);
181            }
182            match matcher.nodes[at].accept {
183                Some(first) => errors.push(Error {
184                    path: path.to_owned(),
185                    line: rule.line,
186                    column: rule.column,
187                    message: format!(
188                        "this rule can never fire, because the rule on line {} matches everything it does",
189                        rules[first].line
190                    ),
191                }),
192                None => matcher.nodes[at].accept = Some(index),
193            }
194        }
195
196        if !errors.is_empty() {
197            return Err(errors);
198        }
199        matcher.sort();
200        Ok(matcher)
201    }
202
203    /// Add one step at one node, reusing the branch if it is already there.
204    fn follow(&mut self, at: usize, step: Step) -> usize {
205        match step {
206            Step::App { head, arity } => {
207                let found = self.nodes[at]
208                    .heads
209                    .iter()
210                    .find(|(have, count, _)| *have == head && *count == arity);
211                if let Some(&(_, _, next)) = found {
212                    return next;
213                }
214                let next = self.push();
215                self.nodes[at].heads.push((head, arity, next));
216                next
217            }
218            Step::Int(value) => {
219                if let Some(&(_, next)) =
220                    self.nodes[at].ints.iter().find(|(have, _)| *have == value)
221                {
222                    return next;
223                }
224                let next = self.push();
225                self.nodes[at].ints.push((value, next));
226                next
227            }
228            Step::Same(index) => {
229                if let Some(&(_, next)) =
230                    self.nodes[at].same.iter().find(|(have, _)| *have == index)
231                {
232                    return next;
233                }
234                let next = self.push();
235                self.nodes[at].same.push((index, next));
236                next
237            }
238            Step::Bind(name) => {
239                if let Some((_, next)) = &self.nodes[at].wildcard {
240                    // The name is the first one written. Two rules that put different names in
241                    // the same hole are the same automaton, and the binding is reported back
242                    // under the name of the rule that fired rather than under this one.
243                    return *next;
244                }
245                let next = self.push();
246                self.nodes[at].wildcard = Some((name, next));
247                next
248            }
249        }
250    }
251
252    /// Put the searchable branches in the order a search needs them.
253    ///
254    /// This is the last thing the build does, so that everything before it can add a branch by
255    /// pushing. Nothing about which rule fires depends on it: one head matches a term and one
256    /// value matches a constant, so the order inside either list is not something a match can
257    /// observe. What it buys is that the walk can binary search rather than read the list.
258    fn sort(&mut self) {
259        for node in &mut self.nodes {
260            node.heads.sort_by(|(head, arity, _), (other, count, _)| {
261                head.cmp(other).then(arity.cmp(count))
262            });
263            node.ints.sort_by_key(|&(value, _)| value);
264        }
265    }
266
267    fn push(&mut self) -> usize {
268        self.nodes.push(Node::default());
269        self.nodes.len() - 1
270    }
271
272    /// Match one term against the whole rule set, returning the rule that fires.
273    ///
274    /// The term is matched as a whole. Finding the subterms of a function worth matching is the
275    /// selector's job and not this one's.
276    #[must_use]
277    pub fn find<'t>(&self, term: &'t Term) -> Option<Match<'t>> {
278        let mut bindings = Vec::new();
279        let rule = self.run(0, vec![term], &mut bindings)?;
280        Some(Match { rule, bindings })
281    }
282
283    /// Walk the trie and the subject together.
284    ///
285    /// `left` is the subterms still to be matched, innermost last, so that popping gives the
286    /// pre-order the patterns were flattened in.
287    fn run<'t>(
288        &self,
289        at: usize,
290        mut left: Vec<&'t Term>,
291        bindings: &mut Vec<(String, &'t Term)>,
292    ) -> Option<usize> {
293        let Some(subject) = left.pop() else {
294            return self.nodes[at].accept;
295        };
296        let node = &self.nodes[at];
297
298        // The head, the value and the repeat, in that order, which is the heuristic the module
299        // doc states. At most one head and at most one value can match, so each of those is a
300        // search rather than a walk, which is the same shape the compiler's own walk has.
301        let mut taken: Vec<usize> = Vec::new();
302        if let TermKind::App { head, args } = &subject.kind {
303            let found = node
304                .heads
305                .binary_search_by(|(have, count, _)| {
306                    have.as_str().cmp(head.as_str()).then(count.cmp(&args.len()))
307                })
308                .ok();
309            taken.extend(found.map(|at| node.heads[at].2));
310        }
311        if let TermKind::Int(value) = &subject.kind {
312            let found = node.ints.binary_search_by(|(have, _)| have.cmp(value)).ok();
313            taken.extend(found.map(|at| node.ints[at].1));
314        }
315        // Written out rather than compared with `==`, because a term carries where it was
316        // written and two occurrences of one name are in two different places.
317        for &(index, next) in &node.same {
318            if bindings.get(index).is_some_and(|(_, bound)| alike(bound, subject)) {
319                taken.push(next);
320            }
321        }
322
323        for next in taken {
324            let mut deeper = left.clone();
325            if let TermKind::App { args, .. } = &subject.kind {
326                deeper.extend(args.iter().rev());
327            }
328            let depth = bindings.len();
329            if let Some(rule) = self.run(next, deeper, bindings) {
330                return Some(rule);
331            }
332            bindings.truncate(depth);
333        }
334
335        // The wildcard is last, which is the whole of what "specificity order" means here.
336        let (name, next) = node.wildcard.as_ref()?;
337        let depth = bindings.len();
338        bindings.push((name.clone(), subject));
339        if let Some(rule) = self.run(*next, left, bindings) {
340            return Some(rule);
341        }
342        bindings.truncate(depth);
343        None
344    }
345
346    /// How many nodes the trie has, which is what a rule set costs to match against.
347    #[must_use]
348    pub fn len(&self) -> usize {
349        self.nodes.len()
350    }
351
352    /// Whether the rule set was empty.
353    #[must_use]
354    pub fn is_empty(&self) -> bool {
355        self.nodes.len() <= 1
356    }
357
358    /// What this rule set costs to match against.
359    ///
360    /// The widest node is the measurement that matters, because it is the one the shape of the
361    /// tree was changed for: it is what a scan would read to the end of and what a search reads
362    /// eight of. It goes in the header of the generated table, where somebody reviewing a rule
363    /// they added can see what adding it did.
364    #[must_use]
365    pub fn shape(&self) -> Shape {
366        let widest = self.nodes.iter().map(|node| node.branches().count()).max().unwrap_or(0);
367        Shape {
368            nodes: self.nodes.len(),
369            widest,
370            search: usize::try_from(widest.next_power_of_two().trailing_zeros()).unwrap_or(0),
371            mixed: self.nodes.iter().filter(|node| node.kinds() > 1).count(),
372        }
373    }
374}
375
376/// Whether two terms say the same thing, ignoring where each of them was written.
377///
378/// A [`Term`] holds its line and column, so the derived equality is equality of two occurrences
379/// and not of two terms. What a repeated name asks is about the terms.
380fn alike(left: &Term, right: &Term) -> bool {
381    match (&left.kind, &right.kind) {
382        (TermKind::Var(a), TermKind::Var(b)) => a == b,
383        (TermKind::Int(a), TermKind::Int(b)) => a == b,
384        (TermKind::App { head: a, args: xs }, TermKind::App { head: b, args: ys }) => {
385            a == b && xs.len() == ys.len() && xs.iter().zip(ys).all(|(x, y)| alike(x, y))
386        }
387        _ => false,
388    }
389}
390
391/// Flatten a pattern into the steps that match it, in the pre-order the matcher walks.
392fn flatten(pattern: &Term) -> Vec<Step> {
393    let mut out = Vec::new();
394    let mut bound: Vec<&str> = Vec::new();
395    push_steps(pattern, &mut bound, &mut out);
396    out
397}
398
399/// `bound` is the names this pattern has bound so far, in order, so that a name written again
400/// becomes a test against the position the first occurrence took. The position is well defined
401/// across rules that share a prefix: sharing a prefix means having consumed the same shape of
402/// subject, so the same number of bindings have been made at any node of the trie.
403fn push_steps<'t>(term: &'t Term, bound: &mut Vec<&'t str>, out: &mut Vec<Step>) {
404    match &term.kind {
405        TermKind::Var(name) => match bound.iter().position(|have| *have == name.as_str()) {
406            Some(index) => out.push(Step::Same(index)),
407            None => {
408                bound.push(name.as_str());
409                out.push(Step::Bind(name.clone()));
410            }
411        },
412        TermKind::Int(value) => out.push(Step::Int(*value)),
413        TermKind::App { head, args } => {
414            out.push(Step::App { head: head.clone(), arity: args.len() });
415            for arg in args {
416                push_steps(arg, bound, out);
417            }
418        }
419    }
420}
421
422impl fmt::Display for Matcher {
423    /// Prints the trie, one branch to a line, indented by depth. This is what makes a rule set's
424    /// shape reviewable: two rules that share a prefix share a line, and a rule that can only be
425    /// reached through a wildcard is visibly the last thing tried.
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        self.show(f, 0, 0)
428    }
429}
430
431impl Matcher {
432    fn show(&self, f: &mut fmt::Formatter<'_>, at: usize, depth: usize) -> fmt::Result {
433        let pad = "  ".repeat(depth);
434        let node = &self.nodes[at];
435        if let Some(rule) = node.accept {
436            writeln!(f, "{pad}=> rule {rule}")?;
437        }
438        for (branch, next) in node.branches() {
439            match branch {
440                Shown::App(head, arity) => writeln!(f, "{pad}{head}/{arity}")?,
441                Shown::Int(value) => writeln!(f, "{pad}{value}")?,
442                Shown::Same(index) => writeln!(f, "{pad}same as binding {index}")?,
443            }
444            self.show(f, next, depth + 1)?;
445        }
446        if let Some((name, next)) = &node.wildcard {
447            writeln!(f, "{pad}bind {name}")?;
448            self.show(f, *next, depth + 1)?;
449        }
450        Ok(())
451    }
452}