aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/parse.rs
blob: dba94ec59213a6d844d3914ed30959f2af304ef7 (plain) (blame)
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
use crate::frontend::lex::*;
use crate::frontend::ast::*;
use crate::frontend::ast::Binding::*;
use crate::frontend::ast::Control::*;
use crate::frontend::ast::Pattern::*;
use Token::*;
use Literal::*;
use Punctuation::*;

struct Input(std::iter::Peekable<std::vec::IntoIter<Token>>);

impl Input {
    /// Map input.next() to return Results for use with the propagation operator
    fn next(&mut self) -> Result<Token> {
        self.0.next().ok_or("end of input".into())
    }

    /// Map input.peek() to return Results for use with the propagation operator
    fn peek(&mut self) -> Result<&Token> {
        self.0.peek().ok_or("end of input".into())
    }

    /// Asserts the next character to be a known token
    fn then(&mut self, expected: Token) -> Result<()> {
        match self.next()? {
            token if expected == token => Ok(()),
            token => Err(format!("expected token {} but found {}", expected, token).into())
        }
    }
}

/// Convert a basic TokenStream into an AbstractSyntaxTree
pub fn astify(input: TokenStream, name: &str) -> Result<Expr> {
    let mut input = Input(input.into_iter().peekable());
    let body = parse_body(&mut input)?;
    Ok(Expr::Binding(Module{ id: name.to_string(), body }))
}

/// Parse a series of Exprs, for ex. the body of a function.
/// Body ::= Expr | ('{' Expr (';' Expr)* '}')
fn parse_body(input: &mut Input) -> Result<Vec<Expr>> {
    let mut res = Vec::new();
    if input.peek()? != &Sep(ScopeLeftBrace) {
        res.push(parse_expr(input)?);
        return Ok(res);
    }
    input.then(Sep(ScopeLeftBrace))?;
    while input.peek()? != &Sep(ScopeRightBrace) {
        res.push(parse_expr(input)?);
        if input.peek()? == &Sep(Semicolon) {
            input.next()?;
        }
    }
    input.then(Sep(ScopeRightBrace))?;
    Ok(res)
}

/// Expr ::= Let | Var | Const | Func | Type | Mod | Import |
///   Block | Static | For | While | Loop | If | When | Try | Match
fn parse_expr(input: &mut Input) -> Result<Expr> {
    use Keyword::*;
    match input.next()? {
        Key(word) => match word {
            Pub => {
                match input.next()? {
                    Key(word) => match word {
                        Const => parse_const(input, true),
                        Func => parse_funcdecl(input, true),
                        Type => parse_typedecl(input, true),
                        Mod => parse_mod(input, true),
                        _ => return Err("unrecognized keyword following pub".into()),
                    }
                    _ => return Err("unrecognized thing following pub".into()),
                }
            },
            Let => parse_let(input),
            Var => parse_var(input),
            Const => parse_const(input, false),
            Func => parse_funcdecl(input, false),
            Type => parse_typedecl(input, false),
            Mod => parse_mod(input, false),
            From => parse_import(input, true), // todo: probably rework imports
            Import => parse_import(input, false),
            Block => parse_block(input),
            Static => parse_static(input),
            For => parse_for(input),
            While => parse_while(input),
            Loop => parse_loop(input),
            If => parse_if(input),
            When => parse_when(input),
            Try => parse_try(input),
            Match => parse_match(input),
            _ => return Err("invalid keyword starting expression".into()),
        },
        _ => todo!(), // what can i do with this?? match line here
    }
}

/// Let ::= 'let' Pattern Annotation? '=' Expr
fn parse_let(input: &mut Input) -> Result<Expr> {
    let id = parse_pattern(input)?;
    let kind = parse_annotation(input)?;
    input.then(Sep(Equals))?;
    let value = Box::new(parse_expr(input)?);
    Ok(Expr::Binding(Let { id, kind, value }))
}

/// Var ::= 'var' Pattern Annotation? ('=' Expr)?
fn parse_var(input: &mut Input) -> Result<Expr> {
    let id = parse_pattern(input)?;
    let kind = parse_annotation(input)?;
    let mut value = None;
    if input.next()? != Sep(Equals) {
        value = Some(Box::new(parse_expr(input)?));
    }
    Ok(Expr::Binding(Var { id, kind, value }))
}

/// Const ::= 'pub'? 'const' Pattern Annotation? '=' Expr
fn parse_const(input: &mut Input, public: bool) -> Result<Expr> {
    let id = parse_pattern(input)?;
    let kind = parse_annotation(input)?;
    input.then(Sep(Equals))?;
    let value = Box::new(parse_expr(input)?);
    Ok(Expr::Binding(Const { public, id, kind, value }))
}

/// Annotation ::= (':' TypeDesc)?
fn parse_annotation(input: &mut Input) -> Result<Option<Type>> {
    let mut kind = None;
    if input.peek()? == &Sep(Colon) {
        input.next()?;
        kind = Some(parse_type(input)?);
    }
    Ok(kind)
}

