Write a Nim macro that implements a pattern match construct similar to Rust's match.
- User
Write a Nim macro that implements a
pattern matchconstruct similar to Rust'smatch. Assistant
Write a Nim macro that implements a pattern match construct similar to Rust's match.
The user wants a Nim macro that implements pattern matching similar to Rust's match expression.
Key features of Rust's match:
enum, but Rust-style variants carry data)._).if condition).Nim's existing capabilities:
case statement, but it's mostly for simple types (integers, strings, enums). It doesn't destructure objects or tuples nicely.Design of the match macro:
Syntax:
match value:
of pattern1: body1
of pattern2: body2
...
else: bodyElse
Core logic:
The macro needs to transform the input into a chain of if/elif/else or a case statement where possible (for performance), but since we are doing complex matching (like destructuring), an if/elif chain with helper conditions is safer and more general.
Step-by-Step Implementation Plan:
of branch or an else branch.of branches:
match(value, pattern).value into local variables).block:
let matchTarget = value
if matchCond1(matchTarget):
# bindings 1
body1
elif matchCond2(matchTarget):
# bindings 2
body2
...
else:
bodyElse
Handling Patterns (The Hard Part):
123, "hello" -> matchTarget == pattern_ -> truex -> true (and bind x to matchTarget)(a, b) -> check if tuple, check length, recurse.ref object of RootObj or distinct enum discriminators inside objects.
(x, y)).Let's simplify the "Object/Variant" case. In Nim, variant objects usually look like:
type
Shape = object
case kind: ShapeKind
of skCircle: radius: float
of skRect: w, h: float
Matching Shape(skCircle, r) requires checking kind == skCircle and extracting radius into r.
Revised Implementation Strategy (Macro "match"):
I will write a macro match that expands into a case statement for simple types if possible, but mostly an if/elif chain for complex destructuring to allow the flexibility requested.
Actually, the standard "cool" way to do this in Nim macros involves generating specific is checks and extract logic.
Let's draft the AST transformation:
Input:
match x:
of (1, 2): "A"
of (_, y): "B: " & $y
Output (conceptually):
block:
let target = x
if target[0] == 1 and target[1] == 2:
"A"
elif true: # _ matches anything
let y = target[1]
"B: " & $y
Pattern Matching Logic (Recursive Macro or Compile-time Procs):
I need a helper getMatchCondition(pattern, targetSym) that returns a NimNode representing the boolean condition.
I need a helper getMatchBindings(pattern, targetSym) that returns a list of NimNode (specifically let statements).
Supported Patterns:
_ (Wildcard): Matches all. Condition: true. Bindings: None.literal (int/string/float/enum): Condition: target == literal.variable (identifier): Matches all. Bindings: let variable = target.Tuple (pat1, pat2): Condition: target.len == 2 and match(pat1, target[0]) and .... Bindings: Recurse.Handling the "Object Variant" (Case Object) case:
Syntax: of ObjectName(field: val, ...) or standard Nim case object syntax? Rust uses Enum::Variant(...). Nim usually just has objects.
Let's stick to generic tuple/sequence/object destructuring for this implementation to keep the code size reasonable for a single prompt response, but I should mention how to handle enums.
Actually, supporting Nim's case objects is very idiomatic.
Pattern: MyObject(field: val, kind: skSomething)?
Let's stick to a generic tuple/sequence destructure as it demonstrates the power of the macro best.
The match Macro Code Structure:
import macros
macro `match`(value: typed; branches: varargs[untyped]): untyped =
# Create a temporary variable for the value to avoid re-evaluation
let val = genSym(nskLet, "matchValue")
result = newStmtList()
result.add newLetStmt(val, value)
# Build the if/elif/else chain
var ifBranch: NimNode = nil
for b in branches:
# Expecting (pattern, body)
# or "of pattern: body"
# Simplify: assume syntax is:
# match x:
# pattern: body
# pattern: body
# _: elseBody
# Wait, standard Nim syntax `of` is cleaner, but custom macro syntax allows flexible patterns.
# Let's use:
# match x:
# (1, 2): echo "A"
# _: echo "B"
# Parsing the block passed to the macro:
# It comes as a StmtList.
# Inside, we expect Call nodes where the name is presumably empty or it's an Infix `:`
# Actually, in Nim `case` syntax, it's `of pattern: body`.
# If I want `pattern: body`, Nim parses `pattern(body)` if it's one line, or just block structure.
# Let's support the `case` style syntax `of pattern: body` and `else: body`.
# It is more idiomatic.
# Check if branch is `of` statement?
# If user writes `match x: of 1: ...`, `branches` is a `nkOfBranch`.
# If user writes custom syntax, it might be different.
# Let's stick to a simpler structure for the demo:
# match x:
# Pattern: Body
# Nim parses `Pattern: Body` as `nnkCall` where the name is `Pattern` and args[0] is `Body` (if Body is one expr)
# or `nnkCommand`.
# To allow complex patterns like `(1, 2)`, they must be wrapped or parsed carefully.
# `(1, 2)` is a tuple construction. `(1, 2): body` is invalid syntax in Nim outside specific contexts.
# Okay, to make it robust and usable, let's support the syntax:
# match x:
# of [Pattern]: [Body]
# of [Pattern]: [Body]
# else: [Body]
# This aligns with Nim's `case` keyword.
# But `case` in Nim doesn't support destructuring `(a, b)`.
# So the macro `match` will replace `case`.
Wait, case syntax is fixed. I can't easily intercept of (1, 2): if the compiler rejects it before the macro runs.
Nim allows case x of 1..5: ....
If I do case x of (1, 2): ..., Nim might interpret (1, 2) as a set or tuple depending on context, but usually case requires sets or single values.
To support "Rust-like" pattern matching (destructuring), we usually need a custom syntax or overload the of operator if possible (not really).
The standard Nim pattern matching libraries (like regex or patty or gensym) often use a syntax like:
match x:
(_, y) => echo y
But writing a parser for that inside a macro is tedious.
Better Approach:
Use do blocks or a specific structure.
However, the user asked for a macro similar to Rust's match.
Rust: match val { pattern => { ... }, ... }
Nim closest equivalent:
match val:
of pattern: ...
If I use of, the compiler parses the pattern as an expression.
If pattern is (a, b), it's a tuple constructor.
I can inspect the AST of the pattern.
Algorithm for match macro:
Input: value, branches (a block of code).
The branches block contains nnkCall (for pattern: body) or nnkOfBranch?
Actually, if I write:
match x:
of (1, 2): echo "yes"
The compiler parses this as a case statement structure usually, unless match is defined as a template/macro that consumes the block blindly.
If match is a macro taking untyped args, the block is passed as StmtList.
Inside, (1, 2): echo "yes" is parsed as nnkCall.
The callee is the tuple (1, 2). The argument is echo "yes".
So, Pattern: Body -> Call(Pattern, Body).
This works well!
Syntax Definition:
match x:
(1, 2): # Pattern
body
_:
body
Parsing Logic:
Iterate over children of the block.
For each child c:
c is nnkCall:
c[0] is the pattern.c[1] is the body.Pattern: Body where Body is multiple lines?ident: stmt as nnkCall. If Body is a block ident: ..., it might be handled differently.ident: stmt in aStmtList is nnkCall.nnkStmtList inside the call.Handling Guards:
Rust: pattern if guard => body
Nim: pattern (guard): body ? Not standard.
Let's skip guards for the basic version to keep it understandable, or support of pattern: body with an if check inside.
Let's write the macro.
Helper: matches(pattern, target, bindings: var seq[NimNode]): NimNode
bindings to include let var = target.field.Patterns to support:
It supports:
when conditions).import macros
macro `match`(value: typed, branches: varargs[untyped]): untyped =
# Verify we have an even number of arguments in branches (pattern -> body)
# branches is processed as: [pattern1, body1, pattern2, body2, ...]
# Create a temporary symbol for the value to avoid re-evaluating it
let valSym = genSym(nskLet, "matchVal")
# Start building the result: (block: let valSym = value; if/elif/else...)
result = newStmtList()
result.add newLetStmt(valSym, value)
# We construct a chain of if/elif statements
var ifTree = nnkIfStmt.newTree()
# Helper to recursively generate conditions and bindings
proc processPattern(pattern, target: NimNode): tuple[cond: NimNode, lets: seq[NimNode]] =
result.cond = newLit(true)
result.lets = @[]
case pattern.kind
of nnkStmtList, nnkArgList:
# Handle multiple patterns (rare in this syntax, but good for safety)
# or unwrapped tuples in some contexts
if pattern.len == 1:
return processPattern(pattern[0], target)
else:
# Treat as a tuple construction
return processPattern(newNimNode(nnkTupleConstr).add(pattern.children), target)
of nnkPar, nnkTupleConstr:
# Tuple Destructuring: (a, b) or (1, 2)
# Check if target is a tuple (hard to verify compile-time types strictly here,
# we assume valid code generation will be caught by compiler later).
let tupleLen = pattern.len
var conds: seq[NimNode] = @[]
for i, child in pattern:
let indexer = newTree(nnkBracketExpr, target, newLit(i))
let (subCond, subLets) = processPattern(child, indexer)
conds.add subCond
result.lets.add subLets
if conds.len > 0:
var acc = conds[0]
for i in 1..<conds.len:
acc = newBinop("and", acc, conds[i])
result.cond = acc
of nnkInfix:
# Check for "when" guard or logical infix
if pattern[0].eqIdent("when"):
# Pattern is: pattern_inner when condition
let (innerCond, innerLets) = processPattern(pattern[1], target)
result.lets = innerLets
let guardCond = pattern[2]
# Replace 'it' in guard with target?
# For simplicity, variables bound in pattern are available in guard.
result.cond = newBinop("and", innerCond, guardCond)
else:
# Treat as expression (e.g., a..b or custom check)
result.cond = newCall("==", target, pattern)
of nnkIdent:
# Variable Binding or Enum check
let name = pattern.strVal
if name == "_":
result.cond = newLit(true) # Wildcard
elif name.len > 0 and name[0].isLowerAscii:
# Heuristic: Lowercase identifiers are bindings
result.lets.add newLetStmt(pattern, target)
result.cond = newLit(true)
else:
# Heuristic: Uppercase/Other are Enum values or constants
result.cond = newCall("==", target, pattern)
of nnkCharLit..nnkFloat128Lit, nnkStrLit..nnkTripleStrLit, nnkSym:
# Literals
result.cond = newCall("==", target, pattern)
else:
# Fallback: try equality check
result.cond = newCall("==", target, pattern)
# Iterate over branches: pairs of (pattern, body)
for i in countup(0, branches.len - 1, 2):
let pattern = branches[i]
let body = branches[i+1]
let (condition, letStmts) = processPattern(pattern, valSym)
var branchBody = newStmtList()
branchBody.add letStmts
branchBody.add body
# Determine if this is the last branch (potential 'else')
let isLast = (i == branches.len - 2)
# Check if pattern is a pure wildcard or ident "_" to make it an else
let isElse = (pattern.kind == nnkIdent and pattern.eqIdent("_")) or
(condition.kind == nnkBoolLit and condition.boolVal == true and isLast)
if ifTree.len == 0:
ifTree.add newTree(if isElse: nnkElse else: nnkElifBranch, condition, branchBody)
else:
if isElse:
# Convert last elif to else if strictly true?
# Nim's ifStmt requires structure: Elif, Elif... Else.
# We use nnkElse for the final catch-all.
ifTree.add newTree(nnkElse, branchBody)
else:
ifTree.add newTree(nnkElifBranch, condition, branchBody)
result.add ifTree
# --- Example Usage ---
type
Color = enum Red, Green, Blue
Point = object
x, y: int
# Simple literals and binding
let c = Red
match c:
Red: echo "It's Red"
Green: echo "It's Green"
_: echo "It's something else"
# Tuple destructuring
let p = (10, 20)
match p:
(0, 0): echo "Origin"
(x, 0): echo "On X axis at ", x
(0, y): echo "On Y axis at ", y
(x, y): echo "At ", x, ", ", y
# Object variant simulation (using field access logic manually or via helpers)
# Note: True object-variant safety requires more complex macro logic checking discriminants.
# Here is a struct destructuring example:
let myPoint = Point(x: 5, y: 5)
# We can match against the object constructor syntax or tuples
# This macro matches expressions. To match object fields, one usually uses tuples
# or specific library helpers.
# However, since `myPoint` is a `Point`, we can use the tuple syntax
# if we project it to a tuple, or manually check fields:
match (myPoint.x, myPoint.y):
(5, 5): echo "Diagonal center"
(_, 0): echo "On X"
(x, y) when x > 0 and y > 0:
echo "Quadrant 1: ", x, ",", y
_:
echo "Somewhere else"
value followed by varargs[untyped]. The varargs are flattened into a sequence: pattern1, body1, pattern2, body2, etc.valSym to store the input value. This ensures that if you pass a function call match foo() as input, the function is only called once.processPattern:
x), while others are treated as checks (e.g., Red).(a, b) compiles to val[0] == a_val and val[1] == b_val.when infix operator in the pattern (e.g., x when x > 5).if/elif/else statement. The body of the match is augmented with let statements for any variable bindings found in the pattern._: Returns newLit(true).Literal: Returns infix(target, "==", pattern).Ident (Variable binding): Binds the name to target. Returns newLit(true).Tuple (p1, p2):
target.len == pattern.len.matches for p1 vs target[0], etc.and.Handling Object Variants (Enums with data):
This requires inspecting the type of target.
If target is an object with a discriminant, we check the discriminant.
Since generic macro support for arbitrary object inspection is complex, I will stick to Tuples and simple types for this demo, but add a mechanism to extract fields if the pattern looks like Ident(field: val).
Refining the Syntax:
To allow else or _, I'll check the pattern.
_ is an ident node with name _.
x is an ident node.
Constructing the result:
block:
let tmp = value
if condition1(tmp):
let b1 = ...
let b2 = ...
body1
elif condition2(tmp):
...
else:
(if provided)
Corner Case:
What if the user writes of 1: ...?
The parser sees of as an identifier.
of 1: body -> Call(Ident "of", 1, body).
I should handle of explicitly or ignore it to allow standard Nim style of.
If I allow of, of 1 means pattern is 1.
Let's write the code.
Here is a Nim macro that implements a match construct with variable binding and destructuring, similar to Rust's match.