lisette-syntax 0.12.4

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
use super::{MAX_TUPLE_ARITY, ParamMode, Parser};
use crate::EcoString;
use crate::ast::{
    Annotation, Attribute, Expression, FunctionBody, Generic, Literal, Span, Visibility,
};
use crate::lex::Token;
use crate::lex::TokenKind::*;
use crate::types::Type;
use std::string;

impl<'source> Parser<'source> {
    pub(crate) fn parse_annotation(&mut self) -> Annotation {
        if let Some(result) = self.with_recursion(Parser::parse_annotation_inner) {
            return result;
        }
        self.resync_on_error();
        Annotation::Unknown
    }

    fn parse_annotation_inner(&mut self) -> Annotation {
        if self.at_recovery_boundary() {
            self.track_error("expected a type", "Add the missing type");
            return Annotation::Unknown;
        }

        if self.is(Mut) {
            return self.parse_writable_annotation();
        }

        match self.current_token().kind {
            Function if self.stream.peek_ahead(1).kind == LeftParen => {
                self.parse_function_annotation()
            }
            Function => {
                let start = self.current_token();
                self.track_error(
                    "incomplete function type",
                    "A function type is written `fn(int) -> int`",
                );
                self.next();
                let return_type = self.parse_function_return_annotation();
                Annotation::Function {
                    params: vec![],
                    return_type: return_type.into(),
                    span: self.span_from_offset(start.byte_offset),
                }
            }
            LeftParen => self.parse_tuple_annotation(),
            LeftSquareBracket => {
                let start = self.current_token();
                self.next();
                if self.advance_if(RightSquareBracket) {
                    let type_token = self.current_token();
                    let type_name = if type_token.kind == Identifier {
                        type_token.text.to_string()
                    } else {
                        "T".to_string()
                    };
                    let span_end = if type_token.kind == Identifier {
                        type_token.byte_offset + type_token.byte_length
                    } else {
                        start.byte_offset + 2
                    };
                    let error_span = Span::new(
                        self.file_id,
                        start.byte_offset,
                        span_end - start.byte_offset,
                    );
                    self.track_error_at(
                        error_span,
                        "invalid syntax for `Slice`",
                        format!("Use `Slice<{}>` instead of `[]{}`", type_name, type_name),
                    );
                    if self.current_token().kind == Identifier {
                        return self.parse_named_annotation();
                    }
                    return Annotation::Constructor {
                        name: "Slice".into(),
                        params: vec![],
                        writable: false,
                        mut_span: None,
                        span: error_span,
                    };
                }
                let span = self.span_from_offset(start.byte_offset);
                self.track_error("unexpected `[` in type", "Use `Slice<T>` for slice types.");
                Annotation::Constructor {
                    name: "".into(),
                    params: vec![],
                    writable: false,
                    mut_span: None,
                    span,
                }
            }
            Integer => self.parse_constant_annotation(),
            _ => self.parse_named_annotation(),
        }
    }

    fn parse_constant_annotation(&mut self) -> Annotation {
        let token = self.current_token();
        let span = Span::new(self.file_id, token.byte_offset, token.byte_length);
        let (value, text) = match self.parse_integer_text(token.text) {
            Literal::Integer { value, text } => (value, text),
            _ => (0, None),
        };
        self.next();
        Annotation::Constant { value, text, span }
    }

    fn parse_writable_annotation(&mut self) -> Annotation {
        let mut_token = self.current_token();
        let mut_span = Span::new(self.file_id, mut_token.byte_offset, mut_token.byte_length);
        self.next();
        while self.is(Mut) {
            self.track_error("duplicate `mut` qualifier", "Write `mut` once.");
            self.next();
        }
        let inner = self.parse_annotation_inner();
        match inner {
            Annotation::Constructor {
                name,
                params,
                writable: _,
                mut_span: _,
                span,
            } => Annotation::Constructor {
                name,
                params,
                writable: true,
                mut_span: Some(mut_span),
                span,
            },
            other => {
                self.track_error_at(
                    mut_span,
                    "`mut` does not apply to this type",
                    "Write `mut` on the reference type it protects, as in `mut Slice<int>`. \
                     A tuple or function type cannot carry it.",
                );
                other
            }
        }
    }

