Skip to content

Commit f56bcf0

Browse files
committed
Implemented no_std with feature gated std support
1 parent d6763d4 commit f56bcf0

6 files changed

Lines changed: 330 additions & 263 deletions

File tree

src/ast.rs

Lines changed: 50 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -12,70 +12,74 @@ use alloc::vec::Vec;
1212

1313
use crate::source::SqlSource;
1414

15-
/// A single SQL file plus all [`Statement`].
15+
/// A single SQL Source (such as a file) plus all [`Statement`].
1616
#[derive(Debug)]
17-
pub struct ParsedSqlFile {
18-
file: SqlSource,
17+
pub struct ParsedSqlSource {
18+
source: SqlSource,
1919
statements: Vec<Statement>,
2020
}
2121

22-
impl ParsedSqlFile {
22+
#[cfg(feature = "std")]
23+
impl ParsedSqlSource {
24+
/// Getter method for returning the current object' source's path
25+
#[must_use]
26+
pub fn path(&self) -> Option<&std::path::Path> {
27+
self.source.path()
28+
}
29+
30+
/// Getter that returns an [`std::path::PathBuf`] for the path rather than `&Path`
31+
#[must_use]
32+
pub fn path_into_path_buf(&self) -> Option<std::path::PathBuf> {
33+
self.source.path_into_path_buf()
34+
}
35+
}
36+
37+
impl ParsedSqlSource {
2338
/// Parses a [`SqlSource`] into `sqlparser` [`Statement`] nodes.
2439
///
2540
/// This is the AST layer used by the `comments` module to attach leading
2641
/// comment spans to statements/columns.
2742
///
2843
/// # Parameters
29-
/// - `file`: the [`SqlSource`] to parse
44+
/// - `source`: the [`SqlSource`] to parse
3045
///
3146
/// # Errors
3247
/// - Returns [`ParserError`] if parsing fails
33-
pub fn parse<D>(file: SqlSource) -> Result<Self, ParserError>
48+
pub fn parse<D>(source: SqlSource) -> Result<Self, ParserError>
3449
where
3550
D: Dialect + Default,
3651
{
37-
let statements = Parser::parse_sql(&D::default(), file.content())?;
38-
Ok(Self { file, statements })
52+
let statements = Parser::parse_sql(&D::default(), source.content())?;
53+
Ok(Self { source, statements })
3954
}
4055

4156
/// Getter method for returning the [`SqlSource`]
4257
#[must_use]
43-
pub const fn file(&self) -> &SqlSource {
44-
&self.file
58+
pub const fn source(&self) -> &SqlSource {
59+
&self.source
4560
}
46-
47-
/// Getter method for returning the current object's file's path
48-
#[must_use]
49-
pub fn path(&self) -> Option<&std::path::Path> {
50-
self.file.path()
51-
}
52-
53-
/// Getter that returns an [`std::path::PathBuf`] for the path rather than `&Path`
54-
#[must_use]
55-
pub fn path_into_path_buf(&self) -> Option<std::path::PathBuf> {
56-
self.file.path_into_path_buf()
57-
}
58-
59-
/// Getter for the file's content
61+
/// Getter for the source's content
6062
#[must_use]
6163
pub fn content(&self) -> &str {
62-
self.file.content()
64+
self.source.content()
6365
}
66+
}
6467

68+
impl ParsedSqlSource {
6569
/// Getter method for returning the vector of all statements [`Statement`]
6670
#[must_use]
6771
pub fn statements(&self) -> &[Statement] {
6872
&self.statements
6973
}
7074
}
7175

72-
/// Struct to contain the vector of parsed SQL files
76+
/// Struct to contain the vector of parsed SQL sources
7377
#[derive(Debug)]
74-
pub struct ParsedSqlFileSet {
75-
files: Vec<ParsedSqlFile>,
78+
pub struct ParsedSqlSourceSet {
79+
sources: Vec<ParsedSqlSource>,
7680
}
7781

78-
impl ParsedSqlFileSet {
82+
impl ParsedSqlSourceSet {
7983
/// Method that parses a set of all members in a [`SqlSource`]
8084
///
8185
/// # Parameters
@@ -87,16 +91,16 @@ impl ParsedSqlFileSet {
8791
where
8892
D: Dialect + Default,
8993
{
90-
let files =
91-
set.into_iter().map(ParsedSqlFile::parse::<D>).collect::<Result<Vec<_>, _>>()?;
94+
let sources =
95+
set.into_iter().map(ParsedSqlSource::parse::<D>).collect::<Result<Vec<_>, _>>()?;
9296

93-
Ok(Self { files })
97+
Ok(Self { sources })
9498
}
9599

96-
/// Getter method for returning the vector of all [`ParsedSqlFile`]
100+
/// Getter method for returning the vector of all [`ParsedSqlSource`]
97101
#[must_use]
98-
pub fn files(&self) -> &[ParsedSqlFile] {
99-
&self.files
102+
pub fn sources(&self) -> &[ParsedSqlSource] {
103+
&self.sources
100104
}
101105
}
102106

@@ -119,7 +123,7 @@ mod tests {
119123
let sql = "CREATE TABLE users (id INTEGER PRIMARY KEY);";
120124
fs::write(&file_path, sql)?;
121125
let sql_file = SqlSource::from_path(&file_path)?;
122-
let parsed = ParsedSqlFile::parse::<GenericDialect>(sql_file)?;
126+
let parsed = ParsedSqlSource::parse::<GenericDialect>(sql_file)?;
123127
assert_eq!(parsed.path(), Some(file_path.as_path()));
124128
assert_eq!(parsed.content(), sql);
125129
assert_eq!(parsed.statements().len(), 1);
@@ -141,8 +145,8 @@ mod tests {
141145
fs::write(&file1, sql1)?;
142146
fs::write(&file2, sql2)?;
143147
let set = SqlSource::sql_sources(&base, &[])?;
144-
let parsed_set = ParsedSqlFileSet::parse_all::<GenericDialect>(set)?;
145-
let existing_files = parsed_set.files();
148+
let parsed_set = ParsedSqlSourceSet::parse_all::<GenericDialect>(set)?;
149+
let existing_files = parsed_set.sources();
146150
assert_eq!(existing_files.len(), 2);
147151
for parsed in existing_files {
148152
assert_eq!(parsed.statements().len(), 1);
@@ -166,7 +170,7 @@ mod tests {
166170
let sql = "CREATE TABLE t (id INTEGER PRIMARY KEY);";
167171
fs::write(&file_path, sql)?;
168172
let sql_file = SqlSource::from_path(&file_path)?;
169-
let parsed = ParsedSqlFile::parse::<GenericDialect>(sql_file)?;
173+
let parsed = ParsedSqlSource::parse::<GenericDialect>(sql_file)?;
170174
assert_eq!(parsed.path_into_path_buf(), Some(file_path));
171175
let _ = fs::remove_dir_all(&base);
172176
Ok(())
@@ -190,8 +194,8 @@ mod tests {
190194
CREATE TABLE t (id INTEGER PRIMARY KEY);
191195
";
192196

193-
let src = SqlSource::from_str(sql.to_owned(), None);
194-
let parsed = ParsedSqlFile::parse::<PostgreSqlDialect>(src)?;
197+
let src = SqlSource::from(sql.to_owned());
198+
let parsed = ParsedSqlSource::parse::<PostgreSqlDialect>(src)?;
195199
assert!(
196200
parsed.statements().len() >= 2,
197201
"expected at least 2 statements (function + table)"
@@ -232,11 +236,11 @@ mod tests {
232236
fs::write(&file2, pg_sql)?;
233237

234238
let set = SqlSource::sql_sources(&base, &[])?;
235-
let parsed_set = ParsedSqlFileSet::parse_all::<GenericDialect>(set)?;
239+
let parsed_set = ParsedSqlSourceSet::parse_all::<GenericDialect>(set)?;
236240

237-
assert_eq!(parsed_set.files().len(), 2);
241+
assert_eq!(parsed_set.sources().len(), 2);
238242

239-
for parsed in parsed_set.files() {
243+
for parsed in parsed_set.sources() {
240244
assert!(
241245
parsed.statements().iter().any(|s| matches!(s, Statement::CreateTable { .. })),
242246
"expected CreateTable in parsed file; got statements: {:?}",
@@ -251,8 +255,8 @@ mod tests {
251255
#[test]
252256
fn parsed_sql_file_parse_invalid_sql_returns_error() {
253257
let sql = "CREATE TABLE";
254-
let src = SqlSource::from_str(sql.to_owned(), None);
255-
let res = ParsedSqlFile::parse::<GenericDialect>(src);
258+
let src = SqlSource::from(sql.to_owned());
259+
let res = ParsedSqlSource::parse::<GenericDialect>(src);
256260
assert!(res.is_err(), "expected parse to fail for invalid SQL");
257261
}
258262
}

src/comments.rs

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,9 @@
55
//! - **inline**: a comment that appears after code on the same line (ignored)
66
//! - **interstitial**: a comment inside a statement (ignored)
77
8-
use std::fmt;
8+
use crate::ast::ParsedSqlSource;
99

10-
use crate::ast::ParsedSqlFile;
11-
12-
use alloc::borrow::ToOwned;
13-
use alloc::string::String;
14-
use alloc::vec::Vec;
10+
use alloc::{borrow::ToOwned, string::String, vec::Vec};
1511

1612
/// Represents a line/column location within a source file.
1713
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
@@ -152,8 +148,8 @@ pub enum CommentError {
152148
},
153149
}
154150

155-
impl fmt::Display for CommentError {
156-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151+
impl core::fmt::Display for CommentError {
152+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
157153
match self {
158154
Self::UnmatchedMultilineCommentStart { location } => {
159155
write!(
@@ -175,7 +171,7 @@ impl fmt::Display for CommentError {
175171
}
176172
}
177173

178-
impl std::error::Error for CommentError {}
174+
impl core::error::Error for CommentError {}
179175

180176
/// Alias for comment results that may return a [`CommentError`]
181177
pub type CommentResult<T> = Result<T, CommentError>;
@@ -218,7 +214,7 @@ impl Comments {
218214
/// comment does not have an opening `/*`
219215
/// - Will return [`CommentError::UnterminatedMultiLineComment`] if a
220216
/// multiline comment doesn't end before `EOF`
221-
pub fn parse_all_comments_from_file(file: &ParsedSqlFile) -> CommentResult<Self> {
217+
pub fn parse_all_comments_from_file(file: &ParsedSqlSource) -> CommentResult<Self> {
222218
let src = file.content();
223219
let comments = Self::scan_comments(src)?;
224220
Ok(comments)
@@ -537,7 +533,7 @@ mod tests {
537533

538534
#[test]
539535
fn parse_comments() -> Result<(), Box<dyn std::error::Error>> {
540-
use crate::{ast::ParsedSqlFileSet, comments::Comments, source::SqlSource};
536+
use crate::{ast::ParsedSqlSourceSet, comments::Comments, source::SqlSource};
541537
let base = env::temp_dir().join("all_sql_files");
542538
let _ = fs::remove_dir_all(&base);
543539
fs::create_dir_all(&base)?;
@@ -554,12 +550,12 @@ mod tests {
554550
fs::File::create(&file4)?;
555551
fs::write(&file4, no_comments_sql())?;
556552
let set = SqlSource::sql_sources(&base, &[])?;
557-
let parsed_set = ParsedSqlFileSet::parse_all::<GenericDialect>(set)?;
553+
let parsed_set = ParsedSqlSourceSet::parse_all::<GenericDialect>(set)?;
558554

559-
for file in parsed_set.files() {
555+
for file in parsed_set.sources() {
560556
let parsed_comments = Comments::parse_all_comments_from_file(file)?;
561557
let filename = file
562-
.file()
558+
.source()
563559
.path()
564560
.and_then(|p| p.file_name())
565561
.and_then(|s| s.to_str())
@@ -773,20 +769,23 @@ CREATE TABLE posts (
773769

774770
#[test]
775771
fn single_line_comment_spans_are_correct() -> Result<(), Box<dyn std::error::Error>> {
776-
use crate::{ast::ParsedSqlFileSet, source::SqlSource};
772+
use crate::{ast::ParsedSqlSourceSet, source::SqlSource};
777773
let base = env::temp_dir().join("single_line_spans");
778774
let _ = fs::remove_dir_all(&base);
779775
fs::create_dir_all(&base)?;
780776
let file = base.join("single.sql");
781777
fs::File::create(&file)?;
782778
fs::write(&file, single_line_comments_sql())?;
783779
let set = SqlSource::sql_sources(&base, &[])?;
784-
let parsed_set = ParsedSqlFileSet::parse_all::<GenericDialect>(set)?;
780+
let parsed_set = ParsedSqlSourceSet::parse_all::<GenericDialect>(set)?;
785781
let file = parsed_set
786-
.files()
782+
.sources()
787783
.iter()
788784
.find(|f| {
789-
f.file().path().and_then(|p| p.to_str()).is_some_and(|p| p.ends_with("single.sql"))
785+
f.source()
786+
.path()
787+
.and_then(|p| p.to_str())
788+
.is_some_and(|p| p.ends_with("single.sql"))
790789
})
791790
.ok_or("single.sql should be present")?;
792791

@@ -811,20 +810,20 @@ CREATE TABLE posts (
811810

812811
#[test]
813812
fn multiline_comment_spans_are_correct() -> Result<(), Box<dyn std::error::Error>> {
814-
use crate::{ast::ParsedSqlFileSet, source::SqlSource};
813+
use crate::{ast::ParsedSqlSourceSet, source::SqlSource};
815814
let base = env::temp_dir().join("multi_line_spans");
816815
let _ = fs::remove_dir_all(&base);
817816
fs::create_dir_all(&base)?;
818817
let file = base.join("multi.sql");
819818
fs::File::create(&file)?;
820819
fs::write(&file, multiline_comments_sql())?;
821820
let set = SqlSource::sql_sources(&base, &[])?;
822-
let parsed_set = ParsedSqlFileSet::parse_all::<GenericDialect>(set)?;
821+
let parsed_set = ParsedSqlSourceSet::parse_all::<GenericDialect>(set)?;
823822
let file = parsed_set
824-
.files()
823+
.sources()
825824
.iter()
826825
.find(|f| {
827-
f.file().path().and_then(|p| p.to_str()).is_some_and(|p| p.ends_with("multi.sql"))
826+
f.source().path().and_then(|p| p.to_str()).is_some_and(|p| p.ends_with("multi.sql"))
828827
})
829828
.ok_or("multi.sql should be present")?;
830829

0 commit comments

Comments
 (0)