ulo-macros 0.1.0-alpha.3

Macros for Ulo
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
//! One entry of a `providers` list and its lowering to the value API:
//!
//! | Entry | Lowers to |
//! |---|---|
//! | `UserService` | `m.provide::<UserService>();` |
//! | `PgUserRepo as dyn UserRepo` | `m.provide::<PgUserRepo>().also_as::<dyn UserRepo>(\|a\| a);` |
//! | `AppConfig::from_env()?` | `m.try_value(AppConfig::from_env());` |
//! | `expr` | `m.value(expr);` |
//! | `PgUserRepo @ Primary` | `m.provide::<PgUserRepo>().qualified::<Primary>();` |
//! | `PgUserRepo as dyn UserRepo @ Primary` | `m.provide::<PgUserRepo>().also_as::<dyn UserRepo>(\|a\| a).qualified::<Primary>();` |
//! | `expr @ Primary`, `expr? @ Primary` | `m.value(expr).qualified::<Primary>();`, `m.try_value(expr).qualified::<Primary>();` |
//! | `with = closure` | `m.with(closure)` or `m.try_with(..)`, picked by autoref over the closure's own type |
//! | `with(singleton) = closure` | `m.singleton(..)` or `m.try_singleton(..)`, ranked the same way |
//! | `with(execution) = closure` | `m.execution(..)` or `m.try_execution(..)` |
//! | `with(transient) = closure` | `m.transient(..)` or `m.try_transient(..)` |
//! | a bare closure | as `with = closure`: `Auto`, the same closure meaning the same thing in every position |
//! | `K: with = closure`, `K: with(<scope>) = closure` | the same call, then `.also_as::<K>(\|a\| a)` |
//! | `into K: [..]` | one `m.contribute::<K>()` statement per item, below |
//!
//! `@ Q` is the notation reports print for a key, `Db @ Primary`, written as the slot that makes
//! one. It follows the entry, after `as dyn K` when both are written, and qualifies every key the
//! entry binds. A closure binding (`with`, a bare closure, `K: with`) and an `into` item take no
//! qualifier: a refusal names the `ModuleDef` call that does.
//!
//! Every closure is written as in `#[guards]`: a synchronous body is wrapped in `async move`, and
//! a closure already `async` is kept. For a provider `Auto` behaves as a singleton; what differs
//! from `with(singleton)` is the record, which the needs-execution pass reads to name
//! `with(execution)` in its hint. The key comes first in `K: with = ..` because a closure's body
//! extends as far as it can, so a trailing `as dyn Cache` would parse as a cast inside it.
//!
//! An `into` list has one grammar for every key, a role key and `dyn Plugin` alike, the one
//! `#[guards]` uses for a type, a value and a closure:
//!
//! | Item | Lowers to |
//! |---|---|
//! | `A` | `m.contribute::<K>().provide::<A>(\|a\| a);` |
//! | `value = expr` | `m.contribute::<K>().value(Arc::new(expr));` |
//! | `value = expr?` | `m.contribute::<K>().try_value(Result::map(expr, \|v\| -> Arc<K> { Arc::new(v) }));` |
//! | `with = closure` | `m.contribute::<K>()` then `.with(closure, \|a\| a)` or `.try_with(..)`, by the same autoref ranking |
//! | `with(singleton) = closure` | `.singleton(..)` or `.try_singleton(..)`, ranked the same way |
//! | `with(execution) = closure` | `.execution(..)` or `.try_execution(..)` |
//! | `with(transient) = closure` | `.transient(..)` or `.try_transient(..)` |
//!
//! A `with` closure is written as in `#[guards]`: a synchronous body is wrapped in `async move`,
//! and a closure already `async` is kept. The scope word is a type argument of the probe, `Auto`
//! when none is written, and the probe's `ContributionScope` impl for that marker picks the
//! method. `Auto` builds the contribution once unless what the closure reads needs an execution;
//! a provider contribution under `Auto` is a singleton, and `wire()` refuses one whose closure
//! reads execution data. Inference reads the closure's parameters, not its body: a closure that
//! creates per-call state while reading nothing per call, such as `|| RequestTimer::start()`, is
//! written `with(execution)`.
//!
//! A `value` is evaluated when `register` runs, once per module. `value = expr?` records an `Err`
//! for `wire()` to report, as a providers list's `expr?` does. Its closure's return type is
//! written because `Result<Arc<T>, E>` does not coerce to `Result<Arc<K>, E>`; the annotation
//! makes the closure's tail the coercion site where `Arc<T>` widens to `Arc<K>`.
//!
//! The core gives the enhancer role to a contribution under a role key at freeze, from the key's
//! type, so `into AnyGuard<Http>: [AuthGuard]` registers a global guard and nothing here tells a
//! role key from another key.
//!
//! A type entry is a plain type path: `Foo`, `db::Pool<Pg>`. In a providers list, a path with
//! parenthesized arguments, `Config::default()`, is a call and reads as an expression, and a bare
//! path naming a constant reads as a type, so a constant is bound by value with a block,
//! `{ LIMITS }`. In an `into` list an expression is written `value = expr`.
//!
//! Before an `into K` list's statements the lowering checks `K` with
//! `ulo::__private::contribution_key`: a `K` implementing `ulo::Meta` is module metadata, and
//! the check is a compile error naming it. A proc macro sees no types, so the check is a bound
//! the compiler evaluates.
//!
//! A braced value, `{ LIMITS }`, is lowered as `m.value(LIMITS)`: the braces only tell a constant
//! from a type, and kept in the call they trip `unused_braces` in the user's crate.
//!
//! An entry `X as <role key>` is an error: `as` binds a single instance, which the transports'
//! walk over a role's contributions never reaches.
//!
//! A type that does not implement `Construct` fails at `provide::<T>()`; the generated call is
//! spanned at the entry, where the error is reported. A type entry, `T`, `T as dyn K`, `T @ Q` or
//! an `into` item `T`, is first checked not to be a controller, and so is the type of a
//! value entry, `expr`, `expr?` or an `into` item `value = ..`: a controller is listed under
//! `controllers`, and only another controller injects it. A closure binding is not checked; what
//! it builds is known only from its future's output.

