-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.rs
279 lines (255 loc) · 7.72 KB
/
types.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
#![allow(non_camel_case_types)]
#![allow(unused)]
#![allow(non_snake_case)]
use crate::codegen::ConstantPool;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
/// All types necessary for the AST.
pub type Prg = Vec<Class>;
#[derive(Debug, Default, Clone, Deserialize, Serialize, PartialEq)]
pub struct Class {
pub name: String,
pub fields: Vec<FieldDecl>,
pub methods: Vec<MethodDecl>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct FieldDecl {
pub field_type: Type,
pub name: String,
pub val: Option<Expr>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct MethodDecl {
pub ret_type: Type,
pub name: String,
pub params: Vec<(Type, String)>,
pub body: Stmt,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum Stmt {
Block(Vec<Stmt>),
Return(Expr),
While(Expr, Box<Stmt>), // first condition, then body of the while-statement
LocalVarDecl(Type, String), // first type of the local variable, then it's name
If(Expr, Box<Stmt>, Option<Box<Stmt>>), // first condition, then body ofthe if-statement and lastly the optional body of the else-statement
StmtExprStmt(StmtExpr),
TypedStmt(Box<Stmt>, Type),
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum StmtExpr {
Assign(Expr, Expr), // first the name of the variable, then the value it is being assigned to
New(Type, Vec<Expr>), // first the class type, that should be instantiated, then the list of arguments for the constructor
MethodCall(Expr, String, Vec<Expr>), // first the object to which the method belongs (e.g. Expr::This), then the name of the method and lastly the list of arguments for the method call
TypedStmtExpr(Box<StmtExpr>, Type),
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum Expr {
This,
LocalOrFieldVar(String), // name of the variable
InstVar(Box<Expr>, String),
LocalVar(String), // name of the variable
FieldVar(String), // name of the variable
Unary(String, Box<Expr>), // operation first, then operand
Binary(String, Box<Expr>, Box<Expr>), // operation first, then left and right operands
Integer(i32),
Bool(bool),
Char(char),
String(String),
Jnull,
StmtExprExpr(Box<StmtExpr>),
TypedExpr(Box<Expr>, Type),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum UnaryOp {
Pos,
Neg,
Not,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Mod,
And,
Or,
Le,
Ge,
Lt,
Gt,
Eq,
Ne,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Hash, Eq)]
pub enum Type {
Int,
Bool,
Char,
String,
Void,
Null,
Class(String),
}
/// All necessary methods/implementations for the type system
impl Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Type::Int => write!(f, "int"),
Type::Bool => write!(f, "boolean"),
Type::Char => write!(f, "char"),
Type::String => write!(f, "String"),
Type::Void => write!(f, "void"),
Type::Null => write!(f, "null"),
Type::Class(name) => write!(f, "{}", name),
}
}
}
impl Type {
fn as_bytes(&self) -> Vec<u8> {
self.to_ir_string().as_bytes().to_vec()
}
pub fn to_ir_string(&self) -> String {
match self {
Type::Int => "I",
Type::Char => "C",
Type::Bool => "Z",
Type::String => "Ljava/lang/String;",
Type::Void => "V",
Type::Class(name) => name,
_ => panic!("Invalid type: {}", self),
}
.to_string()
}
}
impl Display for Class {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut fields = String::new();
for field in &self.fields {
fields.push_str(&format!("{}: {}, ", field.name, field.field_type));
}
let mut methods = String::new();
for method in &self.methods {
methods.push_str(&format!("{}: {}, ", method.name, method.ret_type));
}
write!(
f,
"class {} {{\n\tfields: {}\n\tmethods: {}\n}}",
self.name, fields, methods
)
}
}
impl FieldDecl {
/// See https://docs.oracle.com/javase/specs/jvms/se15/html/jvms-4.html#jvms-4.5
pub fn as_bytes(&self, class_name: &str, constant_pool: &mut ConstantPool) -> Vec<u8> {
use crate::codegen::Constant;
use crate::codegen::FieldRef;
use crate::codegen::NameAndType;
let mut bytes = Vec::new();
// No access modifier
bytes.extend_from_slice(&[0x0, 0x0]);
// Name index
bytes.extend_from_slice(
&constant_pool
.add(Constant::Utf8(self.name.clone()))
.to_be_bytes(),
);
// Descripter index
bytes.extend_from_slice(
&constant_pool
.add(Constant::Utf8(self.field_type.to_ir_string()))
.to_be_bytes(),
);
// Attributes count
bytes.extend_from_slice(&[0x0, 0x0]);
if let Some(val) = &self.val {}
bytes
}
}
impl Expr {
/// Gets the type if one is present
pub(crate) fn get_type(&self) -> Option<Type> {
match self {
Expr::TypedExpr(_, t) => Some(t.clone()),
_ => None,
}
}
}
impl Display for UnaryOp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UnaryOp::Pos => write!(f, "+"),
UnaryOp::Neg => write!(f, "-"),
UnaryOp::Not => write!(f, "!"),
}
}
}
impl From<&str> for UnaryOp {
fn from(s: &str) -> Self {
match s {
"+" => UnaryOp::Pos,
"-" => UnaryOp::Neg,
"!" => UnaryOp::Not,
_ => panic!("Invalid unary operator: {}", s),
}
}
}
impl Display for BinaryOp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BinaryOp::Add => write!(f, "+"),
BinaryOp::Sub => write!(f, "-"),
BinaryOp::Mul => write!(f, "*"),
BinaryOp::Div => write!(f, "/"),
BinaryOp::Mod => write!(f, "%"),
BinaryOp::And => write!(f, "&&"),
BinaryOp::Or => write!(f, "||"),
BinaryOp::Le => write!(f, "<="),
BinaryOp::Ge => write!(f, ">="),
BinaryOp::Lt => write!(f, "<"),
BinaryOp::Gt => write!(f, ">"),
BinaryOp::Eq => write!(f, "=="),
BinaryOp::Ne => write!(f, "!="),
}
}
}
impl From<&str> for BinaryOp {
fn from(s: &str) -> Self {
match s {
"+" => BinaryOp::Add,
"-" => BinaryOp::Sub,
"*" => BinaryOp::Mul,
"/" => BinaryOp::Div,
"%" => BinaryOp::Mod,
"&&" => BinaryOp::And,
"||" => BinaryOp::Or,
"<=" => BinaryOp::Le,
">=" => BinaryOp::Ge,
"<" => BinaryOp::Lt,
">" => BinaryOp::Gt,
"==" => BinaryOp::Eq,
"!=" => BinaryOp::Ne,
_ => panic!("Invalid binary operator: {}", s),
}
}
}
impl BinaryOp {
pub fn prec(op: &str) -> u8 {
match op {
"*" => 0,
"/" => 0,
"%" => 0,
"+" => 1,
"-" => 1,
"<=" => 2,
">=" => 2,
"<" => 2,
">" => 2,
"==" => 3,
"!=" => 3,
"&&" => 4,
"||" => 4,
_ => panic!("Invalid binary operator: {}", op),
}
}
}