Skip to content

Commit

Permalink
compiler: allow deferred panic
Browse files Browse the repository at this point in the history
This is rare, but apparently some programs do this:

    defer panic("...")

This is emitted in the IR as a builtin function.
  • Loading branch information
aykevl committed Oct 31, 2024
1 parent 0edeaf6 commit 0875ebb
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions compiler/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1680,6 +1680,10 @@ func (b *builder) createBuiltin(argTypes []types.Type, argValues []llvm.Value, c
result = b.CreateSelect(cmp, result, arg, "")
}
return result, nil
case "panic":
// This is rare, but happens in "defer panic()".
b.createRuntimeInvoke("_panic", argValues, "")
return llvm.Value{}, nil
case "print", "println":
for i, value := range argValues {
if i >= 1 && callName == "println" {
Expand Down
15 changes: 15 additions & 0 deletions testdata/recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ func main() {

println("\n# panic replace")
panicReplace()

println("\n# defer panic")
deferPanic()
}

func recoverSimple() {
Expand Down Expand Up @@ -89,6 +92,18 @@ func panicReplace() {
panic("panic 1")
}

func deferPanic() {
defer func() {
printitf("recovered from deferred call:", recover())
}()

// This recover should not do anything.
defer recover()

defer panic("deferred panic")
println("defer panic")
}

func printitf(msg string, itf interface{}) {
switch itf := itf.(type) {
case string:
Expand Down
4 changes: 4 additions & 0 deletions testdata/recover.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ recovered: panic
panic 1
panic 2
recovered: panic 2

# defer panic
defer panic
recovered from deferred call: deferred panic

0 comments on commit 0875ebb

Please sign in to comment.