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
use crate::get_name_for_enum_type_with_offset;
use crate::get_name_for_record_type_with_offset;
use crate::get_user_defined_type_from_name;
use crate::list_all_enum_types;
use crate::list_all_record_types;
use crate::SSpan;
use crate::llir::*;
use std::fmt;
use std::rc::Rc;

pub struct File {
    pub imports: Vec<Import>,
    pub constants: Vec<Constant>,
    pub functions: Vec<Function>,
    pub traits: Vec<Trait>,
    pub impls: Vec<Impl>,
    pub enums: Vec<Enum>,
    pub records: Vec<Record>,
    pub globalvars: Vec<GlobalVariable>,
}

pub struct FunctionImport {
    pub span: SSpan,
    pub module_name: Rc<str>,
    pub function_name: Rc<str>,
    pub alias: Rc<str>,
    pub type_: FunctionType,
}

pub struct Constant {
    pub span: SSpan,
    pub name: Rc<str>,
    pub value: ConstValue,
}

#[derive(Debug, Clone)]
pub enum ConstValue {
    I32(i32),
    Type(Type),
}

impl ConstValue {
    pub fn type_(&self) -> Type {
        match self {
            ConstValue::I32(_) => Type::I32,
            ConstValue::Type(_) => Type::Type,
        }
    }
}

pub enum Visibility {
    Private,
    Public,
}

pub struct Enum {
    pub span: SSpan,
    pub name: Rc<str>,
    pub members: Vec<Rc<str>>,
}

pub struct Record {
    pub span: SSpan,
    pub name: Rc<str>,
    pub fields: Vec<(Rc<str>, Type)>,
}

pub struct Trait {
    pub span: SSpan,
    pub name: Rc<str>,
    pub type_: FunctionType,
}

pub struct Impl {
    pub span: SSpan,
    pub receiver_type: Type,
    pub trait_name: Rc<str>,
    pub type_: FunctionType,
    pub body: Expr,
}

pub struct Function {
    pub span: SSpan,
    pub visibility: Visibility,
    pub name: Rc<str>,
    pub type_: FunctionType,
    pub body: Expr,
}

pub struct GlobalVariable {
    pub span: SSpan,
    pub visibility: Visibility,
    pub name: Rc<str>,
    pub type_: Option<Type>,
    pub init: Expr,
}

pub enum Expr {
    Bool(SSpan, bool),
    Int(SSpan, i64),
    Float(SSpan, f64),
    String(SSpan, Rc<str>),
    List(SSpan, Vec<Expr>),
    GetVar(SSpan, Rc<str>),
    SetVar(SSpan, Rc<str>, Box<Expr>),
    DeclVar(SSpan, Rc<str>, Option<Type>, Box<Expr>),
    Block(SSpan, Vec<Expr>),
    FunctionCall(SSpan, Rc<str>, Vec<Expr>),
    If(SSpan, Vec<(Expr, Expr)>, Box<Expr>),
    While(SSpan, Box<Expr>, Box<Expr>),

    GetAttr(SSpan, Box<Expr>, Rc<str>),
    GetItem(SSpan, Box<Expr>, Box<Expr>),
    SetItem(SSpan, Box<Expr>, Box<Expr>, Box<Expr>),

    // builtin operators
    Binop(SSpan, Binop, Box<Expr>, Box<Expr>),
    Unop(SSpan, Unop, Box<Expr>),
    AssertType(SSpan, Type, Box<Expr>),

    // intrinsics
    CString(SSpan, Rc<str>),
    Asm(SSpan, Vec<Expr>, ReturnType, Rc<str>),
}

