/
ast.rs
552 lines (499 loc) · 11.9 KB
/
ast.rs
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
use std::cell::RefCell;
use std::fmt::{Debug, Display};
use std::hash::{Hash, Hasher};
use derivative::Derivative;
use indexmap::{Equivalent, IndexMap, IndexSet};
use crate::capture::Captures;
use crate::diagnostic::WingSpan;
use crate::type_check::symbol_env::SymbolEnv;
use crate::type_check::TypeRef;
#[derive(Debug, Eq, Clone)]
pub struct Symbol {
pub name: String,
pub span: WingSpan,
}
impl Symbol {
pub fn global<S: Into<String>>(name: S) -> Self {
Self {
name: name.into(),
span: Default::default(),
}
}
}
impl Ord for Symbol {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.name.cmp(&other.name).then(self.span.cmp(&other.span))
}
}
impl PartialOrd for Symbol {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
let string_ord = self.name.partial_cmp(&other.name);
if string_ord == Some(std::cmp::Ordering::Equal) {
self.span.partial_cmp(&other.span)
} else {
string_ord
}
}
}
impl Hash for Symbol {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
impl PartialEq for Symbol {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl Display for Symbol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} (at {})", self.name, self.span)
}
}
impl Equivalent<Symbol> for str {
fn equivalent(&self, key: &Symbol) -> bool {
self == key.name
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Phase {
Inflight,
Preflight,
Independent,
}
impl Phase {
/// Returns true if the current phase can call into given phase.
/// Rules:
/// - Independent functions can be called from any phase.
/// - Preflight can call into preflight
/// - Inflight can call into inflight
///
pub fn can_call_to(&self, to: &Phase) -> bool {
match to {
Phase::Independent => true,
Phase::Inflight | Phase::Preflight => to == self,
}
}
}
impl Display for Phase {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Phase::Inflight => write!(f, "inflight"),
Phase::Preflight => write!(f, "preflight"),
Phase::Independent => write!(f, "independent"),
}
}
}
#[derive(Debug, Clone)]
pub enum TypeAnnotation {
Number,
String,
Bool,
Duration,
Json,
MutJson,
Optional(Box<TypeAnnotation>),
Array(Box<TypeAnnotation>),
MutArray(Box<TypeAnnotation>),
Map(Box<TypeAnnotation>),
MutMap(Box<TypeAnnotation>),
Set(Box<TypeAnnotation>),
MutSet(Box<TypeAnnotation>),
FunctionSignature(FunctionSignature),
UserDefined(UserDefinedType),
}
// In the future this may be an enum for type-alias, class, etc. For now its just a nested name.
// Also this root,fields thing isn't really useful, should just turn in to a Vec<Symbol>.
#[derive(Debug, Clone)]
pub struct UserDefinedType {
pub root: Symbol,
pub fields: Vec<Symbol>,
}
impl Display for UserDefinedType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut name = self.root.name.clone();
for field in &self.fields {
name.push('.');
name.push_str(&field.name);
}
write!(f, "{}", name)
}
}
impl Display for TypeAnnotation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TypeAnnotation::Number => write!(f, "num"),
TypeAnnotation::String => write!(f, "str"),
TypeAnnotation::Bool => write!(f, "bool"),
TypeAnnotation::Duration => write!(f, "duration"),
TypeAnnotation::Json => write!(f, "Json"),
TypeAnnotation::MutJson => write!(f, "MutJson"),
TypeAnnotation::Optional(t) => write!(f, "{}?", t),
TypeAnnotation::Array(t) => write!(f, "Array<{}>", t),
TypeAnnotation::MutArray(t) => write!(f, "MutArray<{}>", t),
TypeAnnotation::Map(t) => write!(f, "Map<{}>", t),
TypeAnnotation::MutMap(t) => write!(f, "MutMap<{}>", t),
TypeAnnotation::Set(t) => write!(f, "Set<{}>", t),
TypeAnnotation::MutSet(t) => write!(f, "MutSet<{}>", t),
TypeAnnotation::FunctionSignature(sig) => write!(f, "{}", sig),
TypeAnnotation::UserDefined(user_defined_type) => write!(f, "{}", user_defined_type),
}
}
}
impl Display for FunctionSignature {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let phase_str = match self.phase {
Phase::Inflight => "inflight ",
Phase::Preflight => "preflight ",
Phase::Independent => "",
};
let params_str = self
.parameters
.iter()
.map(|a| format!("{}", a))
.collect::<Vec<String>>()
.join(", ");
let ret_type_str = if let Some(ret_val) = &self.return_type {
format!("{}", ret_val)
} else {
"void".to_string()
};
write!(f, "{phase_str}({params_str}): {ret_type_str}")
}
}
#[derive(Debug, Clone)]
pub struct FunctionSignature {
pub parameters: Vec<TypeAnnotation>,
pub return_type: Option<Box<TypeAnnotation>>,
pub phase: Phase,
}
#[derive(Debug)]
pub enum FunctionBody {
/// The function body implemented within a Wing scope.
Statements(Scope),
/// The `extern` modifier value, pointing to an external implementation file
External(String),
}
#[derive(Derivative)]
#[derivative(Debug)]
pub struct FunctionDefinition {
/// List of names of function parameters and whether they are reassignable (`var`) or not.
pub parameters: Vec<(Symbol, bool)>, // TODO: move into FunctionSignature and make optional
/// The function implementation.
pub body: FunctionBody,
/// The function signature, including the return type.
pub signature: FunctionSignature,
/// Whether this function is static or not. In case of a closure, this is always true.
pub is_static: bool,
pub span: WingSpan,
#[derivative(Debug = "ignore")]
pub captures: RefCell<Option<Captures>>,
}
#[derive(Debug)]
pub struct Constructor {
/// List of names of constructor parameters and whether they are reassignable (`var`) or not.
pub parameters: Vec<(Symbol, bool)>,
pub statements: Scope,
pub signature: FunctionSignature,
}
#[derive(Debug)]
pub struct Stmt {
pub kind: StmtKind,
pub span: WingSpan,
pub idx: usize,
}
#[derive(Debug)]
pub enum UtilityFunctions {
Log,
Panic,
Throw,
Assert,
}
impl Display for UtilityFunctions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UtilityFunctions::Log => write!(f, "log"),
UtilityFunctions::Panic => write!(f, "panic"),
UtilityFunctions::Throw => write!(f, "throw"),
UtilityFunctions::Assert => write!(f, "assert"),
}
}
}
#[derive(Debug)]
pub struct ElifBlock {
pub condition: Expr,
pub statements: Scope,
}
#[derive(Debug)]
pub struct Class {
pub name: Symbol,
pub fields: Vec<ClassField>,
pub methods: Vec<(Symbol, FunctionDefinition)>,
pub constructor: Constructor,
pub parent: Option<UserDefinedType>,
pub implements: Vec<UserDefinedType>,
pub is_resource: bool,
}
#[derive(Debug)]
pub struct Interface {
pub name: Symbol,
pub methods: Vec<(Symbol, FunctionSignature)>,
pub extends: Vec<UserDefinedType>,
}
#[derive(Debug)]
pub enum StmtKind {
Bring {
module_name: Symbol, // Reference?
identifier: Option<Symbol>,
},
VariableDef {
reassignable: bool,
var_name: Symbol,
initial_value: Expr,
type_: Option<TypeAnnotation>,
},
ForLoop {
iterator: Symbol,
iterable: Expr,
statements: Scope,
},
While {
condition: Expr,
statements: Scope,
},
If {
condition: Expr,
statements: Scope,
elif_statements: Vec<ElifBlock>,
else_statements: Option<Scope>,
},
Break,
Continue,
Expression(Expr),
Assignment {
variable: Reference,
value: Expr,
},
Return(Option<Expr>),
Scope(Scope),
Class(Class),
Interface(Interface),
Struct {
name: Symbol,
extends: Vec<Symbol>,
members: Vec<ClassField>,
},
Enum {
name: Symbol,
values: IndexSet<Symbol>,
},
TryCatch {
try_statements: Scope,
catch_block: Option<CatchBlock>,
finally_statements: Option<Scope>,
},
}
#[derive(Debug)]
pub struct CatchBlock {
pub statements: Scope,
pub exception_var: Option<Symbol>,
}
#[derive(Debug)]
pub struct ClassField {
pub name: Symbol,
pub member_type: TypeAnnotation,
pub reassignable: bool,
pub phase: Phase,
pub is_static: bool,
}
#[derive(Debug)]
pub enum ExprKind {
New {
class: TypeAnnotation,
obj_id: Option<String>,
obj_scope: Option<Box<Expr>>,
arg_list: ArgList,
},
Literal(Literal),
Reference(Reference),
Call {
function: Box<Expr>,
arg_list: ArgList,
},
Unary {
// TODO: Split to LogicalUnary, NumericUnary
op: UnaryOperator,
exp: Box<Expr>,
},
Binary {
// TODO: Split to LogicalBinary, NumericBinary, Bit/String??
op: BinaryOperator,
left: Box<Expr>,
right: Box<Expr>,
},
ArrayLiteral {
type_: Option<TypeAnnotation>,
items: Vec<Expr>,
},
StructLiteral {
type_: TypeAnnotation,
// We're using a map implementation with reliable iteration to guarantee deterministic compiler output. See discussion: https://github.com/winglang/wing/discussions/887.
fields: IndexMap<Symbol, Expr>,
},
MapLiteral {
type_: Option<TypeAnnotation>,
// We're using a map implementation with reliable iteration to guarantee deterministic compiler output. See discussion: https://github.com/winglang/wing/discussions/887.
fields: IndexMap<String, Expr>,
},
SetLiteral {
type_: Option<TypeAnnotation>,
items: Vec<Expr>,
},
JsonLiteral {
is_mut: bool,
element: Box<Expr>,
},
FunctionClosure(FunctionDefinition),
OptionalTest {
optional: Box<Expr>,
},
}
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Expr {
pub kind: ExprKind,
pub span: WingSpan,
#[derivative(Debug = "ignore")]
pub evaluated_type: RefCell<Option<TypeRef>>,
}
impl Expr {
pub fn new(kind: ExprKind, span: WingSpan) -> Self {
Self {
kind,
evaluated_type: RefCell::new(None),
span,
}
}
}
#[derive(Debug)]
pub struct ArgList {
pub pos_args: Vec<Expr>,
pub named_args: IndexMap<Symbol, Expr>,
}
impl ArgList {
pub fn new() -> Self {
ArgList {
pos_args: vec![],
named_args: IndexMap::new(),
}
}
}
#[derive(Debug)]
pub enum Literal {
String(String),
InterpolatedString(InterpolatedString),
Number(f64),
Duration(f64),
Boolean(bool),
}
#[derive(Debug)]
pub struct InterpolatedString {
pub parts: Vec<InterpolatedStringPart>,
}
#[derive(Debug)]
pub enum InterpolatedStringPart {
Static(String),
Expr(Expr),
}
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Scope {
pub statements: Vec<Stmt>,
pub span: WingSpan,
#[derivative(Debug = "ignore")]
pub env: RefCell<Option<SymbolEnv>>, // None after parsing, set to Some during type checking phase
}
impl Scope {
pub fn set_env(&self, new_env: SymbolEnv) {
let mut env = self.env.borrow_mut();
assert!((*env).is_none());
*env = Some(new_env);
}
}
#[derive(Debug)]
pub enum UnaryOperator {
Minus,
Not,
}
#[derive(Debug)]
pub enum BinaryOperator {
Add,
Sub,
Mul,
Div,
FloorDiv,
Mod,
Power,
Greater,
GreaterOrEqual,
Less,
LessOrEqual,
Equal,
NotEqual,
LogicalAnd,
LogicalOr,
UnwrapOr,
}
#[derive(Debug)]
pub enum Reference {
/// A simple identifier: `x`
Identifier(Symbol),
/// A reference to a member nested inside some object `expression.x`
InstanceMember { object: Box<Expr>, property: Symbol },
/// A reference to a member inside a type: `MyType.x` or `MyEnum.A`
TypeMember { type_: UserDefinedType, property: Symbol },
}
impl Display for Reference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self {
Reference::Identifier(symb) => write!(f, "{}", symb.name),
Reference::InstanceMember { object, property } => {
let obj_str = match &object.kind {
ExprKind::Reference(r) => format!("{}", r),
_ => "object".to_string(), // TODO!
};
write!(f, "{}.{}", obj_str, property.name)
}
Reference::TypeMember { type_, property } => {
write!(f, "{}.{}", TypeAnnotation::UserDefined(type_.clone()), property.name)
}
}
}
}
/// Represents any type that has a span.
pub trait ToSpan {
fn span(&self) -> WingSpan;
}
impl ToSpan for Stmt {
fn span(&self) -> WingSpan {
self.span.clone()
}
}
impl ToSpan for Expr {
fn span(&self) -> WingSpan {
self.span.clone()
}
}
impl ToSpan for Symbol {
fn span(&self) -> WingSpan {
self.span.clone()
}
}
impl<T> ToSpan for Box<T>
where
T: ToSpan,
{
fn span(&self) -> WingSpan {
(&**self).span()
}
}