use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{Expr, ExprClosure, Ident, PathArguments, Token, Type, TypeParamBound, bracketed, token};

use ulo_handler_codegen::util::wrap_async;
use crate::module_attr::module_def_param;
use crate::shared::scope::ScopeArg;
use crate::shared::{check_factory_params, ulo};

/// The `Q` of an `@ Q` suffix. Boxed so the enums holding one stay near the size of a bare type.
pub(crate) type Qualifier = Option<Box<Type>>;

pub(crate) enum ProviderEntry {
    /// `Type`, with the `@ Q` qualifier when written. Every entry that binds a single instance
    /// from a type or a value carries one; a closure and a contribution do not.
    Provide { ty: Type, qualifier: Qualifier },
    ProvideAs { ty: Type, as_ty: Type, qualifier: Qualifier },
    TryValue { expr: Expr, qualifier: Qualifier },
    Value { expr: Expr, qualifier: Qualifier },
    /// `with = ..`, `with(<scope>) = ..` and a bare closure, `key` `None`; `K: with = ..` and
    /// `K: with(<scope>) = ..`, `key` `Some(K)`. `scope` is `None` for `Auto`.
    With { key: Option<Type>, scope: Option<ScopeArg>, closure: ExprClosure },
    Contribute { into: Type, items: Vec<Contribution> },
}

/// One item of an `into K: [..]` list.
pub(crate) enum Contribution {
    Type(Type),
    Value(Expr),
    /// `value = expr?`, holding `expr` without the `?`.
    TryValue(Expr),
    /// `scope` is `None` for `with = ..`, which declares `Auto`.
    With { scope: Option<ScopeArg>, closure: ExprClosure },
}

const CLOSURE_QUALIFIER: &str = "a closure binding takes no `@` qualifier; write the binding in a `ModuleDef` \
     with `.qualified::<Q>()`, or bind a value, `Db(..) @ Primary`";

const CONTRIBUTION_QUALIFIER: &str = "an `into` item takes no `@` qualifier; a qualified collection is written in a \
     `ModuleDef`, `m.contribute::<K>().qualified::<Q>()`";

