bern-syntax 0.1.2

Shared parser for Bern declarations, used by the macros and the build tool
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
//! `style!`: the application's style overrides and motion tokens.
//!
//! ```text
//! style! {
//!     motion {
//!         jelly: spring(period: 0.42, damping: 0.42),
//!     }
//!     SidebarItem {
//!         corner: 8,
//!         hover: scale(1.03, snappy),
//!         selected: fill(accent),
//!     }
//!     Button.hero { size: large }
//!     #[target(macos)]
//!     SidebarItem { selected: system }
//! }
//! ```
//!
//! This module only reads the declaration; what each property means and
//! where it applies is checked by the build tool.

use proc_macro2::{Span, TokenStream};
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::{Ident, LitFloat, LitInt, LitStr, Token, braced, parenthesized};

#[derive(Clone, Debug)]
pub struct StyleItem {
    pub motion: Vec<MotionDecl>,
    /// `transition { name: pop(from: 0.4, jelly) }`.
    pub transitions: Vec<MotionDecl>,
    /// `pattern { name: check(band(accent, 1, 0.28), gap(6), …) }`.
    pub patterns: Vec<MotionDecl>,
    /// `accents { crimson: "#FF2E55" }`: accent colors the application
    /// chooses among at run time.
    pub accents: Vec<MotionDecl>,
    /// `text { large_title: heavy }`: the weight of a text style.
    pub text: Vec<MotionDecl>,
    /// `corner { card: 22 }`: named corner radii; a block with
    /// `#[target(…)]` gives other values on those platforms.
    pub corners: Vec<CornerBlock>,
    pub rules: Vec<StyleRuleItem>,
    pub span: Span,
}

/// `name: spring(period: T, damping: ζ)`.
#[derive(Clone, Debug)]
pub struct MotionDecl {
    pub name: Ident,
    pub value: StyleValue,
}

/// A `corner { name: radius }` block, for every platform or, with
/// `#[target(…)]`, for those named.
#[derive(Clone, Debug)]
pub struct CornerBlock {
    pub targets: Vec<Ident>,
    pub corners: Vec<MotionDecl>,
    pub span: Span,
}

/// `Component` or `Component.variant`, with its properties.
#[derive(Clone, Debug)]
pub struct StyleRuleItem {
    pub component: Ident,
    pub variant: Option<Ident>,
    /// `#[target(macos, ios)]`: the platforms the rule applies to; empty
    /// for all.
    pub targets: Vec<Ident>,
    /// `#[exempt(gtk, "reason")]`: platforms that keep their default for
    /// what they cannot show.
    pub exempt: Vec<(Ident, String)>,
    pub props: Vec<StyleProp>,
    pub span: Span,
}

#[derive(Clone, Debug)]
pub struct StyleProp {
    pub name: Ident,
    pub value: StyleValue,
}

/// A property value: a number, a name such as `accent` or `fill.subtle`,
/// text, a call such as `scale(1.03, snappy)`, or effects joined by `+`.
#[derive(Clone, Debug)]
pub enum StyleValue {
    Number(f64, Span),
    Name(Vec<Ident>),
    Text(String, Span),
    Call { name: Ident, args: Vec<StyleArg> },
    Sum(Vec<StyleValue>),
}

#[derive(Clone, Debug)]
pub struct StyleArg {
    pub name: Option<Ident>,
    pub value: StyleValue,
}

impl StyleValue {
    pub fn span(&self) -> Span {
        match self {
            StyleValue::Number(_, span) | StyleValue::Text(_, span) => *span,
            StyleValue::Name(path) => path[0].span(),
            StyleValue::Call { name, .. } => name.span(),
            StyleValue::Sum(parts) => parts[0].span(),
        }
    }

    /// `a.b` for a name.
    pub fn dotted(&self) -> Option<String> {
        match self {
            StyleValue::Name(path) => Some(
                path.iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>()
                    .join("."),
            ),
            _ => None,
        }
    }

    /// The parts of a sum, or the value alone.
    pub fn terms(&self) -> Vec<&StyleValue> {
        match self {
            StyleValue::Sum(parts) => parts.iter().collect(),
            other => vec![other],
        }
    }
}

