kas-macros 0.17.0

KAS GUI / macros
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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! KAS macros
//!
//! This crate extends [`impl-tools`](https://docs.rs/impl-tools/).

extern crate proc_macro;

use impl_tools_lib::{anon, autoimpl, scope};
use proc_macro::TokenStream;
use proc_macro_error2::{emit_call_site_error, emit_error, proc_macro_error};
use syn::parse_macro_input;
use syn::spanned::Spanned;

mod collection;
mod extends;
mod make_layout;
mod parser;
mod scroll_traits;
mod visitors;
mod widget;
mod widget_args;
mod widget_derive;

/// Implement `Default`
///
/// See [`impl_tools::impl_default`](https://docs.rs/impl-tools/latest/impl_tools/attr.impl_default.html)
/// for full documentation.
#[proc_macro_attribute]
#[proc_macro_error]
pub fn impl_default(attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut toks = item.clone();
    match syn::parse::<impl_tools_lib::ImplDefault>(attr) {
        Ok(attr) => toks.extend(TokenStream::from(attr.expand(item.into()))),
        Err(err) => {
            emit_call_site_error!(err);
            // Since this form of invocation only adds implementations, we can
            // safely output the original item, thus reducing secondary errors.
        }
    }
    toks
}

/// A variant of the standard `derive` macro
///
/// See [`impl_tools::autoimpl`](https://docs.rs/impl-tools/latest/impl_tools/attr.autoimpl.html)
/// for full documentation.
///
/// The following traits are supported:
///
/// | Path | *ignore* | *using* | *notes* |
/// |----- |--- |--- |--- |
/// | [`::core::borrow::Borrow<T>`] | - | borrow target | `T` is type of target field |
/// | [`::core::borrow::BorrowMut<T>`] | - | borrow target | `T` is type of target field |
/// | [`::core::clone::Clone`] | yes | - | ignored fields use `Default::default()` |
/// | [`::core::cmp::Eq`] | * | - | *allowed with `PartialEq` |
/// | [`::core::cmp::Ord`] | yes | - | |
/// | [`::core::cmp::PartialEq`] | yes | - | |
/// | [`::core::cmp::PartialOrd`] | yes | - | |
/// | [`::core::convert::AsRef<T>`] | - | ref target | `T` is type of target field |
/// | [`::core::convert::AsMut<T>`] | - | ref target | `T` is type of target field |
/// | [`::core::default::Default`] | - | - | [`macro@impl_default`] is a more flexible alternative |
/// | [`::core::fmt::Debug`] | yes | - | |
/// | [`::core::hash::Hash`] | yes | - | |
/// | [`::core::marker::Copy`] | * | - | *allowed with `Clone` |
/// | [`::core::ops::Deref`] | - | deref target | `type Target` is type of target field |
/// | [`::core::ops::DerefMut`] | - | deref target | `type Target` is type of target field |
#[proc_macro_attribute]
#[proc_macro_error]
pub fn autoimpl(attr: TokenStream, item: TokenStream) -> TokenStream {
    use autoimpl::ImplTrait;
    use scroll_traits::ImplViewport;
    use std::iter::once;

    let mut toks = item.clone();
    match syn::parse::<autoimpl::Attr>(attr) {
        Ok(autoimpl::Attr::ForDeref(ai)) => toks.extend(TokenStream::from(ai.expand(item.into()))),
        Ok(autoimpl::Attr::ImplTraits(ai)) => {
            // We could use lazy_static to construct a HashMap for fast lookups,
            // but given the small number of impls a "linear map" is fine.
            let find_impl = |path: &syn::Path| {
                autoimpl::STD_IMPLS
                    .iter()
                    .cloned()
                    .chain(once(&ImplViewport as &dyn ImplTrait))
                    .find(|impl_| impl_.path().matches_ident_or_path(path))
            };
            toks.extend(TokenStream::from(ai.expand(item.into(), find_impl)))
        }
        Err(err) => {
            emit_call_site_error!(err);
            // Since autoimpl only adds implementations, we can safely output
            // the original item, thus reducing secondary errors.
        }
    }
    toks
}

