doge-compiler 0.2.0

Compiler for the Doge programming language — lexer, parser, semantic checks, and Rust codegen.
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
use super::*;

/// A call's parsed arguments: positional expressions, then `(name, value)`
/// keyword arguments in source order.
type CallArgs = (Vec<Expr>, Vec<(String, Expr)>);

impl Parser {
    // ----- expressions (lowest to highest precedence) -----

    pub(super) fn parse_expr(&mut self) -> Result<Expr, Diagnostic> {
        self.parse_ternary()
    }

    /// `then if cond else otherwise` (Python's conditional expression). The
    /// condition and the `then` value are `or`-level; the `else` branch recurses
    /// so `a if p else b if q else c` nests to the right.
    pub(super) fn parse_ternary(&mut self) -> Result<Expr, Diagnostic> {
        let then = self.parse_or()?;
        if self.is(&TokenKind::If) {
            let span = self.current_span();
            self.advance();
            let cond = self.parse_or()?;
            self.eat(TokenKind::Else).map_err(|_| {
                self.diag(self.current_span(), "this a if b needs an else branch")
                    .with_headline("very half. much ternary.")
                    .with_hint("a if cond else b — the else is required")
            })?;
            let otherwise = self.parse_ternary()?;
            Ok(Expr::Ternary {
                cond: Box::new(cond),
                then: Box::new(then),
                otherwise: Box::new(otherwise),
                span,
            })
        } else {
            Ok(then)
        }
    }

