Skip to content

Commit d8be1ed

Browse files
committed
everywhere: Add support for typed comptime generics
This is useful as C++ NTTPs are limited in what they can be, specifying the type allows the compiler to omit the unusable ones from codegen.
1 parent b43ebe2 commit d8be1ed

11 files changed

Lines changed: 312 additions & 38 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/// Expect:
2+
/// - output: "typed: 10\nuntyped: 20\n"
3+
4+
comptime id<T>(anon x: T) -> T => x
5+
6+
fn typed_version<comptime N: i32>() -> i32 {
7+
return id(N) as! i32
8+
}
9+
10+
fn untyped_version<comptime N>() -> i32 {
11+
return id(N) as! i32
12+
}
13+
14+
fn main() {
15+
println("typed: {}", typed_version<comptime 10i32>())
16+
println("untyped: {}", untyped_version<comptime 20>())
17+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/// Expect:
2+
/// - output: "true\nfalse\n"
3+
4+
comptime id<T>(anon x: T) -> T => x
5+
6+
fn is_enabled<comptime B: bool>() -> bool {
7+
return id(B) as! bool
8+
}
9+
10+
fn main() {
11+
println("{}", is_enabled<comptime true>())
12+
println("{}", is_enabled<comptime false>())
13+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/// Expect:
2+
/// - output: "42\n"
3+
4+
comptime id<T>(anon x: T) -> T => x
5+
6+
fn get_value<comptime N: i32>() -> i32 {
7+
return id(N) as! i32
8+
}
9+
10+
fn main() {
11+
println("{}", get_value<comptime 42i32>())
12+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/// Expect:
2+
/// - output: "30\n"
3+
4+
comptime id<T>(anon x: T) -> T => x
5+
6+
fn multiply<comptime A: i32, comptime B: i32>() -> i32 {
7+
let a = id(A) as! i32
8+
let b = id(B) as! i32
9+
return a * b
10+
}
11+
12+
fn main() {
13+
println("{}", multiply<comptime 5i32, comptime 6i32>())
14+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/// Expect:
2+
/// - output: "110\n"
3+
4+
comptime id<T>(anon x: T) -> T => x
5+
6+
fn add_ten<comptime N: u64>() -> u64 {
7+
return (id(N) as! u64) + 10u64
8+
}
9+
10+
fn main() {
11+
println("{}", add_ten<comptime 100u64>())
12+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/// Expect:
2+
/// - output: "hello 5\n"
3+
4+
comptime id<T>(anon x: T) -> T => x
5+
6+
fn format_with_count<T, comptime N: i32>(anon value: T) throws -> String {
7+
let count = id(N) as! i32
8+
return format("{} {}", value, count)
9+
}
10+
11+
fn main() {
12+
println("{}", format_with_count<String, comptime 5i32>("hello"))
13+
}

0 commit comments

Comments
 (0)