2024-04-12 19:36:26 +00:00
|
|
|
//! A [Token] contains a single unit of lexical information, and an optional bit of [TokenData]
|
|
|
|
use super::{TokenData, TokenKind};
|
2023-10-22 23:28:20 +00:00
|
|
|
|
2023-10-24 00:43:16 +00:00
|
|
|
/// Contains a single unit of lexical information,
|
2024-04-12 19:36:26 +00:00
|
|
|
/// and an optional bit of [TokenData]
|
2023-10-22 23:28:20 +00:00
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
2023-10-17 18:23:34 +00:00
|
|
|
pub struct Token {
|
2024-04-13 07:48:16 +00:00
|
|
|
pub ty: TokenKind,
|
|
|
|
pub data: TokenData,
|
|
|
|
pub line: u32,
|
|
|
|
pub col: u32,
|
2023-10-17 18:23:34 +00:00
|
|
|
}
|
|
|
|
impl Token {
|
2024-04-12 19:36:26 +00:00
|
|
|
/// Creates a new [Token] out of a [TokenKind], [TokenData], line, and column.
|
|
|
|
pub fn new(ty: TokenKind, data: impl Into<TokenData>, line: u32, col: u32) -> Self {
|
2023-10-22 23:28:20 +00:00
|
|
|
Self { ty, data: data.into(), line, col }
|
2023-10-17 18:23:34 +00:00
|
|
|
}
|
2024-04-12 19:36:26 +00:00
|
|
|
/// Casts this token to a new [TokenKind]
|
|
|
|
pub fn cast(self, ty: TokenKind) -> Self {
|
2023-10-17 18:23:34 +00:00
|
|
|
Self { ty, ..self }
|
|
|
|
}
|
2024-04-12 19:36:26 +00:00
|
|
|
/// Returns the [TokenKind] of this token
|
|
|
|
pub fn ty(&self) -> TokenKind {
|
2023-10-22 23:28:20 +00:00
|
|
|
self.ty
|
|
|
|
}
|
2024-04-12 19:36:26 +00:00
|
|
|
/// Returns a reference to this token's [TokenData]
|
|
|
|
pub fn data(&self) -> &TokenData {
|
2023-10-22 23:28:20 +00:00
|
|
|
&self.data
|
|
|
|
}
|
2024-04-12 19:36:26 +00:00
|
|
|
/// Converts this token into its inner [TokenData]
|
|
|
|
pub fn into_data(self) -> TokenData {
|
2023-10-22 23:28:20 +00:00
|
|
|
self.data
|
2023-10-17 18:23:34 +00:00
|
|
|
}
|
2023-10-24 00:43:16 +00:00
|
|
|
/// Returns the line where this token originated
|
2023-10-20 20:34:54 +00:00
|
|
|
pub fn line(&self) -> u32 {
|
2023-10-17 18:23:34 +00:00
|
|
|
self.line
|
|
|
|
}
|
2023-10-24 00:43:16 +00:00
|
|
|
/// Returns the column where this token originated
|
2023-10-20 20:34:54 +00:00
|
|
|
pub fn col(&self) -> u32 {
|
2023-10-17 18:23:34 +00:00
|
|
|
self.col
|
|
|
|
}
|
2023-10-19 19:40:03 +00:00
|
|
|
}
|