lisette-syntax 0.1.14

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

use super::{ParseError, Parser};
use crate::ast;
use crate::lex::TokenKind::{self, *};
use crate::types::Type;

const RANGE_PREC: u8 = 6;
const CAST_PREC: u8 = 9;

impl<'source> Parser<'source> {
    /// Parses by grouping together operations in expressions based on precedence.
    ///
    /// 1. Parse a left-hand side expression (primary, unary, or prefix).
    /// 2. Look for binary or postfix operators.
    /// 3. For binary operators: If the operator's precedence is higher than `min_prec`,
    ///    parse the right-hand side recursively with the operator's precedence.
    /// 4. For postfix operators: Transform the current expression into a larger one.
    ///
    /// The `min_prec` param sets the minimum precedence level for this parsing context.
    pub fn pratt_parse(&mut self, min_prec: u8) -> ast::Expression {
        if !self.enter_recursion() {
            let span = self.span_from_token(self.current_token());
            self.resync_on_error();
            return ast::Expression::Unit {
                ty: Type::uninferred(),
                span,
            };
        }

        let start = self.current_token();
        let mut lhs = self.parse_left_hand_side();
        let depth_before_loop = self.depth;

        while !self.at_eof() && !self.too_many_errors() {
            if self.check_go_channel_send() {
                self.depth = depth_before_loop;
                self.leave_recursion();
                return lhs;
            }

            if self.at_range() && RANGE_PREC > min_prec {
                lhs = self.parse_range(Some(lhs.into()), start);
                continue;
            }

            if self.current_token().kind == As && CAST_PREC > min_prec {
                self.next();
                let target_type = self.parse_annotation();
                lhs = ast::Expression::Cast {
                    expression: lhs.into(),
                    target_type,
                    ty: Type::uninferred(),
                    span: self.span_from_tokens(start),
                };
                continue;
            }

            if min_prec == 0
                && self.current_token().kind == PipeDouble
                && self.newline_before_current()
            {
                break;
            }

            if let Some(prec) = self.binary_operator_precedence(self.current_token().kind)
                && prec > min_prec
            {
                let operator = self.parse_binary_operator();
                let rhs = self.pratt_parse(prec);
                lhs = ast::Expression::Binary {
                    operator,
                    left: lhs.into(),
                    right: rhs.into(),
                    ty: Type::uninferred(),
                    span: self.span_from_tokens(start),
                };
                continue;
            }

            if self.is_postfix_operator(&lhs) {
                if !self.enter_recursion() {
                    break;
                }
                if self.is_format_string(&lhs)
                    && (self.current_token().kind == LeftParen
                        || self.current_token().kind == LeftSquareBracket)
                    && self.newline_before_current()
                {
                    break;
                }
                lhs = self.include_in_larger_expression(lhs);
                continue;
            }

            if matches!(self.current_token().kind, Ampersand | Pipe | Caret)
                && !self.newline_before_current()
            {
                let op_token = self.current_token();
                let span = self.span_from_token(op_token);
                let error = ParseError::new(
                    "Unsupported operator",
                    span,
                    format!("`{}` is not a supported binary operator", op_token.text),
                )
                .with_help("Lisette does not support bitwise operators")
                .with_parse_code("unsupported_operator");
                self.errors.push(error);
                self.next();
                let _rhs = self.pratt_parse(min_prec);
                continue;
            }

            break;
        }

        self.depth = depth_before_loop;
        self.leave_recursion();

        lhs
    }

    fn prefix_operator_precedence(&self, kind: TokenKind) -> u8 {
        match kind {
            Minus | Bang | Ampersand => 15,
            _ => {
                debug_assert!(false, "unexpected prefix operator: {:?}", kind);
                15
            }
        }
    }

    fn binary_operator_precedence(&self, kind: TokenKind) -> Option<u8> {
        match kind {
            LeftAngleBracket if self.is_type_args_call() => None,
            Pipeline => Some(1),
            PipeDouble if self.stream.peek_ahead(1).kind == Arrow => None,
            PipeDouble => Some(3),
            AmpersandDouble => Some(4),
            EqualDouble | NotEqual | LeftAngleBracket | RightAngleBracket | LessThanOrEqual
            | GreaterThanOrEqual => Some(5),
            Plus | Minus => Some(7),
            Star | Slash | Percent => Some(8),
            _ => None,
        }
    }

