Skip to main content

patterns

Macro patterns 

Source
patterns!() { /* proc-macro */ }
Expand description

Proc-macro for declarative pattern rewrite rules.

Generates a SimplifiedPatternMatcher from a list of pattern rewrite rules. Patterns are compiled to efficient Rust code with O(1) dispatch via OpKey.

§Syntax Overview

patterns! {
    // Basic rule: pattern ~> rewrite (or => for fallible)
    Add(x, @zero) ~> x,

    // With guard clause
    Mul(x, y) if is_power_of_two(y) => { ... },

    // For-loop to apply same pattern to multiple ops
    for op in binary [Add, Mul, Sub] {
        op(x, @zero) ~> x,
    }
}

§Arrow Types

  • ~> Infallible: Closure returns Arc<UOp> directly
  • => Fallible: Closure returns Option<Arc<UOp>>

§Pattern Syntax

§Operation Patterns

Add(x, y)           // Tuple-style: match by position
Cast { src, dtype } // Struct-style: match by field name

§Special Constants

  • @zero - Matches constant zero (any numeric type)
  • @one - Matches constant one (any numeric type)
  • @const(cv) - Matches any constant, binds value to cv: &ConstValue
  • _c@const(cv) - Underscore prefix: don’t bind the UOp, only the value

§Duplicate Variables (Auto ptr_eq)

Same variable name appearing multiple times generates Arc::ptr_eq checks:

Add(x, x) ~> ...    // Matches when both children are the same node
Where(x, x, x) ~> ...  // All three must be ptr_eq

§Commutative Matching

Square brackets enable commutative matching (tries both orderings):

Add[x, @zero] ~> x  // Matches Add(x, 0) or Add(0, x)

§Alternative Patterns

Match any of several patterns:

(Add | Sub)(x, @zero) ~> x  // Matches Add(x, 0) or Sub(x, 0)

§Binding Patterns

Bind a name to a subpattern:

result@Add(x, y) => { ... use result, x, y ... }

§For-Loops

Apply the same pattern template to multiple operations:

for op in unary [Neg, Not, Sqrt] {
    op(x) if is_const(x) => { fold_unary(op, x) }
}

for op in binary [Add, Mul, Sub] {
    op(x, @zero) ~> x,
}

§Context Types

Declare a context type to pass mutable state through patterns:

patterns! {
    @context MyContext;

    Add(x, y) => |ctx, x, y| {
        ctx.record_match();
        Some(x.clone())
    }
}

§Generated Code

This macro generates a SimplifiedPatternMatcher with:

  • Compile-time validation of all operation names
  • O(1) dispatch via OpKey hashmap
  • Inline pattern matching (no runtime pattern interpretation)
  • Automatic Arc::ptr_eq checks for duplicate variables