forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTokenAnnotator.cpp
6372 lines (5944 loc) · 239 KB
/
TokenAnnotator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements a token annotator, i.e. creates
/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
///
//===----------------------------------------------------------------------===//
#include "TokenAnnotator.h"
#include "FormatToken.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "format-token-annotator"
namespace clang {
namespace format {
static bool mustBreakAfterAttributes(const FormatToken &Tok,
const FormatStyle &Style) {
switch (Style.BreakAfterAttributes) {
case FormatStyle::ABS_Always:
return true;
case FormatStyle::ABS_Leave:
return Tok.NewlinesBefore > 0;
default:
return false;
}
}
namespace {
/// Returns \c true if the line starts with a token that can start a statement
/// with an initializer.
static bool startsWithInitStatement(const AnnotatedLine &Line) {
return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) ||
Line.startsWith(tok::kw_switch);
}
/// Returns \c true if the token can be used as an identifier in
/// an Objective-C \c \@selector, \c false otherwise.
///
/// Because getFormattingLangOpts() always lexes source code as
/// Objective-C++, C++ keywords like \c new and \c delete are
/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
///
/// For Objective-C and Objective-C++, both identifiers and keywords
/// are valid inside @selector(...) (or a macro which
/// invokes @selector(...)). So, we allow treat any identifier or
/// keyword as a potential Objective-C selector component.
static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
return Tok.Tok.getIdentifierInfo();
}
/// With `Left` being '(', check if we're at either `[...](` or
/// `[...]<...>(`, where the [ opens a lambda capture list.
static bool isLambdaParameterList(const FormatToken *Left) {
// Skip <...> if present.
if (Left->Previous && Left->Previous->is(tok::greater) &&
Left->Previous->MatchingParen &&
Left->Previous->MatchingParen->is(TT_TemplateOpener)) {
Left = Left->Previous->MatchingParen;
}
// Check for `[...]`.
return Left->Previous && Left->Previous->is(tok::r_square) &&
Left->Previous->MatchingParen &&
Left->Previous->MatchingParen->is(TT_LambdaLSquare);
}
/// Returns \c true if the token is followed by a boolean condition, \c false
/// otherwise.
static bool isKeywordWithCondition(const FormatToken &Tok) {
return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
tok::kw_constexpr, tok::kw_catch);
}
/// Returns \c true if the token starts a C++ attribute, \c false otherwise.
static bool isCppAttribute(bool IsCpp, const FormatToken &Tok) {
if (!IsCpp || !Tok.startsSequence(tok::l_square, tok::l_square))
return false;
// The first square bracket is part of an ObjC array literal
if (Tok.Previous && Tok.Previous->is(tok::at))
return false;
const FormatToken *AttrTok = Tok.Next->Next;
if (!AttrTok)
return false;
// C++17 '[[using ns: foo, bar(baz, blech)]]'
// We assume nobody will name an ObjC variable 'using'.
if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
return true;
if (AttrTok->isNot(tok::identifier))
return false;
while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
// ObjC message send. We assume nobody will use : in a C++11 attribute
// specifier parameter, although this is technically valid:
// [[foo(:)]].
if (AttrTok->is(tok::colon) ||
AttrTok->startsSequence(tok::identifier, tok::identifier) ||
AttrTok->startsSequence(tok::r_paren, tok::identifier)) {
return false;
}
if (AttrTok->is(tok::ellipsis))
return true;
AttrTok = AttrTok->Next;
}
return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
}
/// A parser that gathers additional information about tokens.
///
/// The \c TokenAnnotator tries to match parenthesis and square brakets and
/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
/// into template parameter lists.
class AnnotatingParser {
public:
AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
const AdditionalKeywords &Keywords,
SmallVector<ScopeType> &Scopes)
: Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
IsCpp(Style.isCpp()), LangOpts(getFormattingLangOpts(Style)),
Keywords(Keywords), Scopes(Scopes), TemplateDeclarationDepth(0) {
assert(IsCpp == LangOpts.CXXOperatorNames);
Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
resetTokenMetadata();
}
private:
ScopeType getScopeType(const FormatToken &Token) const {
switch (Token.getType()) {
case TT_FunctionLBrace:
case TT_LambdaLBrace:
return ST_Function;
case TT_ClassLBrace:
case TT_StructLBrace:
case TT_UnionLBrace:
return ST_Class;
default:
return ST_Other;
}
}
bool parseAngle() {
if (!CurrentToken || !CurrentToken->Previous)
return false;
if (NonTemplateLess.count(CurrentToken->Previous) > 0)
return false;
if (const auto &Previous = *CurrentToken->Previous; // The '<'.
Previous.Previous) {
if (Previous.Previous->Tok.isLiteral())
return false;
if (Previous.Previous->is(tok::r_brace))
return false;
if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
(!Previous.Previous->MatchingParen ||
Previous.Previous->MatchingParen->isNot(
TT_OverloadedOperatorLParen))) {
return false;
}
if (Previous.Previous->is(tok::kw_operator) &&
CurrentToken->is(tok::l_paren)) {
return false;
}
}
FormatToken *Left = CurrentToken->Previous;
Left->ParentBracket = Contexts.back().ContextKind;
ScopedContextCreator ContextCreator(*this, tok::less, 12);
Contexts.back().IsExpression = false;
const auto *BeforeLess = Left->Previous;
// If there's a template keyword before the opening angle bracket, this is a
// template parameter, not an argument.
if (BeforeLess && BeforeLess->isNot(tok::kw_template))
Contexts.back().ContextType = Context::TemplateArgument;
if (Style.Language == FormatStyle::LK_Java &&
CurrentToken->is(tok::question)) {
next();
}
for (bool SeenTernaryOperator = false; CurrentToken;) {
const bool InExpr = Contexts[Contexts.size() - 2].IsExpression;
if (CurrentToken->is(tok::greater)) {
const auto *Next = CurrentToken->Next;
// Try to do a better job at looking for ">>" within the condition of
// a statement. Conservatively insert spaces between consecutive ">"
// tokens to prevent splitting right bitshift operators and potentially
// altering program semantics. This check is overly conservative and
// will prevent spaces from being inserted in select nested template
// parameter cases, but should not alter program semantics.
if (Next && Next->is(tok::greater) &&
Left->ParentBracket != tok::less &&
CurrentToken->getStartOfNonWhitespace() ==
Next->getStartOfNonWhitespace().getLocWithOffset(-1)) {
return false;
}
if (InExpr && SeenTernaryOperator &&
(!Next || !Next->isOneOf(tok::l_paren, tok::l_brace))) {
return false;
}
Left->MatchingParen = CurrentToken;
CurrentToken->MatchingParen = Left;
// In TT_Proto, we must distignuish between:
// map<key, value>
// msg < item: data >
// msg: < item: data >
// In TT_TextProto, map<key, value> does not occur.
if (Style.Language == FormatStyle::LK_TextProto ||
(Style.Language == FormatStyle::LK_Proto && BeforeLess &&
BeforeLess->isOneOf(TT_SelectorName, TT_DictLiteral))) {
CurrentToken->setType(TT_DictLiteral);
} else {
CurrentToken->setType(TT_TemplateCloser);
CurrentToken->Tok.setLength(1);
}
if (Next && Next->Tok.isLiteral())
return false;
next();
return true;
}
if (CurrentToken->is(tok::question) &&
Style.Language == FormatStyle::LK_Java) {
next();
continue;
}
if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
return false;
const auto &Prev = *CurrentToken->Previous;
// If a && or || is found and interpreted as a binary operator, this set
// of angles is likely part of something like "a < b && c > d". If the
// angles are inside an expression, the ||/&& might also be a binary
// operator that was misinterpreted because we are parsing template
// parameters.
// FIXME: This is getting out of hand, write a decent parser.
if (InExpr && !Line.startsWith(tok::kw_template) &&
Prev.is(TT_BinaryOperator)) {
const auto Precedence = Prev.getPrecedence();
if (Precedence > prec::Conditional && Precedence < prec::Relational)
return false;
}
if (Prev.isOneOf(tok::question, tok::colon) && !Style.isProto())
SeenTernaryOperator = true;
updateParameterCount(Left, CurrentToken);
if (Style.Language == FormatStyle::LK_Proto) {
if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
if (CurrentToken->is(tok::colon) ||
(CurrentToken->isOneOf(tok::l_brace, tok::less) &&
Previous->isNot(tok::colon))) {
Previous->setType(TT_SelectorName);
}
}
}
if (Style.isTableGen()) {
if (CurrentToken->isOneOf(tok::comma, tok::equal)) {
// They appear as separators. Unless they are not in class definition.
next();
continue;
}
// In angle, there must be Value like tokens. Types are also able to be
// parsed in the same way with Values.
if (!parseTableGenValue())
return false;
continue;
}
if (!consumeToken())
return false;
}
return false;
}
bool parseUntouchableParens() {
while (CurrentToken) {
CurrentToken->Finalized = true;
switch (CurrentToken->Tok.getKind()) {
case tok::l_paren:
next();
if (!parseUntouchableParens())
return false;
continue;
case tok::r_paren:
next();
return true;
default:
// no-op
break;
}
next();
}
return false;
}
bool parseParens(bool LookForDecls = false) {
if (!CurrentToken)
return false;
assert(CurrentToken->Previous && "Unknown previous token");
FormatToken &OpeningParen = *CurrentToken->Previous;
assert(OpeningParen.is(tok::l_paren));
FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
OpeningParen.ParentBracket = Contexts.back().ContextKind;
ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
// FIXME: This is a bit of a hack. Do better.
Contexts.back().ColonIsForRangeExpr =
Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
OpeningParen.Finalized = true;
return parseUntouchableParens();
}
bool StartsObjCMethodExpr = false;
if (!Style.isVerilog()) {
if (FormatToken *MaybeSel = OpeningParen.Previous) {
// @selector( starts a selector.
if (MaybeSel->isObjCAtKeyword(tok::objc_selector) &&
MaybeSel->Previous && MaybeSel->Previous->is(tok::at)) {
StartsObjCMethodExpr = true;
}
}
}
if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
// Find the previous kw_operator token.
FormatToken *Prev = &OpeningParen;
while (Prev->isNot(tok::kw_operator)) {
Prev = Prev->Previous;
assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
}
// If faced with "a.operator*(argument)" or "a->operator*(argument)",
// i.e. the operator is called as a member function,
// then the argument must be an expression.
bool OperatorCalledAsMemberFunction =
Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow);
Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
} else if (OpeningParen.is(TT_VerilogInstancePortLParen)) {
Contexts.back().IsExpression = true;
Contexts.back().ContextType = Context::VerilogInstancePortList;
} else if (Style.isJavaScript() &&
(Line.startsWith(Keywords.kw_type, tok::identifier) ||
Line.startsWith(tok::kw_export, Keywords.kw_type,
tok::identifier))) {
// type X = (...);
// export type X = (...);
Contexts.back().IsExpression = false;
} else if (OpeningParen.Previous &&
(OpeningParen.Previous->isOneOf(
tok::kw_static_assert, tok::kw_noexcept, tok::kw_explicit,
tok::kw_while, tok::l_paren, tok::comma,
TT_BinaryOperator) ||
OpeningParen.Previous->isIf())) {
// static_assert, if and while usually contain expressions.
Contexts.back().IsExpression = true;
} else if (Style.isJavaScript() && OpeningParen.Previous &&
(OpeningParen.Previous->is(Keywords.kw_function) ||
(OpeningParen.Previous->endsSequence(tok::identifier,
Keywords.kw_function)))) {
// function(...) or function f(...)
Contexts.back().IsExpression = false;
} else if (Style.isJavaScript() && OpeningParen.Previous &&
OpeningParen.Previous->is(TT_JsTypeColon)) {
// let x: (SomeType);
Contexts.back().IsExpression = false;
} else if (isLambdaParameterList(&OpeningParen)) {
// This is a parameter list of a lambda expression.
Contexts.back().IsExpression = false;
} else if (OpeningParen.is(TT_RequiresExpressionLParen)) {
Contexts.back().IsExpression = false;
} else if (OpeningParen.Previous &&
OpeningParen.Previous->is(tok::kw__Generic)) {
Contexts.back().ContextType = Context::C11GenericSelection;
Contexts.back().IsExpression = true;
} else if (Line.InPPDirective &&
(!OpeningParen.Previous ||
OpeningParen.Previous->isNot(tok::identifier))) {
Contexts.back().IsExpression = true;
} else if (Contexts[Contexts.size() - 2].CaretFound) {
// This is the parameter list of an ObjC block.
Contexts.back().IsExpression = false;
} else if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_ForEachMacro)) {
// The first argument to a foreach macro is a declaration.
Contexts.back().ContextType = Context::ForEachMacro;
Contexts.back().IsExpression = false;
} else if (OpeningParen.Previous && OpeningParen.Previous->MatchingParen &&
OpeningParen.Previous->MatchingParen->isOneOf(
TT_ObjCBlockLParen, TT_FunctionTypeLParen)) {
Contexts.back().IsExpression = false;
} else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
bool IsForOrCatch =
OpeningParen.Previous &&
OpeningParen.Previous->isOneOf(tok::kw_for, tok::kw_catch);
Contexts.back().IsExpression = !IsForOrCatch;
}
if (Style.isTableGen()) {
if (FormatToken *Prev = OpeningParen.Previous) {
if (Prev->is(TT_TableGenCondOperator)) {
Contexts.back().IsTableGenCondOpe = true;
Contexts.back().IsExpression = true;
} else if (Contexts.size() > 1 &&
Contexts[Contexts.size() - 2].IsTableGenBangOpe) {
// Hack to handle bang operators. The parent context's flag
// was set by parseTableGenSimpleValue().
// We have to specify the context outside because the prev of "(" may
// be ">", not the bang operator in this case.
Contexts.back().IsTableGenBangOpe = true;
Contexts.back().IsExpression = true;
} else {
// Otherwise, this paren seems DAGArg.
if (!parseTableGenDAGArg())
return false;
return parseTableGenDAGArgAndList(&OpeningParen);
}
}
}
// Infer the role of the l_paren based on the previous token if we haven't
// detected one yet.
if (PrevNonComment && OpeningParen.is(TT_Unknown)) {
if (PrevNonComment->isAttribute()) {
OpeningParen.setType(TT_AttributeLParen);
} else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
tok::kw_typeof,
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
#include "clang/Basic/TransformTypeTraits.def"
tok::kw__Atomic)) {
OpeningParen.setType(TT_TypeDeclarationParen);
// decltype() and typeof() usually contain expressions.
if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
Contexts.back().IsExpression = true;
}
}
if (StartsObjCMethodExpr) {
Contexts.back().ColonIsObjCMethodExpr = true;
OpeningParen.setType(TT_ObjCMethodExpr);
}
// MightBeFunctionType and ProbablyFunctionType are used for
// function pointer and reference types as well as Objective-C
// block types:
//
// void (*FunctionPointer)(void);
// void (&FunctionReference)(void);
// void (&&FunctionReference)(void);
// void (^ObjCBlock)(void);
bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
bool ProbablyFunctionType =
CurrentToken->isPointerOrReference() || CurrentToken->is(tok::caret);
bool HasMultipleLines = false;
bool HasMultipleParametersOnALine = false;
bool MightBeObjCForRangeLoop =
OpeningParen.Previous && OpeningParen.Previous->is(tok::kw_for);
FormatToken *PossibleObjCForInToken = nullptr;
while (CurrentToken) {
// LookForDecls is set when "if (" has been seen. Check for
// 'identifier' '*' 'identifier' followed by not '=' -- this
// '*' has to be a binary operator but determineStarAmpUsage() will
// categorize it as an unary operator, so set the right type here.
if (LookForDecls && CurrentToken->Next) {
FormatToken *Prev = CurrentToken->getPreviousNonComment();
if (Prev) {
FormatToken *PrevPrev = Prev->getPreviousNonComment();
FormatToken *Next = CurrentToken->Next;
if (PrevPrev && PrevPrev->is(tok::identifier) &&
PrevPrev->isNot(TT_TypeName) && Prev->isPointerOrReference() &&
CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
Prev->setType(TT_BinaryOperator);
LookForDecls = false;
}
}
}
if (CurrentToken->Previous->is(TT_PointerOrReference) &&
CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
tok::coloncolon)) {
ProbablyFunctionType = true;
}
if (CurrentToken->is(tok::comma))
MightBeFunctionType = false;
if (CurrentToken->Previous->is(TT_BinaryOperator))
Contexts.back().IsExpression = true;
if (CurrentToken->is(tok::r_paren)) {
if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType &&
ProbablyFunctionType && CurrentToken->Next &&
(CurrentToken->Next->is(tok::l_paren) ||
(CurrentToken->Next->is(tok::l_square) &&
Line.MustBeDeclaration))) {
OpeningParen.setType(OpeningParen.Next->is(tok::caret)
? TT_ObjCBlockLParen
: TT_FunctionTypeLParen);
}
OpeningParen.MatchingParen = CurrentToken;
CurrentToken->MatchingParen = &OpeningParen;
if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
OpeningParen.Previous && OpeningParen.Previous->is(tok::l_paren)) {
// Detect the case where macros are used to generate lambdas or
// function bodies, e.g.:
// auto my_lambda = MACRO((Type *type, int i) { .. body .. });
for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken;
Tok = Tok->Next) {
if (Tok->is(TT_BinaryOperator) && Tok->isPointerOrReference())
Tok->setType(TT_PointerOrReference);
}
}
if (StartsObjCMethodExpr) {
CurrentToken->setType(TT_ObjCMethodExpr);
if (Contexts.back().FirstObjCSelectorName) {
Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
Contexts.back().LongestObjCSelectorName;
}
}
if (OpeningParen.is(TT_AttributeLParen))
CurrentToken->setType(TT_AttributeRParen);
if (OpeningParen.is(TT_TypeDeclarationParen))
CurrentToken->setType(TT_TypeDeclarationParen);
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_JavaAnnotation)) {
CurrentToken->setType(TT_JavaAnnotation);
}
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) {
CurrentToken->setType(TT_LeadingJavaAnnotation);
}
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_AttributeSquare)) {
CurrentToken->setType(TT_AttributeSquare);
}
if (!HasMultipleLines)
OpeningParen.setPackingKind(PPK_Inconclusive);
else if (HasMultipleParametersOnALine)
OpeningParen.setPackingKind(PPK_BinPacked);
else
OpeningParen.setPackingKind(PPK_OnePerLine);
next();
return true;
}
if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
return false;
if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen))
OpeningParen.setType(TT_Unknown);
if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
!CurrentToken->Next->HasUnescapedNewline &&
!CurrentToken->Next->isTrailingComment()) {
HasMultipleParametersOnALine = true;
}
bool ProbablyFunctionTypeLParen =
(CurrentToken->is(tok::l_paren) && CurrentToken->Next &&
CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret));
if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
CurrentToken->Previous->isTypeName(LangOpts)) &&
!(CurrentToken->is(tok::l_brace) ||
(CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) {
Contexts.back().IsExpression = false;
}
if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
MightBeObjCForRangeLoop = false;
if (PossibleObjCForInToken) {
PossibleObjCForInToken->setType(TT_Unknown);
PossibleObjCForInToken = nullptr;
}
}
if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
PossibleObjCForInToken = CurrentToken;
PossibleObjCForInToken->setType(TT_ObjCForIn);
}
// When we discover a 'new', we set CanBeExpression to 'false' in order to
// parse the type correctly. Reset that after a comma.
if (CurrentToken->is(tok::comma))
Contexts.back().CanBeExpression = true;
if (Style.isTableGen()) {
if (CurrentToken->is(tok::comma)) {
if (Contexts.back().IsTableGenCondOpe)
CurrentToken->setType(TT_TableGenCondOperatorComma);
next();
} else if (CurrentToken->is(tok::colon)) {
if (Contexts.back().IsTableGenCondOpe)
CurrentToken->setType(TT_TableGenCondOperatorColon);
next();
}
// In TableGen there must be Values in parens.
if (!parseTableGenValue())
return false;
continue;
}
FormatToken *Tok = CurrentToken;
if (!consumeToken())
return false;
updateParameterCount(&OpeningParen, Tok);
if (CurrentToken && CurrentToken->HasUnescapedNewline)
HasMultipleLines = true;
}
return false;
}
bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
if (!Style.isCSharp())
return false;
// `identifier[i]` is not an attribute.
if (Tok.Previous && Tok.Previous->is(tok::identifier))
return false;
// Chains of [] in `identifier[i][j][k]` are not attributes.
if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
auto *MatchingParen = Tok.Previous->MatchingParen;
if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare))
return false;
}
const FormatToken *AttrTok = Tok.Next;
if (!AttrTok)
return false;
// Just an empty declaration e.g. string [].
if (AttrTok->is(tok::r_square))
return false;
// Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
while (AttrTok && AttrTok->isNot(tok::r_square))
AttrTok = AttrTok->Next;
if (!AttrTok)
return false;
// Allow an attribute to be the only content of a file.
AttrTok = AttrTok->Next;
if (!AttrTok)
return true;
// Limit this to being an access modifier that follows.
if (AttrTok->isAccessSpecifierKeyword() ||
AttrTok->isOneOf(tok::comment, tok::kw_class, tok::kw_static,
tok::l_square, Keywords.kw_internal)) {
return true;
}
// incase its a [XXX] retval func(....
if (AttrTok->Next &&
AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) {
return true;
}
return false;
}
bool parseSquare() {
if (!CurrentToken)
return false;
// A '[' could be an index subscript (after an identifier or after
// ')' or ']'), it could be the start of an Objective-C method
// expression, it could the start of an Objective-C array literal,
// or it could be a C++ attribute specifier [[foo::bar]].
FormatToken *Left = CurrentToken->Previous;
Left->ParentBracket = Contexts.back().ContextKind;
FormatToken *Parent = Left->getPreviousNonComment();
// Cases where '>' is followed by '['.
// In C++, this can happen either in array of templates (foo<int>[10])
// or when array is a nested template type (unique_ptr<type1<type2>[]>).
bool CppArrayTemplates =
IsCpp && Parent && Parent->is(TT_TemplateCloser) &&
(Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
Contexts.back().ContextType == Context::TemplateArgument);
const bool IsInnerSquare = Contexts.back().InCpp11AttributeSpecifier;
const bool IsCpp11AttributeSpecifier =
isCppAttribute(IsCpp, *Left) || IsInnerSquare;
// Treat C# Attributes [STAThread] much like C++ attributes [[...]].
bool IsCSharpAttributeSpecifier =
isCSharpAttributeSpecifier(*Left) ||
Contexts.back().InCSharpAttributeSpecifier;
bool InsideInlineASM = Line.startsWith(tok::kw_asm);
bool IsCppStructuredBinding = Left->isCppStructuredBinding(IsCpp);
bool StartsObjCMethodExpr =
!IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
!CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
(!Parent ||
Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
tok::kw_return, tok::kw_throw) ||
Parent->isUnaryOperator() ||
// FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
(getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
prec::Unknown));
bool ColonFound = false;
unsigned BindingIncrease = 1;
if (IsCppStructuredBinding) {
Left->setType(TT_StructuredBindingLSquare);
} else if (Left->is(TT_Unknown)) {
if (StartsObjCMethodExpr) {
Left->setType(TT_ObjCMethodExpr);
} else if (InsideInlineASM) {
Left->setType(TT_InlineASMSymbolicNameLSquare);
} else if (IsCpp11AttributeSpecifier) {
Left->setType(TT_AttributeSquare);
if (!IsInnerSquare && Left->Previous)
Left->Previous->EndsCppAttributeGroup = false;
} else if (Style.isJavaScript() && Parent &&
Contexts.back().ContextKind == tok::l_brace &&
Parent->isOneOf(tok::l_brace, tok::comma)) {
Left->setType(TT_JsComputedPropertyName);
} else if (IsCpp && Contexts.back().ContextKind == tok::l_brace &&
Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
Left->setType(TT_DesignatedInitializerLSquare);
} else if (IsCSharpAttributeSpecifier) {
Left->setType(TT_AttributeSquare);
} else if (CurrentToken->is(tok::r_square) && Parent &&
Parent->is(TT_TemplateCloser)) {
Left->setType(TT_ArraySubscriptLSquare);
} else if (Style.isProto()) {
// Square braces in LK_Proto can either be message field attributes:
//
// optional Aaa aaa = 1 [
// (aaa) = aaa
// ];
//
// extensions 123 [
// (aaa) = aaa
// ];
//
// or text proto extensions (in options):
//
// option (Aaa.options) = {
// [type.type/type] {
// key: value
// }
// }
//
// or repeated fields (in options):
//
// option (Aaa.options) = {
// keys: [ 1, 2, 3 ]
// }
//
// In the first and the third case we want to spread the contents inside
// the square braces; in the second we want to keep them inline.
Left->setType(TT_ArrayInitializerLSquare);
if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
tok::equal) &&
!Left->endsSequence(tok::l_square, tok::numeric_constant,
tok::identifier) &&
!Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
Left->setType(TT_ProtoExtensionLSquare);
BindingIncrease = 10;
}
} else if (!CppArrayTemplates && Parent &&
Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
tok::comma, tok::l_paren, tok::l_square,
tok::question, tok::colon, tok::kw_return,
// Should only be relevant to JavaScript:
tok::kw_default)) {
Left->setType(TT_ArrayInitializerLSquare);
} else {
BindingIncrease = 10;
Left->setType(TT_ArraySubscriptLSquare);
}
}
ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
Contexts.back().IsExpression = true;
if (Style.isJavaScript() && Parent && Parent->is(TT_JsTypeColon))
Contexts.back().IsExpression = false;
Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier;
while (CurrentToken) {
if (CurrentToken->is(tok::r_square)) {
if (IsCpp11AttributeSpecifier) {
CurrentToken->setType(TT_AttributeSquare);
if (!IsInnerSquare)
CurrentToken->EndsCppAttributeGroup = true;
}
if (IsCSharpAttributeSpecifier) {
CurrentToken->setType(TT_AttributeSquare);
} else if (((CurrentToken->Next &&
CurrentToken->Next->is(tok::l_paren)) ||
(CurrentToken->Previous &&
CurrentToken->Previous->Previous == Left)) &&
Left->is(TT_ObjCMethodExpr)) {
// An ObjC method call is rarely followed by an open parenthesis. It
// also can't be composed of just one token, unless it's a macro that
// will be expanded to more tokens.
// FIXME: Do we incorrectly label ":" with this?
StartsObjCMethodExpr = false;
Left->setType(TT_Unknown);
}
if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
CurrentToken->setType(TT_ObjCMethodExpr);
// If we haven't seen a colon yet, make sure the last identifier
// before the r_square is tagged as a selector name component.
if (!ColonFound && CurrentToken->Previous &&
CurrentToken->Previous->is(TT_Unknown) &&
canBeObjCSelectorComponent(*CurrentToken->Previous)) {
CurrentToken->Previous->setType(TT_SelectorName);
}
// determineStarAmpUsage() thinks that '*' '[' is allocating an
// array of pointers, but if '[' starts a selector then '*' is a
// binary operator.
if (Parent && Parent->is(TT_PointerOrReference))
Parent->overwriteFixedType(TT_BinaryOperator);
}
// An arrow after an ObjC method expression is not a lambda arrow.
if (CurrentToken->is(TT_ObjCMethodExpr) && CurrentToken->Next &&
CurrentToken->Next->is(TT_LambdaArrow)) {
CurrentToken->Next->overwriteFixedType(TT_Unknown);
}
Left->MatchingParen = CurrentToken;
CurrentToken->MatchingParen = Left;
// FirstObjCSelectorName is set when a colon is found. This does
// not work, however, when the method has no parameters.
// Here, we set FirstObjCSelectorName when the end of the method call is
// reached, in case it was not set already.
if (!Contexts.back().FirstObjCSelectorName) {
FormatToken *Previous = CurrentToken->getPreviousNonComment();
if (Previous && Previous->is(TT_SelectorName)) {
Previous->ObjCSelectorNameParts = 1;
Contexts.back().FirstObjCSelectorName = Previous;
}
} else {
Left->ParameterCount =
Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
}
if (Contexts.back().FirstObjCSelectorName) {
Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
Contexts.back().LongestObjCSelectorName;
if (Left->BlockParameterCount > 1)
Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
}
if (Style.isTableGen() && Left->is(TT_TableGenListOpener))
CurrentToken->setType(TT_TableGenListCloser);
next();
return true;
}
if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
return false;
if (CurrentToken->is(tok::colon)) {
if (IsCpp11AttributeSpecifier &&
CurrentToken->endsSequence(tok::colon, tok::identifier,
tok::kw_using)) {
// Remember that this is a [[using ns: foo]] C++ attribute, so we
// don't add a space before the colon (unlike other colons).
CurrentToken->setType(TT_AttributeColon);
} else if (!Style.isVerilog() && !Line.InPragmaDirective &&
Left->isOneOf(TT_ArraySubscriptLSquare,
TT_DesignatedInitializerLSquare)) {
Left->setType(TT_ObjCMethodExpr);
StartsObjCMethodExpr = true;
Contexts.back().ColonIsObjCMethodExpr = true;
if (Parent && Parent->is(tok::r_paren)) {
// FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
Parent->setType(TT_CastRParen);
}
}
ColonFound = true;
}
if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
!ColonFound) {
Left->setType(TT_ArrayInitializerLSquare);
}
FormatToken *Tok = CurrentToken;
if (Style.isTableGen()) {
if (CurrentToken->isOneOf(tok::comma, tok::minus, tok::ellipsis)) {
// '-' and '...' appears as a separator in slice.
next();
} else {
// In TableGen there must be a list of Values in square brackets.
// It must be ValueList or SliceElements.
if (!parseTableGenValue())
return false;
}
updateParameterCount(Left, Tok);
continue;
}
if (!consumeToken())
return false;
updateParameterCount(Left, Tok);
}
return false;
}
void skipToNextNonComment() {
next();
while (CurrentToken && CurrentToken->is(tok::comment))
next();
}
// Simplified parser for TableGen Value. Returns true on success.
// It consists of SimpleValues, SimpleValues with Suffixes, and Value followed
// by '#', paste operator.
// There also exists the case the Value is parsed as NameValue.
// In this case, the Value ends if '{' is found.
bool parseTableGenValue(bool ParseNameMode = false) {
if (!CurrentToken)
return false;
while (CurrentToken->is(tok::comment))
next();
if (!parseTableGenSimpleValue())
return false;
if (!CurrentToken)
return true;
// Value "#" [Value]
if (CurrentToken->is(tok::hash)) {
if (CurrentToken->Next &&
CurrentToken->Next->isOneOf(tok::colon, tok::semi, tok::l_brace)) {
// Trailing paste operator.
// These are only the allowed cases in TGParser::ParseValue().
CurrentToken->setType(TT_TableGenTrailingPasteOperator);
next();
return true;
}
FormatToken *HashTok = CurrentToken;
skipToNextNonComment();
HashTok->setType(TT_Unknown);
if (!parseTableGenValue(ParseNameMode))
return false;
}
// In name mode, '{' is regarded as the end of the value.
// See TGParser::ParseValue in TGParser.cpp
if (ParseNameMode && CurrentToken->is(tok::l_brace))
return true;
// These tokens indicates this is a value with suffixes.
if (CurrentToken->isOneOf(tok::l_brace, tok::l_square, tok::period)) {
CurrentToken->setType(TT_TableGenValueSuffix);
FormatToken *Suffix = CurrentToken;
skipToNextNonComment();
if (Suffix->is(tok::l_square))
return parseSquare();
if (Suffix->is(tok::l_brace)) {
Scopes.push_back(getScopeType(*Suffix));
return parseBrace();
}
}
return true;
}
// TokVarName ::= "$" ualpha (ualpha | "0"..."9")*
// Appears as a part of DagArg.
// This does not change the current token on fail.
bool tryToParseTableGenTokVar() {
if (!CurrentToken)
return false;
if (CurrentToken->is(tok::identifier) &&
CurrentToken->TokenText.front() == '$') {
skipToNextNonComment();
return true;
}
return false;
}
// DagArg ::= Value [":" TokVarName] | TokVarName
// Appears as a part of SimpleValue6.
bool parseTableGenDAGArg(bool AlignColon = false) {
if (tryToParseTableGenTokVar())
return true;
if (parseTableGenValue()) {
if (CurrentToken && CurrentToken->is(tok::colon)) {
if (AlignColon)
CurrentToken->setType(TT_TableGenDAGArgListColonToAlign);
else
CurrentToken->setType(TT_TableGenDAGArgListColon);
skipToNextNonComment();
return tryToParseTableGenTokVar();
}
return true;
}
return false;
}
// Judge if the token is a operator ID to insert line break in DAGArg.
// That is, TableGenBreakingDAGArgOperators is empty (by the definition of the