1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//! Pattern types for structural assertions.
//!
//! This module defines the various pattern types that can be used in assertions,
//! along with helper types for field operations and tuple elements.
mod closure;
mod comparison;
mod enum_pattern;
mod field;
mod map;
mod range;
mod set;
mod simple;
mod slice;
mod string;
mod struct_pattern;
mod tuple;
mod wildcard;
#[cfg(feature = "regex")]
mod regex;
// Re-export all pattern types
pub(crate) use closure::PatternClosure;
pub(crate) use comparison::{ComparisonOp, PatternComparison};
pub(crate) use enum_pattern::PatternEnum;
pub(crate) use field::{FieldAssertion, FieldOperation};
pub(crate) use map::PatternMap;
pub(crate) use range::PatternRange;
pub(crate) use set::PatternSet;
pub(crate) use simple::PatternSimple;
pub(crate) use slice::PatternSlice;
pub(crate) use string::PatternString;
pub(crate) use struct_pattern::PatternStruct;
pub(crate) use tuple::{PatternTuple, TupleElement};
pub(crate) use wildcard::PatternWildcard;
#[cfg(feature = "regex")]
pub(crate) use regex::{PatternLike, PatternRegex};
use proc_macro2::Span;
use syn::{
Token,
parse::{Parse, ParseStream},
spanned::Spanned,
};
/// Unified pattern type that can represent any pattern
#[derive(Debug, Clone)]
pub(crate) enum Pattern {
Simple(PatternSimple),
String(PatternString),
Struct(PatternStruct),
Enum(PatternEnum),
Tuple(PatternTuple),
Slice(PatternSlice),
Set(PatternSet),
Comparison(PatternComparison),
Range(PatternRange),
#[cfg(feature = "regex")]
Regex(PatternRegex),
#[cfg(feature = "regex")]
Like(PatternLike),
Wildcard(PatternWildcard),
Closure(PatternClosure),
Map(PatternMap),
}
impl Pattern {
pub(crate) fn span(&self) -> Option<Span> {
match self {
Pattern::Simple(PatternSimple { expr, .. }) => Some(expr.span()),
Pattern::String(PatternString { lit, .. }) => Some(lit.span()),
Pattern::Comparison(PatternComparison { op, expr, .. }) => {
let op_span = op.span();
Some(op_span.join(expr.span()).unwrap_or(op_span))
}
Pattern::Range(PatternRange { expr, .. }) => Some(expr.span()),
#[cfg(feature = "regex")]
Pattern::Regex(PatternRegex { span, .. }) => Some(*span),
#[cfg(feature = "regex")]
Pattern::Like(PatternLike { expr, .. }) => Some(expr.span()),
Pattern::Struct(PatternStruct { path, .. }) => path.as_ref().map(|p| p.span()),
Pattern::Enum(PatternEnum { path, .. }) => Some(path.span()),
Pattern::Tuple(PatternTuple { .. })
| Pattern::Slice(PatternSlice { .. })
| Pattern::Set(PatternSet { .. })
| Pattern::Wildcard(PatternWildcard { .. })
| Pattern::Map(PatternMap { .. }) => None,
Pattern::Closure(PatternClosure { closure, .. }) => Some(closure.span()),
}
}
/// Compute the source location for the pattern's anchor token(s).
///
/// Returns `(line_start, col_start, line_end, col_end)` where lines are 1-indexed
/// and columns are 0-indexed (proc_macro2 convention). Returns `(0, 0, 0, 0)` for
/// patterns without a meaningful source location.
///
/// Computes start and end from constituent tokens independently to avoid
/// `Span::join()`, which is nightly-only in proc_macro context. For example,
/// a `Comparison` like `> 30` uses the operator for the start and the expression
/// for the end. Enum and struct paths highlight only the type path, not the
/// arguments or fields that follow.
pub(crate) fn location(&self) -> (u32, u32, u32, u32) {
match self {
Pattern::Simple(PatternSimple { expr, .. }) => {
let start = expr.span().start();
let end = expr.span().end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
Pattern::String(PatternString { lit, .. }) => {
let start = lit.span().start();
let end = lit.span().end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
Pattern::Comparison(PatternComparison { op, expr, .. }) => {
let start = op.span().start();
let end = expr.span().end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
Pattern::Range(PatternRange { expr, .. }) => {
if let syn::Expr::Range(range_expr) = expr {
let start = range_expr
.start
.as_ref()
.map(|s| s.span().start())
.unwrap_or_else(|| range_expr.limits.span().start());
let end = range_expr
.end
.as_ref()
.map(|e| e.span().end())
.unwrap_or_else(|| range_expr.limits.span().end());
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
} else {
let start = expr.span().start();
let end = expr.span().end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
}
#[cfg(feature = "regex")]
Pattern::Regex(PatternRegex { span, .. }) => {
let start = span.start();
let end = span.end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
#[cfg(feature = "regex")]
Pattern::Like(PatternLike { expr, .. }) => {
let start = expr.span().start();
let end = expr.span().end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
// Highlight only the path itself, not the args or fields that follow.
// Use first/last segment idents independently to avoid Span::join().
Pattern::Struct(PatternStruct {
path: Some(path), ..
})
| Pattern::Enum(PatternEnum { path, .. }) => {
let first = path.segments.first().map(|s| s.ident.span().start());
let last = path.segments.last().map(|s| s.ident.span().end());
match (first, last) {
(Some(start), Some(end)) => (
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
),
_ => (0, 0, 0, 0),
}
}
Pattern::Closure(PatternClosure { closure, .. }) => {
let start = closure.span().start();
let end = closure.span().end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
Pattern::Tuple(PatternTuple { span, .. })
| Pattern::Slice(PatternSlice { span, .. })
| Pattern::Set(PatternSet { span, .. })
| Pattern::Map(PatternMap { span, .. }) => {
let start = span.start();
let end = span.end();
(
start.line as u32,
start.column as u32,
end.line as u32,
end.column as u32,
)
}
// Wildcard struct patterns and plain wildcards have no meaningful location.
Pattern::Struct(PatternStruct { path: None, .. }) | Pattern::Wildcard(_) => {
(0, 0, 0, 0)
}
}
}
}
impl Parse for Pattern {
/// Parse any pattern at any level - the heart of the macro's flexibility.
///
/// This handles all pattern types in a specific order to avoid ambiguity.
/// The order matters because some patterns share prefixes.
fn parse(input: ParseStream) -> syn::Result<Self> {
// Closure pattern: |x| expr or move |x| expr for custom validation (escape hatch)
// Examples: `|x| x > 5`, `move |x| complex_logic(x)`, `|x| { x.len() > 0 }`
if input.peek(Token![|]) || (input.peek(Token![move]) && input.peek2(Token![|])) {
return Ok(Pattern::Closure(input.parse()?));
}
// Wildcard pattern: _ for ignoring a value while asserting it exists
// Example: `Some(_)`, `field: _`, `[1, _, 3]`
// Special case: `_ { ... }` for wildcard struct patterns
if input.peek(Token![_]) {
// Check if this is a wildcard struct pattern: `_ { ... }`
if input.peek2(syn::token::Brace) {
return Ok(Pattern::Struct(input.parse()?));
} else {
// Regular wildcard pattern
return Ok(Pattern::Wildcard(input.parse()?));
}
}
// Try to parse as a comparison pattern (<, <=, >, >=, ==, !=)
if input.peek(Token![<]) || input.peek(Token![>]) || input.peek(Token![!]) {
// These always start comparisons, safe to parse directly
return Ok(Pattern::Comparison(input.parse()?));
}
// `=` could start `==` (equality) or `=~` (regex pattern)
if input.peek(Token![=]) {
if input.peek2(Token![=]) {
// This is `==` - explicit equality comparison
return Ok(Pattern::Comparison(input.parse()?));
}
#[cfg(feature = "regex")]
if input.peek2(Token![~]) {
// This is `=~` - regex/like pattern
let pattern: PatternLike = input.parse()?;
return Ok(pattern.into_pattern());
}
return Err(input.error("expected `==` or `=~` pattern"));
}
// Set pattern for unordered collection matching
// Example: `#(1, 2, 3)` or `#(> 0, < 10, ..)`
if input.peek(Token![#]) && input.peek2(syn::token::Paren) {
return Ok(Pattern::Set(input.parse()?));
}
// Map patterns for map-like structures using duck typing
// Example: `#{ "key": "value" }` or `#{ "key": > 5, .. }`
if input.peek(Token![#]) && input.peek2(syn::token::Brace) {
return Ok(Pattern::Map(input.parse()?));
}
// Slice patterns for Vec/array matching
// Example: `[1, 2, 3]` or `[> 0, < 10, == 5]`
if input.peek(syn::token::Bracket) {
return Ok(Pattern::Slice(input.parse()?));
}
// Standalone tuple pattern (no type prefix)
// Example: `(10, 20)` or `(> 10, < 30)`
if input.peek(syn::token::Paren) {
return Ok(Pattern::Tuple(input.parse()?));
}
// Bare anonymous struct pattern: { foo: "bar", .. }
// Shorthand for _ { foo: "bar", .. }
if input.peek(syn::token::Brace) {
return Ok(Pattern::Struct(input.parse()?));
}
// Complex path-based patterns: structs, enums, tuple variants
// This is where disambiguation becomes critical
let fork = input.fork();
if fork.parse::<syn::Path>().is_ok() {
// Path followed by braces is a struct pattern
// Example: `User { name: "Alice", age: 30 }`
if fork.peek(syn::token::Brace) {
return Ok(Pattern::Struct(input.parse()?));
}
// Path followed by parens OR standalone path is an enum variant
// Example: `Some(> 30)`, `Event::Click(>= 0, < 100)`, `Status::Active`
return Ok(Pattern::Enum(input.parse()?));
}
// Everything else is either a range, string literal, or simple expression
// Try range first, then string literal, then fallback to simple
let fork = input.fork();
if fork.parse::<PatternRange>().is_ok() {
// Range expressions like `18..65` or `0.0..100.0`
Ok(Pattern::Range(input.parse()?))
} else if input.peek(syn::LitStr) {
// String literal: "hello", "world"
Ok(Pattern::String(PatternString::new(input.parse()?)))
} else {
// Simple value or expression
// Examples: `42`, `true`, `my_variable`, `compute_value()`
Ok(Pattern::Simple(input.parse()?))
}
}
}