|
| 1 | +package java |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strconv" |
| 6 | + "strings" |
| 7 | + |
| 8 | + lib "github.com/nedpals/errgoengine" |
| 9 | +) |
| 10 | + |
| 11 | +var BracketMismatchError = lib.ErrorTemplate{ |
| 12 | + Name: "ArrayIndexOutOfBoundsException", |
| 13 | + Pattern: comptimeErrorPattern(`'(?P<expected>\S+)' expected`), |
| 14 | + OnAnalyzeErrorFn: func(cd *lib.ContextData, m *lib.MainError) { |
| 15 | + lib.QueryNode(m.Nearest, strings.NewReader("(array_access index: (_) @index)"), func(ctx lib.QueryNodeCtx) bool { |
| 16 | + match := ctx.Cursor.FilterPredicates(ctx.Match, []byte(m.Nearest.Doc.Contents)) |
| 17 | + for _, c := range match.Captures { |
| 18 | + node := lib.WrapNode(m.Nearest.Doc, c.Node) |
| 19 | + m.Nearest = node |
| 20 | + return false |
| 21 | + } |
| 22 | + return true |
| 23 | + }) |
| 24 | + }, |
| 25 | + OnGenExplainFn: func(cd *lib.ContextData, gen *lib.ExplainGenerator) { |
| 26 | + gen.Add("This error occurs because the code is trying to access index %s that is beyond the bounds of the array which only has %s items.", cd.Variables["index"], cd.Variables["length"]) |
| 27 | + }, |
| 28 | + OnGenBugFixFn: func(cd *lib.ContextData, gen *lib.BugFixGenerator) { |
| 29 | + arrayLen, _ := strconv.Atoi(cd.Variables["length"]) |
| 30 | + |
| 31 | + // TODO: add a suggestion to add an if statement if the array length is 0 |
| 32 | + |
| 33 | + gen.Add("Accessing Array Index Within Bounds", func(s *lib.BugFixSuggestion) { |
| 34 | + sampleIndex := max(0, arrayLen-2) |
| 35 | + |
| 36 | + s.AddStep("The error is caused by trying to access an index that does not exist within the array. Instead of accessing index %s, which is beyond the array's length, change it to a valid index within the array bounds, for example, `nums[%d]`.", cd.Variables["index"], sampleIndex). |
| 37 | + AddFix(lib.FixSuggestion{ |
| 38 | + NewText: fmt.Sprintf("%d", sampleIndex), |
| 39 | + StartPosition: cd.MainError.Nearest.StartPosition(), |
| 40 | + EndPosition: cd.MainError.Nearest.EndPosition(), |
| 41 | + Description: "This adjustment ensures that you're accessing an index that exists within the array bounds, preventing the `ArrayIndexOutOfBoundsException`.", |
| 42 | + }) |
| 43 | + }) |
| 44 | + }, |
| 45 | +} |
0 commit comments