    fn is_postfix_operator(&self, lhs: &ast::Expression) -> bool {
        match self.current_token().kind {
            LeftParen | LeftSquareBracket | QuestionMark | Dot => true,
            LeftCurlyBrace => match lhs {
                ast::Expression::Identifier { .. } | ast::Expression::DotAccess { .. } => {
                    self.is_struct_instantiation()
                }
                _ => false,
            },
            LeftAngleBracket => self.is_type_args_call(),
            Colon if self.stream.peek_ahead(1).kind == Colon => true,
            _ => false,
        }
    }

    fn is_format_string(&self, expression: &ast::Expression) -> bool {
        matches!(
            expression,
            ast::Expression::Literal {
                literal: ast::Literal::FormatString(_),
                ..
            }
        )
    }

    fn parse_left_hand_side(&mut self) -> ast::Expression {
        let start = self.current_token();

        match start.kind {
            Bang | Minus => {
                self.next();

                let operator = if start.kind == Bang {
                    ast::UnaryOperator::Not
                } else {
                    ast::UnaryOperator::Negative
                };

                let prec = self.prefix_operator_precedence(start.kind);

                ast::Expression::Unary {
                    operator,
                    expression: self.pratt_parse(prec).into(),
                    ty: Type::uninferred(),
                    span: self.span_from_tokens(start),
                }
            }

            Ampersand => {
                self.next();
                if self.current_token().kind == Mut {
                    let span = ast::Span::new(
                        self.file_id,
                        start.byte_offset,
                        self.current_token().byte_offset + self.current_token().byte_length
                            - start.byte_offset,
                    );
                    self.track_error_at(
                        span,
                        "invalid syntax",
                        "Lisette has no mutable references. Use `&x` instead",
                    );
                    self.next(); // consume `mut`
                }
                let prec = self.prefix_operator_precedence(start.kind);
                ast::Expression::Reference {
                    expression: self.pratt_parse(prec).into(),
                    ty: Type::uninferred(),
                    span: self.span_from_tokens(start),
                }
            }

            _ => self.parse_atomic_expression(),
        }
    }

