links_notation/cst.rs
1//! The concrete syntax tree of a Links Notation document.
2//!
3//! Every byte of a document belongs to exactly one token, so the text of the
4//! tree is the document itself, comments, blank lines, indentation, quotes and
5//! line endings included. A document is a list of `line` nodes; a line holds the
6//! tokens up to and including its line ending, and a parenthesized `group` node
7//! holds its own parentheses and the lines written between them. A group is part
8//! of the line it opens on, however many lines it spans.
9//!
10//! The tree records how a document was written; [`parse_lino_to_links`] reads
11//! what it means. They agree because a document is parsed before its tree is
12//! built, and the tokens are read with the same rules the parser uses: comments
13//! are found by [`strip_comments`], delimited references by the parser's own
14//! reader and versioned literals by the same prefix.
15//!
16//! [`parse_lino_to_links`]: crate::parse_lino_to_links
17//! [`strip_comments`]: crate::comments::strip_comments
18
19use crate::comments::COMMENT;
20use crate::parser::bare_reference_end;
21use crate::quotes::{DelimitedReferences, QUOTES};
22use crate::reference_literal::{decode_reference_literal, reference_literal_end};
23use crate::{ParseError, ParserConfig, check_document};
24use std::fmt;
25
26/// The kinds of nodes and tokens of a concrete syntax tree.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum CstKind {
29 /// The whole document: its lines.
30 Document,
31 /// One line: its tokens and groups, up to and including its line ending.
32 Line,
33 /// A parenthesized group: `(`, the lines inside it, and `)`.
34 Group,
35 /// A run of spaces and tabs.
36 Whitespace,
37 /// One line ending: `\n`, `\r\n` or `\r`.
38 Newline,
39 /// A comment, from `#` up to the line ending.
40 Comment,
41 /// `(`
42 OpenParen,
43 /// `)`
44 CloseParen,
45 /// `:`
46 Colon,
47 /// A bare, quoted or versioned literal reference.
48 Reference,
49}
50
51impl CstKind {
52 /// The name every Links Notation implementation gives this kind, as used in
53 /// [`CstNode::to_s_expression`]: `document`, `line`, `group`, `whitespace`,
54 /// `newline`, `comment`, `open_paren`, `close_paren`, `colon` or
55 /// `reference`.
56 pub fn as_str(self) -> &'static str {
57 match self {
58 CstKind::Document => "document",
59 CstKind::Line => "line",
60 CstKind::Group => "group",
61 CstKind::Whitespace => "whitespace",
62 CstKind::Newline => "newline",
63 CstKind::Comment => "comment",
64 CstKind::OpenParen => "open_paren",
65 CstKind::CloseParen => "close_paren",
66 CstKind::Colon => "colon",
67 CstKind::Reference => "reference",
68 }
69 }
70
71 /// Whether this kind is a token, rather than a node with children.
72 pub fn is_token(self) -> bool {
73 !matches!(self, CstKind::Document | CstKind::Line | CstKind::Group)
74 }
75}
76
77impl fmt::Display for CstKind {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 f.write_str(self.as_str())
80 }
81}
82
83/// One node or token of a concrete syntax tree.
84///
85/// Its [`Display`](fmt::Display) writes the exact text it was read from.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct CstNode {
88 /// What this node or token is.
89 pub kind: CstKind,
90 /// The children of a node, in document order; empty for a token.
91 pub children: Vec<CstNode>,
92 /// What a reference token means, its delimiters and escapes resolved and a
93 /// versioned literal decoded (the ID a parsed link has); `None` for every
94 /// other node and token.
95 pub value: Option<String>,
96 /// The delimiter a quoted reference token was written between (`'`, `"` or
97 /// `` ` ``); `None` for a bare or literal reference and every other kind.
98 pub quote: Option<char>,
99 /// A token's text exactly as written; empty for a node.
100 token_text: String,
101}
102
103impl CstNode {
104 fn node(kind: CstKind, children: Vec<CstNode>) -> Self {
105 CstNode {
106 kind,
107 children,
108 value: None,
109 quote: None,
110 token_text: String::new(),
111 }
112 }
113
114 fn token(kind: CstKind, text: &str) -> Self {
115 CstNode {
116 kind,
117 children: Vec::new(),
118 value: None,
119 quote: None,
120 token_text: text.to_owned(),
121 }
122 }
123
124 /// Whether this is a token rather than a node with children.
125 pub fn is_token(&self) -> bool {
126 self.kind.is_token()
127 }
128
129 /// The exact text this node or token was read from: a token's own text, and
130 /// the text of a node's children one after the other.
131 pub fn text(&self) -> String {
132 self.to_string()
133 }
134
135 /// Every token of this subtree, in document order.
136 pub fn tokens(&self) -> Vec<&CstNode> {
137 let mut tokens = Vec::new();
138 self.collect_tokens(&mut tokens);
139 tokens
140 }
141
142 fn collect_tokens<'a>(&'a self, tokens: &mut Vec<&'a CstNode>) {
143 if self.is_token() {
144 tokens.push(self);
145 } else {
146 for child in &self.children {
147 child.collect_tokens(tokens);
148 }
149 }
150 }
151
152 /// The tree as an S-expression: `(kind child ...)` for a node and
153 /// `kind:"text"` for a token, the text escaped as a JSON string would escape
154 /// `\`, `"`, line feeds, carriage returns and tabs. Two trees are the same
155 /// exactly when their S-expressions are.
156 ///
157 /// # Examples
158 /// ```
159 /// use links_notation::parse_lino_to_cst;
160 ///
161 /// assert_eq!(
162 /// parse_lino_to_cst("a '1'").unwrap().to_s_expression(),
163 /// r#"(document (line reference:"a" whitespace:" " reference:"'1'"))"#
164 /// );
165 /// ```
166 pub fn to_s_expression(&self) -> String {
167 let mut out = String::new();
168 self.write_s_expression(&mut out);
169 out
170 }
171
172 fn write_s_expression(&self, out: &mut String) {
173 if self.is_token() {
174 out.push_str(self.kind.as_str());
175 out.push_str(":\"");
176 for c in self.token_text.chars() {
177 match c {
178 '\\' => out.push_str("\\\\"),
179 '"' => out.push_str("\\\""),
180 '\n' => out.push_str("\\n"),
181 '\r' => out.push_str("\\r"),
182 '\t' => out.push_str("\\t"),
183 _ => out.push(c),
184 }
185 }
186 out.push('"');
187 return;
188 }
189 out.push('(');
190 out.push_str(self.kind.as_str());
191 for child in &self.children {
192 out.push(' ');
193 child.write_s_expression(out);
194 }
195 out.push(')');
196 }
197}
198
199impl fmt::Display for CstNode {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 if self.is_token() {
202 return f.write_str(&self.token_text);
203 }
204 for child in &self.children {
205 fmt::Display::fmt(child, f)?;
206 }
207 Ok(())
208 }
209}
210
211/// Reads a document, with comments, as a lossless concrete syntax tree.
212///
213/// Every character of the document, comments and whitespace included, belongs
214/// to exactly one token, so `parse_lino_to_cst(document)?.to_string()` is the
215/// document. The document is parsed first, so it is refused exactly when
216/// [`parse_lino_to_links`](crate::parse_lino_to_links) refuses it, with the
217/// same error.
218///
219/// # Examples
220/// ```
221/// use links_notation::{CstKind, parse_lino_to_cst};
222///
223/// let document = "# config\nname: 'my app' # quoted\n";
224/// let cst = parse_lino_to_cst(document).unwrap();
225/// assert_eq!(cst.to_string(), document);
226/// assert_eq!(cst.kind, CstKind::Document);
227///
228/// let quoted = cst
229/// .tokens()
230/// .into_iter()
231/// .find(|token| token.quote.is_some())
232/// .unwrap();
233/// assert_eq!(quoted.text(), "'my app'");
234/// assert_eq!(quoted.value.as_deref(), Some("my app"));
235///
236/// assert!(parse_lino_to_cst("(a").is_err());
237/// ```
238pub fn parse_lino_to_cst(document: &str) -> Result<CstNode, ParseError> {
239 parse_lino_to_cst_with_config(document, &ParserConfig::default())
240}
241
242/// Reads a document the way `config` says to as a lossless concrete syntax
243/// tree; see [`parse_lino_to_cst`].
244///
245/// Without comments, a `#` is read as part of a reference, as the parser reads
246/// it.
247///
248/// # Examples
249/// ```
250/// use links_notation::{CstKind, ParserConfig, parse_lino_to_cst_with_config};
251///
252/// let cst = parse_lino_to_cst_with_config("a #b", &ParserConfig::without_comments()).unwrap();
253/// let kinds: Vec<CstKind> = cst.tokens().iter().map(|token| token.kind).collect();
254/// assert_eq!(kinds, [CstKind::Reference, CstKind::Whitespace, CstKind::Reference]);
255/// assert_eq!(cst.to_string(), "a #b");
256/// ```
257pub fn parse_lino_to_cst_with_config(
258 document: &str,
259 config: &ParserConfig,
260) -> Result<CstNode, ParseError> {
261 let prepared = check_document(document, config)?;
262 build_cst(document, &prepared, config.comments)
263}
264
265/// A container being filled: the document or a group, with its line that is
266/// still open.
267struct Container {
268 kind: CstKind,
269 children: Vec<CstNode>,
270 line: Option<Vec<CstNode>>,
271}
272
273impl Container {
274 fn new(kind: CstKind, children: Vec<CstNode>) -> Self {
275 Container {
276 kind,
277 children,
278 line: None,
279 }
280 }
281
282 /// The line being filled, started when there is none.
283 fn line(&mut self) -> &mut Vec<CstNode> {
284 self.line.get_or_insert_with(Vec::new)
285 }
286
287 /// Adds the open line, if any, to the children.
288 fn close_line(&mut self) {
289 if let Some(line) = self.line.take() {
290 self.children.push(CstNode::node(CstKind::Line, line));
291 }
292 }
293
294 fn finish(mut self) -> CstNode {
295 self.close_line();
296 CstNode::node(self.kind, self.children)
297 }
298}
299
300/// The concrete syntax tree of `document`, which has already been parsed.
301/// `prepared` is the document the parser read: the same bytes, with its
302/// comments blanked when `comments` is on.
303fn build_cst(document: &str, prepared: &str, comments: bool) -> Result<CstNode, ParseError> {
304 // Blanking a comment keeps every byte where it was, so a position in one is
305 // the same position in the other.
306 debug_assert_eq!(document.len(), prepared.len());
307 let input = document.as_bytes();
308 let blanked = prepared.as_bytes();
309 // Bare references end where they end in the document the parser read.
310 // Delimited references and literals are read, as the parser reads them, in
311 // the document as written, so a comment never changes what a reference
312 // holds (issue #377).
313 let references = DelimitedReferences::new(document);
314 // The open containers, innermost last. A group joins the line it opens on
315 // when it closes; that line stays open until then, since every line break
316 // in between belongs to the group.
317 let mut containers = vec![Container::new(CstKind::Document, Vec::new())];
318 let mut position = 0;
319
320 while position < input.len() {
321 let byte = input[position];
322 let mut end = position + 1;
323 let innermost = containers.len() - 1;
324
325 if comments && byte == COMMENT as u8 && blanked[position] != byte {
326 // A blanked `#` opens a comment, which runs to the line ending.
327 while end < input.len() && input[end] != b'\n' && input[end] != b'\r' {
328 end += 1;
329 }
330 let token = CstNode::token(CstKind::Comment, &document[position..end]);
331 containers[innermost].line().push(token);
332 } else if byte == b'\r' || byte == b'\n' {
333 if byte == b'\r' && input.get(end) == Some(&b'\n') {
334 end += 1;
335 }
336 let token = CstNode::token(CstKind::Newline, &document[position..end]);
337 containers[innermost].line().push(token);
338 containers[innermost].close_line();
339 } else if byte == b' ' || byte == b'\t' {
340 while end < input.len() && (input[end] == b' ' || input[end] == b'\t') {
341 end += 1;
342 }
343 let token = CstNode::token(CstKind::Whitespace, &document[position..end]);
344 containers[innermost].line().push(token);
345 } else if byte == b'(' {
346 // Open the line the group belongs to before the group is filled.
347 containers[innermost].line();
348 let open = CstNode::token(CstKind::OpenParen, &document[position..end]);
349 containers.push(Container::new(CstKind::Group, vec![open]));
350 } else if byte == b')' {
351 if containers.len() == 1 {
352 return Err(ParseError::InternalError(format!(
353 "Unbalanced \")\" at offset {position}"
354 )));
355 }
356 let mut group = containers.pop().expect("a group is open");
357 group.close_line();
358 group.children.push(CstNode::token(
359 CstKind::CloseParen,
360 &document[position..end],
361 ));
362 let group = CstNode::node(CstKind::Group, group.children);
363 containers
364 .last_mut()
365 .expect("the document is open")
366 .line()
367 .push(group);
368 } else if byte == b':' {
369 let token = CstNode::token(CstKind::Colon, &document[position..end]);
370 containers[innermost].line().push(token);
371 } else {
372 let (reference_end, value, quote) =
373 read_reference(document, prepared, position, &references);
374 end = reference_end;
375 let mut token = CstNode::token(CstKind::Reference, &document[position..end]);
376 token.value = Some(value);
377 token.quote = quote;
378 containers[innermost].line().push(token);
379 }
380 position = end;
381 }
382
383 if containers.len() != 1 {
384 return Err(ParseError::InternalError(
385 "Unbalanced \"(\" at the end of the document".to_string(),
386 ));
387 }
388 Ok(containers.pop().expect("the document is open").finish())
389}
390
391/// The reference that starts at `start`, read as the parser reads it: where it
392/// ends, what it means, and the delimiter it was written between.
393fn read_reference(
394 document: &str,
395 prepared: &str,
396 start: usize,
397 references: &DelimitedReferences,
398) -> (usize, String, Option<char>) {
399 let blanked = prepared.as_bytes();
400 if let Some(end) = reference_literal_end(document, start) {
401 let text = &document[start..end];
402 let value = decode_reference_literal(text).unwrap_or_else(|_| text.to_owned());
403 return (end, value, None);
404 }
405 let first = blanked[start];
406 if QUOTES.contains(&first) {
407 if let Some(reading) = references.read(&document[start..]) {
408 return (start + reading.length, reading.value, Some(first as char));
409 }
410 }
411 // A bare reference ends where the parser ends it, colons included
412 // (issue #444).
413 let end = bare_reference_end(prepared, start);
414 (end, document[start..end].to_owned(), None)
415}