Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
cgen: fix interface generic smartcast (#20609)
- Loading branch information
Showing
2 changed files
with
50 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
fn cast_interface[T, U](u U) T { | ||
$if U is $interface { | ||
if u is T { | ||
return u | ||
} else { | ||
panic('expected t to be ${typeof[T]().name}, got ${typeof[U]().name}') | ||
} | ||
} $else { | ||
$compile_error('not an interface') | ||
} | ||
} | ||
|
||
interface Foo { | ||
f() | ||
} | ||
|
||
struct Bar {} | ||
|
||
fn (bar Bar) f() {} | ||
|
||
struct Baz {} | ||
|
||
fn (baz Baz) f() {} | ||
|
||
fn (_ Bar) g() int { | ||
return 0 | ||
} | ||
|
||
fn (_ Baz) g() int { | ||
return 1 | ||
} | ||
|
||
fn f(foo Foo) int { | ||
if foo is Bar { | ||
return cast_interface[Bar, Foo](foo).g() | ||
} | ||
if foo is Baz { | ||
return cast_interface[Baz, Foo](foo).g() | ||
} | ||
return -1 | ||
} | ||
|
||
fn test_main() { | ||
assert f(Bar{}) == 0 | ||
assert f(Baz{}) == 1 | ||
} |