-
Notifications
You must be signed in to change notification settings - Fork 1
/
enums.rs
537 lines (487 loc) · 14.3 KB
/
enums.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
use std::fmt;
use crate::compiler::enums::Type;
use crate::misc::colors::*;
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum TokenKind {
Use,
Public,
Function,
Identifier,
BoolLiteral,
IntegerLiteral,
LongLiteral,
FloatingPoint,
FloatLiteral,
CharLiteral,
StringLiteral,
TrueLiteral,
FalseLiteral,
ExactLiteral,
Comment,
Colon,
DoubleColon,
AtMark,
LeftParenthesis,
RightParenthesis,
LeftCurlyBrace,
RightCurlyBrace,
LeftBlockBrace,
RightBlockBrace,
Comma,
Equal,
AddEqual,
SubtractEqual,
MultiplyEqual,
DivideEqual,
ModulusEqual,
BitwiseXorEqual,
BitwiseOrEqual,
BitwiseAndEqual,
// Exponent,
RightArrow,
LeftArrow,
Semicolon,
If,
Else,
For,
While,
Return,
Question,
Add,
Subtract,
Multiply,
Divide,
Modulus,
GreaterThan,
LessThan,
GreaterThanEqual,
LessThanEqual,
EqualTo,
NotEqualTo,
BitwiseAnd,
BitwiseXor,
BitwiseNot,
BitwiseOr,
Not,
And,
Or,
Concat,
ConcatEqual,
None,
Constant,
Store,
Break,
Continue,
// To,
Ellipsis,
Variadic,
Dot,
Yield,
// Step,
Deref,
Defer,
Size,
Unary,
ArrayLength,
External,
Address,
Struct,
ShiftRight,
ShiftLeft,
ShiftRightEqual,
ShiftLeftEqual,
Global,
Local,
Attribute,
Namespace,
}
impl TokenKind {
pub fn highest_precedence() -> i8 {
// Self::Exponent.precedence()
Self::Multiply.precedence()
}
pub fn precedence(&self) -> i8 {
match self {
// Self::Exponent => 9,
Self::Multiply | Self::Divide | Self::Modulus => 8,
Self::Add | Self::Concat | Self::Subtract => 7,
Self::ShiftLeft | Self::ShiftRight => 6,
Self::LessThan | Self::LessThanEqual | Self::GreaterThan | Self::GreaterThanEqual => 5,
Self::EqualTo | Self::NotEqualTo => 4,
Self::And | Self::BitwiseAnd => 3,
Self::BitwiseXor => 2,
Self::Or | Self::BitwiseOr => 1,
_ => 0,
}
}
pub fn is_arithmetic(&self) -> bool {
match self.to_owned() {
Self::Multiply
// | Self::Exponent
| Self::Divide
| Self::Modulus
| Self::Add
| Self::Concat
| Self::Subtract
| Self::LessThan
| Self::LessThanEqual
| Self::GreaterThan
| Self::GreaterThanEqual
| Self::EqualTo
| Self::NotEqualTo
| Self::And
| Self::Or
| Self::BitwiseXor
| Self::BitwiseOr
| Self::BitwiseAnd
| Self::ShiftLeft
| Self::ShiftRight => true,
_ => false,
}
}
pub fn is_literal(&self) -> bool {
match self.to_owned() {
Self::StringLiteral
| Self::IntegerLiteral
| Self::CharLiteral
| Self::FloatLiteral
| Self::LongLiteral
| Self::ExactLiteral
| Self::TrueLiteral
| Self::FalseLiteral
| Self::Break
| Self::Continue
| Self::FloatingPoint => true,
_ => false,
}
}
pub fn is_declarative(&self) -> bool {
match self.to_owned() {
Self::AddEqual
| Self::ConcatEqual
| Self::SubtractEqual
| Self::MultiplyEqual
| Self::DivideEqual
| Self::ModulusEqual
| Self::BitwiseXorEqual
| Self::BitwiseOrEqual
| Self::BitwiseAndEqual
| Self::ShiftLeftEqual
| Self::ShiftRightEqual => true,
_ => false,
}
}
pub fn is_comparative(&self) -> bool {
match self {
Self::GreaterThan
| Self::GreaterThanEqual
| Self::LessThan
| Self::LessThanEqual
| Self::EqualTo
| Self::NotEqualTo => true,
_ => false,
}
}
pub fn is_brace(&self) -> bool {
match self {
Self::LeftParenthesis
| Self::RightParenthesis
| Self::LeftBlockBrace
| Self::RightBlockBrace
| Self::LeftCurlyBrace
| Self::RightCurlyBrace => true,
_ => false,
}
}
pub fn is_unary_context(&self) -> bool {
match self {
Self::LeftParenthesis
| Self::LeftCurlyBrace
| Self::RightCurlyBrace
| Self::LeftBlockBrace
| Self::Comma
| Self::Colon
| Self::Not
| Self::Semicolon
| Self::Return
| Self::While
| Self::For
| Self::If
| Self::Equal => true,
other if other.is_declarative() => true,
other if other.is_arithmetic() => true,
_ => false,
}
}
pub fn to_non_declarative(&self) -> TokenKind {
match self {
Self::AddEqual => TokenKind::Add,
Self::ConcatEqual => TokenKind::Concat,
Self::SubtractEqual => TokenKind::Subtract,
Self::MultiplyEqual => TokenKind::Multiply,
Self::DivideEqual => TokenKind::Divide,
Self::ModulusEqual => TokenKind::Modulus,
Self::BitwiseXorEqual => TokenKind::BitwiseXor,
Self::BitwiseAndEqual => TokenKind::BitwiseAnd,
Self::BitwiseOrEqual => TokenKind::BitwiseOr,
Self::ShiftLeftEqual => TokenKind::ShiftLeft,
Self::ShiftRightEqual => TokenKind::ShiftRight,
other => panic!("Invalid identifier operation {:?}", other),
}
}
}
impl fmt::Display for TokenKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", format!("{:?}", self).to_lowercase())
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ValueKind {
String(String),
Number(i128),
Character(char),
Nil,
}
impl ValueKind {
pub fn to_type_string(&self, is_struct: bool) -> Option<Type> {
match self.clone() {
ValueKind::String(val) => match val.as_str() {
"string" => Some(Type::Pointer(Box::new(Type::Char))),
"i8" => Some(Type::Byte),
"u8" => Some(Type::UnsignedByte),
"i16" => Some(Type::Halfword),
"u16" => Some(Type::UnsignedHalfword),
"i32" => Some(Type::Word),
"u32" => Some(Type::UnsignedWord),
"i64" => Some(Type::Long),
"u64" => Some(Type::UnsignedLong),
"f32" => Some(Type::Single),
"f64" => Some(Type::Double),
"char" => Some(Type::Char),
"bool" => Some(Type::Boolean),
// Arbitrary because it will be turned into `long` anyway when used as void*`
"void" => Some(Type::Void),
other => Some(if is_struct {
Type::Struct(other.into())
} else {
Type::Unknown(other.into())
}),
},
_ => None,
}
}
pub fn similar_mapping(ty: String) -> Option<String> {
match ty.as_str() {
"short" => Some("i16".into()),
"int" => Some("i32".into()),
"long" => Some("i64".into()),
"float" => Some("f32".into()),
"double" => Some("f64".into()),
_ => None,
}
}
pub fn is_base_type(&self) -> bool {
self.to_type_string(false).is_some()
&& match self.to_type_string(false).unwrap() {
Type::Unknown(_) | Type::Struct(_) => false,
_ => true,
}
}
pub fn get_string_inner(&self) -> Option<String> {
match self.clone() {
Self::String(val) => Some(val),
_ => None,
}
}
}
impl fmt::Display for ValueKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::String(val) => write!(f, "{}", val),
Self::Number(val) => write!(f, "{}", val),
Self::Character(val) => write!(f, "{}", val),
Self::Nil => write!(f, ""),
}
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Location {
pub file: String,
pub row: usize,
pub column: usize,
pub ctx: String,
pub above: Option<String>,
pub length: usize,
pub extra_info: String,
}
impl Location {
pub fn with_extra_info(mut self, extra_info: impl Into<String>) -> Self {
self.extra_info = extra_info.into();
self
}
pub fn display(&self, is_warning: bool) -> String {
return format!(
"{BOLD}{UNDERLINE}{GREEN}{}{RESET}:{UNDERLINE}{fmt}{}{RESET}:{UNDERLINE}{YELLOW}{}{RESET}",
self.file,
self.row + 1,
self.column + 1,
fmt = if is_warning { YELLOW } else { RED }
);
}
pub fn display_plain(&self) -> String {
return format!("{}:{}:{}", self.file, self.row + 1, self.column + 1);
}
pub fn get_expr_lead(&self) -> String {
let ident = self.column - (self.ctx.len() - self.ctx.trim_start().len());
let left = if ident >= self.length {
ident - self.length
} else {
ident
};
self.ctx.trim_start().split_at(left).1.into()
}
fn trim_indentation(&self, ctx: String, above: String) -> (String, String) {
let lines: Vec<&str> = ctx.lines().chain(above.lines()).collect();
let min_indent = lines
.iter()
.filter(|line| !line.trim().is_empty())
.map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
.min()
.unwrap_or(0);
let trim_string = |input: String| {
input
.lines()
.map(|line| {
if line.trim().is_empty() {
String::from(line)
} else {
String::from(&line[min_indent..])
}
})
.collect::<Vec<String>>()
.join("\n")
};
let trimmed_ctx = trim_string(ctx);
let trimmed_above = trim_string(above);
(trimmed_ctx, trimmed_above)
}
pub fn display_pretty(&self, message: impl Into<String>, is_warning: bool) -> String {
let (ctx, above) = if let Some(above) = self.above.clone() {
self.trim_indentation(self.ctx.clone(), above)
} else {
(self.ctx.trim_start().to_string(), "".into())
};
let upper = format!(
"{fmt}{}{RESET}[{}]{fmt}{}{RESET}",
"―".repeat(20),
self.display(is_warning),
"―".repeat(20),
fmt = if is_warning { YELLOW } else { RED }
);
// Used for calculating the bottom width
let upper_plain = format!(
"{}[{}]{}",
"-".repeat(20),
self.display_plain(),
"-".repeat(20)
);
let padding = 2;
let ident = self.column - (self.ctx.len() - ctx.len());
let left = if ident >= self.length {
ident - self.length
} else {
ident
};
let string = ctx.split_at(left);
let fallback_char = format!("{}", string.1.chars().nth(0).unwrap());
let mut fallback_rest = string.1.to_string();
fallback_rest.remove(0);
let lhs = string.0;
let issue = string.1.get(0..self.length).unwrap_or(&fallback_char);
let rhs = string.1.get(self.length..).unwrap_or(&fallback_rest);
let line = format!("{} | ", self.row + 1);
return format!(
"\n{upper}\n{user_mesage}\n\n{above}{line_number}{}{lhs}{BOLD}{fmt}{UNDERLINE}{issue}{RESET}{rhs}\n{}{}{BOLD}{GREEN}^{}{}{RESET}\n{fmt}{}{RESET}\n",
" ".repeat(padding),
" ".repeat(padding + format!("{} | ", self.row + 1).len()),
" ".repeat(left),
"~".repeat(self.length.checked_sub(1).unwrap_or(0)),
if !self.extra_info.is_empty() { format!(" {}", self.extra_info) } else { "".into() },
"―".repeat(upper_plain.len()),
above = if !above.is_empty() {
format!(
"{:<2} | {}{}\n",
self.row,
" ".repeat(padding),
above
)
} else {
"".into()
},
user_mesage = message.into(),
line_number = line,
fmt = if is_warning { YELLOW } else { RED }
);
}
pub fn warning(&self, message: impl Into<String>) -> String {
self.display_pretty(message, true)
}
pub fn error(&self, message: impl Into<String>) -> String {
self.display_pretty(message, false)
}
pub fn default(file: String) -> Location {
Location {
file,
row: 0,
column: 0,
ctx: "".into(),
above: None,
length: 0,
extra_info: "".into(),
}
}
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}:{}", self.file, self.row + 1, self.column + 1)
}
}
impl fmt::Debug for Location {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}:{}", self.file, self.row + 1, self.column + 1)
}
}
#[derive(Debug, Clone)]
pub struct Token {
pub kind: TokenKind,
pub location: Location,
pub value: ValueKind,
}
#[derive(Debug, Clone)]
pub enum Attribute {
Alias,
Volatile,
}
impl Token {
/// Ensures an attribute is valid and returns its enum variant
pub fn parse_attribute(&self) -> Attribute {
if self.kind != TokenKind::Identifier {
panic!(
"{}",
self.location
.error("Tried to parse an attribute on a non-identifier token")
);
}
let attribute = self.value.get_string_inner().unwrap();
match attribute.as_str() {
"alias" => Attribute::Alias,
"volatile" => Attribute::Volatile,
_ => todo!("more attributes"),
}
}
}
#[derive(Debug, Clone)]
pub enum ParseResult {
Float(f64),
Int(i64),
}