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
use crate::{token_name, Loc};

#[derive(Debug, Clone)]
pub enum TokenValue {
    String(String),
    InvalidString(Vec<u8>),
}
impl TokenValue {
    /// Converts TokenValue to string, replaces unknown chars to `U+FFFD`
    pub fn to_string_lossy(&self) -> String {
        match &self {
            Self::String(s) => s.clone(),
            Self::InvalidString(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
        }
    }

    /// Converts TokenValue to a vector of bytes
    pub fn to_bytes(&self) -> Vec<u8> {
        match &self {
            Self::String(s) => s.as_bytes().to_vec(),
            Self::InvalidString(bytes) => bytes.clone(),
        }
    }

    pub fn into_string_lossy(self) -> String {
        match self {
            Self::String(s) => s,
            Self::InvalidString(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
        }
    }

    pub fn into_bytes(self) -> Vec<u8> {
        match self {
            Self::String(s) => s.into_bytes(),
            Self::InvalidString(bytes) => bytes,
        }
    }
}

/// A token that is emitted by a lexer and consumed by a parser
#[derive(Clone)]
pub struct Token {
    pub token_type: i32,
    pub token_value: TokenValue,
    pub loc: Loc,
}

use std::fmt;
impl fmt::Debug for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&format!(
            "[{}, {:?}, {}...{}]",
            token_name(self.token_type),
            self.token_value,
            self.loc.begin,
            self.loc.end
        ))
    }
}

impl Token {
    /// Converts Token to a string, replaces unknown chars to `U+FFFD`
    pub fn to_string_lossy(&self) -> String {
        self.token_value.to_string_lossy()
    }

    /// Converts Token to a vector of bytes
    pub fn to_bytes(&self) -> Vec<u8> {
        self.token_value.to_bytes()
    }

    pub fn into_string_lossy(self) -> String {
        self.token_value.into_string_lossy()
    }

    pub fn into_bytes(self) -> Vec<u8> {
        self.token_value.into_bytes()
    }
}