/// Func ::= 'pub'? 'func' Ident Generics? Parameters? (':' TypeDesc) '=' Body
fn parse_funcdecl(input: &mut Input, public: bool) -> Result<Expr> { todo!() }

/// TypeDecl ::= 'pub'? 'type' Pattern Generics? '=' 'distinct'? 'ref'? TypeDesc
fn parse_typedecl(input: &mut Input, public: bool) -> Result<Expr> {
    let pattern = parse_pattern(input)?;
    todo!()
}

/// Mod ::= 'pub'? 'mod' Ident ':' Body
fn parse_mod(input: &mut Input, public: bool) -> Result<Expr> {
    match input.next()? {
        Word(id) => {
            match input.next()? {
                Sep(Colon) => {
                    let body = parse_body(input)?;
                    Ok(Expr::Binding(Module { id, body }))
                },
                _ => return Err("unexpected token following mod label".into()),
            }
        },
        _ => return Err("unexpected thing following mod keyword".into()),
    }
}

/// Import ::= ('from' Ident)? 'import' Ident (',' Ident)* ('as' Ident)?
fn parse_import(input: &mut Input, from_scope: bool) -> Result<Expr> {
    let mut from = None;
    if from_scope {
        match input.next()? {
            Word(id) => from = Some(id),
            _ => return Err("identifier not following from keyword".into())
        }
        input.then(Key(Keyword::Import))?;
    }
    todo!()
}

/// Block ::= 'block' Ident? ':' Body
fn parse_block(input: &mut Input) -> Result<Expr> { // todo: body + offset
    match input.next()? {
        Sep(Colon) => {
            let id = None;
            let body = parse_body(input)?;
            Ok(Expr::Control(Block { id, body }))
        },
        Word(label) => {
            match input.next()? {
                Sep(Colon) => {
                    let id = Some(label);
                    let body = parse_body(input)?;
                    Ok(Expr::Control(Block { id, body }))
                },
                _ => return Err("unexpected token following block label".into()),
            }
        },
        _ => return Err("unexpected thing following block keyword".into()),
    }
}

/// Static ::= 'static' ':' Body
fn parse_static(input: &mut Input) -> Result<Expr> {
    input.then(Sep(Colon))?;
    let body = parse_body(input)?;
    Ok(Expr::Control(Static { body }))
}

/// For ::= 'for' Pattern 'in' Expr ':' Body
fn parse_for(input: &mut Input) -> Result<Expr> {
    let binding = parse_pattern(input)?;
    input.then(Key(Keyword::In))?;
    let range = Box::new(parse_expr(input)?);
    input.then(Sep(Colon))?;
    let body = parse_body(input)?;
    Ok(Expr::Control(For { binding, range, body }))
}

/// While ::= 'while' Expr ':' Body
fn parse_while(input: &mut Input) -> Result<Expr> {
    let cond = Box::new(parse_expr(input)?);
    input.then(Sep(Colon))?;
    let body = parse_body(input)?;
    Ok(Expr::Control(While { cond, body }))
}

/// Loop ::= 'loop' ':' Body
fn parse_loop(input: &mut Input) -> Result<Expr> {
    input.then(Sep(Colon))?;
    let body = parse_body(input)?;
    Ok(Expr::Control(Loop { body }))
}

/// If ::= 'if' CondBranch ('elif' CondBranch)* ('else' ':' Body)?
fn parse_if(input: &mut Input) -> Result<Expr> {
    let mut branches = Vec::new();
    branches.push(parse_cond_branch(input)?);
    while input.peek()? == &Key(Keyword::Elif) {
        input.next()?;
        branches.push(parse_cond_branch(input)?);
    }
    let mut else_body = None;
    if input.peek()? == &Key(Keyword::Else) {
        input.next()?;
        else_body = Some(parse_body(input)?);
    }
    Ok(Expr::Control(If { branches, else_body }))
}

// When ::= 'when' CondBranch ('elif' CondBranch)* ('else' ':' Body)?
fn parse_when(input: &mut Input) -> Result<Expr> {
    let mut branches = Vec::new();
    branches.push(parse_cond_branch(input)?);
    while input.peek()? == &Key(Keyword::Elif) {
        input.next()?;
        branches.push(parse_cond_branch(input)?);
    }
    let mut else_body = None;
    if input.peek()? == &Key(Keyword::Else) {
        input.next()?;
        input.then(Sep(Colon))?;
        else_body = Some(parse_body(input)?);
    }
    let mut body = Vec::new();
    body.push(Expr::Control(If { branches, else_body }));
    Ok(Expr::Control(Static { body }))
}

/// CondBranch ::= Expr ':' Body
fn parse_cond_branch(input: &mut Input) -> Result<CondBranch> {
    let cond = parse_expr(input)?;
    input.then(Sep(Colon))?;
    let body = parse_body(input)?;
    Ok(CondBranch { cond, body })
}