const CONTRIBUTION_FORMS: &str =
    "an `into` entry is a type, `value = expr`, `with = |..| ..` or `with(<scope>) = |..| ..`";

impl Parse for ProviderEntry {
    /// `into T: [..]` first, then `with ..`, then `K: with ..`, then a type followed by `,`, `as`
    /// or the end, then an expression.
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        if is_with(input) {
            input.parse::<Ident>()?;
            let (scope, closure) = parse_with(input)?;
            refuse_qualifier(input, CLOSURE_QUALIFIER)?;
            return Ok(ProviderEntry::With { key: None, scope, closure });
        }
        if is_keyed_with(input) {
            let key: Type = input.parse()?;
            if written_as_role_key(&key) {
                return Err(syn::Error::new_spanned(
                    key,
                    "a role key takes contributions, and `K: with = ..` binds a single instance; \
                     a global enhancer is written `into AnyGuard<Http>: [with = ..]`",
                ));
            }
            input.parse::<Token![:]>()?;
            input.parse::<Ident>()?;
            let (scope, closure) = parse_with(input)?;
            refuse_qualifier(input, CLOSURE_QUALIFIER)?;
            return Ok(ProviderEntry::With { key: Some(key), scope, closure });
        }
        if is_contribution(input) {
            input.parse::<Ident>()?;
            let into: Type = input.parse()?;
            input.parse::<Token![:]>()?;
            let content;
            bracketed!(content in input);
            let items = Punctuated::<Contribution, Token![,]>::parse_terminated(&content)?.into_iter().collect();
            return Ok(ProviderEntry::Contribute { into, items });
        }

        let fork = input.fork();
        if fork.parse::<Type>().is_ok_and(|ty| is_type_entry(&ty))
            && (fork.is_empty() || fork.peek(Token![,]) || fork.peek(Token![as]) || fork.peek(Token![@]))
        {
            let ty: Type = input.parse()?;
            if input.peek(Token![as]) {
                input.parse::<Token![as]>()?;
                let as_ty: Type = input.parse()?;
                if written_as_role_key(&as_ty) {
                    return Err(syn::Error::new_spanned(
                        as_ty,
                        "a role key takes contributions, and `as` binds a single instance; \
                         a global enhancer is written `into AnyGuard<Http>: [AuthGuard]`",
                    ));
                }
                let qualifier = parse_qualifier(input)?;
                return Ok(ProviderEntry::ProvideAs { ty, as_ty, qualifier });
            }
            let qualifier = parse_qualifier(input)?;
            return Ok(ProviderEntry::Provide { ty, qualifier });
        }

        Ok(match input.parse::<Expr>()? {
            Expr::Try(expr) => ProviderEntry::TryValue { expr: *expr.expr, qualifier: parse_qualifier(input)? },
            Expr::Closure(closure) => {
                check_factory_params(&closure)?;
                refuse_qualifier(input, CLOSURE_QUALIFIER)?;
                ProviderEntry::With { key: None, scope: None, closure }
            }
            expr => ProviderEntry::Value { expr, qualifier: parse_qualifier(input)? },
        })
    }
}

impl Parse for Contribution {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let item = Self::parse_item(input)?;
        refuse_qualifier(input, CONTRIBUTION_QUALIFIER)?;
        Ok(item)
    }
}

impl Contribution {
    /// `value = ..`, `with = ..` and `with(<scope>) = ..` first, then a type followed by `,` or
    /// the end.
    fn parse_item(input: ParseStream<'_>) -> syn::Result<Self> {
        if input.peek(Ident) && input.peek2(token::Paren) {
            let fork = input.fork();
            let key: Ident = fork.parse()?;
            if key == "with" {
                input.parse::<Ident>()?;
                let scope = ScopeArg::parse_parenthesized(input)?;
                input.parse::<Token![=]>()?;
                return Ok(Contribution::With { scope: Some(scope), closure: parse_with_closure(input)? });
            }
            if key == "value" {
                return Err(syn::Error::new(
                    key.span(),
                    "a `value` is built once and shared, so it takes no scope; write `value = ..`",
                ));
            }
        }
        if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![==]) && !input.peek2(Token![=>]) {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            if key == "value" {
                return Ok(match input.parse::<Expr>()? {
                    Expr::Try(expr) => Contribution::TryValue(*expr.expr),
                    expr => Contribution::Value(expr),
                });
            }
            if key == "with" {
                return Ok(Contribution::With { scope: None, closure: parse_with_closure(input)? });
            }
            return Err(syn::Error::new(key.span(), CONTRIBUTION_FORMS));
        }

