|
| 1 | +package java |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "regexp" |
| 6 | + "strings" |
| 7 | + |
| 8 | + lib "github.com/nedpals/errgoengine" |
| 9 | +) |
| 10 | + |
| 11 | +func generateVarName(inputString string) string { |
| 12 | + reg := regexp.MustCompile("[^a-zA-Z0-9_]") |
| 13 | + processedString := reg.ReplaceAllString(inputString, "") |
| 14 | + return strings.TrimSpace(processedString) |
| 15 | +} |
| 16 | + |
| 17 | +var NotAStatementError = lib.ErrorTemplate{ |
| 18 | + Name: "NotAStatementError", |
| 19 | + Pattern: comptimeErrorPattern(`not a statement`), |
| 20 | + StackTracePattern: comptimeStackTracePattern, |
| 21 | + OnAnalyzeErrorFn: func(cd *lib.ContextData, m *lib.MainError) { |
| 22 | + if m.Nearest.Type() == "expression_statement" { |
| 23 | + m.Nearest = m.Nearest.NamedChild(0) |
| 24 | + } |
| 25 | + }, |
| 26 | + OnGenExplainFn: func(cd *lib.ContextData, gen *lib.ExplainGenerator) { |
| 27 | + gen.Add("This error occurs when a line of code is written that is not a valid statement.") |
| 28 | + }, |
| 29 | + OnGenBugFixFn: func(cd *lib.ContextData, gen *lib.BugFixGenerator) { |
| 30 | + nodeType := cd.Analyzer.AnalyzeNode(cd.MainError.Nearest) |
| 31 | + |
| 32 | + gen.Add(fmt.Sprintf("Convert the `%s` to a statement", nodeType.Name()), func(s *lib.BugFixSuggestion) { |
| 33 | + s.AddStep( |
| 34 | + "If you intended to use the `%s` as a statement, you can print it or use it in a valid statement.", |
| 35 | + nodeType.Name(), |
| 36 | + ).AddFix(lib.FixSuggestion{ |
| 37 | + NewText: fmt.Sprintf("System.out.println(%s)", cd.MainError.Nearest.Text()), |
| 38 | + StartPosition: cd.MainError.Nearest.StartPosition(), |
| 39 | + EndPosition: cd.MainError.Nearest.EndPosition(), |
| 40 | + Description: "This change makes the string part of a valid statement by printing it to the console.", |
| 41 | + }) |
| 42 | + }) |
| 43 | + |
| 44 | + gen.Add(fmt.Sprintf("Assign the `%s` to a variable", nodeType.Name()), func(s *lib.BugFixSuggestion) { |
| 45 | + s.AddStep("Alternatively, you can assign the `%s` to a variable to make it a valid statement.", nodeType.Name()). |
| 46 | + AddFix(lib.FixSuggestion{ |
| 47 | + NewText: fmt.Sprintf("%s %s = %s", nodeType.Name(), generateVarName(cd.MainError.Nearest.Text()), cd.MainError.Nearest.Text()), |
| 48 | + StartPosition: cd.MainError.Nearest.StartPosition(), |
| 49 | + EndPosition: cd.MainError.Nearest.EndPosition(), |
| 50 | + Description: "This way, the string is now part of a statement and can be used later in your code.", |
| 51 | + }) |
| 52 | + }) |
| 53 | + }, |
| 54 | +} |
0 commit comments