    pub(super) fn parse_or(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_and()?;
        while self.is(&TokenKind::Or) {
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_and()?;
            lhs = Expr::Binary {
                op: BinOp::Or,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_and(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_not()?;
        while self.is(&TokenKind::And) {
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_not()?;
            lhs = Expr::Binary {
                op: BinOp::And,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_not(&mut self) -> Result<Expr, Diagnostic> {
        if self.is(&TokenKind::Not) {
            let span = self.current_span();
            self.advance();
            let operand = self.parse_not()?;
            Ok(Expr::Unary {
                op: UnOp::Not,
                operand: Box::new(operand),
                span,
            })
        } else {
            self.parse_comparison()
        }
    }

    pub(super) fn parse_comparison(&mut self) -> Result<Expr, Diagnostic> {
        let lhs = self.parse_bitor()?;
        if let Some((op, tokens)) = self.peek_comparison() {
            let span = self.current_span();
            for _ in 0..tokens {
                self.advance();
            }
            let rhs = self.parse_bitor()?;
            // Non-chaining: `1 < x < 10` is a friendly error.
            if self.peek_comparison().is_some() {
                let bad = self.current_span();
                return Err(self
                    .diag(bad, "doge does not chain comparisons like this")
                    .with_hint("use and — 1 < x and x < 10"));
            }
            Ok(Expr::Binary {
                op,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            })
        } else {
            Ok(lhs)
        }
    }

    /// The comparison operator at the cursor and how many tokens it spans, or
    /// `None`. All single-token operators span one; the membership `not in`
    /// spans two (`not` immediately followed by `in`).
    fn peek_comparison(&self) -> Option<(BinOp, usize)> {
        if let Some(op) = comparison_op(self.peek()) {
            return Some((op, 1));
        }
        if self.is(&TokenKind::Not) && self.peek_next() == &TokenKind::In {
            return Some((BinOp::NotIn, 2));
        }
        None
    }

    // Bitwise precedence, loosest to tightest (Python order): `|` then `^` then
    // `&` then the shifts, all between comparison and `+`/`-`.
    pub(super) fn parse_bitor(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_bitxor()?;
        while self.is(&TokenKind::Pipe) {
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_bitxor()?;
            lhs = Expr::Binary {
                op: BinOp::BitOr,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_bitxor(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_bitand()?;
        while self.is(&TokenKind::Caret) {
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_bitand()?;
            lhs = Expr::Binary {
                op: BinOp::BitXor,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_bitand(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_shift()?;
        while self.is(&TokenKind::Amp) {
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_shift()?;
            lhs = Expr::Binary {
                op: BinOp::BitAnd,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_shift(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_add()?;
        loop {
            let op = match self.peek() {
                TokenKind::Shl => BinOp::Shl,
                TokenKind::Shr => BinOp::Shr,
                _ => break,
            };
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_add()?;
            lhs = Expr::Binary {
                op,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_add(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_mul()?;
        loop {
            let op = match self.peek() {
                TokenKind::Plus => BinOp::Add,
                TokenKind::Minus => BinOp::Sub,
                _ => break,
            };
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_mul()?;
            lhs = Expr::Binary {
                op,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_mul(&mut self) -> Result<Expr, Diagnostic> {
        let mut lhs = self.parse_unary()?;
        loop {
            let op = match self.peek() {
                TokenKind::Star => BinOp::Mul,
                TokenKind::Slash => BinOp::Div,
                TokenKind::SlashSlash => BinOp::FloorDiv,
                TokenKind::Percent => BinOp::Rem,
                _ => break,
            };
            let span = self.current_span();
            self.advance();
            let rhs = self.parse_unary()?;
            lhs = Expr::Binary {
                op,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                span,
            };
        }
        Ok(lhs)
    }

    pub(super) fn parse_unary(&mut self) -> Result<Expr, Diagnostic> {
        let op = match self.peek() {
            TokenKind::Minus => UnOp::Neg,
            TokenKind::Tilde => UnOp::BitNot,
            _ => return self.parse_power(),
        };
        let span = self.current_span();
        self.advance();
        let operand = self.parse_unary()?;
        Ok(Expr::Unary {
            op,
            operand: Box::new(operand),
            span,
        })
    }

    /// `base ** exponent` — right-associative, and binding tighter than unary on
    /// its left (`-2 ** 2` is `-(2 ** 2)`) but looser on its right, since the
    /// exponent is a full unary expression (`2 ** -1`).
    pub(super) fn parse_power(&mut self) -> Result<Expr, Diagnostic> {
        let base = self.parse_postfix()?;
        if self.is(&TokenKind::StarStar) {
            let span = self.current_span();
            self.advance();
            let exponent = self.parse_unary()?;
            Ok(Expr::Binary {
                op: BinOp::Pow,
                lhs: Box::new(base),
                rhs: Box::new(exponent),
                span,
            })
        } else {
            Ok(base)
        }
    }

    pub(super) fn parse_postfix(&mut self) -> Result<Expr, Diagnostic> {
        let mut expr = self.parse_primary()?;
        loop {
            match self.peek() {
                TokenKind::LParen => {
                    let span = self.current_span();
                    self.advance();
                    let (args, kwargs) = self.parse_call_args()?;
                    self.eat(TokenKind::RParen)?;
                    expr = Expr::Call {
                        callee: Box::new(expr),
                        args,
                        kwargs,
                        span,
                    };
                }
                TokenKind::LBracket => {
                    let span = self.current_span();
                    self.advance();
                    expr = self.parse_subscript(expr, span)?;
                }
                TokenKind::Dot => {
                    let span = self.current_span();
                    self.advance();
                    let (name, _) = self.eat_ident("a field or method name after .")?;
                    expr = Expr::Attr {
                        obj: Box::new(expr),
                        name,
                        span,
                    };
                }
                _ => break,
            }
        }
        Ok(expr)
    }

    /// The subscript after a consumed `[`: a plain index `obj[e]`, or a slice
    /// `obj[start:end:step]` where every part is optional. The opening `[` is
    /// already eaten; this consumes through the closing `]`.
    pub(super) fn parse_subscript(&mut self, obj: Expr, span: Span) -> Result<Expr, Diagnostic> {
        // No leading `:` means a start expression is present. `obj[]` reaches
        // parse_expr on `]` and yields the usual "expected a value" error.
        let start = if self.is(&TokenKind::Colon) {
            None
        } else {
            Some(Box::new(self.parse_expr()?))
        };

        if !self.is(&TokenKind::Colon) {
            self.eat(TokenKind::RBracket)?;
            let index = start.expect("compiler bug: a non-slice subscript has a start expr");
            return Ok(Expr::Index {
                obj: Box::new(obj),
                index,
                span,
            });
        }

        self.advance(); // first ':'
        let end = if self.is(&TokenKind::Colon) || self.is(&TokenKind::RBracket) {
            None
        } else {
            Some(Box::new(self.parse_expr()?))
        };
        let step = if self.is(&TokenKind::Colon) {
            self.advance(); // second ':'
            if self.is(&TokenKind::RBracket) {
                None
            } else {
                Some(Box::new(self.parse_expr()?))
            }
        } else {
            None
        };
        self.eat(TokenKind::RBracket)?;
        Ok(Expr::Slice {
            obj: Box::new(obj),
            start,
            end,
            step,
            span,
        })
    }

    /// Call arguments after the consumed `(`: positional arguments, then any
    /// keyword arguments `name = value`. A positional argument may not follow a
    /// keyword one, and a keyword name may not repeat (docs/GRAMMAR.md).
    pub(super) fn parse_call_args(&mut self) -> Result<CallArgs, Diagnostic> {
        let mut args = Vec::new();
        let mut kwargs: Vec<(String, Expr)> = Vec::new();
        loop {
            if self.is(&TokenKind::RParen) {
                break;
            }
            // `name = value` — a keyword argument. Any other leading form is a
            // positional expression (which never begins with `IDENT =`).
            if matches!(self.peek(), TokenKind::Ident(_)) && self.peek_next() == &TokenKind::Eq {
                let (name, span) = self.eat_ident("a keyword argument name")?;
                self.eat(TokenKind::Eq)?;
                let value = self.parse_expr()?;
                if kwargs.iter().any(|(n, _)| n == &name) {
                    return Err(self
                        .diag(span, format!("keyword argument {name} is given twice"))
                        .with_headline("very keyword. much repeat.")
                        .with_hint("pass each keyword argument once"));
                }
                kwargs.push((name, value));
            } else {
                if !kwargs.is_empty() {
                    let span = self.current_span();
                    return Err(self
                        .diag(
                            span,
                            "a positional argument cannot follow a keyword argument",
                        )
                        .with_headline("very order. much muddle.")
                        .with_hint("put positional arguments before keyword ones"));
                }
                args.push(self.parse_expr()?);
            }
            if self.is(&TokenKind::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        Ok((args, kwargs))
    }

    /// Turn a lexed interpolated string into an [`Expr::StrInterp`]: literal
    /// segments pass through, and each `{…}` hole's tokens are parsed as a full
    /// expression by a sub-parser. A hole that holds more than one expression is
    /// a diagnostic anchored at the first leftover token.
    pub(super) fn parse_str_interp(
        &mut self,
        segments: Vec<StrSegment>,
        span: Span,
    ) -> Result<Expr, Diagnostic> {
        let mut parts = Vec::with_capacity(segments.len());
        for segment in segments {
            match segment {
                StrSegment::Lit(text) => parts.push(InterpPart::Lit(text)),
                StrSegment::Hole(mut tokens) => {
                    let end_span = tokens.last().map(|t| t.span).unwrap_or(span);
                    tokens.push(Token {
                        kind: TokenKind::Eof,
                        span: end_span,
                    });
                    let mut sub = self.sub(tokens);
                    let expr = sub.parse_expr()?;
                    if !sub.is(&TokenKind::Eof) {
                        let extra = sub.current_span();
                        return Err(sub.diag(
                            extra,
                            format!(
                                "doge expected one expression in this {{}} hole, but found {}",
                                sub.peek().describe()
                            ),
                        ));
                    }
                    parts.push(InterpPart::Expr(expr));
                }
            }
        }
        Ok(Expr::StrInterp { parts, span })
    }

    /// `super.method(args)` — a call to a parent method, resolved statically. The
    /// `super` token is already at the cursor. `super` on its own, or a bare
    /// `super.field` with no call, is a friendly error: it exists only to call up.
    fn parse_super(&mut self, span: Span) -> Result<Expr, Diagnostic> {
        self.advance(); // super
        self.eat(TokenKind::Dot).map_err(|_| {
            self.diag(span, "super only calls a parent method")
                .with_headline("very super. much confuse.")
                .with_hint("call a parent method — super.init(…)")
        })?;
        let (method, _) = self.eat_ident("a parent method name after super.")?;
        if !self.is(&TokenKind::LParen) {
            return Err(self
                .diag(self.current_span(), "super only calls a parent method")
                .with_headline("very super. much confuse.")
                .with_hint(format!("call it — super.{method}(…)")));
        }
        self.eat(TokenKind::LParen)?;
        let (args, kwargs) = self.parse_call_args()?;
        self.eat(TokenKind::RParen)?;
        if !kwargs.is_empty() {
            return Err(self
                .diag(span, "super passes its arguments positionally")
                .with_headline("very keyword. much dynamic.")
                .with_hint(format!("drop the names — super.{method}(…)")));
        }
        Ok(Expr::SuperCall { method, args, span })
    }

    pub(super) fn parse_primary(&mut self) -> Result<Expr, Diagnostic> {
        let span = self.current_span();
        match self.peek().clone() {
            TokenKind::Int(value) => {
                self.advance();
                Ok(Expr::Int { value, span })
            }
            TokenKind::Float(value) => {
                self.advance();
                Ok(Expr::Float { value, span })
            }
            TokenKind::Str(value) => {
                self.advance();
                Ok(Expr::Str { value, span })
            }
            TokenKind::StrInterp(segments) => {
                self.advance();
                self.parse_str_interp(segments, span)
            }
            TokenKind::True => {
                self.advance();
                Ok(Expr::Bool { value: true, span })
            }
            TokenKind::False => {
                self.advance();
                Ok(Expr::Bool { value: false, span })
            }
            TokenKind::None => {
                self.advance();
                Ok(Expr::None { span })
            }
            TokenKind::Ident(name) => {
                self.advance();
                Ok(Expr::Ident { name, span })
            }
            TokenKind::Super => self.parse_super(span),
            TokenKind::LParen => {
                self.advance();
                let inner = self.parse_expr()?;
                self.eat(TokenKind::RParen)?;
                Ok(inner)
            }
            TokenKind::LBracket => self.parse_list(span),
            TokenKind::LBrace => self.parse_dict(span),
            _ => Err(self
                .diag(
                    span,
                    format!(
                        "doge expected a value here, but found {}",
                        self.peek().describe()
                    ),
                )
                .with_hint("a value is a number, string, name, list, or dict")),
        }
    }

    pub(super) fn parse_list(&mut self, span: Span) -> Result<Expr, Diagnostic> {
        self.eat(TokenKind::LBracket)?;
        let mut items = Vec::new();
        loop {
            if self.is(&TokenKind::RBracket) {
                break;
            }
            items.push(self.parse_expr()?);
            if self.is(&TokenKind::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        self.eat(TokenKind::RBracket)?;
        Ok(Expr::List { items, span })
    }

    pub(super) fn parse_dict(&mut self, span: Span) -> Result<Expr, Diagnostic> {
        self.eat(TokenKind::LBrace)?;
        let mut entries = Vec::new();
        loop {
            if self.is(&TokenKind::RBrace) {
                break;
            }
            let key = self.parse_expr()?;
            self.eat(TokenKind::Colon)?;
            let value = self.parse_expr()?;
            entries.push((key, value));
            if self.is(&TokenKind::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        self.eat(TokenKind::RBrace)?;
        Ok(Expr::Dict { entries, span })
    }
}

/// Map a token to its comparison [`BinOp`], if it is one.
fn comparison_op(kind: &TokenKind) -> Option<BinOp> {
    match kind {
        TokenKind::EqEq => Some(BinOp::Eq),
        TokenKind::NotEq => Some(BinOp::NotEq),
        TokenKind::Lt => Some(BinOp::Lt),
        TokenKind::LtEq => Some(BinOp::LtEq),
        TokenKind::Gt => Some(BinOp::Gt),
        TokenKind::GtEq => Some(BinOp::GtEq),
        TokenKind::In => Some(BinOp::In),
        _ => None,
    }
}