Skip to content

Commit 882a05a

Browse files
committed
[Format] Fix crash when hitting eof while lexing JS template string
Different loop termination conditions resulted in confusion of whether *Offset was intended to be inside or outside the token. This ultimately led to constructing an out-of-range SourceLocation. Fix by making Offset consistently point *after* the token. Differential Revision: https://reviews.llvm.org/D135356
1 parent d89d45c commit 882a05a

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

clang/lib/Format/FormatTokenLexer.cpp

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -760,6 +760,7 @@ void FormatTokenLexer::handleTemplateStrings() {
760760
for (; Offset != Lex->getBuffer().end(); ++Offset) {
761761
if (Offset[0] == '`') {
762762
StateStack.pop();
763+
++Offset;
763764
break;
764765
}
765766
if (Offset[0] == '\\') {
@@ -768,12 +769,12 @@ void FormatTokenLexer::handleTemplateStrings() {
768769
Offset[1] == '{') {
769770
// '${' introduces an expression interpolation in the template string.
770771
StateStack.push(LexerState::NORMAL);
771-
++Offset;
772+
Offset += 2;
772773
break;
773774
}
774775
}
775776

776-
StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
777+
StringRef LiteralText(TmplBegin, Offset - TmplBegin);
777778
BacktickToken->setType(TT_TemplateString);
778779
BacktickToken->Tok.setKind(tok::string_literal);
779780
BacktickToken->TokenText = LiteralText;
@@ -794,9 +795,7 @@ void FormatTokenLexer::handleTemplateStrings() {
794795
StartColumn, Style.TabWidth, Encoding);
795796
}
796797

797-
SourceLocation loc = Offset < Lex->getBuffer().end()
798-
? Lex->getSourceLocation(Offset + 1)
799-
: SourceMgr.getLocForEndOfFile(ID);
798+
SourceLocation loc = Lex->getSourceLocation(Offset);
800799
resetLexer(SourceMgr.getFileOffset(loc));
801800
}
802801

clang/unittests/Format/FormatTestJS.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2145,6 +2145,8 @@ TEST_F(FormatTestJS, NestedTemplateStrings) {
21452145

21462146
// Crashed at some point.
21472147
verifyFormat("}");
2148+
verifyFormat("`");
2149+
verifyFormat("`\\");
21482150
}
21492151

21502152
TEST_F(FormatTestJS, TaggedTemplateStrings) {

0 commit comments

Comments
 (0)