Skip to content
This repository was archived by the owner on Nov 1, 2021. It is now read-only.

Commit 3506666

Browse files
committed
clang-format: [JS] Properly set scopes inside template strings.
Before: var f = `aaaaaaaaaaaaa:${aaaaaaa .aaaaa} aaaaaaaa aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`; After: var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`; git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@293622 91177308-0d34-0410-b5e6-96231b3b80d8
1 parent 815735e commit 3506666

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

lib/Format/FormatToken.h

+4
Original file line numberDiff line numberDiff line change
@@ -337,11 +337,15 @@ struct FormatToken {
337337

338338
/// \brief Returns whether \p Tok is ([{ or a template opening <.
339339
bool opensScope() const {
340+
if (is(TT_TemplateString) && TokenText.endswith("${"))
341+
return true;
340342
return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
341343
TT_TemplateOpener);
342344
}
343345
/// \brief Returns whether \p Tok is )]} or a template closing >.
344346
bool closesScope() const {
347+
if (is(TT_TemplateString) && TokenText.startswith("}"))
348+
return true;
345349
return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
346350
TT_TemplateCloser);
347351
}

lib/Format/TokenAnnotator.cpp

+3-1
Original file line numberDiff line numberDiff line change
@@ -1454,7 +1454,9 @@ class ExpressionParser {
14541454

14551455
// Consume scopes: (), [], <> and {}
14561456
if (Current->opensScope()) {
1457-
while (Current && !Current->closesScope()) {
1457+
// In fragment of a JavaScript template string can look like '}..${' and
1458+
// thus close a scope and open a new one at the same time.
1459+
while (Current && (!Current->closesScope() || Current->opensScope())) {
14581460
next();
14591461
parse();
14601462
}

unittests/Format/FormatTestJS.cpp

+7
Original file line numberDiff line numberDiff line change
@@ -1392,6 +1392,13 @@ TEST_F(FormatTestJS, TemplateStrings) {
13921392
// The token stream can contain two string_literals in sequence, but that
13931393
// doesn't mean that they are implicitly concatenated in JavaScript.
13941394
verifyFormat("var f = `aaaa ${a ? 'a' : 'b'}`;");
1395+
1396+
// Ensure that scopes are appropriately set around evaluated expressions in
1397+
// template strings.
1398+
verifyFormat("var f = `aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa\n"
1399+
" aaaaaaaaaaaaa:${aaaaaaa.aaaaa} aaaaaaaa`;",
1400+
"var f = `aaaaaaaaaaaaa:${aaaaaaa. aaaaa} aaaaaaaa\n"
1401+
" aaaaaaaaaaaaa:${ aaaaaaa. aaaaa} aaaaaaaa`;");
13951402
}
13961403

13971404
TEST_F(FormatTestJS, TemplateStringASI) {

0 commit comments

Comments
 (0)