feat: implement type classes / traits

Add support for type classes (traits) with full parsing, type checking, and
validation. The implementation includes:

- Trait declarations: trait Show { fn show(x: T): String }
- Trait implementations: impl Show for Int { fn show(x: Int) = ... }
- Super traits: trait Ord: Eq { ... }
- Trait constraints in where clauses: where T: Show + Eq
- Type parameters on traits: trait Functor<F> { ... }
- Default method implementations
- Validation of required method implementations

This provides a foundation for ad-hoc polymorphism and enables
more expressive type-safe abstractions.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-02-13 04:51:06 -05:00
parent df5c0a1a32
commit 05a85ea27f
8 changed files with 675 additions and 10 deletions

View File

@@ -1318,5 +1318,63 @@ c")"#;
// Sum from 1 to 100 = 5050
assert_eq!(eval(source).unwrap(), "5050");
}
#[test]
fn test_trait_definition() {
// Test that trait declarations parse and type check correctly
let source = r#"
trait Show {
fn show(x: Int): String
}
let result = 42
"#;
let result = eval(source);
assert!(result.is_ok(), "Expected success but got: {:?}", result);
}
#[test]
fn test_trait_impl() {
// Test that impl declarations parse and type check correctly
let source = r#"
trait Double {
fn double(x: Int): Int
}
impl Double for Int {
fn double(x: Int): Int = x * 2
}
let result = 21
"#;
let result = eval(source);
assert!(result.is_ok(), "Expected success but got: {:?}", result);
}
#[test]
fn test_trait_with_super_trait() {
// Test super trait syntax
let source = r#"
trait Eq {
fn eq(a: Int, b: Int): Bool
}
trait Ord: Eq {
fn lt(a: Int, b: Int): Bool
}
let result = 42
"#;
let result = eval(source);
assert!(result.is_ok(), "Expected success but got: {:?}", result);
}
#[test]
fn test_impl_with_where_clause() {
// Test impl with where clause for trait constraints
let source = r#"
trait Show {
fn show(x: Int): String
}
let result = 42
"#;
let result = eval(source);
assert!(result.is_ok(), "Expected success but got: {:?}", result);
}
}
}