const IMPL_SCOPE_RULES: [&dyn scope::ScopeAttr; 3] = [
    &scope::AttrImplDefault,
    &widget_args::AttrImplWidget,
    &widget_derive::AttrDeriveWidget,
];

fn find_attr(path: &syn::Path) -> Option<&'static dyn scope::ScopeAttr> {
    IMPL_SCOPE_RULES
        .iter()
        .cloned()
        .find(|rule| rule.path().matches(path))
}

/// Scope supporting `impl Self` and advanced attribute macros
///
/// This macro facilitates definition of a type (struct, enum or union) plus
/// implementations via `impl Self { .. }` syntax: `Self` is expanded to the
/// type's name, including generics and bounds (as defined on the type).
///
/// Caveat: `rustfmt` can not yet format contents (see
/// [rustfmt#5254](https://github.com/rust-lang/rustfmt/issues/5254),
/// [rustfmt#5538](https://github.com/rust-lang/rustfmt/pull/5538)).
///
/// Note: prefer [`macro@impl_self`] over this macro unless using
/// [`macro@impl_default`]. This macro will be removed once
/// [RFC 3681](https://github.com/rust-lang/rfcs/pull/3681) (default field
/// values) is stable in this crate's MSRV.
///
/// See [`impl_tools::impl_scope`](https://docs.rs/impl-tools/latest/impl_tools/macro.impl_scope.html)
/// for full documentation.
///
/// ## Special attribute macros
///
/// Additionally, `impl_scope!` supports special attribute macros evaluated
/// within its scope:
///
/// -   [`#[impl_default]`](macro@impl_default): implement [`Default`] using
///     field initializers (which are not legal syntax outside of `impl_scope!`)
/// -   [`#[widget]`](macro@widget): implement `kas::Widget` trait family
///
/// Note: matching these macros within `impl_scope!` does not use path
/// resolution. Using `#[kas_macros::impl_default]` would resolve the variant
/// of this macro which *doesn't support* field initializers.
#[proc_macro_error]
#[proc_macro]
pub fn impl_scope(input: TokenStream) -> TokenStream {
    let mut scope = parse_macro_input!(input as scope::Scope);
    scope.apply_attrs(find_attr);
    scope.expand().into()
}

fn find_impl_self_attrs(path: &syn::Path) -> Option<&'static dyn scope::ScopeAttr> {
    use scope::ScopeAttr;
    if widget_args::AttrImplWidget.path().matches(path) {
        Some(&widget_args::AttrImplWidget)
    } else if widget_derive::AttrDeriveWidget.path().matches(path) {
        Some(&widget_derive::AttrDeriveWidget)
    } else {
        None
    }
}

