dsl_auto_type-0.1.3/.cargo_vcs_info.json0000644000000001530000000000100137070ustar { "git": { "sha1": "55d90e04e570f9fb88b69eb0f6ceed58ea92b652" }, "path_in_vcs": "dsl_auto_type" }dsl_auto_type-0.1.3/Cargo.toml0000644000000025160000000000100117120ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.78.0" name = "dsl_auto_type" version = "0.1.3" build = false include = [ "src/**/*.rs", "tests/**/*.rs", "LICENSE-*", "README.md", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Automatically expand query fragment types for factoring as functions" homepage = "https://diesel.rs" documentation = "https://docs.rs/crate/diesel_migrations" readme = false license = "MIT OR Apache-2.0" [lib] name = "dsl_auto_type" path = "src/lib.rs" [dependencies.darling] version = "0.20" [dependencies.either] version = "1" [dependencies.heck] version = "0.5" [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.syn] version = "2" features = [ "extra-traits", "full", "derive", "parsing", "visit", ] [dev-dependencies] dsl_auto_type-0.1.3/Cargo.toml.orig000064400000000000000000000010571046102023000153720ustar 00000000000000[package] name = "dsl_auto_type" version = "0.1.3" license = "MIT OR Apache-2.0" description = "Automatically expand query fragment types for factoring as functions" documentation = "https://docs.rs/crate/diesel_migrations" homepage = "https://diesel.rs" edition = "2021" rust-version.workspace = true include.workspace = true [dependencies] darling = "0.20" either = "1" heck = "0.5" proc-macro2 = "1" quote = "1" syn = { version = "2", features = ["extra-traits", "full", "derive", "parsing", "visit"] } [dev-dependencies] diesel = { path = "../diesel" } dsl_auto_type-0.1.3/LICENSE-APACHE000064400000000000000000000250461046102023000144330ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2015-2021 Sean Griffin, 2018-2021 Diesel Core Team Licensed 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. dsl_auto_type-0.1.3/LICENSE-MIT000064400000000000000000000021121046102023000141300ustar 00000000000000The MIT License (MIT) 2015-2021 Sean Griffin, 2018-2021 Diesel Core Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. dsl_auto_type-0.1.3/src/auto_type/case.rs000064400000000000000000000030251046102023000165610ustar 00000000000000use {heck::*, proc_macro2::Span, syn::Ident}; #[derive(Clone, Copy, PartialEq, Eq)] pub enum Case { DoNotChange, UpperCamel, Pascal, LowerCamel, Snake, ShoutySnake, } impl Case { pub(crate) fn ident_with_case(self, ident: &Ident) -> syn::Ident { let s = ident.to_string(); let cased_s: String = match self { Case::DoNotChange => s, Case::UpperCamel => s.to_upper_camel_case(), Case::Pascal => s.to_pascal_case(), Case::LowerCamel => s.to_lower_camel_case(), Case::Snake => s.to_snake_case(), Case::ShoutySnake => s.to_shouty_snake_case(), }; Ident::new(&cased_s, ident.span()) } } impl Case { pub(crate) fn from_str(s: &str, span: Span) -> Result { Ok(match s { "dO_nOt_cHaNgE_cAsE" => Case::DoNotChange, "UpperCamelCase" => Case::UpperCamel, "PascalCase" => Case::Pascal, "lowerCamelCase" => Case::LowerCamel, "snake_case" => Case::Snake, "SHOUTY_SNAKE_CASE" => Case::ShoutySnake, other => { return Err(syn::Error::new( span, format_args!( "Unknown case: {other}, expected one of: \ `PascalCase`, `snake_case`, `UpperCamelCase`, `lowerCamelCase`, \ `SHOUTY_SNAKE_CASE`, `dO_nOt_cHaNgE_cAsE`" ), )) } }) } } dsl_auto_type-0.1.3/src/auto_type/expression_type_inference.rs000064400000000000000000000454751046102023000231430ustar 00000000000000use super::*; pub use super::settings_builder::InferrerSettingsBuilder; /// This is meant to be used if there's need to infer a single expression type /// out of the context of a function. It will be assumed that there are no /// intermediate variables (`let` statements). initially, but one can still use /// intermediate block expression to annotate types. /// /// This is useful in the context of Diesel's `Selectable` macro. pub fn infer_expression_type( expr: &syn::Expr, type_hint: Option<&syn::Type>, inferrer_settings: &InferrerSettings, ) -> (syn::Type, Vec) { let local_variables_map = LocalVariablesMap { inferrer_settings, inner: LocalVariablesMapInner { map: Default::default(), parent: None, }, }; let inferrer = local_variables_map.inferrer(); let type_ = inferrer.infer_expression_type(expr, type_hint); let errors = inferrer .into_errors() .into_iter() .filter_map(|rc| { // Extracting from the `Rc` only if it's the last reference is an elegant way to // deduplicate errors For this to work it is necessary that the rest of // the errors (those from the local variables map that weren't used) are // dropped before, which is the case here, and that we are iterating on the // errors in an owned manner. Rc::try_unwrap(rc).ok() }) .collect(); (type_, errors) } pub struct InferrerSettings { pub(crate) dsl_path: syn::Path, pub(crate) method_types_case: Case, pub(crate) function_types_case: Case, } impl<'a> LocalVariablesMap<'a, '_> { pub(crate) fn inferrer(&'a self) -> TypeInferrer<'a> { TypeInferrer { local_variables_map: self, errors: Default::default(), } } } pub(crate) struct TypeInferrer<'s> { local_variables_map: &'s LocalVariablesMap<'s, 's>, errors: std::cell::RefCell>>, } impl TypeInferrer<'_> { /// Calls `try_infer_expression_type` and falls back to `_` if it fails, /// collecting the error for display pub(crate) fn infer_expression_type( &self, expr: &syn::Expr, type_hint: Option<&syn::Type>, ) -> syn::Type { let inferred = self.try_infer_expression_type(expr, type_hint); match inferred { Ok(t) => t, Err(e) => self.register_error(e, expr.span()), } } fn register_error(&self, error: syn::Error, infer_type_span: Span) -> syn::Type { self.errors.borrow_mut().push(Rc::new(error)); parse_quote_spanned!(infer_type_span=> _) } fn try_infer_expression_type( &self, expr: &syn::Expr, type_hint: Option<&syn::Type>, ) -> Result { let expression_type: syn::Type = match ( expr, type_hint.filter(|h| !matches!(h, syn::Type::Infer(_))), ) { (syn::Expr::Group(syn::ExprGroup { expr, .. }), type_hint) => { return self.try_infer_expression_type(expr, type_hint) } (syn::Expr::Paren(syn::ExprParen { expr, .. }), type_hint) => { return self.try_infer_expression_type(expr, type_hint) } ( syn::Expr::Tuple(syn::ExprTuple { elems: expr_elems, .. }), Some(syn::Type::Tuple( type_tuple @ syn::TypeTuple { elems: type_elems, .. }, )), ) => { if type_elems.len() != expr_elems.len() { return Err(syn::Error::new( type_tuple.span(), "auto_type: tuple type and its \ expression have different number of elements", )); } syn::Type::Tuple(syn::TypeTuple { elems: type_elems .iter() .zip(expr_elems.iter()) .map(|(type_, expr)| self.infer_expression_type(expr, Some(type_))) .collect(), ..type_tuple.clone() }) } (syn::Expr::Tuple(syn::ExprTuple { elems, .. }), None) => { syn::Type::Tuple(syn::TypeTuple { elems: elems .iter() .map(|e| self.infer_expression_type(e, None)) .collect(), paren_token: Default::default(), }) } (syn::Expr::Path(syn::ExprPath { path, .. }), None) => { // This is either a local variable or we should assume that the type exists at // the same path as the function (with applied casing for last segment) let path_is_ident = path.get_ident(); if path_is_ident.is_some_and(|ident| ident == "self") { parse_quote!(Self) } else if let Some(LetStatementInferredType { type_, errors }) = path_is_ident .and_then(|path_single_ident| { self.local_variables_map.inner.get(path_single_ident) }) { // Since we are using this type for the computation of the current type, any // errors encountered there are relevant here self.errors.borrow_mut().extend(errors.iter().cloned()); type_.clone() } else { syn::Type::Path(syn::TypePath { path: path.clone(), qself: None, }) } } (syn::Expr::Call(syn::ExprCall { func, args, .. }), None) => { let unsupported_function_type = || { syn::Error::new_spanned( &**func, "unsupported function type for auto_type, please provide a type hint", ) }; let func_type = self.try_infer_expression_type(func, None)?; // First we extract the type of the function let mut type_path = match func_type { syn::Type::Path(syn::TypePath { path, .. }) => path, _ => return Err(unsupported_function_type()), }; // Then we update the case if specified if self .local_variables_map .inferrer_settings .function_types_case != Case::DoNotChange { if let Some(last) = type_path.segments.last_mut() { last.ident = self .local_variables_map .inferrer_settings .function_types_case .ident_with_case(&last.ident); } } // Then we will add the generic arguments let last_segment = type_path .segments .last_mut() .ok_or_else(unsupported_function_type)?; last_segment.arguments = self.infer_generics_or_use_hints( None, args, match &last_segment.arguments { syn::PathArguments::None => None, syn::PathArguments::AngleBracketed(ab) => Some(ab), syn::PathArguments::Parenthesized(_) => { return Err(unsupported_function_type()) } }, )?; syn::Type::Path(syn::TypePath { path: type_path, qself: None, }) } ( syn::Expr::MethodCall(syn::ExprMethodCall { receiver, method, turbofish, args, .. }), None, ) => syn::Type::Path(syn::TypePath { path: syn::Path { segments: self .local_variables_map .inferrer_settings .dsl_path .segments .iter() .cloned() .chain([syn::PathSegment { ident: self .local_variables_map .inferrer_settings .method_types_case .ident_with_case(method), arguments: self.infer_generics_or_use_hints( Some(syn::GenericArgument::Type( self.infer_expression_type(receiver, None), )), args, turbofish.as_ref(), )?, }]) .collect(), leading_colon: None, }, qself: None, }), (syn::Expr::Lit(syn::ExprLit { lit, .. }), None) => match lit { syn::Lit::Str(_) => parse_quote_spanned!(lit.span()=> &'static str), syn::Lit::ByteStr(_) => parse_quote_spanned!(lit.span()=> &'static [u8]), syn::Lit::Byte(_) => parse_quote_spanned!(lit.span()=> u8), syn::Lit::Char(_) => parse_quote_spanned!(lit.span()=> char), syn::Lit::Int(lit_int) => literal_type(&lit_int.token())?, syn::Lit::Float(lit_float) => literal_type(&lit_float.token())?, syn::Lit::Bool(_) => parse_quote_spanned!(lit.span()=> bool), _ => { return Err(syn::Error::new( lit.span(), "unsupported literal for auto_type, please provide a type hint", )) } }, (syn::Expr::Block(syn::ExprBlock { block, .. }), type_hint) => { match block.stmts.last() { None | Some( syn::Stmt::Local(_) | syn::Stmt::Item(_) | syn::Stmt::Expr(_, Some(_)), ) => { // Empty blocks, local variables (`let`) and other item definition as last // statement, as well as expressions BUT with a semicolon, lead to the // block having unit type. match type_hint { Some(type_hint) => { // Prefer user-specified type hint to our own inference type_hint.clone() } None => parse_quote_spanned!(block.span()=> ()), } } Some(syn::Stmt::Expr(expr, None)) => { let local_variables_map = LocalVariablesMap { inferrer_settings: self.local_variables_map.inferrer_settings, inner: LocalVariablesMapInner { map: Default::default(), parent: Some(&self.local_variables_map.inner), }, }; local_variables_map.infer_block_expression_type( expr, type_hint, block, &mut self.errors.borrow_mut(), ) } Some(syn::Stmt::Macro(syn::StmtMacro { mac, .. })) => { match type_hint { Some(type_hint) => { // User provided a type hint to the macro expression, we won't be // able to do any better than this type_hint.clone() } None => { return Err(syn::Error::new_spanned( mac, "auto_type: unsupported macro call as last statement in block, \ please provide a type hint", )); } } } } } (syn::Expr::Binary(binary_expression), None) => { let op_span = Span::mixed_site().located_at(binary_expression.op.span()); let trait_name = match binary_expression.op { syn::BinOp::Add(_) => "Add", syn::BinOp::Sub(_) => "Sub", syn::BinOp::Mul(_) => "Mul", syn::BinOp::Div(_) => "Div", syn::BinOp::Rem(_) => "Rem", syn::BinOp::BitXor(_) => "BitXor", syn::BinOp::BitAnd(_) => "BitAnd", syn::BinOp::BitOr(_) => "BitOr", syn::BinOp::Shl(_) => "Shl", syn::BinOp::Shr(_) => "Shr", syn::BinOp::And(_) | syn::BinOp::Or(_) | syn::BinOp::Eq(_) | syn::BinOp::Lt(_) | syn::BinOp::Le(_) | syn::BinOp::Ne(_) | syn::BinOp::Ge(_) | syn::BinOp::Gt(_) => return Ok(parse_quote!(bool)), syn::BinOp::AddAssign(_) | syn::BinOp::SubAssign(_) | syn::BinOp::MulAssign(_) | syn::BinOp::DivAssign(_) | syn::BinOp::RemAssign(_) | syn::BinOp::BitXorAssign(_) | syn::BinOp::BitAndAssign(_) | syn::BinOp::BitOrAssign(_) | syn::BinOp::ShlAssign(_) | syn::BinOp::ShrAssign(_) => return Ok(parse_quote!(())), _ => { // This is here because the `BinOp` enum is marked as #[non_exhaustive], // but in effect we really support all the variants return Err(syn::Error::new( op_span, format_args!( "unsupported binary operator for auto_type: {:?}", binary_expression.op ), )); } }; let trait_name_ident = syn::Ident::new(trait_name, op_span); let left_type = self.infer_expression_type(&binary_expression.left, None); let right_type = self.infer_expression_type(&binary_expression.right, None); parse_quote!(<#left_type as ::core::ops::#trait_name_ident<#right_type>>::Output) } (_, None) => { return Err(syn::Error::new( expr.span(), "unsupported expression for auto_type, please provide a type hint", )) } (_, Some(type_hint)) => type_hint.clone(), }; Ok(expression_type) } /// `infer` is always supposed to be a syn::Type::Infer fn infer_generics_or_use_hints( &self, add_first: Option, args: &syn::punctuated::Punctuated, hint: Option<&syn::AngleBracketedGenericArguments>, ) -> Result { let arguments = syn::AngleBracketedGenericArguments { args: add_first .into_iter() .chain(match hint { None => { // We should infer Either::Left(args.iter().map(|e| { syn::GenericArgument::Type(self.infer_expression_type(e, None)) })) } Some(hint_or_override) => Either::Right( hint_or_override .args .iter() .zip(args.iter().map(Some).chain((0..).map(|_| None))) .map(|(hint, expr)| match (hint, expr) { (syn::GenericArgument::Type(type_hint), Some(expr)) => { syn::GenericArgument::Type( self.infer_expression_type(expr, Some(type_hint)), ) } ( generic_argument @ syn::GenericArgument::Type(syn::Type::Infer( _, )), None, ) => syn::GenericArgument::Type(self.register_error( syn::Error::new_spanned( generic_argument, "auto_type: Can't infer generic argument because \ there is no function argument to infer from \ (less function arguments than generic arguments)", ), generic_argument.span(), )), (generic_argument, _) => generic_argument.clone(), }), ), }) .collect(), colon2_token: None, // there is no colon2 in types, only in function calls lt_token: Default::default(), gt_token: Default::default(), }; Ok(if arguments.args.is_empty() { syn::PathArguments::None } else { syn::PathArguments::AngleBracketed(arguments) }) } pub(crate) fn into_errors(self) -> Vec> { self.errors.into_inner() } } fn literal_type(t: &proc_macro2::Literal) -> Result { let val = t.to_string(); let type_suffix = &val[val .find(|c: char| !c.is_ascii_digit() && c != '_') .ok_or_else(|| { syn::Error::new_spanned( t, format_args!("Literals must have type suffix for auto_type, e.g. {val}i64"), ) })?..]; syn::parse_str(type_suffix) .map_err(|_| syn::Error::new_spanned(t, "Invalid type suffix for literal")) } dsl_auto_type-0.1.3/src/auto_type/local_variables_map.rs000064400000000000000000000172561046102023000216400ustar 00000000000000use super::*; /// The map itself, + some settings to run the inferrer with pub(crate) struct LocalVariablesMap<'a, 'p> { pub(crate) inferrer_settings: &'a InferrerSettings, /// The map, with an optional parent (to support nested blocks) pub(crate) inner: LocalVariablesMapInner<'a, 'p>, } /// The map, with an optional parent (to support nested blocks) pub(crate) struct LocalVariablesMapInner<'a, 'p> { pub(crate) map: HashMap<&'a Ident, LetStatementInferredType>, pub(crate) parent: Option<&'p LocalVariablesMapInner<'a, 'p>>, } pub(crate) struct LetStatementInferredType { pub(crate) type_: Type, pub(crate) errors: Vec>, } impl LocalVariablesMapInner<'_, '_> { /// Lookup in this map, and if not found, in the parent map /// This is to support nested blocks pub(crate) fn get(&self, ident: &Ident) -> Option<&LetStatementInferredType> { match self.map.get(ident) { Some(inferred_type) => Some(inferred_type), None => match self.parent { Some(parent) => parent.get(ident), None => None, }, } } } impl<'a> LocalVariablesMap<'a, '_> { pub(crate) fn process_pat( &mut self, pat: &'a syn::Pat, type_ascription: Option<&'a Type>, local_init_expression: Option<&'a syn::Expr>, ) -> Result<(), syn::Error> { // Either the let statement hints the type or we have to infer it // Either the let statement is a simple assignment or a destructuring assignment match pat { syn::Pat::Type(pat_type) => { self.process_pat( &pat_type.pat, Some(match type_ascription { None => &pat_type.ty, Some(type_ascription) => { return Err(syn::Error::new( type_ascription.span(), "auto_type: unexpected double type ascription", )) } }), local_init_expression, )?; } syn::Pat::Ident(pat_ident) => { self.inner.map.insert( &pat_ident.ident, match (type_ascription, local_init_expression) { (opt_type_ascription, Some(expr)) => { let inferrer = self.inferrer(); LetStatementInferredType { type_: inferrer.infer_expression_type(expr, opt_type_ascription), errors: inferrer.into_errors(), } } (Some(type_ascription), None) => LetStatementInferredType { type_: type_ascription.clone(), errors: Vec::new(), }, (None, None) => LetStatementInferredType { type_: parse_quote_spanned!(pat_ident.span()=> _), errors: vec![Rc::new(syn::Error::new_spanned( pat_ident, "auto_type: Let statement with no type ascription \ and no initializer expression is not supported", ))], }, }, ); } syn::Pat::Tuple(pat_tuple) => { if let Some(type_ascription) = type_ascription { if let Type::Tuple(type_tuple) = type_ascription { if pat_tuple.elems.len() != type_tuple.elems.len() { return Err(syn::Error::new( type_ascription.span(), "auto_type: tuple let assignment and its \ type ascription have different number of elements", )); } } } for (i, pat) in pat_tuple.elems.iter().enumerate() { self.process_pat( pat, match type_ascription { Some(Type::Tuple(type_tuple)) => Some(&type_tuple.elems[i]), _ => None, }, match local_init_expression { Some(syn::Expr::Tuple(expr_tuple)) => Some(&expr_tuple.elems[i]), _ => None, }, )?; } } _ => { // We won't be able to infer these, at the same time we don't // want to error because there may be valid user // code using these, and we won't need it if these variables // are not needed to infer the type of the final expression. } }; Ok(()) } pub(crate) fn process_const_generic(&mut self, const_generic: &'a syn::ConstParam) { self.inner.map.insert( &const_generic.ident, LetStatementInferredType { type_: const_generic.ty.clone(), errors: Vec::new(), }, ); } /// Finishes a block inference for this map. /// It may be initialized with `pat`s before (such as function parameters), /// then this function is used to infer the type of the last expression in the block. /// /// It takes the last expression of the block as a `block_last_expr` /// parameter, because depending on where this is called, /// `return`/`let`,`function_call();` will or not be tolerated, so this is /// matched before calling this function. /// /// Expects that the block has at least one statement (it is assumed that /// the last statement is provided as `block_last_expr`) pub(crate) fn infer_block_expression_type( mut self, block_last_expr: &'a syn::Expr, block_type_hint: Option<&'a syn::Type>, block: &'a syn::Block, errors: &mut Vec>, ) -> syn::Type { for statement in &block.stmts[0..block .stmts .len() .checked_sub(1) .expect("Block should have at least one statement, provided as `block_last_expr`")] { if let syn::Stmt::Local(local) = statement { match self.process_pat( &local.pat, None, local.init.as_ref().map(|local_init| &*local_init.expr), ) { Ok(()) => {} Err(e) => { errors.push(Rc::new(e)); } } }; } if errors.is_empty() { // We haven't encountered any error so the local variables map is // properly initialized. // If there are no such "syntax errors", we may attempt parsing. let inferrer = self.inferrer(); let block_output_type = inferrer.infer_expression_type(block_last_expr, block_type_hint); errors.extend(inferrer.into_errors()); block_output_type } else { // We don't attempt inference if there are already errors because `process_pat` // is already pretty tolerant, and we don't want to only show these errors // once another error starts happening, as they may be confusing to // the user. let block_span = block.span(); parse_quote_spanned!(block_span=> _) } } } dsl_auto_type-0.1.3/src/auto_type/mod.rs000064400000000000000000000164161046102023000164350ustar 00000000000000mod case; pub mod expression_type_inference; mod local_variables_map; mod referenced_generics; mod settings_builder; use { darling::{util::SpannedValue, FromMeta}, either::Either, proc_macro2::{Span, TokenStream}, quote::quote, std::{collections::HashMap, rc::Rc}, syn::{parse_quote, parse_quote_spanned, spanned::Spanned, Ident, ItemFn, Token, Type}, }; use local_variables_map::*; pub use { case::Case, expression_type_inference::InferrerSettings, settings_builder::DeriveSettingsBuilder, }; pub struct DeriveSettings { default_dsl_path: syn::Path, default_method_type_case: Case, default_function_type_case: Case, default_generate_type_alias: bool, } #[derive(darling::FromMeta)] struct DeriveParameters { /// Can be overridden to provide custom DSLs dsl_path: Option, type_alias: darling::util::Flag, no_type_alias: darling::util::Flag, type_name: Option, type_case: Option>, } pub(crate) fn auto_type_impl( attr: TokenStream, input: &TokenStream, derive_settings: DeriveSettings, ) -> Result { let settings_input: DeriveParameters = DeriveParameters::from_list(&darling::ast::NestedMeta::parse_meta_list(attr)?)?; let mut input_function = syn::parse2::(input.clone())?; let inferrer_settings = InferrerSettings { dsl_path: settings_input .dsl_path .unwrap_or(derive_settings.default_dsl_path), method_types_case: derive_settings.default_method_type_case, function_types_case: derive_settings.default_function_type_case, }; let function_name = &input_function.sig.ident; let type_alias = match ( settings_input.type_alias.is_present(), settings_input.no_type_alias.is_present(), derive_settings.default_generate_type_alias, ) { (false, false, b) => b, (true, false, _) => true, (false, true, _) => false, (true, true, _) => { return Err(syn::Error::new( Span::call_site(), "type_alias and no_type_alias are mutually exclusive", ) .into()) } }; let type_alias: Option = match ( type_alias, settings_input.type_name, settings_input.type_case, ) { (false, None, None) => None, (true, None, None) => { // By default be consistent with call expressions, for when other will refer // this query fragment in another auto_type function Some( inferrer_settings .function_types_case .ident_with_case(function_name), ) } (_, Some(ident), None) => Some(ident), (_, None, Some(case)) => { let case = Case::from_str(case.as_str(), case.span())?; Some(case.ident_with_case(function_name)) } (_, Some(_), Some(type_case)) => { return Err(syn::Error::new( type_case.span(), "type_name and type_case are mutually exclusive", ) .into()) } }; let last_statement = input_function.block.stmts.last().ok_or_else(|| { syn::Error::new( input_function.span(), "function body should not be empty for auto_type", ) })?; let mut errors = Vec::new(); let return_type = match input_function.sig.output { syn::ReturnType::Type(_, return_type) => { let return_expression = match last_statement { syn::Stmt::Expr(expr, None) => expr, syn::Stmt::Expr( syn::Expr::Return(syn::ExprReturn { expr: Some(expr), .. }), _, ) => &**expr, _ => { return Err(syn::Error::new( last_statement.span(), "last statement should be an expression for auto_type", ) .into()) } }; // Build a map of local variables, and get the function parameters in there let mut local_variables_map = LocalVariablesMap { inferrer_settings: &inferrer_settings, inner: LocalVariablesMapInner { map: Default::default(), parent: None, }, }; for const_generic in input_function.sig.generics.const_params() { local_variables_map.process_const_generic(const_generic); } for function_param in &input_function.sig.inputs { if let syn::FnArg::Typed(syn::PatType { pat, ty, .. }) = function_param { match local_variables_map.process_pat(pat, Some(ty), None) { Ok(()) => {} Err(e) => errors.push(Rc::new(e)), } }; } // Add local variables from the function body, and finally infer the type local_variables_map.infer_block_expression_type( return_expression, Some(&return_type), &input_function.block, &mut errors, ) } _ => { // This error message is not strictly correct: we also support // partially-specified return types that involve `_`, but for simplicity we just // put the overwhelmingly most common case in this error message return Err(syn::Error::new( input_function.sig.output.span(), "Function return type should be explicitly specified as `-> _` for auto_type", ) .into()); } }; let type_alias = match type_alias { Some(type_alias) => { // We're generating a type alias so we need to extract the necessary lifetimes and // generic type parameters for that type alias let type_alias_generics = referenced_generics::extract_referenced_generics( &return_type, &input_function.sig.generics, &mut errors, ); let vis = &input_function.vis; input_function.sig.output = parse_quote!(-> #type_alias #type_alias_generics); quote! { #[allow(non_camel_case_types)] #vis type #type_alias #type_alias_generics = #return_type; } } None => { input_function.sig.output = parse_quote!(-> #return_type); quote! {} } }; let mut res = quote! { #type_alias #[allow(clippy::needless_lifetimes)] #input_function }; for error in errors { // Extracting from the `Rc` only if it's the last reference is an elegant way to // deduplicate errors. For this to work it is necessary that the rest of // the errors (those from the local variables map that weren't used) are // dropped before, which is the case here, and that we are iterating on the // errors in an owned manner. if let Ok(error) = Rc::try_unwrap(error) { res.extend(error.into_compile_error()); } } Ok(res) } dsl_auto_type-0.1.3/src/auto_type/referenced_generics.rs000064400000000000000000000071261046102023000216350ustar 00000000000000use std::rc::Rc; use syn::parse_quote; use syn::visit::{self, Visit}; use syn::{Ident, Lifetime}; pub(crate) fn extract_referenced_generics( ty: &syn::Type, generics: &syn::Generics, errors: &mut Vec>, ) -> syn::Generics { struct Visitor<'g, 'errs> { lifetimes: Vec<(&'g Lifetime, bool)>, type_parameters: Vec<(&'g Ident, bool)>, errors: &'errs mut Vec>, } let mut visitor = Visitor { lifetimes: generics .lifetimes() .map(|lt| (<.lifetime, false)) .collect(), type_parameters: generics .type_params() .map(|tp| (&tp.ident, false)) .collect(), errors, }; visitor.lifetimes.sort_unstable(); visitor.type_parameters.sort_unstable(); impl<'ast> Visit<'ast> for Visitor<'_, '_> { fn visit_lifetime(&mut self, lifetime: &'ast Lifetime) { if lifetime.ident == "_" { self.errors.push(Rc::new(syn::Error::new_spanned( lifetime, "`#[auto_type]` requires named lifetimes", ))); } else if lifetime.ident != "static" { if let Ok(lifetime_idx) = self .lifetimes .binary_search_by_key(&lifetime, |(lt, _)| *lt) { self.lifetimes[lifetime_idx].1 = true; } } visit::visit_lifetime(self, lifetime) } fn visit_type_reference(&mut self, reference: &'ast syn::TypeReference) { if reference.lifetime.is_none() { self.errors.push(Rc::new(syn::Error::new_spanned( reference, "`#[auto_type]` requires named lifetimes", ))); } visit::visit_type_reference(self, reference) } fn visit_type_path(&mut self, type_path: &'ast syn::TypePath) { if let Some(path_ident) = type_path.path.get_ident() { if let Ok(type_param_idx) = self .type_parameters .binary_search_by_key(&path_ident, |tp| tp.0) { self.type_parameters[type_param_idx].1 = true; } } visit::visit_type_path(self, type_path) } } visitor.visit_type(ty); let generic_params: syn::punctuated::Punctuated = generics .params .iter() .filter_map(|param| match param { syn::GenericParam::Lifetime(lt) if visitor .lifetimes .binary_search(&(<.lifetime, true)) .is_ok() => { let lt = <.lifetime; Some(parse_quote!(#lt)) } syn::GenericParam::Type(tp) if visitor .type_parameters .binary_search(&(&tp.ident, true)) .is_ok() => { let ident = &tp.ident; Some(parse_quote!(#ident)) } _ => None::, }) .collect(); // We need to not set the lt_token and gt_token if `params` is empty to get // a reasonable error message for the case that there is no lifetime specifier // but we need one syn::Generics { lt_token: (!generic_params.is_empty()).then(Default::default), gt_token: (!generic_params.is_empty()).then(Default::default), params: generic_params, where_clause: None, } } dsl_auto_type-0.1.3/src/auto_type/settings_builder.rs000064400000000000000000000042371046102023000212220ustar 00000000000000use syn::parse_quote; use super::{case::Case, DeriveSettings, InferrerSettings}; #[derive(Default)] pub struct DeriveSettingsBuilder { inner: DeriveSettings, } impl DeriveSettingsBuilder { pub fn default_dsl_path(mut self, path: syn::Path) -> Self { self.inner.default_dsl_path = path; self } pub fn default_generate_type_alias(mut self, generate_type_alias: bool) -> Self { self.inner.default_generate_type_alias = generate_type_alias; self } pub fn default_method_type_case(mut self, case: Case) -> Self { self.inner.default_method_type_case = case; self } pub fn default_function_type_case(mut self, case: Case) -> Self { self.inner.default_function_type_case = case; self } pub fn build(self) -> DeriveSettings { self.inner } } impl DeriveSettings { pub fn builder() -> DeriveSettingsBuilder { DeriveSettingsBuilder::default() } } impl Default for DeriveSettings { fn default() -> Self { Self { default_method_type_case: Case::UpperCamel, default_function_type_case: Case::DoNotChange, default_dsl_path: parse_quote!(dsl), default_generate_type_alias: true, } } } #[derive(Default)] pub struct InferrerSettingsBuilder { inner: InferrerSettings, } impl InferrerSettingsBuilder { pub fn dsl_path(mut self, path: syn::Path) -> Self { self.inner.dsl_path = path; self } pub fn method_types_case(mut self, case: Case) -> Self { self.inner.method_types_case = case; self } pub fn function_types_case(mut self, case: Case) -> Self { self.inner.function_types_case = case; self } pub fn build(self) -> InferrerSettings { self.inner } } impl InferrerSettings { pub fn builder() -> InferrerSettingsBuilder { InferrerSettingsBuilder::default() } } impl Default for InferrerSettings { fn default() -> Self { Self { method_types_case: Case::UpperCamel, function_types_case: Case::DoNotChange, dsl_path: parse_quote!(dsl), } } } dsl_auto_type-0.1.3/src/lib.rs000064400000000000000000000017011046102023000144020ustar 00000000000000pub mod auto_type; use proc_macro2::TokenStream; pub use auto_type::{Case, DeriveSettings}; enum Error { Syn(syn::Error), Darling(darling::Error), } pub fn auto_type_proc_macro_attribute( attr: TokenStream, input: TokenStream, config: auto_type::DeriveSettings, ) -> TokenStream { match auto_type::auto_type_impl(attr, &input, config) { Ok(token_stream) => token_stream, Err(e) => { let mut out = input; match e { Error::Syn(e) => { out.extend(e.into_compile_error()); } Error::Darling(e) => { out.extend(e.write_errors()); } } out } } } impl From for Error { fn from(e: syn::Error) -> Self { Error::Syn(e) } } impl From for Error { fn from(e: darling::Error) -> Self { Error::Darling(e) } }