        let fork = input.fork();
        if fork.parse::<Type>().is_ok_and(|ty| !is_call(&ty)) && (fork.is_empty() || fork.peek(Token![,]) || fork.peek(Token![@])) {
            return Ok(Contribution::Type(input.parse()?));
        }
        let expr: Expr = input.parse()?;
        Err(syn::Error::new_spanned(expr, format!("{CONTRIBUTION_FORMS}; an expression is contributed with `value = ..`")))
    }
}

/// An optional `@ Q` after an entry: the qualifier type, once. A second `@` is refused here,
/// where the first one's reader can name it.
pub(crate) fn parse_qualifier(input: ParseStream<'_>) -> syn::Result<Qualifier> {
    if !input.peek(Token![@]) {
        return Ok(None);
    }
    input.parse::<Token![@]>()?;
    let qualifier: Type = input.parse()?;
    if input.peek(Token![@]) {
        return Err(syn::Error::new(input.span(), "an entry takes one `@` qualifier"));
    }
    Ok(Some(Box::new(qualifier)))
}

/// An `@` where the grammar has no slot for one.
fn refuse_qualifier(input: ParseStream<'_>, reason: &str) -> syn::Result<()> {
    if input.peek(Token![@]) { Err(syn::Error::new(input.span(), reason)) } else { Ok(()) }
}

/// What follows `with` in a providers entry: an optional `(<scope>)`, `=`, and the closure.
fn parse_with(input: ParseStream<'_>) -> syn::Result<(Option<ScopeArg>, ExprClosure)> {
    let scope = if input.peek(token::Paren) { Some(ScopeArg::parse_parenthesized(input)?) } else { None };
    input.parse::<Token![=]>()?;
    Ok((scope, parse_with_closure(input)?))
}

/// `with =` or `with(`.
fn is_with(input: ParseStream<'_>) -> bool {
    let fork = input.fork();
    let Ok(ident) = fork.parse::<Ident>() else { return false };
    ident == "with" && ((fork.peek(Token![=]) && !fork.peek(Token![==]) && !fork.peek(Token![=>])) || fork.peek(token::Paren))
}

/// A type, a single `:`, then `with`: the key-first form.
fn is_keyed_with(input: ParseStream<'_>) -> bool {
    let fork = input.fork();
    if fork.parse::<Type>().is_err() || !fork.peek(Token![:]) || fork.peek(Token![::]) {
        return false;
    }
    let _ = fork.parse::<Token![:]>();
    fork.parse::<Ident>().is_ok_and(|ident| ident == "with")
}

fn parse_with_closure(input: ParseStream<'_>) -> syn::Result<ExprClosure> {
    match input.parse::<Expr>()? {
        Expr::Closure(closure) => {
            check_factory_params(&closure)?;
            Ok(closure)
        }
        other => Err(syn::Error::new_spanned(
            other,
            "`with` takes a closure whose parameters are injection points, \
             as in `with = |cfg: Dep<MetricsConfig>| MetricsPlugin::new(cfg)`",
        )),
    }
}

