Skip to content

Commit

Permalink
refactor(ast_codegen): trim r# from start of field names
Browse files Browse the repository at this point in the history
  • Loading branch information
overlookmotel committed Aug 9, 2024
1 parent 7ab0783 commit 875a9cb
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
5 changes: 3 additions & 2 deletions tasks/ast_codegen/src/generators/assert_layouts.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use quote::quote;
use syn::Type;

use crate::{
codegen::LateCtx,
output,
schema::{FieldDef, ToType, TypeDef},
util::ToIdent,
Generator, GeneratorOutput,
};

Expand Down Expand Up @@ -96,7 +97,7 @@ fn with_offsets_assertion(

let assertions = fields.iter().zip(offsets).filter(|(field, _)| field.vis.is_pub()).map(
|(field, offset)| {
let field = field.name.as_ref().map(|it| format_ident!("{it}"));
let field = field.name.as_ref().map(ToIdent::to_ident);
quote! {
assert!(offset_of!(#ty, #field) == #offset);
}
Expand Down
5 changes: 4 additions & 1 deletion tasks/ast_codegen/src/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,10 @@ fn lower_inherit(inherit: &rust::Inherit, ctx: &codegen::EarlyCtx) -> InheritDef

fn lower_field(field: &syn::Field, ctx: &codegen::EarlyCtx) -> FieldDef {
FieldDef {
name: field.ident.as_ref().map(ToString::to_string),
name: field
.ident
.as_ref()
.map(|ident| ident.to_string().trim_start_matches("r#").to_string()),
vis: Visibility::from(&field.vis),
typ: create_type_ref(&field.ty, ctx),
markers: parse_inner_markers(&field.attrs).unwrap(),
Expand Down
22 changes: 21 additions & 1 deletion tasks/ast_codegen/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,12 +282,32 @@ impl TokenStreamExt for TokenStream {
}
}

// From https://doc.rust-lang.org/reference/keywords.html
#[rustfmt::skip]
static RESERVED_NAMES: &[&str] = &[
// Strict keywords
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if",
"impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self",
"static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "async",
"await", "dyn",
// Reserved keywords
"abstract", "become", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized",
"virtual", "yield", "try",
// Weak keywords
"macro_rules", "union", // "dyn" also listed as a weak keyword, but is already on strict list
];

impl<S> ToIdent for S
where
S: AsRef<str>,
{
fn to_ident(&self) -> Ident {
format_ident!("{}", self.as_ref())
let name = self.as_ref();
if RESERVED_NAMES.contains(&name) {
format_ident!("r#{name}")
} else {
format_ident!("{name}")
}
}
}

Expand Down

0 comments on commit 875a9cb

Please sign in to comment.