impl Parse for StyleItem {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let span = input.span();
        let mut motion = Vec::new();
        let mut transitions = Vec::new();
        let mut patterns = Vec::new();
        let mut accents = Vec::new();
        let mut text = Vec::new();
        let mut corners = Vec::new();
        let mut rules = Vec::new();
        while !input.is_empty() {
            let attrs = input.call(syn::Attribute::parse_outer)?;
            let component: Ident = input.parse()?;
            if component == "corner" && input.peek(syn::token::Brace) {
                let mut targets = Vec::new();
                for attr in &attrs {
                    if !attr.path().is_ident("target") {
                        return Err(syn::Error::new(
                            attr.span(),
                            "a `corner` block takes only `#[target(…)]`",
                        ));
                    }
                    let list = attr.parse_args_with(
                        syn::punctuated::Punctuated::<Ident, Token![,]>::parse_terminated,
                    )?;
                    targets.extend(list);
                }
                let content;
                braced!(content in input);
                let mut list = Vec::new();
                while !content.is_empty() {
                    let name: Ident = content.parse()?;
                    content.parse::<Token![:]>()?;
                    let value: StyleValue = content.parse()?;
                    list.push(MotionDecl { name, value });
                    if !content.is_empty() {
                        content.parse::<Token![,]>()?;
                    }
                }
                corners.push(CornerBlock {
                    targets,
                    corners: list,
                    span: component.span(),
                });
                continue;
            }
            if (component == "motion"
                || component == "transition"
                || component == "pattern"
                || component == "accents"
                || component == "text")
                && attrs.is_empty()
                && input.peek(syn::token::Brace)
            {
                let content;
                braced!(content in input);
                let list = if component == "motion" {
                    &mut motion
                } else if component == "transition" {
                    &mut transitions
                } else if component == "accents" {
                    &mut accents
                } else if component == "text" {
                    &mut text
                } else {
                    &mut patterns
                };
                while !content.is_empty() {
                    let name: Ident = content.parse()?;
                    content.parse::<Token![:]>()?;
                    let value: StyleValue = content.parse()?;
                    list.push(MotionDecl { name, value });
                    if !content.is_empty() {
                        content.parse::<Token![,]>()?;
                    }
                }
                continue;
            }
            let variant = if input.peek(Token![.]) {
                input.parse::<Token![.]>()?;
                Some(input.parse()?)
            } else {
                None
            };
            let mut targets = Vec::new();
            let mut exempt = Vec::new();
            for attr in &attrs {
                if attr.path().is_ident("target") {
                    let list = attr.parse_args_with(
                        syn::punctuated::Punctuated::<Ident, Token![,]>::parse_terminated,
                    )?;
                    targets.extend(list);
                } else if attr.path().is_ident("exempt") {
                    attr.parse_args_with(|input: ParseStream| {
                        let target: Ident = input.parse()?;
                        input.parse::<Token![,]>()?;
                        let reason: LitStr = input.parse()?;
                        exempt.push((target, reason.value()));
                        Ok(())
                    })?;
                } else {
                    return Err(syn::Error::new(
                        attr.span(),
                        "style rules take `#[target(…)]` and `#[exempt(target, \"reason\")]`",
                    ));
                }
            }
            let content;
            braced!(content in input);
            let mut props = Vec::new();
            while !content.is_empty() {
                let name: Ident = content.parse()?;
                content.parse::<Token![:]>()?;
                let value: StyleValue = content.parse()?;
                props.push(StyleProp { name, value });
                if !content.is_empty() {
                    content.parse::<Token![,]>()?;
                }
            }
            rules.push(StyleRuleItem {
                span: component.span(),
                component,
                variant,
                targets,
                exempt,
                props,
            });
        }
        Ok(StyleItem {
            motion,
            transitions,
            patterns,
            accents,
            text,
            corners,
            rules,
            span,
        })
    }
}

impl Parse for StyleValue {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut parts = vec![term(input)?];
        while input.peek(Token![+]) {
            input.parse::<Token![+]>()?;
            parts.push(term(input)?);
        }
        Ok(if parts.len() == 1 {
            parts.pop().unwrap()
        } else {
            StyleValue::Sum(parts)
        })
    }
}