/// Implement a type with `impl Self` syntax
///
/// This attribute macro supports a type (struct, enum, type alias or union)
/// definition plus associated `impl` items within a `mod`.
///
/// Macro expansion discards the `mod` entirely, placing all contents into the
/// outer scope. This simplifies privacy rules in many use-cases, and highlights
/// that the usage of `mod` is purely a hack to make the macro input valid Rust
/// syntax (and thus compatible with `rustfmt`).
///
/// ## Special attribute macros
///
/// Additionally, `#[impl_self]` supports special attribute macros evaluated
/// within its scope:
///
/// -   [`#[widget]`](macro@widget): implement `kas::Widget` trait family
///
/// ## Syntax
///
/// > _ImplSelf_ :\
/// > &nbsp;&nbsp; `#[impl_self]` `mod` _Name_ `{` _ScopeItem_ _ItemImpl_ * `}`
/// >
/// > _ScopeItem_ :\
/// > &nbsp;&nbsp; _ItemEnum_ | _ItemStruct_ | _ItemType_ | _ItemUnion_
///
/// Here, _ItemEnum_, _ItemStruct_, _ItemType_ and _ItemUnion_ are `enum`,
/// `struct`, `type` alias and `union` definitions respectively. Whichever of
/// these is used, it must match the module name _Name_.
///
/// _ItemImpl_ is an `impl` item. It may use the standard implementation syntax
/// (e.g. `impl Debug for MyType { .. }`) or `impl Self` syntax (see below).
///
/// The `mod` may not contain any other items, except `doc` items (documentation
/// on the module itself is ignored in favour of documentation on the defined
/// type) and attributes (which apply as usual).
///
/// ### `impl Self` syntax
///
/// `impl Self` "syntax" is syntactically-valid (but not semantically-valid)
/// Rust syntax for writing inherent and trait `impl` blocks:
///
/// -   `impl Self { ... }` — an inherent `impl` item on the defined type
/// -   `impl Debug for Self { ... }` — a trait `impl` item on the defined type
///
/// Generic parameters and bounds are copied from the type definition.
/// Additional generic parameters may be specified; these extend the list of
/// generic parameters on the type itself, and thus must have distinct names.
/// Additional bounds (where clauses) may be specified; these extend the list of
/// bounds on the type itself.
///
/// ## Example
///
/// ```
/// #[kas_macros::impl_self]
/// mod Pair {
///     /// A pair of values of type `T`
///     pub struct Pair<T>(T, T);
///
///     impl Self {
///         pub fn new(a: T, b: T) -> Self {
///             Pair(a, b)
///         }
///     }
///
///     impl Self where T: Clone {
///         pub fn splat(a: T) -> Self {
///             let b = a.clone();
///             Pair(a, b)
///         }
///     }
/// }
/// ```
#[proc_macro_attribute]
#[proc_macro_error]
pub fn impl_self(attr: TokenStream, input: TokenStream) -> TokenStream {
    let _ = parse_macro_input!(attr as scope::ScopeModAttrs);
    let mut scope = parse_macro_input!(input as scope::ScopeMod).contents;
    scope.apply_attrs(find_impl_self_attrs);
    scope.expand().into()
}

/// Attribute to implement the `kas::Widget` family of traits
///
/// This may *only* be used within the [`macro@impl_self`], [`impl_scope!`]
/// and [`impl_anon!`] macros. It does not need to be imported (it is resolved
/// by the afore-mentioned macros).
///
/// Assists implementation of the [`Widget`], [`Events`], [`Layout`] and [`Tile`] traits.
/// Implementations of these traits are generated if missing or augmented with
/// missing method implementations.
///
/// This macro may inject methods into existing [`Layout`] / [`Tile`] /
/// [`Events`] / [`Widget`] implementations.
/// (In the case of multiple implementations of the same trait, as used for
/// specialization, only the first implementation of each trait is extended.)
///
/// See also the [`macro@layout`] attribute which assists in implementing
/// [`Layout`].
///
/// ## Fields
///
/// The struct must contain a field of type `widget_core!()` (usually named
/// `core`). The macro `widget_core!()` is a placeholder, expanded by
/// `#[widget]` and used to identify the field used (any name may be used).
/// This type implements [`Default`] and [`Clone`], though the clone is not an
/// exact clone (cloned widgets must still be configured).
///
/// Assuming the deriving type is a `struct` or `tuple struct`, fields support
/// the following attributes:
///
/// -   `#[widget]`: marks the field as a [`Widget`] to be configured, enumerated by
///     [`Widget::get_child`] and included by glob layouts
/// -   `#[widget(expr)]`: the same, but maps the data reference type; `expr` is
///     an expression returning a reference to the child widget's input data;
///     available inputs are `self`, `data` (own input data) and `index`
///     (of the child).
/// -   `#[widget = expr]`: an alternative way of writing the above
/// -   `#[collection]`: the field is a [`Collection`] of widgets
///
/// ## Examples
///
/// A simple example is the
/// [`Frame`](https://docs.rs/kas/latest/kas/widgets/struct.Frame.html) widget:
///
/// ```ignore
/// #[impl_self]
/// mod Frame {
///     /// A frame around content
///     #[derive(Clone, Default)]
///     #[widget]
///     #[layout(frame!(self.inner))]
///     pub struct Frame<W: Widget> {
///         core: widget_core!(),
///         #[widget]
///         pub inner: W,
///     }
///
///     impl Self {
///         /// Construct a frame
///         #[inline]
///         pub fn new(inner: W) -> Self {
///             Frame {
///                 core: Default::default(),
///                 inner,
///             }
///         }
///     }
/// }
/// ```
///
/// ## Method modification
///
/// As a policy, this macro *may* inject code into user-defined methods of
/// `Widget` and its super traits, such that:
///
/// -   The modification cannot have harmful side effects (other than reported
///     errors).
/// -   All side effects observable outside of reported error cases must be
///     documented in the widget method documentation.
///
/// As an example, status checks are injected into some `Layout` methods to
/// enforce the expected call order of methods at runtime in debug builds.
///
/// ## Debugging
///
/// To inspect the output of this macro, set the environment variable
/// `KAS_DEBUG_WIDGET` to the name of the widget concerned, dump the output to
/// a temporary file and format. For example:
/// ```sh
/// KAS_DEBUG_WIDGET=Border cargo build > temp.rs
/// rustfmt temp.rs
/// ```
///
/// [`Widget`]: https://docs.rs/kas/latest/kas/trait.Widget.html
/// [`Widget::get_child`]: https://docs.rs/kas/latest/kas/trait.Widget.html#method.get_child
/// [`Layout`]: https://docs.rs/kas/latest/kas/trait.Layout.html
/// [`Tile`]: https://docs.rs/kas/latest/kas/trait.Tile.html
/// [`Events`]: https://docs.rs/kas/latest/kas/trait.Events.html
/// [`Collection`]: https://docs.rs/kas/latest/kas/trait.Collection.html
#[proc_macro_attribute]
#[proc_macro_error]
pub fn widget(_: TokenStream, item: TokenStream) -> TokenStream {
    emit_call_site_error!("must be used within scope of #[impl_self], impl_scope! or impl_anon!");
    item
}

