Skip to content

IDE: Guard against out of bounds positions in requests #5991

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions compiler/src/dotty/tools/dotc/util/SourceFile.scala
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ class SourceFile(val file: AbstractFile, computeContent: => Array[Char]) extends
/** Map line to offset of first character in line */
def lineToOffset(index: Int): Int = lineIndices(index)

/** Like `lineToOffset`, but doesn't crash if the index is out of bounds. */
def lineToOffsetOpt(index: Int): Option[Int] =
if (index < 0 || index >= lineIndices.length)
None
else
Some(lineToOffset(index))

/** A cache to speed up offsetToLine searches to similar lines */
private[this] var lastLine = 0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -651,10 +651,15 @@ object DottyLanguageServer {
if (isWorksheet(uri)) toWrappedPosition(pos)
else pos
val source = driver.openedFiles(uri)
if (source.exists) {
val p = Spans.Span(source.lineToOffset(actualPosition.getLine) + actualPosition.getCharacter)
new SourcePosition(source, p)
}
if (source.exists)
source.lineToOffsetOpt(actualPosition.getLine).map(_ + actualPosition.getCharacter) match {
// `<=` to allow an offset to point to the end of the file
case Some(offset) if offset <= source.content().length =>
val p = Spans.Span(offset)
new SourcePosition(source, p)
case _ =>
NoSourcePosition
}
else NoSourcePosition
}

Expand Down