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

Escape rust keywords with r# raw identifier #224

Merged
merged 5 commits into from
Oct 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 3 additions & 2 deletions sea-orm-codegen/src/entity/column.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::util::escape_rust_keyword;
use heck::{CamelCase, SnakeCase};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};
Expand All @@ -14,11 +15,11 @@ pub struct Column {

impl Column {
pub fn get_name_snake_case(&self) -> Ident {
format_ident!("{}", self.name.to_snake_case())
format_ident!("{}", escape_rust_keyword(self.name.to_snake_case()))
}

pub fn get_name_camel_case(&self) -> Ident {
format_ident!("{}", self.name.to_camel_case())
format_ident!("{}", escape_rust_keyword(self.name.to_camel_case()))
}

pub fn get_rs_type(&self) -> TokenStream {
Expand Down
72 changes: 70 additions & 2 deletions sea-orm-codegen/src/entity/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -597,18 +597,85 @@ mod tests {
name: "id".to_owned(),
}],
},
Entity {
table_name: "rust_keyword".to_owned(),
columns: vec![
Column {
name: "id".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: true,
not_null: true,
unique: false,
},
Column {
name: "testing".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "rust".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "keywords".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "type".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "typeof".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "crate".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: false,
not_null: true,
unique: false,
},
Column {
name: "self".to_owned(),
col_type: ColumnType::Integer(Some(11)),
auto_increment: false,
not_null: true,
unique: false,
},
],
relations: vec![],
conjunct_relations: vec![],
primary_keys: vec![PrimaryKey {
name: "id".to_owned(),
}],
},
]
}

