prebindgen-flat 0.5.0

The prebindgen flat model: the parser from captured #[prebindgen] records to a flat namespace of elements
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
//! The elements: one variant per structure the source language allows.
//!
//! Every node — an item, a parameter, a field, a variant, a type — carries one
//! [`Origin`], so generated Rust names the source by re-emitting what the source
//! wrote, nothing re-parses a whole item to find a part of it, and no level has
//! to copy a piece of provenance down from the level above.
//!
//! **Structure only.** Everything that turns an element back into Rust tokens
//! lives in [`spell`](super::spell), so the shape of an element says nothing
//! about the language it came from.

use prebindgen::SourceLocation;

use super::{origin::Origin, ty::TypeRef};

/// One member of the flat API.
///
/// Three modelled kinds — a function, a type, a constant — plus
/// [`Element::Guard`] for an anonymous const and [`Element::Unsupported`] for
/// anything the language cannot express. No *marked*
/// item passes through verbatim: a `#[prebindgen]` crate marks the items that
/// cross the boundary, and the supporting code around them is the consumer
/// crate's job — the proc-macro enforces that already, refusing to mark a `use`,
/// `mod`, `impl` or `macro_rules!` at all.
#[derive(Clone, Debug)]
pub enum Element {
    Function(Function),
    /// A type declaration: a struct, either enum shape, or an opaque handle.
    Type(Type),
    Constant(Constant),
    /// An anonymous const — infrastructure re-emitted verbatim. Carries no API
    /// surface: nothing can name it, declare it, or cross it.
    Guard(Guard),
    /// An item the language cannot express — a parameter type outside the
    /// grammar, a `self` receiver, a reference to a type the flat API never
    /// declares, or a whole item kind it does not model such as a `union`.
    ///
    /// Indexed under its name so nothing else can claim it, with the diagnosis
    /// riding along. Parsing carries it; building a
    /// `Registry` from a model holding one fails, reporting
    /// every offender at once. See the [module docs](super) on where acceptance
    /// is enforced.
    Unsupported(Unsupported),
}

impl Element {
    /// The item's name, which is also its address: `#[prebindgen]` names live
    /// in one flat namespace across every ingested source crate.
    ///
    /// `None` when the item has no address — a [`Guard`], or an item kind with
    /// no identifier at all.
    pub fn name(&self) -> Option<&syn::Ident> {
        match self {
            Element::Function(f) => Some(&f.name),
            Element::Type(t) => Some(t.name()),
            Element::Constant(c) => Some(&c.name),
            Element::Guard(_) => None,
            Element::Unsupported(u) => u.name.as_ref(),
        }
    }

    /// Where the item was captured, including the crate that marked it.
    ///
    /// The same location every component of this item carries — they share one
    /// [`Origin::location`], because one captured record is one item.
    pub fn location(&self) -> &SourceLocation {
        match self {
            Element::Function(f) => &f.origin.location,
            Element::Type(t) => t.location(),
            Element::Constant(c) => &c.origin.location,
            Element::Guard(g) => &g.origin.location,
            Element::Unsupported(u) => &u.origin.location,
        }
    }

    /// The whole item as `syn` — **the escape**, at the item level. See
    /// [`Origin::as_syn`](super::Origin::as_syn).
    ///
    /// It builds a `syn::Item` rather than borrowing one, because each variant
    /// keeps the item kind it was parsed as. That makes it the natural route for
    /// an emitter re-stating a whole item, and the ledger's **item** bucket is
    /// where those land.
    pub(crate) fn as_syn(&self) -> syn::Item {
        match self {
            Element::Function(f) => syn::Item::Fn(f.origin.as_syn().clone()),
            Element::Type(t) => t.as_syn(),
            Element::Constant(c) => syn::Item::Const(c.origin.as_syn().clone()),
            Element::Guard(g) => syn::Item::Const(g.origin.as_syn().clone()),
            Element::Unsupported(u) => u.origin.as_syn().clone(),
        }
    }
}

