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
use crate::syntax::ast::{keyword::Keyword, pos::Position, punc::Punctuator};
use std::fmt::{Debug, Display, Formatter, Result};
#[cfg(feature = "serde-ast")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde-ast", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Token {
pub kind: TokenKind,
pub pos: Position,
}
impl Token {
pub fn new(kind: TokenKind, line_number: u64, column_number: u64) -> Self {
Self {
kind,
pos: Position::new(line_number, column_number),
}
}
}
impl Display for Token {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "{}", self.kind)
}
}
pub struct VecToken(Vec<Token>);
impl Debug for VecToken {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let mut buffer = String::new();
for token in &self.0 {
buffer.push_str(&token.to_string());
}
write!(f, "{}", buffer)
}
}
#[cfg_attr(feature = "serde-ast", derive(Serialize, Deserialize))]
#[derive(Clone, PartialEq, Debug)]
pub enum TokenKind {
BooleanLiteral(bool),
EOF,
Identifier(String),
Keyword(Keyword),
NullLiteral,
NumericLiteral(f64),
Punctuator(Punctuator),
StringLiteral(String),
RegularExpressionLiteral(String, String),
LineTerminator,
}
impl Display for TokenKind {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match *self {
TokenKind::BooleanLiteral(ref val) => write!(f, "{}", val),
TokenKind::EOF => write!(f, "end of file"),
TokenKind::Identifier(ref ident) => write!(f, "{}", ident),
TokenKind::Keyword(ref word) => write!(f, "{}", word),
TokenKind::NullLiteral => write!(f, "null"),
TokenKind::NumericLiteral(ref num) => write!(f, "{}", num),
TokenKind::Punctuator(ref punc) => write!(f, "{}", punc),
TokenKind::StringLiteral(ref lit) => write!(f, "{}", lit),
TokenKind::RegularExpressionLiteral(ref body, ref flags) => {
write!(f, "/{}/{}", body, flags)
}
TokenKind::LineTerminator => write!(f, "line terminator"),
}
}
}