Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Spanned to retrieve source locations on AST nodes #1435

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1a77bac
feat(tokenizer): add source location spans to tokens
Nyrox Sep 16, 2024
d818012
feat: begin work on trait Spanned
Nyrox Sep 16, 2024
079a4e2
implement a bunch more stuff
Nyrox Sep 17, 2024
b97a781
Merge branch 'feat/ast-source-locations'
Nyrox Sep 17, 2024
df9ab1e
fix: restore old behaviour of location display
Nyrox Sep 17, 2024
b718c76
implement spans for eveeeeen more ast nodes
Nyrox Sep 17, 2024
8986a1e
feat: more ast nodes
Nyrox Sep 19, 2024
aeb4f3a
start working on better tests
Nyrox Sep 20, 2024
4de3209
feat: implement spans for Wildcard projections
Nyrox Sep 25, 2024
a04888a
make union_spans public
Nyrox Sep 26, 2024
1b2b03d
enable serde feat for spans and locations
Nyrox Sep 30, 2024
5f60bdc
feat: implement remaining ast nodes
Nyrox Oct 7, 2024
ea8a6b1
fix unused variable warnings
Nyrox Oct 8, 2024
6a9250a
undo parse_keyword signature change
Nyrox Oct 8, 2024
0804e99
fix: diverging hash and partialeq implementations
Nyrox Oct 8, 2024
eb9ff9a
Update src/ast/spans.rs
Nyrox Oct 9, 2024
a93cebc
improve docs & un-pub union_spans
Nyrox Oct 9, 2024
734264a
move union_spans to top of file
Nyrox Oct 9, 2024
441ceb1
replace old tests
Nyrox Oct 9, 2024
e6a4340
pr feedback
Nyrox Oct 11, 2024
16a3f2a
add small comment
Nyrox Oct 11, 2024
98b051d
refactor: rewrite all span implementations to pattern match exhaustiv…
Nyrox Oct 16, 2024
d76d1e0
for_clause is mssql, not mysql
Nyrox Oct 18, 2024
bf75fe4
Merge branch 'main' into main
Nyrox Oct 25, 2024
71c27ea
cargo fmt
Nyrox Oct 25, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 48 additions & 7 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

use crate::tokenizer::{Span, TokenWithLocation};

pub use self::data_type::{
ArrayElemTypeDef, CharLengthUnits, CharacterLength, DataType, ExactNumberInfo,
StructBracketKind, TimezoneInfo,
Expand Down Expand Up @@ -79,6 +81,9 @@ mod dml;
pub mod helpers;
mod operator;
mod query;
mod spans;
pub use spans::{Spanned, union_spans};

mod trigger;
mod value;

Expand Down Expand Up @@ -123,7 +128,7 @@ where
}

/// An identifier, decomposed into its value or character data and the quote style.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[derive(Debug, Clone, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct Ident {
Expand All @@ -132,8 +137,18 @@ pub struct Ident {
/// The starting quote if any. Valid quote characters are the single quote,
/// double quote, backtick, and opening square bracket.
pub quote_style: Option<char>,
/// The span of the identifier in the original SQL string.
pub span: Span,
}

impl PartialEq for Ident {
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.quote_style == other.quote_style
}
}

impl Eq for Ident {}

