tergo_parser/
ast.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use tokenizer::{tokens::CommentedToken, tokens_buffer::TokensBuffer};

#[derive(Debug, Clone, PartialEq)]
pub enum Expression<'a> {
    Symbol(&'a CommentedToken<'a>),
    Literal(&'a CommentedToken<'a>),
    Comment(&'a CommentedToken<'a>),
    Term(Box<TermExpr<'a>>),
    Unary(&'a CommentedToken<'a>, Box<Expression<'a>>),
    Bop(
        &'a CommentedToken<'a>,
        Box<Expression<'a>>,
        Box<Expression<'a>>,
    ),
    Formula(&'a CommentedToken<'a>, Box<Expression<'a>>),
    Newline(&'a CommentedToken<'a>),
    Whitespace(&'a [&'a CommentedToken<'a>]),
    EOF(&'a CommentedToken<'a>),
    FunctionDef(FunctionDefinition<'a>),
    LambdaFunction(Lambda<'a>),
    IfExpression(IfExpression<'a>),
    WhileExpression(WhileExpression<'a>),
    RepeatExpression(RepeatExpression<'a>),
    FunctionCall(FunctionCall<'a>),
    SubsetExpression(SubsetExpression<'a>),
    ForLoopExpression(ForLoop<'a>),
    Break(&'a CommentedToken<'a>),
    Continue(&'a CommentedToken<'a>),
}

impl std::fmt::Display for Expression<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Expression::Symbol(token) => f.write_fmt(format_args!("{}", TokensBuffer(&[token]))),
            Expression::Literal(token) => f.write_fmt(format_args!("{}", TokensBuffer(&[token]))),
            Expression::Comment(token) => f.write_fmt(format_args!("{}", TokensBuffer(&[token]))),
            Expression::Term(term) => f.write_fmt(format_args!("{}", term)),
            Expression::Unary(op, expr) => f.write_fmt(format_args!("{}{}", op, expr)),
            Expression::Bop(op, left, right) => {
                f.write_fmt(format_args!("{} {} {}", left, TokensBuffer(&[op]), right))
            }
            Expression::Formula(tilde, term) => write!(f, "{} {}", tilde, term),
            Expression::Newline(token) => f.write_fmt(format_args!("{}", TokensBuffer(&[token]))),
            Expression::Whitespace(tokens) => f.write_fmt(format_args!("{}", TokensBuffer(tokens))),
            Expression::EOF(token) => f.write_fmt(format_args!("{}", TokensBuffer(&[token]))),
            Expression::FunctionDef(func_def) => f.write_fmt(format_args!("{}", func_def)),
            Expression::IfExpression(if_expression) => {
                f.write_fmt(format_args!("{}", if_expression))
            }
            Expression::WhileExpression(while_expression) => {
                f.write_fmt(format_args!("{}", while_expression))
            }
            Expression::RepeatExpression(repeat_expression) => {
                f.write_fmt(format_args!("{}", repeat_expression))
            }
            Expression::FunctionCall(function_call) => {
                f.write_fmt(format_args!("{}", function_call))
            }
            Expression::SubsetExpression(subset_expression) => {
                f.write_fmt(format_args!("{}", subset_expression))
            }
            Expression::ForLoopExpression(for_loop) => f.write_fmt(format_args!("{}", for_loop)),
            Expression::Break(token) | Expression::Continue(token) => {
                f.write_fmt(format_args!("{}", TokensBuffer(&[token])))
            }
            Expression::LambdaFunction(lambda) => f.write_fmt(format_args!("{}", lambda)),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ExpressionsBuffer<'a>(pub &'a [Expression<'a>]);
impl std::fmt::Display for ExpressionsBuffer<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Expressions: [")?;
        f.write_fmt(format_args!(
            "{}",
            self.0
                .iter()
                .map(|x| x.to_string())
                .collect::<Vec<String>>()
                .join("\n")
        ))?;
        f.write_str("]\n")
    }
}

// Term
#[derive(Debug, Clone, PartialEq)]
pub struct TermExpr<'a> {
    pub pre_delimiters: Option<&'a CommentedToken<'a>>,
    pub term: Vec<Expression<'a>>,
    pub post_delimiters: Option<&'a CommentedToken<'a>>,
}

impl<'a> TermExpr<'a> {
    pub fn new(
        pre_delimiters: Option<&'a CommentedToken<'a>>,
        term: Vec<Expression<'a>>,
        post_delimiters: Option<&'a CommentedToken<'a>>,
    ) -> Self {
        Self {
            pre_delimiters,
            term,
            post_delimiters,
        }
    }
}

impl<'a> From<Expression<'a>> for TermExpr<'a> {
    fn from(expr: Expression<'a>) -> Self {
        Self::new(None, vec![expr], None)
    }
}

impl std::fmt::Display for TermExpr<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "(TermExpr: {} {} {})",
            if let Some(pre_delim) = self.pre_delimiters {
                pre_delim.to_string()
            } else {
                "".to_string()
            },
            self.term
                .iter()
                .map(|e| format!("(expr: {})", e))
                .collect::<Vec<_>>()
                .join(" "),
            if let Some(post_delim) = self.post_delimiters {
                post_delim.to_string()
            } else {
                "".to_string()
            },
        ))
    }
}

// Function definition
// The comma is required due to the way the parser treats comments
// The formatter needs comments and some of them might end up squeezed into
// the comma token
#[derive(Debug, Clone, PartialEq)]
pub struct Arg<'a>(pub Option<Expression<'a>>, pub Option<Expression<'a>>); // Argument, comma

impl std::fmt::Display for Arg<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(ref xpr) = self.0 {
            f.write_fmt(format_args!("{}", xpr))?;
        }
        if let Some(comma) = &self.1 {
            f.write_fmt(format_args!("comma:{}", comma))?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Delimiter<'a> {
    Paren(&'a CommentedToken<'a>),
    SingleBracket(&'a CommentedToken<'a>),
    DoubleBracket((&'a CommentedToken<'a>, &'a CommentedToken<'a>)),
}

impl std::fmt::Display for Delimiter<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Delimiter::Paren(single) | Delimiter::SingleBracket(single) => {
                f.write_fmt(format_args!("{}", single))
            }
            Delimiter::DoubleBracket((b1, b2)) => f.write_fmt(format_args!("{}{}", b1, b2)),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Args<'a> {
    pub left_delimeter: Delimiter<'a>,
    pub args: Vec<Arg<'a>>,
    pub right_delimeter: Delimiter<'a>,
}

impl<'a> Args<'a> {
    pub fn new(
        left_delimeter: Delimiter<'a>,
        args: Vec<Arg<'a>>,
        right_delimeter: Delimiter<'a>,
    ) -> Self {
        Self {
            left_delimeter,
            args,
            right_delimeter,
        }
    }
}

impl std::fmt::Display for Args<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "(Args: {} {} {})",
            self.left_delimeter,
            self.args
                .iter()
                .map(|arg| arg.to_string())
                .collect::<Vec<String>>()
                .join(" "),
            self.right_delimeter,
        ))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct FunctionDefinition<'a> {
    pub keyword: &'a CommentedToken<'a>,
    pub arguments: Args<'a>,
    pub body: Box<Expression<'a>>,
}

impl<'a> FunctionDefinition<'a> {
    pub fn new(
        keyword: &'a CommentedToken<'a>,
        arguments: Args<'a>,
        body: Box<Expression<'a>>,
    ) -> Self {
        Self {
            keyword,
            arguments,
            body,
        }
    }
}

impl std::fmt::Display for FunctionDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "{} {} {}",
            self.keyword, self.arguments, self.body
        ))
    }
}

