Bug Summary

File:tools/clang/lib/Format/TokenAnnotator.cpp
Warning:line 1139, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name TokenAnnotator.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/Format -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Format -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/Format -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Format/TokenAnnotator.cpp -faddrsig
1//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a token annotator, i.e. creates
11/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
12///
13//===----------------------------------------------------------------------===//
14
15#include "TokenAnnotator.h"
16#include "FormatToken.h"
17#include "clang/Basic/SourceManager.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/Support/Debug.h"
20
21#define DEBUG_TYPE"format-token-annotator" "format-token-annotator"
22
23namespace clang {
24namespace format {
25
26namespace {
27
28/// Returns \c true if the token can be used as an identifier in
29/// an Objective-C \c @selector, \c false otherwise.
30///
31/// Because getFormattingLangOpts() always lexes source code as
32/// Objective-C++, C++ keywords like \c new and \c delete are
33/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
34///
35/// For Objective-C and Objective-C++, both identifiers and keywords
36/// are valid inside @selector(...) (or a macro which
37/// invokes @selector(...)). So, we allow treat any identifier or
38/// keyword as a potential Objective-C selector component.
39static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
40 return Tok.Tok.getIdentifierInfo() != nullptr;
41}
42
43/// A parser that gathers additional information about tokens.
44///
45/// The \c TokenAnnotator tries to match parenthesis and square brakets and
46/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
47/// into template parameter lists.
48class AnnotatingParser {
49public:
50 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
51 const AdditionalKeywords &Keywords)
52 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
53 Keywords(Keywords) {
54 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
55 resetTokenMetadata(CurrentToken);
56 }
57
58private:
59 bool parseAngle() {
60 if (!CurrentToken || !CurrentToken->Previous)
61 return false;
62 if (NonTemplateLess.count(CurrentToken->Previous))
63 return false;
64
65 const FormatToken &Previous = *CurrentToken->Previous; // The '<'.
66 if (Previous.Previous) {
67 if (Previous.Previous->Tok.isLiteral())
68 return false;
69 if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
70 (!Previous.Previous->MatchingParen ||
71 !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
72 return false;
73 }
74
75 FormatToken *Left = CurrentToken->Previous;
76 Left->ParentBracket = Contexts.back().ContextKind;
77 ScopedContextCreator ContextCreator(*this, tok::less, 12);
78
79 // If this angle is in the context of an expression, we need to be more
80 // hesitant to detect it as opening template parameters.
81 bool InExprContext = Contexts.back().IsExpression;
82
83 Contexts.back().IsExpression = false;
84 // If there's a template keyword before the opening angle bracket, this is a
85 // template parameter, not an argument.
86 Contexts.back().InTemplateArgument =
87 Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
88
89 if (Style.Language == FormatStyle::LK_Java &&
90 CurrentToken->is(tok::question))
91 next();
92
93 while (CurrentToken) {
94 if (CurrentToken->is(tok::greater)) {
95 Left->MatchingParen = CurrentToken;
96 CurrentToken->MatchingParen = Left;
97 // In TT_Proto, we must distignuish between:
98 // map<key, value>
99 // msg < item: data >
100 // msg: < item: data >
101 // In TT_TextProto, map<key, value> does not occur.
102 if (Style.Language == FormatStyle::LK_TextProto ||
103 (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
104 Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
105 CurrentToken->Type = TT_DictLiteral;
106 else
107 CurrentToken->Type = TT_TemplateCloser;
108 next();
109 return true;
110 }
111 if (CurrentToken->is(tok::question) &&
112 Style.Language == FormatStyle::LK_Java) {
113 next();
114 continue;
115 }
116 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
117 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
118 Style.Language != FormatStyle::LK_Proto &&
119 Style.Language != FormatStyle::LK_TextProto))
120 return false;
121 // If a && or || is found and interpreted as a binary operator, this set
122 // of angles is likely part of something like "a < b && c > d". If the
123 // angles are inside an expression, the ||/&& might also be a binary
124 // operator that was misinterpreted because we are parsing template
125 // parameters.
126 // FIXME: This is getting out of hand, write a decent parser.
127 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
128 CurrentToken->Previous->is(TT_BinaryOperator) &&
129 Contexts[Contexts.size() - 2].IsExpression &&
130 !Line.startsWith(tok::kw_template))
131 return false;
132 updateParameterCount(Left, CurrentToken);
133 if (Style.Language == FormatStyle::LK_Proto) {
134 if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
135 if (CurrentToken->is(tok::colon) ||
136 (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
137 Previous->isNot(tok::colon)))
138 Previous->Type = TT_SelectorName;
139 }
140 }
141 if (!consumeToken())
142 return false;
143 }
144 return false;
145 }
146
147 bool parseParens(bool LookForDecls = false) {
148 if (!CurrentToken)
149 return false;
150 FormatToken *Left = CurrentToken->Previous;
151 Left->ParentBracket = Contexts.back().ContextKind;
152 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
153
154 // FIXME: This is a bit of a hack. Do better.
155 Contexts.back().ColonIsForRangeExpr =
156 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
157
158 bool StartsObjCMethodExpr = false;
159 if (FormatToken *MaybeSel = Left->Previous) {
160 // @selector( starts a selector.
161 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
162 MaybeSel->Previous->is(tok::at)) {
163 StartsObjCMethodExpr = true;
164 }
165 }
166
167 if (Left->is(TT_OverloadedOperatorLParen)) {
168 Contexts.back().IsExpression = false;
169 } else if (Style.Language == FormatStyle::LK_JavaScript &&
170 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
171 Line.startsWith(tok::kw_export, Keywords.kw_type,
172 tok::identifier))) {
173 // type X = (...);
174 // export type X = (...);
175 Contexts.back().IsExpression = false;
176 } else if (Left->Previous &&
177 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
178 tok::kw_if, tok::kw_while, tok::l_paren,
179 tok::comma) ||
180 Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
181 Left->Previous->is(TT_BinaryOperator))) {
182 // static_assert, if and while usually contain expressions.
183 Contexts.back().IsExpression = true;
184 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
185 (Left->Previous->is(Keywords.kw_function) ||
186 (Left->Previous->endsSequence(tok::identifier,
187 Keywords.kw_function)))) {
188 // function(...) or function f(...)
189 Contexts.back().IsExpression = false;
190 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
191 Left->Previous->is(TT_JsTypeColon)) {
192 // let x: (SomeType);
193 Contexts.back().IsExpression = false;
194 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
195 Left->Previous->MatchingParen &&
196 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
197 // This is a parameter list of a lambda expression.
198 Contexts.back().IsExpression = false;
199 } else if (Line.InPPDirective &&
200 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
201 Contexts.back().IsExpression = true;
202 } else if (Contexts[Contexts.size() - 2].CaretFound) {
203 // This is the parameter list of an ObjC block.
204 Contexts.back().IsExpression = false;
205 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
206 Left->Type = TT_AttributeParen;
207 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
208 // The first argument to a foreach macro is a declaration.
209 Contexts.back().IsForEachMacro = true;
210 Contexts.back().IsExpression = false;
211 } else if (Left->Previous && Left->Previous->MatchingParen &&
212 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
213 Contexts.back().IsExpression = false;
214 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
215 bool IsForOrCatch =
216 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
217 Contexts.back().IsExpression = !IsForOrCatch;
218 }
219
220 if (StartsObjCMethodExpr) {
221 Contexts.back().ColonIsObjCMethodExpr = true;
222 Left->Type = TT_ObjCMethodExpr;
223 }
224
225 // MightBeFunctionType and ProbablyFunctionType are used for
226 // function pointer and reference types as well as Objective-C
227 // block types:
228 //
229 // void (*FunctionPointer)(void);
230 // void (&FunctionReference)(void);
231 // void (^ObjCBlock)(void);
232 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
233 bool ProbablyFunctionType =
234 CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
235 bool HasMultipleLines = false;
236 bool HasMultipleParametersOnALine = false;
237 bool MightBeObjCForRangeLoop =
238 Left->Previous && Left->Previous->is(tok::kw_for);
239 FormatToken *PossibleObjCForInToken = nullptr;
240 while (CurrentToken) {
241 // LookForDecls is set when "if (" has been seen. Check for
242 // 'identifier' '*' 'identifier' followed by not '=' -- this
243 // '*' has to be a binary operator but determineStarAmpUsage() will
244 // categorize it as an unary operator, so set the right type here.
245 if (LookForDecls && CurrentToken->Next) {
246 FormatToken *Prev = CurrentToken->getPreviousNonComment();
247 if (Prev) {
248 FormatToken *PrevPrev = Prev->getPreviousNonComment();
249 FormatToken *Next = CurrentToken->Next;
250 if (PrevPrev && PrevPrev->is(tok::identifier) &&
251 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
252 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
253 Prev->Type = TT_BinaryOperator;
254 LookForDecls = false;
255 }
256 }
257 }
258
259 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
260 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
261 tok::coloncolon))
262 ProbablyFunctionType = true;
263 if (CurrentToken->is(tok::comma))
264 MightBeFunctionType = false;
265 if (CurrentToken->Previous->is(TT_BinaryOperator))
266 Contexts.back().IsExpression = true;
267 if (CurrentToken->is(tok::r_paren)) {
268 if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
269 (CurrentToken->Next->is(tok::l_paren) ||
270 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
271 Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
272 : TT_FunctionTypeLParen;
273 Left->MatchingParen = CurrentToken;
274 CurrentToken->MatchingParen = Left;
275
276 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
277 Left->Previous && Left->Previous->is(tok::l_paren)) {
278 // Detect the case where macros are used to generate lambdas or
279 // function bodies, e.g.:
280 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
281 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
282 if (Tok->is(TT_BinaryOperator) &&
283 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
284 Tok->Type = TT_PointerOrReference;
285 }
286 }
287
288 if (StartsObjCMethodExpr) {
289 CurrentToken->Type = TT_ObjCMethodExpr;
290 if (Contexts.back().FirstObjCSelectorName) {
291 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
292 Contexts.back().LongestObjCSelectorName;
293 }
294 }
295
296 if (Left->is(TT_AttributeParen))
297 CurrentToken->Type = TT_AttributeParen;
298 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
299 CurrentToken->Type = TT_JavaAnnotation;
300 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
301 CurrentToken->Type = TT_LeadingJavaAnnotation;
302 if (Left->Previous && Left->Previous->is(TT_AttributeSquare))
303 CurrentToken->Type = TT_AttributeSquare;
304
305 if (!HasMultipleLines)
306 Left->PackingKind = PPK_Inconclusive;
307 else if (HasMultipleParametersOnALine)
308 Left->PackingKind = PPK_BinPacked;
309 else
310 Left->PackingKind = PPK_OnePerLine;
311
312 next();
313 return true;
314 }
315 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
316 return false;
317
318 if (CurrentToken->is(tok::l_brace))
319 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
320 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
321 !CurrentToken->Next->HasUnescapedNewline &&
322 !CurrentToken->Next->isTrailingComment())
323 HasMultipleParametersOnALine = true;
324 if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
325 CurrentToken->Previous->isSimpleTypeSpecifier()) &&
326 !CurrentToken->is(tok::l_brace))
327 Contexts.back().IsExpression = false;
328 if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
329 MightBeObjCForRangeLoop = false;
330 if (PossibleObjCForInToken) {
331 PossibleObjCForInToken->Type = TT_Unknown;
332 PossibleObjCForInToken = nullptr;
333 }
334 }
335 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
336 PossibleObjCForInToken = CurrentToken;
337 PossibleObjCForInToken->Type = TT_ObjCForIn;
338 }
339 // When we discover a 'new', we set CanBeExpression to 'false' in order to
340 // parse the type correctly. Reset that after a comma.
341 if (CurrentToken->is(tok::comma))
342 Contexts.back().CanBeExpression = true;
343
344 FormatToken *Tok = CurrentToken;
345 if (!consumeToken())
346 return false;
347 updateParameterCount(Left, Tok);
348 if (CurrentToken && CurrentToken->HasUnescapedNewline)
349 HasMultipleLines = true;
350 }
351 return false;
352 }
353
354 bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
355 if (!Style.isCSharp())
356 return false;
357
358 const FormatToken *AttrTok = Tok.Next;
359 if (!AttrTok)
360 return false;
361
362 // Just an empty declaration e.g. string [].
363 if (AttrTok->is(tok::r_square))
364 return false;
365
366 // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
367 while (AttrTok && AttrTok->isNot(tok::r_square)) {
368 AttrTok = AttrTok->Next;
369 }
370
371 if (!AttrTok)
372 return false;
373
374 // Move past the end of ']'.
375 AttrTok = AttrTok->Next;
376 if (!AttrTok)
377 return false;
378
379 // Limit this to being an access modifier that follows.
380 if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
381 tok::kw_class, tok::kw_static, tok::l_square,
382 Keywords.kw_internal)) {
383 return true;
384 }
385 return false;
386 }
387
388 bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
389 if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
390 return false;
391 const FormatToken *AttrTok = Tok.Next->Next;
392 if (!AttrTok)
393 return false;
394 // C++17 '[[using ns: foo, bar(baz, blech)]]'
395 // We assume nobody will name an ObjC variable 'using'.
396 if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
397 return true;
398 if (AttrTok->isNot(tok::identifier))
399 return false;
400 while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
401 // ObjC message send. We assume nobody will use : in a C++11 attribute
402 // specifier parameter, although this is technically valid:
403 // [[foo(:)]]
404 if (AttrTok->is(tok::colon) ||
405 AttrTok->startsSequence(tok::identifier, tok::identifier) ||
406 AttrTok->startsSequence(tok::r_paren, tok::identifier))
407 return false;
408 if (AttrTok->is(tok::ellipsis))
409 return true;
410 AttrTok = AttrTok->Next;
411 }
412 return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
413 }
414
415 bool parseSquare() {
416 if (!CurrentToken)
417 return false;
418
419 // A '[' could be an index subscript (after an identifier or after
420 // ')' or ']'), it could be the start of an Objective-C method
421 // expression, it could the start of an Objective-C array literal,
422 // or it could be a C++ attribute specifier [[foo::bar]].
423 FormatToken *Left = CurrentToken->Previous;
424 Left->ParentBracket = Contexts.back().ContextKind;
425 FormatToken *Parent = Left->getPreviousNonComment();
426
427 // Cases where '>' is followed by '['.
428 // In C++, this can happen either in array of templates (foo<int>[10])
429 // or when array is a nested template type (unique_ptr<type1<type2>[]>).
430 bool CppArrayTemplates =
431 Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
432 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
433 Contexts.back().InTemplateArgument);
434
435 bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
436 Contexts.back().InCpp11AttributeSpecifier;
437
438 // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
439 bool IsCSharp11AttributeSpecifier =
440 isCSharpAttributeSpecifier(*Left) ||
441 Contexts.back().InCSharpAttributeSpecifier;
442
443 bool InsideInlineASM = Line.startsWith(tok::kw_asm);
444 bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
445 bool StartsObjCMethodExpr =
446 !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
447 Style.isCpp() && !IsCpp11AttributeSpecifier &&
448 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
449 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
450 (!Parent ||
451 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
452 tok::kw_return, tok::kw_throw) ||
453 Parent->isUnaryOperator() ||
454 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
455 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
456 (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
457 prec::Unknown));
458 bool ColonFound = false;
459
460 unsigned BindingIncrease = 1;
461 if (IsCppStructuredBinding) {
462 Left->Type = TT_StructuredBindingLSquare;
463 } else if (Left->is(TT_Unknown)) {
464 if (StartsObjCMethodExpr) {
465 Left->Type = TT_ObjCMethodExpr;
466 } else if (IsCpp11AttributeSpecifier) {
467 Left->Type = TT_AttributeSquare;
468 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
469 Contexts.back().ContextKind == tok::l_brace &&
470 Parent->isOneOf(tok::l_brace, tok::comma)) {
471 Left->Type = TT_JsComputedPropertyName;
472 } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
473 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
474 Left->Type = TT_DesignatedInitializerLSquare;
475 } else if (CurrentToken->is(tok::r_square) && Parent &&
476 Parent->is(TT_TemplateCloser)) {
477 Left->Type = TT_ArraySubscriptLSquare;
478 } else if (Style.Language == FormatStyle::LK_Proto ||
479 Style.Language == FormatStyle::LK_TextProto) {
480 // Square braces in LK_Proto can either be message field attributes:
481 //
482 // optional Aaa aaa = 1 [
483 // (aaa) = aaa
484 // ];
485 //
486 // extensions 123 [
487 // (aaa) = aaa
488 // ];
489 //
490 // or text proto extensions (in options):
491 //
492 // option (Aaa.options) = {
493 // [type.type/type] {
494 // key: value
495 // }
496 // }
497 //
498 // or repeated fields (in options):
499 //
500 // option (Aaa.options) = {
501 // keys: [ 1, 2, 3 ]
502 // }
503 //
504 // In the first and the third case we want to spread the contents inside
505 // the square braces; in the second we want to keep them inline.
506 Left->Type = TT_ArrayInitializerLSquare;
507 if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
508 tok::equal) &&
509 !Left->endsSequence(tok::l_square, tok::numeric_constant,
510 tok::identifier) &&
511 !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
512 Left->Type = TT_ProtoExtensionLSquare;
513 BindingIncrease = 10;
514 }
515 } else if (!CppArrayTemplates && Parent &&
516 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
517 tok::comma, tok::l_paren, tok::l_square,
518 tok::question, tok::colon, tok::kw_return,
519 // Should only be relevant to JavaScript:
520 tok::kw_default)) {
521 Left->Type = TT_ArrayInitializerLSquare;
522 } else if (IsCSharp11AttributeSpecifier) {
523 Left->Type = TT_AttributeSquare;
524 } else {
525 BindingIncrease = 10;
526 Left->Type = TT_ArraySubscriptLSquare;
527 }
528 }
529
530 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
531 Contexts.back().IsExpression = true;
532 if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
533 Parent->is(TT_JsTypeColon))
534 Contexts.back().IsExpression = false;
535
536 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
537 Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
538 Contexts.back().InCSharpAttributeSpecifier = IsCSharp11AttributeSpecifier;
539
540 while (CurrentToken) {
541 if (CurrentToken->is(tok::r_square)) {
542 if (IsCpp11AttributeSpecifier)
543 CurrentToken->Type = TT_AttributeSquare;
544 if (IsCSharp11AttributeSpecifier)
545 CurrentToken->Type = TT_AttributeSquare;
546 else if (((CurrentToken->Next &&
547 CurrentToken->Next->is(tok::l_paren)) ||
548 (CurrentToken->Previous &&
549 CurrentToken->Previous->Previous == Left)) &&
550 Left->is(TT_ObjCMethodExpr)) {
551 // An ObjC method call is rarely followed by an open parenthesis. It
552 // also can't be composed of just one token, unless it's a macro that
553 // will be expanded to more tokens.
554 // FIXME: Do we incorrectly label ":" with this?
555 StartsObjCMethodExpr = false;
556 Left->Type = TT_Unknown;
557 }
558 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
559 CurrentToken->Type = TT_ObjCMethodExpr;
560 // If we haven't seen a colon yet, make sure the last identifier
561 // before the r_square is tagged as a selector name component.
562 if (!ColonFound && CurrentToken->Previous &&
563 CurrentToken->Previous->is(TT_Unknown) &&
564 canBeObjCSelectorComponent(*CurrentToken->Previous))
565 CurrentToken->Previous->Type = TT_SelectorName;
566 // determineStarAmpUsage() thinks that '*' '[' is allocating an
567 // array of pointers, but if '[' starts a selector then '*' is a
568 // binary operator.
569 if (Parent && Parent->is(TT_PointerOrReference))
570 Parent->Type = TT_BinaryOperator;
571 }
572 // An arrow after an ObjC method expression is not a lambda arrow.
573 if (CurrentToken->Type == TT_ObjCMethodExpr && CurrentToken->Next &&
574 CurrentToken->Next->is(TT_LambdaArrow))
575 CurrentToken->Next->Type = TT_Unknown;
576 Left->MatchingParen = CurrentToken;
577 CurrentToken->MatchingParen = Left;
578 // FirstObjCSelectorName is set when a colon is found. This does
579 // not work, however, when the method has no parameters.
580 // Here, we set FirstObjCSelectorName when the end of the method call is
581 // reached, in case it was not set already.
582 if (!Contexts.back().FirstObjCSelectorName) {
583 FormatToken *Previous = CurrentToken->getPreviousNonComment();
584 if (Previous && Previous->is(TT_SelectorName)) {
585 Previous->ObjCSelectorNameParts = 1;
586 Contexts.back().FirstObjCSelectorName = Previous;
587 }
588 } else {
589 Left->ParameterCount =
590 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
591 }
592 if (Contexts.back().FirstObjCSelectorName) {
593 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
594 Contexts.back().LongestObjCSelectorName;
595 if (Left->BlockParameterCount > 1)
596 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
597 }
598 next();
599 return true;
600 }
601 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
602 return false;
603 if (CurrentToken->is(tok::colon)) {
604 if (IsCpp11AttributeSpecifier &&
605 CurrentToken->endsSequence(tok::colon, tok::identifier,
606 tok::kw_using)) {
607 // Remember that this is a [[using ns: foo]] C++ attribute, so we
608 // don't add a space before the colon (unlike other colons).
609 CurrentToken->Type = TT_AttributeColon;
610 } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
611 TT_DesignatedInitializerLSquare)) {
612 Left->Type = TT_ObjCMethodExpr;
613 StartsObjCMethodExpr = true;
614 Contexts.back().ColonIsObjCMethodExpr = true;
615 if (Parent && Parent->is(tok::r_paren))
616 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
617 Parent->Type = TT_CastRParen;
618 }
619 ColonFound = true;
620 }
621 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
622 !ColonFound)
623 Left->Type = TT_ArrayInitializerLSquare;
624 FormatToken *Tok = CurrentToken;
625 if (!consumeToken())
626 return false;
627 updateParameterCount(Left, Tok);
628 }
629 return false;
630 }
631
632 bool parseBrace() {
633 if (CurrentToken) {
634 FormatToken *Left = CurrentToken->Previous;
635 Left->ParentBracket = Contexts.back().ContextKind;
636
637 if (Contexts.back().CaretFound)
638 Left->Type = TT_ObjCBlockLBrace;
639 Contexts.back().CaretFound = false;
640
641 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
642 Contexts.back().ColonIsDictLiteral = true;
643 if (Left->BlockKind == BK_BracedInit)
644 Contexts.back().IsExpression = true;
645 if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
646 Left->Previous->is(TT_JsTypeColon))
647 Contexts.back().IsExpression = false;
648
649 while (CurrentToken) {
650 if (CurrentToken->is(tok::r_brace)) {
651 Left->MatchingParen = CurrentToken;
652 CurrentToken->MatchingParen = Left;
653 next();
654 return true;
655 }
656 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
657 return false;
658 updateParameterCount(Left, CurrentToken);
659 if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
660 FormatToken *Previous = CurrentToken->getPreviousNonComment();
661 if (Previous->is(TT_JsTypeOptionalQuestion))
662 Previous = Previous->getPreviousNonComment();
663 if ((CurrentToken->is(tok::colon) &&
664 (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
665 Style.Language == FormatStyle::LK_Proto ||
666 Style.Language == FormatStyle::LK_TextProto) {
667 Left->Type = TT_DictLiteral;
668 if (Previous->Tok.getIdentifierInfo() ||
669 Previous->is(tok::string_literal))
670 Previous->Type = TT_SelectorName;
671 }
672 if (CurrentToken->is(tok::colon) ||
673 Style.Language == FormatStyle::LK_JavaScript)
674 Left->Type = TT_DictLiteral;
675 }
676 if (CurrentToken->is(tok::comma) &&
677 Style.Language == FormatStyle::LK_JavaScript)
678 Left->Type = TT_DictLiteral;
679 if (!consumeToken())
680 return false;
681 }
682 }
683 return true;
684 }
685
686 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
687 // For ObjC methods, the number of parameters is calculated differently as
688 // method declarations have a different structure (the parameters are not
689 // inside a bracket scope).
690 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
691 ++Left->BlockParameterCount;
692 if (Current->is(tok::comma)) {
693 ++Left->ParameterCount;
694 if (!Left->Role)
695 Left->Role.reset(new CommaSeparatedList(Style));
696 Left->Role->CommaFound(Current);
697 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
698 Left->ParameterCount = 1;
699 }
700 }
701
702 bool parseConditional() {
703 while (CurrentToken) {
704 if (CurrentToken->is(tok::colon)) {
705 CurrentToken->Type = TT_ConditionalExpr;
706 next();
707 return true;
708 }
709 if (!consumeToken())
710 return false;
711 }
712 return false;
713 }
714
715 bool parseTemplateDeclaration() {
716 if (CurrentToken && CurrentToken->is(tok::less)) {
717 CurrentToken->Type = TT_TemplateOpener;
718 next();
719 if (!parseAngle())
720 return false;
721 if (CurrentToken)
722 CurrentToken->Previous->ClosesTemplateDeclaration = true;
723 return true;
724 }
725 return false;
726 }
727
728 bool consumeToken() {
729 FormatToken *Tok = CurrentToken;
730 next();
731 switch (Tok->Tok.getKind()) {
732 case tok::plus:
733 case tok::minus:
734 if (!Tok->Previous && Line.MustBeDeclaration)
735 Tok->Type = TT_ObjCMethodSpecifier;
736 break;
737 case tok::colon:
738 if (!Tok->Previous)
739 return false;
740 // Colons from ?: are handled in parseConditional().
741 if (Style.Language == FormatStyle::LK_JavaScript) {
742 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
743 (Contexts.size() == 1 && // switch/case labels
744 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
745 Contexts.back().ContextKind == tok::l_paren || // function params
746 Contexts.back().ContextKind == tok::l_square || // array type
747 (!Contexts.back().IsExpression &&
748 Contexts.back().ContextKind == tok::l_brace) || // object type
749 (Contexts.size() == 1 &&
750 Line.MustBeDeclaration)) { // method/property declaration
751 Contexts.back().IsExpression = false;
752 Tok->Type = TT_JsTypeColon;
753 break;
754 }
755 }
756 if (Contexts.back().ColonIsDictLiteral ||
757 Style.Language == FormatStyle::LK_Proto ||
758 Style.Language == FormatStyle::LK_TextProto) {
759 Tok->Type = TT_DictLiteral;
760 if (Style.Language == FormatStyle::LK_TextProto) {
761 if (FormatToken *Previous = Tok->getPreviousNonComment())
762 Previous->Type = TT_SelectorName;
763 }
764 } else if (Contexts.back().ColonIsObjCMethodExpr ||
765 Line.startsWith(TT_ObjCMethodSpecifier)) {
766 Tok->Type = TT_ObjCMethodExpr;
767 const FormatToken *BeforePrevious = Tok->Previous->Previous;
768 // Ensure we tag all identifiers in method declarations as
769 // TT_SelectorName.
770 bool UnknownIdentifierInMethodDeclaration =
771 Line.startsWith(TT_ObjCMethodSpecifier) &&
772 Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
773 if (!BeforePrevious ||
774 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
775 !(BeforePrevious->is(TT_CastRParen) ||
776 (BeforePrevious->is(TT_ObjCMethodExpr) &&
777 BeforePrevious->is(tok::colon))) ||
778 BeforePrevious->is(tok::r_square) ||
779 Contexts.back().LongestObjCSelectorName == 0 ||
780 UnknownIdentifierInMethodDeclaration) {
781 Tok->Previous->Type = TT_SelectorName;
782 if (!Contexts.back().FirstObjCSelectorName)
783 Contexts.back().FirstObjCSelectorName = Tok->Previous;
784 else if (Tok->Previous->ColumnWidth >
785 Contexts.back().LongestObjCSelectorName)
786 Contexts.back().LongestObjCSelectorName =
787 Tok->Previous->ColumnWidth;
788 Tok->Previous->ParameterIndex =
789 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
790 ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
791 }
792 } else if (Contexts.back().ColonIsForRangeExpr) {
793 Tok->Type = TT_RangeBasedForLoopColon;
794 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
795 Tok->Type = TT_BitFieldColon;
796 } else if (Contexts.size() == 1 &&
797 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
798 if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
799 tok::kw_noexcept))
800 Tok->Type = TT_CtorInitializerColon;
801 else
802 Tok->Type = TT_InheritanceColon;
803 } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
804 (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
805 (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
806 Tok->Next->Next->is(tok::colon)))) {
807 // This handles a special macro in ObjC code where selectors including
808 // the colon are passed as macro arguments.
809 Tok->Type = TT_ObjCMethodExpr;
810 } else if (Contexts.back().ContextKind == tok::l_paren) {
811 Tok->Type = TT_InlineASMColon;
812 }
813 break;
814 case tok::pipe:
815 case tok::amp:
816 // | and & in declarations/type expressions represent union and
817 // intersection types, respectively.
818 if (Style.Language == FormatStyle::LK_JavaScript &&
819 !Contexts.back().IsExpression)
820 Tok->Type = TT_JsTypeOperator;
821 break;
822 case tok::kw_if:
823 case tok::kw_while:
824 if (Tok->is(tok::kw_if) && CurrentToken &&
825 CurrentToken->is(tok::kw_constexpr))
826 next();
827 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
828 next();
829 if (!parseParens(/*LookForDecls=*/true))
830 return false;
831 }
832 break;
833 case tok::kw_for:
834 if (Style.Language == FormatStyle::LK_JavaScript) {
835 // x.for and {for: ...}
836 if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
837 (Tok->Next && Tok->Next->is(tok::colon)))
838 break;
839 // JS' for await ( ...
840 if (CurrentToken && CurrentToken->is(Keywords.kw_await))
841 next();
842 }
843 Contexts.back().ColonIsForRangeExpr = true;
844 next();
845 if (!parseParens())
846 return false;
847 break;
848 case tok::l_paren:
849 // When faced with 'operator()()', the kw_operator handler incorrectly
850 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
851 // the first two parens OverloadedOperators and the second l_paren an
852 // OverloadedOperatorLParen.
853 if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
854 Tok->Previous->MatchingParen &&
855 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
856 Tok->Previous->Type = TT_OverloadedOperator;
857 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
858 Tok->Type = TT_OverloadedOperatorLParen;
859 }
860
861 if (!parseParens())
862 return false;
863 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
864 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
865 (!Tok->Previous ||
866 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
867 TT_LeadingJavaAnnotation)))
868 Line.MightBeFunctionDecl = true;
869 break;
870 case tok::l_square:
871 if (!parseSquare())
872 return false;
873 break;
874 case tok::l_brace:
875 if (Style.Language == FormatStyle::LK_TextProto) {
876 FormatToken *Previous = Tok->getPreviousNonComment();
877 if (Previous && Previous->Type != TT_DictLiteral)
878 Previous->Type = TT_SelectorName;
879 }
880 if (!parseBrace())
881 return false;
882 break;
883 case tok::less:
884 if (parseAngle()) {
885 Tok->Type = TT_TemplateOpener;
886 // In TT_Proto, we must distignuish between:
887 // map<key, value>
888 // msg < item: data >
889 // msg: < item: data >
890 // In TT_TextProto, map<key, value> does not occur.
891 if (Style.Language == FormatStyle::LK_TextProto ||
892 (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
893 Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
894 Tok->Type = TT_DictLiteral;
895 FormatToken *Previous = Tok->getPreviousNonComment();
896 if (Previous && Previous->Type != TT_DictLiteral)
897 Previous->Type = TT_SelectorName;
898 }
899 } else {
900 Tok->Type = TT_BinaryOperator;
901 NonTemplateLess.insert(Tok);
902 CurrentToken = Tok;
903 next();
904 }
905 break;
906 case tok::r_paren:
907 case tok::r_square:
908 return false;
909 case tok::r_brace:
910 // Lines can start with '}'.
911 if (Tok->Previous)
912 return false;
913 break;
914 case tok::greater:
915 if (Style.Language != FormatStyle::LK_TextProto)
916 Tok->Type = TT_BinaryOperator;
917 break;
918 case tok::kw_operator:
919 if (Style.Language == FormatStyle::LK_TextProto ||
920 Style.Language == FormatStyle::LK_Proto)
921 break;
922 while (CurrentToken &&
923 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
924 if (CurrentToken->isOneOf(tok::star, tok::amp))
925 CurrentToken->Type = TT_PointerOrReference;
926 consumeToken();
927 if (CurrentToken &&
928 CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
929 tok::comma))
930 CurrentToken->Previous->Type = TT_OverloadedOperator;
931 }
932 if (CurrentToken) {
933 CurrentToken->Type = TT_OverloadedOperatorLParen;
934 if (CurrentToken->Previous->is(TT_BinaryOperator))
935 CurrentToken->Previous->Type = TT_OverloadedOperator;
936 }
937 break;
938 case tok::question:
939 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
940 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
941 tok::r_brace)) {
942 // Question marks before semicolons, colons, etc. indicate optional
943 // types (fields, parameters), e.g.
944 // function(x?: string, y?) {...}
945 // class X { y?; }
946 Tok->Type = TT_JsTypeOptionalQuestion;
947 break;
948 }
949 // Declarations cannot be conditional expressions, this can only be part
950 // of a type declaration.
951 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
952 Style.Language == FormatStyle::LK_JavaScript)
953 break;
954 parseConditional();
955 break;
956 case tok::kw_template:
957 parseTemplateDeclaration();
958 break;
959 case tok::comma:
960 if (Contexts.back().InCtorInitializer)
961 Tok->Type = TT_CtorInitializerComma;
962 else if (Contexts.back().InInheritanceList)
963 Tok->Type = TT_InheritanceComma;
964 else if (Contexts.back().FirstStartOfName &&
965 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
966 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
967 Line.IsMultiVariableDeclStmt = true;
968 }
969 if (Contexts.back().IsForEachMacro)
970 Contexts.back().IsExpression = true;
971 break;
972 case tok::identifier:
973 if (Tok->isOneOf(Keywords.kw___has_include,
974 Keywords.kw___has_include_next)) {
975 parseHasInclude();
976 }
977 break;
978 default:
979 break;
980 }
981 return true;
982 }
983
984 void parseIncludeDirective() {
985 if (CurrentToken && CurrentToken->is(tok::less)) {
986 next();
987 while (CurrentToken) {
988 // Mark tokens up to the trailing line comments as implicit string
989 // literals.
990 if (CurrentToken->isNot(tok::comment) &&
991 !CurrentToken->TokenText.startswith("//"))
992 CurrentToken->Type = TT_ImplicitStringLiteral;
993 next();
994 }
995 }
996 }
997
998 void parseWarningOrError() {
999 next();
1000 // We still want to format the whitespace left of the first token of the
1001 // warning or error.
1002 next();
1003 while (CurrentToken) {
1004 CurrentToken->Type = TT_ImplicitStringLiteral;
1005 next();
1006 }
1007 }
1008
1009 void parsePragma() {
1010 next(); // Consume "pragma".
1011 if (CurrentToken &&
1012 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
1013 bool IsMark = CurrentToken->is(Keywords.kw_mark);
1014 next(); // Consume "mark".
1015 next(); // Consume first token (so we fix leading whitespace).
1016 while (CurrentToken) {
1017 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
1018 CurrentToken->Type = TT_ImplicitStringLiteral;
1019 next();
1020 }
1021 }
1022 }
1023
1024 void parseHasInclude() {
1025 if (!CurrentToken || !CurrentToken->is(tok::l_paren))
1026 return;
1027 next(); // '('
1028 parseIncludeDirective();
1029 next(); // ')'
1030 }
1031
1032 LineType parsePreprocessorDirective() {
1033 bool IsFirstToken = CurrentToken->IsFirst;
1034 LineType Type = LT_PreprocessorDirective;
1035 next();
1036 if (!CurrentToken)
1037 return Type;
1038
1039 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
1040 // JavaScript files can contain shebang lines of the form:
1041 // #!/usr/bin/env node
1042 // Treat these like C++ #include directives.
1043 while (CurrentToken) {
1044 // Tokens cannot be comments here.
1045 CurrentToken->Type = TT_ImplicitStringLiteral;
1046 next();
1047 }
1048 return LT_ImportStatement;
1049 }
1050
1051 if (CurrentToken->Tok.is(tok::numeric_constant)) {
1052 CurrentToken->SpacesRequiredBefore = 1;
1053 return Type;
1054 }
1055 // Hashes in the middle of a line can lead to any strange token
1056 // sequence.
1057 if (!CurrentToken->Tok.getIdentifierInfo())
1058 return Type;
1059 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
1060 case tok::pp_include:
1061 case tok::pp_include_next:
1062 case tok::pp_import:
1063 next();
1064 parseIncludeDirective();
1065 Type = LT_ImportStatement;
1066 break;
1067 case tok::pp_error:
1068 case tok::pp_warning:
1069 parseWarningOrError();
1070 break;
1071 case tok::pp_pragma:
1072 parsePragma();
1073 break;
1074 case tok::pp_if:
1075 case tok::pp_elif:
1076 Contexts.back().IsExpression = true;
1077 parseLine();
1078 break;
1079 default:
1080 break;
1081 }
1082 while (CurrentToken) {
1083 FormatToken *Tok = CurrentToken;
1084 next();
1085 if (Tok->is(tok::l_paren))
1086 parseParens();
1087 else if (Tok->isOneOf(Keywords.kw___has_include,
1088 Keywords.kw___has_include_next))
1089 parseHasInclude();
1090 }
1091 return Type;
1092 }
1093
1094public:
1095 LineType parseLine() {
1096 NonTemplateLess.clear();
1097 if (CurrentToken->is(tok::hash))
13
Taking false branch
1098 return parsePreprocessorDirective();
1099
1100 // Directly allow to 'import <string-literal>' to support protocol buffer
1101 // definitions (github.com/google/protobuf) or missing "#" (either way we
1102 // should not break the line).
1103 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
1104 if ((Style.Language == FormatStyle::LK_Java &&
14
Assuming the condition is false
1105 CurrentToken->is(Keywords.kw_package)) ||
1106 (Info && Info->getPPKeywordID() == tok::pp_import &&
15
Assuming 'Info' is null
1107 CurrentToken->Next &&
1108 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
1109 tok::kw_static))) {
1110 next();
1111 parseIncludeDirective();
1112 return LT_ImportStatement;
1113 }
1114
1115 // If this line starts and ends in '<' and '>', respectively, it is likely
1116 // part of "#define <a/b.h>".
1117 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
1118 parseIncludeDirective();
1119 return LT_ImportStatement;
1120 }
1121
1122 // In .proto files, top-level options and package statements are very
1123 // similar to import statements and should not be line-wrapped.
1124 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
16
Assuming the condition is true
17
Assuming the condition is true
19
Taking true branch
1125 CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
18
Assuming the condition is true
1126 next();
20
Value assigned to 'Parser.CurrentToken'
1127 if (CurrentToken && CurrentToken->is(tok::identifier)) {
21
Assuming pointer value is null
1128 while (CurrentToken)
1129 next();
1130 return LT_ImportStatement;
1131 }
1132 }
1133
1134 bool KeywordVirtualFound = false;
1135 bool ImportStatement = false;
1136
1137 // import {...} from '...';
1138 if (Style.Language == FormatStyle::LK_JavaScript &&
22
Assuming the condition is true
1139 CurrentToken->is(Keywords.kw_import))
23
Called C++ object pointer is null
1140 ImportStatement = true;
1141
1142 while (CurrentToken) {
1143 if (CurrentToken->is(tok::kw_virtual))
1144 KeywordVirtualFound = true;
1145 if (Style.Language == FormatStyle::LK_JavaScript) {
1146 // export {...} from '...';
1147 // An export followed by "from 'some string';" is a re-export from
1148 // another module identified by a URI and is treated as a
1149 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
1150 // Just "export {...};" or "export class ..." should not be treated as
1151 // an import in this sense.
1152 if (Line.First->is(tok::kw_export) &&
1153 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
1154 CurrentToken->Next->isStringLiteral())
1155 ImportStatement = true;
1156 if (isClosureImportStatement(*CurrentToken))
1157 ImportStatement = true;
1158 }
1159 if (!consumeToken())
1160 return LT_Invalid;
1161 }
1162 if (KeywordVirtualFound)
1163 return LT_VirtualFunctionDecl;
1164 if (ImportStatement)
1165 return LT_ImportStatement;
1166
1167 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
1168 if (Contexts.back().FirstObjCSelectorName)
1169 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
1170 Contexts.back().LongestObjCSelectorName;
1171 return LT_ObjCMethodDecl;
1172 }
1173
1174 return LT_Other;
1175 }
1176
1177private:
1178 bool isClosureImportStatement(const FormatToken &Tok) {
1179 // FIXME: Closure-library specific stuff should not be hard-coded but be
1180 // configurable.
1181 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
1182 Tok.Next->Next &&
1183 (Tok.Next->Next->TokenText == "module" ||
1184 Tok.Next->Next->TokenText == "provide" ||
1185 Tok.Next->Next->TokenText == "require" ||
1186 Tok.Next->Next->TokenText == "requireType" ||
1187 Tok.Next->Next->TokenText == "forwardDeclare") &&
1188 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
1189 }
1190
1191 void resetTokenMetadata(FormatToken *Token) {
1192 if (!Token)
1193 return;
1194
1195 // Reset token type in case we have already looked at it and then
1196 // recovered from an error (e.g. failure to find the matching >).
1197 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_LambdaLBrace,
1198 TT_ForEachMacro, TT_TypenameMacro,
1199 TT_FunctionLBrace, TT_ImplicitStringLiteral,
1200 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
1201 TT_OverloadedOperator, TT_RegexLiteral,
1202 TT_TemplateString, TT_ObjCStringLiteral))
1203 CurrentToken->Type = TT_Unknown;
1204 CurrentToken->Role.reset();
1205 CurrentToken->MatchingParen = nullptr;
1206 CurrentToken->FakeLParens.clear();
1207 CurrentToken->FakeRParens = 0;
1208 }
1209
1210 void next() {
1211 if (CurrentToken) {
1212 CurrentToken->NestingLevel = Contexts.size() - 1;
1213 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
1214 modifyContext(*CurrentToken);
1215 determineTokenType(*CurrentToken);
1216 CurrentToken = CurrentToken->Next;
1217 }
1218
1219 resetTokenMetadata(CurrentToken);
1220 }
1221
1222 /// A struct to hold information valid in a specific context, e.g.
1223 /// a pair of parenthesis.
1224 struct Context {
1225 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
1226 bool IsExpression)
1227 : ContextKind(ContextKind), BindingStrength(BindingStrength),
1228 IsExpression(IsExpression) {}
1229
1230 tok::TokenKind ContextKind;
1231 unsigned BindingStrength;
1232 bool IsExpression;
1233 unsigned LongestObjCSelectorName = 0;
1234 bool ColonIsForRangeExpr = false;
1235 bool ColonIsDictLiteral = false;
1236 bool ColonIsObjCMethodExpr = false;
1237 FormatToken *FirstObjCSelectorName = nullptr;
1238 FormatToken *FirstStartOfName = nullptr;
1239 bool CanBeExpression = true;
1240 bool InTemplateArgument = false;
1241 bool InCtorInitializer = false;
1242 bool InInheritanceList = false;
1243 bool CaretFound = false;
1244 bool IsForEachMacro = false;
1245 bool InCpp11AttributeSpecifier = false;
1246 bool InCSharpAttributeSpecifier = false;
1247 };
1248
1249 /// Puts a new \c Context onto the stack \c Contexts for the lifetime
1250 /// of each instance.
1251 struct ScopedContextCreator {
1252 AnnotatingParser &P;
1253
1254 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1255 unsigned Increase)
1256 : P(P) {
1257 P.Contexts.push_back(Context(ContextKind,
1258 P.Contexts.back().BindingStrength + Increase,
1259 P.Contexts.back().IsExpression));
1260 }
1261
1262 ~ScopedContextCreator() { P.Contexts.pop_back(); }
1263 };
1264
1265 void modifyContext(const FormatToken &Current) {
1266 if (Current.getPrecedence() == prec::Assignment &&
1267 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1268 // Type aliases use `type X = ...;` in TypeScript and can be exported
1269 // using `export type ...`.
1270 !(Style.Language == FormatStyle::LK_JavaScript &&
1271 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1272 Line.startsWith(tok::kw_export, Keywords.kw_type,
1273 tok::identifier))) &&
1274 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1275 Contexts.back().IsExpression = true;
1276 if (!Line.startsWith(TT_UnaryOperator)) {
1277 for (FormatToken *Previous = Current.Previous;
1278 Previous && Previous->Previous &&
1279 !Previous->Previous->isOneOf(tok::comma, tok::semi);
1280 Previous = Previous->Previous) {
1281 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1282 Previous = Previous->MatchingParen;
1283 if (!Previous)
1284 break;
1285 }
1286 if (Previous->opensScope())
1287 break;
1288 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1289 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1290 Previous->Previous && Previous->Previous->isNot(tok::equal))
1291 Previous->Type = TT_PointerOrReference;
1292 }
1293 }
1294 } else if (Current.is(tok::lessless) &&
1295 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1296 Contexts.back().IsExpression = true;
1297 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1298 Contexts.back().IsExpression = true;
1299 } else if (Current.is(TT_TrailingReturnArrow)) {
1300 Contexts.back().IsExpression = false;
1301 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1302 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1303 } else if (Current.Previous &&
1304 Current.Previous->is(TT_CtorInitializerColon)) {
1305 Contexts.back().IsExpression = true;
1306 Contexts.back().InCtorInitializer = true;
1307 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1308 Contexts.back().InInheritanceList = true;
1309 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1310 for (FormatToken *Previous = Current.Previous;
1311 Previous && Previous->isOneOf(tok::star, tok::amp);
1312 Previous = Previous->Previous)
1313 Previous->Type = TT_PointerOrReference;
1314 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1315 Contexts.back().IsExpression = false;
1316 } else if (Current.is(tok::kw_new)) {
1317 Contexts.back().CanBeExpression = false;
1318 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1319 // This should be the condition or increment in a for-loop.
1320 Contexts.back().IsExpression = true;
1321 }
1322 }
1323
1324 void determineTokenType(FormatToken &Current) {
1325 if (!Current.is(TT_Unknown))
1326 // The token type is already known.
1327 return;
1328
1329 if (Style.Language == FormatStyle::LK_JavaScript) {
1330 if (Current.is(tok::exclaim)) {
1331 if (Current.Previous &&
1332 (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1333 tok::r_paren, tok::r_square,
1334 tok::r_brace) ||
1335 Current.Previous->Tok.isLiteral())) {
1336 Current.Type = TT_JsNonNullAssertion;
1337 return;
1338 }
1339 if (Current.Next &&
1340 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1341 Current.Type = TT_JsNonNullAssertion;
1342 return;
1343 }
1344 }
1345 }
1346
1347 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1348 // function declaration have been found. In this case, 'Current' is a
1349 // trailing token of this declaration and thus cannot be a name.
1350 if (Current.is(Keywords.kw_instanceof)) {
1351 Current.Type = TT_BinaryOperator;
1352 } else if (isStartOfName(Current) &&
1353 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1354 Contexts.back().FirstStartOfName = &Current;
1355 Current.Type = TT_StartOfName;
1356 } else if (Current.is(tok::semi)) {
1357 // Reset FirstStartOfName after finding a semicolon so that a for loop
1358 // with multiple increment statements is not confused with a for loop
1359 // having multiple variable declarations.
1360 Contexts.back().FirstStartOfName = nullptr;
1361 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1362 AutoFound = true;
1363 } else if (Current.is(tok::arrow) &&
1364 Style.Language == FormatStyle::LK_Java) {
1365 Current.Type = TT_LambdaArrow;
1366 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1367 Current.NestingLevel == 0) {
1368 Current.Type = TT_TrailingReturnArrow;
1369 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1370 Current.Type = determineStarAmpUsage(Current,
1371 Contexts.back().CanBeExpression &&
1372 Contexts.back().IsExpression,
1373 Contexts.back().InTemplateArgument);
1374 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1375 Current.Type = determinePlusMinusCaretUsage(Current);
1376 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1377 Contexts.back().CaretFound = true;
1378 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1379 Current.Type = determineIncrementUsage(Current);
1380 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1381 Current.Type = TT_UnaryOperator;
1382 } else if (Current.is(tok::question)) {
1383 if (Style.Language == FormatStyle::LK_JavaScript &&
1384 Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1385 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1386 // on the interface, not a ternary expression.
1387 Current.Type = TT_JsTypeOptionalQuestion;
1388 } else {
1389 Current.Type = TT_ConditionalExpr;
1390 }
1391 } else if (Current.isBinaryOperator() &&
1392 (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
1393 (!Current.is(tok::greater) &&
1394 Style.Language != FormatStyle::LK_TextProto)) {
1395 Current.Type = TT_BinaryOperator;
1396 } else if (Current.is(tok::comment)) {
1397 if (Current.TokenText.startswith("/*")) {
1398 if (Current.TokenText.endswith("*/"))
1399 Current.Type = TT_BlockComment;
1400 else
1401 // The lexer has for some reason determined a comment here. But we
1402 // cannot really handle it, if it isn't properly terminated.
1403 Current.Tok.setKind(tok::unknown);
1404 } else {
1405 Current.Type = TT_LineComment;
1406 }
1407 } else if (Current.is(tok::r_paren)) {
1408 if (rParenEndsCast(Current))
1409 Current.Type = TT_CastRParen;
1410 if (Current.MatchingParen && Current.Next &&
1411 !Current.Next->isBinaryOperator() &&
1412 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1413 tok::comma, tok::period, tok::arrow,
1414 tok::coloncolon))
1415 if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1416 // Make sure this isn't the return type of an Obj-C block declaration
1417 if (AfterParen->Tok.isNot(tok::caret)) {
1418 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1419 if (BeforeParen->is(tok::identifier) &&
1420 !BeforeParen->is(TT_TypenameMacro) &&
1421 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1422 (!BeforeParen->Previous ||
1423 BeforeParen->Previous->ClosesTemplateDeclaration))
1424 Current.Type = TT_FunctionAnnotationRParen;
1425 }
1426 }
1427 } else if (Current.is(tok::at) && Current.Next &&
1428 Style.Language != FormatStyle::LK_JavaScript &&
1429 Style.Language != FormatStyle::LK_Java) {
1430 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1431 // marks declarations and properties that need special formatting.
1432 switch (Current.Next->Tok.getObjCKeywordID()) {
1433 case tok::objc_interface:
1434 case tok::objc_implementation:
1435 case tok::objc_protocol:
1436 Current.Type = TT_ObjCDecl;
1437 break;
1438 case tok::objc_property:
1439 Current.Type = TT_ObjCProperty;
1440 break;
1441 default:
1442 break;
1443 }
1444 } else if (Current.is(tok::period)) {
1445 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1446 if (PreviousNoComment &&
1447 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1448 Current.Type = TT_DesignatedInitializerPeriod;
1449 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1450 Current.Previous->isOneOf(TT_JavaAnnotation,
1451 TT_LeadingJavaAnnotation)) {
1452 Current.Type = Current.Previous->Type;
1453 }
1454 } else if (canBeObjCSelectorComponent(Current) &&
1455 // FIXME(bug 36976): ObjC return types shouldn't use
1456 // TT_CastRParen.
1457 Current.Previous && Current.Previous->is(TT_CastRParen) &&
1458 Current.Previous->MatchingParen &&
1459 Current.Previous->MatchingParen->Previous &&
1460 Current.Previous->MatchingParen->Previous->is(
1461 TT_ObjCMethodSpecifier)) {
1462 // This is the first part of an Objective-C selector name. (If there's no
1463 // colon after this, this is the only place which annotates the identifier
1464 // as a selector.)
1465 Current.Type = TT_SelectorName;
1466 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1467 Current.Previous &&
1468 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1469 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1470 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1471 // function declaration have been found.
1472 Current.Type = TT_TrailingAnnotation;
1473 } else if ((Style.Language == FormatStyle::LK_Java ||
1474 Style.Language == FormatStyle::LK_JavaScript) &&
1475 Current.Previous) {
1476 if (Current.Previous->is(tok::at) &&
1477 Current.isNot(Keywords.kw_interface)) {
1478 const FormatToken &AtToken = *Current.Previous;
1479 const FormatToken *Previous = AtToken.getPreviousNonComment();
1480 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1481 Current.Type = TT_LeadingJavaAnnotation;
1482 else
1483 Current.Type = TT_JavaAnnotation;
1484 } else if (Current.Previous->is(tok::period) &&
1485 Current.Previous->isOneOf(TT_JavaAnnotation,
1486 TT_LeadingJavaAnnotation)) {
1487 Current.Type = Current.Previous->Type;
1488 }
1489 }
1490 }
1491
1492 /// Take a guess at whether \p Tok starts a name of a function or
1493 /// variable declaration.
1494 ///
1495 /// This is a heuristic based on whether \p Tok is an identifier following
1496 /// something that is likely a type.
1497 bool isStartOfName(const FormatToken &Tok) {
1498 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1499 return false;
1500
1501 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1502 Keywords.kw_as))
1503 return false;
1504 if (Style.Language == FormatStyle::LK_JavaScript &&
1505 Tok.Previous->is(Keywords.kw_in))
1506 return false;
1507
1508 // Skip "const" as it does not have an influence on whether this is a name.
1509 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1510 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1511 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1512
1513 if (!PreviousNotConst)
1514 return false;
1515
1516 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1517 PreviousNotConst->Previous &&
1518 PreviousNotConst->Previous->is(tok::hash);
1519
1520 if (PreviousNotConst->is(TT_TemplateCloser))
1521 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1522 PreviousNotConst->MatchingParen->Previous &&
1523 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1524 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1525
1526 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1527 PreviousNotConst->MatchingParen->Previous &&
1528 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1529 return true;
1530
1531 return (!IsPPKeyword &&
1532 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1533 PreviousNotConst->is(TT_PointerOrReference) ||
1534 PreviousNotConst->isSimpleTypeSpecifier();
1535 }
1536
1537 /// Determine whether ')' is ending a cast.
1538 bool rParenEndsCast(const FormatToken &Tok) {
1539 // C-style casts are only used in C++ and Java.
1540 if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1541 return false;
1542
1543 // Empty parens aren't casts and there are no casts at the end of the line.
1544 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1545 return false;
1546
1547 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1548 if (LeftOfParens) {
1549 // If there is a closing parenthesis left of the current parentheses,
1550 // look past it as these might be chained casts.
1551 if (LeftOfParens->is(tok::r_paren)) {
1552 if (!LeftOfParens->MatchingParen ||
1553 !LeftOfParens->MatchingParen->Previous)
1554 return false;
1555 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1556 }
1557
1558 // If there is an identifier (or with a few exceptions a keyword) right
1559 // before the parentheses, this is unlikely to be a cast.
1560 if (LeftOfParens->Tok.getIdentifierInfo() &&
1561 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1562 tok::kw_delete))
1563 return false;
1564
1565 // Certain other tokens right before the parentheses are also signals that
1566 // this cannot be a cast.
1567 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1568 TT_TemplateCloser, tok::ellipsis))
1569 return false;
1570 }
1571
1572 if (Tok.Next->is(tok::question))
1573 return false;
1574
1575 // As Java has no function types, a "(" after the ")" likely means that this
1576 // is a cast.
1577 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1578 return true;
1579
1580 // If a (non-string) literal follows, this is likely a cast.
1581 if (Tok.Next->isNot(tok::string_literal) &&
1582 (Tok.Next->Tok.isLiteral() ||
1583 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1584 return true;
1585
1586 // Heuristically try to determine whether the parentheses contain a type.
1587 bool ParensAreType =
1588 !Tok.Previous ||
1589 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1590 Tok.Previous->isSimpleTypeSpecifier();
1591 bool ParensCouldEndDecl =
1592 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1593 if (ParensAreType && !ParensCouldEndDecl)
1594 return true;
1595
1596 // At this point, we heuristically assume that there are no casts at the
1597 // start of the line. We assume that we have found most cases where there
1598 // are by the logic above, e.g. "(void)x;".
1599 if (!LeftOfParens)
1600 return false;
1601
1602 // Certain token types inside the parentheses mean that this can't be a
1603 // cast.
1604 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1605 Token = Token->Next)
1606 if (Token->is(TT_BinaryOperator))
1607 return false;
1608
1609 // If the following token is an identifier or 'this', this is a cast. All
1610 // cases where this can be something else are handled above.
1611 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1612 return true;
1613
1614 if (!Tok.Next->Next)
1615 return false;
1616
1617 // If the next token after the parenthesis is a unary operator, assume
1618 // that this is cast, unless there are unexpected tokens inside the
1619 // parenthesis.
1620 bool NextIsUnary =
1621 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1622 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1623 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1624 return false;
1625 // Search for unexpected tokens.
1626 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1627 Prev = Prev->Previous) {
1628 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1629 return false;
1630 }
1631 return true;
1632 }
1633
1634 /// Return the type of the given token assuming it is * or &.
1635 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1636 bool InTemplateArgument) {
1637 if (Style.Language == FormatStyle::LK_JavaScript)
1638 return TT_BinaryOperator;
1639
1640 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1641 if (!PrevToken)
1642 return TT_UnaryOperator;
1643
1644 const FormatToken *NextToken = Tok.getNextNonComment();
1645 if (!NextToken ||
1646 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1647 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1648 return TT_PointerOrReference;
1649
1650 if (PrevToken->is(tok::coloncolon))
1651 return TT_PointerOrReference;
1652
1653 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1654 tok::comma, tok::semi, tok::kw_return, tok::colon,
1655 tok::equal, tok::kw_delete, tok::kw_sizeof,
1656 tok::kw_throw) ||
1657 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1658 TT_UnaryOperator, TT_CastRParen))
1659 return TT_UnaryOperator;
1660
1661 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1662 return TT_PointerOrReference;
1663 if (NextToken->is(tok::kw_operator) && !IsExpression)
1664 return TT_PointerOrReference;
1665 if (NextToken->isOneOf(tok::comma, tok::semi))
1666 return TT_PointerOrReference;
1667
1668 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1669 FormatToken *TokenBeforeMatchingParen =
1670 PrevToken->MatchingParen->getPreviousNonComment();
1671 if (TokenBeforeMatchingParen &&
1672 TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype,
1673 TT_TypenameMacro))
1674 return TT_PointerOrReference;
1675 }
1676
1677 if (PrevToken->Tok.isLiteral() ||
1678 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1679 tok::kw_false, tok::r_brace) ||
1680 NextToken->Tok.isLiteral() ||
1681 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1682 NextToken->isUnaryOperator() ||
1683 // If we know we're in a template argument, there are no named
1684 // declarations. Thus, having an identifier on the right-hand side
1685 // indicates a binary operator.
1686 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1687 return TT_BinaryOperator;
1688
1689 // "&&(" is quite unlikely to be two successive unary "&".
1690 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1691 return TT_BinaryOperator;
1692
1693 // This catches some cases where evaluation order is used as control flow:
1694 // aaa && aaa->f();
1695 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1696 if (NextNextToken && NextNextToken->is(tok::arrow))
1697 return TT_BinaryOperator;
1698
1699 // It is very unlikely that we are going to find a pointer or reference type
1700 // definition on the RHS of an assignment.
1701 if (IsExpression && !Contexts.back().CaretFound)
1702 return TT_BinaryOperator;
1703
1704 return TT_PointerOrReference;
1705 }
1706
1707 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1708 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1709 if (!PrevToken)
1710 return TT_UnaryOperator;
1711
1712 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
1713 // This must be a sequence of leading unary operators.
1714 return TT_UnaryOperator;
1715
1716 // Use heuristics to recognize unary operators.
1717 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1718 tok::question, tok::colon, tok::kw_return,
1719 tok::kw_case, tok::at, tok::l_brace))
1720 return TT_UnaryOperator;
1721
1722 // There can't be two consecutive binary operators.
1723 if (PrevToken->is(TT_BinaryOperator))
1724 return TT_UnaryOperator;
1725
1726 // Fall back to marking the token as binary operator.
1727 return TT_BinaryOperator;
1728 }
1729
1730 /// Determine whether ++/-- are pre- or post-increments/-decrements.
1731 TokenType determineIncrementUsage(const FormatToken &Tok) {
1732 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1733 if (!PrevToken || PrevToken->is(TT_CastRParen))
1734 return TT_UnaryOperator;
1735 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1736 return TT_TrailingUnaryOperator;
1737
1738 return TT_UnaryOperator;
1739 }
1740
1741 SmallVector<Context, 8> Contexts;
1742
1743 const FormatStyle &Style;
1744 AnnotatedLine &Line;
1745 FormatToken *CurrentToken;
1746 bool AutoFound;
1747 const AdditionalKeywords &Keywords;
1748
1749 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1750 // determines that a specific token can't be a template opener, it will make
1751 // same decision irrespective of the decisions for tokens leading up to it.
1752 // Store this information to prevent this from causing exponential runtime.
1753 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1754};
1755
1756static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1757static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1758
1759/// Parses binary expressions by inserting fake parenthesis based on
1760/// operator precedence.
1761class ExpressionParser {
1762public:
1763 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1764 AnnotatedLine &Line)
1765 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1766
1767 /// Parse expressions with the given operator precedence.
1768 void parse(int Precedence = 0) {
1769 // Skip 'return' and ObjC selector colons as they are not part of a binary
1770 // expression.
1771 while (Current && (Current->is(tok::kw_return) ||
1772 (Current->is(tok::colon) &&
1773 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1774 next();
1775
1776 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1777 return;
1778
1779 // Conditional expressions need to be parsed separately for proper nesting.
1780 if (Precedence == prec::Conditional) {
1781 parseConditionalExpr();
1782 return;
1783 }
1784
1785 // Parse unary operators, which all have a higher precedence than binary
1786 // operators.
1787 if (Precedence == PrecedenceUnaryOperator) {
1788 parseUnaryOperator();
1789 return;
1790 }
1791
1792 FormatToken *Start = Current;
1793 FormatToken *LatestOperator = nullptr;
1794 unsigned OperatorIndex = 0;
1795
1796 while (Current) {
1797 // Consume operators with higher precedence.
1798 parse(Precedence + 1);
1799
1800 int CurrentPrecedence = getCurrentPrecedence();
1801
1802 if (Current && Current->is(TT_SelectorName) &&
1803 Precedence == CurrentPrecedence) {
1804 if (LatestOperator)
1805 addFakeParenthesis(Start, prec::Level(Precedence));
1806 Start = Current;
1807 }
1808
1809 // At the end of the line or when an operator with higher precedence is
1810 // found, insert fake parenthesis and return.
1811 if (!Current ||
1812 (Current->closesScope() &&
1813 (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1814 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1815 (CurrentPrecedence == prec::Conditional &&
1816 Precedence == prec::Assignment && Current->is(tok::colon))) {
1817 break;
1818 }
1819
1820 // Consume scopes: (), [], <> and {}
1821 if (Current->opensScope()) {
1822 // In fragment of a JavaScript template string can look like '}..${' and
1823 // thus close a scope and open a new one at the same time.
1824 while (Current && (!Current->closesScope() || Current->opensScope())) {
1825 next();
1826 parse();
1827 }
1828 next();
1829 } else {
1830 // Operator found.
1831 if (CurrentPrecedence == Precedence) {
1832 if (LatestOperator)
1833 LatestOperator->NextOperator = Current;
1834 LatestOperator = Current;
1835 Current->OperatorIndex = OperatorIndex;
1836 ++OperatorIndex;
1837 }
1838 next(/*SkipPastLeadingComments=*/Precedence > 0);
1839 }
1840 }
1841
1842 if (LatestOperator && (Current || Precedence > 0)) {
1843 // LatestOperator->LastOperator = true;
1844 if (Precedence == PrecedenceArrowAndPeriod) {
1845 // Call expressions don't have a binary operator precedence.
1846 addFakeParenthesis(Start, prec::Unknown);
1847 } else {
1848 addFakeParenthesis(Start, prec::Level(Precedence));
1849 }
1850 }
1851 }
1852
1853private:
1854 /// Gets the precedence (+1) of the given token for binary operators
1855 /// and other tokens that we treat like binary operators.
1856 int getCurrentPrecedence() {
1857 if (Current) {
1858 const FormatToken *NextNonComment = Current->getNextNonComment();
1859 if (Current->is(TT_ConditionalExpr))
1860 return prec::Conditional;
1861 if (NextNonComment && Current->is(TT_SelectorName) &&
1862 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
1863 ((Style.Language == FormatStyle::LK_Proto ||
1864 Style.Language == FormatStyle::LK_TextProto) &&
1865 NextNonComment->is(tok::less))))
1866 return prec::Assignment;
1867 if (Current->is(TT_JsComputedPropertyName))
1868 return prec::Assignment;
1869 if (Current->is(TT_LambdaArrow))
1870 return prec::Comma;
1871 if (Current->is(TT_JsFatArrow))
1872 return prec::Assignment;
1873 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1874 (Current->is(tok::comment) && NextNonComment &&
1875 NextNonComment->is(TT_SelectorName)))
1876 return 0;
1877 if (Current->is(TT_RangeBasedForLoopColon))
1878 return prec::Comma;
1879 if ((Style.Language == FormatStyle::LK_Java ||
1880 Style.Language == FormatStyle::LK_JavaScript) &&
1881 Current->is(Keywords.kw_instanceof))
1882 return prec::Relational;
1883 if (Style.Language == FormatStyle::LK_JavaScript &&
1884 Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1885 return prec::Relational;
1886 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1887 return Current->getPrecedence();
1888 if (Current->isOneOf(tok::period, tok::arrow))
1889 return PrecedenceArrowAndPeriod;
1890 if ((Style.Language == FormatStyle::LK_Java ||
1891 Style.Language == FormatStyle::LK_JavaScript) &&
1892 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1893 Keywords.kw_throws))
1894 return 0;
1895 }
1896 return -1;
1897 }
1898
1899 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1900 Start->FakeLParens.push_back(Precedence);
1901 if (Precedence > prec::Unknown)
1902 Start->StartsBinaryExpression = true;
1903 if (Current) {
1904 FormatToken *Previous = Current->Previous;
1905 while (Previous->is(tok::comment) && Previous->Previous)
1906 Previous = Previous->Previous;
1907 ++Previous->FakeRParens;
1908 if (Precedence > prec::Unknown)
1909 Previous->EndsBinaryExpression = true;
1910 }
1911 }
1912
1913 /// Parse unary operator expressions and surround them with fake
1914 /// parentheses if appropriate.
1915 void parseUnaryOperator() {
1916 llvm::SmallVector<FormatToken *, 2> Tokens;
1917 while (Current && Current->is(TT_UnaryOperator)) {
1918 Tokens.push_back(Current);
1919 next();
1920 }
1921 parse(PrecedenceArrowAndPeriod);
1922 for (FormatToken *Token : llvm::reverse(Tokens))
1923 // The actual precedence doesn't matter.
1924 addFakeParenthesis(Token, prec::Unknown);
1925 }
1926
1927 void parseConditionalExpr() {
1928 while (Current && Current->isTrailingComment()) {
1929 next();
1930 }
1931 FormatToken *Start = Current;
1932 parse(prec::LogicalOr);
1933 if (!Current || !Current->is(tok::question))
1934 return;
1935 next();
1936 parse(prec::Assignment);
1937 if (!Current || Current->isNot(TT_ConditionalExpr))
1938 return;
1939 next();
1940 parse(prec::Assignment);
1941 addFakeParenthesis(Start, prec::Conditional);
1942 }
1943
1944 void next(bool SkipPastLeadingComments = true) {
1945 if (Current)
1946 Current = Current->Next;
1947 while (Current &&
1948 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1949 Current->isTrailingComment())
1950 Current = Current->Next;
1951 }
1952
1953 const FormatStyle &Style;
1954 const AdditionalKeywords &Keywords;
1955 FormatToken *Current;
1956};
1957
1958} // end anonymous namespace
1959
1960void TokenAnnotator::setCommentLineLevels(
1961 SmallVectorImpl<AnnotatedLine *> &Lines) {
1962 const AnnotatedLine *NextNonCommentLine = nullptr;
1963 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1964 E = Lines.rend();
1965 I != E; ++I) {
1966 bool CommentLine = true;
1967 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1968 if (!Tok->is(tok::comment)) {
1969 CommentLine = false;
1970 break;
1971 }
1972 }
1973
1974 // If the comment is currently aligned with the line immediately following
1975 // it, that's probably intentional and we should keep it.
1976 if (NextNonCommentLine && CommentLine &&
1977 NextNonCommentLine->First->NewlinesBefore <= 1 &&
1978 NextNonCommentLine->First->OriginalColumn ==
1979 (*I)->First->OriginalColumn) {
1980 // Align comments for preprocessor lines with the # in column 0 if
1981 // preprocessor lines are not indented. Otherwise, align with the next
1982 // line.
1983 (*I)->Level =
1984 (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1985 (NextNonCommentLine->Type == LT_PreprocessorDirective ||
1986 NextNonCommentLine->Type == LT_ImportStatement))
1987 ? 0
1988 : NextNonCommentLine->Level;
1989 } else {
1990 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1991 }
1992
1993 setCommentLineLevels((*I)->Children);
1994 }
1995}
1996
1997static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1998 unsigned Result = 0;
1999 for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
2000 Result = std::max(Result, Tok->NestingLevel);
2001 return Result;
2002}
2003
2004void TokenAnnotator::annotate(AnnotatedLine &Line) {
2005 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2
Loop condition is true. Entering loop body
5
Loop condition is true. Entering loop body
8
Loop condition is true. Entering loop body
11
Loop condition is false. Execution continues on line 2010
2006 E = Line.Children.end();
2007 I != E; ++I) {
1
Assuming 'I' is not equal to 'E'
4
Assuming 'I' is not equal to 'E'
7
Assuming 'I' is not equal to 'E'
10
Assuming 'I' is equal to 'E'
2008 annotate(**I);
3
Calling 'TokenAnnotator::annotate'
6
Calling 'TokenAnnotator::annotate'
9
Calling 'TokenAnnotator::annotate'
2009 }
2010 AnnotatingParser Parser(Style, Line, Keywords);
2011 Line.Type = Parser.parseLine();
12
Calling 'AnnotatingParser::parseLine'
2012
2013 // With very deep nesting, ExpressionParser uses lots of stack and the
2014 // formatting algorithm is very slow. We're not going to do a good job here
2015 // anyway - it's probably generated code being formatted by mistake.
2016 // Just skip the whole line.
2017 if (maxNestingDepth(Line) > 50)
2018 Line.Type = LT_Invalid;
2019
2020 if (Line.Type == LT_Invalid)
2021 return;
2022
2023 ExpressionParser ExprParser(Style, Keywords, Line);
2024 ExprParser.parse();
2025
2026 if (Line.startsWith(TT_ObjCMethodSpecifier))
2027 Line.Type = LT_ObjCMethodDecl;
2028 else if (Line.startsWith(TT_ObjCDecl))
2029 Line.Type = LT_ObjCDecl;
2030 else if (Line.startsWith(TT_ObjCProperty))
2031 Line.Type = LT_ObjCProperty;
2032
2033 Line.First->SpacesRequiredBefore = 1;
2034 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
2035}
2036
2037// This function heuristically determines whether 'Current' starts the name of a
2038// function declaration.
2039static bool isFunctionDeclarationName(const FormatToken &Current,
2040 const AnnotatedLine &Line) {
2041 auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
2042 for (; Next; Next = Next->Next) {
2043 if (Next->is(TT_OverloadedOperatorLParen))
2044 return Next;
2045 if (Next->is(TT_OverloadedOperator))
2046 continue;
2047 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
2048 // For 'new[]' and 'delete[]'.
2049 if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
2050 Next->Next->Next->is(tok::r_square))
2051 Next = Next->Next->Next;
2052 continue;
2053 }
2054
2055 break;
2056 }
2057 return nullptr;
2058 };
2059
2060 // Find parentheses of parameter list.
2061 const FormatToken *Next = Current.Next;
2062 if (Current.is(tok::kw_operator)) {
2063 if (Current.Previous && Current.Previous->is(tok::coloncolon))
2064 return false;
2065 Next = skipOperatorName(Next);
2066 } else {
2067 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
2068 return false;
2069 for (; Next; Next = Next->Next) {
2070 if (Next->is(TT_TemplateOpener)) {
2071 Next = Next->MatchingParen;
2072 } else if (Next->is(tok::coloncolon)) {
2073 Next = Next->Next;
2074 if (!Next)
2075 return false;
2076 if (Next->is(tok::kw_operator)) {
2077 Next = skipOperatorName(Next->Next);
2078 break;
2079 }
2080 if (!Next->is(tok::identifier))
2081 return false;
2082 } else if (Next->is(tok::l_paren)) {
2083 break;
2084 } else {
2085 return false;
2086 }
2087 }
2088 }
2089
2090 // Check whether parameter list can belong to a function declaration.
2091 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
2092 return false;
2093 // If the lines ends with "{", this is likely an function definition.
2094 if (Line.Last->is(tok::l_brace))
2095 return true;
2096 if (Next->Next == Next->MatchingParen)
2097 return true; // Empty parentheses.
2098 // If there is an &/&& after the r_paren, this is likely a function.
2099 if (Next->MatchingParen->Next &&
2100 Next->MatchingParen->Next->is(TT_PointerOrReference))
2101 return true;
2102 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
2103 Tok = Tok->Next) {
2104 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
2105 Tok = Tok->MatchingParen;
2106 continue;
2107 }
2108 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
2109 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
2110 return true;
2111 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
2112 Tok->Tok.isLiteral())
2113 return false;
2114 }
2115 return false;
2116}
2117
2118bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
2119 assert(Line.MightBeFunctionDecl)((Line.MightBeFunctionDecl) ? static_cast<void> (0) : __assert_fail
("Line.MightBeFunctionDecl", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Format/TokenAnnotator.cpp"
, 2119, __PRETTY_FUNCTION__))
;
2120
2121 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
2122 Style.AlwaysBreakAfterReturnType ==
2123 FormatStyle::RTBS_TopLevelDefinitions) &&
2124 Line.Level > 0)
2125 return false;
2126
2127 switch (Style.AlwaysBreakAfterReturnType) {
2128 case FormatStyle::RTBS_None:
2129 return false;
2130 case FormatStyle::RTBS_All:
2131 case FormatStyle::RTBS_TopLevel:
2132 return true;
2133 case FormatStyle::RTBS_AllDefinitions:
2134 case FormatStyle::RTBS_TopLevelDefinitions:
2135 return Line.mightBeFunctionDefinition();
2136 }
2137
2138 return false;
2139}
2140
2141void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2142 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2143 E = Line.Children.end();
2144 I != E; ++I) {
2145 calculateFormattingInformation(**I);
2146 }
2147
2148 Line.First->TotalLength =
2149 Line.First->IsMultiline ? Style.ColumnLimit
2150 : Line.FirstStartColumn + Line.First->ColumnWidth;
2151 FormatToken *Current = Line.First->Next;
2152 bool InFunctionDecl = Line.MightBeFunctionDecl;
2153 while (Current) {
2154 if (isFunctionDeclarationName(*Current, Line))
2155 Current->Type = TT_FunctionDeclarationName;
2156 if (Current->is(TT_LineComment)) {
2157 if (Current->Previous->BlockKind == BK_BracedInit &&
2158 Current->Previous->opensScope())
2159 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
2160 else
2161 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2162
2163 // If we find a trailing comment, iterate backwards to determine whether
2164 // it seems to relate to a specific parameter. If so, break before that
2165 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2166 // to the previous line in:
2167 // SomeFunction(a,
2168 // b, // comment
2169 // c);
2170 if (!Current->HasUnescapedNewline) {
2171 for (FormatToken *Parameter = Current->Previous; Parameter;
2172 Parameter = Parameter->Previous) {
2173 if (Parameter->isOneOf(tok::comment, tok::r_brace))
2174 break;
2175 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2176 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2177 Parameter->HasUnescapedNewline)
2178 Parameter->MustBreakBefore = true;
2179 break;
2180 }
2181 }
2182 }
2183 } else if (Current->SpacesRequiredBefore == 0 &&
2184 spaceRequiredBefore(Line, *Current)) {
2185 Current->SpacesRequiredBefore = 1;
2186 }
2187
2188 Current->MustBreakBefore =
2189 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2190
2191 if (!Current->MustBreakBefore && InFunctionDecl &&
2192 Current->is(TT_FunctionDeclarationName))
2193 Current->MustBreakBefore = mustBreakForReturnType(Line);
2194
2195 Current->CanBreakBefore =
2196 Current->MustBreakBefore || canBreakBefore(Line, *Current);
2197 unsigned ChildSize = 0;
2198 if (Current->Previous->Children.size() == 1) {
2199 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
2200 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2201 : LastOfChild.TotalLength + 1;
2202 }
2203 const FormatToken *Prev = Current->Previous;
2204 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2205 (Prev->Children.size() == 1 &&
2206 Prev->Children[0]->First->MustBreakBefore) ||
2207 Current->IsMultiline)
2208 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2209 else
2210 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2211 ChildSize + Current->SpacesRequiredBefore;
2212
2213 if (Current->is(TT_CtorInitializerColon))
2214 InFunctionDecl = false;
2215
2216 // FIXME: Only calculate this if CanBreakBefore is true once static
2217 // initializers etc. are sorted out.
2218 // FIXME: Move magic numbers to a better place.
2219
2220 // Reduce penalty for aligning ObjC method arguments using the colon
2221 // alignment as this is the canonical way (still prefer fitting everything
2222 // into one line if possible). Trying to fit a whole expression into one
2223 // line should not force other line breaks (e.g. when ObjC method
2224 // expression is a part of other expression).
2225 Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
2226 if (Style.Language == FormatStyle::LK_ObjC &&
2227 Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
2228 if (Current->ParameterIndex == 1)
2229 Current->SplitPenalty += 5 * Current->BindingStrength;
2230 } else {
2231 Current->SplitPenalty += 20 * Current->BindingStrength;
2232 }
2233
2234 Current = Current->Next;
2235 }
2236
2237 calculateUnbreakableTailLengths(Line);
2238 unsigned IndentLevel = Line.Level;
2239 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2240 if (Current->Role)
2241 Current->Role->precomputeFormattingInfos(Current);
2242 if (Current->MatchingParen &&
2243 Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
2244 assert(IndentLevel > 0)((IndentLevel > 0) ? static_cast<void> (0) : __assert_fail
("IndentLevel > 0", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Format/TokenAnnotator.cpp"
, 2244, __PRETTY_FUNCTION__))
;
2245 --IndentLevel;
2246 }
2247 Current->IndentLevel = IndentLevel;
2248 if (Current->opensBlockOrBlockTypeList(Style))
2249 ++IndentLevel;
2250 }
2251
2252 LLVM_DEBUG({ printDebugInfo(Line); })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-token-annotator")) { { printDebugInfo(Line); }; } } while
(false)
;
2253}
2254
2255void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2256 unsigned UnbreakableTailLength = 0;
2257 FormatToken *Current = Line.Last;
2258 while (Current) {
2259 Current->UnbreakableTailLength = UnbreakableTailLength;
2260 if (Current->CanBreakBefore ||
2261 Current->isOneOf(tok::comment, tok::string_literal)) {
2262 UnbreakableTailLength = 0;
2263 } else {
2264 UnbreakableTailLength +=
2265 Current->ColumnWidth + Current->SpacesRequiredBefore;
2266 }
2267 Current = Current->Previous;
2268 }
2269}
2270
2271unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2272 const FormatToken &Tok,
2273 bool InFunctionDecl) {
2274 const FormatToken &Left = *Tok.Previous;
2275 const FormatToken &Right = Tok;
2276
2277 if (Left.is(tok::semi))
2278 return 0;
2279
2280 if (Style.Language == FormatStyle::LK_Java) {
2281 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2282 return 1;
2283 if (Right.is(Keywords.kw_implements))
2284 return 2;
2285 if (Left.is(tok::comma) && Left.NestingLevel == 0)
2286 return 3;
2287 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2288 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2289 return 100;
2290 if (Left.is(TT_JsTypeColon))
2291 return 35;
2292 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2293 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2294 return 100;
2295 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2296 if (Left.opensScope() && Right.closesScope())
2297 return 200;
2298 }
2299
2300 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2301 return 1;
2302 if (Right.is(tok::l_square)) {
2303 if (Style.Language == FormatStyle::LK_Proto)
2304 return 1;
2305 if (Left.is(tok::r_square))
2306 return 200;
2307 // Slightly prefer formatting local lambda definitions like functions.
2308 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2309 return 35;
2310 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2311 TT_ArrayInitializerLSquare,
2312 TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2313 return 500;
2314 }
2315
2316 if (Left.is(tok::coloncolon) ||
2317 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2318 return 500;
2319 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2320 Right.is(tok::kw_operator)) {
2321 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2322 return 3;
2323 if (Left.is(TT_StartOfName))
2324 return 110;
2325 if (InFunctionDecl && Right.NestingLevel == 0)
2326 return Style.PenaltyReturnTypeOnItsOwnLine;
2327 return 200;
2328 }
2329 if (Right.is(TT_PointerOrReference))
2330 return 190;
2331 if (Right.is(TT_LambdaArrow))
2332 return 110;
2333 if (Left.is(tok::equal) && Right.is(tok::l_brace))
2334 return 160;
2335 if (Left.is(TT_CastRParen))
2336 return 100;
2337 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2338 return 5000;
2339 if (Left.is(tok::comment))
2340 return 1000;
2341
2342 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2343 TT_CtorInitializerColon))
2344 return 2;
2345
2346 if (Right.isMemberAccess()) {
2347 // Breaking before the "./->" of a chained call/member access is reasonably
2348 // cheap, as formatting those with one call per line is generally
2349 // desirable. In particular, it should be cheaper to break before the call
2350 // than it is to break inside a call's parameters, which could lead to weird
2351 // "hanging" indents. The exception is the very last "./->" to support this
2352 // frequent pattern:
2353 //
2354 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2355 // dddddddd);
2356 //
2357 // which might otherwise be blown up onto many lines. Here, clang-format
2358 // won't produce "hanging" indents anyway as there is no other trailing
2359 // call.
2360 //
2361 // Also apply higher penalty is not a call as that might lead to a wrapping
2362 // like:
2363 //
2364 // aaaaaaa
2365 // .aaaaaaaaa.bbbbbbbb(cccccccc);
2366 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2367 ? 150
2368 : 35;
2369 }
2370
2371 if (Right.is(TT_TrailingAnnotation) &&
2372 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2373 // Moving trailing annotations to the next line is fine for ObjC method
2374 // declarations.
2375 if (Line.startsWith(TT_ObjCMethodSpecifier))
2376 return 10;
2377 // Generally, breaking before a trailing annotation is bad unless it is
2378 // function-like. It seems to be especially preferable to keep standard
2379 // annotations (i.e. "const", "final" and "override") on the same line.
2380 // Use a slightly higher penalty after ")" so that annotations like
2381 // "const override" are kept together.
2382 bool is_short_annotation = Right.TokenText.size() < 10;
2383 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2384 }
2385
2386 // In for-loops, prefer breaking at ',' and ';'.
2387 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2388 return 4;
2389
2390 // In Objective-C method expressions, prefer breaking before "param:" over
2391 // breaking after it.
2392 if (Right.is(TT_SelectorName))
2393 return 0;
2394 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2395 return Line.MightBeFunctionDecl ? 50 : 500;
2396
2397 // In Objective-C type declarations, avoid breaking after the category's
2398 // open paren (we'll prefer breaking after the protocol list's opening
2399 // angle bracket, if present).
2400 if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
2401 Left.Previous->isOneOf(tok::identifier, tok::greater))
2402 return 500;
2403
2404 if (Left.is(tok::l_paren) && InFunctionDecl &&
2405 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2406 return 100;
2407 if (Left.is(tok::l_paren) && Left.Previous &&
2408 (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
2409 Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
2410 return 1000;
2411 if (Left.is(tok::equal) && InFunctionDecl)
2412 return 110;
2413 if (Right.is(tok::r_brace))
2414 return 1;
2415 if (Left.is(TT_TemplateOpener))
2416 return 100;
2417 if (Left.opensScope()) {
2418 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2419 return 0;
2420 if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
2421 return 19;
2422 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2423 : 19;
2424 }
2425 if (Left.is(TT_JavaAnnotation))
2426 return 50;
2427
2428 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2429 Left.Previous->isLabelString() &&
2430 (Left.NextOperator || Left.OperatorIndex != 0))
2431 return 50;
2432 if (Right.is(tok::plus) && Left.isLabelString() &&
2433 (Right.NextOperator || Right.OperatorIndex != 0))
2434 return 25;
2435 if (Left.is(tok::comma))
2436 return 1;
2437 if (Right.is(tok::lessless) && Left.isLabelString() &&
2438 (Right.NextOperator || Right.OperatorIndex != 1))
2439 return 25;
2440 if (Right.is(tok::lessless)) {
2441 // Breaking at a << is really cheap.
2442 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2443 // Slightly prefer to break before the first one in log-like statements.
2444 return 2;
2445 return 1;
2446 }
2447 if (Left.ClosesTemplateDeclaration)
2448 return Style.PenaltyBreakTemplateDeclaration;
2449 if (Left.is(TT_ConditionalExpr))
2450 return prec::Conditional;
2451 prec::Level Level = Left.getPrecedence();
2452 if (Level == prec::Unknown)
2453 Level = Right.getPrecedence();
2454 if (Level == prec::Assignment)
2455 return Style.PenaltyBreakAssignment;
2456 if (Level != prec::Unknown)
2457 return Level;
2458
2459 return 3;
2460}
2461
2462bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
2463 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always ||
2464 (Style.SpaceBeforeParens == FormatStyle::SBPO_NonEmptyParentheses &&
2465 Right.ParameterCount > 0);
2466}
2467
2468bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2469 const FormatToken &Left,
2470 const FormatToken &Right) {
2471 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2472 return true;
2473 if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2474 return true;
2475 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2476 Left.Tok.getObjCKeywordID() == tok::objc_property)
2477 return true;
2478 if (Right.is(tok::hashhash))
2479 return Left.is(tok::hash);
2480 if (Left.isOneOf(tok::hashhash, tok::hash))
2481 return Right.is(tok::hash);
2482 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2483 return Style.SpaceInEmptyParentheses;
2484 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2485 return (Right.is(TT_CastRParen) ||
2486 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2487 ? Style.SpacesInCStyleCastParentheses
2488 : Style.SpacesInParentheses;
2489 if (Right.isOneOf(tok::semi, tok::comma))
2490 return false;
2491 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
2492 bool IsLightweightGeneric = Right.MatchingParen &&
2493 Right.MatchingParen->Next &&
2494 Right.MatchingParen->Next->is(tok::colon);
2495 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
2496 }
2497 if (Right.is(tok::less) && Left.is(tok::kw_template))
2498 return Style.SpaceAfterTemplateKeyword;
2499 if (Left.isOneOf(tok::exclaim, tok::tilde))
2500 return false;
2501 if (Left.is(tok::at) &&
2502 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2503 tok::numeric_constant, tok::l_paren, tok::l_brace,
2504 tok::kw_true, tok::kw_false))
2505 return false;
2506 if (Left.is(tok::colon))
2507 return !Left.is(TT_ObjCMethodExpr);
2508 if (Left.is(tok::coloncolon))
2509 return false;
2510 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
2511 if (Style.Language == FormatStyle::LK_TextProto ||
2512 (Style.Language == FormatStyle::LK_Proto &&
2513 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
2514 // Format empty list as `<>`.
2515 if (Left.is(tok::less) && Right.is(tok::greater))
2516 return false;
2517 return !Style.Cpp11BracedListStyle;
2518 }
2519 return false;
2520 }
2521 if (Right.is(tok::ellipsis))
2522 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2523 Left.Previous->is(tok::kw_case));
2524 if (Left.is(tok::l_square) && Right.is(tok::amp))
2525 return false;
2526 if (Right.is(TT_PointerOrReference)) {
2527 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2528 if (!Left.MatchingParen)
2529 return true;
2530 FormatToken *TokenBeforeMatchingParen =
2531 Left.MatchingParen->getPreviousNonComment();
2532 if (!TokenBeforeMatchingParen ||
2533 !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype,
2534 TT_TypenameMacro))
2535 return true;
2536 }
2537 return (Left.Tok.isLiteral() ||
2538 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2539 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2540 (Line.IsMultiVariableDeclStmt &&
2541 (Left.NestingLevel == 0 ||
2542 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2543 }
2544 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2545 (!Left.is(TT_PointerOrReference) ||
2546 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2547 !Line.IsMultiVariableDeclStmt)))
2548 return true;
2549 if (Left.is(TT_PointerOrReference))
2550 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2551 (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2552 !Right.is(TT_StartOfName)) ||
2553 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2554 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2555 tok::l_paren) &&
2556 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2557 !Line.IsMultiVariableDeclStmt) &&
2558 Left.Previous &&
2559 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2560 if (Right.is(tok::star) && Left.is(tok::l_paren))
2561 return false;
2562 const auto SpaceRequiredForArrayInitializerLSquare =
2563 [](const FormatToken &LSquareTok, const FormatStyle &Style) {
2564 return Style.SpacesInContainerLiterals ||
2565 ((Style.Language == FormatStyle::LK_Proto ||
2566 Style.Language == FormatStyle::LK_TextProto) &&
2567 !Style.Cpp11BracedListStyle &&
2568 LSquareTok.endsSequence(tok::l_square, tok::colon,
2569 TT_SelectorName));
2570 };
2571 if (Left.is(tok::l_square))
2572 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
2573 SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
2574 (Left.isOneOf(TT_ArraySubscriptLSquare,
2575 TT_StructuredBindingLSquare) &&
2576 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2577 if (Right.is(tok::r_square))
2578 return Right.MatchingParen &&
2579 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
2580 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
2581 Style)) ||
2582 (Style.SpacesInSquareBrackets &&
2583 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2584 TT_StructuredBindingLSquare)) ||
2585 Right.MatchingParen->is(TT_AttributeParen));
2586 if (Right.is(tok::l_square) &&
2587 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2588 TT_DesignatedInitializerLSquare,
2589 TT_StructuredBindingLSquare, TT_AttributeSquare) &&
2590 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2591 return false;
2592 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2593 return !Left.Children.empty(); // No spaces in "{}".
2594 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2595 (Right.is(tok::r_brace) && Right.MatchingParen &&
2596 Right.MatchingParen->BlockKind != BK_Block))
2597 return !Style.Cpp11BracedListStyle;
2598 if (Left.is(TT_BlockComment))
2599 // No whitespace in x(/*foo=*/1), except for JavaScript.
2600 return Style.Language == FormatStyle::LK_JavaScript ||
2601 !Left.TokenText.endswith("=*/");
2602 if (Right.is(tok::l_paren)) {
2603 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
2604 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
2605 return true;
2606 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2607 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2608 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2609 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2610 TT_ObjCForIn) ||
2611 Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
2612 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2613 tok::kw_new, tok::kw_delete) &&
2614 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2615 (spaceRequiredBeforeParens(Right) &&
2616 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2617 Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier() ||
2618 (Left.is(tok::r_square) && Left.MatchingParen &&
2619 Left.MatchingParen->is(TT_LambdaLSquare))) &&
2620 Line.Type != LT_PreprocessorDirective);
2621 }
2622 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2623 return false;
2624 if (Right.is(TT_UnaryOperator))
2625 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2626 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2627 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2628 tok::r_paren) ||
2629 Left.isSimpleTypeSpecifier()) &&
2630 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2631 Right.BlockKind != BK_Block)
2632 return false;
2633 if (Left.is(tok::period) || Right.is(tok::period))
2634 return false;
2635 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2636 return false;
2637 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2638 Left.MatchingParen->Previous &&
2639 (Left.MatchingParen->Previous->is(tok::period) ||
2640 Left.MatchingParen->Previous->is(tok::coloncolon)))
2641 // Java call to generic function with explicit type:
2642 // A.<B<C<...>>>DoSomething();
2643 // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference.
2644 return false;
2645 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2646 return false;
2647 if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
2648 // Objective-C dictionary literal -> no space after opening brace.
2649 return false;
2650 if (Right.is(tok::r_brace) && Right.MatchingParen &&
2651 Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
2652 // Objective-C dictionary literal -> no space before closing brace.
2653 return false;
2654 return true;
2655}
2656
2657bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2658 const FormatToken &Right) {
2659 const FormatToken &Left = *Right.Previous;
2660 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2661 return true; // Never ever merge two identifiers.
2662 if (Style.isCpp()) {
2663 if (Left.is(tok::kw_operator))
2664 return Right.is(tok::coloncolon);
2665 if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
2666 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
2667 return true;
2668 } else if (Style.Language == FormatStyle::LK_Proto ||
2669 Style.Language == FormatStyle::LK_TextProto) {
2670 if (Right.is(tok::period) &&
2671 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2672 Keywords.kw_repeated, Keywords.kw_extend))
2673 return true;
2674 if (Right.is(tok::l_paren) &&
2675 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2676 return true;
2677 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2678 return true;
2679 // Slashes occur in text protocol extension syntax: [type/type] { ... }.
2680 if (Left.is(tok::slash) || Right.is(tok::slash))
2681 return false;
2682 if (Left.MatchingParen &&
2683 Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
2684 Right.isOneOf(tok::l_brace, tok::less))
2685 return !Style.Cpp11BracedListStyle;
2686 // A percent is probably part of a formatting specification, such as %lld.
2687 if (Left.is(tok::percent))
2688 return false;
2689 // Preserve the existence of a space before a percent for cases like 0x%04x
2690 // and "%d %d"
2691 if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
2692 return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
2693 } else if (Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
2694 if (Left.is(TT_JsFatArrow))
2695 return true;
2696 // for await ( ...
2697 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
2698 Left.Previous->is(tok::kw_for))
2699 return true;
2700 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2701 Right.MatchingParen) {
2702 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2703 // An async arrow function, for example: `x = async () => foo();`,
2704 // as opposed to calling a function called async: `x = async();`
2705 if (Next && Next->is(TT_JsFatArrow))
2706 return true;
2707 }
2708 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2709 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2710 return false;
2711 // In tagged template literals ("html`bar baz`"), there is no space between
2712 // the tag identifier and the template string. getIdentifierInfo makes sure
2713 // that the identifier is not a pseudo keyword like `yield`, either.
2714 if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
2715 Right.is(TT_TemplateString))
2716 return false;
2717 if (Right.is(tok::star) &&
2718 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2719 return false;
2720 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2721 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
2722 Keywords.kw_extends, Keywords.kw_implements))
2723 return true;
2724 if (Right.is(tok::l_paren)) {
2725 // JS methods can use some keywords as names (e.g. `delete()`).
2726 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
2727 return false;
2728 // Valid JS method names can include keywords, e.g. `foo.delete()` or
2729 // `bar.instanceof()`. Recognize call positions by preceding period.
2730 if (Left.Previous && Left.Previous->is(tok::period) &&
2731 Left.Tok.getIdentifierInfo())
2732 return false;
2733 // Additional unary JavaScript operators that need a space after.
2734 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
2735 tok::kw_void))
2736 return true;
2737 }
2738 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2739 tok::kw_const) ||
2740 // "of" is only a keyword if it appears after another identifier
2741 // (e.g. as "const x of y" in a for loop), or after a destructuring
2742 // operation (const [x, y] of z, const {a, b} of c).
2743 (Left.is(Keywords.kw_of) && Left.Previous &&
2744 (Left.Previous->Tok.is(tok::identifier) ||
2745 Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
2746 (!Left.Previous || !Left.Previous->is(tok::period)))
2747 return true;
2748 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2749 Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2750 return false;
2751 if (Left.is(Keywords.kw_as) &&
2752 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2753 return true;
2754 if (Left.is(tok::kw_default) && Left.Previous &&
2755 Left.Previous->is(tok::kw_export))
2756 return true;
2757 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2758 return true;
2759 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2760 return false;
2761 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2762 return false;
2763 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2764 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2765 return false;
2766 if (Left.is(tok::ellipsis))
2767 return false;
2768 if (Left.is(TT_TemplateCloser) &&
2769 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2770 Keywords.kw_implements, Keywords.kw_extends))
2771 // Type assertions ('<type>expr') are not followed by whitespace. Other
2772 // locations that should have whitespace following are identified by the
2773 // above set of follower tokens.
2774 return false;
2775 if (Right.is(TT_JsNonNullAssertion))
2776 return false;
2777 if (Left.is(TT_JsNonNullAssertion) &&
2778 Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
2779 return true; // "x! as string", "x! in y"
2780 } else if (Style.Language == FormatStyle::LK_Java) {
2781 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2782 return true;
2783 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2784 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2785 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2786 tok::kw_protected) ||
2787 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2788 Keywords.kw_native)) &&
2789 Right.is(TT_TemplateOpener))
2790 return true;
2791 }
2792 if (Left.is(TT_ImplicitStringLiteral))
2793 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2794 if (Line.Type == LT_ObjCMethodDecl) {
2795 if (Left.is(TT_ObjCMethodSpecifier))
2796 return true;
2797 if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
2798 // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
2799 // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
2800 // method declaration.
2801 return false;
2802 }
2803 if (Line.Type == LT_ObjCProperty &&
2804 (Right.is(tok::equal) || Left.is(tok::equal)))
2805 return false;
2806
2807 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2808 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2809 return true;
2810 if (Right.is(TT_OverloadedOperatorLParen))
2811 return spaceRequiredBeforeParens(Right);
2812 if (Left.is(tok::comma))
2813 return true;
2814 if (Right.is(tok::comma))
2815 return false;
2816 if (Right.is(TT_ObjCBlockLParen))
2817 return true;
2818 if (Right.is(TT_CtorInitializerColon))
2819 return Style.SpaceBeforeCtorInitializerColon;
2820 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
2821 return false;
2822 if (Right.is(TT_RangeBasedForLoopColon) &&
2823 !Style.SpaceBeforeRangeBasedForLoopColon)
2824 return false;
2825 if (Right.is(tok::colon)) {
2826 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2827 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2828 return false;
2829 if (Right.is(TT_ObjCMethodExpr))
2830 return false;
2831 if (Left.is(tok::question))
2832 return false;
2833 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2834 return false;
2835 if (Right.is(TT_DictLiteral))
2836 return Style.SpacesInContainerLiterals;
2837 if (Right.is(TT_AttributeColon))
2838 return false;
2839 return true;
2840 }
2841 if (Left.is(TT_UnaryOperator))
2842 return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
2843 Right.is(TT_BinaryOperator);
2844
2845 // If the next token is a binary operator or a selector name, we have
2846 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2847 if (Left.is(TT_CastRParen))
2848 return Style.SpaceAfterCStyleCast ||
2849 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2850
2851 if (Left.is(tok::greater) && Right.is(tok::greater)) {
2852 if (Style.Language == FormatStyle::LK_TextProto ||
2853 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
2854 return !Style.Cpp11BracedListStyle;
2855 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2856 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2857 }
2858 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
2859 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2860 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
2861 return false;
2862 if (!Style.SpaceBeforeAssignmentOperators &&
2863 Right.getPrecedence() == prec::Assignment)
2864 return false;
2865 if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) &&
2866 (Left.is(tok::identifier) || Left.is(tok::kw_this)))
2867 return false;
2868 if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2869 // Generally don't remove existing spaces between an identifier and "::".
2870 // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2871 // this turns out to be too lenient, add analysis of the identifier itself.
2872 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2873 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2874 return (Left.is(TT_TemplateOpener) &&
2875 Style.Standard == FormatStyle::LS_Cpp03) ||
2876 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2877 tok::kw___super, TT_TemplateCloser,
2878 TT_TemplateOpener)) ||
2879 (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
2880 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2881 return Style.SpacesInAngles;
2882 // Space before TT_StructuredBindingLSquare.
2883 if (Right.is(TT_StructuredBindingLSquare))
2884 return !Left.isOneOf(tok::amp, tok::ampamp) ||
2885 Style.PointerAlignment != FormatStyle::PAS_Right;
2886 // Space before & or && following a TT_StructuredBindingLSquare.
2887 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
2888 Right.isOneOf(tok::amp, tok::ampamp))
2889 return Style.PointerAlignment != FormatStyle::PAS_Left;
2890 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2891 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2892 !Right.is(tok::r_paren)))
2893 return true;
2894 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2895 Right.isNot(TT_FunctionTypeLParen))
2896 return spaceRequiredBeforeParens(Right);
2897 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2898 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2899 return false;
2900 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2901 Line.startsWith(tok::hash))
2902 return true;
2903 if (Right.is(TT_TrailingUnaryOperator))
2904 return false;
2905 if (Left.is(TT_RegexLiteral))
2906 return false;
2907 return spaceRequiredBetween(Line, Left, Right);
2908}
2909
2910// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2911static bool isAllmanBrace(const FormatToken &Tok) {
2912 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2913 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
2914}
2915
2916bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2917 const FormatToken &Right) {
2918 const FormatToken &Left = *Right.Previous;
2919 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2920 return true;
2921
2922 if (Style.Language == FormatStyle::LK_JavaScript) {
2923 // FIXME: This might apply to other languages and token kinds.
2924 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2925 Left.Previous->is(tok::string_literal))
2926 return true;
2927 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2928 Left.Previous && Left.Previous->is(tok::equal) &&
2929 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2930 tok::kw_const) &&
2931 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2932 // above.
2933 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2934 // Object literals on the top level of a file are treated as "enum-style".
2935 // Each key/value pair is put on a separate line, instead of bin-packing.
2936 return true;
2937 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2938 (Line.startsWith(tok::kw_enum) ||
2939 Line.startsWith(tok::kw_const, tok::kw_enum) ||
2940 Line.startsWith(tok::kw_export, tok::kw_enum) ||
2941 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
2942 // JavaScript top-level enum key/value pairs are put on separate lines
2943 // instead of bin-packing.
2944 return true;
2945 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2946 !Left.Children.empty())
2947 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2948 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2949 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2950 (Left.NestingLevel == 0 && Line.Level == 0 &&
2951 Style.AllowShortFunctionsOnASingleLine &
2952 FormatStyle::SFS_InlineOnly);
2953 } else if (Style.Language == FormatStyle::LK_Java) {
2954 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2955 Right.Next->is(tok::string_literal))
2956 return true;
2957 } else if (Style.Language == FormatStyle::LK_Cpp ||
2958 Style.Language == FormatStyle::LK_ObjC ||
2959 Style.Language == FormatStyle::LK_Proto ||
2960 Style.Language == FormatStyle::LK_TableGen ||
2961 Style.Language == FormatStyle::LK_TextProto) {
2962 if (Left.isStringLiteral() && Right.isStringLiteral())
2963 return true;
2964 }
2965
2966 // If the last token before a '}', ']', or ')' is a comma or a trailing
2967 // comment, the intention is to insert a line break after it in order to make
2968 // shuffling around entries easier. Import statements, especially in
2969 // JavaScript, can be an exception to this rule.
2970 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
2971 const FormatToken *BeforeClosingBrace = nullptr;
2972 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2973 (Style.Language == FormatStyle::LK_JavaScript &&
2974 Left.is(tok::l_paren))) &&
2975 Left.BlockKind != BK_Block && Left.MatchingParen)
2976 BeforeClosingBrace = Left.MatchingParen->Previous;
2977 else if (Right.MatchingParen &&
2978 (Right.MatchingParen->isOneOf(tok::l_brace,
2979 TT_ArrayInitializerLSquare) ||
2980 (Style.Language == FormatStyle::LK_JavaScript &&
2981 Right.MatchingParen->is(tok::l_paren))))
2982 BeforeClosingBrace = &Left;
2983 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2984 BeforeClosingBrace->isTrailingComment()))
2985 return true;
2986 }
2987
2988 if (Right.is(tok::comment))
2989 return Left.BlockKind != BK_BracedInit &&
2990 Left.isNot(TT_CtorInitializerColon) &&
2991 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2992 if (Left.isTrailingComment())
2993 return true;
2994 if (Right.Previous->IsUnterminatedLiteral)
2995 return true;
2996 if (Right.is(tok::lessless) && Right.Next &&
2997 Right.Previous->is(tok::string_literal) &&
2998 Right.Next->is(tok::string_literal))
2999 return true;
3000 if (Right.Previous->ClosesTemplateDeclaration &&
3001 Right.Previous->MatchingParen &&
3002 Right.Previous->MatchingParen->NestingLevel == 0 &&
3003 Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
3004 return true;
3005 if (Right.is(TT_CtorInitializerComma) &&
3006 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3007 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
3008 return true;
3009 if (Right.is(TT_CtorInitializerColon) &&
3010 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3011 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
3012 return true;
3013 // Break only if we have multiple inheritance.
3014 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
3015 Right.is(TT_InheritanceComma))
3016 return true;
3017 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
3018 // Multiline raw string literals are special wrt. line breaks. The author
3019 // has made a deliberate choice and might have aligned the contents of the
3020 // string literal accordingly. Thus, we try keep existing line breaks.
3021 return Right.IsMultiline && Right.NewlinesBefore > 0;
3022 if ((Right.Previous->is(tok::l_brace) ||
3023 (Right.Previous->is(tok::less) && Right.Previous->Previous &&
3024 Right.Previous->Previous->is(tok::equal))) &&
3025 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
3026 // Don't put enums or option definitions onto single lines in protocol
3027 // buffers.
3028 return true;
3029 }
3030 if (Right.is(TT_InlineASMBrace))
3031 return Right.HasUnescapedNewline;
3032 if (isAllmanBrace(Left) || isAllmanBrace(Right))
3033 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
3034 (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
3035 Style.BraceWrapping.AfterEnum) ||
3036 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
3037 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
3038 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
3039 return true;
3040
3041 if (Left.is(TT_LambdaLBrace)) {
3042 if (Left.MatchingParen && Left.MatchingParen->Next &&
3043 Left.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren) &&
3044 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
3045 return false;
3046
3047 if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
3048 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
3049 (!Left.Children.empty() &&
3050 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty))
3051 return true;
3052 }
3053
3054 // Put multiple C# attributes on a new line.
3055 if (Style.isCSharp() &&
3056 ((Left.is(TT_AttributeSquare) && Left.is(tok::r_square)) ||
3057 (Left.is(tok::r_square) && Right.is(TT_AttributeSquare) &&
3058 Right.is(tok::l_square))))
3059 return true;
3060
3061 // Put multiple Java annotation on a new line.
3062 if ((Style.Language == FormatStyle::LK_Java ||
3063 Style.Language == FormatStyle::LK_JavaScript) &&
3064 Left.is(TT_LeadingJavaAnnotation) &&
3065 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
3066 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
3067 return true;
3068
3069 if (Right.is(TT_ProtoExtensionLSquare))
3070 return true;
3071
3072 // In text proto instances if a submessage contains at least 2 entries and at
3073 // least one of them is a submessage, like A { ... B { ... } ... },
3074 // put all of the entries of A on separate lines by forcing the selector of
3075 // the submessage B to be put on a newline.
3076 //
3077 // Example: these can stay on one line:
3078 // a { scalar_1: 1 scalar_2: 2 }
3079 // a { b { key: value } }
3080 //
3081 // and these entries need to be on a new line even if putting them all in one
3082 // line is under the column limit:
3083 // a {
3084 // scalar: 1
3085 // b { key: value }
3086 // }
3087 //
3088 // We enforce this by breaking before a submessage field that has previous
3089 // siblings, *and* breaking before a field that follows a submessage field.
3090 //
3091 // Be careful to exclude the case [proto.ext] { ... } since the `]` is
3092 // the TT_SelectorName there, but we don't want to break inside the brackets.
3093 //
3094 // Another edge case is @submessage { key: value }, which is a common
3095 // substitution placeholder. In this case we want to keep `@` and `submessage`
3096 // together.
3097 //
3098 // We ensure elsewhere that extensions are always on their own line.
3099 if ((Style.Language == FormatStyle::LK_Proto ||
3100 Style.Language == FormatStyle::LK_TextProto) &&
3101 Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
3102 // Keep `@submessage` together in:
3103 // @submessage { key: value }
3104 if (Right.Previous && Right.Previous->is(tok::at))
3105 return false;
3106 // Look for the scope opener after selector in cases like:
3107 // selector { ...
3108 // selector: { ...
3109 // selector: @base { ...
3110 FormatToken *LBrace = Right.Next;
3111 if (LBrace && LBrace->is(tok::colon)) {
3112 LBrace = LBrace->Next;
3113 if (LBrace && LBrace->is(tok::at)) {
3114 LBrace = LBrace->Next;
3115 if (LBrace)
3116 LBrace = LBrace->Next;
3117 }
3118 }
3119 if (LBrace &&
3120 // The scope opener is one of {, [, <:
3121 // selector { ... }
3122 // selector [ ... ]
3123 // selector < ... >
3124 //
3125 // In case of selector { ... }, the l_brace is TT_DictLiteral.
3126 // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
3127 // so we check for immediately following r_brace.
3128 ((LBrace->is(tok::l_brace) &&
3129 (LBrace->is(TT_DictLiteral) ||
3130 (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
3131 LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
3132 // If Left.ParameterCount is 0, then this submessage entry is not the
3133 // first in its parent submessage, and we want to break before this entry.
3134 // If Left.ParameterCount is greater than 0, then its parent submessage
3135 // might contain 1 or more entries and we want to break before this entry
3136 // if it contains at least 2 entries. We deal with this case later by
3137 // detecting and breaking before the next entry in the parent submessage.
3138 if (Left.ParameterCount == 0)
3139 return true;
3140 // However, if this submessage is the first entry in its parent
3141 // submessage, Left.ParameterCount might be 1 in some cases.
3142 // We deal with this case later by detecting an entry
3143 // following a closing paren of this submessage.
3144 }
3145
3146 // If this is an entry immediately following a submessage, it will be
3147 // preceded by a closing paren of that submessage, like in:
3148 // left---. .---right
3149 // v v
3150 // sub: { ... } key: value
3151 // If there was a comment between `}` an `key` above, then `key` would be
3152 // put on a new line anyways.
3153 if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
3154 return true;
3155 }
3156
3157 // Deal with lambda arguments in C++ - we want consistent line breaks whether
3158 // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
3159 // as aggressive line breaks are placed when the lambda is not the last arg.
3160 if ((Style.Language == FormatStyle::LK_Cpp ||
3161 Style.Language == FormatStyle::LK_ObjC) &&
3162 Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
3163 !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
3164 // Multiple lambdas in the same function call force line breaks.
3165 if (Left.BlockParameterCount > 1)
3166 return true;
3167
3168 // A lambda followed by another arg forces a line break.
3169 if (!Left.Role)
3170 return false;
3171 auto Comma = Left.Role->lastComma();
3172 if (!Comma)
3173 return false;
3174 auto Next = Comma->getNextNonComment();
3175 if (!Next)
3176 return false;
3177 if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
3178 return true;
3179 }
3180
3181 return false;
3182}
3183
3184bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
3185 const FormatToken &Right) {
3186 const FormatToken &Left = *Right.Previous;
3187
3188 // Language-specific stuff.
3189 if (Style.Language == FormatStyle::LK_Java) {
3190 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3191 Keywords.kw_implements))
3192 return false;
3193 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3194 Keywords.kw_implements))
3195 return true;
3196 } else if (Style.Language == FormatStyle::LK_JavaScript) {
3197 const FormatToken *NonComment = Right.getPreviousNonComment();
3198 if (NonComment &&
3199 NonComment->isOneOf(
3200 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
3201 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
3202 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
3203 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
3204 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
3205 return false; // Otherwise automatic semicolon insertion would trigger.
3206 if (Right.NestingLevel == 0 &&
3207 (Left.Tok.getIdentifierInfo() ||
3208 Left.isOneOf(tok::r_square, tok::r_paren)) &&
3209 Right.isOneOf(tok::l_square, tok::l_paren))
3210 return false; // Otherwise automatic semicolon insertion would trigger.
3211 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
3212 return false;
3213 if (Left.is(TT_JsTypeColon))
3214 return true;
3215 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
3216 if (Left.is(tok::exclaim) && Right.is(tok::colon))
3217 return false;
3218 // Look for is type annotations like:
3219 // function f(): a is B { ... }
3220 // Do not break before is in these cases.
3221 if (Right.is(Keywords.kw_is)) {
3222 const FormatToken *Next = Right.getNextNonComment();
3223 // If `is` is followed by a colon, it's likely that it's a dict key, so
3224 // ignore it for this check.
3225 // For example this is common in Polymer:
3226 // Polymer({
3227 // is: 'name',
3228 // ...
3229 // });
3230 if (!Next || !Next->is(tok::colon))
3231 return false;
3232 }
3233 if (Left.is(Keywords.kw_in))
3234 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
3235 if (Right.is(Keywords.kw_in))
3236 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
3237 if (Right.is(Keywords.kw_as))
3238 return false; // must not break before as in 'x as type' casts
3239 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
3240 // extends and infer can appear as keywords in conditional types:
3241 // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
3242 // do not break before them, as the expressions are subject to ASI.
3243 return false;
3244 }
3245 if (Left.is(Keywords.kw_as))
3246 return true;
3247 if (Left.is(TT_JsNonNullAssertion))
3248 return true;
3249 if (Left.is(Keywords.kw_declare) &&
3250 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
3251 Keywords.kw_function, tok::kw_class, tok::kw_enum,
3252 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
3253 Keywords.kw_let, tok::kw_const))
3254 // See grammar for 'declare' statements at:
3255 // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
3256 return false;
3257 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
3258 Right.isOneOf(tok::identifier, tok::string_literal))
3259 return false; // must not break in "module foo { ...}"
3260 if (Right.is(TT_TemplateString) && Right.closesScope())
3261 return false;
3262 // Don't split tagged template literal so there is a break between the tag
3263 // identifier and template string.
3264 if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) {
3265 return false;
3266 }
3267 if (Left.is(TT_TemplateString) && Left.opensScope())
3268 return true;
3269 }
3270
3271 if (Left.is(tok::at))
3272 return false;
3273 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
3274 return false;
3275 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
3276 return !Right.is(tok::l_paren);
3277 if (Right.is(TT_PointerOrReference))
3278 return Line.IsMultiVariableDeclStmt ||
3279 (Style.PointerAlignment == FormatStyle::PAS_Right &&
3280 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
3281 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
3282 Right.is(tok::kw_operator))
3283 return true;
3284 if (Left.is(TT_PointerOrReference))
3285 return false;
3286 if (Right.isTrailingComment())
3287 // We rely on MustBreakBefore being set correctly here as we should not
3288 // change the "binding" behavior of a comment.
3289 // The first comment in a braced lists is always interpreted as belonging to
3290 // the first list element. Otherwise, it should be placed outside of the
3291 // list.
3292 return Left.BlockKind == BK_BracedInit ||
3293 (Left.is(TT_CtorInitializerColon) &&
3294 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
3295 if (Left.is(tok::question) && Right.is(tok::colon))
3296 return false;
3297 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
3298 return Style.BreakBeforeTernaryOperators;
3299 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
3300 return !Style.BreakBeforeTernaryOperators;
3301 if (Left.is(TT_InheritanceColon))
3302 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
3303 if (Right.is(TT_InheritanceColon))
3304 return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
3305 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
3306 Left.isNot(TT_SelectorName))
3307 return true;
3308
3309 if (Right.is(tok::colon) &&
3310 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
3311 return false;
3312 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
3313 if (Style.Language == FormatStyle::LK_Proto ||
3314 Style.Language == FormatStyle::LK_TextProto) {
3315 if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
3316 return false;
3317 // Prevent cases like:
3318 //
3319 // submessage:
3320 // { key: valueeeeeeeeeeee }
3321 //
3322 // when the snippet does not fit into one line.
3323 // Prefer:
3324 //
3325 // submessage: {
3326 // key: valueeeeeeeeeeee
3327 // }
3328 //
3329 // instead, even if it is longer by one line.
3330 //
3331 // Note that this allows allows the "{" to go over the column limit
3332 // when the column limit is just between ":" and "{", but that does
3333 // not happen too often and alternative formattings in this case are
3334 // not much better.
3335 //
3336 // The code covers the cases:
3337 //
3338 // submessage: { ... }
3339 // submessage: < ... >
3340 // repeated: [ ... ]
3341 if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
3342 Right.is(TT_DictLiteral)) ||
3343 Right.is(TT_ArrayInitializerLSquare))
3344 return false;
3345 }
3346 return true;
3347 }
3348 if (Right.is(tok::r_square) && Right.MatchingParen &&
3349 Right.MatchingParen->is(TT_ProtoExtensionLSquare))
3350 return false;
3351 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
3352 Right.Next->is(TT_ObjCMethodExpr)))
3353 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
3354 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
3355 return true;
3356 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
3357 return true;
3358 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
3359 TT_OverloadedOperator))
3360 return false;
3361 if (Left.is(TT_RangeBasedForLoopColon))
3362 return true;
3363 if (Right.is(TT_RangeBasedForLoopColon))
3364 return false;
3365 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
3366 return true;
3367 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
3368 Left.is(tok::kw_operator))
3369 return false;
3370 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
3371 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
3372 return false;
3373 if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
3374 !Style.Cpp11BracedListStyle)
3375 return false;
3376 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
3377 return false;
3378 if (Left.is(tok::l_paren) && Left.Previous &&
3379 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
3380 return false;
3381 if (Right.is(TT_ImplicitStringLiteral))
3382 return false;
3383
3384 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
3385 return false;
3386 if (Right.is(tok::r_square) && Right.MatchingParen &&
3387 Right.MatchingParen->is(TT_LambdaLSquare))
3388 return false;
3389
3390 // We only break before r_brace if there was a corresponding break before
3391 // the l_brace, which is tracked by BreakBeforeClosingBrace.
3392 if (Right.is(tok::r_brace))
3393 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
3394
3395 // Allow breaking after a trailing annotation, e.g. after a method
3396 // declaration.
3397 if (Left.is(TT_TrailingAnnotation))
3398 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
3399 tok::less, tok::coloncolon);
3400
3401 if (Right.is(tok::kw___attribute) ||
3402 (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
3403 return true;
3404
3405 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
3406 return true;
3407
3408 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
3409 return true;
3410
3411 if (Left.is(TT_CtorInitializerColon))
3412 return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
3413 if (Right.is(TT_CtorInitializerColon))
3414 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
3415 if (Left.is(TT_CtorInitializerComma) &&
3416 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3417 return false;
3418 if (Right.is(TT_CtorInitializerComma) &&
3419 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3420 return true;
3421 if (Left.is(TT_InheritanceComma) &&
3422 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3423 return false;
3424 if (Right.is(TT_InheritanceComma) &&
3425 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3426 return true;
3427 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
3428 (Left.is(tok::less) && Right.is(tok::less)))
3429 return false;
3430 if (Right.is(TT_BinaryOperator) &&
3431 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
3432 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
3433 Right.getPrecedence() != prec::Assignment))
3434 return true;
3435 if (Left.is(TT_ArrayInitializerLSquare))
3436 return true;
3437 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
3438 return true;
3439 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
3440 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
3441 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
3442 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
3443 Left.getPrecedence() == prec::Assignment))
3444 return true;
3445 if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
3446 (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
3447 return false;
3448 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
3449 tok::kw_class, tok::kw_struct, tok::comment) ||
3450 Right.isMemberAccess() ||
3451 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
3452 tok::colon, tok::l_square, tok::at) ||
3453 (Left.is(tok::r_paren) &&
3454 Right.isOneOf(tok::identifier, tok::kw_const)) ||
3455 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
3456 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
3457}
3458
3459void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
3460 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
3461 const FormatToken *Tok = Line.First;
3462 while (Tok) {
3463 llvm::errs() << " M=" << Tok->MustBreakBefore
3464 << " C=" << Tok->CanBreakBefore
3465 << " T=" << getTokenTypeName(Tok->Type)
3466 << " S=" << Tok->SpacesRequiredBefore
3467 << " B=" << Tok->BlockParameterCount
3468 << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
3469 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
3470 << " PPK=" << Tok->PackingKind << " FakeLParens=";
3471 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
3472 llvm::errs() << Tok->FakeLParens[i] << "/";
3473 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
3474 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
3475 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
3476 if (!Tok->Next)
3477 assert(Tok == Line.Last)((Tok == Line.Last) ? static_cast<void> (0) : __assert_fail
("Tok == Line.Last", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Format/TokenAnnotator.cpp"
, 3477, __PRETTY_FUNCTION__))
;
3478 Tok = Tok->Next;
3479 }
3480 llvm::errs() << "----\n";
3481}
3482
3483} // namespace format
3484} // namespace clang