Pattern Matching Compilation
TL;DR This is republishing of my article about Pattern Matching Compilation (PMC) for Cloudozer's discontinued LLVM F:> language L dated back in 2014-07-07. It is more like PMC survey.
Here is the description of Patterm Matching Compilation scheme used in L. Obviously compiler should optimize matching tree for number of comparisons, the processing speed. Next, if possible, optimize the size of decision tree, the code size. It is well known that producing smallest decision tree is NP-hard. That is why was proposed a several heuristics
— Relevance (Baudined, MacQueen, 1985)
— Arity Factor (Baudinet, MacQueen, 1985)
— Small Defaults (Baudinet, MacQueen, 1985)
— Fewer Child Rules (Maranget, 1992, Ramsey, Fernandez, 1995)
— Left to Right (Sestoft, 1996, Moscow ML, OCaml, MLKit)
— Small Branching Factor (SML/NJ)
— Large Branching Factor (Cardelli, 1984)
— Leaf Edges
— Artificial Rule
— Right to Left Top-down
In this document we will generalize all heuristics and also provide extra information about binary strings and named tuples pattern maching.
Here is example of patterns set which should be matched along x with minimal set of atomic operations like SWITCH. You may specify patterns of any type. Consider the type of x an alberaic sum type of all patterns. Subsums of same type patterns is being processed separately, producing different decision tree for each type.
First of all patterns should be filtered by the type of x. L compiler should compile only patterns that fit its type.
All cells in the matrix coule be vars, wildcards, constants or type constructors. Type constructors like cons or tuple encoded with type tag information, thus type constructors is allowed to use in SWITCH along with constants. Constants are encoded with int, atom, nil and other value types.
In runtime the value will holds the type index nunber, while the type information will be erased. E.g. some set of patterns may fall the same type, like in example assuming x is list of deep 2. The first four patterns has the same type (_,(_,_)) — list of length two.
After normalized M-arity matrix with N rules we can apply selected algorithm directly. We call decision tree efficient if it examines each matrix cell at most once. In this sense Mac-Queen (1985), Laville (1991), Maranget (1992), Sestoft (1996) are efficient while Augustsson (1985), Wadler (1987), Maranget (1994) are not.
Usually each heuristic is dealing with only one column. Depending on the function result over column (e.g. equality), we can apply another heuristic on the same step, in other words we can compose heuristics.
As we can do SWITCH operation only over constants and type constructors (encoded in memory with type tag) we take constants and constructors number of occurance with positive sign. The vars and wildcards (which could be treated as vars that are not binded in matched expression) are counted with negated weight during heuristic decision.
In some cases base heuristics could be extended with additional information. E.g. you can observe not only the number of constructors, but also count the sum of their arity.
Most Constants or Constructors
Consider having simple case with vars and constants. We will use here only SWITCH target LLVM instruction and ELEMENT runtime tuple extraction.
Left to Right
Matching binary string with variable segment size is slightly different from matching alge- braic data types.
To unvail the power of binary segments pattern maching, we should extend the target language [SWITCH,ELEMENT,TAG,BIND] with [READ,SIZE,SCAN] operations. READ operation scans the bit string of variable size and SIZE operation is a guard that does range checks.
One can extend the operation set with SCAN operation, which scans the bit string till a given byte or pattern. And you can also specify scan sections multiple times. The only rule is that rest/binary sections should be separated with constant bitstring.
Multiple scans binding is another possible evolution of bitstring pattern matching. Often used in video decoders, we need a case to fold several sequential null-terminated strings into one list of binded variables.
Here Strings will be binded with an list of null-terminated strings, and N will be binded with number of its occurance.
Named Tuples could be easily transformed to normalized by constructing smallest union the tuple keys.
List Matching Sample
The test coverage should include lists, deep lists and tuples custom heuristic cases. Here is example of deep list pattern matching.
The PMC output:
The alrorithm uses Left to Right strategy for Lists and it is possible to plug any heuristics for Tuples matching. Type Constructors and Constant Values comes withing the same container and so do Variables and Wildcards. On the low level switch among Constructors and Constant Values should be handled separately, here its unified for clarity.
1. Peter Sestoft. ML Pattern Match Compilation. 1996
2. Luc Maranget. Compiling Pattern Matching. 2008
3. SPJ, Philip Wadler. Implementation of Functional Languages. 1958.