-
Notifications
You must be signed in to change notification settings - Fork 12.4k
/
ParseDecl.cpp
8590 lines (7650 loc) · 316 KB
/
ParseDecl.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
//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the Declaration portions of the Parser interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/PrettyDeclStackTrace.h"
#include "clang/Basic/AddressSpaces.h"
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/Attributes.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/EnterExpressionEvaluationContext.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/SemaCUDA.h"
#include "clang/Sema/SemaCodeCompletion.h"
#include "clang/Sema/SemaDiagnostic.h"
#include "clang/Sema/SemaObjC.h"
#include "clang/Sema/SemaOpenMP.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include <optional>
using namespace clang;
//===----------------------------------------------------------------------===//
// C99 6.7: Declarations.
//===----------------------------------------------------------------------===//
/// ParseTypeName
/// type-name: [C99 6.7.6]
/// specifier-qualifier-list abstract-declarator[opt]
///
/// Called type-id in C++.
TypeResult Parser::ParseTypeName(SourceRange *Range, DeclaratorContext Context,
AccessSpecifier AS, Decl **OwnedType,
ParsedAttributes *Attrs) {
DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
if (DSC == DeclSpecContext::DSC_normal)
DSC = DeclSpecContext::DSC_type_specifier;
// Parse the common declaration-specifiers piece.
DeclSpec DS(AttrFactory);
if (Attrs)
DS.addAttributes(*Attrs);
ParseSpecifierQualifierList(DS, AS, DSC);
if (OwnedType)
*OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
// Move declspec attributes to ParsedAttributes
if (Attrs) {
llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
for (ParsedAttr &AL : DS.getAttributes()) {
if (AL.isDeclspecAttribute())
ToBeMoved.push_back(&AL);
}
for (ParsedAttr *AL : ToBeMoved)
Attrs->takeOneFrom(DS.getAttributes(), AL);
}
// Parse the abstract-declarator, if present.
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
ParseDeclarator(DeclaratorInfo);
if (Range)
*Range = DeclaratorInfo.getSourceRange();
if (DeclaratorInfo.isInvalidType())
return true;
return Actions.ActOnTypeName(DeclaratorInfo);
}
/// Normalizes an attribute name by dropping prefixed and suffixed __.
static StringRef normalizeAttrName(StringRef Name) {
if (Name.size() >= 4 && Name.starts_with("__") && Name.ends_with("__"))
return Name.drop_front(2).drop_back(2);
return Name;
}
/// returns true iff attribute is annotated with `LateAttrParseExperimentalExt`
/// in `Attr.td`.
static bool IsAttributeLateParsedExperimentalExt(const IdentifierInfo &II) {
#define CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST
}
/// returns true iff attribute is annotated with `LateAttrParseStandard` in
/// `Attr.td`.
static bool IsAttributeLateParsedStandard(const IdentifierInfo &II) {
#define CLANG_ATTR_LATE_PARSED_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_LATE_PARSED_LIST
}
/// Check if the a start and end source location expand to the same macro.
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
SourceLocation EndLoc) {
if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
return false;
SourceManager &SM = PP.getSourceManager();
if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
return false;
bool AttrStartIsInMacro =
Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
bool AttrEndIsInMacro =
Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
return AttrStartIsInMacro && AttrEndIsInMacro;
}
void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
LateParsedAttrList *LateAttrs) {
bool MoreToParse;
do {
// Assume there's nothing left to parse, but if any attributes are in fact
// parsed, loop to ensure all specified attribute combinations are parsed.
MoreToParse = false;
if (WhichAttrKinds & PAKM_CXX11)
MoreToParse |= MaybeParseCXX11Attributes(Attrs);
if (WhichAttrKinds & PAKM_GNU)
MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
if (WhichAttrKinds & PAKM_Declspec)
MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
} while (MoreToParse);
}
/// ParseGNUAttributes - Parse a non-empty attributes list.
///
/// [GNU] attributes:
/// attribute
/// attributes attribute
///
/// [GNU] attribute:
/// '__attribute__' '(' '(' attribute-list ')' ')'
///
/// [GNU] attribute-list:
/// attrib
/// attribute_list ',' attrib
///
/// [GNU] attrib:
/// empty
/// attrib-name
/// attrib-name '(' identifier ')'
/// attrib-name '(' identifier ',' nonempty-expr-list ')'
/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
///
/// [GNU] attrib-name:
/// identifier
/// typespec
/// typequal
/// storageclass
///
/// Whether an attribute takes an 'identifier' is determined by the
/// attrib-name. GCC's behavior here is not worth imitating:
///
/// * In C mode, if the attribute argument list starts with an identifier
/// followed by a ',' or an ')', and the identifier doesn't resolve to
/// a type, it is parsed as an identifier. If the attribute actually
/// wanted an expression, it's out of luck (but it turns out that no
/// attributes work that way, because C constant expressions are very
/// limited).
/// * In C++ mode, if the attribute argument list starts with an identifier,
/// and the attribute *wants* an identifier, it is parsed as an identifier.
/// At block scope, any additional tokens between the identifier and the
/// ',' or ')' are ignored, otherwise they produce a parse error.
///
/// We follow the C++ model, but don't allow junk after the identifier.
void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
LateParsedAttrList *LateAttrs, Declarator *D) {
assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc = StartLoc;
while (Tok.is(tok::kw___attribute)) {
SourceLocation AttrTokLoc = ConsumeToken();
unsigned OldNumAttrs = Attrs.size();
unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
"attribute")) {
SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
return;
}
if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
return;
}
// Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
do {
// Eat preceeding commas to allow __attribute__((,,,foo))
while (TryConsumeToken(tok::comma))
;
// Expect an identifier or declaration specifier (const, int, etc.)
if (Tok.isAnnotation())
break;
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompletion().CodeCompleteAttribute(
AttributeCommonInfo::Syntax::AS_GNU);
break;
}
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
if (!AttrName)
break;
SourceLocation AttrNameLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::Form::GNU());
continue;
}
bool LateParse = false;
if (!LateAttrs)
LateParse = false;
else if (LateAttrs->lateAttrParseExperimentalExtOnly()) {
// The caller requested that this attribute **only** be late
// parsed for `LateAttrParseExperimentalExt` attributes. This will
// only be late parsed if the experimental language option is enabled.
LateParse = getLangOpts().ExperimentalLateParseAttributes &&
IsAttributeLateParsedExperimentalExt(*AttrName);
} else {
// The caller did not restrict late parsing to only
// `LateAttrParseExperimentalExt` attributes so late parse
// both `LateAttrParseStandard` and `LateAttrParseExperimentalExt`
// attributes.
LateParse = IsAttributeLateParsedExperimentalExt(*AttrName) ||
IsAttributeLateParsedStandard(*AttrName);
}
// Handle "parameterized" attributes
if (!LateParse) {
ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
SourceLocation(), ParsedAttr::Form::GNU(), D);
continue;
}
// Handle attributes with arguments that require late parsing.
LateParsedAttribute *LA =
new LateParsedAttribute(this, *AttrName, AttrNameLoc);
LateAttrs->push_back(LA);
// Attributes in a class are parsed at the end of the class, along
// with other late-parsed declarations.
if (!ClassStack.empty() && !LateAttrs->parseSoon())
getCurrentClass().LateParsedDeclarations.push_back(LA);
// Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
// recursively consumes balanced parens.
LA->Toks.push_back(Tok);
ConsumeParen();
// Consume everything up to and including the matching right parens.
ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
Token Eof;
Eof.startToken();
Eof.setLocation(Tok.getLocation());
LA->Toks.push_back(Eof);
} while (Tok.is(tok::comma));
if (ExpectAndConsume(tok::r_paren))
SkipUntil(tok::r_paren, StopAtSemi);
SourceLocation Loc = Tok.getLocation();
if (ExpectAndConsume(tok::r_paren))
SkipUntil(tok::r_paren, StopAtSemi);
EndLoc = Loc;
// If this was declared in a macro, attach the macro IdentifierInfo to the
// parsed attribute.
auto &SM = PP.getSourceManager();
if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
StringRef FoundName =
Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
if (LateAttrs) {
for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
(*LateAttrs)[i]->MacroII = MacroII;
}
}
}
Attrs.Range = SourceRange(StartLoc, EndLoc);
}
/// Determine whether the given attribute has an identifier argument.
static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
#define CLANG_ATTR_IDENTIFIER_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
}
/// Determine whether the given attribute has an identifier argument.
static ParsedAttributeArgumentsProperties
attributeStringLiteralListArg(const llvm::Triple &T, const IdentifierInfo &II) {
#define CLANG_ATTR_STRING_LITERAL_ARG_LIST
return llvm::StringSwitch<uint32_t>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(0);
#undef CLANG_ATTR_STRING_LITERAL_ARG_LIST
}
/// Determine whether the given attribute has a variadic identifier argument.
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
}
/// Determine whether the given attribute treats kw_this as an identifier.
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
}
/// Determine if an attribute accepts parameter packs.
static bool attributeAcceptsExprPack(const IdentifierInfo &II) {
#define CLANG_ATTR_ACCEPTS_EXPR_PACK
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_ACCEPTS_EXPR_PACK
}
/// Determine whether the given attribute parses a type argument.
static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
#define CLANG_ATTR_TYPE_ARG_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_TYPE_ARG_LIST
}
/// Determine whether the given attribute takes identifier arguments.
static bool attributeHasStrictIdentifierArgs(const IdentifierInfo &II) {
#define CLANG_ATTR_STRICT_IDENTIFIER_ARG_AT_INDEX_LIST
return (llvm::StringSwitch<uint64_t>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(0)) != 0;
#undef CLANG_ATTR_STRICT_IDENTIFIER_ARG_AT_INDEX_LIST
}
/// Determine whether the given attribute takes an identifier argument at a
/// specific index
static bool attributeHasStrictIdentifierArgAtIndex(const IdentifierInfo &II,
size_t argIndex) {
#define CLANG_ATTR_STRICT_IDENTIFIER_ARG_AT_INDEX_LIST
return (llvm::StringSwitch<uint64_t>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(0)) &
(1ull << argIndex);
#undef CLANG_ATTR_STRICT_IDENTIFIER_ARG_AT_INDEX_LIST
}
/// Determine whether the given attribute requires parsing its arguments
/// in an unevaluated context or not.
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
#define CLANG_ATTR_ARG_CONTEXT_LIST
return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
#include "clang/Parse/AttrParserStringSwitches.inc"
.Default(false);
#undef CLANG_ATTR_ARG_CONTEXT_LIST
}
IdentifierLoc *Parser::ParseIdentifierLoc() {
assert(Tok.is(tok::identifier) && "expected an identifier");
IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
Tok.getLocation(),
Tok.getIdentifierInfo());
ConsumeToken();
return IL;
}
void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Form Form) {
BalancedDelimiterTracker Parens(*this, tok::l_paren);
Parens.consumeOpen();
TypeResult T;
if (Tok.isNot(tok::r_paren))
T = ParseTypeName();
if (Parens.consumeClose())
return;
if (T.isInvalid())
return;
if (T.isUsable())
Attrs.addNewTypeAttr(&AttrName,
SourceRange(AttrNameLoc, Parens.getCloseLocation()),
ScopeName, ScopeLoc, T.get(), Form);
else
Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
ScopeName, ScopeLoc, nullptr, 0, Form);
}
ExprResult
Parser::ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName) {
if (Tok.is(tok::l_paren)) {
BalancedDelimiterTracker Paren(*this, tok::l_paren);
Paren.consumeOpen();
ExprResult Res = ParseUnevaluatedStringInAttribute(AttrName);
Paren.consumeClose();
return Res;
}
if (!isTokenStringLiteral()) {
Diag(Tok.getLocation(), diag::err_expected_string_literal)
<< /*in attribute...*/ 4 << AttrName.getName();
return ExprError();
}
return ParseUnevaluatedStringLiteralExpression();
}
bool Parser::ParseAttributeArgumentList(
const IdentifierInfo &AttrName, SmallVectorImpl<Expr *> &Exprs,
ParsedAttributeArgumentsProperties ArgsProperties) {
bool SawError = false;
unsigned Arg = 0;
while (true) {
ExprResult Expr;
if (ArgsProperties.isStringLiteralArg(Arg)) {
Expr = ParseUnevaluatedStringInAttribute(AttrName);
} else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Expr = ParseBraceInitializer();
} else {
Expr = ParseAssignmentExpression();
}
Expr = Actions.CorrectDelayedTyposInExpr(Expr);
if (Tok.is(tok::ellipsis))
Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
else if (Tok.is(tok::code_completion)) {
// There's nothing to suggest in here as we parsed a full expression.
// Instead fail and propagate the error since caller might have something
// the suggest, e.g. signature help in function call. Note that this is
// performed before pushing the \p Expr, so that signature help can report
// current argument correctly.
SawError = true;
cutOffParsing();
break;
}
if (Expr.isInvalid()) {
SawError = true;
break;
}
if (Actions.DiagnoseUnexpandedParameterPack(Expr.get())) {
SawError = true;
break;
}
Exprs.push_back(Expr.get());
if (Tok.isNot(tok::comma))
break;
// Move to the next argument, remember where the comma was.
Token Comma = Tok;
ConsumeToken();
checkPotentialAngleBracketDelimiter(Comma);
Arg++;
}
if (SawError) {
// Ensure typos get diagnosed when errors were encountered while parsing the
// expression list.
for (auto &E : Exprs) {
ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
if (Expr.isUsable())
E = Expr.get();
}
}
return SawError;
}
unsigned Parser::ParseAttributeArgsCommon(
IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Form Form) {
// Ignore the left paren location for now.
ConsumeParen();
bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
bool AttributeHasVariadicIdentifierArg =
attributeHasVariadicIdentifierArg(*AttrName);
// Interpret "kw_this" as an identifier if the attributed requests it.
if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
Tok.setKind(tok::identifier);
ArgsVector ArgExprs;
if (Tok.is(tok::identifier)) {
// If this attribute wants an 'identifier' argument, make it so.
bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
attributeHasIdentifierArg(*AttrName);
ParsedAttr::Kind AttrKind =
ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
// If we don't know how to parse this attribute, but this is the only
// token in this argument, assume it's meant to be an identifier.
if (AttrKind == ParsedAttr::UnknownAttribute ||
AttrKind == ParsedAttr::IgnoredAttribute) {
const Token &Next = NextToken();
IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
}
if (IsIdentifierArg)
ArgExprs.push_back(ParseIdentifierLoc());
}
ParsedType TheParsedType;
if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
// Eat the comma.
if (!ArgExprs.empty())
ConsumeToken();
if (AttributeIsTypeArgAttr) {
// FIXME: Multiple type arguments are not implemented.
TypeResult T = ParseTypeName();
if (T.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
if (T.isUsable())
TheParsedType = T.get();
} else if (AttributeHasVariadicIdentifierArg ||
attributeHasStrictIdentifierArgs(*AttrName)) {
// Parse variadic identifier arg. This can either consume identifiers or
// expressions. Variadic identifier args do not support parameter packs
// because those are typically used for attributes with enumeration
// arguments, and those enumerations are not something the user could
// express via a pack.
do {
// Interpret "kw_this" as an identifier if the attributed requests it.
if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
Tok.setKind(tok::identifier);
if (Tok.is(tok::identifier) && attributeHasStrictIdentifierArgAtIndex(
*AttrName, ArgExprs.size())) {
ArgExprs.push_back(ParseIdentifierLoc());
continue;
}
ExprResult ArgExpr;
if (Tok.is(tok::identifier)) {
ArgExprs.push_back(ParseIdentifierLoc());
} else {
bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
EnterExpressionEvaluationContext Unevaluated(
Actions,
Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
: Sema::ExpressionEvaluationContext::ConstantEvaluated,
nullptr,
Sema::ExpressionEvaluationContextRecord::EK_AttrArgument);
ExprResult ArgExpr(
Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
if (ArgExpr.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
ArgExprs.push_back(ArgExpr.get());
}
// Eat the comma, move to the next argument
} while (TryConsumeToken(tok::comma));
} else {
// General case. Parse all available expressions.
bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
EnterExpressionEvaluationContext Unevaluated(
Actions,
Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
: Sema::ExpressionEvaluationContext::ConstantEvaluated,
nullptr,
Sema::ExpressionEvaluationContextRecord::ExpressionKind::
EK_AttrArgument);
ExprVector ParsedExprs;
ParsedAttributeArgumentsProperties ArgProperties =
attributeStringLiteralListArg(getTargetInfo().getTriple(), *AttrName);
if (ParseAttributeArgumentList(*AttrName, ParsedExprs, ArgProperties)) {
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
// Pack expansion must currently be explicitly supported by an attribute.
for (size_t I = 0; I < ParsedExprs.size(); ++I) {
if (!isa<PackExpansionExpr>(ParsedExprs[I]))
continue;
if (!attributeAcceptsExprPack(*AttrName)) {
Diag(Tok.getLocation(),
diag::err_attribute_argument_parm_pack_not_supported)
<< AttrName;
SkipUntil(tok::r_paren, StopAtSemi);
return 0;
}
}
ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
}
}
SourceLocation RParen = Tok.getLocation();
if (!ExpectAndConsume(tok::r_paren)) {
SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
ScopeName, ScopeLoc, TheParsedType, Form);
} else {
Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
ArgExprs.data(), ArgExprs.size(), Form);
}
}
if (EndLoc)
*EndLoc = RParen;
return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
}
/// Parse the arguments to a parameterized GNU attribute or
/// a C++11 attribute in "gnu" namespace.
void Parser::ParseGNUAttributeArgs(
IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Form Form, Declarator *D) {
assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
ParsedAttr::Kind AttrKind =
ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
if (AttrKind == ParsedAttr::AT_Availability) {
ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Form);
return;
} else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Form);
return;
} else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Form);
return;
} else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Form);
return;
} else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Form);
return;
} else if (attributeIsTypeArgAttr(*AttrName)) {
ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
ScopeLoc, Form);
return;
} else if (AttrKind == ParsedAttr::AT_CountedBy ||
AttrKind == ParsedAttr::AT_CountedByOrNull ||
AttrKind == ParsedAttr::AT_SizedBy ||
AttrKind == ParsedAttr::AT_SizedByOrNull) {
ParseBoundsAttribute(*AttrName, AttrNameLoc, Attrs, ScopeName, ScopeLoc,
Form);
return;
} else if (AttrKind == ParsedAttr::AT_CXXAssume) {
ParseCXXAssumeAttributeArg(Attrs, AttrName, AttrNameLoc, EndLoc, Form);
return;
}
// These may refer to the function arguments, but need to be parsed early to
// participate in determining whether it's a redeclaration.
std::optional<ParseScope> PrototypeScope;
if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
D && D->isFunctionDeclarator()) {
DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
Scope::FunctionDeclarationScope |
Scope::DeclScope);
for (unsigned i = 0; i != FTI.NumParams; ++i) {
ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
}
}
ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Form);
}
unsigned Parser::ParseClangAttributeArgs(
IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Form Form) {
assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
ParsedAttr::Kind AttrKind =
ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
switch (AttrKind) {
default:
return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Form);
case ParsedAttr::AT_ExternalSourceSymbol:
ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Form);
break;
case ParsedAttr::AT_Availability:
ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Form);
break;
case ParsedAttr::AT_ObjCBridgeRelated:
ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Form);
break;
case ParsedAttr::AT_SwiftNewType:
ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
ScopeLoc, Form);
break;
case ParsedAttr::AT_TypeTagForDatatype:
ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
ScopeName, ScopeLoc, Form);
break;
case ParsedAttr::AT_CXXAssume:
ParseCXXAssumeAttributeArg(Attrs, AttrName, AttrNameLoc, EndLoc, Form);
break;
}
return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
}
bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs) {
unsigned ExistingAttrs = Attrs.size();
// If the attribute isn't known, we will not attempt to parse any
// arguments.
if (!hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr, AttrName,
getTargetInfo(), getLangOpts())) {
// Eat the left paren, then skip to the ending right paren.
ConsumeParen();
SkipUntil(tok::r_paren);
return false;
}
SourceLocation OpenParenLoc = Tok.getLocation();
if (AttrName->getName() == "property") {
// The property declspec is more complex in that it can take one or two
// assignment expressions as a parameter, but the lhs of the assignment
// must be named get or put.
BalancedDelimiterTracker T(*this, tok::l_paren);
T.expectAndConsume(diag::err_expected_lparen_after,
AttrName->getNameStart(), tok::r_paren);
enum AccessorKind {
AK_Invalid = -1,
AK_Put = 0,
AK_Get = 1 // indices into AccessorNames
};
IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
bool HasInvalidAccessor = false;
// Parse the accessor specifications.
while (true) {
// Stop if this doesn't look like an accessor spec.
if (!Tok.is(tok::identifier)) {
// If the user wrote a completely empty list, use a special diagnostic.
if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
AccessorNames[AK_Put] == nullptr &&
AccessorNames[AK_Get] == nullptr) {
Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
break;
}
Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
break;
}
AccessorKind Kind;
SourceLocation KindLoc = Tok.getLocation();
StringRef KindStr = Tok.getIdentifierInfo()->getName();
if (KindStr == "get") {
Kind = AK_Get;
} else if (KindStr == "put") {
Kind = AK_Put;
// Recover from the common mistake of using 'set' instead of 'put'.
} else if (KindStr == "set") {
Diag(KindLoc, diag::err_ms_property_has_set_accessor)
<< FixItHint::CreateReplacement(KindLoc, "put");
Kind = AK_Put;
// Handle the mistake of forgetting the accessor kind by skipping
// this accessor.
} else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
ConsumeToken();
HasInvalidAccessor = true;
goto next_property_accessor;
// Otherwise, complain about the unknown accessor kind.
} else {
Diag(KindLoc, diag::err_ms_property_unknown_accessor);
HasInvalidAccessor = true;
Kind = AK_Invalid;
// Try to keep parsing unless it doesn't look like an accessor spec.
if (!NextToken().is(tok::equal))
break;
}
// Consume the identifier.
ConsumeToken();
// Consume the '='.
if (!TryConsumeToken(tok::equal)) {
Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
<< KindStr;
break;
}
// Expect the method name.
if (!Tok.is(tok::identifier)) {
Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
break;
}
if (Kind == AK_Invalid) {
// Just drop invalid accessors.
} else if (AccessorNames[Kind] != nullptr) {
// Complain about the repeated accessor, ignore it, and keep parsing.
Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
} else {
AccessorNames[Kind] = Tok.getIdentifierInfo();
}
ConsumeToken();
next_property_accessor:
// Keep processing accessors until we run out.
if (TryConsumeToken(tok::comma))
continue;
// If we run into the ')', stop without consuming it.
if (Tok.is(tok::r_paren))
break;
Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
break;
}
// Only add the property attribute if it was well-formed.
if (!HasInvalidAccessor)
Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
AccessorNames[AK_Get], AccessorNames[AK_Put],
ParsedAttr::Form::Declspec());
T.skipToEnd();
return !HasInvalidAccessor;
}
unsigned NumArgs =
ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
SourceLocation(), ParsedAttr::Form::Declspec());
// If this attribute's args were parsed, and it was expected to have
// arguments but none were provided, emit a diagnostic.
if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
return false;
}
return true;
}
/// [MS] decl-specifier:
/// __declspec ( extended-decl-modifier-seq )
///
/// [MS] extended-decl-modifier-seq:
/// extended-decl-modifier[opt]
/// extended-decl-modifier extended-decl-modifier-seq
void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc = StartLoc;
while (Tok.is(tok::kw___declspec)) {
ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
tok::r_paren))
return;
// An empty declspec is perfectly legal and should not warn. Additionally,
// you can specify multiple attributes per declspec.
while (Tok.isNot(tok::r_paren)) {
// Attribute not present.
if (TryConsumeToken(tok::comma))
continue;
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompletion().CodeCompleteAttribute(
AttributeCommonInfo::AS_Declspec);
return;
}
// We expect either a well-known identifier or a generic string. Anything
// else is a malformed declspec.
bool IsString = Tok.getKind() == tok::string_literal;
if (!IsString && Tok.getKind() != tok::identifier &&
Tok.getKind() != tok::kw_restrict) {
Diag(Tok, diag::err_ms_declspec_type);
T.skipToEnd();
return;
}
IdentifierInfo *AttrName;
SourceLocation AttrNameLoc;
if (IsString) {
SmallString<8> StrBuffer;
bool Invalid = false;
StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
if (Invalid) {
T.skipToEnd();
return;
}
AttrName = PP.getIdentifierInfo(Str);
AttrNameLoc = ConsumeStringToken();
} else {
AttrName = Tok.getIdentifierInfo();
AttrNameLoc = ConsumeToken();
}
bool AttrHandled = false;
// Parse attribute arguments.
if (Tok.is(tok::l_paren))
AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
else if (AttrName->getName() == "property")
// The property attribute must have an argument list.
Diag(Tok.getLocation(), diag::err_expected_lparen_after)
<< AttrName->getName();
if (!AttrHandled)
Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::Form::Declspec());
}
T.consumeClose();
EndLoc = T.getCloseLocation();
}
Attrs.Range = SourceRange(StartLoc, EndLoc);
}