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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use crate::{
parser::ast::Node,
trim::{TrimHint, TrimState},
};
#[derive(Debug)]
pub struct NodeEvent<'a> {
pub node: &'a Node<'a>,
pub trim: TrimState,
pub first: bool,
pub last: bool,
}
impl<'a> NodeEvent<'a> {
pub fn new(
node: &'a Node,
trim: TrimState,
first: bool,
last: bool,
) -> Self {
Self {
node,
trim,
first,
last,
}
}
}
pub struct BranchIter<'source> {
node: &'source Node<'source>,
children: Option<std::slice::Iter<'source, Node<'source>>>,
}
impl<'source> BranchIter<'source> {
pub fn new(node: &'source Node) -> Self {
Self {
node,
children: None,
}
}
pub fn event(self, hint: Option<TrimHint>) -> EventIter<'source> {
EventIter::new(self, hint)
}
}
impl<'source> Iterator for BranchIter<'source> {
type Item = &'source Node<'source>;
fn next(&mut self) -> Option<Self::Item> {
let iter = match *self.node {
Node::Document(ref node) => {
Some(self.children.get_or_insert(node.nodes().iter()))
}
Node::Block(ref node) => {
Some(self.children.get_or_insert(node.nodes().iter()))
}
Node::Text(_)
| Node::Link(_)
| Node::Statement(_)
| Node::RawStatement(_)
| Node::RawComment(_)
| Node::Comment(_) => None,
};
if let Some(it) = iter {
let child = it.next();
if child.is_none() {
self.children.take();
}
child
} else {
None
}
}
}
pub struct EventIter<'source> {
iter: std::iter::Peekable<BranchIter<'source>>,
prev_trim_after: Option<bool>,
hint: Option<TrimHint>,
}
impl<'source> EventIter<'source> {
pub(crate) fn new(
nodes: BranchIter<'source>,
hint: Option<TrimHint>,
) -> Self {
let iter = nodes.peekable();
Self {
iter,
hint,
prev_trim_after: None,
}
}
}
impl<'source> Iterator for EventIter<'source> {
type Item = NodeEvent<'source>;
fn next(&mut self) -> Option<Self::Item> {
let node = self.iter.next();
let peek = self.iter.peek();
let first = self.prev_trim_after.is_none();
let start = if let Some(trim_after) = self.prev_trim_after.take() {
trim_after
} else {
if let Some(hint) = self.hint.take() {
hint.after
} else {
false
}
};
let mut end = false;
if let Some(next) = peek {
if next.trim().before {
end = true;
}
}
if let Some(ref current) = node {
self.prev_trim_after = Some(current.trim().after);
let should_clear_trim = match current {
Node::Block(_) => true,
_ => false,
};
if should_clear_trim {
self.prev_trim_after = None;
}
}
let state = TrimState::from((start, end));
node.map(|n| NodeEvent::new(n, state, first, peek.is_none()))
}
}