lisette-syntax 0.12.2

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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
use ecow::EcoString;

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

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

#[derive(Clone, Copy)]
pub(super) enum ExpressionContext {
    Normal,
    ControlFlowHeader,
}

impl ExpressionContext {
    pub(super) fn is_control_flow_header(self) -> bool {
        matches!(self, Self::ControlFlowHeader)
    }
}

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(super) fn pratt_parse(
        &mut self,
        min_prec: u8,
        context: ExpressionContext,
    ) -> ast::Expression {
        if let Some(result) =
            self.with_recursion(|parser| parser.pratt_parse_inner(min_prec, context))
        {
            return result;
        }
        let span = self.span_from_token(self.current_token());
        self.resync_on_error();
        Self::error_expression(span)
    }

    fn pratt_parse_inner(&mut self, min_prec: u8, context: ExpressionContext) -> ast::Expression {
        let start = self.current_token();
        let mut lhs = self.parse_left_hand_side(context);

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

            if self.check_increment_decrement(&lhs, start.byte_offset, context) {
                return lhs;
            }

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

            if self.current_token().kind == As && CAST_PREC > min_prec {
                if !self.deepen() {
                    break;
                }
                self.next();
                let target_type = self.parse_annotation();
                lhs = ast::Expression::Cast {
                    expression: lhs.into(),
                    target_type,
                    ty: Type::uninferred(),
                    span: self.span_from_offset(start.byte_offset),
                };
                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
            {
                if !self.deepen() {
                    break;
                }
                let operator = self.parse_binary_operator();
                let rhs = self.pratt_parse(prec, context);
                lhs = ast::Expression::Binary {
                    operator,
                    left: lhs.into(),
                    right: rhs.into(),
                    ty: Type::uninferred(),
                    span: self.span_from_offset(start.byte_offset),
                };
                continue;
            }

            if self.is_postfix_operator(&lhs, context) {
                if !self.deepen() {
                    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;
            }

            break;
        }

        lhs
    }

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

    fn binary_operator_precedence(&self, kind: TokenKind) -> Option<u8> {
        match kind {
            LeftAngleBracket if self.opens_type_args() => 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 | Pipe | Caret => Some(7),
            Star | Slash | Percent | ShiftLeft | ShiftRight | Ampersand | AndNot => Some(8),
            _ => None,
        }
    }

    fn is_postfix_operator(&self, lhs: &ast::Expression, context: ExpressionContext) -> bool {
        match self.current_token().kind {
            LeftParen | LeftSquareBracket | QuestionMark | Dot => true,
            LeftCurlyBrace => match lhs {
                ast::Expression::Identifier { .. } | ast::Expression::DotAccess { .. } => {
                    self.is_struct_instantiation(context)
                }
                _ => false,
            },
            LeftAngleBracket => self.opens_type_args(),
            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, context: ExpressionContext) -> ast::Expression {
        let start = self.current_token();

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

                let operator = match start.kind {
                    Bang => ast::UnaryOperator::Not,
                    Minus => ast::UnaryOperator::Negative,
                    Caret => ast::UnaryOperator::BitwiseNot,
                    _ => unreachable!("guarded by match arm"),
                };

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

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

            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, context).into(),
                    ty: Type::uninferred(),
                    span: self.span_from_offset(start.byte_offset),
                }
            }

            _ => self.parse_atomic_expression(context),
        }
    }

    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, format!("belongs on `{}`", method))
                        .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);
                }

                if !self.is(LeftParen) {
                    return self.recover_call_missing_parens(lhs, 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(),
                    _ => 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 {
                    self.next(); // consume first `:`
                    self.next(); // consume second `:`
                    let type_args = self.parse_type_args();

                    if self.at_turbofish_method() {
                        return self.recover_turbofish_method(lhs, type_args, &lhs_name, span);
                    }

                    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.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.recover_double_colon_access(lhs)
                }
            }

            _ => {
                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
            }
        }
    }

    fn at_turbofish_method(&self) -> bool {
        self.is(Colon)
            && self.stream.peek_ahead(1).kind == Colon
            && self.stream.peek_ahead(2).kind == Identifier
    }

    fn recover_turbofish_method(
        &mut self,
        lhs: ast::Expression,
        type_args: Vec<ast::Annotation>,
        lhs_name: &str,
        span: ast::Span,
    ) -> ast::Expression {
        let method = self.stream.peek_ahead(2).text;
        let args = type_args
            .iter()
            .map(format_annotation)
            .collect::<Vec<_>>()
            .join(", ");
        let help = format!(
            "Lisette does not use turbofish syntax. Use `{}.{}<{}>()` instead",
            lhs_name, method, args
        );
        self.track_error_at(span, "invalid syntax", help);

        let dot_access = self.recover_double_colon_access(lhs);

        self.parse_function_call(dot_access, type_args)
    }

    fn recover_double_colon_access(&mut self, lhs: ast::Expression) -> ast::Expression {
        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_offset(field_start.byte_offset),
            resolution: DotAccessResolution::Unresolved,
        }
    }

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

    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 check_increment_decrement(
        &mut self,
        lhs: &ast::Expression,
        start_offset: u32,
        context: ExpressionContext,
    ) -> bool {
        let current = self.current_token();
        let kind = current.kind;
        if kind != Plus && kind != Minus {
            return false;
        }
        let next = self.stream.peek_ahead(1);
        if next.kind != kind {
            return false;
        }
        if current.byte_offset + current.byte_length != next.byte_offset {
            return false;
        }
        if !self.is_valid_assignment_target(lhs) {
            return false;
        }

        let mut ahead = 2;
        while matches!(
            self.stream.peek_ahead(ahead).kind,
            Comment | DocComment | FileComment
        ) {
            ahead += 1;
        }
        let after = self.stream.peek_ahead(ahead);
        let newline_after = {
            let from = (next.byte_offset + next.byte_length) as usize;
            let to = after.byte_offset as usize;
            from <= to && to <= self.source.len() && self.source[from..to].contains('\n')
        };
        let ends_statement = newline_after
            || matches!(
                after.kind,
                EOF | Semicolon | RightCurlyBrace | RightParen | RightSquareBracket | Comma
            )
            || (after.kind == LeftCurlyBrace && context.is_control_flow_header());
        if !ends_statement {
            return false;
        }

        let (operator, compound) = if kind == Plus {
            ("++", "+= 1")
        } else {
            ("--", "-= 1")
        };
        let span = ast::Span::new(self.file_id, current.byte_offset, 2);
        let target = self.source[start_offset as usize..current.byte_offset as usize].trim_end();
        let help = format!("Use `{target} {compound}` instead");
        self.track_error_at(span, format!("Lisette has no `{operator}` operator"), help);
        self.next();
        self.next();
        true
    }
}