/// A type the flat API declares.
///
/// Four shapes, and the classification is what a destination language acts on: a
/// product of fields, a sum, a named set of integers, or a handle whose contents
/// do not cross.
#[derive(Clone, Debug)]
pub enum Type {
    Struct(Struct),
    /// An enum whose alternatives carry payloads — a sum type.
    Variant(Variant),
    /// An enum whose every alternative is fieldless — a named set of integers.
    Enum(Enum),
    Extern(Extern),
}

impl Type {
    pub fn name(&self) -> &syn::Ident {
        match self {
            Type::Struct(s) => &s.name,
            Type::Variant(v) => &v.name,
            Type::Enum(e) => &e.name,
            Type::Extern(e) => &e.name,
        }
    }

    pub fn location(&self) -> &SourceLocation {
        self.location_rc()
    }

    /// The shared location itself, for building a sibling node's [`Origin`].
    pub(super) fn location_rc(&self) -> &std::rc::Rc<SourceLocation> {
        match self {
            Type::Struct(s) => &s.origin.location,
            Type::Variant(v) => &v.origin.location,
            Type::Enum(e) => &e.origin.location,
            Type::Extern(e) => &e.origin.location,
        }
    }

    /// The whole item as `syn` — **the escape**. See [`Element::as_syn`].
    pub(crate) fn as_syn(&self) -> syn::Item {
        match self {
            Type::Struct(s) => syn::Item::Struct(s.origin.as_syn().clone()),
            Type::Variant(v) => syn::Item::Enum(v.origin.as_syn().clone()),
            Type::Enum(e) => syn::Item::Enum(e.origin.as_syn().clone()),
            Type::Extern(e) => e.origin.as_syn().clone(),
        }
    }
}

/// A type the flat API **names** but whose contents it does not model.
///
/// Two spellings declare one thing, because what the frontend records is the fact
/// rather than the Rust shape that carried it:
///
/// * `#[prebindgen] pub type X = path::To<Thing>;` — how a foreign or
///   crate-private type gets a name here. A **one-way road**: the name is
///   thereafter the only way to spell that type inside the flat API, and the
///   qualified path stays refused. This declares a name; it is not an equivalence
///   between spellings: the normalization that makes `std::vec::Vec<T>` and
///   `Vec<T>` one key covers the names the *language* predeclares, and a crate's
///   own alias is never one of those — treating it as one is a category error.
/// * `#[prebindgen] pub struct X(..);` — a tuple struct, whose fields no adapter
///   has ever crossed.
///
/// Not necessarily a *handle*: `#[prebindgen] pub type Duration =
/// std::time::Duration;` crosses by value through a `convert!`, erased to a plain
/// integer. What it becomes — an opaque pointer, a `ptr_class`, a conversion — is
/// the adapter's decision, and this says only that the frontend does not model the
/// contents.
#[derive(Clone, Debug)]
pub struct Extern {
    pub name: syn::Ident,
    /// What the declaration points at, for an alias — `std::time::Duration`,
    /// `zenoh::Session`, `handles::Storage`. `None` for a tuple struct, which is
    /// itself the definition.
    ///
    /// Informational, and deliberately **not** classified. `Error` is
    /// `Box<dyn std::error::Error + Send + Sync>` behind a `zenoh::` alias in one
    /// crate and spelled openly in another, so being "a std type" is a property of
    /// the spelling, not of the type. An adapter that wants to recognise a target
    /// may; the frontend does not decide for it.
    pub target: Option<String>,
    /// The declaring item — a type alias or a tuple struct.
    pub origin: Origin<syn::Item>,
}

