lazy-regex-proc_macros 3.3.0

proc macros for the lazy_regex crate
Documentation
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
mod args;
mod regex_code;

use {
    crate::{args::*, regex_code::*},
    proc_macro::TokenStream,
    quote::quote,
    syn::{parse_macro_input, Expr},
};

//  The following `process*` functions are convenience funcs
//  to reduce boilerplate in macro implementations below.
fn process<T, F>(input: TokenStream, as_bytes: bool, f: F) -> TokenStream
where
    T: Into<TokenStream>,
    F: Fn(RegexCode) -> T,
{
    match RegexCode::from_token_stream(input, as_bytes) {
        Ok(r) => f(r).into(),
        Err(e) => e.to_compile_error().into(),
    }
}

fn process_with_value<T, F>(input: TokenStream, as_bytes: bool, f: F) -> TokenStream
where
    T: Into<TokenStream>,
    F: Fn(RegexCode, Expr) -> T,
{
    let parsed = parse_macro_input!(input as RexValArgs);
    match RegexCode::from_lit_str(parsed.regex_str, as_bytes) {
        Ok(r) => f(r, parsed.value).into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// Return a lazy static Regex checked at compilation time and
/// built at first use.
///
/// Flags can be specified as suffix:
/// ```
/// let case_insensitive_regex = regex!("^ab+$"i);
/// ```
///
/// The macro returns a reference to a [regex::Regex]
/// or a [regex::bytes::Regex] instance,
/// differentiated by the `B` flag:
/// ```
/// let verbose = regex!(r#"_([\d\.]+)"#)
///     .replace("This is lazy-regex_2.2", " (version $1)");
/// assert_eq!(verbose, "This is lazy-regex (version 2.2)");
/// ```
#[proc_macro]
pub fn regex(input: TokenStream) -> TokenStream {
    process(input, false, |regex_code| regex_code.lazy_static())
}

/// Return a lazy static `regex::bytes::Regex` checked at compilation time and
/// built at first use.
///
/// Flags can be specified as suffix:
/// ```
/// let case_insensitive_regex = bytes_regex!("^ab+$"i);
/// assert!(case_insensitive_regex.is_match(b"abB"));
/// ```
#[proc_macro]
pub fn bytes_regex(input: TokenStream) -> TokenStream {
    process(input, true, |regex_code| regex_code.lazy_static())
}

/// Return an instance of `once_cell::sync::Lazy<regex::Regex>` or
/// `once_cell::sync::Lazy<regex::bytes::Regex>` that
/// you can use in a public static declaration.
///
/// Example:
///
/// ```
/// pub static GLOBAL_REX: Lazy<Regex> = lazy_regex!("^ab+$"i);
/// ```
///
/// As for other macros, the regex is checked at compilation time.
#[proc_macro]
pub fn lazy_regex(input: TokenStream) -> TokenStream {
    process(input, false, |regex_code| regex_code.build)
}

/// Return an instance of `once_cell::sync::Lazy<bytes::Regex>` that
/// you can use in a public static declaration.
///
/// Example:
///
/// ```
/// pub static GLOBAL_REX: Lazy<bytes::Regex> = bytes_lazy_regex!("^ab+$"i);
/// ```
///
/// As for other macros, the regex is checked at compilation time.
#[proc_macro]
pub fn bytes_lazy_regex(input: TokenStream) -> TokenStream {
    process(input, true, |regex_code| regex_code.build)
}

/// Test whether an expression matches a lazy static
/// regular expression (the regex is checked at compile
/// time)
///
/// Example:
/// ```
/// let b = regex_is_match!("[ab]+", "car");
/// assert_eq!(b, true);
/// ```
#[proc_macro]
pub fn regex_is_match(input: TokenStream) -> TokenStream {
    process_with_value(input, false, |regex_code, value| {
        let statick = regex_code.statick();
        quote! {{
            #statick;
            RE.is_match(#value)
        }}
    })
}

/// Test whether an expression matches a lazy static
/// bytes::Regex regular expression (the regex is checked
/// at compile time)
///
/// Example:
/// ```
/// let b = bytes_regex_is_match!("[ab]+", b"car");
/// assert_eq!(b, true);
/// ```
#[proc_macro]
pub fn bytes_regex_is_match(input: TokenStream) -> TokenStream {
    process_with_value(input, true, |regex_code, value| {
        let statick = regex_code.statick();
        quote! {{
            #statick;
            RE.is_match(#value)
        }}
    })
}

/// Extract the leftmost match of the regex in the
/// second argument, as a `&str`, or a `&[u8]` if the `B` flag is set.
///
/// Example:
/// ```
/// let f_word = regex_find!(r#"\bf\w+\b"#, "The fox jumps.");
/// assert_eq!(f_word, Some("fox"));
/// let f_word = regex_find!(r#"\bf\w+\b"#B, "The forest is silent.");
/// assert_eq!(f_word, Some(b"forest" as &[u8]));
/// ```
#[proc_macro]
pub fn regex_find(input: TokenStream) -> TokenStream {
    process_with_value(input, false, |regex_code, value| {
        let statick = regex_code.statick();
        let as_method = match regex_code.regex {
            RegexInstance::Regex(..) => quote!(as_str),
            RegexInstance::Bytes(..) => quote!(as_bytes),
        };
        quote! {{
            #statick;
            RE.find(#value).map(|mat| mat. #as_method ())
        }}
    })
}

/// Extract the leftmost match of the regex in the
/// second argument as a `&[u8]`
///
/// Example:
/// ```
/// let f_word = bytes_regex_find!(r#"\bf\w+\b"#, b"The fox jumps.");
/// assert_eq!(f_word, Some("fox".as_bytes()));
/// ```
#[proc_macro]
pub fn bytes_regex_find(input: TokenStream) -> TokenStream {
    process_with_value(input, true, |regex_code, value| {
        let statick = regex_code.statick();
        let as_method = match regex_code.regex {
            RegexInstance::Regex(..) => quote!(as_str),
            RegexInstance::Bytes(..) => quote!(as_bytes),
        };
        quote! {{
            #statick;
            RE.find(#value).map(|mat| mat. #as_method ())
        }}
    })
}

/// Extract captured groups as a tuple of &str.
///
/// If there's no match, the macro returns `None`.
///
/// If an optional group has no value, the tuple
/// will contain `""` instead.
///
/// Example:
/// ```
/// let (whole, name, version) = regex_captures!(
///     r#"(\w+)-([0-9.]+)"#, // a literal regex
///     "This is lazy_regex-2.0!", // any expression
/// ).unwrap();
/// assert_eq!(whole, "lazy_regex-2.0");
/// assert_eq!(name, "lazy_regex");
/// assert_eq!(version, "2.0");
/// ```
#[proc_macro]
pub fn regex_captures(input: TokenStream) -> TokenStream {
    process_with_value(input, false, |regex_code, value| {
        let statick = regex_code.statick();
        let n = regex_code.captures_len();
        let groups = (0..n).map(|i| {
            quote! {
                caps.get(#i).map_or("", |c| c.as_str())
            }
        });
        quote! {{
            #statick;
            RE.captures(#value)
                .map(|caps| (
                    #(#groups),*
                ))
        }}
    })
}

/// Extract captured groups as a tuple of &[u8]
///
/// If there's no match, the macro returns `None`.
///
/// If an optional group has no value, the tuple
/// will contain `b""` instead.
///
/// Example:
/// ```
/// let (whole, name, version) = bytes_regex_captures!(
///     r#"(\w+)-([0-9.]+)"#, // a literal regex
///     b"This is lazy_regex-2.0!", // any expression
/// ).unwrap();
/// assert_eq!(whole, b"lazy_regex-2.0");
/// assert_eq!(name, b"lazy_regex");
/// assert_eq!(version, "2.0".as_bytes());
/// ```
#[proc_macro]
pub fn bytes_regex_captures(input: TokenStream) -> TokenStream {
    process_with_value(input, true, |regex_code, value| {
        let statick = regex_code.statick();
        let n = regex_code.captures_len();
        let groups = (0..n).map(|i| {
            quote! {
                caps.get(#i).map_or(&b""[..], |c| c.as_bytes())
            }
        });
        quote! {{
            #statick;
            RE.captures(#value)
                .map(|caps| (
                    #(#groups),*
                ))
        }}
    })
}

/// common implementation of regex_replace and regex_replace_all
fn replacen(input: TokenStream, limit: usize) -> TokenStream {
    let parsed = parse_macro_input!(input as ReplaceArgs);
    let ReplaceArgs { regex_str, value, replacer } = parsed;
    let regex_code = match RegexCode::from_lit_str(regex_str, false) {
        Ok(r) => r,
        Err(e) => {
            return e.to_compile_error().into();
        }
    };
    let statick = regex_code.statick();
    let stream = match replacer {
        MaybeFun::Fun(fun) => {
            let n = regex_code.captures_len();
            let groups = (0..n).map(|i| {
                quote! {
                    caps.get(#i).map_or("", |c| c.as_str())
                }
            });
            quote! {{
                #statick;
                RE.replacen(
                    #value,
                    #limit,
                    |caps: &lazy_regex::Captures<'_>| {
                        let mut fun = #fun;
                        fun(
                            #(#groups),*
                        )
                    })
            }}
        }
        MaybeFun::Expr(expr) => {
            quote! {{
                #statick;
                RE.replacen(#value, #limit, #expr)
            }}
        }
    };
    stream.into()
}

/// common implementation of bytes_regex_replace and bytes_regex_replace_all
fn bytes_replacen(input: TokenStream, limit: usize) -> TokenStream {
    let parsed = parse_macro_input!(input as ReplaceArgs);
    let ReplaceArgs { regex_str, value, replacer } = parsed;
    let regex_code = match RegexCode::from_lit_str(regex_str, true) {
        Ok(r) => r,
        Err(e) => {
            return e.to_compile_error().into();
        }
    };
    let statick = regex_code.statick();
    let stream = match replacer {
        MaybeFun::Fun(fun) => {
            let n = regex_code.captures_len();
            let groups = (0..n).map(|i| {
                quote! {
                    caps.get(#i).map_or(&b""[..], |c| c.as_bytes())
                }
            });
            quote! {{
                #statick;
                RE.replacen(
                    #value,
                    #limit,
                    |caps: &lazy_regex::regex::bytes::Captures<'_>| {
                        let mut fun = #fun;
                        fun(
                            #(#groups),*
                        )
                    })
            }}
        }
        MaybeFun::Expr(expr) => {
            quote! {{
                #statick;
                RE.replacen(#value, #limit, #expr)
            }}
        }
    };
    stream.into()
}

/// Replaces the leftmost match in the second argument
/// using the replacer given as third argument.
///
/// When the replacer is a closure, it is given one or more `&str`,
/// the first one for the whole match and the following ones for
/// the groups.
/// Any optional group with no value is replaced with `""`.
///
/// Example:
/// ```
/// let text = "Fuu fuuu";
/// let text = regex_replace!(
///     "f(u*)"i,
///     text,
///     |_, suffix: &str| format!("F{}", suffix.len()),
/// );
/// assert_eq!(text, "F2 fuuu");
/// ```
#[proc_macro]
pub fn regex_replace(input: TokenStream) -> TokenStream {
    replacen(input, 1)
}

/// Replaces the leftmost match in the second argument
/// using the replacer given as third argument.
///
/// When the replacer is a closure, it is given one or more `&str`,
/// the first one for the whole match and the following ones for
/// the groups.
/// Any optional group with no value is replaced with `b""`.
///
/// Example:
/// ```
/// println!("{:?}", "ck ck".as_bytes());
/// let text = b"Fuu fuuu";
/// let text = bytes_regex_replace!(
///     "f(u*)"i,
///     text,
///     b"ck",
/// );
/// assert_eq!(text, "ck fuuu".as_bytes());
/// ```
#[proc_macro]
pub fn bytes_regex_replace(input: TokenStream) -> TokenStream {
    bytes_replacen(input, 1)
}

/// Replaces all non-overlapping matches in the second argument
/// using the replacer given as third argument.
///
/// When the replacer is a closure, it is given one or more `&str`,
/// the first one for the whole match and the following ones for
/// the groups.
/// Any optional group with no value is replaced with `""`.
///
/// Example:
/// ```
/// let text = "Foo fuu";
/// let text = regex_replace_all!(
///     r#"\bf(?P<suffix>\w+)"#i,
///     text,
///     |_, suffix| format!("F<{}>", suffix),
/// );
/// assert_eq!(text, "F<oo> F<uu>");
/// ```
#[proc_macro]
pub fn regex_replace_all(input: TokenStream) -> TokenStream {
    replacen(input, 0)
}

/// Replaces all non-overlapping matches in the second argument
/// using the replacer given as third argument.
///
/// When the replacer is a closure, it is given one or more `&str`,
/// the first one for the whole match and the following ones for
/// the groups.
/// Any optional group with no value is replaced with `""`.
///
/// Example:
/// ```
/// let text = b"Foo fuu";
/// let text = bytes_regex_replace_all!(
///     r#"\bf(?P<suffix>\w+)"#i,
///     text,
///     b"H",
/// );
/// assert_eq!(text, "H H".as_bytes());
/// ```
#[proc_macro]
pub fn bytes_regex_replace_all(input: TokenStream) -> TokenStream {
    bytes_replacen(input, 0)
}

/// Return an Option<T>, with T being the type returned by the block or expression
/// given as third argument.
///
/// If the regex matches, executes the expression and return it as Some.
/// Return None if the regex doesn't match.
///
/// ```
///  let grey = regex_if!(r#"^gr(a|e)y\((?<level>\d{1,2})\)$"#, "grey(22)", {
///      level.parse().unwrap()
///  });
///  assert_eq!(grey, Some(22));
/// ```
#[proc_macro]
pub fn regex_if(input: TokenStream) -> TokenStream {
    let RexIfArgs {
        regex_str,
        value,
        then,
    } = parse_macro_input!(input as RexIfArgs);
    let regex_code = match RegexCode::from_lit_str(regex_str, false) {
        Ok(r) => r,
        Err(e) => {
            return e.to_compile_error().into();
        }
    };
    let statick = regex_code.statick();
    let assigns = regex_code.named_groups().into_iter().map(|(idx, name)| {
        let var_name = syn::Ident::new(name, proc_macro2::Span::call_site());
        quote! {
            let #var_name: &str = caps.get(#idx).map_or("", |c| c.as_str());
        }
    });
    quote! {{
        #statick;
        match RE.captures(#value) {
            Some(caps) => {
                #(#assigns);*
                Some(#then)
            }
            None => None,
        }
    }}.into()
}

#[proc_macro]
pub fn bytes_regex_if(input: TokenStream) -> TokenStream {
    let RexIfArgs {
        regex_str,
        value,
        then,
    } = parse_macro_input!(input as RexIfArgs);
    let regex_code = match RegexCode::from_lit_str(regex_str, true) {
        Ok(r) => r,
        Err(e) => {
            return e.to_compile_error().into();
        }
    };
    let statick = regex_code.statick();
    let assigns = regex_code.named_groups().into_iter().map(|(idx, name)| {
        let var_name = syn::Ident::new(name, proc_macro2::Span::call_site());
        quote! {
            let #var_name: &[u8] = caps.get(#idx).map_or(&b""[..], |c| c.as_bytes());
        }
    });
    quote! {{
        #statick;
        match RE.captures(#value) {
            Some(caps) => {
                #(#assigns);*
                Some(#then)
            }
            None => None,
        }
    }}.into()
}

/// Define a set of lazy static statically compiled regexes, with a block
/// or expression for each one. The first matching expression is computed
/// with the named capture groups declaring `&str` variables available for this
/// computation.
/// If no regex matches, return `None`.
///
/// Example:
/// ```
/// #[derive(Debug, PartialEq)]
/// enum Color {
///     Grey(u8),
///     Pink,
///     Rgb(u8, u8, u8),
/// }
///
/// let input = "rgb(1, 2, 3)";
/// let color = regex_switch!(input,
///     r#"^gr(a|e)y\((?<level>\d{1,2})\)$"#i => {
///         Color::Grey(level.parse()?)
///     }
///     "^pink"i => Color::Pink,
///     r#"^rgb\((?<r>\d+),\s*(?<g>\d+),\s*(?<b>\d+),?\)$"#i => Color::Rgb (
///         r.parse()?,
///         g.parse()?,
///         b.parse()?,
///     ),
/// );
/// assert_eq!(color, Some(Color::Rgb(1, 2, 3)));
///
/// ```
#[proc_macro]
pub fn regex_switch(input: TokenStream) -> TokenStream {
    let RexSwitchArgs {
        value,
        arms,
    } = parse_macro_input!(input as RexSwitchArgs);
    let mut q_arms = Vec::new();
    for RexSwitchArmArgs { regex_str, then } in arms.into_iter() {
        let regex_code = match RegexCode::from_lit_str(regex_str, false) {
            Ok(r) => r,
            Err(e) => {
                return e.to_compile_error().into();
            }
        };
        let statick = regex_code.statick();
        let assigns = regex_code.named_groups().into_iter().map(|(idx, name)| {
            let var_name = syn::Ident::new(name, proc_macro2::Span::call_site());
            quote! {
                let #var_name: &str = caps.get(#idx).map_or("", |c| c.as_str());
            }
        });
        q_arms.push(
            quote! {{
                #statick;
                if let Some(caps) = RE.captures(#value) {
                    #(#assigns);*
                    let output = Some(#then);
                    break 'switch output;
                }
            }}
        );
    }
    quote! {{
        'switch: {
            #(#q_arms)*
            None
        }
    }}.into()
}

/// Define a set of lazy static statically compiled regexes, with a block
/// or expression for each one. The first matching expression is computed
/// with the named capture groups declaring `&str` variables available for this
/// computation.
/// If no regex matches, return `None`.
///
/// Example:
/// ```
/// #[derive(Debug, PartialEq)]
/// enum Color {
///     Grey(u8),
///     Pink,
///     Rgb(u8, u8, u8),
/// }
///
/// let input = "rgb(1, 2, 3)";
/// let color = regex_switch!(input,
///     r#"^gr(a|e)y\((?<level>\d{1,2})\)$"#i => {
///         Color::Grey(level.parse()?)
///     }
///     "^pink"i => Color::Pink,
///     r#"^rgb\((?<r>\d+),\s*(?<g>\d+),\s*(?<b>\d+),?\)$"#i => Color::Rgb (
///         r.parse()?,
///         g.parse()?,
///         b.parse()?,
///     ),
/// );
/// assert_eq!(color, Some(Color::Rgb(1, 2, 3)));
///
/// ```
#[proc_macro]
pub fn bytes_regex_switch(input: TokenStream) -> TokenStream {
    let RexSwitchArgs {
        value,
        arms,
    } = parse_macro_input!(input as RexSwitchArgs);
    let mut q_arms = Vec::new();
    for RexSwitchArmArgs { regex_str, then } in arms.into_iter() {
        let regex_code = match RegexCode::from_lit_str(regex_str, true) {
            Ok(r) => r,
            Err(e) => {
                return e.to_compile_error().into();
            }
        };
        let statick = regex_code.statick();
        let assigns = regex_code.named_groups().into_iter().map(|(idx, name)| {
            let var_name = syn::Ident::new(name, proc_macro2::Span::call_site());
            quote! {
                let #var_name: &[u8] = caps.get(#idx).map_or(&b""[..], |c| c.as_bytes());
            }
        });
        q_arms.push(
            quote! {{
                #statick;
                if let Some(caps) = RE.captures(#value) {
                    #(#assigns);*
                    let output = Some(#then);
                    break 'switch output;
                }
            }}
        );
    }
    quote! {{
        'switch: {
            #(#q_arms)*
            None
        }
    }}.into()
}