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
// 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

//! Collection macro

use crate::parser::{Parser, parse_grid, parse_list};
use proc_macro2::{Span, TokenStream as Toks};
use quote::{ToTokens, TokenStreamExt, quote};
use syn::parenthesized;
use syn::parse::{Error, Parse, ParseStream, Result};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::Comma;
use syn::{Expr, Ident, LitInt, LitStr, Token};

#[allow(non_camel_case_types)]
mod kw {
    syn::custom_keyword!(align);
    syn::custom_keyword!(pack);
    syn::custom_keyword!(with_stretch);
    syn::custom_keyword!(column);
    syn::custom_keyword!(row);
}

#[derive(Default)]
pub struct NameGenerator(usize);
impl NameGenerator {
    pub fn next(&mut self) -> Ident {
        let name = format!("_stor{}", self.0);
        self.0 += 1;
        let span = Span::call_site();
        Ident::new(&name, span)
    }
}

#[derive(Copy, Clone, Debug)]
pub struct CellInfo {
    pub col: u32,
    pub last_col: u32,
    pub row: u32,
    pub last_row: u32,
}

impl CellInfo {
    pub fn new(col: u32, row: u32) -> Self {
        CellInfo {
            col,
            last_col: col,
            row,
            last_row: row,
        }
    }
}

impl Parse for CellInfo {
    fn parse(input: ParseStream) -> Result<Self> {
        fn parse_last(input: ParseStream, start: u32) -> Result<u32> {
            if input.parse::<Token![..=]>().is_ok() {
                let lit = input.parse::<LitInt>()?;
                let n: u32 = lit.base10_parse()?;
                if n >= start {
                    Ok(n)
                } else {
                    Err(Error::new(lit.span(), format!("expected value >= {start}")))
                }
            } else {
                Ok(start)
            }
        }

        let inner;
        let _ = parenthesized!(inner in input);

        let col = inner.parse::<LitInt>()?.base10_parse()?;
        let last_col = parse_last(&inner, col)?;

        let _ = inner.parse::<Token![,]>()?;

        let row = inner.parse::<LitInt>()?.base10_parse()?;
        let last_row = parse_last(&inner, row)?;

        Ok(CellInfo {
            row,
            last_row,
            col,
            last_col,
        })
    }
}

impl ToTokens for CellInfo {
    fn to_tokens(&self, toks: &mut Toks) {
        let (col, last_col) = (self.col, self.last_col);
        let (row, last_row) = (self.row, self.last_row);
        toks.append_all(quote! {
            ::kas::layout::GridCellInfo {
                col: #col,
                last_col: #last_col,
                row: #row,
                last_row: #last_row,
            }
        });
    }
}

#[derive(Debug, Default)]
pub struct GridDimensions {
    pub cols: u32,
    col_spans: u32,
    pub rows: u32,
    row_spans: u32,
}

impl GridDimensions {
    pub fn update(&mut self, cell: &CellInfo) {
        self.cols = self.cols.max(cell.last_col + 1);
        if cell.last_col > cell.col {
            self.col_spans += 1;
        }
        self.rows = self.rows.max(cell.last_row + 1);
        if cell.last_row > cell.row {
            self.row_spans += 1;
        }
    }
}

impl ToTokens for GridDimensions {
    fn to_tokens(&self, toks: &mut Toks) {
        let (cols, rows) = (self.cols, self.rows);
        let (col_spans, row_spans) = (self.col_spans, self.row_spans);
        toks.append_all(quote! { ::kas::layout::GridDimensions {
            cols: #cols,
            col_spans: #col_spans,
            rows: #rows,
            row_spans: #row_spans,
        } });
    }
}

pub enum Item {
    Label(Ident, Toks, Toks),
    Widget(Ident, Expr),
}