    fn parse_named_annotation(&mut self) -> Annotation {
        let start = self.current_token();
        let name = self.read_identifier_sequence();

        if self.advance_if(LeftAngleBracket) {
            let mut type_params = vec![];

            // A type-arg is a type or an integer size (the `N` in `Array<T, N>`).
            while self.can_start_annotation() || self.at_size_position_value() {
                if self.can_start_annotation() {
                    type_params.push(self.parse_annotation());
                } else {
                    type_params.push(self.parse_size_type_arg());
                }
                match self.current_token().kind {
                    RightAngleBracket | ShiftRight => break,
                    Comma => self.next(),
                    _ => break,
                }
                if self.is_right_angle_like() {
                    self.track_error("expected type", "Add a type or remove the trailing comma.");
                }
            }

            if !self.advance_if_right_angle() {
                self.track_error("expected `>`", "Add `>` to close the type arguments.");
            }

            return Annotation::Constructor {
                name,
                params: type_params,
                writable: false,
                mut_span: None,
                span: self.span_from_offset(start.byte_offset),
            };
        }

        if matches!(self.current_token().kind, LeftParen | LeftSquareBracket) {
            return self.parse_misdelimited_type_args(name, start);
        }

        Annotation::Constructor {
            name,
            params: vec![],
            writable: false,
            mut_span: None,
            span: self.span_from_offset(start.byte_offset),
        }
    }

    fn parse_misdelimited_type_args(
        &mut self,
        name: EcoString,
        start: Token<'source>,
    ) -> Annotation {
        let open = self.current_token();
        let close_kind = if open.kind == LeftParen {
            RightParen
        } else {
            RightSquareBracket
        };
        let open_end = (open.byte_offset + open.byte_length) as usize;
        self.next();

        let mut type_params = vec![];
        while self.current_token().kind != close_kind && !self.at_eof() {
            if !self.can_start_annotation() {
                break;
            }
            type_params.push(self.parse_annotation());
            if !self.advance_if(Comma) {
                break;
            }
        }

        while self.current_token().kind != close_kind && !self.at_eof() {
            self.next();
        }

        let close = self.current_token();
        let close_start = close.byte_offset as usize;
        let consumed = self.advance_if(close_kind);
        let close_end = if consumed {
            (close.byte_offset + close.byte_length) as usize
        } else {
            close_start
        };

        let inner = self.source[open_end..close_start].trim();
        let corrected = format!("{}<{}>", name, inner);
        let original = &self.source[start.byte_offset as usize..close_end];

        let label_span = Span::new(
            self.file_id,
            open.byte_offset,
            (close_end as u32).saturating_sub(open.byte_offset),
        );
        self.error_angle_brackets_for_generics(
            label_span,
            format!("Write `{corrected}` instead of `{original}`"),
        );

        Annotation::Constructor {
            name,
            params: type_params,
            writable: false,
            mut_span: None,
            span: self.span_from_offset(start.byte_offset),
        }
    }

    /// A value literal where an `Array` size goes. Non-integers are matched too,
    /// so `parse_size_type_arg` can reject them with one clear error.
    pub(crate) fn at_size_position_value(&self) -> bool {
        matches!(
            self.current_token().kind,
            Integer | Float | String | RawString | Char | Boolean | Imaginary | Minus | Plus
        )
    }

    /// Parse an `Array` size. Only an integer literal is valid, anything else
    /// gets one clear error instead of derailing into a parse cascade.
    pub(crate) fn parse_size_type_arg(&mut self) -> Annotation {
        let start = self.current_token();
        if start.kind == Integer {
            return self.parse_constant_annotation();
        }

        // A signed number is two tokens, so consume both to keep `<...>` closing.
        self.next();
        if matches!(start.kind, Minus | Plus)
            && matches!(self.current_token().kind, Integer | Float)
        {
            self.next();
        }
        self.track_error_at(
            self.span_from_offset(start.byte_offset),
            "Array size must be an integer literal",
            "Array sizes are whole numbers, e.g. `Array<string, 3>`",
        );
        Annotation::Unknown
    }

    fn parse_function_annotation(&mut self) -> Annotation {
        let start = self.current_token();
        self.ensure(Function);
        self.ensure(LeftParen);

        let mut params = vec![];

        while self.is_not(RightParen) && !self.at_recovery_boundary() {
            let start_position = self.stream.position;
            params.push(self.parse_annotation());
            if self.at_recovery_boundary() {
                break;
            }
            self.expect_comma_or(RightParen);
            self.ensure_progress(start_position, RightParen);
        }

        self.ensure_in_place(RightParen);

        let return_type = self.parse_function_return_annotation();

        Annotation::Function {
            params,
            return_type: return_type.into(),
            span: self.span_from_offset(start.byte_offset),
        }
    }

