Skip to content

Commit

Permalink
frontend: Avoid error if trait default method exists
Browse files Browse the repository at this point in the history
  • Loading branch information
dinfuehr committed Oct 14, 2024
1 parent 6af5cbe commit 3bb40a7
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 20 deletions.
1 change: 1 addition & 0 deletions dora-frontend/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3287,6 +3287,7 @@ pub fn register_bty_from_ty(ty: SourceType) -> BytecodeType {
SourceType::TypeParam(idx) => BytecodeType::TypeParam(idx.index() as u32),
SourceType::Lambda(_, _) => BytecodeType::Ptr,
SourceType::Ptr => BytecodeType::Ptr,
SourceType::This => BytecodeType::This,
_ => panic!("SourceType {:?} cannot be converted to BytecodeType", ty),
}
}
Expand Down
67 changes: 47 additions & 20 deletions dora-frontend/src/impldefck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,20 @@ fn check_impl_methods(
}
}

if !remaining_trait_methods.is_empty() {
report_missing_methods(sa, impl_, trait_, remaining_trait_methods);
for trait_method_id in &remaining_trait_methods {
let trait_method = sa.fct(*trait_method_id);

if trait_method.has_body() {
// Do nothing.
} else {
let mtd_name = sa.interner.str(trait_method.name).to_string();

sa.report(
impl_.file_id,
impl_.declaration_span,
ErrorMessage::ElementNotInImpl(mtd_name),
)
}
}

assert!(impl_.trait_method_map.set(trait_method_map).is_ok());
Expand Down Expand Up @@ -370,24 +382,6 @@ fn trait_and_impl_arg_ty_compatible_array(
true
}

fn report_missing_methods(
sa: &Sema,
impl_: &ImplDefinition,
_trait: &TraitDefinition,
missing_methods: HashSet<FctDefinitionId>,
) {
for method_id in missing_methods {
let method = sa.fct(method_id);
let mtd_name = sa.interner.str(method.name).to_string();

sa.report(
impl_.file_id,
impl_.declaration_span,
ErrorMessage::ElementNotInImpl(mtd_name),
)
}
}

pub fn connect_aliases_to_trait(sa: &Sema) {
for (_id, impl_) in sa.impls.iter() {
if let Some(trait_ty) = impl_.trait_ty() {
Expand Down Expand Up @@ -1063,4 +1057,37 @@ mod tests {
fn f(x: Int64): Foo[Int64] { x as Foo[Int64] }
");
}

#[test]
fn impl_reuse_trait_implementation() {
ok("
trait Foo {
fn f(): Int64;
fn g(): Int64 { 0 }
}
impl Foo for String {
fn f(): Int64 { 1 }
}
")
}

#[test]
#[ignore]
fn impl_reuse_trait_implementation_with_call() {
ok("
trait Foo {
fn f(): Int64;
fn g(): Int64 { 0 }
}
impl Foo for String {
fn f(): Int64 { 1 }
}
fn x(a: String) {
a.g();
}
")
}
}
16 changes: 16 additions & 0 deletions tests/trait/trait-default1.dora
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//= ignore

trait Foo {
fn f(): Int64 { 0}
fn g(): Int64 { 2 }
}

impl Foo for String {
fn f(): Int64 { 1 }
}

fn main() {
let a: String = "foo";
assert(a.f() == 1);
assert(a.g() == 2);
}

0 comments on commit 3bb40a7

Please sign in to comment.