Skip to content

Commit

Permalink
Code generation for trait support in Kotlin (#689)
Browse files Browse the repository at this point in the history
  • Loading branch information
emarteca authored Sep 16, 2024
1 parent 8e09751 commit de87900
Show file tree
Hide file tree
Showing 7 changed files with 679 additions and 8 deletions.

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

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

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

40 changes: 39 additions & 1 deletion tool/src/kotlin/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use diplomat_core::hir::{
self,
borrowing_param::{LifetimeEdge, LifetimeEdgeKind},
FloatType, IntSizeType, IntType, LifetimeEnv, MaybeStatic, PrimitiveType, Slice,
StringEncoding, StructPathLike, TyPosition, Type, TypeContext, TypeId,
StringEncoding, StructPathLike, TraitId, TyPosition, Type, TypeContext, TypeId,
};
use heck::ToLowerCamelCase;
use std::{borrow::Cow, iter::once};
Expand Down Expand Up @@ -106,6 +106,23 @@ impl<'tcx> KotlinFormatter<'tcx> {
}
}

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");
}
let name = method.name.clone().unwrap().as_str().to_lower_camel_case();
let name = if method.attrs.is_some() {
method.attrs.as_ref().unwrap().rename.apply(name.into())
} else {
name.into()
};
if INVALID_METHOD_NAMES.contains(&&*name) {
format!("{name}_").into()
} else {
name
}
}

pub fn fmt_param_name<'a>(&self, ident: &'a str) -> Cow<'tcx, str> {
ident.to_lower_camel_case().into()
}
Expand Down Expand Up @@ -351,6 +368,27 @@ impl<'tcx> KotlinFormatter<'tcx> {
resolved.attrs().rename.apply(candidate)
}

pub fn fmt_trait_name(&self, id: TraitId) -> Cow<'tcx, str> {
let resolved = self.tcx.resolve_trait(id);

let candidate: Cow<str> = if let Some(strip_prefix) = self.strip_prefix.as_ref() {
resolved
.name
.as_str()
.strip_prefix(strip_prefix)
.unwrap_or(resolved.name.as_str())
.into()
} else {
resolved.name.as_str().into()
};

if DISALLOWED_CORE_TYPES.contains(&&*candidate) {
panic!("{candidate:?} is not a valid Kotlin trait name. Please rename.");
}

resolved.attrs.rename.apply(candidate)
}

pub fn fmt_nullable(&self, ident: &str) -> String {
format!("{ident}?")
}
Expand Down
Loading

0 comments on commit de87900

Please sign in to comment.