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

feat: remove nonstandard_snake_case and import special_namings configuration #234

Merged
merged 1 commit into from
Mar 29, 2024
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
37 changes: 18 additions & 19 deletions pilota-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ pub struct Builder<MkB, P> {
change_case: bool,
keep_unknown_fields: Vec<std::path::PathBuf>,
dedups: Vec<FastStr>,
nonstandard_snake_case: bool,
special_namings: Vec<FastStr>,
common_crate_name: FastStr,
}

Expand All @@ -108,7 +108,7 @@ impl Builder<MkThriftBackend, ThriftParser> {
change_case: true,
keep_unknown_fields: Vec::default(),
dedups: Vec::default(),
nonstandard_snake_case: false,
special_namings: Vec::default(),
common_crate_name: "common".into(),
}
}
Expand All @@ -129,7 +129,7 @@ impl Builder<MkProtobufBackend, ProtobufParser> {
change_case: true,
keep_unknown_fields: Vec::default(),
dedups: Vec::default(),
nonstandard_snake_case: false,
special_namings: Vec::default(),
common_crate_name: "common".into(),
}
}
Expand All @@ -143,17 +143,6 @@ where
self.parser.include_dirs(include_dirs);
self
}

pub fn nonstandard_snake_case(mut self, flag: bool) -> Self {
self.parser.nonstandard_snake_case(flag);
self.nonstandard_snake_case = flag;
self
}

pub fn common_crate_name(mut self, name: FastStr) -> Self {
self.common_crate_name = name;
self
}
}

impl<MkB, P> Builder<MkB, P> {
Expand All @@ -168,7 +157,7 @@ impl<MkB, P> Builder<MkB, P> {
change_case: self.change_case,
keep_unknown_fields: self.keep_unknown_fields,
dedups: self.dedups,
nonstandard_snake_case: self.nonstandard_snake_case,
special_namings: self.special_namings,
common_crate_name: self.common_crate_name,
}
}
Expand Down Expand Up @@ -217,6 +206,16 @@ impl<MkB, P> Builder<MkB, P> {
self.dedups.extend(item);
self
}

pub fn special_namings(mut self, item: impl IntoIterator<Item = FastStr>) -> Self {
self.special_namings.extend(item);
self
}

pub fn common_crate_name(mut self, name: FastStr) -> Self {
self.common_crate_name = name;
self
}
}

pub enum Output {
Expand Down Expand Up @@ -272,7 +271,7 @@ where
change_case: bool,
keep_unknown_fields: Vec<PathBuf>,
dedups: Vec<FastStr>,
nonstandard_snake_case: bool,
special_namings: Vec<FastStr>,
common_crate_name: FastStr,
) -> Context {
let mut db = RootDatabase::default();
Expand Down Expand Up @@ -347,7 +346,7 @@ where
source_type,
change_case,
dedups,
nonstandard_snake_case,
special_namings,
common_crate_name,
)
}
Expand All @@ -365,7 +364,7 @@ where
self.change_case,
self.keep_unknown_fields,
self.dedups,
self.nonstandard_snake_case,
self.special_namings,
self.common_crate_name,
);

Expand Down Expand Up @@ -447,7 +446,7 @@ where
self.change_case,
self.keep_unknown_fields,
self.dedups,
self.nonstandard_snake_case,
self.special_namings,
self.common_crate_name,
);

