diff --git a/error_templates/java/test_files/unreachable_statement_error/test.txt b/error_templates/java/test_files/unreachable_statement_error/test.txt index ed6ea90..3da7a03 100644 --- a/error_templates/java/test_files/unreachable_statement_error/test.txt +++ b/error_templates/java/test_files/unreachable_statement_error/test.txt @@ -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"); + } } ``` diff --git a/error_templates/java/unreachable_statement_error.go b/error_templates/java/unreachable_statement_error.go index 2c92976..5f1a1a5 100644 --- a/error_templates/java/unreachable_statement_error.go +++ b/error_templates/java/unreachable_statement_error.go @@ -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, + }) + }) }, }