Skip to content

Commit

Permalink
fix: make Java.UnreachableStatementError work
Browse files Browse the repository at this point in the history
  • Loading branch information
nedpals committed Nov 28, 2023
1 parent 04609eb commit fee825d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,21 @@ template: "Java.UnreachableStatementError"
---
# UnreachableStatementError
This error occurs because there's code after a return statement, which can never be reached as the function has already exited.

```
return;
System.out.println("c");
^^^^^^^^^^^^^^^^^^^^^^^^
}
}
```
## Steps to fix
1. Remove the code after the `return` statement.

### Remove unreachable code
Since the `return` statement is encountered before `System.out.println("c");`, the latter statement is unreachable. Remove the unreachable statement/s.
```diff
System.out.println("b");
return;
- System.out.println("c");
public static void main(String[] args) {
System.out.println("b");
return;
- System.out.println("c");
}
}
```
27 changes: 23 additions & 4 deletions error_templates/java/unreachable_statement_error.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,35 @@
package java

import lib "github.com/nedpals/errgoengine"
import (
lib "github.com/nedpals/errgoengine"
)

var UnreachableStatementError = lib.ErrorTemplate{
Name: "UnreachableStatementError",
Pattern: comptimeErrorPattern("unreachable statement"),
StackTracePattern: comptimeStackTracePattern,
OnAnalyzeErrorFn: func(cd *lib.ContextData, m *lib.MainError) {

},
OnGenExplainFn: func(cd *lib.ContextData, gen *lib.ExplainGenerator) {
// TODO: identify return
gen.Add("You have code below after you returned a value")
gen.Add("This error occurs because there's code after a return statement, which can never be reached as the function has already exited.")
},
OnGenBugFixFn: func(cd *lib.ContextData, gen *lib.BugFixGenerator) {
// TODO:
gen.Add("Remove unreachable code", func(s *lib.BugFixSuggestion) {
startPos := cd.MainError.Nearest.StartPosition()
endPos := cd.MainError.Nearest.Parent().LastNamedChild().EndPosition()

// Adjust the start position to the beginning of the line
startPos = startPos.Add(lib.Position{Column: -startPos.Column})

s.AddStep(
"Since the `return` statement is encountered before `%s`, the latter statement is unreachable. Remove the unreachable statement/s.",
cd.MainError.Nearest.Text(),
).AddFix(lib.FixSuggestion{
NewText: "",
StartPosition: startPos,
EndPosition: endPos,
})
})
},
}

0 comments on commit fee825d

Please sign in to comment.