Skip to main content

sqlparser/ast/
comments.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5// http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12
13//! Provides a representation of source code comments in parsed SQL code.
14//!
15//! See [Comments::find] for an example.
16
17#[cfg(not(feature = "std"))]
18use alloc::{string::String, vec::Vec};
19
20use core::{
21    ops::{Bound, Deref, RangeBounds},
22    slice,
23};
24
25use crate::tokenizer::{Location, Span};
26
27/// An opaque container for comments from a parse SQL source code.
28#[derive(Default, Debug, Clone)]
29pub struct Comments(Vec<CommentWithSpan>);
30
31impl Comments {
32    /// Accepts `comment` if its the first or is located strictly after the
33    /// last accepted comment.  In other words, this method will skip the
34    /// comment if its comming out of order (as encountered in the parsed
35    /// source code.)
36    pub fn offer(&mut self, comment: CommentWithSpan) {
37        if self
38            .0
39            .last()
40            .map(|last| last.span < comment.span)
41            .unwrap_or(true)
42        {
43            self.0.push(comment);
44        }
45    }
46
47    /// Finds comments starting within the given location range. The order of
48    /// iterator reflects the order of the comments as encountered in the parsed
49    /// source code.
50    ///
51    /// # Example
52    /// ```rust
53    /// use sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Location};
54    ///
55    /// let sql = r#"/*
56    ///  header comment ...
57    ///  ... spanning multiple lines
58    /// */
59    ///
60    ///  -- first statement
61    ///  SELECT 'hello' /* world */ FROM DUAL;
62    ///
63    ///  -- second statement
64    ///  SELECT 123 FROM DUAL;
65    ///
66    ///  -- trailing comment
67    /// "#;
68    ///
69    /// let (ast, comments) = Parser::parse_sql_with_comments(&GenericDialect, sql).unwrap();
70    ///
71    /// // all comments appearing before line seven, i.e. before the first statement itself
72    /// assert_eq!(
73    ///    &comments.find(..Location::new(7, 1)).map(|c| c.as_str()).collect::<Vec<_>>(),
74    ///    &["\n header comment ...\n ... spanning multiple lines\n", " first statement"]);
75    ///
76    /// // all comments appearing within the first statement
77    /// assert_eq!(
78    ///    &comments.find(Location::new(7, 1)..Location::new(8,1)).map(|c| c.as_str()).collect::<Vec<_>>(),
79    ///    &[" world "]);
80    ///
81    /// // all comments appearing within or after the first statement
82    /// assert_eq!(
83    ///    &comments.find(Location::new(7, 1)..).map(|c| c.as_str()).collect::<Vec<_>>(),
84    ///    &[" world ", " second statement", " trailing comment"]);
85    /// ```
86    ///
87    /// The [Spanned](crate::ast::Spanned) trait allows you to access location
88    /// information for certain AST nodes.
89    pub fn find<R: RangeBounds<Location>>(&self, range: R) -> Iter<'_> {
90        let (start, end) = (
91            self.start_index(range.start_bound()),
92            self.end_index(range.end_bound()),
93        );
94        debug_assert!((0..=self.0.len()).contains(&start));
95        debug_assert!((0..=self.0.len()).contains(&end));
96        // in case the user specified a reverse range
97        Iter(if start <= end {
98            self.0[start..end].iter()
99        } else {
100            self.0[0..0].iter()
101        })
102    }
103
104    /// Finds comments immediately before the token starting at `location`, in source order.
105    ///
106    /// # Example
107    /// ```rust
108    /// use sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Location};
109    ///
110    /// let sql = r#"SELECT 1; -- one
111    /// -- two
112    /// SELECT 2"#;
113    /// let (_, comments) = Parser::parse_sql_with_comments(&GenericDialect, sql).unwrap();
114    ///
115    /// let second = Location::new(3, 1);
116    /// assert_eq!(
117    ///    &comments.find_before(second).map(|c| c.as_str()).collect::<Vec<_>>(),
118    ///    &[" one", " two"]);
119    /// ```
120    pub fn find_before(&self, location: Location) -> Iter<'_> {
121        let end = self.end_index(Bound::Excluded(&location));
122        let start = self.0[..end].partition_point(|c| c.next_token_start != Some(location));
123        Iter(self.0[start..end].iter())
124    }
125
126    pub(crate) fn set_next_token_start(&mut self, next_token_start: Location) {
127        for comment in self
128            .0
129            .iter_mut()
130            .rev()
131            .take_while(|c| c.next_token_start.is_none())
132        {
133            comment.next_token_start = Some(next_token_start);
134        }
135    }
136
137    /// Find the index of the first comment starting "before" the given location.
138    ///
139    /// The returned index is _inclusive_ and within the range of `0..=self.0.len()`.
140    fn start_index(&self, location: Bound<&Location>) -> usize {
141        match location {
142            Bound::Included(location) => {
143                match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
144                    Ok(i) => i,
145                    Err(i) => i,
146                }
147            }
148            Bound::Excluded(location) => {
149                match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
150                    Ok(i) => i + 1,
151                    Err(i) => i,
152                }
153            }
154            Bound::Unbounded => 0,
155        }
156    }
157
158    /// Find the index of the first comment starting "after" the given location.
159    ///
160    /// The returned index is _exclusive_ and within the range of `0..=self.0.len()`.
161    fn end_index(&self, location: Bound<&Location>) -> usize {
162        match location {
163            Bound::Included(location) => {
164                match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
165                    Ok(i) => i + 1,
166                    Err(i) => i,
167                }
168            }
169            Bound::Excluded(location) => {
170                match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
171                    Ok(i) => i,
172                    Err(i) => i,
173                }
174            }
175            Bound::Unbounded => self.0.len(),
176        }
177    }
178}
179
180impl From<Comments> for Vec<CommentWithSpan> {
181    fn from(comments: Comments) -> Self {
182        comments.0
183    }
184}
185
186/// A source code comment with information of its entire span.
187#[derive(Debug, Clone, PartialEq, Eq, Hash)]
188pub struct CommentWithSpan {
189    /// The source code comment iself
190    pub comment: Comment,
191    /// The span of the comment including its markers
192    pub span: Span,
193    /// End of the previous non-whitespace source token, or `None` before the first token.
194    pub prev_token_end: Option<Location>,
195    /// Start of the next non-whitespace source token, or `None` after the last token.
196    pub next_token_start: Option<Location>,
197}
198
199impl Deref for CommentWithSpan {
200    type Target = Comment;
201
202    fn deref(&self) -> &Self::Target {
203        &self.comment
204    }
205}
206
207/// A unified type of the different source code comment formats.
208#[derive(Debug, Clone, PartialEq, Eq, Hash)]
209pub enum Comment {
210    /// A single line comment, typically introduced with a prefix and spanning
211    /// until end-of-line or end-of-file in the source code.
212    ///
213    /// Note: `content` will include the terminating new-line character, if any.
214    /// A single-line comment, typically introduced with a prefix and spanning
215    /// until end-of-line or end-of-file in the source code.
216    ///
217    /// Note: `content` will include the terminating new-line character, if any.
218    SingleLine {
219        /// The content of the comment (including trailing newline, if any).
220        content: String,
221        /// The prefix introducing the comment (e.g. `--`, `#`).
222        prefix: String,
223    },
224
225    /// A multi-line comment, typically enclosed in `/* .. */` markers. The
226    /// string represents the content excluding the markers.
227    MultiLine(String),
228}
229
230impl Comment {
231    /// Retrieves the content of the comment as string slice.
232    pub fn as_str(&self) -> &str {
233        match self {
234            Comment::SingleLine { content, prefix: _ } => content.as_str(),
235            Comment::MultiLine(content) => content.as_str(),
236        }
237    }
238}
239
240impl Deref for Comment {
241    type Target = str;
242
243    fn deref(&self) -> &Self::Target {
244        self.as_str()
245    }
246}
247
248/// An opaque iterator over comments returned by [`Comments::find`] and [`Comments::find_before`].
249pub struct Iter<'a>(slice::Iter<'a, CommentWithSpan>);
250
251impl<'a> Iterator for Iter<'a> {
252    type Item = &'a CommentWithSpan;
253
254    fn next(&mut self) -> Option<Self::Item> {
255        self.0.next()
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn test_find() {
265        let comments = {
266            // ```
267            // -- abc
268            //   /* hello */--, world
269            // /* def
270            //  ghi
271            //  jkl
272            // */
273            // ```
274            let mut c = Comments(Vec::new());
275            c.offer(CommentWithSpan {
276                comment: Comment::SingleLine {
277                    content: " abc".into(),
278                    prefix: "--".into(),
279                },
280                span: Span::new((1, 1).into(), (1, 7).into()),
281                prev_token_end: None,
282                next_token_start: None,
283            });
284            c.offer(CommentWithSpan {
285                comment: Comment::MultiLine(" hello ".into()),
286                span: Span::new((2, 3).into(), (2, 14).into()),
287                prev_token_end: None,
288                next_token_start: None,
289            });
290            c.offer(CommentWithSpan {
291                comment: Comment::SingleLine {
292                    content: ", world".into(),
293                    prefix: "--".into(),
294                },
295                span: Span::new((2, 14).into(), (2, 21).into()),
296                prev_token_end: None,
297                next_token_start: None,
298            });
299            c.offer(CommentWithSpan {
300                comment: Comment::MultiLine(" def\n ghi\n jkl\n".into()),
301                span: Span::new((3, 3).into(), (7, 1).into()),
302                prev_token_end: None,
303                next_token_start: None,
304            });
305            c
306        };
307
308        fn find<R: RangeBounds<Location>>(comments: &Comments, range: R) -> Vec<&str> {
309            comments.find(range).map(|c| c.as_str()).collect::<Vec<_>>()
310        }
311
312        // ~ end-points only --------------------------------------------------
313        assert_eq!(find(&comments, ..Location::new(0, 0)), Vec::<&str>::new());
314        assert_eq!(find(&comments, ..Location::new(2, 1)), vec![" abc"]);
315        assert_eq!(find(&comments, ..Location::new(2, 3)), vec![" abc"]);
316        assert_eq!(
317            find(&comments, ..=Location::new(2, 3)),
318            vec![" abc", " hello "]
319        );
320        assert_eq!(
321            find(&comments, ..=Location::new(2, 3)),
322            vec![" abc", " hello "]
323        );
324        assert_eq!(
325            find(&comments, ..Location::new(2, 15)),
326            vec![" abc", " hello ", ", world"]
327        );
328
329        // ~ start-points only ------------------------------------------------
330        assert_eq!(
331            find(&comments, Location::new(1000, 1000)..),
332            Vec::<&str>::new()
333        );
334        assert_eq!(
335            find(&comments, Location::new(2, 14)..),
336            vec![", world", " def\n ghi\n jkl\n"]
337        );
338        assert_eq!(
339            find(&comments, Location::new(2, 15)..),
340            vec![" def\n ghi\n jkl\n"]
341        );
342        assert_eq!(
343            find(&comments, Location::new(0, 0)..),
344            vec![" abc", " hello ", ", world", " def\n ghi\n jkl\n"]
345        );
346        assert_eq!(
347            find(&comments, Location::new(1, 1)..),
348            vec![" abc", " hello ", ", world", " def\n ghi\n jkl\n"]
349        );
350
351        // ~ ranges -----------------------------------------------------------
352        assert_eq!(
353            find(&comments, Location::new(2, 1)..Location::new(1, 1)),
354            Vec::<&str>::new()
355        );
356        assert_eq!(
357            find(&comments, Location::new(1, 1)..Location::new(2, 3)),
358            vec![" abc"]
359        );
360        assert_eq!(
361            find(&comments, Location::new(1, 1)..=Location::new(2, 3)),
362            vec![" abc", " hello "]
363        );
364        assert_eq!(
365            find(&comments, Location::new(1, 1)..=Location::new(2, 10)),
366            vec![" abc", " hello "]
367        );
368        assert_eq!(
369            find(&comments, Location::new(1, 1)..=Location::new(2, 14)),
370            vec![" abc", " hello ", ", world"]
371        );
372        assert_eq!(
373            find(&comments, Location::new(1, 1)..Location::new(2, 15)),
374            vec![" abc", " hello ", ", world"]
375        );
376
377        // ~ find everything --------------------------------------------------
378        assert_eq!(
379            find(&comments, ..),
380            vec![" abc", " hello ", ", world", " def\n ghi\n jkl\n"]
381        );
382    }
383
384    #[test]
385    fn test_find_before() {
386        let first_token = Location::new(2, 1);
387        let second_token = Location::new(4, 1);
388        let mut comments = Comments::default();
389        for comment in [
390            CommentWithSpan {
391                comment: Comment::SingleLine {
392                    content: " first".into(),
393                    prefix: "--".into(),
394                },
395                span: Span::new((1, 1).into(), (1, 9).into()),
396                prev_token_end: None,
397                next_token_start: Some(first_token),
398            },
399            CommentWithSpan {
400                comment: Comment::SingleLine {
401                    content: " second".into(),
402                    prefix: "--".into(),
403                },
404                span: Span::new((2, 11).into(), (2, 20).into()),
405                prev_token_end: Some(Location::new(2, 10)),
406                next_token_start: Some(second_token),
407            },
408            CommentWithSpan {
409                comment: Comment::SingleLine {
410                    content: " third".into(),
411                    prefix: "--".into(),
412                },
413                span: Span::new((3, 1).into(), (3, 9).into()),
414                prev_token_end: Some(Location::new(2, 10)),
415                next_token_start: Some(second_token),
416            },
417            CommentWithSpan {
418                comment: Comment::SingleLine {
419                    content: " tail".into(),
420                    prefix: "--".into(),
421                },
422                span: Span::new((4, 11).into(), (4, 18).into()),
423                prev_token_end: Some(Location::new(4, 10)),
424                next_token_start: None,
425            },
426        ] {
427            comments.offer(comment);
428        }
429
430        fn find_before(comments: &Comments, location: Location) -> Vec<&str> {
431            comments.find_before(location).map(|c| c.as_str()).collect()
432        }
433
434        assert_eq!(find_before(&comments, first_token), vec![" first"]);
435        assert_eq!(
436            find_before(&comments, second_token),
437            vec![" second", " third"]
438        );
439        for location in [
440            Location::new(0, 0),
441            Location::new(1, 3),
442            Location::new(2, 8),
443            Location::new(3, 12),
444            Location::new(4, 3),
445            Location::new(5, 1),
446        ] {
447            assert_eq!(
448                find_before(&comments, location),
449                Vec::<&str>::new(),
450                "{location:?}"
451            );
452        }
453        assert_eq!(
454            find_before(&Comments::default(), first_token),
455            Vec::<&str>::new()
456        );
457    }
458}