/// Provide a default implementation of the [`Layout`] trait for a widget
///
/// This attribute macro may be used with the [`macro@widget`] macro to provide
/// an implementation of [`Layout`].
///
/// The `#[layout]` attribute **must** follow the [`macro@widget`] attribute (it
/// is not a stand-alone macro).
/// It does not need to be imported (it is resolved by [`macro@widget`]).
///
/// ## Overriding provided fns
///
/// This macro implements [`MacroDefinedLayout`] for the widget and adjusts the
/// default implementations of each [`Layout`] method to call the corresponding
/// [`MacroDefinedLayout`] method. The user may instead provide a direct
/// implementation of any [`Layout`] method; this implementation may or may not
/// call the corresponding [`MacroDefinedLayout`] method.
///
/// ## Layout syntax
///
/// Syntax is as follows:
///
/// > _Item_: _MemberItem_ _Call_* | _LitItem_ _Call_* |
/// > _MacroItem_ _Call_* | _ExprItem_\
/// > &nbsp;&nbsp; A single item
/// >
/// > _MemberItem_: `self` `.` _Member_\
/// > &nbsp;&nbsp; A reference to a field (e.g. `self.label` or `self.0`); this
/// > field must be a `#[widget]`.
/// >
/// > _LitItem_: _StrLit_\
/// > &nbsp;&nbsp; A string literal (e.g. `"Hello world"`). This implicitly
/// > constructs a widget roughly equivalent to `Label<'static str>` but without
/// > text wrapping.
/// >
/// > _MacroItem_: (`frame` | `column` | `row` | `list` | `float` |
/// > `grid`) `!` _MacroArgs_\
/// > &nbsp;&nbsp; These layout macros are natively supported in layout syntax.
/// > They are equivalent to the like-named [macros in `kas::widgets`] aside from
/// > name resolution.
/// >
/// > _ExprItem_: _Expr_\
/// > &nbsp;&nbsp; An expression yielding a widget, e.g.
/// > `Label::new("Hello world")`. The result must be an object of some type
/// > `W: Widget<Data = ()>`. This widget will be stored in a hidden field and
/// > is accessible through `Tile::get_child` but does not receive input data.
///
/// > _Call_ : (`.` ([`align`] | [`pack`] | [`with_stretch`] | [`with_margin_style`]) _MethodArgs_)\
/// > &nbsp;&nbsp; A method call modifying layout.
///
/// [`Layout`]: https://docs.rs/kas/latest/kas/trait.Layout.html
/// [`MacroDefinedLayout`]: https://docs.rs/kas/latest/kas/trait.MacroDefinedLayout.html
/// [macros in `kas::widgets`]: https://docs.rs/kas/latest/kas/widgets/#macros
/// [`align`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.align
/// [`pack`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.pack
/// [`with_stretch`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.with_stretch
/// [`with_margin_style`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.with_margin_style
#[proc_macro_attribute]
#[proc_macro_error]
pub fn layout(_: TokenStream, item: TokenStream) -> TokenStream {
    emit_call_site_error!("must follow use of #[widget]");
    item
}

