Fix index out of bounds
exception in rescript-editor-analysis codeAction
#7523
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When editing switch statements in VS Code, I've sometimes been seeing error messages of the form
rescript-editor-analysis codeAction MyFile.res 42 0 42 0 /tmp/xxx.res failed with Fatal error: exception Invalid_argument("index out of bounds")
.(Since the temporary files generated by the extension were deleted as soon as this command failed, I could not come up with a simple repo. However, by hitting backspace quickly on the first line of switch statements, I was sometimes able to reproduce this error.)
After enabling backtraces with
Printexc.record_backtrace true
, I managed to track this down to line 376 ofCompletionFrontEnd.completionWithParser1
:rescript/analysis/src/CompletionFrontEnd.ml
Line 376 in 6f4275c
While we're ensuring that
offset < String.length text
, there was no check thatoffset >= 0
and sotext.[-1]
triggered an index out of bounds exception.I'm not sure exactly why
offset
was negative, but I'm guessing it's becauseloc_start.pos_cnum
is initialised as -1 and soPos.positionToOffset
is called with args"..." (line, -1)
.rescript/analysis/src/Xform.ml
Lines 7 to 9 in 6f4275c
rescript/analysis/src/Pos.ml
Lines 3 to 4 in 6f4275c
rescript/analysis/src/Pos.ml
Lines 21 to 26 in 6f4275c
rescript/analysis/src/CompletionFrontEnd.ml
Lines 1755 to 1757 in 6f4275c
In addition to adding bounds checks before using
offset
forcharAtCursor
, I've also added them for some offset-related logic further down.I've also fixed the root of the issue by ensuring that
Pos.positionToOffset
does not return negative offsets.