Skip to main content

mirascript_core/parser/
token_ref.rs

1use std::{fmt::Display, ops::Deref};
2
3use super::prelude::*;
4
5#[derive(Debug)]
6pub enum TokenRef<'s> {
7    /// A reference to a token that is owned by the parser.
8    Owned(Box<Token<'s>>),
9    /// A reference to a token that is borrowed from the input.
10    Borrowed(&'s Token<'s>),
11}
12
13impl<'s> TokenRef<'s> {
14    pub(crate) fn new(token: Token<'s>) -> Self {
15        Self::Owned(Box::new(token))
16    }
17
18    pub(crate) fn borrow(token: &'s Token<'s>) -> Self {
19        Self::Borrowed(token)
20    }
21
22    pub(crate) fn wrap_as_unknown(&mut self, error: DiagnosticCode) {
23        match self {
24            Self::Owned(token) => token.wrap_as_unknown(error),
25            Self::Borrowed(token) => {
26                let mut cloned = token.clone();
27                cloned.wrap_as_unknown(error);
28                *self = Self::new(cloned);
29            }
30        }
31    }
32}
33
34impl Display for TokenRef<'_> {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        self.deref().fmt(f)
37    }
38}
39
40impl<'s> Clone for TokenRef<'s> {
41    fn clone(&self) -> Self {
42        match self {
43            // Owned 的生存期不一定长于 's,所以不能直接转为 Borrowed
44            Self::Owned(token) => Self::Owned(token.clone()),
45            Self::Borrowed(token) => Self::Borrowed(token),
46        }
47    }
48}
49
50impl<'s> From<Token<'s>> for TokenRef<'s> {
51    fn from(token: Token<'s>) -> Self {
52        Self::new(token)
53    }
54}
55
56impl<'s> From<&'s Token<'s>> for TokenRef<'s> {
57    fn from(token: &'s Token<'s>) -> Self {
58        Self::borrow(token)
59    }
60}
61
62impl<'s> PartialEq for TokenRef<'s> {
63    fn eq(&self, other: &Self) -> bool {
64        self.deref() == other.deref()
65    }
66}
67
68impl<'s> Deref for TokenRef<'s> {
69    type Target = Token<'s>;
70
71    fn deref(&self) -> &Self::Target {
72        match self {
73            Self::Owned(token) => token,
74            Self::Borrowed(token) => token,
75        }
76    }
77}
78
79impl<'s> AsRef<Token<'s>> for TokenRef<'s> {
80    fn as_ref(&self) -> &Token<'s> {
81        self.deref()
82    }
83}
84
85impl<'s> AstWalker<'s> for TokenRef<'s> {
86    fn collect_diagnostics(&mut self, collector: &mut DiagnosticsCollector<'_, '_>) {
87        if let Self::Owned(token) = self {
88            token.collect_diagnostics(collector);
89        }
90    }
91    fn range(&self) -> SourceRange {
92        self.as_ref().range()
93    }
94}