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
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::*;
pub type Span = Option<(usize, usize, usize, usize)>;
#[derive(Debug, Deserialize, Serialize)]
pub struct AstPayload {
pub id: String,
pub file_name: String,
pub code: String,
pub comment: bool,
pub span: bool,
}
#[derive(Debug, Serialize)]
pub struct AstResponse {
pub id: String,
pub root: Option<AstNode>,
}
#[derive(Debug)]
pub struct AstNode {
pub r#type: &'static str,
pub value: String,
pub span: Span,
pub children: Vec<AstNode>,
}
impl Serialize for AstNode {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut st = serializer.serialize_struct("Node", 4)?;
st.serialize_field("Type", &self.r#type)?;
st.serialize_field("TextValue", &self.value)?;
st.serialize_field("Span", &self.span)?;
st.serialize_field("Children", &self.children)?;
st.end()
}
}
impl AstNode {
pub fn new(r#type: &'static str, value: String, span: Span, children: Vec<AstNode>) -> Self {
Self {
r#type,
value,
span,
children,
}
}
}
fn build<T: ParserTrait>(parser: &T, span: bool, comment: bool) -> Option<AstNode> {
let code = parser.get_code();
let root = parser.get_root();
let mut cursor = root.object().walk();
let mut node_stack = Vec::new();
let mut child_stack = Vec::new();
node_stack.push(root);
child_stack.push(Vec::new());
loop {
let ts_node = node_stack.last().unwrap();
cursor.reset(ts_node.object());
if cursor.goto_first_child() {
let node = cursor.node();
child_stack.push(Vec::with_capacity(node.child_count()));
node_stack.push(Node::new(node));
} else {
loop {
let ts_node = node_stack.pop().unwrap();
if let Some(node) = T::Checker::get_ast_node(
&ts_node,
code,
child_stack.pop().unwrap(),
span,
comment,
) {
if !child_stack.is_empty() {
child_stack.last_mut().unwrap().push(node);
} else {
return Some(node);
}
}
if let Some(next_node) = ts_node.object().next_sibling() {
child_stack.push(Vec::with_capacity(next_node.child_count()));
node_stack.push(Node::new(next_node));
break;
}
}
}
}
}
pub struct AstCallback {
_guard: (),
}
pub struct AstCfg {
pub id: String,
pub comment: bool,
pub span: bool,
}
impl Callback for AstCallback {
type Res = AstResponse;
type Cfg = AstCfg;
fn call<T: ParserTrait>(cfg: Self::Cfg, parser: &T) -> Self::Res {
AstResponse {
id: cfg.id,
root: build(parser, cfg.span, cfg.comment),
}
}
}