fn format_annotation(ann: &ast::Annotation) -> string::String {
    match ann {
        ast::Annotation::Constructor {
            name,
            params,
            writable,
            ..
        } => {
            let rendered = if params.is_empty() {
                name.to_string()
            } else {
                format!(
                    "{}<{}>",
                    name,
                    params
                        .iter()
                        .map(format_annotation)
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };
            if *writable {
                format!("mut {}", rendered)
            } else {
                rendered
            }
        }
        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::Constant { value, text, .. } => {
            text.clone().unwrap_or_else(|| value.to_string())
        }
        ast::Annotation::Unknown | ast::Annotation::Opaque { .. } => "_".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use crate::ast::Expression;
    use crate::parse::{MAX_DEPTH, Parser};

    fn depth(expression: &Expression) -> u32 {
        1 + expression
            .children()
            .into_iter()
            .map(depth)
            .max()
            .unwrap_or(0)
    }

    fn parse_bounded(source: &str) -> u32 {
        let result = Parser::lex_and_parse_file(source, 0);
        assert!(result.has_errors(), "expected a nesting error");
        result.ast.iter().map(depth).max().unwrap_or(0)
    }

    #[test]
    fn long_pipeline_chain_stays_shallow() {
        let source = format!("pub const x = a{}", " |> f".repeat(500));
        assert!(parse_bounded(&source) <= MAX_DEPTH);
    }

    #[test]
    fn long_binary_chain_stays_shallow() {
        let source = format!("pub const x: int = 1{}", " + 1".repeat(500));
        assert!(parse_bounded(&source) <= MAX_DEPTH);
    }

    #[test]
    fn long_cast_chain_stays_shallow() {
        let source = format!("pub const x = 1{}", " as int".repeat(500));
        assert!(parse_bounded(&source) <= MAX_DEPTH);
    }

    #[test]
    fn long_range_chain_stays_shallow() {
        let source = format!("pub const x = 1{}", "..2".repeat(500));
        assert!(parse_bounded(&source) <= MAX_DEPTH);
    }
}