Expand Down
20 changes: 9 additions & 11 deletions pilota-build/src/middle/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use super::{
use crate::{
db::{RirDatabase, RootDatabase},
rir::{self, Field, Item, ItemPath, Literal},
symbol::{DefId, FileId, IdentName, Symbol},
symbol::{DefId, FileId, IdentName, Symbol, SPECIAL_NAMINGS},
tags::{TagId, Tags},
ty::{AdtDef, AdtKind, CodegenTy, Visitor},
Plugin, MAX_RESOLVE_DEPTH,
Expand Down Expand Up @@ -69,7 +69,6 @@ pub struct Context {
pub entry_map: HashMap<DefLocation, Vec<(DefId, DefLocation)>>,
pub plugin_gen: DashMap<DefLocation, String>,
pub(crate) dedups: Vec<FastStr>,
pub(crate) nonstandard_snake_case: bool,
pub(crate) common_crate_name: FastStr,
}

Expand All @@ -89,7 +88,6 @@ impl Clone for Context {
entry_map: self.entry_map.clone(),
plugin_gen: self.plugin_gen.clone(),
dedups: self.dedups.clone(),
nonstandard_snake_case: self.nonstandard_snake_case,
common_crate_name: self.common_crate_name.clone(),
}
}
Expand Down Expand Up @@ -426,9 +424,10 @@ impl ContextBuilder {
source_type: SourceType,
change_case: bool,
dedups: Vec<FastStr>,
nonstandard_snake_case: bool,
special_namings: Vec<FastStr>,
common_crate_name: FastStr,
) -> Context {
SPECIAL_NAMINGS.get_or_init(|| special_namings);
Context {
adjusts: Default::default(),
source_type,
Expand All @@ -446,7 +445,6 @@ impl ContextBuilder {
entry_map: self.entry_map,
plugin_gen: Default::default(),
dedups,
nonstandard_snake_case,
common_crate_name,
}
}
Expand Down Expand Up @@ -842,26 +840,26 @@ impl Context {
crate::rir::Item::Enum(e) => (&**e.name).enum_ident(),
crate::rir::Item::Service(s) => (&**s.name).trait_ident(),
crate::rir::Item::NewType(t) => (&**t.name).newtype_ident(),
crate::rir::Item::Const(c) => (&**c.name).const_ident(self.nonstandard_snake_case),
crate::rir::Item::Mod(m) => (&**m.name).mod_ident(self.nonstandard_snake_case),
crate::rir::Item::Const(c) => (&**c.name).const_ident(),
crate::rir::Item::Mod(m) => (&**m.name).mod_ident(),
},
NodeKind::Variant(v) => {
let parent = self.node(def_id).unwrap().parent.unwrap();
let item = self.expect_item(parent);
match &*item {
rir::Item::Enum(e) => {
if e.repr.is_some() {
(&**v.name).const_ident(self.nonstandard_snake_case)
(&**v.name).const_ident()
} else {
(&**v.name).variant_ident()
}
}
_ => unreachable!(),
}
}
NodeKind::Field(f) => (&**f.name).field_ident(self.nonstandard_snake_case),
NodeKind::Method(m) => (&**m.name).fn_ident(self.nonstandard_snake_case),
NodeKind::Arg(a) => (&**a.name).field_ident(self.nonstandard_snake_case),
NodeKind::Field(f) => (&**f.name).field_ident(),
NodeKind::Method(m) => (&**m.name).fn_ident(),
NodeKind::Arg(a) => (&**a.name).field_ident(),
}
.into()
}
Expand Down
6 changes: 1 addition & 5 deletions pilota-build/src/middle/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,7 @@ impl PathResolver for DefaultPathResolver {
let file = cx.file(node.file_id).unwrap();
let package = &file.package;
if package.len() != 1 || !package.first().unwrap().0.is_empty() {
segs.extend(
package
.iter()
.map(|s| (&*s.0).mod_ident(cx.nonstandard_snake_case).into()),
)
segs.extend(package.iter().map(|s| (&*s.0).mod_ident().into()))
}
}

Expand Down
2 changes: 0 additions & 2 deletions pilota-build/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,5 @@ pub trait Parser {

fn include_dirs(&mut self, dirs: Vec<PathBuf>);

fn nonstandard_snake_case(&mut self, _nonstandard: bool) {}

fn parse(self) -> ParseResult;
}
16 changes: 3 additions & 13 deletions pilota-build/src/parser/protobuf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ pub struct ProtobufParser {
inner: protobuf_parse::Parser,
include_dirs: Vec<PathBuf>,
input_files: FxHashSet<PathBuf>,
nonstandard_snake_case: bool,
}

#[derive(PartialEq, Eq)]
Expand All @@ -41,7 +40,6 @@ struct Lower {
files: FxHashMap<String, FileId>,
cur_package: Option<String>,
cur_syntax: Syntax,
nonstandard_snake_case: bool,
}

