generics (in the compiler written in Finch)

fn max[T](T a, T b) -> T      struct Stack[T] { []T items }      fn Stack[T].push(T x)

The type is worked out from the arguments (max(3, 4), first([1, 2])) and written out
where it cannot be: max[float](1, 2.5), Stack[int](), Pair[str, int](...). Each use makes
its own copy, so a generic costs nothing at run time. Several parameters
(Pair[A, B]), nesting (Stack[Pair[int, str]]), methods, and printing (Stack[int](items: ...))
work. An error inside a generic says which version it was building.

boot.sh: 37 passed, 0 failed (stage 2 and 3 identical).
This commit is contained in:
Nexoniarz 2026-10-25 20:53:13 +01:00
commit 04eb0cce55
10 changed files with 575 additions and 7 deletions

View file

@ -0,0 +1,15 @@
// expect: (while building bigger[Point])
struct Point {
int x
}
fn bigger[T](T a, T b) -> T {
if a > b {
return a
}
return b
}
fn main() {
print(bigger(Point(1), Point(2)))
}

View file

@ -0,0 +1,10 @@
// expect: can't tell what T is here
fn make[T]() -> []T {
[]T out
return out
}
fn main() {
x := make()
print(x)
}

View file

@ -0,0 +1,9 @@
// expect: 'Stack' is generic, so say which type it holds
struct Stack[T] {
[]T items
}
fn main() {
s := Stack()
print(s)
}

View file

@ -0,0 +1,8 @@
// expect: 'add' is not generic, so it takes no type arguments
fn add(int a, int b) -> int {
return a + b
}
fn main() {
print(add[int](1, 2))
}

View file

@ -0,0 +1,9 @@
// expect: Stack takes 1 type argument(s)
struct Stack[T] {
[]T items
}
fn main() {
Stack[int, str] s
print(s)
}