Skip to content

Commit 653aa67

Browse files
authored
Merge pull request #177 from Philippus/fix-regression
Take into account leading and trailing line endings
2 parents 09c453a + c873dc4 commit 653aa67

File tree

2 files changed

+44
-9
lines changed

2 files changed

+44
-9
lines changed

shared/src/main/scala/scala/util/parsing/input/OffsetPosition.scala

+7-8
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,13 @@ case class OffsetPosition(source: CharSequence, offset: Int) extends Position {
3434

3535
private def genIndex: Array[Int] = {
3636
val lineStarts = new ArrayBuffer[Int]
37-
lineStarts += 0 // first line
38-
for (i <- 1 until source.length) {
39-
if (source.charAt(i - 1) == '\n') // \n or \r\n
40-
lineStarts += i
41-
else if (source.charAt(i - 1) == '\r' && source.charAt(i) != '\n') // \r but not \r\n
42-
lineStarts += i
43-
}
44-
lineStarts += source.length // eof
37+
lineStarts += 0
38+
for (i <- 0 until source.length)
39+
if (source.charAt(i) == '\n' ||
40+
(source.charAt(i) == '\r' && (i == (source.length - 1) || source.charAt(i + 1) != '\n'))) {
41+
lineStarts += (i + 1)
42+
}
43+
lineStarts += source.length
4544
lineStarts.toArray
4645
}
4746

shared/src/test/scala/scala/util/parsing/input/OffsetPositionTest.scala

+37-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class OffsetPositionTest {
1818

1919
@Test
2020
def lineContentsWithTrailingCRLF: Unit = {
21-
val op = new OffsetPosition("\r\n", 1)
21+
val op = new OffsetPosition("\r\n", 2)
2222
assertEquals("", op.lineContents)
2323
}
2424

@@ -45,4 +45,40 @@ class OffsetPositionTest {
4545
val op = new OffsetPosition("foo\r\nbar", 5)
4646
assertEquals(2, op.line)
4747
}
48+
49+
@Test
50+
def linesWithTrailingLFs: Unit = {
51+
val op = new OffsetPosition("foo\n\n", 5)
52+
assertEquals(3, op.line)
53+
}
54+
55+
@Test
56+
def linesWithTrailingCRs: Unit = {
57+
val op = new OffsetPosition("foo\r\r", 5)
58+
assertEquals(3, op.line)
59+
}
60+
61+
@Test
62+
def linesWithTrailingCRLFs: Unit = {
63+
val op = new OffsetPosition("foo\r\n\r\n", 7)
64+
assertEquals(3, op.line)
65+
}
66+
67+
@Test
68+
def linesWithLeadingLF: Unit = {
69+
val op = new OffsetPosition("\n", 1)
70+
assertEquals(2, op.line)
71+
}
72+
73+
@Test
74+
def linesWithLeadingCR: Unit = {
75+
val op = new OffsetPosition("\r", 1)
76+
assertEquals(2, op.line)
77+
}
78+
79+
@Test
80+
def linesWithLeadingCRLF: Unit = {
81+
val op = new OffsetPosition("\r\n", 2)
82+
assertEquals(2, op.line)
83+
}
4884
}

0 commit comments

Comments
 (0)