fn number(input: ParseStream, negative: bool) -> syn::Result<StyleValue> {
    let sign = if negative { -1.0 } else { 1.0 };
    if input.peek(LitFloat) {
        let lit: LitFloat = input.parse()?;
        Ok(StyleValue::Number(
            sign * crate::finite(lit.base10_parse()?, lit.span())?,
            lit.span(),
        ))
    } else {
        let lit: LitInt = input.parse()?;
        Ok(StyleValue::Number(
            sign * crate::finite(lit.base10_parse()?, lit.span())?,
            lit.span(),
        ))
    }
}

fn term(input: ParseStream) -> syn::Result<StyleValue> {
    if input.peek(Token![-]) {
        input.parse::<Token![-]>()?;
        return number(input, true);
    }
    if input.peek(LitFloat) || input.peek(LitInt) {
        return number(input, false);
    }
    if input.peek(LitStr) {
        let lit: LitStr = input.parse()?;
        return Ok(StyleValue::Text(lit.value(), lit.span()));
    }
    // Any word, so `twill: true` reads as a name.
    let name: Ident = input.call(Ident::parse_any)?;
    if input.peek(syn::token::Paren) {
        let content;
        parenthesized!(content in input);
        let mut args = Vec::new();
        while !content.is_empty() {
            let named = content.peek(Ident) && content.peek2(Token![:]);
            let name = if named {
                let name: Ident = content.parse()?;
                content.parse::<Token![:]>()?;
                Some(name)
            } else {
                None
            };
            let value: StyleValue = content.parse()?;
            args.push(StyleArg { name, value });
            if !content.is_empty() {
                content.parse::<Token![,]>()?;
            }
        }
        return Ok(StyleValue::Call { name, args });
    }
    let mut path = vec![name];
    while input.peek(Token![.]) {
        input.parse::<Token![.]>()?;
        path.push(input.parse()?);
    }
    Ok(StyleValue::Name(path))
}

/// Parse the body of a `style!` invocation.
pub fn parse_style(tokens: TokenStream) -> syn::Result<StyleItem> {
    syn::parse2(tokens)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_style_reads_rules_motion_and_attributes() {
        let style = parse_style(quote::quote! {
            motion {
                jelly: spring(period: 0.42, damping: 0.42),
            }
            SidebarItem {
                corner: 8,
                hover: scale(1.03, snappy),
                selected: fill(accent),
            }
            IconButton {
                hover: background(fill.subtle) + scale(1.08, snappy),
            }
            #[target(macos)]
            #[exempt(gtk, "no transforms on rows")]
            Button.hero { size: large, pressed: scale(x: 0.97, y: 0.9, press) }
        })
        .unwrap();
        assert_eq!(style.motion.len(), 1);
        assert_eq!(style.motion[0].name, "jelly");
        assert_eq!(style.rules.len(), 3);
        let icon = &style.rules[1];
        let StyleValue::Sum(parts) = &icon.props[0].value else {
            panic!("a sum")
        };
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0].clone().terms().len(), 1);
        let hero = &style.rules[2];
        assert_eq!(hero.variant.as_ref().unwrap(), "hero");
        assert_eq!(hero.targets[0], "macos");
        assert_eq!(hero.exempt[0].1, "no transforms on rows");
        let StyleValue::Call { args, .. } = &hero.props[1].value else {
            panic!("a call")
        };
        assert_eq!(args[0].name.as_ref().unwrap(), "x");
        assert!(matches!(args[2].value, StyleValue::Name(_)));
        assert!(parse_style(quote::quote! { Button { corner } }).is_err());
    }

    #[test]
    fn numbers_out_of_range_for_f64_are_rejected() {
        for tokens in [
            quote::quote! { Button { corner: 1e999 } },
            quote::quote! { Button { hover: scale(-1e999, snappy) } },
        ] {
            let error = parse_style(tokens).unwrap_err().to_string();
            assert!(error.contains("out of range for f64"), "{error}");
        }
    }
}