From 18ef1c0641859a24c594a8c8b30108dc3a9a353e Mon Sep 17 00:00:00 2001 From: gammelalf Date: Fri, 6 Sep 2024 21:57:39 +0200 Subject: [PATCH] Fixed usage of `Self` in a model's fields Fixes #66 --- rorm-macro/Cargo.toml | 5 +---- rorm-macro/src/analyze/model.rs | 14 +++++++++++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/rorm-macro/Cargo.toml b/rorm-macro/Cargo.toml index 2a374ad..a22e41a 100644 --- a/rorm-macro/Cargo.toml +++ b/rorm-macro/Cargo.toml @@ -16,7 +16,7 @@ proc-macro = true [dependencies] # syn builds rust syntax trees from strings or tokenstream -syn = { version = "~1" } +syn = { version = "~1", features = ["full", "visit-mut"] } # quote provides a macro to write rust code with template variables which then produces a tokenstream quote = { version = "~1" } # a higher level wrapper for rust's proc-macro which is used by syn and quote @@ -28,8 +28,5 @@ darling = { version = "~0.14" } rustc_version = "0.4.0" [features] -default = [ - "syn/full" -] # requires nightly rust unstable = [] diff --git a/rorm-macro/src/analyze/model.rs b/rorm-macro/src/analyze/model.rs index 60a4c92..b519a01 100644 --- a/rorm-macro/src/analyze/model.rs +++ b/rorm-macro/src/analyze/model.rs @@ -1,5 +1,6 @@ use proc_macro2::Ident; use quote::format_ident; +use syn::visit_mut::VisitMut; use syn::{LitInt, LitStr, Type, Visibility}; use crate::analyze::vis_to_display; @@ -39,7 +40,7 @@ pub fn analyze_model(parsed: ParsedModel) -> darling::Result { let ParsedField { vis, ident, - ty, + mut ty, annos: ModelFieldAnnotations { auto_create_time, @@ -86,6 +87,17 @@ pub fn analyze_model(parsed: ParsedModel) -> darling::Result { auto_increment = true; } + // Replace `Self` in the field's type to the model's identifier + struct ReplaceSelf<'a>(&'a Ident); + impl<'a> VisitMut for ReplaceSelf<'a> { + fn visit_ident_mut(&mut self, i: &mut Ident) { + if i == "Self" { + *i = self.0.clone(); + } + } + } + ReplaceSelf(model_ident).visit_type_mut(&mut ty); + analyzed_fields.push(AnalyzedField { vis, unit: format_ident!("__{}_{}", model_ident, ident),