Expr: apply recursive-protection to Clone and PartialEq
diff --git a/Cargo.toml b/Cargo.toml index 97b4612..c8fe47a 100644 --- a/Cargo.toml +++ b/Cargo.toml
@@ -55,7 +55,7 @@ [features] default = ["std", "recursive-protection"] std = [] -recursive-protection = ["std", "recursive"] +recursive-protection = ["std", "recursive", "sqlparser_derive"] # Enable JSON output in the `cli` example: json_example = ["serde_json", "serde"] derive-dialect = ["sqlparser_derive"]
diff --git a/derive/src/guarded.rs b/derive/src/guarded.rs new file mode 100644 index 0000000..428cd34 --- /dev/null +++ b/derive/src/guarded.rs
@@ -0,0 +1,168 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Implementation of the `GuardedClone` and `GuardedPartialEq` derive macros. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::ext::IdentExt; +use syn::{parse_quote, Data, DeriveInput, Fields, GenericParam, Generics, Ident}; + +pub(crate) fn derive_guarded_clone(input: DeriveInput) -> TokenStream { + let name = &input.ident; + let generics = add_trait_bounds(input.generics.clone(), quote!(::core::clone::Clone)); + let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); + + let body = match &input.data { + Data::Struct(data) => { + let (pattern, bindings) = bind_fields(&data.fields, "self"); + let copy = rebuild(&data.fields, &bindings); + quote! { + let Self #pattern = self; + Self #copy + } + } + Data::Enum(data) if data.variants.is_empty() => quote!(match *self {}), + Data::Enum(data) => { + let arms = data.variants.iter().map(|variant| { + let variant_name = &variant.ident; + let (pattern, bindings) = bind_fields(&variant.fields, "self"); + let copy = rebuild(&variant.fields, &bindings); + quote!(Self::#variant_name #pattern => Self::#variant_name #copy) + }); + quote! { + match self { + #(#arms,)* + } + } + } + Data::Union(data) => { + return syn::Error::new(data.union_token.span, "unions are not supported") + .to_compile_error() + } + }; + + quote! { + #[automatically_derived] + impl #impl_generics ::core::clone::Clone for #name #ty_generics #where_clause { + #[cfg_attr(feature = "recursive-protection", recursive::recursive)] + fn clone(&self) -> Self { + #body + } + } + } +} + +pub(crate) fn derive_guarded_partial_eq(input: DeriveInput) -> TokenStream { + let name = &input.ident; + let generics = add_trait_bounds(input.generics.clone(), quote!(::core::cmp::PartialEq)); + let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); + + let body = match &input.data { + Data::Struct(data) => { + let (self_pattern, self_bindings) = bind_fields(&data.fields, "self"); + let (other_pattern, other_bindings) = bind_fields(&data.fields, "other"); + let equal = all_equal(&self_bindings, &other_bindings); + quote! { + let Self #self_pattern = self; + let Self #other_pattern = other; + #equal + } + } + Data::Enum(data) if data.variants.is_empty() => quote!(match *self {}), + Data::Enum(data) => { + let arms = data.variants.iter().map(|variant| { + let variant_name = &variant.ident; + let (self_pattern, self_bindings) = bind_fields(&variant.fields, "self"); + let (other_pattern, other_bindings) = bind_fields(&variant.fields, "other"); + let equal = all_equal(&self_bindings, &other_bindings); + quote!((Self::#variant_name #self_pattern, Self::#variant_name #other_pattern) => #equal) + }); + let mismatch = (data.variants.len() > 1).then(|| quote!(_ => false,)); + quote! { + match (self, other) { + #(#arms,)* + #mismatch + } + } + } + Data::Union(data) => { + return syn::Error::new(data.union_token.span, "unions are not supported") + .to_compile_error() + } + }; + + quote! { + #[automatically_derived] + impl #impl_generics ::core::cmp::PartialEq for #name #ty_generics #where_clause { + #[cfg_attr(feature = "recursive-protection", recursive::recursive)] + fn eq(&self, other: &Self) -> bool { + #body + } + } + } +} + +fn add_trait_bounds(mut generics: Generics, bound: TokenStream) -> Generics { + for param in &mut generics.params { + if let GenericParam::Type(type_param) = param { + type_param.bounds.push(parse_quote!(#bound)); + } + } + generics +} + +/// Returns a pattern binding every field to `{prefix}_{field}`, with the bindings in field order. +fn bind_fields(fields: &Fields, prefix: &str) -> (TokenStream, Vec<Ident>) { + match fields { + Fields::Named(named) => { + let names: Vec<&Ident> = named.named.iter().flat_map(|field| &field.ident).collect(); + let bindings: Vec<Ident> = names + .iter() + .map(|name| format_ident!("{}_{}", prefix, name.unraw())) + .collect(); + (quote!({ #(#names: #bindings),* }), bindings) + } + Fields::Unnamed(unnamed) => { + let bindings: Vec<Ident> = (0..unnamed.unnamed.len()) + .map(|index| format_ident!("{}_{}", prefix, index)) + .collect(); + (quote!(( #(#bindings),* )), bindings) + } + Fields::Unit => (TokenStream::new(), Vec::new()), + } +} + +/// Builds the fields of a value of the same shape from clones of `bindings`. +fn rebuild(fields: &Fields, bindings: &[Ident]) -> TokenStream { + match fields { + Fields::Named(named) => { + let names = named.named.iter().flat_map(|field| &field.ident); + quote!({ #(#names: ::core::clone::Clone::clone(#bindings)),* }) + } + Fields::Unnamed(_) => quote!(( #(::core::clone::Clone::clone(#bindings)),* )), + Fields::Unit => TokenStream::new(), + } +} + +fn all_equal(left: &[Ident], right: &[Ident]) -> TokenStream { + if left.is_empty() { + quote!(true) + } else { + quote!(#(#left == #right)&&*) + } +}
diff --git a/derive/src/lib.rs b/derive/src/lib.rs index e3eaeea..072321c 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs
@@ -20,13 +20,30 @@ //! This crate provides: //! - [`Visit`] and [`VisitMut`] derive macros for AST traversal. //! - [`derive_dialect!`] macro for creating custom SQL dialects. +//! - [`GuardedClone`] and [`GuardedPartialEq`] derive macros whose methods are guarded by +//! `recursive-protection`. use quote::quote; use syn::parse_macro_input; mod dialect; +mod guarded; mod visit; +/// Derives `Clone` with each `clone` call guarded by `recursive-protection`. +#[proc_macro_derive(GuardedClone)] +pub fn derive_guarded_clone(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = parse_macro_input!(input as syn::DeriveInput); + guarded::derive_guarded_clone(input).into() +} + +/// Derives `PartialEq` with each `eq` call guarded by `recursive-protection`. +#[proc_macro_derive(GuardedPartialEq)] +pub fn derive_guarded_partial_eq(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = parse_macro_input!(input as syn::DeriveInput); + guarded::derive_guarded_partial_eq(input).into() +} + /// Implementation of `#[derive(VisitMut)]` #[proc_macro_derive(VisitMut, attributes(visit))] pub fn derive_visit_mut(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 97cb38e..efab3a8 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs
@@ -41,6 +41,8 @@ #[cfg(feature = "visitor")] use core::ops::ControlFlow; +#[cfg(feature = "recursive-protection")] +use sqlparser_derive::{GuardedClone, GuardedPartialEq}; #[cfg(feature = "visitor")] use sqlparser_derive::{Visit, VisitMut}; @@ -946,7 +948,13 @@ /// of the expression (not bitwise comparison). This means that `Expr` instances /// that are semantically equivalent but have different spans (locations in the /// source tree) will compare as equal. -#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] +#[derive(Debug, PartialOrd, Eq, Ord, Hash)] +// A parsed operator chain nests one `Expr` per operator. +#[cfg_attr( + feature = "recursive-protection", + derive(GuardedClone, GuardedPartialEq) +)] +#[cfg_attr(not(feature = "recursive-protection"), derive(Clone, PartialEq))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr( feature = "visitor",
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index 912baad..3721e2a 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs
@@ -23665,3 +23665,21 @@ ParserError::ParserError("Expected: identifier, found: )".to_string()) ); } + +#[test] +fn clone_and_eq_of_a_deep_operator_chain_complete() { + let sql = format!("SELECT 1{}", " + 1".repeat(20_000)); + std::thread::Builder::new() + .stack_size(2 * 1024 * 1024) + .spawn(move || { + let statements = Parser::parse_sql(&GenericDialect {}, &sql).unwrap(); + let copy = statements.clone(); + assert_eq!(copy, statements); + // Recursive drop glue would overflow too. + core::mem::forget(copy); + core::mem::forget(statements); + }) + .unwrap() + .join() + .unwrap(); +}