/// Derive the [`Widget`] family of traits
///
/// This may *only* be used within the [`macro@impl_self`], [`impl_scope!`]
/// and [`impl_anon!`] macros.
///
/// This macro derives a [`Widget`] implementation from the inner field
/// annotated with `#[widget]`. The deriving type may (optionally) override:
///
/// -   Any [`Layout`] method
/// -   A subset of [`Tile`] methods: `navigable`, `tooltip`, `role`, `role_child_properties`, `try_probe`, `nav_next`
/// -   The `Data` type (see [the example below](#example-mapping-data))
///
/// ## Example
///
/// ```ignore
/// #[impl_self]
/// mod Align {
///     /// Apply an alignment hint
///     #[derive_widget]
///     pub struct Align<W: Widget> {
///         #[widget]
///         pub inner: W,
///         hints: AlignHints,
///     }
///
///     impl Self {
///         /// Construct
///         #[inline]
///         pub fn new(inner: W, hints: AlignHints) -> Self {
///             Align { inner, hints }
///         }
///     }
///
///     impl Layout for Self {
///         fn set_rect(&mut self, cx: &mut SizeCx, rect: Rect, hints: AlignHints) {
///             self.inner.set_rect(cx, rect, self.hints.combine(hints));
///         }
///     }
/// }
/// ```
///
/// ### Example mapping data
///
/// This macro supports mapping the data passed to the inner widget. The
/// attribute annotating the inner field specifies the data map. It is required
/// to specify the `Widget::Data` type.
///
/// ```ignore
/// #[impl_self]
/// mod Map {
///     #[autoimpl(Deref, DerefMut using self.inner)]
///     #[autoimpl(Viewport using self.inner where W: trait)]
///     #[derive_widget]
///     pub struct Map<A, W: Widget, F>
///     where
///         F: for<'a> Fn(&'a A) -> &'a W::Data,
///     {
///         #[widget = (self.map_fn)(data)]
///         pub inner: W,
///         map_fn: F,
///         _data: PhantomData<A>,
///     }
///
///     impl Widget for Self {
///         type Data = A;
///     }
/// }
/// ```
///
/// ### A note on `Deref`
///
/// The above examples implement [`Deref`] over the inner widget. This is
/// acceptable for a simple wrapping "derive widget". It is not recommended to
/// implement [`Deref`] for non-derived widgets (i.e. when the outer widget has
/// its own `Id`) due to the potential for method collision (e.g. `outer.id()`
/// may resolve to `outer.deref().id()` when the trait providing `fn id` is not
/// in scope, yet is available through a bound on the field).
///
/// [`Layout`]: https://docs.rs/kas/latest/kas/trait.Layout.html
/// [`Tile`]: https://docs.rs/kas/latest/kas/trait.Tile.html
/// [`Widget`]: https://docs.rs/kas/latest/kas/trait.Widget.html
/// [`Deref`]: std::ops::Deref
#[proc_macro_attribute]
#[proc_macro_error]
pub fn derive_widget(_: TokenStream, item: TokenStream) -> TokenStream {
    emit_call_site_error!("must be used within scope of #[impl_self], impl_scope! or impl_anon!");
    item
}