impl Ident {
/// Create a new identifier with the given value and no quotes.
pub fn new<S>(value: S) -> Self
Expand All @@ -143,6 +158,7 @@ impl Ident {
Ident {
value: value.into(),
quote_style: None,
span: Span::empty(),
}
}

Expand All @@ -156,6 +172,30 @@ impl Ident {
Ident {
value: value.into(),
quote_style: Some(quote),
span: Span::empty(),
}
}

pub fn with_span<S>(span: Span, value: S) -> Self
where
S: Into<String>,
{
Ident {
value: value.into(),
quote_style: None,
span,
}
}

pub fn with_quote_and_span<S>(quote: char, span: Span, value: S) -> Self
where
S: Into<String>,
{
assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for the assert I think we can remove to avoid panicking in any case. if we want to restrict the quote char the fn would rather return a Result<Self> I imagine, though in this case I think it could make more sense to let the parser accept any char

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing it sounds good to me, I just wanted to have the same behaviour as Ident::with_quote which still has the check, so it should prob. be removed in both places then

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the verdict here? Remove or not? :P I am not sure it's in the scope of this PR tbh.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I didn't realise the behavior exists already, it sounds reasonable to follow suit. The current behavior feels unusual to me though, and I agree that it'd be out of scope for this PR to change it. I can take a closer look at it and we can have the behavior here match the outcome

Ident {
value: value.into(),
quote_style: Some(quote),
span,
}
}
}
Expand All @@ -165,6 +205,7 @@ impl From<&str> for Ident {
Ident {
value: value.to_string(),
quote_style: None,
span: Span::empty(),
}
}
}
Expand Down Expand Up @@ -881,10 +922,10 @@ pub enum Expr {
/// `<search modifier>`
opt_search_modifier: Option<SearchModifier>,
},
Wildcard,
Wildcard(TokenWithLocation),
/// Qualified wildcard, e.g. `alias.*` or `schema.table.*`.
/// (Same caveats apply to `QualifiedWildcard` as to `Wildcard`.)
QualifiedWildcard(ObjectName),
QualifiedWildcard(ObjectName, TokenWithLocation),
/// Some dialects support an older syntax for outer joins where columns are
/// marked with the `(+)` operator in the WHERE clause, for example:
///
Expand Down Expand Up @@ -1173,8 +1214,8 @@ impl fmt::Display for Expr {
Expr::MapAccess { column, keys } => {
write!(f, "{column}{}", display_separated(keys, ""))
}
Expr::Wildcard => f.write_str("*"),
Expr::QualifiedWildcard(prefix) => write!(f, "{}.*", prefix),
Expr::Wildcard(_) => f.write_str("*"),
Expr::QualifiedWildcard(prefix, _) => write!(f, "{}.*", prefix),
Expr::CompoundIdentifier(s) => write!(f, "{}", display_separated(s, ".")),
Expr::IsTrue(ast) => write!(f, "{ast} IS TRUE"),
Expr::IsNotTrue(ast) => write!(f, "{ast} IS NOT TRUE"),
Expand Down Expand Up @@ -5169,8 +5210,8 @@ pub enum FunctionArgExpr {
impl From<Expr> for FunctionArgExpr {
fn from(wildcard_expr: Expr) -> Self {
match wildcard_expr {
Expr::QualifiedWildcard(prefix) => Self::QualifiedWildcard(prefix),
Expr::Wildcard => Self::Wildcard,
Expr::QualifiedWildcard(prefix, _) => Self::QualifiedWildcard(prefix),
Expr::Wildcard(_) => Self::Wildcard,
expr => Self::Expr(expr),
}
}
Expand Down
26 changes: 24 additions & 2 deletions src/ast/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};

use crate::ast::*;
use crate::{
ast::*,
tokenizer::{Token, TokenWithLocation},
};

/// The most complete variant of a `SELECT` query expression, optionally
/// including `WITH`, `UNION` / other set operations, and `ORDER BY`.
Expand Down Expand Up @@ -271,6 +274,8 @@ impl fmt::Display for Table {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct Select {
/// SELECT
pub select_token: TokenWithLocation,
pub distinct: Option<Distinct>,
/// MSSQL syntax: `TOP (<N>) [ PERCENT ] [ WITH TIES ]`
pub top: Option<Top>,
Expand Down Expand Up @@ -490,6 +495,7 @@ impl fmt::Display for NamedWindowDefinition {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct With {
pub with_token: TokenWithLocation,
pub recursive: bool,
pub cte_tables: Vec<Cte>,
}
Expand Down Expand Up @@ -541,6 +547,8 @@ pub struct Cte {
pub query: Box<Query>,
pub from: Option<Ident>,
pub materialized: Option<CteAsMaterialized>,
// needed for accurate span reporting
pub closing_paren_token: TokenWithLocation,
}

impl fmt::Display for Cte {
Expand Down Expand Up @@ -592,10 +600,11 @@ impl fmt::Display for IdentWithAlias {
}

/// Additional options for wildcards, e.g. Snowflake `EXCLUDE`/`RENAME` and Bigquery `EXCEPT`.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct WildcardAdditionalOptions {
pub wildcard_token: TokenWithLocation,
/// `[ILIKE...]`.
/// Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
pub opt_ilike: Option<IlikeSelectItem>,
Expand All @@ -613,6 +622,19 @@ pub struct WildcardAdditionalOptions {
pub opt_rename: Option<RenameSelectItem>,
}

impl Default for WildcardAdditionalOptions {
fn default() -> Self {
Self {
wildcard_token: TokenWithLocation::wrap(Token::Mul),
opt_ilike: None,
opt_exclude: None,
opt_except: None,
opt_replace: None,
opt_rename: None,
}
}
}

impl fmt::Display for WildcardAdditionalOptions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ilike) = &self.opt_ilike {
Expand Down
Loading