Skip to content

Commit 2d4c8e6

Browse files
andrea.bergiagbrail
authored andcommitted
Fixed an off-by-one error in the lexer when encountering EOF
Fixes mozilla#2151
1 parent b516c50 commit 2d4c8e6

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

rhino/src/main/java/org/mozilla/javascript/TokenStream.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2261,8 +2261,18 @@ private void skipLine() throws IOException {
22612261
// skip to end of line
22622262
int c;
22632263
while ((c = getChar()) != EOF_CHAR && c != '\n') {}
2264-
ungetChar(c);
2265-
tokenEnd = cursor;
2264+
if (c == EOF_CHAR) {
2265+
// If we've hit EOF, the cursor hasn't been incremented, so we need to save tokenEnd
2266+
// _before_ ungetChar
2267+
tokenEnd = cursor;
2268+
ungetChar(c);
2269+
} else {
2270+
// If we've hit a newline, the cursor has been incremented past it, and ungetChar will
2271+
// point at the newline, so saving tokenEnd after ungetChar will correctly exclude the
2272+
// newline
2273+
ungetChar(c);
2274+
tokenEnd = cursor;
2275+
}
22662276
}
22672277

22682278
/** Returns the offset into the current line. */

tests/src/test/java/org/mozilla/javascript/tests/ParserTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1498,6 +1498,18 @@ public void errorOnInvalidDestructuringDeclaration() {
14981498
new String[] {"Missing = in destructuring declaration", "syntax error"});
14991499
}
15001500

1501+
@Test
1502+
public void commentValueIsNotTruncatedBecauseOfEof() {
1503+
String source = "// comment";
1504+
1505+
AstRoot root = parse(source);
1506+
assertNotNull(root.getComments());
1507+
assertEquals(1, root.getComments().size());
1508+
Comment comment = root.getComments().first();
1509+
assertEquals(source, comment.getValue());
1510+
assertEquals(10, comment.getLength());
1511+
}
1512+
15011513
private void expectParseErrors(String string, String[] errors) {
15021514
parse(string, errors, null, false);
15031515
}

0 commit comments

Comments
 (0)