/// Construct a single-instance struct
///
/// Rust doesn't currently support [`impl Trait { ... }` expressions](https://github.com/canndrew/rfcs/blob/impl-trait-expressions/text/0000-impl-trait-expressions.md)
/// or implicit typing of struct fields. This macro is a **hack** allowing that.
///
/// Example:
/// ```
/// # use kas_macros as kas;
/// use std::fmt;
/// fn main() {
///     let world = "world";
///     let says_hello_world = kas::impl_anon! {
///         struct(&'static str = world);
///         impl fmt::Display for Self {
///             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
///                 write!(f, "hello {}", self.0)
///             }
///         }
///     };
///     assert_eq!(format!("{}", says_hello_world), "hello world");
/// }
/// ```
///
/// That is, this macro creates an anonymous struct type (must be a struct),
/// which may have trait implementations, then creates an instance of that
/// struct.
///
/// Struct fields may have a fixed type or may be generic. Syntax is as follows:
///
/// -   **regular struct:** `ident: ty = value`
/// -   **regular struct:** `ident: ty` (uses `Default` to construct value)
/// -   **tuple struct:** `ty = value`
/// -   **tuple struct:** `ty` (uses `Default` to construct value)
///
/// The field name, `ident`, may be `_` (anonymous field).
///
/// Refer to [examples](https://github.com/search?q=impl_anon+repo%3Akas-gui%2Fkas+path%3Aexamples&type=Code) for usage.
#[proc_macro_error]
#[proc_macro]
pub fn impl_anon(input: TokenStream) -> TokenStream {
    let mut input = parse_macro_input!(input as anon::Anon);
    for field in input.fields.iter_mut() {
        if matches!(&field.ty, syn::Type::Infer(_)) {
            let span = if let Some(ref ident) = field.ident {
                ident.span()
            } else if let Some((ref eq, _)) = field.assignment {
                eq.span()
            } else {
                // This is always available and should be the first choice,
                // but it may be synthesized (thus no useful span).
                // We can't test since Span::eq is unstable!
                field.ty.span()
            };
            emit_error!(span, "expected `: TYPE`");
        }
    }
    let mut scope = input.into_scope();
    scope.apply_attrs(find_attr);
    scope.expand().into()
}

/// Index of a child widget
///
/// This macro is usable only within an [`macro@impl_self`], [`impl_scope!`] or
/// [`impl_anon!`] macro using the [`macro@widget`] attribute.
///
/// Example usage: `widget_index![self.a]`. If `a` is a child widget (a field
/// marked with the `#[widget]` attribute), then this expands to the child
/// widget's index (as used by [`Widget::get_child`]). Otherwise, this is an error.
///
/// [`Widget::get_child`]: https://docs.rs/kas/latest/kas/trait.Widget.html#method.get_child
#[proc_macro_error]
#[proc_macro]
pub fn widget_index(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as visitors::UnscopedInput);
    input.into_token_stream().into()
}

/// Generate an anonymous struct which implements [`kas::Collection`]
///
/// # Syntax
///
/// > _Collection_ :\
/// > &nbsp;&nbsp; `collection!` `[` _Items_<sup>\?</sup> `]`
/// >
/// > _Items_ :\
/// > &nbsp;&nbsp; (_Item_ `,`)<sup>\*</sup> _Item_ `,`<sup>\?</sup>
///
/// In this case, _Item_ may be:
///
/// -   A string literal (interpreted as a label widget), optionally followed by
///     any of the following method calls: [`align`], [`pack`],
///     [`with_stretch`], [`with_margin_style`]
/// -   An expression yielding an object implementing `Widget<Data = _A>`
///
/// In case all _Item_ instances are a string literal, the data type of the
/// `collection!` widget will be `()`; otherwise the data type of the widget is `_A`
/// where `_A` is a generic type parameter of the widget.
///
/// For example usage, see [`List`](https://docs.rs/kas/latest/kas/widgets/struct.List.html).
///
/// [`kas::Collection`]: https://docs.rs/kas/latest/kas/trait.Collection.html
/// [`align`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.align
/// [`pack`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.pack
/// [`with_stretch`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.with_stretch
/// [`with_margin_style`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.with_margin_style
#[proc_macro_error]
#[proc_macro]
pub fn collection(input: TokenStream) -> TokenStream {
    parse_macro_input!(input as collection::Collection)
        .expand()
        .into()
}

