scala 0.1.1

A experimental Scala interpreter written in Rust: lexer, parser, type inference, and tree-walking evaluation with a REPL.
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
use crate::token::Span;
use std::fmt;

#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    Int(i64),
    Long(i64),
    Double(f64),
    Float(f64),
    Bool(bool),
    String(String),
    Char(char),
    Null,
    Unit,
}

#[derive(Debug, Clone, PartialEq)]
pub enum BinOp {
    Add, Sub, Mul, Div, Mod,
    BitAnd, BitOr, BitXor,
    LeftShift, RightShift, UnsignedRightShift,
    And, Or,
    Eq, Neq, Lt, Gt, Leq, Geq,
}

#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOp {
    Negate, Not, BitNot, Positive,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Param {
    pub name: String,
    pub type_ann: Option<TypeExpr>,
    pub default: Option<Expr>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TypeParam {
    pub name: String,
    pub variance: Variance,
    pub upper_bound: Option<TypeExpr>,
    pub lower_bound: Option<TypeExpr>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Variance {
    Invariant,
    Covariant,
    Contravariant,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
    Wildcard(Span),
    Variable { name: String, span: Span },
    Literal { value: Literal, span: Span },
    Constructor { name: String, args: Vec<Pattern>, span: Span },
    Tuple { elements: Vec<Pattern>, span: Span },
    Typed { pattern: Box<Pattern>, type_ann: TypeExpr, span: Span },
    Alternative { left: Box<Pattern>, right: Box<Pattern>, span: Span },
    SequenceWildcard(Span),
}

#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    Literal { value: Literal, span: Span },
    Binary { left: Box<Expr>, op: BinOp, right: Box<Expr>, span: Span },
    Unary { op: UnaryOp, operand: Box<Expr>, span: Span },
    If { cond: Box<Expr>, then_branch: Box<Expr>, else_branch: Option<Box<Expr>>, span: Span },
    Block { stmts: Vec<Stmt>, span: Span },
    Lambda { params: Vec<Param>, body: Box<Expr>, span: Span },
    Apply { func: Box<Expr>, args: Vec<Expr>, span: Span },
    MethodCall { receiver: Box<Expr>, method: String, args: Vec<Expr>, span: Span },
    FieldAccess { receiver: Box<Expr>, field: String, span: Span },
    Match { scrutinee: Box<Expr>, cases: Vec<MatchCase>, span: Span },
    Tuple { elements: Vec<Expr>, span: Span },
    Assign { target: Box<Expr>, value: Box<Expr>, span: Span },
    Return { value: Option<Box<Expr>>, span: Span },
    Throw { value: Box<Expr>, span: Span },
    Try { body: Box<Expr>, catches: Vec<MatchCase>, finally_block: Option<Box<Expr>>, span: Span },
    New { class_name: String, type_args: Vec<TypeExpr>, args: Vec<Expr>, span: Span },
    For { enumerators: Vec<Enumerator>, body: Box<Expr>, is_yield: bool, span: Span },
    While { cond: Box<Expr>, body: Box<Expr>, span: Span },
    DoWhile { body: Box<Expr>, cond: Box<Expr>, span: Span },
    StringInterpolation { prefix: String, parts: Vec<InterpPart>, span: Span },
    This(Span),
    Super(Span),
    Identifier { name: String, span: Span },
    Paren { expr: Box<Expr>, span: Span },
    TypeApply { expr: Box<Expr>, type_args: Vec<TypeExpr>, span: Span },
    UnaryMethodCall { receiver: Box<Expr>, method: String, span: Span },
}

#[derive(Debug, Clone, PartialEq)]
pub enum InterpPart {
    Literal(String),
    Expression(Expr),
}

#[derive(Debug, Clone, PartialEq)]
pub struct MatchCase {
    pub pattern: Pattern,
    pub guard: Option<Expr>,
    pub body: Expr,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Enumerator {
    Generator { pattern: Pattern, expr: Expr, span: Span },
    Filter { cond: Expr, span: Span },
    Val { pattern: Pattern, expr: Expr, span: Span },
}

#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
    Expr(Expr),
    ValDecl { pattern: Pattern, type_ann: Option<TypeExpr>, value: Expr, span: Span },
    VarDecl { pattern: Pattern, type_ann: Option<TypeExpr>, value: Expr, span: Span },
    DefDecl(DefDecl),
    ClassDecl(ClassDecl),
    TraitDecl(TraitDecl),
    ObjectDecl(ObjectDecl),
    TypeDecl { name: String, type_params: Vec<TypeParam>, rhs: TypeExpr, span: Span },
    ImportDecl { path: Vec<String>, selectors: ImportSelectors, span: Span },
}

#[derive(Debug, Clone, PartialEq)]
pub enum ImportSelectors {
    All,
    Names(Vec<String>),
    Rename(Vec<(String, String)>),
}

#[derive(Debug, Clone, PartialEq)]
pub struct DefDecl {
    pub name: String,
    pub type_params: Vec<TypeParam>,
    pub params: Vec<Param>,
    pub return_type: Option<TypeExpr>,
    pub body: Expr,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ClassDecl {
    pub name: String,
    pub type_params: Vec<TypeParam>,
    pub ctor_params: Vec<Param>,
    pub parents: Vec<(String, Vec<Expr>)>,
    pub body: Vec<Stmt>,
    pub is_case: bool,
    pub is_abstract: bool,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TraitDecl {
    pub name: String,
    pub type_params: Vec<TypeParam>,
    pub parents: Vec<String>,
    pub body: Vec<Stmt>,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ObjectDecl {
    pub name: String,
    pub parents: Vec<(String, Vec<Expr>)>,
    pub body: Vec<Stmt>,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub enum TypeExpr {
    Simple { name: String, span: Span },
    Parameterized { base: Box<TypeExpr>, args: Vec<TypeExpr>, span: Span },
    Function { params: Vec<TypeExpr>, result: Box<TypeExpr>, span: Span },
    Tuple { elements: Vec<TypeExpr>, span: Span },
    Compound { types: Vec<TypeExpr>, span: Span },
    Wildcard { upper: Option<Box<TypeExpr>>, lower: Option<Box<TypeExpr>>, span: Span },
}

impl TypeExpr {
    pub fn simple(name: &str) -> Self {
        TypeExpr::Simple { name: name.to_string(), span: Span::zero() }
    }
}

impl fmt::Display for Literal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Literal::Int(v) => write!(f, "{}", v),
            Literal::Long(v) => write!(f, "{}L", v),
            Literal::Double(v) => write!(f, "{}", v),
            Literal::Float(v) => write!(f, "{}f", v),
            Literal::Bool(b) => write!(f, "{}", b),
            Literal::String(s) => write!(f, "\"{}\"", s),
            Literal::Char(c) => write!(f, "'{}'", c),
            Literal::Null => write!(f, "null"),
            Literal::Unit => write!(f, "()"),
        }
    }
}

impl fmt::Display for BinOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BinOp::Add => write!(f, "+"),
            BinOp::Sub => write!(f, "-"),
            BinOp::Mul => write!(f, "*"),
            BinOp::Div => write!(f, "/"),
            BinOp::Mod => write!(f, "%"),
            BinOp::BitAnd => write!(f, "&"),
            BinOp::BitOr => write!(f, "|"),
            BinOp::BitXor => write!(f, "^"),
            BinOp::LeftShift => write!(f, "<<"),
            BinOp::RightShift => write!(f, ">>"),
            BinOp::UnsignedRightShift => write!(f, ">>>"),
            BinOp::And => write!(f, "&&"),
            BinOp::Or => write!(f, "||"),
            BinOp::Eq => write!(f, "=="),
            BinOp::Neq => write!(f, "!="),
            BinOp::Lt => write!(f, "<"),
            BinOp::Gt => write!(f, ">"),
            BinOp::Leq => write!(f, "<="),
            BinOp::Geq => write!(f, ">="),
        }
    }
}