    pub fn include_in_larger_expression(&mut self, lhs: ast::Expression) -> ast::Expression {
        match self.current_token().kind {
            LeftParen => self.parse_function_call(lhs, vec![]),
            LeftSquareBracket => self.parse_index_expression(lhs),
            LeftCurlyBrace => self.parse_struct_call(lhs),
            QuestionMark => self.parse_try(lhs),
            Dot => self.parse_field_access(lhs),
            LeftAngleBracket => {
                let type_args = self.parse_type_args();

                if self.current_token().kind == Dot && self.stream.peek_ahead(1).kind == Identifier
                {
                    let type_name = match &lhs {
                        ast::Expression::Identifier { value, .. } => value.as_str(),
                        ast::Expression::DotAccess { member, .. } => member.as_str(),
                        _ => "",
                    };
                    let method = self.stream.peek_ahead(1).text;
                    let args_str = type_args
                        .iter()
                        .map(format_annotation)
                        .collect::<Vec<_>>()
                        .join(", ");
                    let plural = type_args.len() != 1;
                    let title = if plural {
                        "Misplaced type arguments"
                    } else {
                        "Misplaced type argument"
                    };
                    let help = if !type_name.is_empty() {
                        format!(
                            "Set the type {} on the method: `{}.{}<{}>()`",
                            if plural { "arguments" } else { "argument" },
                            type_name,
                            method,
                            args_str,
                        )
                    } else {
                        format!(
                            "Set the type {} on the method: `.{}<{}>()`",
                            if plural { "arguments" } else { "argument" },
                            method,
                            args_str,
                        )
                    };
                    let Some(first) = type_args.first() else {
                        return self.parse_function_call(lhs, type_args);
                    };
                    let first_span = first.get_span();
                    let last_span = type_args.last().expect("non-empty").get_span();
                    let span = ast::Span::new(
                        self.file_id,
                        first_span.byte_offset,
                        (last_span.byte_offset + last_span.byte_length)
                            .saturating_sub(first_span.byte_offset),
                    );
                    let error = ParseError::new(title, span, "misplaced")
                        .with_parse_code("syntax_error")
                        .with_help(help);
                    self.errors.push(error);

                    let dot_access = self.parse_field_access(lhs);
                    return self.parse_function_call(dot_access, type_args);
                }

                self.parse_function_call(lhs, type_args)
            }

            Colon => {
                let lhs_name = match &lhs {
                    ast::Expression::Identifier { value, .. } => value.to_string(),
                    ast::Expression::DotAccess { member, .. } => member.to_string(),
                    _ => std::string::String::new(),
                };
                let colon_token = self.current_token();
                let span = ast::Span::new(self.file_id, colon_token.byte_offset, 2);
                let after = self.stream.peek_ahead(2);

                if after.kind == LeftAngleBracket {
                    let help = if !lhs_name.is_empty() {
                        format!(
                            "Lisette does not use turbofish syntax. Use `{}<T>(...)` instead",
                            lhs_name
                        )
                    } else {
                        "Lisette does not use turbofish syntax. Use `func<T>(...)` instead"
                            .to_string()
                    };
                    self.track_error_at(span, "invalid syntax", help);
                    self.next(); // consume first `:`
                    self.next(); // consume second `:`
                    let type_args = self.parse_type_args();
                    self.parse_function_call(lhs, type_args)
                } else {
                    let help = if !lhs_name.is_empty() && after.kind == Identifier {
                        format!(
                            "Use `.` instead of `::` for enum variant access, e.g. `{}.{}`",
                            lhs_name, after.text
                        )
                    } else {
                        "Use `.` instead of `::` for enum variant access".to_string()
                    };
                    self.track_error_at(span, "invalid syntax", help);
                    self.next(); // consume first `:`
                    self.next(); // consume second `:`
                    let field_start = self.current_token();
                    let field: EcoString = self.current_token().text.into();
                    self.ensure(Identifier);
                    ast::Expression::DotAccess {
                        ty: Type::uninferred(),
                        expression: lhs.into(),
                        member: field,
                        span: self.span_from_tokens(field_start),
                    }
                }
            }

            _ => {
                debug_assert!(
                    false,
                    "is_postfix_operator and include_in_larger_expression are out of sync"
                );
                self.track_error("internal error", "Unexpected token in postfix position");
                self.resync_on_error();
                lhs
            }
        }
    }

    pub fn parse_range_end(&mut self) -> ast::Expression {
        self.pratt_parse(RANGE_PREC)
    }

    fn check_go_channel_send(&mut self) -> bool {
        if self.current_token().kind != LeftAngleBracket {
            return false;
        }
        let next = self.stream.peek_ahead(1);
        if next.kind != Minus {
            return false;
        }
        let current = self.current_token();
        if current.byte_offset + current.byte_length != next.byte_offset {
            return false;
        }

        let span = ast::Span::new(
            self.file_id,
            self.current_token().byte_offset,
            self.current_token().byte_length + 1,
        );
        self.track_error_at(
            span,
            "invalid syntax",
            "Use `ch.Send(value)` inside a `select` expression",
        );
        self.resync_on_error();
        true
    }
}

fn format_annotation(ann: &ast::Annotation) -> std::string::String {
    match ann {
        ast::Annotation::Constructor { name, params, .. } => {
            if params.is_empty() {
                name.to_string()
            } else {
                format!(
                    "{}<{}>",
                    name,
                    params
                        .iter()
                        .map(format_annotation)
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
        }
        ast::Annotation::Tuple { elements, .. } => {
            format!(
                "({})",
                elements
                    .iter()
                    .map(format_annotation)
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
        ast::Annotation::Function {
            params,
            return_type,
            ..
        } => {
            format!(
                "fn({}) -> {}",
                params
                    .iter()
                    .map(format_annotation)
                    .collect::<Vec<_>>()
                    .join(", "),
                format_annotation(return_type)
            )
        }
        ast::Annotation::Unknown | ast::Annotation::Opaque { .. } => "_".to_string(),
    }
}