Skip to main content

lisette_syntax/parse/
pratt.rs

1use ecow::EcoString;
2
3use super::{ParseError, Parser};
4use crate::ast;
5use crate::lex::TokenKind::{self, *};
6use crate::types::Type;
7
8const RANGE_PREC: u8 = 6;
9const CAST_PREC: u8 = 9;
10
11impl<'source> Parser<'source> {
12    /// Parses by grouping together operations in expressions based on precedence.
13    ///
14    /// 1. Parse a left-hand side expression (primary, unary, or prefix).
15    /// 2. Look for binary or postfix operators.
16    /// 3. For binary operators: If the operator's precedence is higher than `min_prec`,
17    ///    parse the right-hand side recursively with the operator's precedence.
18    /// 4. For postfix operators: Transform the current expression into a larger one.
19    ///
20    /// The `min_prec` param sets the minimum precedence level for this parsing context.
21    pub fn pratt_parse(&mut self, min_prec: u8) -> ast::Expression {
22        if !self.enter_recursion() {
23            let span = self.span_from_token(self.current_token());
24            self.resync_on_error();
25            return ast::Expression::Unit {
26                ty: Type::uninferred(),
27                span,
28            };
29        }
30
31        let start = self.current_token();
32        let mut lhs = self.parse_left_hand_side();
33        let depth_before_loop = self.depth;
34
35        while !self.at_eof() && !self.too_many_errors() {
36            if self.check_go_channel_send() {
37                self.depth = depth_before_loop;
38                self.leave_recursion();
39                return lhs;
40            }
41
42            if self.check_increment_decrement(&lhs, start.byte_offset) {
43                self.depth = depth_before_loop;
44                self.leave_recursion();
45                return lhs;
46            }
47
48            if self.at_range() && RANGE_PREC > min_prec {
49                lhs = self.parse_range(Some(lhs.into()), start);
50                continue;
51            }
52
53            if self.current_token().kind == As && CAST_PREC > min_prec {
54                self.next();
55                let target_type = self.parse_annotation();
56                lhs = ast::Expression::Cast {
57                    expression: lhs.into(),
58                    target_type,
59                    ty: Type::uninferred(),
60                    span: self.span_from_tokens(start),
61                };
62                continue;
63            }
64
65            if min_prec == 0
66                && self.current_token().kind == PipeDouble
67                && self.newline_before_current()
68            {
69                break;
70            }
71
72            if let Some(prec) = self.binary_operator_precedence(self.current_token().kind)
73                && prec > min_prec
74            {
75                let operator = self.parse_binary_operator();
76                let rhs = self.pratt_parse(prec);
77                lhs = ast::Expression::Binary {
78                    operator,
79                    left: lhs.into(),
80                    right: rhs.into(),
81                    ty: Type::uninferred(),
82                    span: self.span_from_tokens(start),
83                };
84                continue;
85            }
86
87            if self.is_postfix_operator(&lhs) {
88                if !self.enter_recursion() {
89                    break;
90                }
91                if self.is_format_string(&lhs)
92                    && (self.current_token().kind == LeftParen
93                        || self.current_token().kind == LeftSquareBracket)
94                    && self.newline_before_current()
95                {
96                    break;
97                }
98                lhs = self.include_in_larger_expression(lhs);
99                continue;
100            }
101
102            break;
103        }
104
105        self.depth = depth_before_loop;
106        self.leave_recursion();
107
108        lhs
109    }
110
111    fn prefix_operator_precedence(&self, kind: TokenKind) -> u8 {
112        match kind {
113            Minus | Bang | Caret | Ampersand => 15,
114            _ => {
115                debug_assert!(false, "unexpected prefix operator: {:?}", kind);
116                15
117            }
118        }
119    }
120
121    fn binary_operator_precedence(&self, kind: TokenKind) -> Option<u8> {
122        match kind {
123            LeftAngleBracket if self.is_type_args_call() => None,
124            Pipeline => Some(1),
125            PipeDouble if self.stream.peek_ahead(1).kind == Arrow => None,
126            PipeDouble => Some(3),
127            AmpersandDouble => Some(4),
128            EqualDouble | NotEqual | LeftAngleBracket | RightAngleBracket | LessThanOrEqual
129            | GreaterThanOrEqual => Some(5),
130            Plus | Minus | Pipe | Caret => Some(7),
131            Star | Slash | Percent | ShiftLeft | ShiftRight | Ampersand | AndNot => Some(8),
132            _ => None,
133        }
134    }
135
136    fn is_postfix_operator(&self, lhs: &ast::Expression) -> bool {
137        match self.current_token().kind {
138            LeftParen | LeftSquareBracket | QuestionMark | Dot => true,
139            LeftCurlyBrace => match lhs {
140                ast::Expression::Identifier { .. } | ast::Expression::DotAccess { .. } => {
141                    self.is_struct_instantiation()
142                }
143                _ => false,
144            },
145            LeftAngleBracket => self.is_type_args_call(),
146            Colon if self.stream.peek_ahead(1).kind == Colon => true,
147            _ => false,
148        }
149    }
150
151    fn is_format_string(&self, expression: &ast::Expression) -> bool {
152        matches!(
153            expression,
154            ast::Expression::Literal {
155                literal: ast::Literal::FormatString(_),
156                ..
157            }
158        )
159    }
160
161    fn parse_left_hand_side(&mut self) -> ast::Expression {
162        let start = self.current_token();
163
164        match start.kind {
165            Bang | Minus | Caret => {
166                self.next();
167
168                let operator = match start.kind {
169                    Bang => ast::UnaryOperator::Not,
170                    Minus => ast::UnaryOperator::Negative,
171                    Caret => ast::UnaryOperator::BitwiseNot,
172                    _ => unreachable!("guarded by match arm"),
173                };
174
175                let prec = self.prefix_operator_precedence(start.kind);
176
177                ast::Expression::Unary {
178                    operator,
179                    expression: self.pratt_parse(prec).into(),
180                    ty: Type::uninferred(),
181                    span: self.span_from_tokens(start),
182                }
183            }
184
185            Ampersand => {
186                self.next();
187                if self.current_token().kind == Mut {
188                    let span = ast::Span::new(
189                        self.file_id,
190                        start.byte_offset,
191                        self.current_token().byte_offset + self.current_token().byte_length
192                            - start.byte_offset,
193                    );
194                    self.track_error_at(
195                        span,
196                        "invalid syntax",
197                        "Lisette has no mutable references. Use `&x` instead",
198                    );
199                    self.next(); // consume `mut`
200                }
201                let prec = self.prefix_operator_precedence(start.kind);
202                ast::Expression::Reference {
203                    expression: self.pratt_parse(prec).into(),
204                    ty: Type::uninferred(),
205                    span: self.span_from_tokens(start),
206                }
207            }
208
209            _ => self.parse_atomic_expression(),
210        }
211    }
212
213    pub fn include_in_larger_expression(&mut self, lhs: ast::Expression) -> ast::Expression {
214        match self.current_token().kind {
215            LeftParen => self.parse_function_call(lhs, vec![]),
216            LeftSquareBracket => self.parse_index_expression(lhs),
217            LeftCurlyBrace => self.parse_struct_call(lhs),
218            QuestionMark => self.parse_try(lhs),
219            Dot => self.parse_field_access(lhs),
220            LeftAngleBracket => {
221                let type_args = self.parse_type_args();
222
223                if self.current_token().kind == Dot && self.stream.peek_ahead(1).kind == Identifier
224                {
225                    let type_name = match &lhs {
226                        ast::Expression::Identifier { value, .. } => value.as_str(),
227                        ast::Expression::DotAccess { member, .. } => member.as_str(),
228                        _ => "",
229                    };
230                    let method = self.stream.peek_ahead(1).text;
231                    let args_str = type_args
232                        .iter()
233                        .map(format_annotation)
234                        .collect::<Vec<_>>()
235                        .join(", ");
236                    let plural = type_args.len() != 1;
237                    let title = if plural {
238                        "Misplaced type arguments"
239                    } else {
240                        "Misplaced type argument"
241                    };
242                    let help = if !type_name.is_empty() {
243                        format!(
244                            "Set the type {} on the method: `{}.{}<{}>()`",
245                            if plural { "arguments" } else { "argument" },
246                            type_name,
247                            method,
248                            args_str,
249                        )
250                    } else {
251                        format!(
252                            "Set the type {} on the method: `.{}<{}>()`",
253                            if plural { "arguments" } else { "argument" },
254                            method,
255                            args_str,
256                        )
257                    };
258                    let Some(first) = type_args.first() else {
259                        return self.parse_function_call(lhs, type_args);
260                    };
261                    let first_span = first.get_span();
262                    let last_span = type_args.last().expect("non-empty").get_span();
263                    let span = ast::Span::new(
264                        self.file_id,
265                        first_span.byte_offset,
266                        (last_span.byte_offset + last_span.byte_length)
267                            .saturating_sub(first_span.byte_offset),
268                    );
269                    let error = ParseError::new(title, span, "misplaced")
270                        .with_parse_code("syntax_error")
271                        .with_help(help);
272                    self.errors.push(error);
273
274                    let dot_access = self.parse_field_access(lhs);
275                    return self.parse_function_call(dot_access, type_args);
276                }
277
278                self.parse_function_call(lhs, type_args)
279            }
280
281            Colon => {
282                let lhs_name = match &lhs {
283                    ast::Expression::Identifier { value, .. } => value.to_string(),
284                    ast::Expression::DotAccess { member, .. } => member.to_string(),
285                    _ => std::string::String::new(),
286                };
287                let colon_token = self.current_token();
288                let span = ast::Span::new(self.file_id, colon_token.byte_offset, 2);
289                let after = self.stream.peek_ahead(2);
290
291                if after.kind == LeftAngleBracket {
292                    let help = if !lhs_name.is_empty() {
293                        format!(
294                            "Lisette does not use turbofish syntax. Use `{}<T>(...)` instead",
295                            lhs_name
296                        )
297                    } else {
298                        "Lisette does not use turbofish syntax. Use `func<T>(...)` instead"
299                            .to_string()
300                    };
301                    self.track_error_at(span, "invalid syntax", help);
302                    self.next(); // consume first `:`
303                    self.next(); // consume second `:`
304                    let type_args = self.parse_type_args();
305                    self.parse_function_call(lhs, type_args)
306                } else {
307                    let help = if !lhs_name.is_empty() && after.kind == Identifier {
308                        format!(
309                            "Use `.` instead of `::` for enum variant access, e.g. `{}.{}`",
310                            lhs_name, after.text
311                        )
312                    } else {
313                        "Use `.` instead of `::` for enum variant access".to_string()
314                    };
315                    self.track_error_at(span, "invalid syntax", help);
316                    self.next(); // consume first `:`
317                    self.next(); // consume second `:`
318                    let field_start = self.current_token();
319                    let field: EcoString = self.current_token().text.into();
320                    self.ensure(Identifier);
321                    ast::Expression::DotAccess {
322                        ty: Type::uninferred(),
323                        expression: lhs.into(),
324                        member: field,
325                        span: self.span_from_tokens(field_start),
326                        dot_access_kind: None,
327                        receiver_coercion: None,
328                    }
329                }
330            }
331
332            _ => {
333                debug_assert!(
334                    false,
335                    "is_postfix_operator and include_in_larger_expression are out of sync"
336                );
337                self.track_error("internal error", "Unexpected token in postfix position");
338                self.resync_on_error();
339                lhs
340            }
341        }
342    }
343
344    pub fn parse_range_end(&mut self) -> ast::Expression {
345        self.pratt_parse(RANGE_PREC)
346    }
347
348    fn check_go_channel_send(&mut self) -> bool {
349        if self.current_token().kind != LeftAngleBracket {
350            return false;
351        }
352        let next = self.stream.peek_ahead(1);
353        if next.kind != Minus {
354            return false;
355        }
356        let current = self.current_token();
357        if current.byte_offset + current.byte_length != next.byte_offset {
358            return false;
359        }
360
361        let span = ast::Span::new(
362            self.file_id,
363            self.current_token().byte_offset,
364            self.current_token().byte_length + 1,
365        );
366        self.track_error_at(
367            span,
368            "invalid syntax",
369            "Use `ch.Send(value)` inside a `select` expression",
370        );
371        self.resync_on_error();
372        true
373    }
374
375    fn check_increment_decrement(&mut self, lhs: &ast::Expression, start_offset: u32) -> bool {
376        let current = self.current_token();
377        let kind = current.kind;
378        if kind != Plus && kind != Minus {
379            return false;
380        }
381        let next = self.stream.peek_ahead(1);
382        if next.kind != kind {
383            return false;
384        }
385        if current.byte_offset + current.byte_length != next.byte_offset {
386            return false;
387        }
388        if !self.is_valid_assignment_target(lhs) {
389            return false;
390        }
391
392        let mut ahead = 2;
393        while matches!(self.stream.peek_ahead(ahead).kind, Comment | DocComment) {
394            ahead += 1;
395        }
396        let after = self.stream.peek_ahead(ahead);
397        let newline_after = {
398            let from = (next.byte_offset + next.byte_length) as usize;
399            let to = after.byte_offset as usize;
400            from <= to && to <= self.source.len() && self.source[from..to].contains('\n')
401        };
402        let ends_statement = newline_after
403            || matches!(
404                after.kind,
405                EOF | Semicolon | RightCurlyBrace | RightParen | RightSquareBracket | Comma
406            )
407            || (after.kind == LeftCurlyBrace && self.in_control_flow_header);
408        if !ends_statement {
409            return false;
410        }
411
412        let (operator, compound) = if kind == Plus {
413            ("++", "+= 1")
414        } else {
415            ("--", "-= 1")
416        };
417        let span = ast::Span::new(self.file_id, current.byte_offset, 2);
418        let target = self.source[start_offset as usize..current.byte_offset as usize].trim_end();
419        let help = format!("Use `{target} {compound}` instead");
420        self.track_error_at(span, format!("Lisette has no `{operator}` operator"), help);
421        self.next();
422        self.next();
423        true
424    }
425}
426
427fn format_annotation(ann: &ast::Annotation) -> std::string::String {
428    match ann {
429        ast::Annotation::Constructor { name, params, .. } => {
430            if params.is_empty() {
431                name.to_string()
432            } else {
433                format!(
434                    "{}<{}>",
435                    name,
436                    params
437                        .iter()
438                        .map(format_annotation)
439                        .collect::<Vec<_>>()
440                        .join(", ")
441                )
442            }
443        }
444        ast::Annotation::Tuple { elements, .. } => {
445            format!(
446                "({})",
447                elements
448                    .iter()
449                    .map(format_annotation)
450                    .collect::<Vec<_>>()
451                    .join(", ")
452            )
453        }
454        ast::Annotation::Function {
455            params,
456            param_mutability,
457            return_type,
458            ..
459        } => {
460            format!(
461                "fn({}) -> {}",
462                params
463                    .iter()
464                    .enumerate()
465                    .map(|(index, param)| {
466                        let rendered = format_annotation(param);
467                        if param_mutability.get(index).copied().unwrap_or(false) {
468                            format!("mut {}", rendered)
469                        } else {
470                            rendered
471                        }
472                    })
473                    .collect::<Vec<_>>()
474                    .join(", "),
475                format_annotation(return_type)
476            )
477        }
478        ast::Annotation::Constant { value, text, .. } => {
479            text.clone().unwrap_or_else(|| value.to_string())
480        }
481        ast::Annotation::Unknown | ast::Annotation::Opaque { .. } => "_".to_string(),
482    }
483}