aboutsummaryrefslogtreecommitdiff
path: root/crates/libsyntax2/src/yellow/green.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/libsyntax2/src/yellow/green.rs')
-rw-r--r--crates/libsyntax2/src/yellow/green.rs95
1 files changed, 95 insertions, 0 deletions
diff --git a/crates/libsyntax2/src/yellow/green.rs b/crates/libsyntax2/src/yellow/green.rs
new file mode 100644
index 000000000..f505b26d7
--- /dev/null
+++ b/crates/libsyntax2/src/yellow/green.rs
@@ -0,0 +1,95 @@
1use std::sync::Arc;
2use {
3 SyntaxKind, TextUnit,
4 smol_str::SmolStr,
5};
6
7#[derive(Clone, Debug)]
8pub(crate) enum GreenNode {
9 Leaf {
10 kind: SyntaxKind,
11 text: SmolStr,
12 },
13 Branch(Arc<GreenBranch>),
14}
15
16impl GreenNode {
17 pub(crate) fn new_leaf(kind: SyntaxKind, text: &str) -> GreenNode {
18 GreenNode::Leaf { kind, text: SmolStr::new(text) }
19 }
20
21 pub(crate) fn new_branch(kind: SyntaxKind, children: Box<[GreenNode]>) -> GreenNode {
22 GreenNode::Branch(Arc::new(GreenBranch::new(kind, children)))
23 }
24
25 pub fn kind(&self) -> SyntaxKind {
26 match self {
27 GreenNode::Leaf { kind, .. } => *kind,
28 GreenNode::Branch(b) => b.kind(),
29 }
30 }
31
32 pub fn text_len(&self) -> TextUnit {
33 match self {
34 GreenNode::Leaf { text, ..} => TextUnit::of_str(text.as_str()),
35 GreenNode::Branch(b) => b.text_len(),
36 }
37 }
38
39 pub fn children(&self) -> &[GreenNode] {
40 match self {
41 GreenNode::Leaf { .. } => &[],
42 GreenNode::Branch(b) => b.children(),
43 }
44 }
45
46 pub fn text(&self) -> String {
47 let mut buff = String::new();
48 go(self, &mut buff);
49 return buff;
50 fn go(node: &GreenNode, buff: &mut String) {
51 match node {
52 GreenNode::Leaf { text, .. } => buff.push_str(text.as_str()),
53 GreenNode::Branch(b) => b.children().iter().for_each(|child| go(child, buff)),
54 }
55 }
56 }
57}
58
59#[derive(Clone, Debug)]
60pub(crate) struct GreenBranch {
61 text_len: TextUnit,
62 kind: SyntaxKind,
63 children: Box<[GreenNode]>,
64}
65
66impl GreenBranch {
67 fn new(kind: SyntaxKind, children: Box<[GreenNode]>) -> GreenBranch {
68 let text_len = children.iter().map(|x| x.text_len()).sum::<TextUnit>();
69 GreenBranch {
70 text_len,
71 kind,
72 children,
73 }
74 }
75
76 pub fn kind(&self) -> SyntaxKind {
77 self.kind
78 }
79
80 pub fn text_len(&self) -> TextUnit {
81 self.text_len
82 }
83
84 pub fn children(&self) -> &[GreenNode] {
85 &*self.children
86 }
87}
88
89#[test]
90fn test_sizes() {
91 use std::mem::size_of;
92 println!("GreenBranch = {}", size_of::<GreenBranch>());
93 println!("GreenNode = {}", size_of::<GreenNode>());
94 println!("SmolStr = {}", size_of::<SmolStr>());
95}