Skip to content

Commit 16212b8

Browse files
committed
clang-format: [JS] support new assignment operators.
Before: a && = b; After: a &&= b; These operators are new additions in ES2021. Differential Revision: https://reviews.llvm.org/D91132
1 parent 25755a0 commit 16212b8

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

clang/lib/Format/FormatToken.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,9 @@ namespace format {
6868
TYPE(JsTypeColon) \
6969
TYPE(JsTypeOperator) \
7070
TYPE(JsTypeOptionalQuestion) \
71+
TYPE(JsAndAndEqual) \
72+
TYPE(JsPipePipeEqual) \
73+
TYPE(JsNullishCoalescingEqual) \
7174
TYPE(LambdaArrow) \
7275
TYPE(LambdaLBrace) \
7376
TYPE(LambdaLSquare) \

clang/lib/Format/FormatTokenLexer.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,10 @@ void FormatTokenLexer::tryMergePreviousTokens() {
121121
tok::period};
122122
static const tok::TokenKind JSNullishOperator[] = {tok::question,
123123
tok::question};
124+
static const tok::TokenKind JSNullishEqual[] = {tok::question,
125+
tok::question, tok::equal};
126+
static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
127+
static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
124128

125129
// FIXME: Investigate what token type gives the correct operator priority.
126130
if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
@@ -148,6 +152,13 @@ void FormatTokenLexer::tryMergePreviousTokens() {
148152
Tokens.back()->Tok.setKind(tok::period);
149153
return;
150154
}
155+
if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
156+
tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual) ||
157+
tryMergeTokens(JSNullishEqual, TT_JsNullishCoalescingEqual)) {
158+
// Treat like the "=" assignment operator.
159+
Tokens.back()->Tok.setKind(tok::equal);
160+
return;
161+
}
151162
if (tryMergeJSPrivateIdentifier())
152163
return;
153164
}

clang/unittests/Format/FormatTestJS.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2424,6 +2424,15 @@ TEST_F(FormatTestJS, NullishCoalescingOperator) {
24242424
getGoogleJSStyleWithColumns(40));
24252425
}
24262426

2427+
TEST_F(FormatTestJS, AssignmentOperators) {
2428+
verifyFormat("a &&= b;\n");
2429+
verifyFormat("a ||= b;\n");
2430+
// NB: need to split ? ?= to avoid it being interpreted by C++ as a trigraph
2431+
// for #.
2432+
verifyFormat("a ?"
2433+
"?= b;\n");
2434+
}
2435+
24272436
TEST_F(FormatTestJS, Conditional) {
24282437
verifyFormat("y = x ? 1 : 2;");
24292438
verifyFormat("x ? 1 : 2;");

0 commit comments

Comments
 (0)