1use nom::{
2 IResult,
3 branch::alt,
4 bytes::complete::{take_while, take_while1, is_not},
5 character::complete::{char, line_ending},
6 combinator::eof,
7 multi::{many0, many1},
8 sequence::{preceded, terminated, delimited},
9 Parser,
10};
11use std::cell::RefCell;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct Link {
15 pub id: Option<String>,
16 pub values: Vec<Link>,
17 pub children: Vec<Link>,
18}
19
20impl Link {
21 pub fn new_singlet(id: String) -> Self {
22 Link {
23 id: Some(id),
24 values: vec![],
25 children: vec![],
26 }
27 }
28
29 pub fn new_value(values: Vec<Link>) -> Self {
30 Link {
31 id: None,
32 values,
33 children: vec![],
34 }
35 }
36
37 pub fn new_link(id: Option<String>, values: Vec<Link>) -> Self {
38 Link {
39 id,
40 values,
41 children: vec![],
42 }
43 }
44
45 pub fn with_children(mut self, children: Vec<Link>) -> Self {
46 self.children = children;
47 self
48 }
49}
50
51pub struct ParserState {
52 indentation_stack: RefCell<Vec<usize>>,
53}
54
55impl ParserState {
56 pub fn new() -> Self {
57 ParserState {
58 indentation_stack: RefCell::new(vec![0]),
59 }
60 }
61
62 pub fn push_indentation(&self, indent: usize) {
63 self.indentation_stack.borrow_mut().push(indent);
64 }
65
66 pub fn pop_indentation(&self) {
67 let mut stack = self.indentation_stack.borrow_mut();
68 if stack.len() > 1 {
69 stack.pop();
70 }
71 }
72
73 pub fn current_indentation(&self) -> usize {
74 *self.indentation_stack.borrow().last().unwrap_or(&0)
75 }
76
77 pub fn check_indentation(&self, indent: usize) -> bool {
78 indent >= self.current_indentation()
79 }
80}
81
82fn is_whitespace_char(c: char) -> bool {
83 c == ' ' || c == '\t' || c == '\n' || c == '\r'
84}
85
86fn is_horizontal_whitespace(c: char) -> bool {
87 c == ' ' || c == '\t'
88}
89
90fn is_reference_char(c: char) -> bool {
91 !is_whitespace_char(c) && c != '(' && c != ':' && c != ')'
92}
93
94fn horizontal_whitespace(input: &str) -> IResult<&str, &str> {
95 take_while(is_horizontal_whitespace)(input)
96}
97
98fn whitespace(input: &str) -> IResult<&str, &str> {
99 take_while(is_whitespace_char)(input)
100}
101
102fn simple_reference(input: &str) -> IResult<&str, String> {
103 take_while1(is_reference_char)
104 .map(|s: &str| s.to_string())
105 .parse(input)
106}
107
108fn double_quoted_reference(input: &str) -> IResult<&str, String> {
109 delimited(
110 char('"'),
111 is_not("\""),
112 char('"')
113 )
114 .map(|s: &str| s.to_string())
115 .parse(input)
116}
117
118fn single_quoted_reference(input: &str) -> IResult<&str, String> {
119 delimited(
120 char('\''),
121 is_not("'"),
122 char('\'')
123 )
124 .map(|s: &str| s.to_string())
125 .parse(input)
126}
127
128fn reference(input: &str) -> IResult<&str, String> {
129 alt((
130 double_quoted_reference,
131 single_quoted_reference,
132 simple_reference,
133 )).parse(input)
134}
135
136fn eol(input: &str) -> IResult<&str, &str> {
137 alt((
138 preceded(horizontal_whitespace, line_ending),
139 preceded(horizontal_whitespace, eof),
140 )).parse(input)
141}
142
143
144
145fn reference_or_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
146 alt((
147 |i| multi_line_any_link(i, state),
148 reference.map(Link::new_singlet),
149 )).parse(input)
150}
151
152fn multi_line_value_and_whitespace<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
153 terminated(
154 |i| reference_or_link(i, state),
155 whitespace
156 ).parse(input)
157}
158
159fn multi_line_values<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Vec<Link>> {
160 preceded(
161 whitespace,
162 many0(|i| multi_line_value_and_whitespace(i, state))
163 ).parse(input)
164}
165
166fn single_line_value_and_whitespace<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
167 preceded(
168 horizontal_whitespace,
169 |i| reference_or_link(i, state)
170 ).parse(input)
171}
172
173fn single_line_values<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Vec<Link>> {
174 many1(|i| single_line_value_and_whitespace(i, state)).parse(input)
175}
176
177fn single_line_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
178 (
179 horizontal_whitespace,
180 reference,
181 horizontal_whitespace,
182 char(':'),
183 |i| single_line_values(i, state)
184 ).map(|(_, id, _, _, values)| Link::new_link(Some(id), values))
185 .parse(input)
186}
187
188fn multi_line_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
189 (
190 char('('),
191 whitespace,
192 reference,
193 whitespace,
194 char(':'),
195 |i| multi_line_values(i, state),
196 whitespace,
197 char(')')
198 ).map(|(_, _, id, _, _, values, _, _)| Link::new_link(Some(id), values))
199 .parse(input)
200}
201
202fn single_line_value_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
203 (|i| single_line_values(i, state))
204 .map(|values| {
205 if values.len() == 1 && values[0].id.is_some() && values[0].values.is_empty() && values[0].children.is_empty() {
206 Link::new_singlet(values[0].id.clone().unwrap())
207 } else {
208 Link::new_value(values)
209 }
210 })
211 .parse(input)
212}
213
214fn multi_line_value_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
215 (
216 char('('),
217 |i| multi_line_values(i, state),
218 whitespace,
219 char(')')
220 ).map(|(_, values, _, _)| {
221 if values.len() == 1 && values[0].id.is_some() && values[0].values.is_empty() && values[0].children.is_empty() {
222 Link::new_singlet(values[0].id.clone().unwrap())
223 } else {
224 Link::new_value(values)
225 }
226 })
227 .parse(input)
228}
229
230fn multi_line_any_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
231 alt((
232 |i| multi_line_value_link(i, state),
233 |i| multi_line_link(i, state),
234 )).parse(input)
235}
236
237fn single_line_any_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
238 alt((
239 terminated(|i| single_line_link(i, state), eol),
240 terminated(|i| single_line_value_link(i, state), eol),
241 )).parse(input)
242}
243
244fn any_link<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
245 alt((
246 terminated(|i| multi_line_any_link(i, state), eol),
247 |i| single_line_any_link(i, state),
248 )).parse(input)
249}
250
251fn count_indentation(input: &str) -> IResult<&str, usize> {
252 take_while(|c| c == ' ')
253 .map(|s: &str| s.len())
254 .parse(input)
255}
256
257fn push_indentation<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, ()> {
258 let (input, spaces) = count_indentation(input)?;
259 let current = state.current_indentation();
260
261 if spaces > current {
262 state.push_indentation(spaces);
263 Ok((input, ()))
264 } else {
265 Err(nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Verify)))
266 }
267}
268
269fn check_indentation<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, ()> {
270 let (input, spaces) = count_indentation(input)?;
271
272 if state.check_indentation(spaces) {
273 Ok((input, ()))
274 } else {
275 Err(nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Verify)))
276 }
277}
278
279fn element<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
280 let (input, link) = any_link(input, state)?;
281
282 if let Ok((input, _)) = push_indentation(input, state) {
283 let (input, children) = links(input, state)?;
284 Ok((input, link.with_children(children)))
285 } else {
286 Ok((input, link))
287 }
288}
289
290fn first_line<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
291 element(input, state)
292}
293
294fn line<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Link> {
295 preceded(
296 |i| check_indentation(i, state),
297 |i| element(i, state)
298 ).parse(input)
299}
300
301fn links<'a>(input: &'a str, state: &ParserState) -> IResult<&'a str, Vec<Link>> {
302 let (input, first) = first_line(input, state)?;
303 let (input, rest) = many0(|i| line(i, state)).parse(input)?;
304
305 state.pop_indentation();
306
307 let mut result = vec![first];
308 result.extend(rest);
309 Ok((input, result))
310}
311
312pub fn parse_document(input: &str) -> IResult<&str, Vec<Link>> {
313 let state = ParserState::new();
314
315 let input = input.trim_start_matches(|c: char| c == '\n' || c == '\r');
317
318 if input.trim().is_empty() {
320 return Ok(("", vec![]));
321 }
322
323 let (input, result) = links(input, &state)?;
324 let (input, _) = whitespace(input)?;
325 let (input, _) = eof(input)?;
326
327 Ok((input, result))
328}
329