Skip to content

Commit b20cdd1

Browse files
committed
Add documentation example
1 parent bac9acd commit b20cdd1

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/ast/comments.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
// limitations under the License.
1212

1313
//! Provides a representation of source code comments in parsed SQL code.
14+
//!
15+
//! See [Comments::find] for an example.
1416
1517
#[cfg(not(feature = "std"))]
1618
use alloc::{string::String, vec::Vec};
@@ -40,6 +42,45 @@ impl Comments {
4042
/// Finds comments starting within the given location range. The order of
4143
/// iterator reflects the order of the comments as encountered in the parsed
4244
/// source code.
45+
///
46+
/// # Example
47+
/// ```rust
48+
/// use sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Location};
49+
///
50+
/// let sql = r#"/*
51+
/// header comment ...
52+
/// ... spanning multiple lines
53+
/// */
54+
///
55+
/// -- first statement
56+
/// SELECT 'hello' /* world */ FROM DUAL;
57+
///
58+
/// -- second statement
59+
/// SELECT 123 FROM DUAL;
60+
///
61+
/// -- trailing comment
62+
/// "#;
63+
///
64+
/// let (ast, comments) = Parser::parse_sql_with_comments(&GenericDialect, sql).unwrap();
65+
///
66+
/// // all comments appearing before line seven, i.e. before the first statement itself
67+
/// assert_eq!(
68+
/// &comments.find(..Location::new(7, 1)).map(|c| c.as_str()).collect::<Vec<_>>(),
69+
/// &["\n header comment ...\n ... spanning multiple lines\n", " first statement\n"]);
70+
///
71+
/// // all comments appearing within the first statement
72+
/// assert_eq!(
73+
/// &comments.find(Location::new(7, 1)..Location::new(8,1)).map(|c| c.as_str()).collect::<Vec<_>>(),
74+
/// &[" world "]);
75+
///
76+
/// // all comments appearing within or after the first statement
77+
/// assert_eq!(
78+
/// &comments.find(Location::new(7, 1)..).map(|c| c.as_str()).collect::<Vec<_>>(),
79+
/// &[" world ", " second statement\n", " trailing comment\n"]);
80+
/// ```
81+
///
82+
/// The [Spanned](crate::ast::Spanned) trait allows you to access location
83+
/// information for certain AST nodes.
4384
pub fn find<R: RangeBounds<Location>>(&self, range: R) -> Iter<'_> {
4485
let (start, end) = (
4586
self.start_index(range.start_bound()),

0 commit comments

Comments
 (0)