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
//! This module contains the `Token` and `TokenKind` structs, which represent the
//! tokens generated by the lexer.
use std::fmt::Display;
use serde::Serialize;
use shared::span::Span;
/// Represents a token in the lexer.
///
/// Tokens are the smallest units of a programming language. They represent
/// individual elements such as keywords, identifiers, literals, and symbols.
/// Tokens are used by the lexer to break down the source code into meaningful
/// components that can be processed by the parser.
///
/// Tokens are useful because they provide a structured representation of the
/// source code, allowing for easier analysis, interpretation, and transformation
/// of the code. They serve as the foundation for building compilers, interpreters,
/// and other language processing tools.
#[derive(PartialEq, Debug, Clone)]
pub struct Token {
pub kind: TokenKind,
pub span: Span,
}
/// Implements the `Display` trait for the `Token` struct.
/// This allows the `Token` struct to be formatted as a string.
impl Display for Token {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Token::{:?} ('{}', <{}:{}>)",
self.kind, self.kind, self.span.start, self.span.end
)
}
}
/// Represents a specific variant of a token.
///
/// A `TokenKind` can be one of several variants, such as `Identifier`, `Int`,
/// etc. Variants may contain additional data specific to that kind of token.
#[derive(PartialEq, Debug, Clone, Serialize)]
pub enum TokenKind {
// Special
// -------
NewLine,
/// Represents a character that does not match any other token.
Illegal(String),
/// Represents a multi-line comment `/*` that does not have a corresponding `*/`.
UnterminatedComment,
/// Represents a string literal that does not have a closing quote.
UnterminatedString,
/// Represents the end of the file.
Eof,
// Value holders
// -------------
Identifier {
name: String,
},
Int(String),
Float(String),
String(String),
// Arithmetic operators
// --------------------
Assign, // =
Plus, // +
Minus, // -
Mult, // *
Div, // /
Mod, // %
// Comparison operators
// --------------------
Lt, // <
LtEq, // <=
Gt, // >
GtEq, // >=
Eq, // ==
NotEq, // !=
// Delimiters
// ----------
Comma, // ,
Semicolon, // ;
Colon, // :
// Brackets
// --------
LParen, // (
RParen, // )
LCurly, // {
RCurly, // }
LBracket, // [
RBracket, // ]
// Keywords
// --------
DefineFunction,
Set,
True,
False,
If,
Otherwise,
Return,
Then,
End,
Repeat,
Times,
Until,
Forever,
Display,
// Boolean operator keywords
// -------------------------
Not,
And,
Or,
}
impl TokenKind {
/// Looks up an identifier and returns the corresponding token kind.
///
/// This function serves as a mapping, providing a single point of truth defining all
/// the keywords in the language. The lexer module uses this function to generate
/// tokens for keywords.
///
/// # Arguments
///
/// * `ident` - The identifier to look up.
///
/// # Returns
///
/// The corresponding token kind for the identifier.
pub fn lookup_ident(ident: &str) -> Self {
match ident {
"defineFunction" => Self::DefineFunction,
"set" => Self::Set,
"if" => Self::If,
"otherwise" => Self::Otherwise,
"true" => Self::True,
"false" => Self::False,
"return" => Self::Return,
"then" => Self::Then,
"end" => Self::End,
"repeat" => Self::Repeat,
"times" => Self::Times,
"until" => Self::Until,
"forever" => Self::Forever,
"display" => Self::Display,
"not" => Self::Not,
"and" => Self::And,
"or" => Self::Or,
_ => Self::Identifier {
name: ident.to_string(),
},
}
}
}
/// Implements the `Display` trait for `TokenKind`.
/// This allows `TokenKind` to be formatted as a string when using the `write!` macro.
impl Display for TokenKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Match the `TokenKind` variant and assign the corresponding string literal.
let string_literal = match self {
Self::Identifier { name } => name,
Self::Int(num) => num,
Self::Float(num) => num,
Self::String(string) => string,
Self::Illegal(string) => string,
Self::Assign => "=",
Self::Plus => "+",
Self::Minus => "-",
Self::Mult => "*",
Self::Div => "/",
Self::Mod => "%",
Self::Lt => "<",
Self::LtEq => "<=",
Self::Gt => ">",
Self::GtEq => ">=",
Self::Eq => "==",
Self::NotEq => "!=",
Self::Comma => ",",
Self::Semicolon => ";",
Self::Colon => ":",
Self::LParen => "(",
Self::RParen => ")",
Self::LCurly => "{",
Self::RCurly => "}",
Self::LBracket => "[",
Self::RBracket => "]",
Self::DefineFunction => "defineFunction",
Self::Set => "set",
Self::If => "if",
Self::Otherwise => "otherwise",
Self::True => "true",
Self::False => "false",
Self::Return => "return",
Self::Then => "then",
Self::End => "end",
Self::Repeat => "repeat",
Self::Times => "times",
Self::Until => "until",
Self::Forever => "forever",
Self::Display => "display",
Self::Not => "not",
Self::And => "and",
Self::Or => "or",
Self::Eof => "<EOF>",
Self::UnterminatedComment => "<UnterminatedComment>",
Self::UnterminatedString => "<UnterminatedString>",
Self::NewLine => "\\n",
}
.to_string();
// Write the string literal to the formatter.
write!(f, "{}", string_literal)
}
}