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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//! Field assertion and operation types.
//!
//! These types support field access patterns in struct and tuple matching.
use std::fmt;
use syn::{Token, parse::Parse};
use crate::pattern::Pattern;
/// Represents a field name which can be either an identifier (for structs)
/// or an index (for tuples)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum FieldName {
/// Named field: user.name, response.status
Ident(syn::Ident),
/// Indexed field: tuple.0, tuple.1
Index(usize),
}
impl fmt::Display for FieldName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FieldName::Ident(ident) => write!(f, "{}", ident),
FieldName::Index(index) => write!(f, "{}", index),
}
}
}
impl quote::ToTokens for FieldName {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
match self {
FieldName::Ident(ident) => ident.to_tokens(tokens),
FieldName::Index(index) => {
// Convert index to a syn::Index for proper token generation
let idx = syn::Index::from(*index);
idx.to_tokens(tokens);
}
}
}
}
impl Parse for FieldName {
/// Parses a field name, which can be either an identifier or a numeric index.
///
/// # Examples
/// - `name` → `FieldName::Ident("name")`
/// - `0` → `FieldName::Index(0)`
/// - `42` → `FieldName::Index(42)`
///
/// # Note on consecutive indices
/// Due to proc macro tokenization, consecutive numeric indices like `.0.0`
/// are tokenized as a float literal after the first dot is consumed.
/// This is a known limitation - use tuple destructuring syntax instead.
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
// Try to parse as a numeric literal first using fork
let fork = input.fork();
if let Ok(lit) = fork.parse::<syn::LitInt>() {
// Successfully parsed as number, consume from real input
let _: syn::LitInt = input.parse()?;
let index = lit.base10_parse()?;
Ok(FieldName::Index(index))
} else {
// Try parsing as identifier
input
.parse::<syn::Ident>()
.map(FieldName::Ident)
.map_err(|_| {
syn::Error::new(
input.span(),
"expected field name (identifier or numeric index)",
)
})
}
}
}
/// Field assertion - field operations paired with an expected pattern
/// The operations represent the full path to the field (e.g., `.name`, `.0.field`, `*field.method()`)
#[derive(Debug, Clone)]
pub(crate) struct FieldAssertion {
pub operations: FieldOperation,
pub pattern: Pattern,
}
/// Represents an operation to be performed on a field before pattern matching
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) enum FieldOperation {
/// Dereference operation: *field, **field, etc.
/// The count indicates how many dereferences to perform
Deref {
count: usize,
span: proc_macro2::Span,
},
/// Method call: field.method(), field.len(), etc.
/// Stores the method name and arguments (if any)
Method {
name: syn::Ident,
args: Vec<syn::Expr>,
span: proc_macro2::Span,
},
/// Await operation: field.await
/// For async futures that need to be awaited
Await { span: proc_macro2::Span },
/// Named field access: field.name, field.inner, etc.
/// A single step in a field chain accessing a named field
NamedField {
name: syn::Ident,
span: proc_macro2::Span,
},
/// Unnamed field access: field.0, field.1, etc.
/// A single step in a field chain accessing a tuple element
UnnamedField {
index: usize,
span: proc_macro2::Span,
},
/// Index operation: field\[0\], field\[index\], etc.
/// Stores the index expression to use
Index {
index: syn::Expr,
span: proc_macro2::Span,
},
/// Chained operations: multiple operations in sequence
/// Example: field.nested\[0\], field.inner.method(), *field.len(), **field.inner
Chained {
operations: Vec<FieldOperation>,
span: proc_macro2::Span,
},
}
impl Parse for FieldAssertion {
/// Parses a single field assertion within a struct pattern.
///
/// # Example Input
/// ```text
/// name: "Alice"
/// age: >= 18
/// *boxed_value: 42
/// email: =~ r".*@example\.com"
/// ```
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let operations = input.parse()?;
let _: Token![:] = input.parse()?;
let pattern = input.parse()?;
Ok(FieldAssertion {
operations,
pattern,
})
}
}
impl Parse for FieldOperation {
/// Parse a complete field operation sequence: *field.method()\[index\].await
///
/// # Example Input
/// ```text
/// name
/// *boxed_value
/// field.method()
/// tuple.0.inner
/// ```
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let span = input.span();
let mut operations = Vec::new();
// Parse leading derefs
let mut deref_count = 0;
while input.peek(Token![*]) {
let _: Token![*] = input.parse()?;
deref_count += 1;
}
if deref_count > 0 {
operations.push(FieldOperation::Deref {
count: deref_count,
span,
});
}
// Parse field name (required)
let field_name: FieldName = input.parse()?;
let field_op = match field_name {
FieldName::Ident(ident) => FieldOperation::NamedField { name: ident, span },
FieldName::Index(index) => FieldOperation::UnnamedField { index, span },
};
operations.push(field_op);
// Parse additional operations (.field, .method(), [index], .await)
while input.peek(Token![.]) || input.peek(syn::token::Bracket) {
FieldOperation::parse_one_into(input, &mut operations)?;
}
// Convert Vec to single operation or Chained
let final_operation = match operations.len() {
0 => unreachable!("Must have at least field name"),
1 => operations.into_iter().next().unwrap(),
_ => FieldOperation::Chained { operations, span },
};
Ok(final_operation)
}
}
impl FieldOperation {
/// Get the root field name from this operation
/// For NamedField/UnnamedField, returns that name
/// For Chained, recursively finds the first field access (skipping Deref operations)
pub(crate) fn root_field_name(&self) -> FieldName {
match self {
FieldOperation::NamedField { name, .. } => FieldName::Ident(name.clone()),
FieldOperation::UnnamedField { index, .. } => FieldName::Index(*index),
FieldOperation::Chained { operations, .. } => {
// Find the first non-Deref operation and get its root field name
operations
.iter()
.find(|op| !matches!(op, FieldOperation::Deref { .. }))
.expect("Chained operation must have at least one non-Deref operation")
.root_field_name()
}
_ => panic!("Cannot extract root field name from {:?}", self),
}
}
/// Get operations after the root field access (tail operations)
/// For NamedField/UnnamedField alone, returns None (no additional operations)
/// For Chained, returns all operations except the first non-Deref field access
///
/// Examples:
/// - Chained([Deref, NamedField("x")]) → Some(Deref)
/// - Chained([NamedField("x"), Method("len")]) → Some(Method("len"))
/// - Chained([Deref, NamedField("x"), Method("len")]) → Some(Chained([Deref, Method("len")]))
pub(crate) fn tail_operations(&self) -> Option<Self> {
match self {
FieldOperation::NamedField { .. } | FieldOperation::UnnamedField { .. } => {
// Just a field access, no additional operations
None
}
FieldOperation::Chained { operations, span } => {
// Find the index of the first non-Deref field access
let field_access_idx = operations
.iter()
.position(|op| {
matches!(
op,
FieldOperation::NamedField { .. } | FieldOperation::UnnamedField { .. }
)
})
.expect("Chained operation must have at least one field access");
// Collect all operations except the field access itself
let mut tail_ops: Vec<_> = operations[..field_access_idx].to_vec();
tail_ops.extend_from_slice(&operations[field_access_idx + 1..]);
if tail_ops.is_empty() {
None
} else if tail_ops.len() == 1 {
Some(tail_ops.into_iter().next().unwrap())
} else {
Some(FieldOperation::Chained {
operations: tail_ops,
span: *span,
})
}
}
// For other operation types (Method, Await, Index, Deref), they don't have a root field to strip
// These should not appear at the root level of a FieldAssertion, but if they do,
// return None to indicate no tail
_ => None,
}
}
}
impl FieldOperation {
/// Parse a dot operation: .await, .field, .method(), or .0
/// Pushes the parsed operation(s) into the provided Vec
fn parse_one_dot_into(
input: syn::parse::ParseStream,
ops: &mut Vec<FieldOperation>,
) -> syn::Result<()> {
let dot_span = input.span();
let _: Token![.] = input.parse()?;
if input.peek(Token![await]) {
let await_span = input.span();
let _: Token![await] = input.parse()?;
ops.push(FieldOperation::Await { span: await_span });
Ok(())
} else if input.peek(syn::LitInt) {
// It's a tuple index like .0 or .1
let lit_int: syn::LitInt = input.parse()?;
let index: usize = lit_int.base10_parse()?;
ops.push(FieldOperation::UnnamedField {
index,
span: dot_span,
});
Ok(())
} else if input.peek(syn::LitFloat) {
let lit_float: syn::LitFloat = input.parse()?;
// Parse float like "0.0" and split into two UnnamedField operations
let float_str = lit_float.to_string();
let Some((first, second)) = float_str.split_once('.') else {
return Err(syn::Error::new(
dot_span,
"Invalid float literal in field access",
));
};
let first_idx = first
.parse::<usize>()
.map_err(|_| syn::Error::new(dot_span, "Invalid numeric index in field access"))?;
let second_idx = second
.parse::<usize>()
.map_err(|_| syn::Error::new(dot_span, "Invalid numeric index in field access"))?;
// Push two sequential UnnamedField operations
ops.push(FieldOperation::UnnamedField {
index: first_idx,
span: dot_span,
});
ops.push(FieldOperation::UnnamedField {
index: second_idx,
span: dot_span,
});
Ok(())
} else {
// Parse as identifier for named field
let ident: syn::Ident = input.parse()?;
// Check if this is a method call
if input.peek(syn::token::Paren) {
let args_content;
syn::parenthesized!(args_content in input);
let mut args = Vec::new();
while !args_content.is_empty() {
let arg: syn::Expr = args_content.parse()?;
args.push(arg);
if !args_content.peek(Token![,]) {
break;
}
let _: Token![,] = args_content.parse()?;
}
ops.push(FieldOperation::Method {
name: ident,
args,
span: dot_span,
});
Ok(())
} else {
// Single named field access
ops.push(FieldOperation::NamedField {
name: ident,
span: dot_span,
});
Ok(())
}
}
}
/// Parse a single operation: .await, .field, .method(), or \[index\]
/// Pushes the parsed operation into the provided Vec
pub(crate) fn parse_one_into(
input: syn::parse::ParseStream,
ops: &mut Vec<FieldOperation>,
) -> syn::Result<()> {
if input.peek(Token![.]) {
Self::parse_one_dot_into(input, ops)
} else if input.peek(syn::token::Bracket) {
// Index operation - need to capture the span that encompasses the bracket
let content;
let bracket_token = syn::bracketed!(content in input);
let index: syn::Expr = content.parse()?;
ops.push(FieldOperation::Index {
index,
span: bracket_token.span.open(),
});
Ok(())
} else {
Err(syn::Error::new(
input.span(),
"Expected field operation (.field, .method(), .await, or [index])",
))
}
}
}