impl ProviderEntry {
    /// The statement this entry writes inside `register`, with `m` the `ModuleDef`.
    pub(crate) fn lower(&self) -> TokenStream {
        let ulo = ulo();
        let m = module_def_param();
        match self {
            ProviderEntry::Provide { ty, qualifier } => {
                let qualified = qualified(qualifier);
                let refuse = refuse_controller(ty);
                quote_spanned! {ty.span()=>
                    #refuse
                    #m.provide::<#ty>()#qualified;
                }
            }
            ProviderEntry::ProvideAs { ty, as_ty, qualifier } => {
                let qualified = qualified(qualifier);
                let refuse = refuse_controller(ty);
                quote_spanned! {ty.span()=>
                    #refuse
                    #m.provide::<#ty>().also_as::<#as_ty>(|a| a)#qualified;
                }
            }
            ProviderEntry::TryValue { expr, qualifier } => {
                let expr = unbraced(expr);
                let qualified = qualified(qualifier);
                refuse_controller_value(&expr, quote_spanned! {expr.span()=> #m.try_value(#expr)#qualified })
            }
            ProviderEntry::Value { expr, qualifier } => {
                let expr = unbraced(expr);
                let qualified = qualified(qualifier);
                refuse_controller_value(&expr, quote_spanned! {expr.span()=> #m.value(#expr)#qualified })
            }
            ProviderEntry::With { key, scope, closure } => {
                let closure = wrap_async(closure);
                let scope = scope.map_or_else(|| quote!(#ulo::scope::Auto), |scope| scope.path());
                let bind = match key {
                    None => quote!(__ulo_bind::<#scope>(&mut *#m)),
                    Some(key) => quote!(__ulo_bind_as::<#key, #scope, _>(&mut *#m, |a| a)),
                };
                quote_spanned! {closure.span()=>
                    {
                        #[allow(unused_imports)]
                        use #ulo::__private::factory::{FallibleBinding as _, PlainBinding as _};
                        (&#ulo::__private::factory::Probe::new(#closure)).#bind;
                    }
                }
            }
            ProviderEntry::Contribute { into, items } => {
                let contributions = items.iter().map(|item| item.lower(into));
                quote_spanned! {into.span()=>
                    {
                        #[allow(unused_imports)]
                        use #ulo::__private::contribution_key::{KeyArm as _, MetadataArm as _};
                        (&#ulo::__private::contribution_key::Probe::<#into>::new()).__ulo_check_contribution_key();
                    }
                    #(#contributions)*
                }
            }
        }
    }
}

/// `bind`, a value entry's `m.value(..)` or `m.try_value(..)`, followed by the check that the
/// bound type is not a controller, as [`refuse_controller`] does for a type entry. The
/// type is read off the `Handle` the call returns rather than off the expression, so an expression
/// of the wrong type gets the one error the call reports.
fn refuse_controller_value(expr: &Expr, bind: TokenStream) -> TokenStream {
    let ulo = ulo();
    let handle = Ident::new("handle", Span::mixed_site());
    quote_spanned! {expr.span()=>
        {
            let #handle = #bind;
            #[allow(unused_imports)]
            use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
            (&#ulo::__private::controller_entry::Probe::of_handle(&#handle)).__ulo_check_provider();
        }
    }
}

/// The check that `ty`, bound by a providers entry, is not a controller, spanned at the
/// type so the refusal points there.
fn refuse_controller(ty: &Type) -> TokenStream {
    let ulo = ulo();
    quote_spanned! {ty.span()=>
        {
            #[allow(unused_imports)]
            use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
            (&#ulo::__private::controller_entry::Probe::<#ty>::new()).__ulo_check_provider();
        }
    }
}

/// The expression of a `{ expr }` entry, braces taken off. The braces are how a constant is told
/// from a type in a providers list; written again as the argument of `m.value(..)` they trip
/// rustc's `unused_braces` in the user's crate.
fn unbraced(expr: &Expr) -> &Expr {
    if let Expr::Block(block) = expr
        && block.attrs.is_empty()
        && block.label.is_none()
        && let [syn::Stmt::Expr(inner, None)] = block.block.stmts.as_slice()
    {
        return inner;
    }
    expr
}

/// `.qualified::<Q>()` for an entry written `@ Q`, spanned at the qualifier so a type that does
/// not exist is reported there.
pub(crate) fn qualified(qualifier: &Qualifier) -> TokenStream {
    match qualifier.as_deref() {
        Some(q) => quote_spanned!(q.span()=> .qualified::<#q>()),
        None => TokenStream::new(),
    }
}

impl Contribution {
    /// The statement contributing this item to the collection `into`.
    fn lower(&self, into: &Type) -> TokenStream {
        let ulo = ulo();
        let m = module_def_param();
        match self {
            Contribution::Type(ty) => {
                let refuse = refuse_controller(ty);
                quote_spanned! {ty.span()=>
                    #refuse
                    #m.contribute::<#into>().provide::<#ty>(|a| a);
                }
            }
            Contribution::Value(expr) => quote_spanned! {expr.span()=>
                #m.contribute::<#into>().value(#ulo::__private::Arc::new({
                    let v = #expr;
                    #[allow(unused_imports)]
                    use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
                    (&#ulo::__private::controller_entry::Probe::of(&v)).__ulo_check_provider();
                    v
                }));
            },
            Contribution::TryValue(expr) => quote_spanned! {expr.span()=>
                #m.contribute::<#into>().try_value(::core::result::Result::map(
                    #expr,
                    |v| -> #ulo::__private::Arc<#into> {
                        #[allow(unused_imports)]
                        use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
                        (&#ulo::__private::controller_entry::Probe::of(&v)).__ulo_check_provider();
                        #ulo::__private::Arc::new(v)
                    },
                ));
            },
            Contribution::With { scope, closure } => {
                let closure = wrap_async(closure);
                let scope = scope.map_or_else(|| quote!(#ulo::scope::Auto), |scope| scope.path());
                quote_spanned! {closure.span()=>
                    {
                        #[allow(unused_imports)]
                        use #ulo::__private::factory::{FallibleContribution as _, PlainContribution as _};
                        (&#ulo::__private::factory::Probe::new(#closure))
                            .__ulo_contribute_with::<#into, #scope, _>(&mut *#m, |a| a);
                    }
                }
            }
        }
    }
}

/// Whether `ty` is spelled like one of the role keys: a path ending in `AnyGuard`,
/// `AnyInterceptor` or `AnyErrorHandler`, or `dyn` of the `Erased*` trait each aliases. Read for
/// the `as` diagnostic alone; no lowering depends on it. An alias under another name passes
/// unreported.
fn written_as_role_key(ty: &Type) -> bool {
    const ALIASES: &[&str] = &["AnyGuard", "AnyInterceptor", "AnyErrorHandler"];
    const TWINS: &[&str] = &["ErasedGuard", "ErasedInterceptor", "ErasedErrorHandler"];
    let ends_in = |path: &syn::Path, names: &[&str]| {
        path.segments.last().is_some_and(|segment| names.iter().any(|name| segment.ident == *name))
    };
    match ty {
        Type::Group(group) => written_as_role_key(&group.elem),
        Type::Paren(paren) => written_as_role_key(&paren.elem),
        Type::Path(path) => path.qself.is_none() && ends_in(&path.path, ALIASES),
        Type::TraitObject(object) => object
            .bounds
            .iter()
            .any(|bound| matches!(bound, TypeParamBound::Trait(t) if ends_in(&t.path, TWINS))),
        _ => false,
    }
}

/// `into` followed by a type and a single `:`; `into(x)` and a path through `into::` are
/// expressions.
fn is_contribution(input: ParseStream<'_>) -> bool {
    let fork = input.fork();
    let Ok(ident) = fork.parse::<Ident>() else { return false };
    ident == "into" && fork.parse::<Type>().is_ok() && fork.peek(Token![:]) && !fork.peek(Token![::])
}

/// A provider type is a path without parenthesized arguments. syn reads `Config::default()` as a
/// type, the `Fn()` sugar, so a call would otherwise bind as `provide::<..>()`.
fn is_type_entry(ty: &Type) -> bool {
    matches!(ty, Type::Path(_)) && !is_call(ty)
}

/// A path with parenthesized arguments, looking through the invisible group a `macro_rules`
/// `$t:ty` produces. An `into` list refuses only this shape among types, having no bare
/// expressions for any other to be mistaken for.
fn is_call(ty: &Type) -> bool {
    match ty {
        Type::Group(group) => is_call(&group.elem),
        Type::Path(path) => {
            path.path.segments.iter().any(|segment| matches!(segment.arguments, PathArguments::Parenthesized(_)))
        }
        _ => false,
    }
}