/// A `#[prebindgen]` free function.
#[derive(Clone, Debug)]
pub struct Function {
    pub name: syn::Ident,
    /// Parameters in declaration order.
    pub params: Vec<Param>,
    /// What the function returns. An elided return is
    /// [`TypeKind::Unit`](super::TypeKind), exactly as a written `-> ()` is:
    /// they mean the same thing, differ only in spelling, and every consumer
    /// today already normalizes one to the other on the spot.
    pub ret: TypeRef,
    /// The whole item: attributes, `cfg`, doc comments, body.
    pub origin: Origin<syn::ItemFn>,
}

impl Function {
    /// A synthesized **nullary getter**: `pub fn <ident>() -> <ret>`.
    ///
    /// The model's own constructor for the one element an adapter legitimately
    /// needs to invent — a declared `const`'s accessor, whose type flows through
    /// the ordinary output-converter machinery and so has to arrive as a
    /// `Function` like any other.
    ///
    /// It lives here because building one means **spelling** `ret`, and #280
    /// says a `TypeRef` is the model's to mint. An adapter that built this
    /// itself needed a spelling for a model element — which dragged the
    /// emission capability into validation and Kotlin rendering, both of which
    /// only wanted the resulting `Function`.
    ///
    /// The body is `unimplemented!()` and is never emitted: only the signature
    /// is read.
    pub fn synthetic_getter(ident: syn::Ident, ret: TypeRef) -> Self {
        let ret_syntax = ret.spell();
        let item: syn::ItemFn = syn::parse_quote! {
            pub fn #ident() -> #ret_syntax {
                unimplemented!()
            }
        };
        Self {
            name: ident,
            params: Vec::new(),
            origin: ret.origin_with(item),
            ret,
        }
    }
}

/// One parameter of a [`Function`].
#[derive(Clone, Debug)]
pub struct Param {
    pub name: syn::Ident,
    pub ty: TypeRef,
    /// The parameter as written — `mode: Mode`.
    pub origin: Origin<syn::PatType>,
}

/// A `#[prebindgen]` struct: a product of fields that cross the boundary.
///
/// A struct whose contents do *not* cross is an [`Extern`], not a `Struct` with
/// nothing in it — so `fields` is a plain list, and empty means the source wrote
/// a struct with no fields.
///
/// Whether the fields are named or positional is not recorded: a [`Field`]
/// already knows its own address, and the delimiters are spelling, read off the
/// syntax when the struct is spelled.
#[derive(Clone, Debug)]
pub struct Struct {
    pub name: syn::Ident,
    pub fields: Vec<Field>,
    pub origin: Origin<syn::ItemStruct>,
    /// This struct **as a type**, taken at parse time — the twin of
    /// [`Variant::reading`], stored and `pub(super)` for the same two reasons.
    pub(super) reading: TypeRef,
}

impl Struct {
    /// This struct as a type reference — what the **declaration** answers when
    /// something needs a reading naming it.
    ///
    /// The alternative is composing one from the name at the call site, which
    /// an adapter cannot do (minting is sealed to this crate) and which would
    /// be phase-dependent if routed through the registry instead: a
    /// decomposition is declared before anything is interned. The declaration
    /// is the one thing that can always say. Same reasoning as
    /// [`Variant::type_ref`].
    pub fn type_ref(&self) -> &TypeRef {
        &self.reading
    }
}

