Skip to main content

oak_j/parser/
element_type.rs

1use crate::lexer::JTokenType;
2use oak_core::{ElementType, GreenNode, UniversalElementRole};
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5use std::sync::Arc;
6
7/// J 语法树元素的类型别名
8pub type JElement<'a> = Arc<GreenNode<'a, JElementType>>;
9
10/// J 语法树中所有可能的元素类型。
11#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub enum JElementType {
14    /// Root node
15    Root,
16    /// Compilation unit
17    CompilationUnit,
18
19    /// 句子 (Sentence)
20    Sentence,
21
22    /// 赋值语句 (Assignment)
23    Assignment,
24
25    /// 表达式 (Expression)
26    Expression,
27
28    /// 动词 (Verb)
29    Verb,
30
31    /// 名词 (Noun)
32    Noun,
33
34    /// 副词 (Adverb)
35    Adverb,
36
37    /// 连词 (Conjunction)
38    Conjunction,
39
40    /// 括号表达式
41    Group,
42}
43
44impl From<JTokenType> for JElementType {
45    fn from(token: JTokenType) -> Self {
46        match token {
47            JTokenType::Identifier => Self::Noun,
48            JTokenType::NumberLiteral => Self::Noun,
49            JTokenType::StringLiteral => Self::Noun,
50            JTokenType::IsGlobal | JTokenType::IsLocal => Self::Assignment,
51            _ => Self::Expression,
52        }
53    }
54}
55
56impl ElementType for JElementType {
57    type Role = UniversalElementRole;
58
59    fn role(&self) -> Self::Role {
60        match self {
61            Self::Root | Self::CompilationUnit => UniversalElementRole::Root,
62            Self::Sentence => UniversalElementRole::Statement,
63            Self::Assignment => UniversalElementRole::Binding,
64            Self::Expression => UniversalElementRole::Expression,
65            _ => UniversalElementRole::None,
66        }
67    }
68}