aboutsummaryrefslogtreecommitdiff
path: root/compiler/src/ast/parser.rs
blob: 2e6d2ddd273d748fcf344ef2fb77623c744a767a (plain)
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
use std::{iter::Peekable, result};

use crate::{
    ast::{Atom, Error, Expr, Program},
    lexer::Token,
    span::{Pos, Span, Spanned},
};

type Result<T> = result::Result<T, Spanned<Error>>;

fn parse_number(number: &str) -> Atom {
    let is_float = number.bytes().any(|b| matches!(b, b'.' | b'e' | b'E'));

    if is_float {
        match number.parse() {
            Ok(ok) => Atom::Float(ok),
            Err(err) => todo!("invalid float literal {number}: {err}"),
        }
    } else {
        match number.parse() {
            Ok(ok) => Atom::Integer(ok),
            Err(err) => todo!("invalid integer literal {number}: {err}"),
        }
    }
}

fn parse_string(string: &str) -> Atom {
    let mut result = String::new();
    let mut is_escape = false;

    for ch in string.chars() {
        if !is_escape {
            match ch {
                '\\' => is_escape = true,
                _ => result.push(ch),
            }
        } else {
            match ch {
                '"' => result.push('"'),
                'n' => result.push('\n'),
                '\\' => result.push('\\'),
                '\n' => {}
                _ => todo!("unexpected escape char {ch:?}"),
            }
            is_escape = false;
        }
    }

    if is_escape {
        todo!("unclosed string");
    }

    Atom::String(result.into())
}

fn parse_symbol(symbol: &str) -> Atom {
    match symbol {
        "true" => Atom::Bool(true),
        "false" => Atom::Bool(false),
        "nil" => Atom::Nil,
        _ => Atom::Symbol(symbol.into()),
    }
}

pub struct Parser<'a, I>
where
    I: Iterator<Item = Spanned<Token<'a>>>,
{
    tokens: Peekable<I>,
    last_token_end: Pos,
}

impl<'a, I> Parser<'a, I>
where
    I: Iterator<Item = Spanned<Token<'a>>>,
{
    pub fn new(tokens: I) -> Self {
        Self {
            tokens: tokens.peekable(),
            last_token_end: Pos::new(1, 0, 0),
        }
    }

    fn peek(&mut self) -> Option<Spanned<Token<'a>>> {
        self.tokens.peek().copied()
    }

    fn consume(&mut self) -> Option<Spanned<Token<'a>>> {
        self.tokens
            .next()
            .inspect(|s| self.last_token_end = s.span.end)
    }

    fn parse_expr(&mut self) -> Result<Spanned<Expr>> {
        let Spanned { inner: token, span } = match self.peek() {
            Some(spanned) => spanned,
            None => todo!("unexpected eof"),
        };

        let expr = match token {
            Token::LeftPar => {
                self.consume();
                let list = self.parse_list()?;
                let expr = if !list.is_empty() {
                    Expr::List(list)
                } else {
                    Expr::Atom(Atom::Nil)
                };

                Spanned::new(expr, Span::new(span.start, self.last_token_end))
            }
            Token::RightPar => todo!("unexpected par"),
            Token::Quote => {
                self.consume();
                let quote = Spanned::new(
                    Expr::Atom(Atom::Symbol("quote".into())),
                    Span::new(span.start, self.last_token_end),
                );
                let expr = self.parse_expr()?;

                Spanned::new(
                    Expr::List(vec![quote, expr]),
                    Span::new(span.start, self.last_token_end),
                )
            }
            Token::Number(number) => {
                self.consume();

                Spanned::new(
                    Expr::Atom(parse_number(number)),
                    Span::new(span.start, self.last_token_end),
                )
            }
            Token::String(string) => {
                self.consume();

                Spanned::new(
                    Expr::Atom(parse_string(string)),
                    Span::new(span.start, self.last_token_end),
                )
            }
            Token::UnclosedString(string) => {
                self.consume();
                todo!("unclosed string {string:?}")
            }
            Token::Symbol(symbol) => {
                self.consume();

                Spanned::new(
                    Expr::Atom(parse_symbol(symbol)),
                    Span::new(span.start, self.last_token_end),
                )
            }
        };

        Ok(expr)
    }

    fn parse_list(&mut self) -> Result<Vec<Spanned<Expr>>> {
        let mut list = Vec::new();

        while let Some(Spanned { inner: token, .. }) = self.peek() {
            match token {
                Token::RightPar => {
                    self.consume();
                    return Ok(list);
                }
                _ => list.push(self.parse_expr()?),
            }
        }

        todo!("unclosed par")
    }

    pub fn parse(mut self) -> Result<Program> {
        let mut program = Vec::new();

        while self.peek().is_some() {
            program.push(self.parse_expr()?)
        }

        Ok(Program(program))
    }
}