/// A `#[prebindgen]` enum whose alternatives carry payloads — a sum type.
///
/// Distinct from [`Enum`], which is the fieldless shape, because the two are
/// consumed as different constructs and **numbered differently**. A sum's
/// alternatives are identified by position: the mirror an adapter builds carries
/// no `repr` and numbers its own arms, so a Rust discriminant would be the wrong
/// answer here — which is why there is no slot for one.
///
/// Both shapes are spelled `enum` in Rust and both keep a `syn::ItemEnum` in
/// their origin. Which one an item *is* is the classification, and it is decided
/// once: any alternative with a field makes it a `Variant`.
#[derive(Clone, Debug)]
pub struct Variant {
    pub name: syn::Ident,
    /// Alternatives in declaration order; `alternatives[i].index == i`.
    pub alternatives: Vec<Alternative>,
    pub origin: Origin<syn::ItemEnum>,
    /// This sum **as a type**, taken at parse time — see [`Self::type_ref`].
    ///
    /// **Stored, not computed**, and that is what makes the accessor safe: a
    /// method composing `TypeRef::named(&self.name)` would answer for whatever
    /// name a caller put in the struct, so a `Variant` named `String` would
    /// yield `Named` over the spelling `String` — which the model reads as
    /// `Str`. A stored reading cannot disagree with the model, because the
    /// model is what put it there, and an assembler has no way to mint a
    /// different one.
    ///
    /// `pub(super)` is the second line, not the first: it also stops a
    /// `Variant` being assembled at all outside `flat` (`E0451`), so `name` and
    /// `reading` cannot be paired inconsistently with *each other*.
    pub(super) reading: TypeRef,
}

impl Variant {
    /// A reference to this sum **as a type** — what a consumer needs when it
    /// has to name the sum rather than walk it (jnigen's `SumTag` selector,
    /// which carries *which* sum it chooses between).
    ///
    /// The **declaration** answers, so no consumer has to mint a reading from
    /// the name and hope it matches what the model would have said.
    ///
    /// This returns state the parser took, **not** a fresh composition, and the
    /// difference is the difference between sealing and appearing to.
    ///
    /// A version that composed `TypeRef::named(&self.name)` would hand a
    /// `Variant` assembled with the name `String` a
    /// [`Named`](super::TypeKind::Named) over the spelling `String` — which the
    /// model reads as [`Str`](super::TypeKind::Str). That is the `kind`/`syntax`
    /// disagreement [`TypeRef`]'s private fields exist to prevent, and it was
    /// reachable from outside the crate while being invisible to every doctest
    /// there, because assembling the *element* is not minting the *type*.
    ///
    /// Reading a stored value closes it: whatever a caller does with the other
    /// fields, the reading here is the one the model made, and no caller can
    /// mint a different one to put in its place.
    ///
    /// The `Variant` is sealed as well — its `reading` field is `pub(super)` —
    /// so the two cannot even be paired inconsistently:
    ///
    /// ```compile_fail
    /// # use prebindgen_flat::flat::{Origin, Variant};
    /// let assembled = Variant {
    ///     name: syn::parse_str("String").unwrap(),
    ///     alternatives: vec![],
    ///     origin: Origin::new(
    ///         syn::parse_str("enum String { A(u8) }").unwrap(),
    ///         std::rc::Rc::new(Default::default()),
    ///     ),
    /// };
    /// let mismatched = assembled.type_ref();
    /// ```
    ///
    /// That doctest pins *"a consumer cannot assemble a `Variant`"* and nothing
    /// finer: measured, it still fails with the field made `pub` — as `E0063`
    /// (missing field) rather than `E0451` (private field), since a consumer
    /// cannot produce a `TypeRef` to supply either way. The visibility itself
    /// is the check the compiler runs on every build.
    pub fn type_ref(&self) -> &TypeRef {
        &self.reading
    }
}

/// One alternative of a [`Variant`].
#[derive(Clone, Debug)]
pub struct Alternative {
    pub name: syn::Ident,
    /// Position within its sum, `0..N-1` — the same fact a [`Field`] carries,
    /// for the same reason: a node handed out on its own still knows where it
    /// sits.
    ///
    /// This is the *only* numbering a sum has. What a destination language does
    /// with it is its own business: one may transmit it to say which alternative
    /// is live, another may send a name instead.
    pub index: usize,
    /// The alternative's payload, in declaration order. May be empty — a sum can
    /// mix payload-carrying and payload-free alternatives, and only the presence
    /// of *some* payload makes the type a `Variant`.
    pub fields: Vec<Field>,
    /// The alternative as written: delimiters, attributes, doc comments.
    pub origin: Origin<syn::Variant>,
}