#[test]
fn test_gen_expanded_code_blocks() -> io::Result<()> {
let entities = setup();
const ENTITY_FILES: [&str; 5] = [
const ENTITY_FILES: [&str; 6] = [
include_str!("../../tests/expanded/cake.rs"),
include_str!("../../tests/expanded/cake_filling.rs"),
include_str!("../../tests/expanded/filling.rs"),
include_str!("../../tests/expanded/fruit.rs"),
include_str!("../../tests/expanded/vendor.rs"),
include_str!("../../tests/expanded/rust_keyword.rs"),
];

assert_eq!(entities.len(), ENTITY_FILES.len());
Expand Down Expand Up @@ -642,12 +709,13 @@ mod tests {
#[test]
fn test_gen_compact_code_blocks() -> io::Result<()> {
let entities = setup();
const ENTITY_FILES: [&str; 5] = [
const ENTITY_FILES: [&str; 6] = [
include_str!("../../tests/compact/cake.rs"),
include_str!("../../tests/compact/cake_filling.rs"),
include_str!("../../tests/compact/filling.rs"),
include_str!("../../tests/compact/fruit.rs"),
include_str!("../../tests/compact/vendor.rs"),
include_str!("../../tests/compact/rust_keyword.rs"),
];

assert_eq!(entities.len(), ENTITY_FILES.len());
Expand Down
1 change: 1 addition & 0 deletions sea-orm-codegen/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod entity;
mod error;
mod util;

pub use entity::*;
pub use error::*;
23 changes: 23 additions & 0 deletions sea-orm-codegen/src/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub(crate) fn escape_rust_keyword<T>(string: T) -> String
where
T: ToString,
{
let string = string.to_string();
if RUST_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("r#{}", string)
} else if RUST_SPECIAL_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("{}_", string)
} else {
string
}
}

pub(crate) const RUST_KEYWORDS: [&str; 49] = [
"as", "async", "await", "break", "const", "continue", "dyn", "else", "enum", "extern", "false",
"fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
"return", "static", "struct", "super", "trait", "true", "type", "union", "unsafe", "use",
"where", "while", "abstract", "become", "box", "do", "final", "macro", "override", "priv",
"try", "typeof", "unsized", "virtual", "yield",
];

pub(crate) const RUST_SPECIAL_KEYWORDS: [&str; 3] = ["crate", "Self", "self"];
30 changes: 30 additions & 0 deletions sea-orm-codegen/tests/compact/rust_keyword.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.1.0

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "rust_keyword")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub testing: i32,
pub rust: i32,
pub keywords: i32,
pub r#type: i32,
pub r#typeof: i32,
pub crate_: i32,
pub self_: i32,
}

#[derive(Copy, Clone, Debug, EnumIter)]
pub enum Relation {}

impl RelationTrait for Relation {
fn def(&self) -> RelationDef {
match self {
_ => panic!("No RelationDef"),
}
}
}

impl ActiveModelBehavior for ActiveModel {}
79 changes: 79 additions & 0 deletions sea-orm-codegen/tests/expanded/rust_keyword.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.1.0

use sea_orm::entity::prelude::*;

#[derive(Copy, Clone, Default, Debug, DeriveEntity)]
pub struct Entity;

impl EntityName for Entity {
fn table_name(&self) -> &str {
"rust_keyword"
}
}

#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel)]
pub struct Model {
pub id: i32,
pub testing: i32,
pub rust: i32,
pub keywords: i32,
pub r#type: i32,
pub r#typeof: i32,
pub crate_: i32,
pub self_: i32,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
pub enum Column {
Id,
Testing,
Rust,
Keywords,
Type,
Typeof,
Crate,
Self_,
}

#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)]
pub enum PrimaryKey {
Id,
}

impl PrimaryKeyTrait for PrimaryKey {
type ValueType = i32;

fn auto_increment() -> bool {
true
}
}

#[derive(Copy, Clone, Debug, EnumIter)]
pub enum Relation {}

impl ColumnTrait for Column {
type EntityName = Entity;

fn def(&self) -> ColumnDef {
match self {
Self::Id => ColumnType::Integer.def(),
Self::Testing => ColumnType::Integer.def(),
Self::Rust => ColumnType::Integer.def(),
Self::Keywords => ColumnType::Integer.def(),
Self::Type => ColumnType::Integer.def(),
Self::Typeof => ColumnType::Integer.def(),
Self::Crate => ColumnType::Integer.def(),
Self::Self_ => ColumnType::Integer.def(),
}
}
}

impl RelationTrait for Relation {
fn def(&self) -> RelationDef {
match self {
_ => panic!("No RelationDef"),
}
}
}

impl ActiveModelBehavior for ActiveModel {}
10 changes: 5 additions & 5 deletions sea-orm-macros/src/derives/active_model.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::util::field_not_ignored;
use crate::util::{escape_rust_keyword, field_not_ignored, trim_starting_raw_identifier};
use heck::CamelCase;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, quote_spanned};
Expand Down Expand Up @@ -29,10 +29,10 @@ pub fn expand_derive_active_model(ident: Ident, data: Data) -> syn::Result<Token
.clone()
.into_iter()
.map(|field| {
let mut ident = format_ident!(
"{}",
field.ident.as_ref().unwrap().to_string().to_camel_case()
);
let ident = field.ident.as_ref().unwrap().to_string();
let ident = trim_starting_raw_identifier(ident).to_camel_case();
let ident = escape_rust_keyword(ident);
let mut ident = format_ident!("{}", &ident);
for attr in field.attrs.iter() {
if let Some(ident) = attr.path.get_ident() {
if ident != "sea_orm" {
Expand Down
12 changes: 8 additions & 4 deletions sea-orm-macros/src/derives/entity_model.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::util::{escape_rust_keyword, trim_starting_raw_identifier};
use convert_case::{Case, Casing};
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use syn::{
parse::Error, punctuated::Punctuated, spanned::Spanned, token::Comma, Attribute, Data, Fields,
Lit, Meta,
};

use convert_case::{Case, Casing};

pub fn expand_derive_entity_model(data: Data, attrs: Vec<Attribute>) -> syn::Result<TokenStream> {
// if #[sea_orm(table_name = "foo", schema_name = "bar")] specified, create Entity struct
let mut table_name = None;
Expand Down Expand Up @@ -60,8 +60,10 @@ pub fn expand_derive_entity_model(data: Data, attrs: Vec<Attribute>) -> syn::Res
if let Fields::Named(fields) = item_struct.fields {
for field in fields.named {
if let Some(ident) = &field.ident {
let mut field_name =
Ident::new(&ident.to_string().to_case(Case::Pascal), Span::call_site());
let mut field_name = Ident::new(
&trim_starting_raw_identifier(&ident).to_case(Case::Pascal),
Span::call_site(),
);

let mut nullable = false;
let mut default_value = None;
Expand Down Expand Up @@ -168,6 +170,8 @@ pub fn expand_derive_entity_model(data: Data, attrs: Vec<Attribute>) -> syn::Res
field_name = enum_name;
}

field_name = Ident::new(&escape_rust_keyword(field_name), Span::call_site());

if ignore {
continue;
} else {
Expand Down
13 changes: 8 additions & 5 deletions sea-orm-macros/src/derives/model.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::{attributes::derive_attr, util::field_not_ignored};
use crate::{
attributes::derive_attr,
util::{escape_rust_keyword, field_not_ignored, trim_starting_raw_identifier},
};
use heck::CamelCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
Expand Down Expand Up @@ -43,10 +46,10 @@ impl DeriveModel {
let column_idents = fields
.iter()
.map(|field| {
let mut ident = format_ident!(
"{}",
field.ident.as_ref().unwrap().to_string().to_camel_case()
);
let ident = field.ident.as_ref().unwrap().to_string();
let ident = trim_starting_raw_identifier(ident).to_camel_case();
let ident = escape_rust_keyword(ident);
let mut ident = format_ident!("{}", &ident);
for attr in field.attrs.iter() {
if let Some(ident) = attr.path.get_ident() {
if ident != "sea_orm" {
Expand Down
36 changes: 36 additions & 0 deletions sea-orm-macros/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,39 @@ pub(crate) fn field_not_ignored(field: &Field) -> bool {
}
true
}

pub(crate) fn trim_starting_raw_identifier<T>(string: T) -> String
where
T: ToString,
{
string
.to_string()
.trim_start_matches(RAW_IDENTIFIER)
.to_string()
}

pub(crate) fn escape_rust_keyword<T>(string: T) -> String
where
T: ToString,
{
let string = string.to_string();
if RUST_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("r#{}", string)
} else if RUST_SPECIAL_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("{}_", string)
} else {
string
}
}

pub(crate) const RAW_IDENTIFIER: &str = "r#";

pub(crate) const RUST_KEYWORDS: [&str; 49] = [
"as", "async", "await", "break", "const", "continue", "dyn", "else", "enum", "extern", "false",
"fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
"return", "static", "struct", "super", "trait", "true", "type", "union", "unsafe", "use",
"where", "while", "abstract", "become", "box", "do", "final", "macro", "override", "priv",
"try", "typeof", "unsized", "virtual", "yield",
];

pub(crate) const RUST_SPECIAL_KEYWORDS: [&str; 3] = ["crate", "Self", "self"];
2 changes: 2 additions & 0 deletions src/tests_cfg/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod cake_filling_price;
pub mod entity_linked;
pub mod filling;
pub mod fruit;
pub mod rust_keyword;
pub mod vendor;

pub use cake::Entity as Cake;
Expand All @@ -15,4 +16,5 @@ pub use cake_filling::Entity as CakeFilling;
pub use cake_filling_price::Entity as CakeFillingPrice;
pub use filling::Entity as Filling;
pub use fruit::Entity as Fruit;
pub use rust_keyword::Entity as RustKeyword;
pub use vendor::Entity as Vendor;
Loading