impl Item {
    fn parse(input: ParseStream, names: &mut NameGenerator) -> Result<Self> {
        if input.peek(LitStr) {
            let text: LitStr = input.parse()?;
            let mut ty = quote! { ::kas::widgets::Label<&'static str> };
            let mut def = quote! { ::kas::widgets::Label::new(#text) };

            if input.peek(Token![.]) && input.peek2(kw::align) {
                let _: Token![.] = input.parse()?;
                let _: kw::align = input.parse()?;

                let inner;
                let _ = parenthesized!(inner in input);
                let hints: Expr = inner.parse()?;

                ty = quote! { ::kas::widgets::adapt::Align<#ty> };
                def = quote! { ::kas::widgets::adapt::Align::new(#def, #hints) };
            } else if input.peek(Token![.]) && input.peek2(kw::pack) {
                let _: Token![.] = input.parse()?;
                let _: kw::pack = input.parse()?;

                let inner;
                let _ = parenthesized!(inner in input);
                let hints: Expr = inner.parse()?;

                ty = quote! { ::kas::widgets::adapt::Pack<#ty> };
                def = quote! { ::kas::widgets::adapt::Pack::new(#def, #hints) };
            } else if input.peek(Token![.]) && input.peek2(kw::with_stretch) {
                let _: Token![.] = input.parse()?;
                let _: kw::with_stretch = input.parse()?;

                let inner;
                let _ = parenthesized!(inner in input);
                let horiz: Expr = inner.parse()?;
                let _: Token![,] = input.parse()?;
                let vert: Expr = inner.parse()?;

                ty = quote! { ::kas::widgets::adapt::WithStretch<#ty> };
                def = quote! { ::kas::widgets::adapt::WithStretch::new(#def, #horiz, #vert) };
            }

            Ok(Item::Label(names.next(), ty, def))
        } else {
            Ok(Item::Widget(names.next(), input.parse()?))
        }
    }
}

impl Parser for Item {
    type Output = Self;

    fn parse(input: ParseStream, core_gen: &mut NameGenerator) -> Result<Self::Output> {
        Item::parse(input, core_gen)
    }
}

pub struct Collection(Vec<Item>);
pub struct CellCollection(Vec<CellInfo>, Collection);

impl Parse for Collection {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut names = NameGenerator::default();
        let items = parse_list::<Item>(input, &mut names)?;
        Ok(Collection(items))
    }
}

impl Parse for CellCollection {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut names = NameGenerator::default();
        let (_, infos, items) = parse_grid::<Item>(input, &mut names)?;
        Ok(CellCollection(infos, Collection(items)))
    }
}

impl Collection {
    pub fn impl_parts(&self) -> (Toks, Toks, Toks, Toks, Toks) {
        let mut data_ty = None;
        for (index, item) in self.0.iter().enumerate() {
            if let Item::Widget(_, expr) = item {
                let ty = Ident::new(&format!("_W{index}"), expr.span());
                data_ty = Some(quote! {<#ty as ::kas::Widget>::Data});
                break;
            }
        }

        let len = self.0.len();
        let is_empty = match len {
            0 => quote! { true },
            _ => quote! { false },
        };

        let mut ty_generics = Punctuated::<Ident, Comma>::new();
        let mut stor_ty = quote! {};
        let mut stor_def = quote! {};

        let mut get_tile_rules = quote! {};
        let mut get_mut_tile_rules = quote! {};
        let mut for_node_rules = quote! {};

        for (index, item) in self.0.iter().enumerate() {
            let path = match item {
                Item::Label(stor, ty, def) => {
                    if let Some(ref data_ty) = data_ty {
                        stor_ty.append_all(
                            quote! { #stor: ::kas::widgets::adapt::MapAny<#data_ty, #ty>, },
                        );
                        stor_def.append_all(
                            quote! { #stor: ::kas::widgets::adapt::MapAny::new(#def), },
                        );
                    } else {
                        stor_ty.append_all(quote! { #stor: #ty, });
                        stor_def.append_all(quote! { #stor: #def, });
                    }
                    stor.to_token_stream()
                }
                Item::Widget(stor, expr) => {
                    let span = expr.span();
                    let ty = Ident::new(&format!("_W{index}"), span);
                    stor_ty.append_all(quote! { #stor: #ty, });
                    stor_def.append_all(quote! { #stor: Box::new(#expr), });
                    ty_generics.push(ty);

                    stor.to_token_stream()
                }
            };

            get_tile_rules.append_all(quote! {
                #index => Some(&self.#path),
            });
            get_mut_tile_rules.append_all(quote! {
                #index => Some(&mut self.#path),
            });
            for_node_rules.append_all(quote! {
                #index => Some(self.#path.as_node(data)),
            });
        }

        let data_ty = data_ty
            .map(|ty| quote! { #ty })
            .unwrap_or_else(|| quote! { () });

        let (impl_generics, ty_generics) = if ty_generics.is_empty() {
            (quote! {}, quote! {})
        } else {
            let mut toks = quote! {};
            let mut iter = ty_generics.iter();
            if let Some(ty) = iter.next() {
                toks = quote! { #ty: ::kas::Widget, }
            }
            for ty in iter {
                toks.append_all(quote!(
                    #ty: ::kas::Widget<Data = #data_ty>,
                ));
            }
            (quote! { <#toks> }, quote! { <#ty_generics> })
        };

        let collection = quote! {
            type Data = #data_ty;

            fn is_empty(&self) -> bool { #is_empty }
            fn len(&self) -> usize { #len }

            fn get_tile(&self, index: usize) -> Option<&dyn ::kas::Tile> {
                match index {
                    #get_tile_rules
                    _ => None,
                }
            }
            fn get_mut_tile(&mut self, index: usize) -> Option<&mut dyn ::kas::Tile> {
                match index {
                    #get_mut_tile_rules
                    _ => None,
                }
            }
            #[inline]
            fn child_node<'__n>(
                &'__n mut self,
                data: &'__n Self::Data,
                index: usize,
            ) -> Option<::kas::Node<'__n>> {
                use ::kas::Widget;
                match index {
                    #for_node_rules
                    _ => None,
                }
            }
        };

        (impl_generics, ty_generics, stor_ty, stor_def, collection)
    }

    pub fn expand(&self) -> Toks {
        let name = Ident::new("_Collection", Span::call_site());
        let (impl_generics, ty_generics, stor_ty, stor_def, collection) = self.impl_parts();

        let toks = quote! {{
            struct #name #impl_generics {
                #stor_ty
            }

            impl #impl_generics ::kas::Collection for #name #ty_generics {
                #collection
            }

            #name {
                #stor_def
            }
        }};
        // println!("{}", toks);
        toks
    }
}

impl CellCollection {
    pub fn expand(&self) -> Toks {
        let name = Ident::new("_Collection", Span::call_site());
        let (impl_generics, ty_generics, stor_ty, stor_def, collection) = self.1.impl_parts();

        let mut cell_info_rules = quote! {};
        let mut dim = GridDimensions::default();
        for (index, cell) in self.0.iter().enumerate() {
            cell_info_rules.append_all(quote! {
                #index => Some(#cell),
            });
            dim.update(cell);
        }

        let toks = quote! {{
            struct #name #impl_generics {
                #stor_ty
            }

            impl #impl_generics ::kas::Collection for #name #ty_generics {
                #collection
            }

            impl #impl_generics ::kas::CellCollection for #name #ty_generics {
                fn cell_info(&self, index: usize) -> Option<::kas::layout::GridCellInfo> {
                    match index {
                        #cell_info_rules
                        _ => None,
                    }
                }

                fn grid_dimensions(&self) -> ::kas::layout::GridDimensions {
                    #dim
                }
            }

            #name {
                #stor_def
            }
        }};
        // println!("{}", toks);
        toks
    }
}