impl Alternative {
    /// True when this alternative carries no payload.
    ///
    /// The *group* question, not the syntax one: `B`, `B()` and `B {}` are all
    /// empty by this test; what keeps their delimiters apart is the spelling,
    /// not this.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

/// A `#[prebindgen]` enum whose every alternative is fieldless — the C-style
/// shape, a named set of integers.
///
/// Distinct from [`Variant`] because the identity of a member here is the value
/// Rust **assigns** it, not where it sits: a C header re-states each `= expr`
/// and a Kotlin `enum class` entry is `NAME(7)`. A sum has no such value, which
/// is why the two are separate entities rather than one with a dead field each.
#[derive(Clone, Debug)]
pub struct Enum {
    pub name: syn::Ident,
    /// This enum **as a type**, taken at parse time — the twin of
    /// [`Variant::reading`] and [`Struct::reading`], stored and `pub(super)`
    /// for the same two reasons.
    pub(super) reading: TypeRef,
    /// Values in declaration order; `values[i].index == i`.
    pub values: Vec<EnumValue>,
    pub origin: Origin<syn::ItemEnum>,
}

impl Enum {
    /// Every value paired with the number Rust assigns it, or the first value
    /// whose discriminant could not be evaluated.
    ///
    /// This is the numbering a destination language needs when it has no way to
    /// reference a Rust constant: a Kotlin `enum class` entry is `NAME(3)`, and
    /// the generated `int → value` decode matches on the same numbers, so both
    /// come from here and cannot drift. An `Err` is a refusal for *that*
    /// consumer only — one that re-emits the source spelling never asks.
    pub fn discriminant_values(&self) -> Result<Vec<(&syn::Ident, i64)>, &syn::Ident> {
        self.values
            .iter()
            .map(|v| match v.discriminant {
                Some(n) => Ok((&v.name, n)),
                None => Err(&v.name),
            })
            .collect()
    }
}

impl Enum {
    /// This enum as a type reference — what the **declaration** answers.
    /// See [`Variant::type_ref`].
    pub fn type_ref(&self) -> &TypeRef {
        &self.reading
    }
}

/// One named value of an [`Enum`].
#[derive(Clone, Debug)]

pub struct EnumValue {
    pub name: syn::Ident,
    /// Position within its enum, `0..N-1`. Not the identity — see
    /// [`Self::discriminant`] — but the same "where it sits" fact every node in
    /// an ordered list carries, and what a consumer falls back to when a
    /// discriminant cannot be evaluated.
    pub index: usize,
    /// The value Rust assigns — an explicit `= N` sets it, an implicit value
    /// takes the previous plus one, starting at 0. **This shape's identity.**
    ///
    /// `None` once a spelling the frontend cannot evaluate (a `const`, a `cfg`,
    /// arithmetic) has broken the chain, or once the chain has run out of `i64`.
    /// That is not a failure: only a consumer that needs the *number* is
    /// affected, and one that re-emits the *spelling* reads
    /// [`Self::origin`]`.syntax.discriminant` instead.
    pub discriminant: Option<i64>,
    /// The value as written: `= 0x07`, attributes, doc comments — and its
    /// delimiters, since `B` and `B()` are both fieldless and still spelled
    /// differently.
    pub origin: Origin<syn::Variant>,
}

/// One field of a [`Struct`] or of an [`Alternative`].
#[derive(Clone, Debug)]
pub struct Field {
    /// The field's name, or `None` for a positional one.
    pub name: Option<syn::Ident>,
    /// Position within its struct or alternative, `0..N-1` — the same fact an
    /// [`Alternative`] carries.
    ///
    /// The address of a positional field. A named field has one too, and simply
    /// does not need it: it is addressed by name, so this is available rather
    /// than used — the same way it carries its item's location.
    pub index: usize,
    pub ty: TypeRef,
    /// The field as written — `pub id: u64`, attributes and docs included.
    pub origin: Origin<syn::Field>,
}

/// A `#[prebindgen]` constant.
///
/// Always named: an unnamed `const _` is a [`Guard`], not a constant with no
/// address.
#[derive(Clone, Debug)]
pub struct Constant {
    pub name: syn::Ident,
    pub ty: TypeRef,
    /// The whole item — the initializer expression included, which is where a
    /// consumer that re-emits the value reads it from.
    pub origin: Origin<syn::ItemConst>,
}

/// An **anonymous const**: `const _: T = ..`, whatever produced it.
///
/// The definition is the shape, not the origin. A const with no name has no
/// address, so nothing can declare it, reference it, or emit it as an alias —
/// which is what puts it outside the flat API rather than in it, and that holds
/// however the item arrived: synthesized, hand-fed to [`FlatBuilder`](super::FlatBuilder), or written
/// as `#[prebindgen] const _: () = ..` in a source crate.
///
/// **Today's producer** is [`Source`](prebindgen::Source)'s cfg filter, which
/// synthesizes `const _: () = { konst::assertc_eq!(..) }` to assert that a source
/// crate's `FEATURES` match what the build script asked for. Nothing *marked*
/// that one — it is prebindgen's own item riding the same stream — but it is not
/// the only thing that can land here, and the model does not claim otherwise.
///
/// **Cardinality is zero or more.** `enable_feature_filtering(None)` produces
/// none, and each item iterator taken from a `Source` emits its own, so composing
/// two iterators from one crate yields two.
///
/// It carries no type, unlike a [`Constant`]. The item is emitted verbatim, so
/// what its types mean is the consumer crate's business; modelling them would let
/// a guard that names something undeclared refuse the whole element.
#[derive(Clone, Debug)]
pub struct Guard {
    /// Emitted verbatim, so the item is all there is.
    pub origin: Origin<syn::ItemConst>,
}

/// An item the language cannot express.
#[derive(Clone, Debug)]
pub struct Unsupported {
    /// The item's identifier, or `None` for an item kind that has none.
    pub name: Option<syn::Ident>,
    /// What could not be expressed, ready to be raised by whatever declares
    /// this item. Boxed: it is the size outlier among the elements, and this
    /// one is the rare variant.
    pub error: Box<super::ItemError>,
    /// The item as written, so a diagnosis can quote the source.
    pub origin: Origin<syn::Item>,
}

/// An item's `///` documentation, read off the attributes it was captured
/// with: `#[doc = " …"]` lines in order, one leading space stripped per line,
/// joined with `\n`; `None` when there are none. `*/` is defanged so the text
/// is safe inside a `/** … */` block, which is what every destination that
/// re-emits prose needs.
///
/// **Here rather than in an adapter.** A doc comment is something the *source*
/// said, so it is the model's to report — and reading it was the last common
/// reason an emitter reached for a captured item's node. Two adapters wanting
/// the same prose is one function, not a copy each.
fn docs_from(attrs: &[syn::Attribute]) -> Option<String> {
    let mut lines: Vec<String> = Vec::new();
    for attr in attrs {
        if !attr.path().is_ident("doc") {
            continue;
        }
        let syn::Meta::NameValue(nv) = &attr.meta else {
            continue;
        };
        let syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Str(s),
            ..
        }) = &nv.value
        else {
            continue;
        };
        let raw = s.value();
        let line = raw.strip_prefix(' ').unwrap_or(&raw);
        lines.push(line.replace("*/", "*\u{200B}/"));
    }
    (!lines.is_empty()).then(|| lines.join("\n"))
}

macro_rules! docs_accessor {
    ($($ty:ident),+ $(,)?) => {$(
        impl $ty {
            /// This item's `///` documentation.
            pub fn docs(&self) -> Option<String> {
                docs_from(&self.origin.syntax.attrs)
            }
        }
    )+};
}

docs_accessor!(
    Function,
    Struct,
    Enum,
    Variant,
    Constant,
    Field,
    Alternative,
    EnumValue
);