// If expression
#[derive(Debug, Clone, PartialEq)]
pub struct IfConditional<'a> {
    pub keyword: &'a CommentedToken<'a>,
    pub left_delimiter: &'a CommentedToken<'a>,
    pub condition: Box<Expression<'a>>,
    pub right_delimiter: &'a CommentedToken<'a>,
    pub body: Box<Expression<'a>>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ElseIfConditional<'a> {
    pub else_keyword: &'a CommentedToken<'a>,
    pub if_conditional: IfConditional<'a>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TrailingElse<'a> {
    pub else_keyword: &'a CommentedToken<'a>,
    pub body: Box<Expression<'a>>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IfExpression<'a> {
    pub if_conditional: IfConditional<'a>,
    pub else_ifs: Vec<ElseIfConditional<'a>>,
    pub trailing_else: Option<TrailingElse<'a>>,
}

impl std::fmt::Display for TrailingElse<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{} {}", self.else_keyword, self.body))
    }
}

impl std::fmt::Display for IfConditional<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "{} {} {} {} {}",
            self.keyword, self.left_delimiter, self.condition, self.right_delimiter, self.body
        ))
    }
}

impl std::fmt::Display for ElseIfConditional<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "{} {}",
            self.else_keyword, self.if_conditional
        ))
    }
}