impl Default for Lower {
Expand All @@ -51,7 +49,6 @@ impl Default for Lower {
files: Default::default(),
cur_package: None,
cur_syntax: Syntax::Proto3,
nonstandard_snake_case: false,
}
}
}
Expand Down Expand Up @@ -351,7 +348,7 @@ impl Lower {
} else {
let name = item.name();
let mut tags = Tags::default();
tags.insert(PilotaName(name.0.mod_ident(self.nonstandard_snake_case)));
tags.insert(PilotaName(name.0.mod_ident()));
vec![
item,
Item {
Expand Down Expand Up @@ -421,7 +418,7 @@ impl Lower {
files
.iter()
.map(|f| {
self.cur_package = f.package.clone();
self.cur_package.clone_from(&f.package);
self.cur_syntax = match f.syntax() {
"proto3" => Syntax::Proto3,
_ => Syntax::Proto2,
Expand Down Expand Up @@ -483,19 +480,12 @@ impl Parser for ProtobufParser {
self.inner.includes(dirs);
}

fn nonstandard_snake_case(&mut self, nonstandard: bool) {
self.nonstandard_snake_case = nonstandard;
}

fn parse(self) -> super::ParseResult {
let descriptors = self.inner.parse_and_typecheck().unwrap().file_descriptors;

let mut input_file_ids = vec![];

let mut lower = Lower {
nonstandard_snake_case: self.nonstandard_snake_case,
..Default::default()
};
let mut lower = Lower::default();

let files = lower.lower(&descriptors);

Expand Down
55 changes: 36 additions & 19 deletions pilota-build/src/symbol.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{fmt::Display, ops::Deref};
use std::{fmt::Display, ops::Deref, sync::OnceLock};

use faststr::FastStr;
use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
Expand All @@ -12,6 +12,8 @@ crate::newtype_index! {
pub struct DefId { .. }
}

pub static SPECIAL_NAMINGS: OnceLock<Vec<FastStr>> = OnceLock::new();

lazy_static::lazy_static! {
static ref KEYWORDS_SET: phf::Set<&'static str> = phf_set![
"as",
Expand Down Expand Up @@ -71,6 +73,7 @@ lazy_static::lazy_static! {
"await",
"try"
];

}

#[derive(Hash, PartialEq, Eq, Clone, Debug, PartialOrd, Ord)]
Expand Down Expand Up @@ -169,21 +172,21 @@ pub trait IdentName {
self.upper_camel_ident()
}

fn mod_ident(&self, nonstandard: bool) -> FastStr {
self.snake_ident(nonstandard)
fn mod_ident(&self) -> FastStr {
self.snake_ident()
}

fn variant_ident(&self) -> FastStr {
self.upper_camel_ident()
}
fn fn_ident(&self, nonstandard: bool) -> FastStr {
self.snake_ident(nonstandard)
fn fn_ident(&self) -> FastStr {
self.snake_ident()
}
fn field_ident(&self, nonstandard: bool) -> FastStr {
self.snake_ident(nonstandard)
fn field_ident(&self) -> FastStr {
self.snake_ident()
}
fn const_ident(&self, nonstandard: bool) -> FastStr {
self.shouty_snake_case(nonstandard)
fn const_ident(&self) -> FastStr {
self.shouty_snake_case()
}

fn trait_ident(&self) -> FastStr {
Expand All @@ -195,8 +198,8 @@ pub trait IdentName {
}

fn upper_camel_ident(&self) -> FastStr;
fn snake_ident(&self, nonstandard: bool) -> FastStr;
fn shouty_snake_case(&self, nonstandard: bool) -> FastStr;
fn snake_ident(&self) -> FastStr;
fn shouty_snake_case(&self) -> FastStr;
}

impl IdentName for &str {
Expand All @@ -205,17 +208,17 @@ impl IdentName for &str {
s.into()
}

fn snake_ident(&self, nonstandard: bool) -> FastStr {
if nonstandard {
fn snake_ident(&self) -> FastStr {
if is_common_initialism(self) {
to_snake_case(self)
} else {
self.to_snake_case()
}
.into()
}

fn shouty_snake_case(&self, nonstandard: bool) -> FastStr {
if nonstandard {
fn shouty_snake_case(&self) -> FastStr {
if is_common_initialism(self) {
to_snake_case(self).to_uppercase()
} else {
self.to_shouty_snake_case()
Expand All @@ -229,12 +232,12 @@ impl IdentName for FastStr {
(&**self).upper_camel_ident()
}

fn snake_ident(&self, nonstandard: bool) -> FastStr {
(&**self).snake_ident(nonstandard)
fn snake_ident(&self) -> FastStr {
(&**self).snake_ident()
}

fn shouty_snake_case(&self, nonstandard: bool) -> FastStr {
(&**self).shouty_snake_case(nonstandard)
fn shouty_snake_case(&self) -> FastStr {
(&**self).shouty_snake_case()
}
}

Expand Down Expand Up @@ -269,6 +272,15 @@ fn to_snake_case(mut str: &str) -> String {
words.join("_")
}

fn is_common_initialism(s: &str) -> bool {
for name in SPECIAL_NAMINGS.get().unwrap_or(&Default::default()).iter() {
if s.contains(name.as_str()) {
return true;
}
}
false
}

#[cfg(test)]
mod tests {
use heck::ToSnakeCase;
Expand All @@ -278,6 +290,11 @@ mod tests {
#[test]
fn snake_case() {
assert_eq!("IDs".to_snake_case(), "i_ds");
// positive
assert_eq!(to_snake_case("IDs"), "ids");

assert_eq!("UIDSecure".to_snake_case(), "uid_secure");
// negative
assert_eq!(to_snake_case("UIDSecure"), "uidsecure");
}
}
Loading