/// Generate an anonymous struct which implements [`kas::CellCollection`]
///
/// # Syntax
///
/// > _Collection_ :\
/// > &nbsp;&nbsp; `cell_collection!` `{` _ItemArms_<sup>\?</sup> `}`
/// >
/// > _ItemArms_ :\
/// > &nbsp;&nbsp; (_ItemArm_ `,`)<sup>\*</sup> _ItemArm_ `,`<sup>\?</sup>
/// >
/// > _ItemArm_ :\
/// > &nbsp;&nbsp; _Cell_ | _RowMacro_ | _ColumnMacro_
/// >
/// > _Cell_ :\
/// > &nbsp;&nbsp; `(` _Column_ `,` _Row_ `)` `=>` _Item_
/// >
/// > _Column_, _Row_ :\
/// > &nbsp;&nbsp; _LitInt_ | ( _LitInt_ `..=` _LitInt_ )
/// >
/// > _RowMacro_ :\
/// > &npsb;&nbsp; `row!` `[` (_Item_ `,` | `_` `,`)* _Item_ `]`
/// >
/// > _ColumnMacro_ :\
/// > &npsb;&nbsp; `column!` `[` (_Item_ `,` | `_` `,`)* _Item_ `]`
///
/// Here, _Column_ and _Row_ are selected via an index (from 0) or an inclusive
/// range, for example `2` or `2..=3`.
///
/// A `row!` macro resolves to a list of cells whose column index is one larger
/// than maximum prior column index and whose row indices count from 0.
/// As a special case, `_` may be used to skip a cell (infer an empty cell).
/// A `column!` macro functions similarly.
///
/// _Item_ may be:
///
/// -   A string literal (interpreted as a label widget), optionally followed by
///     any of the following method calls: [`align`], [`pack`], [`with_stretch`]
///     [`with_stretch`], [`with_margin_style`]
/// -   An expression yielding an object implementing `Widget<Data = _A>`
///
/// In case all _Item_ instances are a string literal, the data type of the
/// `collection!` widget will be `()`; otherwise the data type of the widget is `_A`
/// where `_A` is a generic type parameter of the widget.
///
/// For example usage, see [`Grid`](https://docs.rs/kas/latest/kas/widgets/struct.Grid.html).
///
/// [`kas::CellCollection`]: https://docs.rs/kas/latest/kas/trait.CellCollection.html
/// [`align`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.align
/// [`pack`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.pack
/// [`with_stretch`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.with_stretch
/// [`with_margin_style`]: https://docs.rs/kas/latest/kas/widgets/adapt/trait.AdaptWidget.html#method.with_margin_style
#[proc_macro_error]
#[proc_macro]
pub fn cell_collection(input: TokenStream) -> TokenStream {
    parse_macro_input!(input as collection::CellCollection)
        .expand()
        .into()
}

/// A limited form of class inheritance
///
/// For supported traits (see below), this macro implements missing trait
/// methods as a wrapper over the same method on a specified *base*.
///
/// ## Supported usage
///
/// ### ThemeDraw
///
/// Attribute parameters:
///
/// > `ThemeDraw` `using` _Expr_
///
/// This implements missing `kas::theme::ThemeDraw` methods over the specified
/// *base* expression _Expr_. This expression is expected to yield an object
/// implementing `ThemeDraw`. All applicable types should be in scope.
///
/// #### Example
///
/// ```ignore
/// #[extends(ThemeDraw using self.base())]
/// impl ThemeDraw for Object {
///     // ...
/// }
/// ```
///
/// Since this example does not provide an implementation of `fn image`, this
/// macro would provide the implementation below:
/// ```ignore
/// fn image(&mut self, id: ImageId, rect: Rect) {
///     (self.base()).image(id, rect);
/// }
/// ```
/// Each `ThemeDraw` method not implemented in the `impl` block is implemented
/// by the macro in this manner.
#[proc_macro_attribute]
#[proc_macro_error]
pub fn extends(attr: TokenStream, item: TokenStream) -> TokenStream {
    match syn::parse::<extends::Extends>(attr) {
        Ok(extends) => match extends.extend(item.into()) {
            Ok(result) => result.into(),
            Err(err) => {
                emit_call_site_error!(err);
                TokenStream::new()
            }
        },
        Err(err) => {
            emit_call_site_error!(err);
            item
        }
    }
}