Skip to content

Commit

Permalink
adding support for overriding toString in kotlin
Browse files Browse the repository at this point in the history
  • Loading branch information
Ellen Arteca committed Dec 3, 2024
1 parent 9e627e2 commit 0c32e7b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 10 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 24 additions & 4 deletions tool/src/kotlin/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ pub(super) struct KotlinFormatter<'tcx> {
docs_url_gen: &'tcx DocsUrlGenerator,
}

const INVALID_METHOD_NAMES: &[&str] = &[
const INVALID_RAW_METHOD_NAMES: &[&str] = &[
"new", "static", "default", "private", "internal", "toString",
];
const DISALLOWED_CORE_TYPES: &[&str] = &["Object", "String"];
const OVERRIDE_METHOD_SIGS: &[&str] = &["fun toString(): String"];

impl<'tcx> KotlinFormatter<'tcx> {
pub fn new(
Expand Down Expand Up @@ -112,18 +113,37 @@ impl<'tcx> KotlinFormatter<'tcx> {
}
}

pub fn fmt_method_name<'a>(&self, method: &'a hir::Method) -> Cow<'a, str> {
pub fn fmt_method_name<'a>(
&self,
method: &'a hir::Method,
should_be_overridden: bool,
) -> Cow<'a, str> {
// TODO(#60): handle other keywords

let name = method.name.as_str().to_lower_camel_case();
let name = method.attrs.rename.apply(name.into());
if INVALID_METHOD_NAMES.contains(&&*name) {
if INVALID_RAW_METHOD_NAMES.contains(&&*name) && !should_be_overridden {
format!("{name}_").into()
} else {
name
}
}

pub fn method_should_be_overridden<'a>(
&self,
method: &'a hir::Method,
params: &str,
return_type: &str,
) -> bool {
let method_sig = format!(
"fun {}({}): {}",
&&*method.name.as_str().to_lower_camel_case(),
params,
return_type
);
OVERRIDE_METHOD_SIGS.contains(&&*method_sig)
}

pub fn fmt_trait_method_name<'a>(&self, method: &'a hir::Callback) -> Cow<'a, str> {
if method.name.is_none() {
panic!("Trait methods need a name");
Expand All @@ -134,7 +154,7 @@ impl<'tcx> KotlinFormatter<'tcx> {
} else {
name.into()
};
if INVALID_METHOD_NAMES.contains(&&*name) {
if INVALID_RAW_METHOD_NAMES.contains(&&*name) {
format!("{name}_").into()
} else {
name
Expand Down
22 changes: 17 additions & 5 deletions tool/src/kotlin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1188,11 +1188,23 @@ returnVal.option() ?: return null
panic!("Can only have one iterable method per opaque struct")
}
}
_ => format!(
"fun {}({}): {return_ty}",
self.formatter.fmt_method_name(method),
params
),
_ => {
let should_be_overridden = self.formatter.method_should_be_overridden(
method,
&params,
&return_ty.to_string(),
);
format!(
"{}fun {}({}): {return_ty}",
if should_be_overridden {
"override "
} else {
""
},
self.formatter.fmt_method_name(method, should_be_overridden),
params
)
}
};

MethodTpl {
Expand Down

0 comments on commit 0c32e7b

Please sign in to comment.