Skip to main content

teksilo_parse/
ir.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Intermediate representation for the `teksu!` DSL.
5//!
6//! The parser builds an IR tree; the lowering walks the tree and emits
7//! the final builder-call token stream. Keeping parse and lower separate
8//! keeps span handling predictable: each IR node carries the span of the
9//! user token it originated from.
10
11use proc_macro2::Span;
12use syn::{Block, Expr, Ident, Local, Pat, Path};
13
14/// The root of a `teksu!` invocation.
15pub struct TeksiRoot {
16    /// If `Some(ident)`, the macro was called as `teksu!(ident => ...)`
17    /// and expansion should wrap the root in `ident.add(...)` to return
18    /// a `WidgetId`. If `None`, expansion returns the widget value
19    /// directly.
20    pub ctx: Option<Ident>,
21    pub root: TeksiElement,
22}
23
24/// An element: `Type[::ctor](args...) { body }`.
25pub struct TeksiElement {
26    /// The full callable path the user wrote. `Button("x")` stores
27    /// `Button`; `Button::new(lit!("x"))` stores the whole
28    /// `Button::new_literal` path. Lowering appends `::new` only when
29    /// `has_explicit_ctor` is false.
30    pub type_path: Path,
31    /// True when the user named a constructor explicitly (a lowercase
32    /// last path segment, per Rust naming convention). Lowering then
33    /// calls the path as-is without appending `::new`.
34    pub has_explicit_ctor: bool,
35    /// Positional arguments between the parens after the type path.
36    /// Empty when the user wrote `VStack` with no parens (equivalent to
37    /// `VStack()`).
38    pub args: Vec<Expr>,
39    /// Body items in source order.
40    pub body: Vec<BodyItem>,
41    /// Span of the type path's first segment — used for error reporting
42    /// on constructor typos.
43    pub head_span: Span,
44    /// Span of the closing `)` after the args, if the user wrote any
45    /// args parens (including empty `()`). `None` when no arg parens
46    /// were written. Consumers (e.g. the formatter) use this to find
47    /// the exact byte offset just past the args.
48    pub args_close: Option<Span>,
49    /// Span of the closing `}` of the body, if the user wrote any body
50    /// braces (including empty `{}`). `None` when no body braces were
51    /// written. Consumers use this to find the exact end of the body
52    /// for trivia attribution.
53    pub body_close: Option<Span>,
54}
55
56/// One item in an element's body block.
57#[allow(clippy::large_enum_variant)]
58pub enum BodyItem {
59    /// `name: arg1, arg2, ...` — builder method call with N args.
60    /// A bare lowercase ident with no body is modeled as `args == []`.
61    Property(TeksiProperty),
62    /// A bare element at body position — attaches via `.child(...)`.
63    Child(TeksiElement),
64    /// A bare Rust *expression* at body position that evaluates to a
65    /// widget — the `section("Header")` / `row(x).bold()` helper-call
66    /// shape. Attaches via `.child(expr)`. Distinct from `Child`, which
67    /// is a teksu element the macro constructs itself.
68    ExprChild { expr: Expr, span: Span },
69    /// `name = Element` — a binding that hoists `let name = ctx.add(...)`
70    /// to the enclosing statement-forming block, then attaches via
71    /// `.child(name)` on the parent.
72    Binding { name: Ident, element: TeksiElement },
73    /// `#{ expr }` at body position — attaches via `.child(expr)`. `child`
74    /// takes `impl IntoTeksiChild`, so the expr may be a `WidgetId` or a
75    /// widget value.
76    Escape { expr: Expr, span: Span },
77    /// `let pat = expr;` at body position. Introduces a
78    /// local whose value is used by subsequent body items. Triggers
79    /// statement-sequence lowering on the enclosing element.
80    Let(Local),
81    /// `rust { ... }` imperative escape. Two forms:
82    /// expression-producing (block tail has no semicolon, lowered as
83    /// `.child(block)`) and side-effect (block tail ends in `;`,
84    /// emitted inline as a side-effect statement).
85    Rust {
86        block: Block,
87        span: Span,
88        shape: RustShape,
89    },
90    /// `if cond { Element } [else if cond { Element }]* [else { Element }]?`
91    /// Lowers to `.child_opt(...)` (no-else) or
92    /// `.child(TeksiBranch{N}::...)` (with else branches).
93    If(TeksiIf),
94    /// `match expr { pat => Element, ... }`. Lowers to
95    /// `.child(match ... { ... TeksiBranch{N}::... })` with arms
96    /// dispatched by variant index.
97    Match(TeksiMatch),
98    /// `for pat in iter { Element }`. Lowers to
99    /// `.children(iter.map(|pat| Element))`.
100    For(TeksiFor),
101    /// `..expr` — inlines an iterator of `WidgetId`s as
102    /// children. Forces statement-sequence lowering on the parent.
103    Spread { expr: Expr, span: Span },
104}
105
106pub struct TeksiIf {
107    pub cond: Expr,
108    pub then: TeksiElement,
109    pub else_branch: Option<Box<TeksiElse>>,
110    pub span: Span,
111    /// Span of the `}` that closes this if's `then` block. Held by every
112    /// `TeksiIf` (including else-if recursion) so consumers can compute
113    /// the rightmost byte of an if-chain. Inner `TeksiElement`s carry no
114    /// braces of their own — the structural form owns them.
115    pub body_close: Span,
116}
117
118#[allow(clippy::large_enum_variant)]
119pub enum TeksiElse {
120    ElseIf(TeksiIf),
121    Element {
122        element: TeksiElement,
123        /// Span of the `}` that closes the trailing `else { ... }` block.
124        body_close: Span,
125    },
126}
127
128pub struct TeksiMatch {
129    pub scrutinee: Expr,
130    pub arms: Vec<TeksiMatchArm>,
131    pub span: Span,
132    /// Span of the `}` that closes the match block.
133    pub body_close: Span,
134}
135
136pub struct TeksiMatchArm {
137    pub pat: Pat,
138    pub guard: Option<(syn::Token![if], Expr)>,
139    pub element: TeksiElement,
140}
141
142pub struct TeksiFor {
143    pub pat: Pat,
144    pub iter: Expr,
145    pub lets: Vec<Local>,
146    pub element: TeksiElement,
147    pub span: Span,
148    /// Span of the `}` that closes the for block.
149    pub body_close: Span,
150}
151
152#[derive(Clone, Copy, PartialEq, Eq)]
153pub enum RustShape {
154    /// Block's last statement is an expression without trailing `;` —
155    /// the block's value becomes a child via `.child(block)`.
156    Expression,
157    /// Block has a unit tail (last statement ends in `;` or is a
158    /// `Stmt::Semi`) — emitted as a side-effect statement.
159    SideEffect,
160}
161
162pub struct TeksiProperty {
163    pub name: Ident,
164    pub args: Vec<PropArg>,
165}
166
167/// A property argument. `Expr` and `Element` both emit `.prop_name(...)`;
168/// `Escape` and `Binding` force the `_id` slot suffix per spec §A.3 and
169/// hoist the binding when present.
170pub enum PropArg {
171    /// A plain Rust expression (scalars, closures, method calls).
172    Expr(Expr),
173    /// An embedded teksu element — `tab: "name", Card { ... }`.
174    Element(TeksiElement),
175    /// `#{ expr }` — a WidgetId expression that routes to `.prop_id`.
176    Escape(Expr),
177    /// `name = Element` — hoists `let name = ctx.add(...)` and routes
178    /// to `.prop_id(name)`.
179    Binding { name: Ident, element: TeksiElement },
180}