marser_macros 0.1.0

Procedural macros for the marser parser-combinator library.
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! Procedural macros for [`marser`](https://docs.rs/marser).
//!
//! Prefer `use marser::capture;` (re-exported from the main crate). This crate is the proc-macro
//! implementation; [`capture`] builds a `marser::parser::capture::Capture` parser from a grammar expression.

use std::cell::{Cell, RefCell};

use proc_macro::TokenStream;
use proc_macro_crate::{FoundCrate, crate_name};
use proc_macro2::Span;
use quote::{quote, quote_spanned};
use syn::parse::{Parse, ParseStream, Result as ParseResult};
use syn::visit::{self, Visit};
use syn::visit_mut::{self, VisitMut};
use syn::{Expr, ExprClosure, Ident, Index, Pat, Path, Token, Type, parse_quote};

// ---------------------------------------------------------------------------
// Input structs
// ---------------------------------------------------------------------------

struct CaptureInput {
    grammar: Expr,
    _arrow: Token![=>],
    result_expr: Expr,
}

impl Parse for CaptureInput {
    fn parse(input: ParseStream) -> ParseResult<Self> {
        let grammar = input.parse()?;
        let _arrow = input.parse::<Token![=>]>()?;
        let result_expr = input.parse()?;
        if !input.is_empty() {
            return Err(input.error("unexpected tokens after `capture!( … => … )`"));
        }
        Ok(CaptureInput {
            grammar,
            _arrow,
            result_expr,
        })
    }
}

#[derive(Clone, PartialEq)]
enum BindKind {
    Single,
    Multiple,
    Optional,
}

/// Shared helper: peek at an optional `*` / `?` sigil, then parse the ident.
fn parse_kind_and_ident(input: ParseStream) -> ParseResult<(BindKind, Ident)> {
    if input.peek(Token![*]) {
        input.parse::<Token![*]>()?;
        Ok((BindKind::Multiple, input.parse()?))
    } else if input.peek(Token![?]) {
        input.parse::<Token![?]>()?;
        Ok((BindKind::Optional, input.parse()?))
    } else {
        Ok((BindKind::Single, input.parse()?))
    }
}

#[derive(Clone)]
struct TypedBindTarget {
    kind: BindKind,
    ident: Ident,
    ty: Option<Type>,
}

fn parse_typed_target(input: ParseStream) -> ParseResult<TypedBindTarget> {
    let (kind, ident) = parse_kind_and_ident(input)?;
    let ty = if input.peek(Token![as]) {
        input.parse::<Token![as]>()?;
        Some(input.parse::<Type>()?)
    } else {
        None
    };
    Ok(TypedBindTarget { kind, ident, ty })
}

/// `bind!(parser, [*|?]ident [as Type] [, [*|?]span_ident [as Type]])`
struct BindInfo {
    parser: Expr,
    ident: Ident,
    kind: BindKind,
    value_ty: Option<Type>,
    span_ident: Option<Ident>,
    span_kind: Option<BindKind>,
    span_ty: Option<Type>,
}

impl Parse for BindInfo {
    fn parse(input: ParseStream) -> ParseResult<Self> {
        let parser: Expr = input.parse()?;
        let _: Token![,] = input.parse()?;
        let value_target = parse_typed_target(input)?;

        let (span_ident, span_kind, span_ty) = if input.peek(Token![,]) {
            let _: Token![,] = input.parse()?;
            let span_target = parse_typed_target(input)?;
            (
                Some(span_target.ident),
                Some(span_target.kind),
                span_target.ty,
            )
        } else {
            (None, None, None)
        };

        if !input.is_empty() {
            return Err(input.error(
                "unexpected tokens in `bind!` (expected `bind!(parser, target [, span_target])`)",
            ));
        }

        Ok(BindInfo {
            parser,
            ident: value_target.ident,
            kind: value_target.kind,
            value_ty: value_target.ty,
            span_ident,
            span_kind,
            span_ty,
        })
    }
}

/// `bind_span!(parser, [*|?]span_ident [as Type])` – binds only the span, no value capture.
struct BindSpanInfo {
    parser: Expr,
    span_ident: Ident,
    kind: BindKind,
    ty: Option<Type>,
}

impl Parse for BindSpanInfo {
    fn parse(input: ParseStream) -> ParseResult<Self> {
        let parser: Expr = input.parse()?;
        let _: Token![,] = input.parse()?;
        let target = parse_typed_target(input)?;
        if !input.is_empty() {
            return Err(input.error("unexpected tokens in `bind_span!`"));
        }
        Ok(BindSpanInfo {
            parser,
            span_ident: target.ident,
            kind: target.kind,
            ty: target.ty,
        })
    }
}

/// `bind_slice!(parser, [*|?]slice_ident [as Type])` – binds only the consumed slice.
struct BindSliceInfo {
    parser: Expr,
    slice_ident: Ident,
    kind: BindKind,
    ty: Option<Type>,
}

impl Parse for BindSliceInfo {
    fn parse(input: ParseStream) -> ParseResult<Self> {
        let parser: Expr = input.parse()?;
        let _: Token![,] = input.parse()?;
        let target = parse_typed_target(input)?;
        if !input.is_empty() {
            return Err(input.error("unexpected tokens in `bind_slice!`"));
        }
        Ok(BindSliceInfo {
            parser,
            slice_ident: target.ident,
            kind: target.kind,
            ty: target.ty,
        })
    }
}

#[derive(Clone)]
struct TypedBinding {
    ident: Ident,
    ty: Option<Type>,
}

/// Registry of `bind!` / `bind_span!` / `bind_slice!` idents (layout matches [`BindCollector`] output).
#[derive(Default, Clone)]
struct BindRegistry {
    single_values: Vec<TypedBinding>,
    single_spans: Vec<TypedBinding>,
    multiple_values: Vec<TypedBinding>,
    multiple_spans: Vec<TypedBinding>,
    optional_values: Vec<TypedBinding>,
    optional_spans: Vec<TypedBinding>,
}

impl BindRegistry {
    fn types_compatible(a: &Option<Type>, b: &Option<Type>) -> bool {
        match (a, b) {
            (None, _) | (_, None) => true,
            (Some(t1), Some(t2)) => quote!(#t1).to_string() == quote!(#t2).to_string(),
        }
    }

    fn value_kind_if_present(&self, id: &Ident) -> Option<BindKind> {
        if self.single_values.iter().any(|b| b.ident == *id) {
            Some(BindKind::Single)
        } else if self.multiple_values.iter().any(|b| b.ident == *id) {
            Some(BindKind::Multiple)
        } else if self.optional_values.iter().any(|b| b.ident == *id) {
            Some(BindKind::Optional)
        } else {
            None
        }
    }

    fn span_kind_if_present(&self, id: &Ident) -> Option<BindKind> {
        if self.single_spans.iter().any(|b| b.ident == *id) {
            Some(BindKind::Single)
        } else if self.multiple_spans.iter().any(|b| b.ident == *id) {
            Some(BindKind::Multiple)
        } else if self.optional_spans.iter().any(|b| b.ident == *id) {
            Some(BindKind::Optional)
        } else {
            None
        }
    }

    fn ident_in_any_span_list(&self, id: &Ident) -> bool {
        self.span_kind_if_present(id).is_some()
    }

    fn ident_in_any_value_list(&self, id: &Ident) -> bool {
        self.value_kind_if_present(id).is_some()
    }

    fn values_mut(&mut self, kind: &BindKind) -> &mut Vec<TypedBinding> {
        match kind {
            BindKind::Single => &mut self.single_values,
            BindKind::Multiple => &mut self.multiple_values,
            BindKind::Optional => &mut self.optional_values,
        }
    }

    fn spans_mut(&mut self, kind: &BindKind) -> &mut Vec<TypedBinding> {
        match kind {
            BindKind::Single => &mut self.single_spans,
            BindKind::Multiple => &mut self.multiple_spans,
            BindKind::Optional => &mut self.optional_spans,
        }
    }

    fn merge_into(
        list: &mut Vec<TypedBinding>,
        ident: Ident,
        ty: Option<Type>,
    ) -> std::result::Result<(), syn::Error> {
        if let Some(existing) = list.iter_mut().find(|e| e.ident == ident) {
            if !Self::types_compatible(&existing.ty, &ty) {
                return Err(syn::Error::new_spanned(
                    &ident,
                    format!(
                        "conflicting explicit `as` types for repeated binding `{}` in `capture!`",
                        ident
                    ),
                ));
            }
            if existing.ty.is_none()
                && let Some(t) = ty
            {
                existing.ty = Some(t);
            }
            Ok(())
        } else {
            list.push(TypedBinding { ident, ty });
            Ok(())
        }
    }

    /// Register a value capture. Repeated uses of the same `ident` with the same sigil bucket are merged
    /// when `as` types are compatible (see module docs on `capture!`).
    fn register_value(
        &mut self,
        ident: Ident,
        ty: Option<Type>,
        kind: &BindKind,
    ) -> std::result::Result<(), syn::Error> {
        if self.ident_in_any_span_list(&ident) {
            return Err(syn::Error::new_spanned(
                &ident,
                format!(
                    "binding `{}` is already used as a span binding; value and span captures cannot share an identifier in `capture!`",
                    ident
                ),
            ));
        }
        if let Some(existing) = self.value_kind_if_present(&ident)
            && existing != *kind
        {
            return Err(syn::Error::new_spanned(
                &ident,
                format!(
                    "binding `{}` is used with incompatible sigils (for example `x` vs `*x` vs `?x`) in the same `capture!`",
                    ident
                ),
            ));
        }
        let list = self.values_mut(kind);
        Self::merge_into(list, ident, ty)
    }

    fn register_span(
        &mut self,
        ident: Ident,
        ty: Option<Type>,
        kind: &BindKind,
    ) -> std::result::Result<(), syn::Error> {
        if self.ident_in_any_value_list(&ident) {
            return Err(syn::Error::new_spanned(
                &ident,
                format!(
                    "binding `{}` is already used as a value binding; value and span captures cannot share an identifier in `capture!`",
                    ident
                ),
            ));
        }
        if let Some(existing) = self.span_kind_if_present(&ident)
            && existing != *kind
        {
            return Err(syn::Error::new_spanned(
                &ident,
                format!(
                    "span binding `{}` is used with incompatible sigils in the same `capture!`",
                    ident
                ),
            ));
        }
        let list = self.spans_mut(kind);
        Self::merge_into(list, ident, ty)
    }
}

/// Walk the raw grammar `Expr` before `bind!` expansion and collect binding targets.
struct BindCollector {
    reg: BindRegistry,
    errors: Option<syn::Error>,
}

impl BindCollector {
    fn bump_err(&mut self, e: syn::Error) {
        self.errors = Some(match self.errors.take() {
            None => e,
            Some(mut prev) => {
                prev.combine(e);
                prev
            }
        });
    }

    fn collect(expr: &Expr) -> std::result::Result<BindRegistry, syn::Error> {
        let mut c = Self {
            reg: BindRegistry::default(),
            errors: None,
        };
        c.visit_expr(expr);
        if let Some(e) = c.errors {
            Err(e)
        } else {
            Ok(c.reg)
        }
    }
}

impl<'ast> Visit<'ast> for BindCollector {
    fn visit_expr(&mut self, expr: &'ast Expr) {
        if let Expr::Macro(m) = expr {
            if m.mac.path.is_ident("bind") {
                let info = match m.mac.parse_body::<BindInfo>() {
                    Ok(i) => i,
                    Err(e) => {
                        self.bump_err(e);
                        visit::visit_expr(self, expr);
                        return;
                    }
                };
                if let Some(ref span_ident) = info.span_ident
                    && *span_ident == info.ident
                {
                    self.bump_err(syn::Error::new_spanned(
                        span_ident,
                        "`bind!` value and span targets must use distinct identifiers",
                    ));
                    self.visit_expr(&info.parser);
                    return;
                }
                if let Err(e) =
                    self.reg
                        .register_value(info.ident.clone(), info.value_ty.clone(), &info.kind)
                {
                    self.bump_err(e);
                }
                if let Some(span_ident) = &info.span_ident {
                    let span_kind = info.span_kind.as_ref().unwrap();
                    if let Err(e) =
                        self.reg
                            .register_span(span_ident.clone(), info.span_ty.clone(), span_kind)
                    {
                        self.bump_err(e);
                    }
                }
                self.visit_expr(&info.parser);
                return;
            }
            if m.mac.path.is_ident("bind_span") {
                let info = match m.mac.parse_body::<BindSpanInfo>() {
                    Ok(i) => i,
                    Err(e) => {
                        self.bump_err(e);
                        visit::visit_expr(self, expr);
                        return;
                    }
                };
                if let Err(e) =
                    self.reg
                        .register_span(info.span_ident.clone(), info.ty.clone(), &info.kind)
                {
                    self.bump_err(e);
                }
                self.visit_expr(&info.parser);
                return;
            }
            if m.mac.path.is_ident("bind_slice") {
                let info = match m.mac.parse_body::<BindSliceInfo>() {
                    Ok(i) => i,
                    Err(e) => {
                        self.bump_err(e);
                        visit::visit_expr(self, expr);
                        return;
                    }
                };
                if let Err(e) =
                    self.reg
                        .register_value(info.slice_ident.clone(), info.ty.clone(), &info.kind)
                {
                    self.bump_err(e);
                }
                self.visit_expr(&info.parser);
                return;
            }
        }
        visit::visit_expr(self, expr);
    }
}

/// Build the `(S, M, O)` tuple for [`Capture::<MRes, _, _>`] (explicit `as T` preserved; untyped values use `_`).
fn build_capture_mres_tuple(registry: &BindRegistry) -> proc_macro2::TokenStream {
    let build_bucket = |values: &[TypedBinding], spans: &[TypedBinding], is_vec: bool| {
        let wrap = |inner: proc_macro2::TokenStream| {
            if is_vec {
                quote! { ::std::vec::Vec<#inner> }
            } else {
                quote! { ::std::option::Option<#inner> }
            }
        };
        let mut pieces = Vec::new();
        for b in values.iter() {
            let inner = if let Some(ty) = &b.ty {
                quote! { #ty }
            } else {
                quote! { _ }
            };
            pieces.push(wrap(inner));
        }
        for b in spans.iter() {
            let inner = if let Some(ty) = &b.ty {
                quote! { #ty }
            } else {
                quote! { (_, _) }
            };
            pieces.push(wrap(inner));
        }
        if pieces.is_empty() {
            quote! { () }
        } else {
            quote! { ( #(#pieces,)* ) }
        }
    };

    let s_ty = build_bucket(&registry.single_values, &registry.single_spans, false);
    let m_ty = build_bucket(&registry.multiple_values, &registry.multiple_spans, true);
    let o_ty = build_bucket(&registry.optional_values, &registry.optional_spans, false);
    quote! { (#s_ty, #m_ty, #o_ty) }
}

// ---------------------------------------------------------------------------
// `use_binds!` expansion
// ---------------------------------------------------------------------------
//
// User-facing syntax is `use_binds!(|ctx| { … })` for `err_if_*` factories. Hand-written
// grammars can use `marser::error::SnapshotFactory(|snap, ctx| { … })` instead; that path goes
// through `SnapCallable` in the main crate.
//
// We do **not** expand each `use_binds!` to an inline `SnapshotFactory` closure because:
//
// 1. **Type inference** — `Capture::<MRes, …>` needs a concrete `MRes` triple. An untyped closure
//    in the grammar blocks inference (`E0282`). Putting `__BindTn` on `Capture::new` itself would
//    leak those names into the user's function scope (`E0412`).
//
// 2. **`'src` / `erase_types`** — Wrapping a site in `SnapshotFactory(…)` makes `err_if_*` see
//    `SnapshotFactory<F>` with `F: for<'a> SnapCallable<'a, MRes>`. That bound can still force the
//    `MRes: 'static` well-formedness trap (see `inline_error.rs`), breaking parsers with
//    `bind_slice!` and `.erase_types()` on borrowed input.
//
// The approach below matches what worked before: one ZST per capture, `BuildInlineError` with an
// explicit `build_inline_error<'snap>(…, snapshot) where MRes: 'snap`, and `__BindTn` only on the
// **impl** (not on `Capture`). Sites are `__UseBindsSite::<N>`; multiple sites share one struct and
// a `match SITE` body. Same snapshot locals as a closure expansion would use (`snapshot_bind_lets`).

/// `(S, M, O)` for [`BuildInlineError`] on `__UseBindsSite`, plus `__BindTn` impl type parameters.
///
/// Separate from [`build_capture_mres_tuple`]: `Capture` keeps `_` for inference; the factory impl
/// declares `__BindT0`, … so rustc can unify capture slots with `bind!` output types.
fn build_factory_mres_tuple(registry: &BindRegistry) -> (proc_macro2::TokenStream, Vec<Ident>) {
    let mut gen_names: Vec<Ident> = Vec::new();
    let mut next_ty = |span: Span| -> proc_macro2::TokenStream {
        let n = gen_names.len();
        let id = Ident::new(&format!("__BindT{n}"), span);
        gen_names.push(id.clone());
        quote! { #id }
    };

    let mut build_bucket = |values: &[TypedBinding], spans: &[TypedBinding], is_vec: bool| {
        let wrap = |inner: proc_macro2::TokenStream| {
            if is_vec {
                quote! { ::std::vec::Vec<#inner> }
            } else {
                quote! { ::std::option::Option<#inner> }
            }
        };
        let mut pieces = Vec::new();
        for b in values.iter() {
            pieces.push(wrap(next_ty(b.ident.span())));
        }
        for b in spans.iter() {
            let inner = if let Some(ty) = &b.ty {
                quote! { #ty }
            } else {
                quote! { (usize, usize) }
            };
            pieces.push(wrap(inner));
        }
        if pieces.is_empty() {
            quote! { () }
        } else {
            quote! { ( #(#pieces,)* ) }
        }
    };

    let s_ty = build_bucket(&registry.single_values, &registry.single_spans, false);
    let m_ty = build_bucket(&registry.multiple_values, &registry.multiple_spans, true);
    let o_ty = build_bucket(&registry.optional_values, &registry.optional_spans, false);
    (quote! { (#s_ty, #m_ty, #o_ty) }, gen_names)
}

fn snapshot_bind_lets(
    registry: &BindRegistry,
) -> (
    Vec<proc_macro2::TokenStream>,
    Vec<proc_macro2::TokenStream>,
    Vec<proc_macro2::TokenStream>,
) {
    let mut single_lets = Vec::new();
    for (i, b) in registry
        .single_values
        .iter()
        .chain(&registry.single_spans)
        .enumerate()
    {
        let idx = Index::from(i);
        let id = &b.ident;
        single_lets.push(quote! {
            #[allow(unused_variables)]
            let #id = __single.#idx;
        });
    }
    let mut multiple_lets = Vec::new();
    for (i, b) in registry
        .multiple_values
        .iter()
        .chain(&registry.multiple_spans)
        .enumerate()
    {
        let idx = Index::from(i);
        let id = &b.ident;
        multiple_lets.push(quote! {
            #[allow(unused_variables)]
            let #id = &__multiple.#idx;
        });
    }
    let mut optional_lets = Vec::new();
    for (i, b) in registry
        .optional_values
        .iter()
        .chain(&registry.optional_spans)
        .enumerate()
    {
        let idx = Index::from(i);
        let id = &b.ident;
        optional_lets.push(quote! {
            #[allow(unused_variables)]
            let #id = __optional.#idx;
        });
    }
    (single_lets, multiple_lets, optional_lets)
}

/// One `use_binds!` site collected before codegen (becomes a `match` arm in [`emit_use_binds_sites`]).
struct UseBindSite {
    site: usize,
    ctx_ident: Ident,
    inner: proc_macro2::TokenStream,
}

/// Emit `__UseBindsSite` and a single `BuildInlineError` impl for all sites in this `capture!`.
fn emit_use_binds_sites(
    sites: &[UseBindSite],
    registry: &BindRegistry,
    marser: &Path,
    mres: &proc_macro2::TokenStream,
    mres_generics: &[Ident],
) -> proc_macro2::TokenStream {
    if sites.is_empty() {
        return quote! {};
    }

    let (single_lets, multiple_lets, optional_lets) = snapshot_bind_lets(registry);

    let const_site_params = quote! { <const __SITE: usize> };
    let build_inline_params = if mres_generics.is_empty() {
        quote! { <const __SITE: usize> }
    } else {
        quote! { <const __SITE: usize, #(#mres_generics),*> }
    };

    let arms: Vec<_> = sites
        .iter()
        .map(|s| {
            let lit = syn::LitInt::new(&format!("{}", s.site), Span::call_site());
            let ctx = &s.ctx_ident;
            let inner = &s.inner;
            quote! {
                #lit => {
                    let #ctx = __ctx;
                    #inner
                }
            }
        })
        .collect();

    quote! {
        struct __UseBindsSite<const __SITE: usize>;

        impl #const_site_params ::core::clone::Clone for __UseBindsSite<__SITE> {
            fn clone(&self) -> Self {
                *self
            }
        }

        impl #const_site_params ::core::marker::Copy for __UseBindsSite<__SITE> {}

        impl #build_inline_params #marser::error::BuildInlineError<#mres> for __UseBindsSite<__SITE> {
            fn build_inline_error<'__snap>(
                &self,
                __ctx: #marser::error::MatchDiagCtx,
                __snap: <#mres as #marser::parser::capture::MatchResult>::Snapshot<'__snap>,
            ) -> #marser::error::InlineError
            where
                #mres: '__snap,
            {
                let __single = &__snap.0;
                let __multiple = &__snap.1;
                let __optional = &__snap.2;
                #(#single_lets)*
                #(#multiple_lets)*
                #(#optional_lets)*
                match __SITE {
                    #(#arms)*
                    _ => ::core::unreachable!("use_binds site out of range"),
                }
            }
        }
    }
}

fn parse_use_binds_closure(
    closure: ExprClosure,
) -> std::result::Result<(Ident, proc_macro2::TokenStream), syn::Error> {
    let ctx_ident = match closure.inputs.iter().next() {
        Some(Pat::Type(pt)) => {
            if let Pat::Ident(pi) = pt.pat.as_ref() {
                pi.ident.clone()
            } else {
                Ident::new("ctx", Span::call_site())
            }
        }
        Some(Pat::Ident(pi)) => pi.ident.clone(),
        _ => Ident::new("ctx", Span::call_site()),
    };

    let inner = match closure.body.as_ref() {
        Expr::Block(b) => {
            let stmts = b.block.stmts.iter();
            quote! { #(#stmts)* }
        }
        expr => quote! { #expr },
    };
    Ok((ctx_ident, inner))
}

struct UseBindsRewriter {
    sites: RefCell<Vec<UseBindSite>>,
    next_site: Cell<usize>,
    errors: RefCell<Option<syn::Error>>,
}

impl UseBindsRewriter {
    fn bump_err(&self, e: syn::Error) {
        let mut slot = self.errors.borrow_mut();
        *slot = Some(match slot.take() {
            None => e,
            Some(mut prev) => {
                prev.combine(e);
                prev
            }
        });
    }
}

impl VisitMut for UseBindsRewriter {
    fn visit_expr_mut(&mut self, expr: &mut Expr) {
        if let Expr::Macro(m) = expr
            && m.mac.path.is_ident("use_binds")
        {
            let closure = match m.mac.parse_body::<ExprClosure>() {
                Ok(c) => c,
                Err(e) => {
                    self.bump_err(e);
                    return;
                }
            };
            let (ctx_ident, inner) = match parse_use_binds_closure(closure) {
                Ok(x) => x,
                Err(e) => {
                    self.bump_err(e);
                    return;
                }
            };
            let site = self.next_site.get();
            self.next_site.set(site + 1);
            self.sites.borrow_mut().push(UseBindSite {
                site,
                ctx_ident,
                inner,
            });
            let lit = syn::LitInt::new(&format!("{}", site), Span::call_site());
            // ZST factory type, not `SnapshotFactory(closure)` — see module comment above.
            match syn::parse2::<Expr>(quote! { __UseBindsSite::<#lit> }) {
                Ok(expanded) => *expr = expanded,
                Err(e) => self.bump_err(e),
            }
            return;
        }
        visit_mut::visit_expr_mut(self, expr);
    }
}

/// Reject `use_binds!` in the `capture!` result expression (only meaningful in the grammar).
struct UseBindsInResultChecker {
    error: Option<syn::Error>,
}

impl<'ast> Visit<'ast> for UseBindsInResultChecker {
    fn visit_expr(&mut self, expr: &'ast Expr) {
        if let Expr::Macro(m) = expr
            && m.mac.path.is_ident("use_binds")
        {
            self.error = Some(syn::Error::new_spanned(
                m.mac.path.get_ident().unwrap(),
                "`use_binds!` is only allowed in the grammar of `capture!`, not in the `=>` result expression",
            ));
            return;
        }
        visit::visit_expr(self, expr);
    }
}

// ---------------------------------------------------------------------------
// Bind macro expansion
// ---------------------------------------------------------------------------

/// Expands `bind!` / `bind_span!` / `bind_slice!` inside `capture!` after [`BindCollector`] validation.
struct BindMacroExpander {
    marser_path: Path,
    errors: Option<syn::Error>,
}

impl BindMacroExpander {
    fn new(marser_path: Path) -> Self {
        Self {
            marser_path,
            errors: None,
        }
    }

    fn bump_err(&mut self, e: syn::Error) {
        self.errors = Some(match self.errors.take() {
            None => e,
            Some(mut prev) => {
                prev.combine(e);
                prev
            }
        });
    }

    fn take_errors(self) -> Option<syn::Error> {
        self.errors
    }
}

impl VisitMut for BindMacroExpander {
    fn visit_expr_mut(&mut self, i: &mut Expr) {
        if let Expr::Macro(m) = i {
            if m.mac.path.is_ident("bind") {
                let info = match m.mac.parse_body::<BindInfo>() {
                    Ok(info) => info,
                    Err(e) => {
                        self.bump_err(e);
                        visit_mut::visit_expr_mut(self, i);
                        return;
                    }
                };
                let id = &info.ident;
                let parser = &info.parser;
                let bind_span = id.span();
                let rewrite = if let Some(span_id) = &info.span_ident {
                    let marser = self.marser_path.clone();
                    quote_spanned! {bind_span=>
                        #marser::parser::capture::bind_span(
                            #marser::parser::capture::bind_result(#parser, #id),
                            #span_id
                        )
                    }
                } else {
                    let marser = self.marser_path.clone();
                    quote_spanned! {bind_span=>
                        #marser::parser::capture::bind_result(#parser, #id)
                    }
                };
                match syn::parse2(rewrite) {
                    Ok(expr) => *i = expr,
                    Err(e) => self.bump_err(e),
                }
                return;
            }

            if m.mac.path.is_ident("bind_span") {
                let info = match m.mac.parse_body::<BindSpanInfo>() {
                    Ok(i) => i,
                    Err(e) => {
                        self.bump_err(e);
                        visit_mut::visit_expr_mut(self, i);
                        return;
                    }
                };
                let span_id = &info.span_ident;
                let parser = &info.parser;
                let marser = self.marser_path.clone();
                *i = parse_quote! { #marser::parser::capture::bind_span(#parser, #span_id) };
                return;
            }

            if m.mac.path.is_ident("bind_slice") {
                let info = match m.mac.parse_body::<BindSliceInfo>() {
                    Ok(i) => i,
                    Err(e) => {
                        self.bump_err(e);
                        visit_mut::visit_expr_mut(self, i);
                        return;
                    }
                };
                let slice_id = &info.slice_ident;
                let parser = &info.parser;
                let marser = self.marser_path.clone();
                *i = parse_quote! { #marser::parser::capture::bind_slice(#parser, #slice_id) };
                return;
            }
        }
        visit_mut::visit_expr_mut(self, i);
    }
}

// ---------------------------------------------------------------------------
// capture! proc-macro
// ---------------------------------------------------------------------------

/// Build a parser from grammar + result expressions (via [`Capture`](https://docs.rs/marser/latest/marser/parser/capture/struct.Capture.html), returned as `impl Parser` to limit type size).
///
/// # Syntax
///
/// ```rust,ignore
/// capture!( <grammar> => <result> )
/// ```
///
/// - **`<grammar>`** — any expression after `bind!` / `bind_span!` expansion (typically a tuple
///   of matchers, often using [`crate::matcher::Matcher`](https://docs.rs/marser/latest/marser/matcher/trait.Matcher.html)
///   combinators like `many` / `one_of`).
/// - **`<result>`** — Rust expression that receives the captured bindings and produces the parser output.
///
/// Inside `<grammar>`, the macro recognizes:
///
/// - **`bind!(parser, ident)`** — single capture into `ident` (`Option<_>` in the bucket).
/// - **`bind!(parser, *ident)`** — repeated capture into `ident` (`Vec<_>`).
/// - **`bind!(parser, ?ident)`** — optional capture (`Option<_>`).
/// - **`bind!(parser, ident as T)`** / **`bind!(parser, *ident as T)`** / **`bind!(parser, ?ident as T)`** —
///   typed captures. With `*` / `?`, the sigil still wraps `T` (Option A semantics).
/// - **`bind!(parser, ident [as T], *span_ident [as U])`** (and `?` / `*` on the value) — value plus span capture.
/// - **`bind_span!(parser, ident)`** / **`bind_span!(parser, *ident)`** / **`bind_span!(parser, ?ident)`** / **`bind_span!(parser, ident as T)`** —
///   capture only a span (expands to `marser::parser::capture::bind_span`).
/// - **`bind_slice!(parser, ident)`** / **`bind_slice!(parser, *ident)`** / **`bind_slice!(parser, ?ident)`** / **`bind_slice!(parser, ident as T)`** —
///   capture only the consumed input slice (expands to `marser::parser::capture::bind_slice`).
///
/// - **`use_binds!(|ctx| { … })`** — expands to `__UseBindsSite::<N>` (not an inline
///   [`marser::error::SnapshotFactory`] closure). One shared `__UseBindsSite<const SITE>` per
///   `capture!` implements [`marser::error::BuildInlineError`] with `match SITE` dispatch. See the
///   `use_binds! expansion` comment in this crate for why (inference, `'src`, `erase_types`).
///
/// Repeated **compatible** binds to the same identifier (same sigil bucket and compatible `as`
/// types) are merged into one capture slot. Conflicting sigils, incompatible explicit types, or
/// reusing the same name for both value and span captures are **compile errors** with spans on the
/// offending `bind!` / `bind_span!` / `bind_slice!` sites.
///
/// These helper macros are only expanded meaningfully inside `capture!`; using them elsewhere
/// yields normal unresolved-macro errors unless you import the `marser` crate and use `capture!`
/// from it (or depend on `marser_macros` directly for experimentation).
///
/// Each binding becomes a parameter to both the grammar closure and the result closure; the grammar
/// side often ignores those names because wiring goes through `bind_result` / `bind_span`.
///
/// The expansion prefixes APIs with the dependency name from Cargo (via `proc_macro_crate::crate_name("marser")`).
/// If you rename the `marser` dependency in your `Cargo.toml`, generated paths use that name.
#[proc_macro]
pub fn capture(input: TokenStream) -> TokenStream {
    let mut input: CaptureInput = syn::parse_macro_input!(input as CaptureInput);
    let marser_path = marser_crate_path();
    let registry = match BindCollector::collect(&input.grammar) {
        Ok(r) => r,
        Err(e) => return e.to_compile_error().into(),
    };

    let mut expander = BindMacroExpander::new(marser_path.clone());
    expander.visit_expr_mut(&mut input.grammar);
    if let Some(e) = expander.take_errors() {
        return e.to_compile_error().into();
    }

    let pat_tuple = |values: &[TypedBinding], spans: &[TypedBinding]| {
        let all: Vec<_> = values
            .iter()
            .chain(spans.iter())
            .map(|x| &x.ident)
            .collect();
        if all.is_empty() {
            quote! { () }
        } else {
            quote! { ( #(#all,)* ) }
        }
    };

    let s_pat = pat_tuple(&registry.single_values, &registry.single_spans);
    let m_pat = pat_tuple(&registry.multiple_values, &registry.multiple_spans);
    let o_pat = pat_tuple(&registry.optional_values, &registry.optional_spans);

    let mres_capture = build_capture_mres_tuple(&registry);
    // Only used when the grammar contains `use_binds!`; see `use_binds!` section above.
    let (mres_factory, mres_generics) = build_factory_mres_tuple(&registry);

    let mut use_binds_rw = UseBindsRewriter {
        sites: RefCell::new(Vec::new()),
        next_site: Cell::new(0),
        errors: RefCell::new(None),
    };
    use_binds_rw.visit_expr_mut(&mut input.grammar);
    if let Some(e) = use_binds_rw.errors.into_inner() {
        return e.to_compile_error().into();
    }
    let sites = use_binds_rw.sites.into_inner();

    let mut result_checker = UseBindsInResultChecker { error: None };
    result_checker.visit_expr(&input.result_expr);
    if let Some(e) = result_checker.error {
        return e.to_compile_error().into();
    }

    let use_binds_block = emit_use_binds_sites(
        &sites,
        &registry,
        &marser_path,
        &mres_factory,
        &mres_generics,
    );

    let grammar = &input.grammar;
    let result_expr = &input.result_expr;

    TokenStream::from(quote! {
        {
            #use_binds_block
            #[allow(unused_variables)]
            #marser_path::parser::as_parser(
                #marser_path::parser::capture::Capture::<#mres_capture, _, _>::new(
                    |#s_pat, #m_pat, #o_pat| { #grammar     },
                    |#s_pat, #m_pat, #o_pat| { #result_expr },
                ),
            )
        }
    })
}

fn marser_crate_path() -> Path {
    match crate_name("marser") {
        Ok(FoundCrate::Itself) => parse_quote!(::marser),
        Ok(FoundCrate::Name(name)) => {
            let ident = Ident::new(&name, Span::call_site());
            parse_quote!(::#ident)
        }
        Err(_) => parse_quote!(::marser),
    }
}