impl std::fmt::Display for IfExpression<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_fmt(format_args!("{} ", self.if_conditional))?;
        for else_if in &self.else_ifs {
            f.write_fmt(format_args!("{}", else_if))?;
        }
        match &self.trailing_else {
            Some(trailing_else) => f.write_fmt(format_args!("{}", trailing_else)),
            None => Ok(()),
        }
    }
}

// While expression
#[derive(Debug, Clone, PartialEq)]
pub struct WhileExpression<'a> {
    pub while_keyword: &'a CommentedToken<'a>,
    pub condition: Box<Expression<'a>>,
    pub body: Box<Expression<'a>>,
}

impl std::fmt::Display for WhileExpression<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "({} {} {})",
            self.while_keyword, self.condition, self.body
        ))
    }
}

// Repeat expresssion
#[derive(Debug, Clone, PartialEq)]
pub struct RepeatExpression<'a> {
    pub repeat_keyword: &'a CommentedToken<'a>,
    pub body: Box<Expression<'a>>,
}

impl std::fmt::Display for RepeatExpression<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("({} {})", self.repeat_keyword, self.body))
    }
}

// Function call
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionCall<'a> {
    pub function_ref: Box<Expression<'a>>,
    pub args: Args<'a>,
}

impl std::fmt::Display for FunctionCall<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("Call({} {})", self.function_ref, self.args))
    }
}

// Subset expression
#[derive(Debug, Clone, PartialEq)]
pub struct SubsetExpression<'a> {
    pub object_ref: Box<Expression<'a>>,
    pub args: Args<'a>,
}

impl std::fmt::Display for SubsetExpression<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}{}", self.object_ref, self.args))
    }
}

// For loop
#[derive(Debug, Clone, PartialEq)]
pub struct ForLoop<'a> {
    pub keyword: &'a CommentedToken<'a>,
    pub left_delim: Delimiter<'a>,
    pub identifier: Box<Expression<'a>>,
    pub in_keyword: &'a CommentedToken<'a>,
    pub collection: Box<Expression<'a>>,
    pub right_delim: Delimiter<'a>,
    pub body: Box<Expression<'a>>,
}

impl std::fmt::Display for ForLoop<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "<{} {} {} {} {} {} {}>",
            self.keyword,
            self.left_delim,
            self.identifier,
            self.in_keyword,
            self.collection,
            self.right_delim,
            self.body
        ))
    }
}

// Lambda
#[derive(Debug, Clone, PartialEq)]
pub struct Lambda<'a> {
    pub keyword: &'a CommentedToken<'a>,
    pub args: Args<'a>,
    pub body: Box<Expression<'a>>,
}

impl std::fmt::Display for Lambda<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{} {} {}", self.keyword, self.args, self.body))
    }
}