impl Expr {
    pub fn span(&self) -> &SSpan {
        match self {
            Expr::Bool(span, ..) => span,
            Expr::Int(span, ..) => span,
            Expr::Float(span, ..) => span,
            Expr::String(span, ..) => span,
            Expr::List(span, ..) => span,
            Expr::GetVar(span, ..) => span,
            Expr::SetVar(span, ..) => span,
            Expr::DeclVar(span, ..) => span,
            Expr::Block(span, ..) => span,
            Expr::FunctionCall(span, ..) => span,
            Expr::If(span, ..) => span,
            Expr::While(span, ..) => span,
            Expr::GetAttr(span, ..) => span,
            Expr::GetItem(span, ..) => span,
            Expr::SetItem(span, ..) => span,
            Expr::Binop(span, ..) => span,
            Expr::Unop(span, ..) => span,
            Expr::AssertType(span, ..) => span,
            Expr::CString(span, ..) => span,
            Expr::Asm(span, ..) => span,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Binop {
    Add,
    Subtract,
    Multiply,
    Divide,
    TruncDivide,
    Remainder,

    BitwiseAnd,
    BitwiseOr,
    BitwiseXor,
    ShiftLeft,
    ShiftRight,

    Is,
    IsNot,
    Equal,
    NotEqual,
    Less,
    LessOrEqual,
    Greater,
    GreaterOrEqual,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Unop {
    Plus,
    Minus,
    Not,
}

pub enum Import {
    Function(FunctionImport),
}

impl Import {
    pub fn span(&self) -> &SSpan {
        match self {
            Import::Function(i) => &i.span,
        }
    }
}

pub const TAG_I32: i32 = 1;
pub const TAG_I64: i32 = 2;
pub const TAG_F32: i32 = 3;
pub const TAG_F64: i32 = 4;
pub const TAG_BOOL: i32 = 5;
pub const TAG_TYPE: i32 = 6;
pub const TAG_STRING: i32 = 7;
pub const TAG_LIST: i32 = 8;
pub const TAG_ID: i32 = 9;

#[repr(i32)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinType {
    I32 = TAG_I32,
    I64 = TAG_I64,
    F32 = TAG_F32,
    F64 = TAG_F64,
    Bool = TAG_BOOL,

    /// a primitive i32 type that uniquely identifies
    /// a type (in practice, the type tag)
    Type = TAG_TYPE,

    /// Reference counted str type
    /// i32 that points to:
    ///   [refcnt i32][size i32][utf8...]
    String = TAG_STRING,

    /// Reference counted list type
    /// i32 that points to:
    ///   [refcnt i32][size i32][capacity i32][ptr i32]
    List = TAG_LIST,

    /// i64 value that can represent all types except
    /// other i64 types
    ///
    /// This always needs to be last one among the BuiltinTypes
    /// (i.e. TAG_ID has to be the largest among the builtin
    /// TAG_* values), because UserDefined types assume this
    /// to determine its tags
    Id = TAG_ID,
}

#[repr(i32)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum Type {
    // builtin types
    I32,
    I64,
    F32,
    F64,
    Bool,
    Type,
    String,
    List,
    Id,
    Enum(u16),
    Record(u16),
}

impl Type {
    pub fn from_name(name: &str) -> Option<Type> {
        match name {
            "i32" => Some(Type::I32),
            "i64" => Some(Type::I64),
            "f32" => Some(Type::F32),
            "f64" => Some(Type::F64),
            "bool" => Some(Type::Bool),
            "type" => Some(Type::Type),
            "str" => Some(Type::String),
            "list" => Some(Type::List),
            "id" => Some(Type::Id),
            _ => get_user_defined_type_from_name(name),
        }
    }
    pub fn tag(self) -> i32 {
        match self {
            Type::I32 => TAG_I32,
            Type::I64 => TAG_I64,
            Type::F32 => TAG_F32,
            Type::F64 => TAG_F64,
            Type::Bool => TAG_BOOL,
            Type::Type => TAG_TYPE,
            Type::String => TAG_STRING,
            Type::List => TAG_LIST,
            Type::Id => TAG_ID,
            // enums always have an odd tag
            Type::Enum(offset) => {
                if (TAG_ID + 1) % 2 == 1 {
                    (TAG_ID + 1) + 2 * (offset as i32)
                } else {
                    (TAG_ID + 2) + 2 * (offset as i32)
                }
            }
            // records always have an even tag
            Type::Record(offset) => {
                if (TAG_ID + 1) % 2 == 0 {
                    (TAG_ID + 1) + 2 * (offset as i32)
                } else {
                    (TAG_ID + 2) + 2 * (offset as i32)
                }
            }
        }
    }
    pub fn is_enum(self) -> bool {
        if let Type::Enum(_) = self {
            true
        } else {
            false
        }
    }
    pub fn is_record(self) -> bool {
        if let Type::Record(_) = self {
            true
        } else {
            false
        }
    }
    pub fn list_builtins() -> Vec<Type> {
        vec![
            Type::I32,
            Type::I64,
            Type::F32,
            Type::F64,
            Type::Bool,
            Type::Type,
            Type::String,
            Type::List,
            Type::Id,
        ]
    }
    /// list all known types
    pub fn list() -> Vec<Type> {
        let mut ret = Self::list_builtins();
        ret.extend(list_all_enum_types());
        ret.extend(list_all_record_types());
        ret
    }
    pub fn name(&self) -> Rc<str> {
        match self {
            Type::I32 => "i32".into(),
            Type::I64 => "i64".into(),
            Type::F32 => "f32".into(),
            Type::F64 => "f64".into(),
            Type::Bool => "bool".into(),
            Type::Type => "type".into(),
            Type::String => "str".into(),
            Type::List => "list".into(),
            Type::Id => "id".into(),
            Type::Enum(offset) => get_name_for_enum_type_with_offset(*offset),
            Type::Record(offset) => get_name_for_record_type_with_offset(*offset),
        }
    }
    pub fn primitive(self) -> bool {
        match self {
            Type::I32
            | Type::I64
            | Type::F32
            | Type::F64
            | Type::Bool
            | Type::Type
            | Type::Enum(_) => true,
            Type::String | Type::List | Type::Id | Type::Record(_) => false,
        }
    }
    pub fn wasm(self) -> WasmType {
        match self {
            Type::I32 => WasmType::I32,
            Type::I64 => WasmType::I64,
            Type::F32 => WasmType::F32,
            Type::F64 => WasmType::F64,
            Type::Bool => WasmType::I32,
            Type::Type => WasmType::I32,
            Type::String => WasmType::I32,
            Type::List => WasmType::I32,
            Type::Id => WasmType::I64,
            Type::Enum(_) => WasmType::I32,
            Type::Record(_) => WasmType::I32,
        }
    }
}

impl From<BuiltinType> for Type {
    fn from(t: BuiltinType) -> Self {
        match t {
            BuiltinType::I32 => Self::I32,
            BuiltinType::I64 => Self::I64,
            BuiltinType::F32 => Self::F32,
            BuiltinType::F64 => Self::F64,
            BuiltinType::Bool => Self::Bool,
            BuiltinType::Type => Self::Type,
            BuiltinType::String => Self::String,
            BuiltinType::List => Self::List,
            BuiltinType::Id => Self::Id,
        }
    }
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl fmt::Debug for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReturnType {
    // This branch is the most 'typical' case
    // where the function or expression returns a
    // real normal value
    Value(Type),

    // "Universal receiver" type
    //
    // Any expression may be used when a void type is
    // expected.
    // However, void value cannot be used in place of any other type
    //
    // void means that the function returns no value when
    // it returns
    // like 'void' in C
    Void,

    // "Universal donor" type
    //
    // An expression of type noreturn may be used
    // no matter what type is required.
    // However, when a NoReturn is expected, no other type may be
    // accepted
    //
    // NoReturn means that the function never actually
    // returns
    // like '!' in Rust
    NoReturn,
}

impl fmt::Display for ReturnType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ReturnType::Value(t) => t.fmt(f),
            ReturnType::Void => write!(f, "void"),
            ReturnType::NoReturn => write!(f, "noreturn"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FunctionType {
    pub parameters: Vec<(Rc<str>, Type)>,
    pub return_type: ReturnType,

    /// Indicates whether filename, lineno should be stored in the stacktrace
    /// whenever this function is called.
    /// If the function is known to never panic or inspect the stack trace,
    /// it may be better for performance to set this to false.
    /// By default, this is true.
    pub trace: bool,
}

impl fmt::Display for FunctionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.trace {
            write!(f, "[notrace]")?;
        }
        write!(f, "(")?;
        for (i, (name, typ)) in self.parameters.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{} {}", name, typ)?;
        }
        write!(f, ") {}", self.return_type)?;
        Ok(())
    }
}

impl From<Type> for ReturnType {
    fn from(t: Type) -> Self {
        Self::Value(t)
    }
}