impl fmt::Display for TypeExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TypeExpr::Simple { name, .. } => write!(f, "{}", name),
            TypeExpr::Parameterized { base, args, .. } => {
                write!(f, "{}[", base)?;
                for (i, arg) in args.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{}", arg)?;
                }
                write!(f, "]")
            }
            TypeExpr::Function { params, result, .. } => {
                write!(f, "(")?;
                for (i, p) in params.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{}", p)?;
                }
                write!(f, ") => {}", result)
            }
            TypeExpr::Tuple { elements, .. } => {
                write!(f, "(")?;
                for (i, e) in elements.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{}", e)?;
                }
                write!(f, ")")
            }
            TypeExpr::Compound { types, .. } => {
                for (i, t) in types.iter().enumerate() {
                    if i > 0 { write!(f, " with ")?; }
                    write!(f, "{}", t)?;
                }
                Ok(())
            }
            TypeExpr::Wildcard { .. } => write!(f, "_"),
        }
    }
}

pub fn indent(n: usize) -> String {
    "  ".repeat(n)
}

pub fn fmt_expr(expr: &Expr, depth: usize) -> String {
    match expr {
        Expr::Literal { value, .. } => format!("{}{}", indent(depth), value),
        Expr::Binary { left, op, right, .. } => {
            format!("{}({} {} {})", indent(depth), fmt_expr(left, 0), op, fmt_expr(right, 0))
        }
        Expr::Unary { op, operand, .. } => {
            format!("{}({}{})", indent(depth), match op {
                UnaryOp::Negate => "-",
                UnaryOp::Not => "!",
                UnaryOp::BitNot => "~",
                UnaryOp::Positive => "+",
            }, fmt_expr(operand, 0))
        }
        Expr::If { cond, then_branch, else_branch, .. } => {
            let mut s = format!("{}if ({})\n", indent(depth), fmt_expr(cond, 0));
            s.push_str(&fmt_expr(then_branch, depth + 1));
            if let Some(els) = else_branch {
                s.push_str(&format!("\n{}else\n", indent(depth)));
                s.push_str(&fmt_expr(els, depth + 1));
            }
            s
        }
        Expr::Block { stmts, .. } => {
            let mut s = format!("{}{{\n", indent(depth));
            for stmt in stmts {
                s.push_str(&fmt_stmt(stmt, depth + 1));
                s.push('\n');
            }
            s.push_str(&format!("{}}}", indent(depth)));
            s
        }
        Expr::Lambda { params, body, .. } => {
            let ps: Vec<String> = params.iter().map(|p| p.name.clone()).collect();
            format!("{}({}) => {}", indent(depth), ps.join(", "), fmt_expr(body, 0))
        }
        Expr::Identifier { name, .. } => format!("{}{}", indent(depth), name),
        Expr::Apply { func, args, .. } => {
            let as_: Vec<String> = args.iter().map(|a| fmt_expr(a, 0)).collect();
            format!("{}{}({})", indent(depth), fmt_expr(func, 0), as_.join(", "))
        }
        Expr::MethodCall { receiver, method, args, .. } => {
            let as_: Vec<String> = args.iter().map(|a| fmt_expr(a, 0)).collect();
            format!("{}{}.{}({})", indent(depth), fmt_expr(receiver, 0), method, as_.join(", "))
        }
        Expr::FieldAccess { receiver, field, .. } => {
            format!("{}{}.{}", indent(depth), fmt_expr(receiver, 0), field)
        }
        Expr::Tuple { elements, .. } => {
            let es: Vec<String> = elements.iter().map(|e| fmt_expr(e, 0)).collect();
            format!("{}({})", indent(depth), es.join(", "))
        }
        Expr::Match { scrutinee, cases, .. } => {
            let mut s = format!("{}{} match {{\n", indent(depth), fmt_expr(scrutinee, 0));
            for case in cases {
                s.push_str(&format!("{}  case {} => {}\n", indent(depth), fmt_pattern(&case.pattern), fmt_expr(&case.body, 0)));
            }
            s.push_str(&format!("{}}}", indent(depth)));
            s
        }
        Expr::New { class_name, args, .. } => {
            let as_: Vec<String> = args.iter().map(|a| fmt_expr(a, 0)).collect();
            format!("{}new {}({})", indent(depth), class_name, as_.join(", "))
        }
        Expr::This(_) => format!("{}this", indent(depth)),
        Expr::Super(_) => format!("{}super", indent(depth)),
        Expr::While { cond, body, .. } => {
            format!("{}while ({}) {}", indent(depth), fmt_expr(cond, 0), fmt_expr(body, 0))
        }
        Expr::Assign { target, value, .. } => {
            format!("{}{} = {}", indent(depth), fmt_expr(target, 0), fmt_expr(value, 0))
        }
        Expr::Return { value, .. } => {
            match value {
                Some(v) => format!("{}return {}", indent(depth), fmt_expr(v, 0)),
                None => format!("{}return", indent(depth)),
            }
        }
        Expr::Throw { value, .. } => format!("{}throw {}", indent(depth), fmt_expr(value, 0)),
        Expr::Paren { expr, .. } => format!("({})", fmt_expr(expr, 0)),
        _ => format!("{}<???>", indent(depth)),
    }
}

