Skip to main content

links_notation/
comments.rs

1//! Comments, and the rule that decides where one starts.
2//!
3//! A comment starts at a `#` written where a line or a token starts and runs to
4//! the end of the line, unless the `#` opens a value:
5//!
6//! - at the start of a line, after any indentation, a `#` always starts one;
7//! - later on a line, after a space or a tab, a `#` starts one only when no
8//!   character that could continue a bare reference follows it, that is when
9//!   whitespace, the end of the document, `(`, `)` or `:` comes next. So
10//!   `a: b # why` and `a: b #` hold a comment, while `tag #release` is the link
11//!   of `tag` and `#release` (issue #444): a value is never silently dropped.
12//!
13//! A `#` written inside a token (`issue#1047`) or inside a delimited reference
14//! (`"# not a comment"`) is an ordinary character. The parser never sees it: [`strip_comments`] replaces
15//! every byte of every comment with a space before the document is parsed, so
16//! the notation itself stays exactly as it was and a position reported by the
17//! parser still points at the same character of the document the caller wrote.
18
19use crate::quotes::{DelimitedReferences, QUOTES};
20use crate::reference_literal::reference_literal_end;
21
22/// The character that opens a comment.
23pub const COMMENT: char = '#';
24
25/// What ends a bare reference. A token starts after one of these, at the start
26/// of the document, and right after a delimited reference or a versioned
27/// literal: the places the parser reads a reference from.
28const SEPARATORS: [u8; 7] = *b" \t\n\r(:)";
29
30/// What can stand before a comment: the comment is the first thing on a line,
31/// or it follows whitespace. A `#` inside a word is part of that word, so
32/// `issue#1047` is a reference and not the start of a comment.
33const BEFORE_COMMENT: [u8; 4] = *b" \t\n\r";
34
35/// Indentation: what may stand between the start of a line and a comment.
36const INDENTATION: [u8; 2] = *b" \t";
37
38/// Whether the `#` at byte `position` of `document` starts a comment: it opens
39/// a token, and either only indentation stands before it on its line or no
40/// character that could continue a bare reference follows it.
41///
42/// The comment stripper and the stream parser both judge a `#` with this one
43/// rule, so they always agree on where a comment starts.
44pub(crate) fn opens_comment(document: &[u8], position: usize) -> bool {
45    if document.get(position) != Some(&(COMMENT as u8)) {
46        return false;
47    }
48    if !follows(document, position, &BEFORE_COMMENT) {
49        return false;
50    }
51    let line_start = document[..position]
52        .iter()
53        .rposition(|byte| !INDENTATION.contains(byte));
54    match line_start {
55        None => return true,
56        Some(before) if matches!(document[before], b'\n' | b'\r') => return true,
57        Some(_) => {}
58    }
59    document
60        .get(position + 1)
61        .is_none_or(|next| SEPARATORS.contains(next))
62}
63
64/// Blanks out every comment in `document`, keeping every other byte where it
65/// was.
66///
67/// Comments are replaced rather than removed so that a byte offset in the
68/// result is the same byte offset in `document`: the line and column a parse
69/// error reports are the line and column the writer sees in their file.
70///
71/// A `#` inside a delimited reference is content, so `"# not a comment"` is
72/// still one reference. The document is read token by token, the way the
73/// parser reads it, so this holds as well for a reference that starts right
74/// after a group, another reference or a literal, and references are read in
75/// the document as written, as the parser reads them (issue #377).
76///
77/// # Examples
78/// ```
79/// use links_notation::comments::strip_comments;
80///
81/// assert_eq!(strip_comments("a: b # why\n"), "a: b      \n");
82/// assert_eq!(strip_comments("\"# kept\"\n"), "\"# kept\"\n");
83/// assert_eq!(strip_comments("tag #release\n"), "tag #release\n");
84/// assert_eq!(strip_comments("issue#1047\n"), "issue#1047\n");
85/// assert_eq!(strip_comments("(a)\" #kept\"\n"), "(a)\" #kept\"\n");
86/// ```
87pub fn strip_comments(document: &str) -> String {
88    let mut bytes = document.as_bytes().to_vec();
89    let references = DelimitedReferences::new(document);
90    let mut position = 0;
91    // Whether a token may start at `position`.
92    let mut token_start = true;
93
94    while position < bytes.len() {
95        let byte = bytes[position];
96
97        if byte == COMMENT as u8 && opens_comment(document.as_bytes(), position) {
98            while position < bytes.len() && bytes[position] != b'\n' && bytes[position] != b'\r' {
99                bytes[position] = b' ';
100                position += 1;
101            }
102            continue;
103        }
104
105        if SEPARATORS.contains(&byte) {
106            token_start = true;
107            position += 1;
108            continue;
109        }
110
111        if token_start {
112            if let Some(end) = delimited_token_end(document, position, &references) {
113                position = end;
114                continue;
115            }
116        }
117
118        // Anything else is part of a bare reference, which runs to a separator.
119        token_start = false;
120        position += 1;
121    }
122
123    // Only whole comments were replaced, and only by spaces, so what is left is
124    // the document it was read from with some of its bytes blanked.
125    String::from_utf8(bytes).expect("blanking comment bytes keeps the document valid UTF-8")
126}
127
128/// The offset just past the versioned literal or delimited reference that
129/// starts the token at `start`, or `None` when the token there is a bare
130/// reference: a delimiter run that never closes is read as one, as the parser
131/// reads it.
132fn delimited_token_end(
133    document: &str,
134    start: usize,
135    references: &DelimitedReferences,
136) -> Option<usize> {
137    if let Some(end) = reference_literal_end(document, start) {
138        return Some(end);
139    }
140    if QUOTES.contains(&document.as_bytes()[start]) {
141        return references.end_at(document, start);
142    }
143    None
144}
145
146/// Reports whether the byte before `position` is one of `allowed`, treating the
147/// start of the document as one of them.
148fn follows(bytes: &[u8], position: usize, allowed: &[u8]) -> bool {
149    match position {
150        0 => true,
151        _ => allowed.contains(&bytes[position - 1]),
152    }
153}