rustre_parser/
parser.rs

1use crate::lexer::{Tok, TokInfo};
2use crate::location::Spanned;
3
4/// A Lustre v6 parser
5pub struct Parser<'a, 'f> {
6    pub errors: Vec<Error<'a, 'f>>,
7}
8
9#[derive(Debug)]
10/// Parsing error
11pub enum Error<'a, 'f> {
12    /// An unexpected token was encountered
13    UnexpectedToken(
14        /// The list of remaining tokens. The first one was the unexpected one.
15        &'a [Tok<'a, 'f>],
16        /// The error message
17        &'static str
18    ),
19    /// An internal error that was handled. You should normally never
20    /// see this variant when using the public API, and you can ignore
21    /// it safely.
22    ReportedError,
23}
24
25#[derive(Debug)]
26/// A parsed source file.
27///
28/// This syntax tree is not typed.
29///
30/// ## Lifetime parameters
31///
32/// - `'a` is the lifetime of the source code
33/// - `'f` is the lifetime of the file path
34pub struct Ast<'a, 'f> {
35    /// A list of files this file includes
36    includes: Vec<Spanned<'f, &'a str>>,
37    /// The declarations this file contains
38    decls: Vec<Spanned<'f, Decl<'a, 'f>>>,
39}
40
41#[derive(Debug)]
42/// A single declaration
43pub enum Decl<'a, 'f> {
44    /// Constant declaration
45    Const {
46        /// Name of the constant
47        name: Ident<'a, 'f>,
48        /// The value of the constant.
49        ///
50        /// May be None for external constants
51        value: Option<Spanned<'f, Expr<'a, 'f>>>,
52        /// The type of the constant, if specified.
53        ty: Option<TyExpr<'a, 'f>>,
54    },
55    /// Type declaration
56    Ty {
57        /// Name of the type
58        name: Spanned<'f, Ident<'a, 'f>>,
59        /// Value of the type
60        value: Spanned<'f, TyDecl<'a, 'f>>,
61    },
62    /// An external node.
63    ExternalNode {
64        /// Is it unsafe
65        is_unsafe: bool,
66        /// Is it a functional node
67        is_function: bool,
68        /// Its name
69        name: Spanned<'f, Ident<'a, 'f>>,
70        /// The static parameters it takes
71        static_params: Vec<Spanned<'f, StaticParamDecl<'a, 'f>>>,
72        /// The dynamic parameters it takes
73        params: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
74        /// Its outputs
75        outputs: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
76    },
77    /// A local node
78    Node {
79        /// Is it unsafe
80        is_unsafe: bool,
81        /// Is it a functional node
82        is_function: bool,
83        /// Its name
84        name: Spanned<'f, Ident<'a, 'f>>,
85        /// The static parameters it takes
86        static_params: Vec<Spanned<'f, StaticParamDecl<'a, 'f>>>,
87        /// The dynamic parameters it takes
88        params: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
89        /// Its outputs
90        outputs: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
91        /// The local variables of this node
92        vars: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
93        /// The local constants of this node
94        consts: Vec<Spanned<'f, Decl<'a, 'f>>>,
95        /// The body of the node.
96        ///
97        /// It is a list of assertions and equations.
98        body: Vec<Spanned<'f, BodyItem<'a, 'f>>>,
99    },
100    /// An alias node
101    AliasNode {
102        /// Is it unsafe
103        is_unsafe: bool,
104        /// Is it a functional node
105        is_function: bool,
106        /// Its name
107        name: Spanned<'f, Ident<'a, 'f>>,
108        /// The static parameters it takes
109        static_params: Vec<Spanned<'f, StaticParamDecl<'a, 'f>>>,
110        /// The dynamic parameters it takes
111        params: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
112        /// Its outputs
113        outputs: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
114        /// The value of the aliasing
115        effective_node: Spanned<'f, (Spanned<'f, Ident<'a, 'f>>, Vec<StaticArg<'a, 'f>>)>,
116    },
117    /// A package model
118    Model {
119        /// Its name
120        name: Spanned<'f, Ident<'a, 'f>>,
121        /// What packages this model uses
122        uses: Vec<Spanned<'f, Ident<'a, 'f>>>,
123        /// What functions/nodes/types/constants this model needs
124        needs: Vec<Spanned<'f, StaticParamDecl<'a, 'f>>>,
125        /// What functions/nodes/types/constants this model should provides
126        provides: Vec<Spanned<'f, AbstractDecl<'a, 'f>>>,
127        /// The body of the model
128        body: Vec<Spanned<'f, Decl<'a, 'f>>>,
129    },
130    /// A package alias
131    PackageAlias {
132        /// Its name
133        name: Spanned<'f, Ident<'a, 'f>>,
134        /// The model this package is based on
135        model: Spanned<'f, Ident<'a, 'f>>,
136        /// The parameters of the model
137        static_params: Vec<(Spanned<'f, Ident<'a, 'f>>, StaticArg<'a, 'f>)>,
138    },
139    /// A package definition
140    Package {
141        /// Its name
142        name: Spanned<'f, Ident<'a, 'f>>,
143        /// What packages it uses
144        uses: Vec<Spanned<'f, Ident<'a, 'f>>>,
145        /// What definitions it provides
146        provides: Vec<Spanned<'f, AbstractDecl<'a, 'f>>>,
147        /// Its body, which is a collection of declarations
148        body: Vec<Spanned<'f, Decl<'a, 'f>>>,
149    },
150}
151
152#[derive(Debug, Clone)]
153/// Abstract declarations, used in models
154pub enum AbstractDecl<'a, 'f> {
155    /// Constant
156    Const {
157        /// Its name
158        name: Spanned<'f, Ident<'a, 'f>>,
159        /// Its type
160        ty: Spanned<'f, TyExpr<'a, 'f>>,
161        /// A value, if defined
162        def: Option<Spanned<'f, Expr<'a, 'f>>>,
163    },
164    /// Type
165    Ty {
166        /// Its name
167        name: Spanned<'f, Ident<'a, 'f>>,
168        /// Its definition 
169        value: Spanned<'f, TyDecl<'a, 'f>>,
170    },
171    /// Node
172    Node {
173        /// Is it unsafe
174        is_unsafe: bool,
175        /// Is it a functional node
176        is_function: bool,
177        /// Its name
178        name: Spanned<'f, Ident<'a, 'f>>,
179        /// Its static parameters
180        static_params: Vec<Spanned<'f, StaticParamDecl<'a, 'f>>>,
181        /// Its dynamic parameters
182        params: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
183        /// Its outputs
184        outputs: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
185    },
186}
187
188#[derive(Debug, Clone)]
189/// Static argument
190///
191/// This is not a declaration, but the possible "expression" for static
192/// parameters when calling a node.
193///
194/// The declaration of static parameters is represented by [`StaticParamDecl`].
195pub enum StaticArg<'a, 'f> {
196    /// A regular expression
197    Expr(Spanned<'f, Expr<'a, 'f>>),
198    /// A predefined operation
199    Predefined(Spanned<'f, PredefinedItem>),
200    /// A type
201    Ty(Spanned<'f, TyExpr<'a, 'f>>),
202    /// A node
203    Node(Spanned<'f, Ident<'a, 'f>>, Vec<StaticArg<'a, 'f>>),
204    /// Maybe a node name, maybe some constant, maybe something else, who knows?
205    AmbiguousIdent(Ident<'a, 'f>),
206}
207
208#[derive(Debug, Clone)]
209/// A predefined operation
210pub enum PredefinedItem {
211    /// Unary operator
212    Unary(UnaryOp),
213    /// Binary operator
214    Binary(BinaryOp),
215    /// N-ary operator
216    NAry(NAryOp),
217}
218
219#[derive(Clone, Debug)]
220/// Declaration of a static parameter
221///
222/// For the possible values that can be passed as a static argument
223/// when calling a node, see [`StaticArg`].
224pub enum StaticParamDecl<'a, 'f> {
225    /// Constant
226    Const {
227        name: Spanned<'f, Ident<'a, 'f>>,
228        ty: Spanned<'f, TyExpr<'a, 'f>>,
229    },
230    /// Type
231    Ty {
232        name: Spanned<'f, Ident<'a, 'f>>,
233    },
234    /// Node
235    Node {
236        is_unsafe: bool,
237        is_function: bool,
238        name: Spanned<'f, Ident<'a, 'f>>,
239        params: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
240        outputs: Vec<Spanned<'f, VariableDecl<'a, 'f>>>,
241    },
242}
243
244#[derive(Clone, Debug)]
245/// Variable declaration
246///
247/// For variable declarations that may have a value, see [`ValuedVariableDecl`].
248pub struct VariableDecl<'a, 'f> {
249    /// Its name
250    name: Spanned<'f, Ident<'a, 'f>>,
251    /// Its type
252    ty: Spanned<'f, TyExpr<'a, 'f>>,
253    /// If None, the base clock is used
254    clock: Option<Spanned<'f, ClockExpr<'a, 'f>>>,
255}
256
257#[derive(Clone, Debug)]
258/// A variable declaration, which may have an initial value
259pub struct ValuedVariableDecl<'a, 'f> {
260    /// Its name
261    name: Spanned<'f, Ident<'a, 'f>>,
262    /// Its type
263    ty: Spanned<'f, TyExpr<'a, 'f>>,
264    /// If None, the base clock is used
265    clock: Option<Spanned<'f, ClockExpr<'a, 'f>>>,
266    /// Its initial value
267    value: Option<Spanned<'f, Expr<'a, 'f>>>,
268}
269
270#[derive(Clone, Debug)]
271/// Represents a clock
272pub struct ClockExpr<'a, 'f>(
273    /// I have no idea what these fields are
274    ///
275    /// TODO: find their meaning and document it
276    Option<Spanned<'f, Ident<'a, 'f>>>,
277    /// I have no idea what these fields are
278    ///
279    /// TODO: find their meaning and document it
280    Box<Option<Spanned<'f, Ident<'a, 'f>>>>,
281);
282
283#[derive(Clone, Debug)]
284/// A type expression
285pub enum TyExpr<'a, 'f> {
286    /// Base type: `int`
287    Int,
288    /// Base type: `bool`
289    Bool,
290    /// Base type: `real`
291    Real,
292    /// A named type.
293    ///
294    /// Example: `a`, `my_type`
295    Named(Ident<'a, 'f>),
296    /// An array type
297    ///
298    /// Example: `a^5`, `bool^2^2`
299    Power(Spanned<'f, Box<TyExpr<'a, 'f>>>, Spanned<'f, Expr<'a, 'f>>),
300}
301
302#[derive(Clone, Debug)]
303/// A type declaration
304pub enum TyDecl<'a, 'f> {
305    /// External type
306    External,
307    /// Type alias
308    Alias(TyExpr<'a, 'f>),
309    /// Enumerated type
310    Enum(
311        /// The variants of the enum
312        Vec<Spanned<'f, Ident<'a, 'f>>>
313    ),
314    /// A structured type
315    Struct(
316        /// The fields of the structure
317        Vec<Spanned<'f, ValuedVariableDecl<'a, 'f>>>
318    ),
319}
320
321#[derive(Clone, Debug)]
322/// A constant value
323pub enum ConstValue {
324    /// Integer constant
325    Int(i64),
326    /// Real constant
327    Float(f64),
328    /// Boolean constant
329    Bool(bool),
330}
331
332#[derive(Clone, Debug)]
333/// An expression
334pub enum Expr<'a, 'f> {
335    /// Constant value
336    Const(ConstValue),
337    /// Identifier
338    Ident(Ident<'a, 'f>),
339    /// Unary operation
340    Unary(
341        /// Operator
342        Spanned<'f, UnaryOp>,
343        /// Operand
344        Spanned<'f, Box<Expr<'a, 'f>>>
345    ),
346    /// Binary operation
347    Binary(
348        /// Operator
349        Spanned<'f, BinaryOp>,
350        /// LHS
351        Spanned<'f, Box<Expr<'a, 'f>>>,
352        /// RHS
353        Spanned<'f, Box<Expr<'a, 'f>>>,
354    ),
355    /// N-ary operation
356    NAry(
357        /// Operator
358        NAryOp,
359        /// Operands
360        Spanned<'f, Vec<Spanned<'f, Expr<'a, 'f>>>>
361    ),
362    /// Slice access (`tab[x..y]`)
363    Slice(
364        /// Array 
365        Spanned<'f, Box<Expr<'a, 'f>>>,
366        /// Start
367        Spanned<'f, Box<Expr<'a, 'f>>>,
368        /// End
369        Spanned<'f, Box<Expr<'a, 'f>>>,
370        /// Step
371        Option<Spanned<'f, Box<Expr<'a, 'f>>>>,
372    ),
373    /// Ternary expression
374    Ternary {
375        /// Operator
376        op: TernaryOp,
377        /// Condition
378        condition: Spanned<'f, Box<Expr<'a, 'f>>>,
379        /// Value if the condition is true
380        then: Spanned<'f, Box<Expr<'a, 'f>>>,
381        /// Value if the condition is false
382        otherwise: Spanned<'f, Box<Expr<'a, 'f>>>,
383    },
384    /// A clock expression
385    NamedClock(Spanned<'f, ClockExpr<'a, 'f>>),
386    /// Node call
387    ///
388    /// Not sure what the difference with [`Expr::CallByPos`] is…
389    /// TODO
390    CallByName(
391        /// The name of the node
392        Spanned<'f, Ident<'a, 'f>>,
393        /// The static arguments
394        Vec<Spanned<'f, StaticArg<'a, 'f>>>,
395        /// The dynamic arguments
396        Vec<Spanned<'f, Expr<'a, 'f>>>,
397    ),
398    /// Structure creation
399    CreateStruct {
400        /// Type name
401        ty_name: Spanned<'f, Ident<'a, 'f>>,
402        /// Fields (name and value)
403        fields: Vec<(Spanned<'f, Ident<'a, 'f>>, Spanned<'f, Expr<'a, 'f>>)>,
404        /// Base structure (fields that are not specified will be copied from this structure)
405        base_value: Option<Spanned<'f, Box<Expr<'a, 'f>>>>,
406    },
407    /// Merge operation
408    Merge(
409        /// Not sure what that is
410        /// TODO
411        Spanned<'f, Ident<'a, 'f>>,
412        /// The different cases of the merge
413        Vec<Spanned<'f, MergeCase<'a, 'f>>>,
414    ),
415    /// Node call 
416    ///
417    /// Not sure what the difference with [`Expr::CallByName`] is…
418    /// TODO
419    CallByPos(
420        /// The node name and its static arguments
421        ///
422        /// TODO: shouldn't that be two different fields?
423        Spanned<'f, (Spanned<'f, Ident<'a, 'f>>, Vec<StaticArg<'a, 'f>>)>,
424        /// The dynamic arguments
425        Vec<Spanned<'f, Expr<'a, 'f>>>,
426    ),
427}
428
429#[derive(Clone, Debug)]
430/// A merge case
431pub struct MergeCase<'a, 'f> {
432    /// The LHS
433    lhs: Spanned<'f, MergeLHS<'a, 'f>>,
434    /// The expression
435    expr: Spanned<'f, Expr<'a, 'f>>,
436}
437
438#[derive(Clone, Debug)]
439/// LHS of a merge case
440pub enum MergeLHS<'a, 'f> {
441    True,
442    False,
443    Ident(Spanned<'f, Ident<'a, 'f>>),
444}
445
446#[derive(Clone, Debug)]
447/// Unary operators
448pub enum UnaryOp {
449    Not,
450    Minus,
451    Pre,
452    Current,
453    IntToReal,
454    RealToInt,
455}
456
457#[derive(Clone, Debug)]
458/// Binary operators
459pub enum BinaryOp {
460    When,
461    FBy,
462    Default,
463    And,
464    Or,
465    Impl,
466    Equal,
467    Neq,
468    Lt,
469    Gt,
470    Lte,
471    Gte,
472    Mod,
473    Minus,
474    Plus,
475    Slash,
476    Power,
477    Concat,
478    Index,
479    Range,
480    Div,
481    Prod,
482    Step,
483    // TODO: maybe this could be merged with Mod?
484    // same for Div/Slash btw
485    Percent,
486    FieldAccess,
487    Hat,
488}
489
490#[derive(Debug, Clone)]
491/// Ternary operators
492pub enum TernaryOp {
493    IfThenElse,
494    WithThenElse,
495}
496
497#[derive(Debug, Clone)]
498/// N-ary operators
499pub enum NAryOp {
500    Xor,
501    Nor,
502    Array,
503    Tuple,
504}
505
506#[derive(Debug)]
507/// An item in the body of a node
508pub enum BodyItem<'a, 'f> {
509    /// An assertion
510    Assert(Spanned<'f, Expr<'a, 'f>>),
511    /// An equation
512    Equation(
513        Vec<Spanned<'f, LeftItem<'a, 'f>>>,
514        Spanned<'f, Expr<'a, 'f>>,
515    ),
516}
517
518#[derive(Debug)]
519/// The left side of an equation
520pub enum LeftItem<'a, 'f> {
521    /// Identifier
522    Ident(Spanned<'f, Ident<'a, 'f>>),
523    /// Tuple, made of many smaller left items
524    Tuple(Spanned<'f, Vec<LeftItem<'a, 'f>>>),
525    /// A field access (`my_struct.my_field = …`)
526    Field(
527        /// The structure
528        Box<Spanned<'f, LeftItem<'a, 'f>>>,
529        /// The field name
530        Spanned<'f, Ident<'a, 'f>>,
531    ),
532    /// Array index
533    ArrayIndex(
534        /// The table
535        Box<Spanned<'f, LeftItem<'a, 'f>>>,
536        /// The index
537        Spanned<'f, Expr<'a, 'f>>,
538    ),
539    /// Array slice
540    ArraySlice(
541        /// The array
542        Box<Spanned<'f, LeftItem<'a, 'f>>>,
543        /// Start
544        Spanned<'f, Expr<'a, 'f>>,
545        /// End
546        Spanned<'f, Expr<'a, 'f>>,
547        /// Step
548        Option<Spanned<'f, Expr<'a, 'f>>>,
549    ),
550}
551
552#[derive(Clone)]
553/// An identifier
554pub enum Ident<'a, 'f> {
555    /// A short identifier: just a single "word"
556    ///
557    /// It may have "pragmas" next to it, to give it special
558    /// properties
559    Short {
560        id: Spanned<'f, &'a str>,
561        pragmas: Vec<(&'a str, &'a str)>,
562    },
563    /// A long ID: a package name followed by another identifier
564    Long(Spanned<'f, &'a str>, Box<Ident<'a, 'f>>),
565}
566
567impl<'a, 'f> std::fmt::Debug for Ident<'a, 'f> {
568    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
569        match self {
570            Ident::Short { id, .. } => {
571                write!(f, "{} \x1b[38;5;240m@ {:?}\x1b[0m", id.item, id.span)
572            }
573            Ident::Long(Spanned { item: id, .. }, next) => {
574                write!(f, "{} :: {:?}", id, next)
575            }
576        }
577    }
578}
579
580type Res<'a, 'f, T> = Result<(&'a [Tok<'a, 'f>], T), Error<'a, 'f>>;
581type SpannedRes<'a, 'f, T> = Res<'a, 'f, Spanned<'f, T>>;
582
583macro_rules! parse_bin {
584    (LEFT $name:ident, $op:ident, $op2:ident, $disp:expr, $next:ident) => {
585        fn $name(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
586            let start = toks[0].span.clone();
587            let (toks, lhs) = self.$next(toks)?;
588            if let Ok(op) = self.expect(toks, TokInfo::$op, concat!("expected ", $disp)) {
589                let (toks, rhs) = self.parse_expr(&toks[1..])?;
590                Ok((
591                    toks,
592                    Spanned::fusion(
593                        start,
594                        rhs.span.clone(),
595                        Expr::Binary(
596                            op.map_ref(|_| BinaryOp::$op2),
597                            lhs.boxed(),
598                            rhs.boxed(),
599                        ),
600                    ),
601                ))
602            } else {
603                Ok((toks, lhs))
604            }
605        }
606    };
607    (LEFT $name:ident, rhs = $rhs:ident, $op:ident, $op2:ident, $disp:expr, $next:ident) => {
608        fn $name(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
609            let start = toks[0].span.clone();
610            let (toks, lhs) = self.$next(toks)?;
611            if let Ok(op) = self.expect(toks, TokInfo::$op, concat!("expected ", $disp)) {
612                let (toks, rhs) = self.$rhs(&toks[1..])?;
613                Ok((
614                    toks,
615                    Spanned::fusion(
616                        start,
617                        rhs.span.clone(),
618                        Expr::Binary(op.map_ref(|_| BinaryOp::$op2), lhs.boxed(), rhs.boxed()),
619                    ),
620                ))
621            } else {
622                Ok((toks, lhs))
623            }
624        }
625    };
626    (NONE $name:ident, $op:ident, $op2:ident, $disp:expr, $next:ident) => {
627        fn $name(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
628            let start = toks[0].span.clone();
629            let (toks, lhs) = self.$next(toks)?;
630            if let Ok(op) = self.expect(toks, TokInfo::$op, concat!("expected ", $disp)) {
631                let (toks, rhs) = self.$next(&toks[1..])?;
632                Ok((
633                    toks,
634                    Spanned::fusion(
635                        start,
636                        rhs.span.clone(),
637                        Expr::Binary(
638                            op.map_ref(|_| BinaryOp::$op2),
639                            lhs.boxed(),
640                            rhs.boxed(),
641                        ),
642                    ),
643                ))
644            } else {
645                Ok((toks, lhs))
646            }
647        }
648    };
649    (RIGHT $name:ident, $op:ident, $op2:ident, $disp:expr, $next:ident) => {
650        fn $name(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
651            let start = toks[0].span.clone();
652            let op_index = toks.iter().position(|t| t.item == TokInfo::$op);
653            match op_index {
654                None | Some(0) => self.$next(toks),
655                Some(op_index) => {
656                    if let Ok((left_toks, lhs)) = self.$name(&toks[..op_index]) {
657                        if !left_toks.is_empty() { // parsing the LHS actually failed
658                            return self.$next(toks);
659                        }
660                        let (t, rhs) = self.parse_expr(&toks[op_index + 1..])?;
661                        Ok((
662                            t,
663                            Spanned::fusion(
664                                start,
665                                rhs.span.clone(),
666                                Expr::Binary(
667                                    toks[op_index].map_ref(|_| BinaryOp::$op2),
668                                    lhs.boxed(),
669                                    rhs.boxed(),
670                                ),
671                            ),
672                        ))
673                    } else {
674                        self.$next(toks)
675                    }
676                }
677            }
678        }
679    };
680    ($kind:tt $name:ident, $op:ident, $disp:expr, $next:ident) => {
681        parse_bin!($kind $name, $op, $op, $disp, $next);
682    };
683}
684
685macro_rules! parse_un {
686    ($name:ident, $op:ident, $op2:ident, $disp:expr, $next:ident) => {
687        fn $name(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
688            let start = toks[0].span.clone();
689            if let Ok(op) = self.expect(toks, TokInfo::$op, concat!("expected ", $disp)) {
690                let (toks, expr) = self.parse_expr(&toks[1..])?;
691                Ok((
692                    toks,
693                    Spanned::fusion(
694                        start,
695                        expr.span.clone(),
696                        Expr::Unary(op.map_ref(|_| UnaryOp::$op2), expr.boxed()),
697                    ),
698                ))
699            } else {
700                self.$next(toks)
701            }
702        }
703    };
704    ($name:ident, $op:ident, $disp:expr, $next:ident) => {
705        parse_un!($name, $op, $op, $disp, $next);
706    };
707}
708
709macro_rules! parse_tern {
710    ($name:ident, $op1:ident, $op2:ident, $op3:ident, $parser_op:ident, $disp1:expr, $disp2:expr, $disp3:expr, $next:ident) => {
711        fn $name(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
712            let start = toks[0].span.clone();
713            if let Ok(_) = self.expect(toks, TokInfo::$op1, concat!("expected ", $disp1)) {
714                // special case when "if"/"when" is used as a static node
715                if self.expect(&toks[1..], TokInfo::Coma, ",").is_ok() {
716                    return Err(Error::ReportedError);
717                }
718                let cond_res = self.parse_expr(&toks[1..]);
719                let (toks, cond) = self.report_now(cond_res)?;
720                self.expect(toks, TokInfo::$op2, concat!("expected ", $disp2))?;
721                let (toks, then) = self.parse_expr(&toks[1..])?;
722                self.expect(toks, TokInfo::$op3, concat!("expected ", $disp3))?;
723                let (toks, otherwise) = self.parse_expr(&toks[1..])?;
724                Ok((
725                    toks,
726                    Spanned::fusion(
727                        start,
728                        otherwise.span.clone(),
729                        Expr::Ternary {
730                            op: TernaryOp::$parser_op,
731                            condition: cond.boxed(),
732                            then: then.boxed(),
733                            otherwise: otherwise.boxed(),
734                        },
735                    ),
736                ))
737            } else {
738                self.$next(toks)
739            }
740        }
741    };
742}
743
744macro_rules! reportable {
745    ($self:expr, $fn:ident, $toks:expr) => {{
746        let res = $self.$fn($toks);
747        $self.report_now(res)?
748    }};
749}
750
751impl<'a, 'f> Parser<'a, 'f> {
752    /// Initializes a parser
753    pub fn new() -> Self {
754        Self { errors: Vec::new() }
755    }
756
757    #[track_caller]
758    fn report<T>(&mut self, res: Result<T, Error<'a, 'f>>) -> Option<T> {
759        match res {
760            Ok(x) => Some(x),
761            Err(e) => {
762                println!("reported from l{}", std::panic::Location::caller().line());
763                self.errors.push(e);
764                None
765            }
766        }
767    }
768
769    #[track_caller]
770    fn report_now<T>(&mut self, res: Result<T, Error<'a, 'f>>) -> Result<T, Error<'a, 'f>> {
771        match res {
772            Err(e) => {
773                println!("reported from l{}", std::panic::Location::caller().line());
774                self.errors.push(e);
775                Err(Error::ReportedError)
776            }
777            ok => ok,
778        }
779    }
780
781    #[track_caller]
782    fn expect(
783        &mut self,
784        toks: &'a [Tok<'a, 'f>],
785        t: TokInfo<'a>,
786        exp: &'static str,
787    ) -> Result<&'a Tok<'a, 'f>, Error<'a, 'f>> {
788        match toks.get(0) {
789            Some(x) if x.item == t => Ok(x),
790            _ => Err(Error::UnexpectedToken(
791                toks,
792                exp,
793            )),
794        }
795    }
796
797    /// Parses tokens into a syntax tree.
798    ///
799    /// Tokens can be retrieved from a file using a [`Lexer`](crate::lexer::Lexer).
800    pub fn parse(&mut self, toks: &'a [Tok<'a, 'f>]) -> Result<Ast<'a, 'f>, Error<'a, 'f>> {
801        let mut includes = vec![];
802        let mut toks = toks;
803        while let Ok((t, inc)) = self.parse_include(toks) {
804            includes.push(inc);
805            toks = t;
806        }
807
808        let decls = if let Ok((t, decls)) = self.parse_package_body(toks) {
809            toks = t;
810            decls
811        } else if let Ok((t, decls)) = self.parse_package_list(toks) {
812            toks = t;
813            decls
814        } else {
815            return Err(Error::UnexpectedToken(toks, "expected declarations"));
816        };
817
818        self.expect(toks, TokInfo::EOF, "expected end of file")?;
819
820        Ok(Ast { includes, decls })
821    }
822
823    fn parse_include(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, &'a str> {
824        if let Ok(kw) = self.expect(toks, TokInfo::Include, "expected include") {
825            match toks.get(1) {
826                Some(
827                    tok
828                    @
829                    Spanned {
830                        item: TokInfo::Str(inc),
831                        ..
832                    },
833                ) => Ok((&toks[2..], Spanned::fusion(kw, tok, inc))),
834                _ => Err(Error::UnexpectedToken(
835                    &toks[1..],
836                    "expected a file name between quotes",
837                )),
838            }
839        } else {
840            Err(Error::UnexpectedToken(toks, "expected include"))
841        }
842    }
843
844    fn parse_package_list(
845        &mut self,
846        toks: &'a [Tok<'a, 'f>],
847    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
848        self.parse_many(
849            toks,
850            &[],
851            |_, _| false,
852            |s, t| {
853                s.parse_model_decl(t)
854                    .or_else(|e| choose_err(e, s.parse_package_eq(t)))
855                    .or_else(|e| choose_err(e, s.parse_package_decl(t)))
856            },
857        )
858    }
859
860    // parses many times the same thing
861    // if an error is found it is reported and the tokens are skipped
862    // until another item can be parsed
863    #[track_caller]
864    fn parse_many<F, E, T>(
865        &mut self,
866        toks: &'a [Tok<'a, 'f>],
867        sep: &'a [TokInfo<'a>],
868        end: E,
869        parse: F,
870    ) -> Res<'a, 'f, Vec<T>>
871    where
872        F: Fn(&mut Self, &'a [Tok<'a, 'f>]) -> Res<'a, 'f, Vec<T>>,
873        E: Fn(&mut Self, &'a [Tok<'a, 'f>]) -> bool,
874    {
875        let mut items = Vec::new();
876        let mut toks = toks;
877        let mut err = None;
878        let mut first = true;
879        'not_done: while toks.len() > 1 && !end(self, toks) {
880            if first {
881                first = false;
882            } else {
883                let mut err = None;
884                'sep: for s in sep {
885                    match (
886                        err,
887                        self.expect(
888                            toks,
889                            s.clone(),
890                            "expected separator", // Box::leak(format!("expected separator {:?}", s,).into_boxed_str()),
891                        ),
892                    ) {
893                        (None, Err(e)) => err = Some(e),
894                        (_, Ok(_)) => {
895                            err = None;
896                            toks = &toks[1..];
897                            break 'sep;
898                        }
899                        (e, _) => err = e,
900                    }
901                }
902
903                if end(self, toks) {
904                    break 'not_done;
905                }
906
907                if let Some(err) = err {
908                    return Err(err);
909                }
910            }
911
912            match parse(self, toks) {
913                Ok((t, mut item)) => {
914                    if let Some(e) = err.take() {
915                        self.report::<()>(Err(e));
916                    }
917                    items.append(&mut item);
918                    toks = t;
919                }
920                Err(e) => {
921                    if err.is_none() {
922                        err = Some(e);
923                    }
924                    if toks.len() > 1 && !end(self, toks) {
925                        toks = &toks[1..];
926                    }
927                }
928            }
929        }
930
931        if let Some(e) = err.take() {
932            self.report::<()>(Err(e));
933        }
934
935        Ok((toks, items))
936    }
937
938    fn parse_model_decl(
939        &mut self,
940        toks: &'a [Tok<'a, 'f>],
941    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
942        let start = &self.expect(toks, TokInfo::Model, "expected model")?.span;
943        let (toks, name) = self.parse_id(&toks[1..])?;
944        let (toks, uses) = self.parse_uses(toks)?;
945        self.expect(toks, TokInfo::Needs, "expected needs")?;
946        let (toks, needs) = self.parse_static_param_decl(&toks[1..])?;
947        let (toks, provides) = self.parse_provides(toks)?;
948        self.expect(toks, TokInfo::Body, "expected body")?;
949        let (toks, body) = self.parse_package_body(&toks[1..])?;
950        self.expect(toks, TokInfo::End, "expected end")?;
951        Ok((
952            &toks[1..],
953            vec![Spanned::fusion(
954                start.clone(),
955                toks[0].span.clone(),
956                Decl::Model {
957                    name,
958                    body,
959                    provides,
960                    needs,
961                    uses,
962                },
963            )],
964        ))
965    }
966
967    fn parse_package_eq(
968        &mut self,
969        toks: &'a [Tok<'a, 'f>],
970    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
971        let start = toks[0].span.clone();
972        self.expect(toks, TokInfo::Package, "expected package")?;
973        let (toks, name) = self.parse_id(&toks[1..])?;
974        self.expect(toks, TokInfo::Equal, "expected = or is")
975            .or(self.expect(toks, TokInfo::Is, "expected = or is"))?;
976        let (toks, alias) = self.parse_id(&toks[1..])?;
977        self.expect(toks, TokInfo::OpenPar, "expected (")?;
978        let (toks, params) = self.parse_by_name_static_args(&toks[1..])?;
979        self.expect(toks, TokInfo::ClosePar, "expected )")?;
980        self.expect(&toks[1..], TokInfo::Semicolon, "expected ;")?;
981        Ok((
982            &toks[2..],
983            vec![Spanned::fusion(
984                start,
985                toks[1].span.clone(),
986                Decl::PackageAlias {
987                    model: alias,
988                    static_params: params,
989                    name,
990                },
991            )],
992        ))
993    }
994
995    fn parse_package_decl(
996        &mut self,
997        toks: &'a [Tok<'a, 'f>],
998    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
999        let start = toks[0].span.clone();
1000        self.expect(toks, TokInfo::Package, "expected package")?;
1001        let (toks, name) = self.parse_id(&toks[1..])?;
1002        let (toks, uses) = self.parse_uses(toks)?;
1003        let (toks, provides) = self.parse_provides(toks)?;
1004        self.expect(toks, TokInfo::Body, "expected body")?;
1005        let (toks, body) = self.parse_package_body(&toks[1..])?;
1006        self.expect(toks, TokInfo::End, "expected end")?;
1007        Ok((
1008            &toks[1..],
1009            vec![Spanned::fusion(
1010                start,
1011                toks[0].span.clone(),
1012                Decl::Package {
1013                    name,
1014                    body,
1015                    uses,
1016                    provides,
1017                },
1018            )],
1019        ))
1020    }
1021
1022    fn parse_package_body(
1023        &mut self,
1024        toks: &'a [Tok<'a, 'f>],
1025    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
1026        if self.expect(toks, TokInfo::Model, "").is_ok()
1027            || self.expect(toks, TokInfo::Package, "").is_ok()
1028        {
1029            return Err(Error::UnexpectedToken(toks, "expected a package body"));
1030        }
1031
1032        self.parse_many(
1033            toks,
1034            &[],
1035            |s, t| s.expect(t, TokInfo::End, "end").is_ok(),
1036            |s, t| {
1037                s.parse_const_decl(t)
1038                    .or_else(|e| choose_err(e, s.parse_node_decl(t)))
1039                    .or_else(|e| choose_err(e, s.parse_type_decl(t)))
1040            },
1041        )
1042    }
1043
1044    fn parse_const_decl(
1045        &mut self,
1046        toks: &'a [Tok<'a, 'f>],
1047    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
1048        let kw = self.expect(toks, TokInfo::Const, "expected const keyword")?;
1049        self.parse_many(
1050            &toks[1..],
1051            &[TokInfo::Semicolon],
1052            |s, t| {
1053                s.expect(t, TokInfo::Const, "const").is_ok()
1054                    || s.expect(t, TokInfo::Type, "type").is_ok()
1055                    || s.expect(t, TokInfo::Extern, "extern").is_ok()
1056                    || s.expect(t, TokInfo::Unsafe, "unsafe").is_ok()
1057                    || s.expect(t, TokInfo::Node, "node").is_ok()
1058                    || s.expect(t, TokInfo::Function, "function").is_ok()
1059                    || s.expect(t, TokInfo::CloseStaticPar, ">>").is_ok()
1060                    || s.expect(t, TokInfo::Let, "let").is_ok()
1061                    || s.expect(t, TokInfo::Var, "var").is_ok()
1062                    || s.expect(t, TokInfo::EOF, "EOF").is_ok()
1063            },
1064            |s, t| {
1065                // TODO: refactor id parsing with parse_many?
1066                let (t, id) = s.parse_id(&t)?;
1067                let mut ids = vec![id];
1068                let t = {
1069                    let mut toks = t;
1070                    while s.expect(toks, TokInfo::Coma, "expected ,").is_ok() {
1071                        let (t, id) = s.parse_id(&toks[1..])?;
1072                        ids.push(id);
1073                        toks = t;
1074                    }
1075                    toks
1076                };
1077
1078                let (t, ty) = if s.expect(t, TokInfo::Colon, "expected :").is_ok() {
1079                    let (t, ty) = s.parse_ty_expr(&t[1..])?;
1080                    (t, Some(ty))
1081                } else {
1082                    (t, None)
1083                };
1084
1085                let (t, expr) =
1086                    if ids.len() == 1 && s.expect(t, TokInfo::Equal, "expected =").is_ok() {
1087                        let (t, expr) = reportable!(s, parse_expr, &t[1..]);
1088                        (t, Some(expr))
1089                    } else {
1090                        (t, None)
1091                    };
1092
1093                let ty = ty.map(|x| x.item);
1094                Ok((
1095                    t,
1096                    ids.into_iter()
1097                        .map(|i| {
1098                            Spanned::fusion(
1099                                kw,
1100                                &i,
1101                                Decl::Const {
1102                                    name: i.item.clone(),
1103                                    ty: ty.clone(),
1104                                    value: expr.clone(),
1105                                },
1106                            )
1107                        })
1108                        .collect(),
1109                ))
1110            },
1111        )
1112    }
1113
1114    fn parse_type_decl(
1115        &mut self,
1116        toks: &'a [Tok<'a, 'f>],
1117    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
1118        self.expect(toks, TokInfo::Type, "expected type")?;
1119        self.parse_many(
1120            &toks[1..],
1121            &[TokInfo::Semicolon],
1122            |s, t| {
1123                s.expect(t, TokInfo::Const, "const").is_ok()
1124                    || s.expect(t, TokInfo::Type, "type").is_ok()
1125                    || s.expect(t, TokInfo::Extern, "extern").is_ok()
1126                    || s.expect(t, TokInfo::Unsafe, "unsafe").is_ok()
1127                    || s.expect(t, TokInfo::Node, "node").is_ok()
1128                    || s.expect(t, TokInfo::Function, "function").is_ok()
1129                    || s.expect(t, TokInfo::End, "end").is_ok()
1130                    || s.expect(t, TokInfo::EOF, "EOF").is_ok()
1131            },
1132            |s, t| {
1133                let (toks, decl) = s.parse_one_type_decl(t)?;
1134                Ok((toks, vec![decl]))
1135            },
1136        )
1137    }
1138
1139    fn parse_one_type_decl(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Decl<'a, 'f>> {
1140        let start = toks[0].span.clone();
1141        let (toks, name) = self.parse_id(toks)?;
1142        if self.expect(toks, TokInfo::Equal, "expected =").is_ok() {
1143            let has_brace = self.expect(&toks[1..], TokInfo::OpenBrace, "{").is_ok();
1144            if let Ok((toks, ty)) = self.parse_ty_expr(&toks[1..]) {
1145                Ok((
1146                    toks,
1147                    Spanned::fusion(
1148                        start,
1149                        toks[0].span.clone(),
1150                        Decl::Ty {
1151                            name,
1152                            value: ty.map(TyDecl::Alias),
1153                        },
1154                    ),
1155                ))
1156            } else if self.expect(&toks[1..], TokInfo::Struct, "struct").is_ok() || has_brace {
1157                let decl_start = toks[1].span.clone();
1158                let toks = if !has_brace {
1159                    self.expect(&toks[2..], TokInfo::OpenBrace, "expected {")?;
1160                    &toks[3..]
1161                } else {
1162                    &toks[2..]
1163                };
1164                let (toks, fields) = self.parse_valued_var_decl(toks, true)?;
1165                self.expect(toks, TokInfo::CloseBrace, "expected }")?;
1166                Ok((
1167                    &toks[1..],
1168                    Spanned::fusion(
1169                        start,
1170                        toks[0].span.clone(),
1171                        Decl::Ty {
1172                            name,
1173                            value: Spanned::fusion(
1174                                decl_start,
1175                                toks[0].span.clone(),
1176                                TyDecl::Struct(fields),
1177                            ),
1178                        },
1179                    ),
1180                ))
1181            } else if self.expect(&toks[1..], TokInfo::Enum, "enum").is_ok() {
1182                let decl_start = toks[1].span.clone();
1183                self.expect(&toks[2..], TokInfo::OpenBrace, "expected {")?;
1184                let (toks, variants) = self.parse_many(
1185                    &toks[3..],
1186                    &[TokInfo::Coma],
1187                    |s, t| s.expect(t, TokInfo::CloseBrace, "").is_ok(),
1188                    |s, t| {
1189                        let (toks, id) = s.parse_id(t)?;
1190                        Ok((toks, vec![id]))
1191                    },
1192                )?;
1193                self.expect(toks, TokInfo::CloseBrace, "expected }")?;
1194                Ok((
1195                    &toks[1..],
1196                    Spanned::fusion(
1197                        start,
1198                        toks[0].span.clone(),
1199                        Decl::Ty {
1200                            name,
1201                            value: Spanned::fusion(
1202                                decl_start,
1203                                toks[0].span.clone(),
1204                                TyDecl::Enum(variants),
1205                            ),
1206                        },
1207                    ),
1208                ))
1209            } else {
1210                Err(Error::UnexpectedToken(
1211                    &toks[1..],
1212                    "expected a type expression, struct or enum",
1213                ))
1214            }
1215        } else {
1216            Ok((
1217                toks,
1218                Spanned::fusion(
1219                    start,
1220                    name.span.clone(),
1221                    Decl::Ty {
1222                        value: name.map_ref(|_| TyDecl::External),
1223                        name,
1224                    },
1225                ),
1226            ))
1227        }
1228    }
1229
1230    #[track_caller]
1231    fn parse_id(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Ident<'a, 'f>> {
1232        let id = match toks.get(0) {
1233            Some(
1234                tok
1235                @
1236                Spanned {
1237                    item: TokInfo::Ident(x),
1238                    ..
1239                },
1240            ) => Spanned {
1241                span: tok.span.clone(),
1242                item: *x,
1243            },
1244            // TODO: check exhaustiveness
1245            // TODO: maybe they are actually accepted only when fully qualified (e.g Lustre::and,
1246            // not just and)
1247            Some(Spanned {
1248                item: TokInfo::And,
1249                span,
1250            }) => Spanned {
1251                span: span.clone(),
1252                item: "and",
1253            },
1254            Some(Spanned {
1255                item: TokInfo::Or,
1256                span,
1257            }) => Spanned {
1258                span: span.clone(),
1259                item: "or",
1260            },
1261            Some(Spanned {
1262                item: TokInfo::Xor,
1263                span,
1264            }) => Spanned {
1265                span: span.clone(),
1266                item: "xor",
1267            },
1268            Some(Spanned {
1269                item: TokInfo::Nor,
1270                span,
1271            }) => Spanned {
1272                span: span.clone(),
1273                item: "nor",
1274            },
1275            Some(Spanned {
1276                item: TokInfo::Not,
1277                span,
1278            }) => Spanned {
1279                span: span.clone(),
1280                item: "not",
1281            },
1282            Some(Spanned {
1283                item: TokInfo::If,
1284                span,
1285            }) => Spanned {
1286                span: span.clone(),
1287                item: "if",
1288            },
1289            Some(Spanned {
1290                item: TokInfo::FBy,
1291                span,
1292            }) => Spanned {
1293                span: span.clone(),
1294                item: "fby",
1295            },
1296            _ => {
1297                return Err(Error::UnexpectedToken(
1298                    &toks,
1299                    Box::leak(
1300                        format!(
1301                            "expected an identifier (line {})",
1302                            std::panic::Location::caller().line()
1303                        )
1304                        .into_boxed_str(),
1305                    ),
1306                    //"expected an identifier",
1307                ));
1308            }
1309        };
1310        if self.expect(&toks[1..], TokInfo::DoubleColon, "::").is_ok() {
1311            let (toks, next) = self.parse_id(&toks[2..])?;
1312            Ok((
1313                toks,
1314                Spanned::fusion(
1315                    id.span.clone(),
1316                    next.span.clone(),
1317                    Ident::Long(id, Box::new(next.item)),
1318                ),
1319            ))
1320        } else {
1321            let (toks, pragmas) = self.parse_pragmas(&toks[1..])?;
1322            Ok((
1323                toks,
1324                id.clone().map(
1325                    |_| Ident::Short { id, pragmas },
1326                ),
1327            ))
1328        }
1329    }
1330    
1331    fn parse_pragmas(&mut self, toks: &'a [Tok<'a, 'f>]) -> Res<'a, 'f, Vec<(&'a str, &'a str)>> {
1332        let mut res = Vec::new();
1333        let mut toks = toks;
1334        while self.expect(toks, TokInfo::Percent, "%").is_ok() {
1335            match (toks.get(1), toks.get(2), toks.get(3)) {
1336                (
1337                    Some(Spanned { item: TokInfo::Ident(lhs), .. }),
1338                    Some(Spanned { item: TokInfo::Colon, .. }),
1339                    Some(Spanned { item: TokInfo::Ident(rhs), .. })
1340                ) => {
1341                    toks = &toks[4..];
1342                    res.push((*lhs, *rhs));
1343                }
1344                _ => return Err(Error::UnexpectedToken(&toks[1..], "expected a pragma")),
1345            }
1346            self.expect(toks, TokInfo::Percent, "expected %")?;
1347            toks = &toks[1..];
1348        }
1349        Ok((toks, res))
1350    }
1351
1352    fn parse_named_clock(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1353        let (toks, clock) = self.parse_clock_expr(toks)?;
1354        Ok((
1355            toks,
1356            Spanned {
1357                span: clock.span.clone(),
1358                item: Expr::NamedClock(clock),
1359            },
1360        ))
1361    }
1362
1363    fn parse_clock_expr(
1364        &mut self,
1365        toks: &'a [Tok<'a, 'f>],
1366    ) -> SpannedRes<'a, 'f, ClockExpr<'a, 'f>> {
1367        let start = toks[0].span.clone();
1368        let not = self.expect(toks, TokInfo::Not, "not").is_ok();
1369        let toks = if not { &toks[1..] } else { toks };
1370        let (toks, name) = if let Ok((toks, name)) = self.parse_id(toks) {
1371            (toks, Some(name))
1372        } else if not {
1373            (toks, None)
1374        } else {
1375            return Err(Error::UnexpectedToken(
1376                toks,
1377                "expected `not` or an identifier",
1378            ));
1379        };
1380        let (toks, param) = if self.expect(toks, TokInfo::OpenPar, "(").is_ok() {
1381            let (toks, param) = self.parse_id(&toks[1..])?;
1382            self.expect(toks, TokInfo::ClosePar, "expected )")?;
1383            (&toks[1..], Some(param))
1384        } else {
1385            (toks, None)
1386        };
1387        Ok((
1388            toks,
1389            Spanned::fusion(
1390                start,
1391                toks[0].span.clone(),
1392                ClockExpr(name, Box::new(param)),
1393            ),
1394        ))
1395    }
1396
1397    parse_bin!(LEFT parse_default, Arrow, Default, "->", parse_if);
1398    parse_tern!(parse_if, If, Then, Else, IfThenElse, "if", "then", "else", parse_with);
1399    parse_tern!(
1400        parse_with,
1401        With,
1402        Then,
1403        Else,
1404        WithThenElse,
1405        "with",
1406        "then",
1407        "else",
1408        parse_concat
1409    );
1410    parse_bin!(LEFT parse_concat, Bar, Concat, "|", parse_step);
1411    parse_bin!(NONE parse_step, Step, Step, "step", parse_range);
1412    parse_bin!(NONE parse_range, CDots, Range, "..", parse_impl);
1413    parse_bin!(RIGHT parse_impl, Impl, "=>", parse_or);
1414    parse_bin!(LEFT parse_or, Or, "or", parse_xor);
1415
1416    fn parse_xor(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1417        let start = toks[0].span.clone();
1418        let (toks, lhs) = self.parse_and(toks)?;
1419        if let Ok(_) = self.expect(toks, TokInfo::Xor, "expected xor") {
1420            let (toks, rhs) = self.parse_xor(&toks[1..])?;
1421            match rhs.item {
1422                // TODO: this will build one n-ary expression from `a xor #(b, c)`, which is maybe
1423                // not wanted?
1424                Expr::NAry(NAryOp::Xor, mut items) => {
1425                    let mut result = Vec::with_capacity(items.item.len() + 1);
1426                    result.push(lhs);
1427                    result.append(&mut items.item);
1428                    Ok((
1429                        toks,
1430                        Spanned::fusion(
1431                            start.clone(),
1432                            toks[0].span.clone(),
1433                            Expr::NAry(
1434                                NAryOp::Xor,
1435                                Spanned::fusion(start, items.span.clone(), result),
1436                            ),
1437                        ),
1438                    ))
1439                }
1440                _ => Ok((
1441                    toks,
1442                    Spanned::fusion(
1443                        start,
1444                        rhs.span.clone(),
1445                        Expr::NAry(
1446                            NAryOp::Xor,
1447                            Spanned::fusion(lhs.span.clone(), rhs.span.clone(), vec![lhs, rhs]),
1448                        ),
1449                    ),
1450                )),
1451            }
1452        } else {
1453            Ok((toks, lhs))
1454        }
1455    }
1456
1457    parse_bin!(LEFT parse_and, And, "and", parse_lt);
1458    // TODO: this allow this kind of expr, while it should not
1459    // a < b <= c >= d
1460    parse_bin!(NONE parse_lt, Lt, "<", parse_lte);
1461    parse_bin!(NONE parse_lte, Lte, "<=", parse_gt);
1462    parse_bin!(NONE parse_gt, Gt, ">", parse_gte);
1463    parse_bin!(NONE parse_gte, Gte, ">=", parse_eq);
1464    parse_bin!(NONE parse_eq, Equal, "=", parse_neq);
1465    parse_bin!(NONE parse_neq, Neq, "!=", parse_not);
1466    parse_un!(parse_not, Not, "not", parse_add);
1467    parse_bin!(LEFT parse_add, Plus, "+", parse_minus);
1468    parse_bin!(LEFT parse_minus, Minus, "-", parse_mul);
1469    parse_bin!(LEFT parse_mul, Star, Prod, "*", parse_slash);
1470    parse_bin!(LEFT parse_slash, Slash, "/", parse_percent);
1471    parse_bin!(LEFT parse_percent, Percent, "/", parse_mod);
1472    parse_bin!(LEFT parse_mod, Mod, Mod, "mod", parse_div);
1473    parse_bin!(LEFT parse_div, Div, "div", parse_power);
1474    parse_bin!(LEFT parse_power, Power, "**", parse_when);
1475    parse_bin!(LEFT parse_when, rhs = parse_named_clock, When, When, "when", parse_real_to_int);
1476    parse_un!(parse_real_to_int, Int, RealToInt, "int", parse_int_to_real);
1477    parse_un!(
1478        parse_int_to_real,
1479        Real,
1480        IntToReal,
1481        "real",
1482        parse_minus_unary
1483    );
1484    parse_un!(parse_minus_unary, Minus, "-", parse_pre);
1485    parse_un!(parse_pre, Pre, "pre", parse_current);
1486    parse_un!(parse_current, Current, "current", parse_sharp);
1487
1488    fn parse_sharp(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1489        let start = &toks[0].span;
1490        if self.expect(toks, TokInfo::Sharp, "#").is_ok() {
1491            self.expect(&toks[1..], TokInfo::OpenPar, "expected (")?;
1492            let (toks, items) = self.parse_tuple(&toks[2..])?;
1493            self.expect(toks, TokInfo::ClosePar, "expected )")?;
1494            Ok((
1495                &toks[1..],
1496                Spanned::fusion(
1497                    start.clone(),
1498                    toks[0].span.clone(),
1499                    Expr::NAry(NAryOp::Xor, items),
1500                ),
1501            ))
1502        } else {
1503            self.parse_nor(toks)
1504        }
1505    }
1506
1507    fn parse_nor(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1508        let start = &toks[0].span;
1509        if self.expect(toks, TokInfo::Nor, "nor").is_ok() {
1510            self.expect(&toks[1..], TokInfo::OpenPar, "expected (")?;
1511            let (toks, items) = self.parse_tuple(&toks[2..])?;
1512            self.expect(toks, TokInfo::ClosePar, "expected )")?;
1513            Ok((
1514                &toks[1..],
1515                Spanned::fusion(
1516                    start.clone(),
1517                    toks[0].span.clone(),
1518                    Expr::NAry(NAryOp::Nor, items),
1519                ),
1520            ))
1521        } else {
1522            self.parse_hat(toks)
1523        }
1524    }
1525
1526    parse_bin!(LEFT parse_hat, Hat, "^", parse_dot);
1527    parse_bin!(LEFT parse_dot, Dot, FieldAccess, ".", parse_index_or_slice);
1528
1529    fn parse_index_or_slice(
1530        &mut self,
1531        toks: &'a [Tok<'a, 'f>],
1532    ) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1533        let start = toks[0].span.clone();
1534        let (mut tokens, mut expr) = self.parse_array_expr(toks)?;
1535        while self.expect(tokens, TokInfo::OpenBracket, "[").is_ok() {
1536            let op_span = tokens[0].span.clone();
1537            if let Ok((
1538                toks,
1539                Spanned {
1540                    item: Expr::Binary(_, from, to),
1541                    ..
1542                },
1543            )) = self.parse_range(&tokens[1..])
1544            {
1545                let (toks, step) = if self.expect(toks, TokInfo::Step, "step").is_ok() {
1546                    let (t, s) = self.parse_expr(&toks[1..])?;
1547                    (t, Some(s))
1548                } else {
1549                    (toks, None)
1550                };
1551                self.expect(toks, TokInfo::CloseBracket, "expected ]")?;
1552                tokens = &toks[1..];
1553                expr = Spanned::fusion(
1554                    start.clone(),
1555                    toks[0].span.clone(),
1556                    Expr::Slice(expr.boxed(), from, to, step.map(Spanned::boxed)),
1557                );
1558            } else {
1559                let (toks, rhs) = self.parse_expr(&tokens[1..])?;
1560                self.expect(toks, TokInfo::CloseBracket, "expected ]")?;
1561
1562                tokens = &toks[1..];
1563                expr = Spanned::fusion(
1564                    start.clone(),
1565                    rhs.span.clone(),
1566                    Expr::Binary(
1567                        Spanned {
1568                            span: op_span,
1569                            item: BinaryOp::Index,
1570                        },
1571                        expr.boxed(),
1572                        rhs.boxed(),
1573                    ),
1574                );
1575            };
1576        }
1577        Ok((tokens, expr))
1578    }
1579
1580    fn parse_array_expr(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1581        let start = &toks[0].span;
1582        if self.expect(toks, TokInfo::OpenBracket, "[").is_ok() {
1583            let (toks, items) = self.parse_tuple(&toks[1..])?;
1584            self.expect(toks, TokInfo::CloseBracket, "expected ]")?;
1585            Ok((
1586                &toks[1..],
1587                Spanned::fusion(
1588                    start.clone(),
1589                    toks[0].span.clone(),
1590                    Expr::NAry(NAryOp::Array, items),
1591                ),
1592            ))
1593        } else {
1594            self.parse_struct_expr(toks)
1595        }
1596    }
1597
1598    fn parse_struct_expr(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1599        let t = toks;
1600        let start = toks[0].span.clone();
1601        if let Ok((toks, name)) = self.parse_id(toks) {
1602            if self.expect(toks, TokInfo::OpenBrace, "{").is_ok() {
1603                let t = &toks[1..];
1604                let (toks, base) = if let Ok((toks, base)) = self.parse_expr(t) {
1605                    if self.expect(toks, TokInfo::With, "").is_ok() {
1606                        (&toks[1..], Some(base))
1607                    } else {
1608                        (t, None)
1609                    }
1610                } else {
1611                    (t, None)
1612                };
1613
1614                let (toks, fields) = self.parse_many(
1615                    toks,
1616                    &[TokInfo::Coma, TokInfo::Semicolon],
1617                    |s, t| s.expect(t, TokInfo::CloseBrace, "").is_ok(),
1618                    |s, t| {
1619                        let (t, name) = s.parse_id(t)?;
1620                        s.expect(t, TokInfo::Equal, "expected =")?;
1621                        let (t, val) = s.parse_expr(&t[1..])?;
1622                        Ok((t, vec![(name, val)]))
1623                    },
1624                )?;
1625
1626                self.expect(toks, TokInfo::CloseBrace, "expected }")?;
1627
1628                Ok((
1629                    &toks[1..],
1630                    Spanned::fusion(
1631                        start,
1632                        toks[0].span.clone(),
1633                        Expr::CreateStruct {
1634                            ty_name: name,
1635                            base_value: base.map(Spanned::boxed),
1636                            fields,
1637                        },
1638                    ),
1639                ))
1640            } else {
1641                self.parse_paren_expr(t)
1642            }
1643        } else {
1644            self.parse_paren_expr(t)
1645        }
1646    }
1647
1648    fn parse_paren_expr(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1649        if self.expect(toks, TokInfo::OpenPar, "(").is_ok() {
1650            let (mut toks, expr) = self.parse_expr(&toks[1..])?;
1651            let mut exprs = vec![expr];
1652            while self.expect(toks, TokInfo::Coma, ",").is_ok() {
1653                let (t, e) = self.parse_expr(&toks[1..])?;
1654                toks = t;
1655                exprs.push(e);
1656            }
1657            self.expect(toks, TokInfo::ClosePar, "expected )")?;
1658            let expr = if exprs.len() == 1 {
1659                exprs.remove(0)
1660            } else {
1661                Spanned::fusion(
1662                    exprs[0].span.clone(),
1663                    exprs[exprs.len() - 1].span.clone(),
1664                    Expr::NAry(
1665                        NAryOp::Tuple,
1666                        Spanned::fusion(
1667                            exprs[0].span.clone(),
1668                            exprs[exprs.len() - 1].span.clone(),
1669                            exprs,
1670                        ),
1671                    ),
1672                )
1673            };
1674            Ok((&toks[1..], expr))
1675        } else {
1676            self.parse_fby(toks)
1677        }
1678    }
1679
1680    parse_bin!(RIGHT parse_fby, FBy, "fby", parse_merge);
1681
1682    fn parse_merge(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1683        if self.expect(toks, TokInfo::Merge, "merge").is_ok() {
1684            let (toks, id) = self.parse_id(&toks[1..])?;
1685            let (toks, cases) = self.parse_many(
1686                toks,
1687                &[],
1688                |s, t| {
1689                    s.expect(t, TokInfo::Semicolon, "").is_ok()
1690                        || s.expect(t, TokInfo::ClosePar, "").is_ok()
1691                        || s.expect(t, TokInfo::CloseBracket, "").is_ok()
1692                        || s.expect(t, TokInfo::CloseBrace, "").is_ok()
1693                        || s.expect(t, TokInfo::Tel, "").is_ok()
1694                        || s.expect(t, TokInfo::EOF, "").is_ok()
1695                },
1696                |s, t| {
1697                    s.expect(t, TokInfo::OpenPar, "expected (")?;
1698                    let (t, lhs) = if s.expect(&t[1..], TokInfo::True, "true").is_ok() {
1699                        (&t[2..], t[0].map_ref(|_| MergeLHS::True))
1700                    } else if s.expect(&t[1..], TokInfo::False, "false").is_ok() {
1701                        (&t[2..], t[0].map_ref(|_| MergeLHS::False))
1702                    } else {
1703                        let (t, id) = s.parse_id(&t[1..])?;
1704                        (t, id.clone().map(|_| MergeLHS::Ident(id)))
1705                    };
1706
1707                    s.expect(t, TokInfo::Arrow, "expected ->")?;
1708
1709                    let (t, expr) = s.parse_expr(&t[1..])?;
1710
1711                    s.expect(t, TokInfo::ClosePar, "expected )")?;
1712                    Ok((
1713                        &t[1..],
1714                        vec![Spanned::fusion(
1715                            lhs.span.clone(),
1716                            t[0].span.clone(),
1717                            MergeCase { lhs, expr },
1718                        )],
1719                    ))
1720                },
1721            )?;
1722            Ok((
1723                toks,
1724                Spanned::fusion(
1725                    id.span.clone(),
1726                    toks[0].span.clone(),
1727                    Expr::Merge(id, cases),
1728                ),
1729            ))
1730        } else {
1731            self.parse_call_by_pos(toks)
1732        }
1733    }
1734
1735    fn parse_call_by_pos(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1736        let original_toks = toks;
1737        if let Ok((toks, effective_node)) = self.parse_effective_node(toks) {
1738            if self.expect(toks, TokInfo::OpenPar, "expected (").is_ok() {
1739                let (toks, params) = self.parse_many(
1740                    &toks[1..],
1741                    &[TokInfo::Coma],
1742                    |s, t| s.expect(t, TokInfo::ClosePar, "").is_ok(),
1743                    |s, t| {
1744                        let (t, expr) = s.parse_expr(t)?;
1745                        Ok((t, vec![expr]))
1746                    },
1747                )?;
1748                self.expect(toks, TokInfo::ClosePar, "expected )")?;
1749                Ok((
1750                    &toks[1..],
1751                    Spanned::fusion(
1752                        effective_node.span.clone(),
1753                        toks[0].span.clone(),
1754                        Expr::CallByPos(effective_node, params),
1755                    ),
1756                ))
1757            } else {
1758                self.parse_call_by_name(original_toks)
1759            }
1760        } else {
1761            self.parse_call_by_name(toks)
1762        }
1763    }
1764
1765    fn parse_call_by_name(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1766        let original_toks = toks;
1767        if let Ok((toks, name)) = self.parse_id(toks) {
1768            let (toks, static_params) = if self.expect(toks, TokInfo::OpenStaticPar, "<<").is_ok() {
1769                let (toks, params) = self.parse_many(
1770                    &toks[1..],
1771                    &[TokInfo::Coma, TokInfo::Semicolon],
1772                    |s, t| s.expect(t, TokInfo::CloseStaticPar, ">>").is_ok(),
1773                    |s, t| {
1774                        let (toks, expr) = reportable!(s, parse_static_arg, t);
1775                        Ok((
1776                            toks,
1777                            vec![Spanned::fusion(
1778                                t[0].span.clone(),
1779                                toks[0].span.clone(),
1780                                expr,
1781                            )],
1782                        ))
1783                    },
1784                )?;
1785                self.expect(toks, TokInfo::CloseStaticPar, "expected >>")?;
1786                (&toks[1..], params)
1787            } else {
1788                (toks, Vec::new())
1789            };
1790
1791            if self.expect(toks, TokInfo::OpenPar, "expected (").is_ok()
1792                // || !static_params.is_empty()
1793            {
1794                let (toks, params) = self.parse_many(
1795                    &toks[1..],
1796                    &[TokInfo::Coma],
1797                    |s, t| s.expect(t, TokInfo::ClosePar, ")").is_ok(),
1798                    |s, t| {
1799                        let (toks, expr) = s.parse_expr(t)?;
1800                        Ok((toks, vec![expr]))
1801                    },
1802                )?;
1803                self.expect(toks, TokInfo::ClosePar, "expected )")?;
1804
1805                Ok((
1806                    &toks[1..],
1807                    Spanned::fusion(
1808                        name.span.clone(),
1809                        toks[0].span.clone(),
1810                        Expr::CallByName(name, static_params, params),
1811                    ),
1812                ))
1813            } else {
1814                self.parse_expr_term(original_toks)
1815            }
1816        } else {
1817            self.parse_expr_term(original_toks)
1818        }
1819    }
1820
1821    fn parse_expr_term(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1822        self.parse_const(toks).or_else(|_| {
1823            let (t, id) = self.parse_id(toks)?;
1824            Ok((t, id.map(Expr::Ident)))
1825        })
1826        .map_err(|_: Error| Error::UnexpectedToken(toks, "expected an expression"))
1827    }
1828
1829    fn parse_expr(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1830        self.parse_default(toks)
1831    }
1832
1833    fn parse_const(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, Expr<'a, 'f>> {
1834        let neg = self.expect(toks, TokInfo::Minus, "-").is_ok();
1835        match toks.get(if neg { 1 } else { 0 }) {
1836            Some(
1837                tok
1838                @
1839                Spanned {
1840                    item: TokInfo::IConst(i),
1841                    ..
1842                },
1843            ) => Ok((
1844                &toks[1..],
1845                Spanned {
1846                    span: tok.span.clone(),
1847                    item: Expr::Const(ConstValue::Int(if neg { -i } else { *i })),
1848                },
1849            )),
1850            Some(
1851                tok
1852                @
1853                Spanned {
1854                    item: TokInfo::RConst(r),
1855                    ..
1856                },
1857            ) => Ok((
1858                &toks[1..],
1859                Spanned {
1860                    span: tok.span.clone(),
1861                    item: Expr::Const(ConstValue::Float(if neg { -r } else { *r })),
1862                },
1863            )),
1864            Some(
1865                tok
1866                @
1867                Spanned {
1868                    item: TokInfo::False,
1869                    ..
1870                },
1871            ) => Ok((
1872                &toks[1..],
1873                tok.map_ref(|_| Expr::Const(ConstValue::Bool(false))),
1874            )),
1875            Some(
1876                tok
1877                @
1878                Spanned {
1879                    item: TokInfo::True,
1880                    ..
1881                },
1882            ) => Ok((
1883                &toks[1..],
1884                tok.map_ref(|_| Expr::Const(ConstValue::Bool(true))),
1885            )),
1886            _ => Err(Error::UnexpectedToken(&toks, "expected a constant")),
1887        }
1888    }
1889
1890    fn parse_tuple(
1891        &mut self,
1892        toks: &'a [Tok<'a, 'f>],
1893    ) -> SpannedRes<'a, 'f, Vec<Spanned<'f, Expr<'a, 'f>>>> {
1894        let (toks, fst) = reportable!(self, parse_expr, toks);
1895        let start = fst.span.clone();
1896        if self.expect(toks, TokInfo::Coma, ",").is_ok() {
1897            let (toks, mut next) = self.parse_tuple(&toks[1..])?;
1898            let mut result = Vec::with_capacity(next.item.len() + 1);
1899            result.push(fst);
1900            result.append(&mut next.item);
1901            Ok((toks, Spanned::fusion(start, toks[0].span.clone(), result)))
1902        } else {
1903            Ok((
1904                toks,
1905                Spanned {
1906                    span: start,
1907                    item: vec![fst],
1908                },
1909            ))
1910        }
1911    }
1912
1913    fn parse_node_decl(
1914        &mut self,
1915        toks: &'a [Tok<'a, 'f>],
1916    ) -> Res<'a, 'f, Vec<Spanned<'f, Decl<'a, 'f>>>> {
1917        let start_span = toks[0].span.clone();
1918        let mut toks = toks;
1919        let is_unsafe = self.expect(toks, TokInfo::Unsafe, "unsafe keyword").is_ok();
1920        toks = if is_unsafe { &toks[1..] } else { toks };
1921        let is_extern = self.expect(toks, TokInfo::Extern, "extern keyword").is_ok();
1922        toks = if is_extern { &toks[1..] } else { toks };
1923        let is_node = self.expect(&toks, TokInfo::Node, "node keyword").is_ok();
1924        if !is_node {
1925            self.expect(
1926                &toks,
1927                TokInfo::Function,
1928                "expected function or node keyword",
1929            )?;
1930        }
1931
1932        toks = &toks[1..];
1933        let (t, name) = self.parse_id(&toks)?;
1934        toks = t;
1935        let static_params = if self.expect(&toks, TokInfo::OpenStaticPar, "<<").is_ok() {
1936            let (t, sp) = self.parse_many(
1937                &toks[1..],
1938                &[TokInfo::Semicolon],
1939                |s, t| s.expect(t, TokInfo::CloseStaticPar, ">>").is_ok(),
1940                |s, t| s.parse_static_param_decl(t),
1941            )?;
1942            toks = t;
1943            self.expect(toks, TokInfo::CloseStaticPar, "expected >>")?;
1944            toks = &toks[1..];
1945            sp
1946        } else {
1947            Vec::new()
1948        };
1949
1950        let has_params = self.expect(toks, TokInfo::OpenPar, "(").is_ok();
1951        let params = if has_params {
1952            let (t, pars) = self.parse_var_decl(&toks[1..], true)?;
1953            toks = t;
1954            self.expect(toks, TokInfo::ClosePar, "expected )")?;
1955            toks = &toks[1..];
1956            pars
1957        } else {
1958            Vec::new()
1959        };
1960
1961        let returns = if has_params {
1962            self.expect(toks, TokInfo::Returns, "expected returns")?;
1963            self.expect(&toks[1..], TokInfo::OpenPar, "expected (")?; // TODO: check if parenthesis are always required after returns
1964            let (t, rets) = self.parse_var_decl(&toks[2..], true)?;
1965            toks = t;
1966            self.expect(toks, TokInfo::ClosePar, "expected )")?;
1967            toks = &toks[1..];
1968            rets
1969        } else {
1970            Vec::new()
1971        };
1972
1973        if is_extern {
1974            self.expect(toks, TokInfo::Semicolon, "expected ;")?;
1975
1976            return Ok((
1977                &toks[1..],
1978                vec![Spanned::fusion(
1979                    start_span,
1980                    toks[0].span.clone(),
1981                    Decl::ExternalNode {
1982                        is_function: !is_node,
1983                        is_unsafe,
1984                        name,
1985                        outputs: returns,
1986                        params,
1987                        static_params,
1988                    },
1989                )],
1990            ));
1991        }
1992
1993        let is_alias = self.expect(toks, TokInfo::Equal, "=").is_ok();
1994        if !is_alias && !has_params {
1995            return Err(Error::UnexpectedToken(
1996                toks,
1997                "expected a node alias (declared with a =) or parameters",
1998            ));
1999        }
2000
2001        if is_alias {
2002            toks = &toks[1..];
2003            let (t, effective_node) = self.parse_effective_node(toks)?;
2004            toks = if self.expect(t, TokInfo::Semicolon, ";").is_ok() {
2005                &t[1..]
2006            } else {
2007                t
2008            };
2009
2010            Ok((
2011                toks,
2012                vec![Spanned::fusion(
2013                    start_span,
2014                    toks[0].span.clone(),
2015                    Decl::AliasNode {
2016                        name,
2017                        params,
2018                        outputs: returns,
2019                        is_unsafe,
2020                        is_function: !is_node,
2021                        effective_node,
2022                        static_params,
2023                    },
2024                )],
2025            ))
2026        } else {
2027            toks = if self.expect(toks, TokInfo::Semicolon, ";").is_ok() {
2028                &toks[1..]
2029            } else {
2030                toks
2031            };
2032
2033            let mut vars = Vec::new();
2034            let mut consts = Vec::new();
2035            while self.expect(toks, TokInfo::Var, "var").is_ok()
2036                || self.expect(toks, TokInfo::Const, "const").is_ok()
2037            {
2038                let is_vars = self.expect(toks, TokInfo::Var, "var").is_ok();
2039                if is_vars {
2040                    let (t, mut decls) = self.parse_var_decl(&toks[1..], true)?; // FIXME: the final semicolon is not optional
2041                    toks = t;
2042                    vars.append(&mut decls);
2043                } else {
2044                    let (t, mut decls) = self.parse_const_decl(toks)?;
2045                    toks = t;
2046                    consts.append(&mut decls);
2047                }
2048            }
2049
2050
2051            self.expect(toks, TokInfo::Let, "expected let")?;
2052            let (toks, body) = self.parse_node_body(&toks[1..])?;
2053            self.expect(toks, TokInfo::Tel, "expected tel")?;
2054            let toks = if self.expect(&toks[1..], TokInfo::Semicolon, ";").is_ok() {
2055                &toks[2..]
2056            } else {
2057                &toks[1..]
2058            };
2059
2060            Ok((
2061                toks,
2062                vec![Spanned::fusion(
2063                    start_span,
2064                    toks[0].span.clone(),
2065                    Decl::Node {
2066                        name,
2067                        params,
2068                        outputs: returns,
2069                        is_unsafe,
2070                        is_function: !is_node,
2071                        static_params,
2072                        vars,
2073                        consts,
2074                        body,
2075                    },
2076                )],
2077            ))
2078        }
2079    }
2080
2081    fn parse_static_arg(&mut self, toks: &'a [Tok<'a, 'f>]) -> Res<'a, 'f, StaticArg<'a, 'f>> {
2082        if self.expect(toks, TokInfo::Const, "").is_ok() {
2083            let (toks, arg) = self.parse_expr(&toks[1..])?;
2084            Ok((toks, StaticArg::Expr(arg)))
2085        } else if self.expect(toks, TokInfo::Node, "").is_ok() || self.expect(toks, TokInfo::Function, "").is_ok() {
2086            let (toks, Spanned { item: (name, args), .. }) = self.parse_effective_node(&toks[1..])?;
2087            Ok((toks, StaticArg::Node(name, args)))
2088        } else if self.expect(toks, TokInfo::Type, "").is_ok() {
2089            let (toks, ty) = self.parse_ty_expr(&toks[1..])?;
2090            Ok((toks, StaticArg::Ty(ty)))
2091        } else {
2092            self.parse_expr(toks)
2093                .and_then(|(t, expr)| match expr.item {
2094                    Expr::Ident(i) => {
2095                        match t.get(0).map(|x| x.item.clone()) {
2096                            Some(TokInfo::OpenStaticPar) => Err(Error::ReportedError), // to continue with node parsing
2097                            _ => Ok((t, StaticArg::AmbiguousIdent(i))),
2098                        }
2099                    },
2100                    _ => Ok((t, StaticArg::Expr(expr))),
2101                })
2102                .or_else(|e| {
2103                    choose_err(
2104                        e,
2105                        self.parse_effective_node(toks).map(
2106                            |(
2107                                t,
2108                                Spanned {
2109                                    item: (name, args), ..
2110                                },
2111                            )| (t, StaticArg::Node(name, args)),
2112                        ),
2113                    )
2114                })
2115                .or_else(|e| {
2116                    choose_err(
2117                        e,
2118                        self.parse_predefined(toks)
2119                            .map(|(t, p)| (t, StaticArg::Predefined(p))),
2120                    )
2121                })
2122                .or_else(|e| {
2123                    choose_err(
2124                        e,
2125                        self.parse_ty_expr(toks)
2126                            .map(|(t, ty)| (t, StaticArg::Ty(ty))),
2127                    )
2128                })
2129        }
2130    }
2131
2132    fn parse_effective_node(
2133        &mut self,
2134        toks: &'a [Tok<'a, 'f>],
2135    ) -> SpannedRes<'a, 'f, (Spanned<'f, Ident<'a, 'f>>, Vec<StaticArg<'a, 'f>>)> {
2136        let name_span = toks[0].span.clone();
2137        let (toks, effective_node_name) = self.parse_id(toks)?;
2138        let (toks, effective_static_params) =
2139            if self.expect(toks, TokInfo::OpenStaticPar, "<<").is_ok() {
2140                let (toks, params) = self.parse_many(
2141                    &toks[1..],
2142                    &[TokInfo::Coma, TokInfo::Semicolon],
2143                    |s, t| s.expect(t, TokInfo::CloseStaticPar, ">>").is_ok(),
2144                    |s, t| {
2145                        let (t, expr) = s.parse_static_arg(t)?;
2146                        Ok((t, vec![expr]))
2147                    },
2148                )?;
2149                self.expect(toks, TokInfo::CloseStaticPar, "expected >>")?;
2150                (&toks[1..], params)
2151            } else {
2152                (toks, Vec::new())
2153            };
2154
2155        Ok((
2156            toks,
2157            Spanned::fusion(
2158                name_span,
2159                toks.get(0).map(|x| x.span.clone()).unwrap_or_default(), // TODO: compute the actual span
2160                (effective_node_name, effective_static_params),
2161            ),
2162        ))
2163    }
2164
2165    fn parse_predefined(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, PredefinedItem> {
2166        use TokInfo::*;
2167        // TODO: check the exhaustiveness of this list
2168        let bin_op = match toks[0].item {
2169            Plus => Some(BinaryOp::Plus),
2170            Minus => Some(BinaryOp::Minus),
2171            Star => Some(BinaryOp::Prod),
2172            Slash => Some(BinaryOp::Slash),
2173            Div => Some(BinaryOp::Div),
2174            Mod => Some(BinaryOp::Mod),
2175            Percent => Some(BinaryOp::Percent),
2176            Or => Some(BinaryOp::Or),
2177            And => Some(BinaryOp::And),
2178            Impl => Some(BinaryOp::Impl),
2179            Lt => Some(BinaryOp::Lt),
2180            Lte => Some(BinaryOp::Lte),
2181            Gt => Some(BinaryOp::Gt),
2182            Gte => Some(BinaryOp::Gte),
2183            Equal => Some(BinaryOp::Equal),
2184            Neq => Some(BinaryOp::Neq),
2185            _ => None,
2186        };
2187        let un_op = match toks[0].item {
2188            Minus => Some(UnaryOp::Minus),
2189            Not => Some(UnaryOp::Not),
2190            _ => None,
2191        };
2192        let n_op = match toks[0].item {
2193            Xor | Sharp => Some(NAryOp::Xor),
2194            Nor => Some(NAryOp::Nor),
2195            _ => None,
2196        };
2197        let span = toks[0].span.clone();
2198        let item = if let Some(bin) = bin_op {
2199            PredefinedItem::Binary(bin)
2200        } else if let Some(un) = un_op {
2201            PredefinedItem::Unary(un)
2202        } else if let Some(nary) = n_op {
2203            PredefinedItem::NAry(nary)
2204        } else {
2205            return Err(Error::UnexpectedToken(
2206                toks,
2207                "expected a predefined operator or node",
2208            ));
2209        };
2210        Ok((&toks[1..], Spanned { span, item }))
2211    }
2212
2213    // TODO: a lot of the code is shared with parse_var_decl, maybe
2214    // find a nice way to merge the two functions?
2215    // adding a boolean parameter won't be enough, as the return types
2216    // are not the same
2217    // maybe one return type would be enough, since even this method may
2218    // give `None` as a value
2219    fn parse_valued_var_decl(
2220        &mut self,
2221        toks: &'a [Tok<'a, 'f>],
2222        optional_final_semicolon: bool,
2223    ) -> Res<'a, 'f, Vec<Spanned<'f, ValuedVariableDecl<'a, 'f>>>> {
2224        let (toks, decls) = self.parse_many(
2225            toks,
2226            &[TokInfo::Semicolon],
2227            |_, t| match t.get(0).map(|t| t.item.clone()) {
2228                Some(
2229                    TokInfo::Semicolon
2230                    | TokInfo::Ident(_)
2231                    | TokInfo::Coma
2232                    | TokInfo::Colon
2233                    | TokInfo::Hat,
2234                ) => false,
2235                _ => true,
2236            },
2237            |s, t| {
2238                let (t, names) = s.parse_many(
2239                    t,
2240                    &[TokInfo::Coma],
2241                    |_, t| match t.get(0).map(|t| t.item.clone()) {
2242                        Some(TokInfo::Ident(_) | TokInfo::Coma) => false,
2243                        _ => true,
2244                    },
2245                    |s, t| {
2246                        let (t, var_name) = s.parse_id(t)?;
2247                        Ok((t, vec![var_name]))
2248                    },
2249                )?;
2250
2251                s.expect(t, TokInfo::Colon, "expected :")?;
2252                let t = &t[1..];
2253                let (t, ty) = s.parse_ty_expr(t)?;
2254                let (t, clock) = if s.expect(t, TokInfo::When, "when").is_ok() {
2255                    let (t, clock) = s.parse_clock_expr(&t[1..])?;
2256                    (t, Some(clock))
2257                } else {
2258                    (t, None)
2259                };
2260
2261                let (t, value) = if s.expect(t, TokInfo::Equal, "").is_ok() {
2262                    let (t, val) = s.parse_expr(&t[1..])?;
2263                    (t, Some(val))
2264                } else {
2265                    (t, None)
2266                };
2267
2268                Ok((
2269                    t,
2270                    names
2271                        .into_iter()
2272                        .map(|name| {
2273                            name.map_ref(|_| ValuedVariableDecl {
2274                                name: name.clone(),
2275                                ty: ty.clone(),
2276                                clock: clock.clone(),
2277                                value: value.clone(),
2278                            })
2279                        })
2280                        .collect(),
2281                ))
2282            },
2283        )?;
2284        let final_semicolon = self.expect(toks, TokInfo::Semicolon, "expected ;");
2285        if !optional_final_semicolon && final_semicolon.is_err() {
2286            return Err(final_semicolon.unwrap_err());
2287        } else if final_semicolon.is_err() {
2288            Ok((toks, decls))
2289        } else {
2290            Ok((&toks[1..], decls))
2291        }
2292    }
2293
2294    fn parse_var_decl(
2295        &mut self,
2296        toks: &'a [Tok<'a, 'f>],
2297        optional_final_semicolon: bool,
2298    ) -> Res<'a, 'f, Vec<Spanned<'f, VariableDecl<'a, 'f>>>> {
2299        let (toks, decls) = self.parse_many(
2300            toks,
2301            &[TokInfo::Semicolon],
2302            |_, t| match t.get(0).map(|t| t.item.clone()) {
2303                Some(
2304                    TokInfo::Semicolon
2305                    | TokInfo::Ident(_)
2306                    | TokInfo::Coma
2307                    | TokInfo::Colon
2308                    | TokInfo::Hat,
2309                ) => false,
2310                _ => true,
2311            },
2312            |s, t| {
2313                let (t, names) = s.parse_many(
2314                    t,
2315                    &[TokInfo::Coma],
2316                    |_, t| match t.get(0).map(|t| t.item.clone()) {
2317                        Some(TokInfo::Ident(_) | TokInfo::Coma) => false,
2318                        _ => true,
2319                    },
2320                    |s, t| {
2321                        let (t, var_name) = s.parse_id(t)?;
2322                        Ok((t, vec![var_name]))
2323                    },
2324                )?;
2325
2326                s.expect(t, TokInfo::Colon, "expected :")?;
2327                let t = &t[1..];
2328                let (t, ty) = s.parse_ty_expr(t)?;
2329                let (t, clock) = if s.expect(t, TokInfo::When, "when").is_ok() {
2330                    let (t, clock) = s.parse_clock_expr(&t[1..])?;
2331                    (t, Some(clock))
2332                } else {
2333                    (t, None)
2334                };
2335
2336                Ok((
2337                    t,
2338                    names
2339                        .into_iter()
2340                        .map(|name| {
2341                            name.map_ref(|_| VariableDecl {
2342                                name: name.clone(),
2343                                ty: ty.clone(),
2344                                clock: clock.clone(),
2345                            })
2346                        })
2347                        .collect(),
2348                ))
2349            },
2350        )?;
2351        let final_semicolon = self.expect(toks, TokInfo::Semicolon, "expected ;");
2352        if !optional_final_semicolon && final_semicolon.is_err() {
2353            return Err(final_semicolon.unwrap_err());
2354        } else if final_semicolon.is_err() {
2355            Ok((toks, decls))
2356        } else {
2357            Ok((&toks[1..], decls))
2358        }
2359    }
2360
2361    fn parse_ty_expr(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, TyExpr<'a, 'f>> {
2362        let start = toks[0].span.clone();
2363        let op_index = toks.iter().position(|t| t.item == TokInfo::Hat);
2364        match op_index {
2365            None | Some(0) => self.parse_base_ty_expr(toks),
2366            Some(op_index) => {
2367                if let Ok((left_toks, lhs)) = self.parse_ty_expr(&toks[..op_index]) {
2368                    if !left_toks.is_empty() {
2369                        // parsing the LHS actually failed
2370                        return self.parse_base_ty_expr(toks);
2371                    }
2372                    let (t, rhs) = self.parse_expr(&toks[op_index + 1..])?;
2373                    Ok((
2374                        t,
2375                        Spanned::fusion(start, rhs.span.clone(), TyExpr::Power(lhs.boxed(), rhs)),
2376                    ))
2377                } else {
2378                    self.parse_base_ty_expr(toks)
2379                }
2380            }
2381        }
2382    }
2383
2384    fn parse_base_ty_expr(
2385        &mut self,
2386        toks: &'a [Tok<'a, 'f>],
2387    ) -> SpannedRes<'a, 'f, TyExpr<'a, 'f>> {
2388        let start = toks[0].span.clone();
2389        let (toks, ty) = if self.expect(toks, TokInfo::Int, "int").is_ok() {
2390            (&toks[1..], TyExpr::Int)
2391        } else if self.expect(toks, TokInfo::Real, "real").is_ok() {
2392            (&toks[1..], TyExpr::Real)
2393        } else if self.expect(toks, TokInfo::Bool, "bool").is_ok() {
2394            (&toks[1..], TyExpr::Bool)
2395        } else {
2396            let (toks, name) = self.parse_id(toks)?;
2397            (toks, TyExpr::Named(name.item))
2398        };
2399
2400        Ok((
2401            toks,
2402            Spanned {
2403                span: start,
2404                item: ty,
2405            },
2406        ))
2407    }
2408
2409    fn parse_static_param_decl(
2410        &mut self,
2411        toks: &'a [Tok<'a, 'f>],
2412    ) -> Res<'a, 'f, Vec<Spanned<'f, StaticParamDecl<'a, 'f>>>> {
2413        self.parse_many(
2414            toks,
2415            &[TokInfo::Semicolon],
2416            |s, t| {
2417                s.expect(t, TokInfo::CloseStaticPar, ">>").is_ok()
2418                    || s.expect(t, TokInfo::Provides, "provides").is_ok()
2419            },
2420            |s, t| {
2421                let start_span = t[0].span.clone();
2422                if s.expect(t, TokInfo::Type, "type").is_ok() {
2423                    let (t, name) = s.parse_id(&t[1..])?;
2424                    Ok((
2425                        t,
2426                        vec![Spanned::fusion(
2427                            start_span,
2428                            name.span.clone(),
2429                            StaticParamDecl::Ty { name },
2430                        )],
2431                    ))
2432                } else if s.expect(t, TokInfo::Const, "const").is_ok() {
2433                    let (t, name) = s.parse_id(&t[1..])?;
2434                    s.expect(t, TokInfo::Colon, "expected :")?;
2435                    let (t, ty) = s.parse_ty_expr(&t[1..])?;
2436                    Ok((
2437                        t,
2438                        vec![Spanned::fusion(
2439                            start_span,
2440                            ty.span.clone(),
2441                            StaticParamDecl::Const { name, ty },
2442                        )],
2443                    ))
2444                } else {
2445                    let is_unsafe = s.expect(t, TokInfo::Unsafe, "unsafe").is_ok();
2446                    let t = if is_unsafe { &t[1..] } else { t };
2447                    let is_node = s.expect(t, TokInfo::Node, "node").is_ok();
2448                    if !is_node {
2449                        s.expect(t, TokInfo::Function, "expected function or node")?;
2450                    }
2451                    let t = &t[1..];
2452                    let (t, name) = s.parse_id(t)?;
2453                    s.expect(t, TokInfo::OpenPar, "expected (")?;
2454                    let (t, params) = s.parse_var_decl(&t[1..], true)?;
2455                    s.expect(t, TokInfo::ClosePar, "expected )")?;
2456                    s.expect(&t[1..], TokInfo::Returns, "expected returns")?;
2457                    s.expect(&t[2..], TokInfo::OpenPar, "expected (")?;
2458                    let (t, outputs) = s.parse_var_decl(&t[3..], true)?;
2459                    s.expect(t, TokInfo::ClosePar, "expected )")?;
2460                    Ok((
2461                        &t[1..],
2462                        vec![Spanned::fusion(
2463                            start_span,
2464                            t[0].span.clone(),
2465                            StaticParamDecl::Node {
2466                                is_function: !is_node,
2467                                is_unsafe,
2468                                params,
2469                                outputs,
2470                                name,
2471                            },
2472                        )],
2473                    ))
2474                }
2475            },
2476        )
2477    }
2478
2479    fn parse_node_body(
2480        &mut self,
2481        toks: &'a [Spanned<'f, TokInfo<'a>>],
2482    ) -> Res<'a, 'f, Vec<Spanned<'f, BodyItem<'a, 'f>>>> {
2483        self.parse_many(
2484            toks,
2485            &[TokInfo::Semicolon],
2486            |s, t| s.expect(t, TokInfo::Tel, "tel").is_ok(),
2487            |s, t| {
2488                let start = t[0].span.clone();
2489                if s.expect(t, TokInfo::Assert, "assert").is_ok() {
2490                    let (t, expr) = reportable!(s, parse_expr, &t[1..]);
2491                    Ok((
2492                        t,
2493                        vec![Spanned::fusion(
2494                            start,
2495                            t[0].span.clone(),
2496                            BodyItem::Assert(expr),
2497                        )],
2498                    ))
2499                } else {
2500                    let (t, left) = reportable!(s, parse_left_items, t);
2501                    s.expect(t, TokInfo::Equal, "expected =")?;
2502                    let (t, expr) = reportable!(s, parse_expr, &t[1..]);
2503                    Ok((
2504                        t,
2505                        vec![Spanned::fusion(
2506                            start,
2507                            t[0].span.clone(),
2508                            BodyItem::Equation(left, expr),
2509                        )],
2510                    ))
2511                }
2512            },
2513        )
2514    }
2515
2516    fn parse_left_item(&mut self, toks: &'a [Tok<'a, 'f>]) -> SpannedRes<'a, 'f, LeftItem<'a, 'f>> {
2517        if self.expect(toks, TokInfo::OpenPar, "(").is_ok() {
2518            let (toks, items) = self.parse_many(
2519                &toks[1..],
2520                &[TokInfo::Coma],
2521                |s, t| s.expect(t, TokInfo::ClosePar, ")").is_ok(),
2522                |s, t| {
2523                    let (toks, inner) = s.parse_left_item(t)?;
2524                    Ok((toks, vec![inner]))
2525                },
2526            )?;
2527            let spanned_item = Spanned::fusion(
2528                items[0].span.clone(),
2529                toks[0].span.clone(),
2530                items.into_iter().map(|i| i.item).collect(),
2531            );
2532            self.expect(toks, TokInfo::ClosePar, ")")?;
2533            return Ok((
2534                &toks[1..],
2535                Spanned {
2536                    span: spanned_item.span.clone(),
2537                    item: LeftItem::Tuple(spanned_item),
2538                },
2539            ));
2540        }
2541
2542        let (mut toks, id) = self.parse_id(toks)?;
2543        let mut item = Spanned {
2544            span: id.span.clone(),
2545            item: LeftItem::Ident(id),
2546        };
2547
2548        loop {
2549            if self.expect(toks, TokInfo::OpenBracket, "[").is_ok() {
2550                if let Ok((
2551                    t,
2552                    Spanned {
2553                        item: Expr::Binary(_, from, to),
2554                        ..
2555                    },
2556                )) = self.parse_range(&toks[1..])
2557                {
2558                    let (t, step) = if self.expect(t, TokInfo::Step, "step").is_ok() {
2559                        let (t, s) = self.parse_expr(&t[1..])?;
2560                        (t, Some(s))
2561                    } else {
2562                        (t, None)
2563                    };
2564                    self.expect(t, TokInfo::CloseBracket, "expected ]")?;
2565                    toks = &t[1..];
2566                    item = Spanned::fusion(
2567                        item.span.clone(),
2568                        toks[0].span.clone(),
2569                        LeftItem::ArraySlice(
2570                            Box::new(item),
2571                            from.map(|x| *x),
2572                            to.map(|x| *x),
2573                            step,
2574                        ),
2575                    );
2576                } else {
2577                    let (t, rhs) = self.parse_expr(&toks[1..])?;
2578                    self.expect(t, TokInfo::CloseBracket, "expected ]")?;
2579
2580                    toks = &t[1..];
2581                    item = Spanned::fusion(
2582                        item.span.clone(),
2583                        rhs.span.clone(),
2584                        LeftItem::ArrayIndex(Box::new(item), rhs),
2585                    );
2586                }
2587            } else if self.expect(toks, TokInfo::Dot, ".").is_ok() {
2588                let (t, id) = self.parse_id(&toks[1..])?;
2589                toks = t;
2590                item = Spanned::fusion(
2591                    item.span.clone(),
2592                    id.span.clone(),
2593                    LeftItem::Field(Box::new(item), id),
2594                );
2595            } else {
2596                break;
2597            }
2598        }
2599
2600        Ok((toks, item))
2601    }
2602
2603    fn parse_left_items(
2604        &mut self,
2605        t: &'a [Spanned<'f, TokInfo<'a>>],
2606    ) -> Res<'a, 'f, Vec<Spanned<'f, LeftItem<'a, 'f>>>> {
2607        self.parse_many(
2608            t,
2609            &[TokInfo::Coma],
2610            |s, t| {
2611                s.expect(t, TokInfo::Equal, "=").is_ok() || s.expect(t, TokInfo::Tel, "tel").is_ok()
2612            },
2613            |s, t| {
2614                let (t, item) = s.parse_left_item(t)?;
2615                Ok((t, vec![item]))
2616            },
2617        )
2618    }
2619
2620    fn parse_uses(
2621        &mut self,
2622        toks: &'a [Tok<'a, 'f>],
2623    ) -> Res<'a, 'f, Vec<Spanned<'f, Ident<'a, 'f>>>> {
2624        if self.expect(toks, TokInfo::Uses, "uses").is_ok() {
2625            let (toks, res) = self.parse_many(
2626                &toks[1..],
2627                &[TokInfo::Coma],
2628                |s, t| s.expect(t, TokInfo::Semicolon, "").is_ok(),
2629                |s, t| {
2630                    let (toks, id) = s.parse_id(t)?;
2631                    Ok((toks, vec![id]))
2632                },
2633            )?;
2634            self.expect(toks, TokInfo::Semicolon, "expected ;")?;
2635            Ok((&toks[1..], res))
2636        } else {
2637            Ok((toks, Vec::new()))
2638        }
2639    }
2640
2641    fn parse_provides(
2642        &mut self,
2643        toks: &'a [Tok<'a, 'f>],
2644    ) -> Res<'a, 'f, Vec<Spanned<'f, AbstractDecl<'a, 'f>>>> {
2645        if self.expect(toks, TokInfo::Provides, "provides").is_ok() {
2646            self.parse_many(
2647                &toks[1..],
2648                &[TokInfo::Semicolon],
2649                |s, t| {
2650                    s.expect(t, TokInfo::Provides, "").is_ok()
2651                        || s.expect(t, TokInfo::Needs, "").is_ok()
2652                        || s.expect(t, TokInfo::Body, "").is_ok()
2653                },
2654                |s, t| {
2655                    let (toks, res) = s
2656                        .parse_abstract_const(t)
2657                        .or_else(|e| choose_err(e, s.parse_abstract_node(t)))
2658                        .or_else(|e| choose_err(e, s.parse_abstract_type(t)))?;
2659                    Ok((toks, vec![res]))
2660                },
2661            )
2662        } else {
2663            Ok((toks, Vec::new()))
2664        }
2665    }
2666
2667    fn parse_abstract_const(
2668        &mut self,
2669        toks: &'a [Tok<'a, 'f>],
2670    ) -> SpannedRes<'a, 'f, AbstractDecl<'a, 'f>> {
2671        let start = &self.expect(toks, TokInfo::Const, "expected const")?.span;
2672        let (toks, name) = self.parse_id(&toks[1..])?;
2673        self.expect(toks, TokInfo::Colon, "exepected :")?;
2674        let (toks, ty) = self.parse_ty_expr(&toks[1..])?;
2675        let (toks, def) = if self.expect(toks, TokInfo::Equal, "=").is_ok() {
2676            let (toks, def) = self.parse_expr(&toks[1..])?;
2677            (toks, Some(def))
2678        } else {
2679            (toks, None)
2680        };
2681
2682        Ok((
2683            toks,
2684            Spanned::fusion(
2685                start.clone(),
2686                toks[0].span.clone(),
2687                AbstractDecl::Const { name, ty, def },
2688            ),
2689        ))
2690    }
2691
2692    fn parse_abstract_node(
2693        &mut self,
2694        toks: &'a [Tok<'a, 'f>],
2695    ) -> SpannedRes<'a, 'f, AbstractDecl<'a, 'f>> {
2696        let start = toks[0].span.clone();
2697        let is_unsafe = self.expect(toks, TokInfo::Unsafe, "unsafe").is_ok();
2698        let toks = if is_unsafe { &toks[1..] } else { toks };
2699        let is_node = self.expect(toks, TokInfo::Node, "node").is_ok();
2700        if !is_node {
2701            self.expect(toks, TokInfo::Function, "expected node or function")?;
2702        }
2703        let (toks, name) = self.parse_id(&toks[1..])?;
2704        let (toks, static_params) = if self.expect(toks, TokInfo::OpenStaticPar, "<<").is_ok() {
2705            let (toks, params) = self.parse_static_param_decl(&toks[1..])?;
2706            self.expect(toks, TokInfo::CloseStaticPar, "expected >>")?;
2707            (&toks[1..], params)
2708        } else {
2709            (toks, Vec::new())
2710        };
2711        self.expect(toks, TokInfo::OpenPar, "expected (")?;
2712        let (toks, params) = self.parse_var_decl(&toks[1..], true)?;
2713        self.expect(toks, TokInfo::ClosePar, "expected )")?;
2714        self.expect(&toks[1..], TokInfo::Returns, "expected returns")?;
2715        self.expect(&toks[2..], TokInfo::OpenPar, "expected (")?;
2716        let (toks, outputs) = self.parse_var_decl(&toks[3..], true)?;
2717        self.expect(toks, TokInfo::ClosePar, "expected )")?;
2718        Ok((
2719            &toks[1..],
2720            Spanned::fusion(
2721                start,
2722                toks[0].span.clone(),
2723                AbstractDecl::Node {
2724                    is_unsafe,
2725                    is_function: !is_node,
2726                    name,
2727                    static_params,
2728                    params,
2729                    outputs,
2730                },
2731            ),
2732        ))
2733    }
2734
2735    fn parse_abstract_type(
2736        &mut self,
2737        toks: &'a [Tok<'a, 'f>],
2738    ) -> SpannedRes<'a, 'f, AbstractDecl<'a, 'f>> {
2739        let start = &self.expect(toks, TokInfo::Type, "expected type")?.span;
2740        let (toks, (name, ty)) = match self.parse_one_type_decl(&toks[1..])? {
2741            (
2742                t,
2743                Spanned {
2744                    item: Decl::Ty { name, value },
2745                    ..
2746                },
2747            ) => (t, (name, value)),
2748            _ => unreachable!(),
2749        };
2750        Ok((
2751            toks,
2752            Spanned::fusion(
2753                start.clone(),
2754                toks[0].span.clone(),
2755                AbstractDecl::Ty { name, value: ty },
2756            ),
2757        ))
2758    }
2759
2760    fn parse_by_name_static_args(
2761        &mut self,
2762        toks: &'a [Tok<'a, 'f>],
2763    ) -> Res<'a, 'f, Vec<(Spanned<'f, Ident<'a, 'f>>, StaticArg<'a, 'f>)>> {
2764        self.parse_many(
2765            toks,
2766            &[TokInfo::Semicolon, TokInfo::Coma],
2767            |s, t| s.expect(t, TokInfo::ClosePar, ")").is_ok(),
2768            |s, t| {
2769                // TODO: handle explicit nature
2770                let (toks, name) = s.parse_id(t)?;
2771                s.expect(toks, TokInfo::Equal, "expected =")?;
2772                // for the moment we can use parse_static_arg bc it doesn't handle
2773                // explicit nature either
2774                let (toks, arg) = s.parse_static_arg(&toks[1..])?;
2775                Ok((toks, vec![(name, arg)]))
2776            },
2777        )
2778    }
2779}
2780
2781fn choose_err<'a, 'f, T>(
2782    err: Error<'a, 'f>,
2783    res: Result<T, Error<'a, 'f>>,
2784) -> Result<T, Error<'a, 'f>> {
2785    match (err, res) {
2786        (_, Ok(x)) => Ok(x),
2787        (Error::UnexpectedToken(toks1, msg1), Err(Error::UnexpectedToken(toks2, msg2))) => {
2788            if toks1.len() <= toks2.len() {
2789                Err(Error::UnexpectedToken(toks1, msg1))
2790            } else {
2791                Err(Error::UnexpectedToken(toks2, msg2))
2792            }
2793        }
2794        (e @ Error::UnexpectedToken(_, _), _) | (_, Err(e @ Error::UnexpectedToken(_, _))) => {
2795            Err(e)
2796        }
2797        (e, _) => Err(e),
2798    }
2799}