/// Try ::= 'try' ':' Body ('except' Ident (',' Ident)* ':' Body) ('finally' ':' Body)?
fn parse_try(input: &mut Input) -> Result<Expr> {
    input.then(Sep(Colon))?;
    let body = parse_body(input)?;
    let mut catches = Vec::new();
    while input.peek()? == &Key(Keyword::Catch) {
        input.next()?;
        todo!();
    }
    let mut finally = None;
    if input.peek()? == &Key(Keyword::Finally) {
        input.next()?;
        input.then(Sep(Colon))?;
        finally = Some(parse_body(input)?);
    }
    Ok(Expr::Control(Try { body, catches, finally }))
}

/// Match ::= 'match' Expr ('of' Pattern (',' Pattern)* ('where' Expr)? ':' Body)+
fn parse_match(input: &mut Input) -> Result<Expr> {
    let item = parse_pattern(input)?; // fixme
    let mut branches = Vec::new();
    while input.peek()? == &Key(Keyword::Of) {
        input.next()?;
        todo!();
    }
    Ok(Expr::Control(Match { item, branches }))
}

/// Type ::=
///   ('ref' | 'ptr' | 'mut' | 'static' | 'struct' | 'tuple' | 'enum' | 'union' | 'interface' | 'concept') |
///   ('ref' WrappedType) | ('ptr' WrappedType) | ('mut' WrappedType) | ('static' WrappedType) | ('distinct' WrappedType) |
///   StructType | TupleType | EnumType | UnionType | InterfaceType
/// The input stream must be normalized before attempting to parse types, because otherwise it's just a little bit hellish.
/// In particular: ref, ptr, mut, static, distinct must wrap their parameters in '[' ']' and all type declarations must be on one line.
fn parse_type(input: &mut Input) -> Result<Type> {
    use Type::*;
    match input.next()? {
        Key(word) => {
            match input.peek()? { // todo: check if the type is a special typeclass
                Sep(GenericLeftBracket) => (),
                _ => todo!() // ref, ptr, mut, static, struct, tuple, enum, union, interface, concept
            }
            match word {
                Keyword::Distinct => Ok(Distinct(Box::new(parse_wrapped_type(input)?))),
                Keyword::Ref => Ok(Reference(Box::new(parse_wrapped_type(input)?))),
                Keyword::Ptr => Ok(Pointer(Box::new(parse_wrapped_type(input)?))),
                Keyword::Var => Ok(Mutable(Box::new(parse_wrapped_type(input)?))),
                Keyword::Const => Ok(Static(Box::new(parse_wrapped_type(input)?))),
                Keyword::Struct => parse_struct_type(input),
                Keyword::Tuple => parse_tuple_type(input),
                Keyword::Enum => parse_enum_type(input),
                Keyword::Union => parse_union_type(input),
                Keyword::Interface => parse_interface(input),
                _ => return Err("invalid keyword present in type!".into())
            }
        },
        Word(id) => {
            let mut generics = Vec::new();
            if input.peek()? == &Sep(GenericLeftBracket) {
                generics = parse_generics(input)?;
            }
            Ok(Alias { id, generics })
        },
        _ => return Err("error".into())
    }
}

/// `StructType ::= ('struct' '[' Ident ':' Type (',' Ident ':' Type)* ']'`
fn parse_struct_type(input: &mut Input) -> Result<Type> { todo!() }
/// `TupleType ::= 'tuple' '[' (Ident ':')? Type (',' (Ident ':')? Type)* ']'`
fn parse_tuple_type(input: &mut Input) -> Result<Type> { todo!() }
/// `EnumType ::= 'enum' '[' Ident ('=' Pattern)? (Ident ('=' Pattern)?)* ']'`
fn parse_enum_type(input: &mut Input) -> Result<Type> { todo!() }
/// `UnionType ::= 'union' '[' Ident (':' Type)? (',' Ident (':' Type)?)* ']'`
fn parse_union_type(input: &mut Input) -> Result<Type> { todo!() }
/// `Interface ::= 'interface' '[' Signature (',' Signature)* ']'`
fn parse_interface(input: &mut Input) -> Result<Type> { todo!() }
/// `Signature ::= Ident ('[' Ident (':' Type)? (',' Ident (':' Type)?)* ']')? ('(' Type (',' Type)* ')')? (':' Type)?`
fn parse_signature(input: &mut Input) -> Result<Sig> { todo!() }

/// `WrappedType ::= Type | ('[' Type ']')`
fn parse_wrapped_type(input: &mut Input) -> Result<Type> {
    if input.next()? == Sep(GenericLeftBracket) {
        let result = parse_type(input)?;
        input.then(Sep(GenericRightBracket))?;
        Ok(result)
    } else {
        parse_type(input)
    }
}

/// `GenericType ::= '[' Type (',' Type)* ']'`
fn parse_generics(input: &mut Input) -> Result<Vec<Type>> { todo!() }

/// Pattern ::= Literal | Ident | '(' Pattern (',' Pattern)* ')' | Ident '(' Pattern (',' Pattern)* ')'
fn parse_pattern(input: &mut Input) -> Result<Pattern> { todo!() }

/// Literal ::= Char | String | Number | Float
fn parse_literal(input: &mut Input) -> Result<Pattern> { todo!() }