    fn parse_tuple_annotation(&mut self) -> Annotation {
        let start = self.current_token();
        self.ensure(LeftParen);

        let mut annotations = vec![];
        let mut has_trailing_comma = false;

        while self.is_not(RightParen) && !self.at_recovery_boundary() {
            let start_position = self.stream.position;
            annotations.push(self.parse_annotation());
            has_trailing_comma = self.is(Comma);
            if self.at_recovery_boundary() {
                break;
            }
            self.expect_comma_or(RightParen);
            self.ensure_progress(start_position, RightParen);
        }

        self.ensure_in_place(RightParen);

        let span = self.span_from_offset(start.byte_offset);

        if annotations.is_empty() {
            return Annotation::unit();
        }

        if annotations.len() == 1 {
            if has_trailing_comma {
                self.error_tuple_arity(1, span);
            }
            return annotations.into_iter().next().expect("len is 1");
        }

        if annotations.len() > MAX_TUPLE_ARITY {
            self.error_tuple_arity(annotations.len(), span);
        }

        Annotation::Tuple {
            elements: annotations,
            span,
        }
    }

    pub(crate) fn parse_generics(&mut self) -> Vec<Generic> {
        if !self.advance_if(LeftAngleBracket) {
            return vec![];
        }

        let mut generics = vec![];

        while !self.is_right_angle_like() && !self.at_eof() {
            generics.push(self.parse_generic());
            self.expect_comma_or(RightAngleBracket);
        }

        if !self.advance_if_right_angle() {
            self.ensure(RightAngleBracket);
        }

        generics
    }

    fn parse_generic(&mut self) -> Generic {
        let start = self.current_token();
        let name = self.read_identifier();
        let bounds = self.parse_generic_bounds();
        Generic::new(name, bounds, self.span_from_offset(start.byte_offset))
    }

    fn parse_generic_bounds(&mut self) -> Vec<Annotation> {
        if !self.advance_if(Colon) {
            return vec![];
        }

        if self.is_right_angle_like() || self.is(Comma) {
            self.track_error(
                "expected bound after `:`",
                "Provide a bound like `T: Display`.",
            );
            return vec![];
        }

        let mut bounds = vec![];

        while !self.is_right_angle_like() && self.is_not(Comma) {
            bounds.push(self.parse_annotation());
            if self.is_right_angle_like() || self.is(Comma) {
                break;
            }
            if !self.advance_if(Plus) {
                self.track_error(
                    "missing `+` between bounds",
                    "Use `+` to separate multiple bounds.",
                );
                break;
            }
            if self.is_right_angle_like() || self.is(Comma) {
                self.track_error(
                    "expected bound after `+`",
                    "Provide a bound or remove the trailing `+`.",
                );
            }
        }

        bounds
    }

    pub(crate) fn parse_function_return_annotation(&mut self) -> Annotation {
        if self.advance_if(Arrow) {
            return self.parse_annotation();
        }

        Annotation::Unknown
    }

    pub(crate) fn parse_interface_method(
        &mut self,
        doc: Option<string::String>,
        attributes: Vec<Attribute>,
    ) -> Expression {
        self.ensure(Function);

        let start = self.current_token();
        let name_token = self.current_token();
        let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
        let name = self.read_identifier();

        if self.is(LeftAngleBracket) {
            let generics_start = self.current_token();
            let generics = self.parse_generics(); // consume and discard
            let generics_span = self.span_from_offset(generics_start.byte_offset);
            self.error_interface_method_with_type_parameters(generics_span, generics.len());
        }

        Expression::Function {
            doc,
            attributes,
            name,
            name_span,
            generics: vec![],
            params: self.parse_function_params(ParamMode::Strict),
            return_annotation: self.parse_function_return_annotation(),
            return_type: Type::uninferred(),
            visibility: Visibility::Private,
            body: FunctionBody::Declaration,
            ty: Type::uninferred(),
            span: self.span_from_offset(start.byte_offset),
        }
    }

    pub(crate) fn parse_type_alias_with_doc(
        &mut self,
        doc: Option<string::String>,
        attributes: Vec<Attribute>,
    ) -> Expression {
        let start = self.current_token();

        self.ensure(Type);

        let name_token = self.current_token();
        let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
        let name = self.read_identifier();
        let generics = self.parse_generics();

        let annotation = if self.advance_if(Equal) {
            self.parse_annotation()
        } else {
            Annotation::Opaque {
                span: self.span_from_offset(start.byte_offset),
            }
        };

        Expression::TypeAlias {
            doc,
            attributes,
            name,
            name_span,
            generics,
            annotation,
            ty: Type::uninferred(),
            visibility: Visibility::Private,
            span: self.span_from_offset(start.byte_offset),
        }
    }
}