pub fn fmt_pattern(pat: &Pattern) -> String {
    match pat {
        Pattern::Wildcard(_) => "_".into(),
        Pattern::Variable { name, .. } => name.clone(),
        Pattern::Literal { value, .. } => value.to_string(),
        Pattern::Constructor { name, args, .. } => {
            let ps: Vec<String> = args.iter().map(fmt_pattern).collect();
            format!("{}({})", name, ps.join(", "))
        }
        Pattern::Tuple { elements, .. } => {
            let ps: Vec<String> = elements.iter().map(fmt_pattern).collect();
            format!("({})", ps.join(", "))
        }
        Pattern::Typed { pattern, type_ann, .. } => format!("{}: {}", fmt_pattern(pattern), type_ann),
        Pattern::Alternative { left, right, .. } => format!("{} | {}", fmt_pattern(left), fmt_pattern(right)),
        Pattern::SequenceWildcard(_) => "_*".into(),
    }
}

pub fn fmt_stmt(stmt: &Stmt, depth: usize) -> String {
    match stmt {
        Stmt::Expr(e) => fmt_expr(e, depth),
        Stmt::ValDecl { pattern, type_ann, value, .. } => {
            match type_ann {
                Some(t) => format!("{}val {}: {} = {}", indent(depth), fmt_pattern(pattern), t, fmt_expr(value, 0)),
                None => format!("{}val {} = {}", indent(depth), fmt_pattern(pattern), fmt_expr(value, 0)),
            }
        }
        Stmt::VarDecl { pattern, type_ann, value, .. } => {
            match type_ann {
                Some(t) => format!("{}var {}: {} = {}", indent(depth), fmt_pattern(pattern), t, fmt_expr(value, 0)),
                None => format!("{}var {} = {}", indent(depth), fmt_pattern(pattern), fmt_expr(value, 0)),
            }
        }
        Stmt::DefDecl(d) => {
            let ps: Vec<String> = d.params.iter().map(|p| {
                match &p.type_ann {
                    Some(t) => format!("{}: {}", p.name, t),
                    None => p.name.clone(),
                }
            }).collect();
            match &d.return_type {
                Some(t) => format!("{}def {}({}): {} = {}", indent(depth), d.name, ps.join(", "), t, fmt_expr(&d.body, 0)),
                None => format!("{}def {}({}) = {}", indent(depth), d.name, ps.join(", "), fmt_expr(&d.body, 0)),
            }
        }
        Stmt::ClassDecl(c) => {
            let ps: Vec<String> = c.ctor_params.iter().map(|p| p.name.clone()).collect();
            let mut s = if c.is_case {
                format!("{}case class {}({})", indent(depth), c.name, ps.join(", "))
            } else {
                format!("{}class {}({})", indent(depth), c.name, ps.join(", "))
            };
            if !c.body.is_empty() {
                s.push_str(" {\n");
                for st in &c.body {
                    s.push_str(&fmt_stmt(st, depth + 1));
                    s.push('\n');
                }
                s.push_str(&format!("{}}}", indent(depth)));
            }
            s
        }
        Stmt::TraitDecl(t) => {
            let mut s = format!("{}trait {}", indent(depth), t.name);
            if !t.body.is_empty() {
                s.push_str(" {\n");
                for st in &t.body {
                    s.push_str(&fmt_stmt(st, depth + 1));
                    s.push('\n');
                }
                s.push_str(&format!("{}}}", indent(depth)));
            }
            s
        }
        Stmt::ObjectDecl(o) => {
            let mut s = format!("{}object {}", indent(depth), o.name);
            if !o.body.is_empty() {
                s.push_str(" {\n");
                for st in &o.body {
                    s.push_str(&fmt_stmt(st, depth + 1));
                    s.push('\n');
                }
                s.push_str(&format!("{}}}", indent(depth)));
            }
            s
        }
        Stmt::ImportDecl { path, selectors, .. } => {
            let p = path.join(".");
            match selectors {
                ImportSelectors::All => format!("{}import {}._", indent(depth), p),
                ImportSelectors::Names(names) => format!("{}import {}.{{{}}}", indent(depth), p, names.join(", ")),
                ImportSelectors::Rename(pairs) => {
                    let rs: Vec<String> = pairs.iter().map(|(a, b)| format!("{} => {}", a, b)).collect();
                    format!("{}import {}.{{{}}}", indent(depth), p, rs.join(", "))
                }
            }
        }
        Stmt::TypeDecl { name, rhs, .. } => {
            format!("{}type {} = {}", indent(depth), name, rhs)
        }
    }
}