-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.rs
84 lines (72 loc) · 2.24 KB
/
token.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
use ari_errors;
#[allow(dead_code)]
#[derive(Debug)]
#[derive(Clone, Copy)]
#[derive(PartialEq)] // For equality comparisons
pub enum TokenType {
LeftBracket, RightBracket, // Square Brackets
LeftParen, RightParen, LeftBrace, RightBrace,
Comma, Dot, Minus, Plus, Semicolon, Slash, Star,
// One or two character tokens.
Bang, BangEqual,
Equal, EqualEqual,
Greater, GreaterEqual,
Less, LessEqual,
// Literals.
Identifier, String, Number,
// Keywords.
And, Class, Else, False, For, Fn, If, Null, Or,
Print, Println, Return, Super, This, True, Let, While,
Bai, // Quit
// Loop keywords
Break, // Quit while loop
Continue, // Skip to the end of iteration
// End of File
Eof,
// Empty placeholder
None,
}
#[derive(Debug)]
pub struct Token{
pub token_type: TokenType,
pub lexeme: String,
pub literal: String, // Either number or string
pub line_number: usize,
pub index: usize,
pub source: String,
}
impl Token {
pub fn new(token_type: TokenType, lexeme: &str, literal: &str, line_number: usize, index: usize, source: &str) -> Token {
//println!("{:?}", token_type);
Token {
token_type,
lexeme: lexeme.to_owned(), // Name of variables/keywords/arguments etc
literal: literal.to_owned(), // Value such as string/number/bool etc
line_number,
index,
source: source.to_owned(),
}
}
pub fn none() -> Token{
//println!("none");
Token::new(TokenType::None, "", "", 0, 0, "")
}
pub fn print_error(&self, error: ari_errors::ErrorType) {
ari_errors::print_error(error, &self.source, self.index + 1, self.line_number);
}
pub fn print_custom_error(&self, message: &str) {
ari_errors::print_custom_error(message, &self.source, self.index + 1, self.line_number);
}
}
impl Clone for Token { // Enables Token to be copied
fn clone(&self) -> Token {
Token {
token_type: self.token_type,
lexeme: self.lexeme.clone(),
literal: self.literal.clone(),
line_number: self.line_number,
index: self.index,
source: self.source.clone(),
}
}
}