graphcal-compiler 0.0.1-alpha.14

Type-safe, unit-aware, Git-friendly reactive programming language for engineering calculations
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
use crate::syntax::ast::{
    Attribute, AttributeArg, BindableVisibility, DeclKind, Declaration, Visibility,
};
use crate::syntax::non_empty::NonEmpty;
use crate::syntax::span::Span;
use crate::syntax::token::Token;

use super::{ParseError, Parser};
use multi::SlotKind;

mod dag;
mod dim_unit;
mod figure;
mod import;
mod index;
mod layer;
mod multi;
mod plot;
#[cfg(test)]
mod tests;
mod type_decl;
mod value;

const fn visibility_without_bindability(visibility: BindableVisibility) -> Visibility {
    match visibility {
        BindableVisibility::Private => Visibility::Private,
        BindableVisibility::Public | BindableVisibility::PublicBind => Visibility::Public,
    }
}

const fn decl_accepts_bindable_visibility(decl: &Declaration) -> bool {
    matches!(
        decl.kind,
        DeclKind::Dimension(_) | DeclKind::Type(_) | DeclKind::Index(_)
    )
}

const fn set_decl_visibility(decl: &mut Declaration, visibility: BindableVisibility) {
    match &mut decl.kind {
        DeclKind::Param(_) | DeclKind::Sugar(_) => {}
        DeclKind::Node(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::ConstNode(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::BaseDimension(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Dimension(d) => d.visibility = visibility,
        DeclKind::Unit(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Type(d) => d.visibility = visibility,
        DeclKind::Index(d) => d.visibility = visibility,
        DeclKind::Import(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Include(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Dag(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Assert(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Plot(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Figure(d) => d.visibility = visibility_without_bindability(visibility),
        DeclKind::Layer(d) => d.visibility = visibility_without_bindability(visibility),
    }
}

impl Parser<'_> {
    /// Parse one top-level declaration surface form. A multi-decl is
    /// represented as `DeclKind::Multi(MultiDecl)` and expanded later
    /// by the desugar pass.
    #[expect(
        clippy::too_many_lines,
        reason = "single entry point dispatches across every declaration kind"
    )]
    pub(super) fn parse_declaration(&mut self) -> Result<Declaration, ParseError> {
        // Collect any leading attributes: #[name] or #[name(arg1, arg2)]
        let mut attributes = Vec::new();
        while self.lexer.peek() == Some(&Token::Hash) {
            attributes.push(self.parse_attribute()?);
        }

        // Optional `pub` or `pub(bind)` visibility modifier.
        let (visibility, visibility_span) = self.parse_visibility_prefix()?;

        // Reject `pub` / `pub(bind)` on `param` at parse time. The spec
        // (visibility-bindability axioms §4.0) says `param` is
        // annotation-free: it is inherently visible + bindable, and any
        // annotation conveys no information. Catching this here keeps
        // the grammar surface itself compliant without deferring to the
        // resolver.
        let found = match visibility {
            BindableVisibility::Private => None,
            BindableVisibility::Public => Some("`pub`"),
            BindableVisibility::PublicBind => Some("`pub(bind)`"),
        };
        if let Some(found) = found
            && self.lexer.peek() == Some(&Token::Param)
            && let Some(vis_span) = visibility_span
        {
            return Err(self.unexpected_token(
                "no visibility annotation (params are always visible and bindable)",
                found,
                vis_span,
            ));
        }

        // Reject `pub(bind)` on `import` / `include`. Use-sites are not
        // bindable (A5: B ≡ fixed). `pub` is legal as a re-export marker
        // per issue #452.
        if visibility == BindableVisibility::PublicBind
            && matches!(self.lexer.peek(), Some(Token::Import | Token::Include))
            && let Some(vis_span) = visibility_span
        {
            return Err(self.unexpected_token(
                "`pub` (use-sites are not bindable — `pub(bind)` is only for declaration kinds)",
                "`pub(bind)`",
                vis_span,
            ));
        }

        // Reject `pub(bind)` on `node` / `const node`. Nodes are computed
        // values, not a bindable surface; `param` already plays that role.
        // `pub` on `node` is legal and controls projection visibility from
        // inline-dag call sites.
        let is_node_decl = match self.lexer.peek() {
            Some(Token::Node) => true,
            Some(Token::Const) => matches!(self.lexer.peek_second(), Some(Token::Node)),
            _ => false,
        };
        if visibility == BindableVisibility::PublicBind
            && is_node_decl
            && let Some(vis_span) = visibility_span
        {
            return Err(self.unexpected_token(
                "`pub` (nodes are computed values — `pub(bind)` is not meaningful; use `param` to declare a bindable input)",
                "`pub(bind)`",
                vis_span,
            ));
        }

        let expected = "`param`, `node`, `const node`, `base dim`, `dim`, `unit`, `const unit`, `type`, `dag`, `index`, `import`, `include`, `assert`, `plot`, `figure`, or `layer`";

        // Value-declaration paths (`param`, `node`, `const node`) can be
        // either a single declaration or a multi-decl (issue #481). We
        // consume the kind keyword(s), parse the slot header, then peek
        // at the next token to decide.
        match self.lexer.peek() {
            Some(Token::Param) => {
                let (_, kind_span) = self.advance()?;
                return self.finish_value_decl_or_multi(
                    SlotKind::Param,
                    kind_span,
                    attributes,
                    visibility,
                    visibility_span,
                );
            }
            Some(Token::Node) => {
                let (_, kind_span) = self.advance()?;
                return self.finish_value_decl_or_multi(
                    SlotKind::Node,
                    kind_span,
                    attributes,
                    visibility,
                    visibility_span,
                );
            }
            Some(Token::Const) => {
                let (_, const_span) = self.advance()?;
                match self.lexer.peek() {
                    Some(Token::Node) => {
                        let (_, node_span) = self.advance()?;
                        return self.finish_value_decl_or_multi(
                            SlotKind::ConstNode,
                            const_span.merge(node_span),
                            attributes,
                            visibility,
                            visibility_span,
                        );
                    }
                    Some(Token::Unit) => {
                        // `const unit`: single declaration only (no multi-decl sugar).
                        let mut decl = self.parse_const_unit(const_span)?;
                        if visibility == BindableVisibility::PublicBind
                            && let Some(vis_span) = visibility_span
                        {
                            return Err(self.unexpected_token(
                                "`pub` (`pub(bind)` is only valid on bindable declaration kinds: `dim`, `type`, and `index`)",
                                "`pub(bind)`",
                                vis_span,
                            ));
                        }
                        set_decl_visibility(&mut decl, visibility);
                        if let Some(ps) = visibility_span {
                            decl.span = ps.merge(decl.span);
                        }
                        if let Some(first_attr) = attributes.first() {
                            decl.span = first_attr.span.merge(decl.span);
                        }
                        decl.attributes = attributes;
                        return Ok(decl);
                    }
                    Some(_) => {
                        let (tok, span) = self.advance()?;
                        return Err(self.unexpected_token(
                            "`node` or `unit` after `const`",
                            &tok.to_string(),
                            span,
                        ));
                    }
                    None => {
                        return Err(self.unexpected_eof("`node` or `unit` after `const`"));
                    }
                }
            }
            _ => {}
        }

        let mut decl = match self.lexer.peek() {
            Some(Token::Base) => {
                let (_, base_span) = self.advance()?;
                match self.lexer.peek() {
                    Some(Token::Dimension) => self.parse_base_dimension_decl(base_span),
                    Some(Token::Unit) => self.parse_base_unit_decl(base_span),
                    Some(_) => {
                        let (tok, span) = self.advance()?;
                        Err(self.unexpected_token(
                            "`dim` or `unit` after `base`",
                            &tok.to_string(),
                            span,
                        ))
                    }
                    None => Err(self.unexpected_eof("`dim` or `unit` after `base`")),
                }
            }
            Some(Token::Dimension) => self.parse_dimension_decl(),
            Some(Token::Unit) => self.parse_unit_decl(),
            Some(Token::Type) => self.parse_type_decl(),
            Some(Token::Index) => self.parse_index_decl(),
            Some(Token::Import) => self.parse_import_decl(),
            Some(Token::Include) => self.parse_include_decl(),
            Some(Token::Dag) => self.parse_dag_decl(),
            Some(Token::Assert) => self.parse_assert(),
            Some(Token::Plot) => self.parse_plot(),
            Some(Token::Figure) => self.parse_figure(),
            Some(Token::Layer) => self.parse_layer(),
            Some(_) => {
                let (tok, span) = self.advance()?;
                Err(self.unexpected_token(expected, &tok.to_string(), span))
            }
            None => Err(self.unexpected_eof(expected)),
        }?;

        // Set visibility
        if visibility == BindableVisibility::PublicBind
            && !decl_accepts_bindable_visibility(&decl)
            && let Some(vis_span) = visibility_span
        {
            return Err(self.unexpected_token(
                "`pub` (`pub(bind)` is only valid on bindable declaration kinds: `dim`, `type`, and `index`)",
                "`pub(bind)`",
                vis_span,
            ));
        }
        set_decl_visibility(&mut decl, visibility);

        // Mutual exclusion for re-exports (issue #452 / spec §4.1):
        // `pub import "X" { pub items };` mixes whole-module and selective
        // re-export forms. Reject at parse so the semantics of a single
        // re-export construct stays unambiguous.
        if visibility == BindableVisibility::Public
            && let Some(vis_span) = visibility_span
        {
            let selective_items = match &decl.kind {
                DeclKind::Import(d) => match &d.kind {
                    crate::syntax::ast::ImportKind::Selective(items) => Some(items.as_slice()),
                    crate::syntax::ast::ImportKind::Module { .. } => None,
                },
                DeclKind::Include(d) => match &d.kind {
                    crate::syntax::ast::ImportKind::Selective(items) => Some(items.as_slice()),
                    crate::syntax::ast::ImportKind::Module { .. } => None,
                },
                _ => None,
            };
            if let Some(items) = selective_items
                && items.iter().any(|it| it.is_pub)
            {
                return Err(self.unexpected_token(
                    "either `pub include/import \"X\" ...` (whole-module re-export) or `include/import \"X\" { pub items }` (selective re-export), not both",
                    "`pub`",
                    vis_span,
                ));
            }
        }

        // Extend the declaration span to include `pub` / `pub(bind)` prefix
        if let Some(ps) = visibility_span {
            decl.span = ps.merge(decl.span);
        }

        // Extend the declaration span to include the attributes
        if let Some(first_attr) = attributes.first() {
            decl.span = first_attr.span.merge(decl.span);
        }

        decl.attributes = attributes;

        Ok(decl)
    }

    /// Complete parsing of a `param` / `node` / `const node` declaration
    /// starting from after the kind keyword, dispatching to either the
    /// single-decl path or the multi-decl path based on the first
    /// post-type-annotation token.
    fn finish_value_decl_or_multi(
        &mut self,
        kind: SlotKind,
        kind_span: Span,
        attributes: Vec<Attribute>,
        visibility: BindableVisibility,
        visibility_span: Option<Span>,
    ) -> Result<Declaration, ParseError> {
        let header = self.parse_slot_header_tail(visibility, kind, kind_span)?;

        if self.lexer.peek() == Some(&Token::Comma) {
            // Multi-decl. Attributes are still forbidden; visibility now
            // attaches to each slot, with the leading prefix consumed by
            // `parse_declaration` becoming the first slot's visibility.
            if let Some(first_attr) = attributes.first() {
                return Err(self.unexpected_token(
                    "no attributes on multi-decl (attributes are forbidden on multi-decl surface forms in v1)",
                    "`#[...]`",
                    first_attr.span,
                ));
            }
            return self.parse_multi_decl_rest(header, visibility, visibility_span);
        }

        // Single decl. Continue with the existing param/node/const-node path.
        let mut decl = self.finish_single_value_decl(header)?;
        set_decl_visibility(&mut decl, visibility);
        if let Some(ps) = visibility_span {
            decl.span = ps.merge(decl.span);
        }
        if let Some(first_attr) = attributes.first() {
            decl.span = first_attr.span.merge(decl.span);
        }
        decl.attributes = attributes;
        Ok(decl)
    }

    /// Parse an optional `pub` / `pub(bind)` visibility prefix.
    ///
    /// Returns `(BindableVisibility::Private, None)` when the next token is not
    /// `pub`. `bind` is a contextual keyword: parsed as a literal identifier
    /// inside the parens, not reserved as a token elsewhere.
    pub(super) fn parse_visibility_prefix(
        &mut self,
    ) -> Result<(BindableVisibility, Option<Span>), ParseError> {
        if self.lexer.peek() != Some(&Token::Pub) {
            return Ok((BindableVisibility::Private, None));
        }
        let (_, pub_span) = self.advance()?;
        if self.lexer.peek() != Some(&Token::LParen) {
            return Ok((BindableVisibility::Public, Some(pub_span)));
        }
        self.expect(Token::LParen)?;
        let (bind_tok, bind_span) = self.advance()?;
        if bind_tok != Token::Ident || self.lexer.slice_at(bind_span) != "bind" {
            return Err(self.unexpected_token("`bind`", &bind_tok.to_string(), bind_span));
        }
        let (_, rparen_span) = self.expect(Token::RParen)?;
        Ok((
            BindableVisibility::PublicBind,
            Some(pub_span.merge(rparen_span)),
        ))
    }

    /// Parse a single attribute: `#[name]` or `#[name(arg1, arg2)]`
    fn parse_attribute(&mut self) -> Result<Attribute, ParseError> {
        let (_, start_span) = self.expect(Token::Hash)?;
        self.expect(Token::LBracket)?;
        let name = self.parse_any_ident()?;
        let mut args = Vec::new();
        if self.lexer.peek() == Some(&Token::LParen) {
            self.expect(Token::LParen)?;
            if self.lexer.peek() != Some(&Token::RParen) {
                args.push(self.parse_attribute_arg()?);
                while self.lexer.peek() == Some(&Token::Comma) {
                    self.expect(Token::Comma)?;
                    if self.lexer.peek() == Some(&Token::RParen) {
                        break;
                    }
                    args.push(self.parse_attribute_arg()?);
                }
            }
            self.expect(Token::RParen)?;
        }
        let (_, end_span) = self.expect(Token::RBracket)?;
        let span = start_span.merge(end_span);
        Ok(Attribute { name, args, span })
    }

    /// Parse a single attribute argument: a path (`ident`, `Idx.Var`) or
    /// a parenthesized group (`(Idx.A, Idx.B)`).
    fn parse_attribute_arg(&mut self) -> Result<AttributeArg, ParseError> {
        if self.lexer.peek() == Some(&Token::LParen) {
            // Group: (arg, arg, ...)
            let (_, start_span) = self.expect(Token::LParen)?;
            let mut elements = Vec::new();
            if self.lexer.peek() != Some(&Token::RParen) {
                elements.push(self.parse_attribute_arg()?);
                while self.lexer.peek() == Some(&Token::Comma) {
                    self.expect(Token::Comma)?;
                    if self.lexer.peek() == Some(&Token::RParen) {
                        break;
                    }
                    elements.push(self.parse_attribute_arg()?);
                }
            }
            let (_, end_span) = self.expect(Token::RParen)?;
            Ok(AttributeArg::Group {
                elements,
                span: start_span.merge(end_span),
            })
        } else if self.lexer.peek() == Some(&Token::Hash) {
            // Range step: #N (key syntax for Nat range axes, matching the
            // `#N` slice labels of `table` expressions).
            let (_, hash_span) = self.expect(Token::Hash)?;
            let (_, num_span) = self.expect(Token::Number)?;
            let text = self.lexer.slice_at(num_span).replace('_', "");
            let step: u64 = text.parse().map_err(|_| ParseError::InvalidNumber {
                reason: "expected non-negative integer after `#` in attribute argument".to_string(),
                src: self.named_source(),
                span: num_span.into(),
            })?;
            Ok(AttributeArg::RangeStep {
                step,
                span: hash_span.merge(num_span),
            })
        } else {
            // Path: ident or ident.ident.ident...
            let first = self.parse_any_ident()?;
            let start_span = first.span;
            let mut end_span = start_span;
            let mut rest_segments = Vec::new();
            while self.lexer.peek() == Some(&Token::Dot) {
                self.expect(Token::Dot)?;
                let segment = self.parse_any_ident()?;
                end_span = segment.span;
                rest_segments.push(segment);
            }
            Ok(AttributeArg::Path {
                segments: NonEmpty::new(first, rest_segments),
                span: start_span.merge(end_span),
            })
        }
    }
}