clang 19.0.0git
Parser.h
Go to the documentation of this file.
1//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
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// This file defines the Parser interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_PARSE_PARSER_H
14#define LLVM_CLANG_PARSE_PARSER_H
15
20#include "clang/Sema/Sema.h"
22#include "clang/Sema/SemaObjC.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Frontend/OpenMP/OMPContext.h"
26#include "llvm/Support/SaveAndRestore.h"
27#include <optional>
28#include <stack>
29
30namespace clang {
31 class PragmaHandler;
32 class Scope;
33 class BalancedDelimiterTracker;
34 class CorrectionCandidateCallback;
35 class DeclGroupRef;
36 class DiagnosticBuilder;
37 struct LoopHint;
38 class Parser;
39 class ParsingDeclRAIIObject;
40 class ParsingDeclSpec;
41 class ParsingDeclarator;
42 class ParsingFieldDeclarator;
43 class ColonProtectionRAIIObject;
44 class InMessageExpressionRAIIObject;
45 class PoisonSEHIdentifiersRAIIObject;
46 class OMPClause;
47 class OpenACCClause;
48 class ObjCTypeParamList;
49 struct OMPTraitProperty;
50 struct OMPTraitSelector;
51 struct OMPTraitSet;
52 class OMPTraitInfo;
53
54/// Parser - This implements a parser for the C family of languages. After
55/// parsing units of the grammar, productions are invoked to handle whatever has
56/// been read.
57///
68
69 Preprocessor &PP;
70
71 /// Tok - The current token we are peeking ahead. All parsing methods assume
72 /// that this is valid.
73 Token Tok;
74
75 // PrevTokLocation - The location of the token we previously
76 // consumed. This token is used for diagnostics where we expected to
77 // see a token following another token (e.g., the ';' at the end of
78 // a statement).
79 SourceLocation PrevTokLocation;
80
81 /// Tracks an expected type for the current token when parsing an expression.
82 /// Used by code completion for ranking.
83 PreferredTypeBuilder PreferredType;
84
85 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
86 unsigned short MisplacedModuleBeginCount = 0;
87
88 /// Actions - These are the callbacks we invoke as we parse various constructs
89 /// in the file.
90 Sema &Actions;
91
92 DiagnosticsEngine &Diags;
93
94 /// ScopeCache - Cache scopes to reduce malloc traffic.
95 enum { ScopeCacheSize = 16 };
96 unsigned NumCachedScopes;
97 Scope *ScopeCache[ScopeCacheSize];
98
99 /// Identifiers used for SEH handling in Borland. These are only
100 /// allowed in particular circumstances
101 // __except block
102 IdentifierInfo *Ident__exception_code,
103 *Ident___exception_code,
104 *Ident_GetExceptionCode;
105 // __except filter expression
106 IdentifierInfo *Ident__exception_info,
107 *Ident___exception_info,
108 *Ident_GetExceptionInfo;
109 // __finally
110 IdentifierInfo *Ident__abnormal_termination,
111 *Ident___abnormal_termination,
112 *Ident_AbnormalTermination;
113
114 /// Contextual keywords for Microsoft extensions.
115 IdentifierInfo *Ident__except;
116 mutable IdentifierInfo *Ident_sealed;
117 mutable IdentifierInfo *Ident_abstract;
118
119 /// Ident_super - IdentifierInfo for "super", to support fast
120 /// comparison.
121 IdentifierInfo *Ident_super;
122 /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
123 /// and "bool" fast comparison. Only present if AltiVec or ZVector are
124 /// enabled.
125 IdentifierInfo *Ident_vector;
126 IdentifierInfo *Ident_bool;
127 IdentifierInfo *Ident_Bool;
128 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
129 /// Only present if AltiVec enabled.
130 IdentifierInfo *Ident_pixel;
131
132 /// Objective-C contextual keywords.
133 IdentifierInfo *Ident_instancetype;
134
135 /// Identifier for "introduced".
136 IdentifierInfo *Ident_introduced;
137
138 /// Identifier for "deprecated".
139 IdentifierInfo *Ident_deprecated;
140
141 /// Identifier for "obsoleted".
142 IdentifierInfo *Ident_obsoleted;
143
144 /// Identifier for "unavailable".
145 IdentifierInfo *Ident_unavailable;
146
147 /// Identifier for "message".
148 IdentifierInfo *Ident_message;
149
150 /// Identifier for "strict".
151 IdentifierInfo *Ident_strict;
152
153 /// Identifier for "replacement".
154 IdentifierInfo *Ident_replacement;
155
156 /// Identifier for "environment".
157 IdentifierInfo *Ident_environment;
158
159 /// Identifiers used by the 'external_source_symbol' attribute.
160 IdentifierInfo *Ident_language, *Ident_defined_in,
161 *Ident_generated_declaration, *Ident_USR;
162
163 /// C++11 contextual keywords.
164 mutable IdentifierInfo *Ident_final;
165 mutable IdentifierInfo *Ident_GNU_final;
166 mutable IdentifierInfo *Ident_override;
167
168 // C++2a contextual keywords.
169 mutable IdentifierInfo *Ident_import;
170 mutable IdentifierInfo *Ident_module;
171
172 // C++ type trait keywords that can be reverted to identifiers and still be
173 // used as type traits.
174 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
175
176 std::unique_ptr<PragmaHandler> AlignHandler;
177 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
178 std::unique_ptr<PragmaHandler> OptionsHandler;
179 std::unique_ptr<PragmaHandler> PackHandler;
180 std::unique_ptr<PragmaHandler> MSStructHandler;
181 std::unique_ptr<PragmaHandler> UnusedHandler;
182 std::unique_ptr<PragmaHandler> WeakHandler;
183 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
184 std::unique_ptr<PragmaHandler> FPContractHandler;
185 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
186 std::unique_ptr<PragmaHandler> OpenMPHandler;
187 std::unique_ptr<PragmaHandler> OpenACCHandler;
188 std::unique_ptr<PragmaHandler> PCSectionHandler;
189 std::unique_ptr<PragmaHandler> MSCommentHandler;
190 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
191 std::unique_ptr<PragmaHandler> FPEvalMethodHandler;
192 std::unique_ptr<PragmaHandler> FloatControlHandler;
193 std::unique_ptr<PragmaHandler> MSPointersToMembers;
194 std::unique_ptr<PragmaHandler> MSVtorDisp;
195 std::unique_ptr<PragmaHandler> MSInitSeg;
196 std::unique_ptr<PragmaHandler> MSDataSeg;
197 std::unique_ptr<PragmaHandler> MSBSSSeg;
198 std::unique_ptr<PragmaHandler> MSConstSeg;
199 std::unique_ptr<PragmaHandler> MSCodeSeg;
200 std::unique_ptr<PragmaHandler> MSSection;
201 std::unique_ptr<PragmaHandler> MSStrictGuardStackCheck;
202 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
203 std::unique_ptr<PragmaHandler> MSIntrinsic;
204 std::unique_ptr<PragmaHandler> MSFunction;
205 std::unique_ptr<PragmaHandler> MSOptimize;
206 std::unique_ptr<PragmaHandler> MSFenvAccess;
207 std::unique_ptr<PragmaHandler> MSAllocText;
208 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
209 std::unique_ptr<PragmaHandler> OptimizeHandler;
210 std::unique_ptr<PragmaHandler> LoopHintHandler;
211 std::unique_ptr<PragmaHandler> UnrollHintHandler;
212 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
213 std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
214 std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
215 std::unique_ptr<PragmaHandler> FPHandler;
216 std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
217 std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
218 std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
219 std::unique_ptr<PragmaHandler> STDCUnknownHandler;
220 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
221 std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
222 std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
223 std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
224
225 std::unique_ptr<CommentHandler> CommentSemaHandler;
226
227 /// Whether the '>' token acts as an operator or not. This will be
228 /// true except when we are parsing an expression within a C++
229 /// template argument list, where the '>' closes the template
230 /// argument list.
231 bool GreaterThanIsOperator;
232
233 /// ColonIsSacred - When this is false, we aggressively try to recover from
234 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
235 /// safe in case statements and a few other things. This is managed by the
236 /// ColonProtectionRAIIObject RAII object.
237 bool ColonIsSacred;
238
239 /// Parsing OpenMP directive mode.
240 bool OpenMPDirectiveParsing = false;
241
242 /// Parsing OpenACC directive mode.
243 bool OpenACCDirectiveParsing = false;
244
245 /// Currently parsing a situation where an OpenACC array section could be
246 /// legal, such as a 'var-list'.
247 bool AllowOpenACCArraySections = false;
248
249 /// RAII object to set reset OpenACC parsing a context where Array Sections
250 /// are allowed.
251 class OpenACCArraySectionRAII {
252 Parser &P;
253
254 public:
255 OpenACCArraySectionRAII(Parser &P) : P(P) {
256 assert(!P.AllowOpenACCArraySections);
257 P.AllowOpenACCArraySections = true;
258 }
259 ~OpenACCArraySectionRAII() {
260 assert(P.AllowOpenACCArraySections);
261 P.AllowOpenACCArraySections = false;
262 }
263 };
264
265 /// When true, we are directly inside an Objective-C message
266 /// send expression.
267 ///
268 /// This is managed by the \c InMessageExpressionRAIIObject class, and
269 /// should not be set directly.
270 bool InMessageExpression;
271
272 /// Gets set to true after calling ProduceSignatureHelp, it is for a
273 /// workaround to make sure ProduceSignatureHelp is only called at the deepest
274 /// function call.
275 bool CalledSignatureHelp = false;
276
278
279 /// The "depth" of the template parameters currently being parsed.
280 unsigned TemplateParameterDepth;
281
282 /// Current kind of OpenMP clause
283 OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
284
285 /// RAII class that manages the template parameter depth.
286 class TemplateParameterDepthRAII {
287 unsigned &Depth;
288 unsigned AddedLevels;
289 public:
290 explicit TemplateParameterDepthRAII(unsigned &Depth)
291 : Depth(Depth), AddedLevels(0) {}
292
293 ~TemplateParameterDepthRAII() {
294 Depth -= AddedLevels;
295 }
296
297 void operator++() {
298 ++Depth;
299 ++AddedLevels;
300 }
301 void addDepth(unsigned D) {
302 Depth += D;
303 AddedLevels += D;
304 }
305 void setAddedDepth(unsigned D) {
306 Depth = Depth - AddedLevels + D;
307 AddedLevels = D;
308 }
309
310 unsigned getDepth() const { return Depth; }
311 unsigned getOriginalDepth() const { return Depth - AddedLevels; }
312 };
313
314 /// Factory object for creating ParsedAttr objects.
315 AttributeFactory AttrFactory;
316
317 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
318 /// top-level declaration is finished.
319 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
320
321 /// Don't destroy template annotations in MaybeDestroyTemplateIds even if
322 /// we're at the end of a declaration. Instead, we defer the destruction until
323 /// after a top-level declaration.
324 /// Use DelayTemplateIdDestructionRAII rather than setting it directly.
325 bool DelayTemplateIdDestruction = false;
326
327 void MaybeDestroyTemplateIds() {
328 if (DelayTemplateIdDestruction)
329 return;
330 if (!TemplateIds.empty() &&
331 (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
332 DestroyTemplateIds();
333 }
334 void DestroyTemplateIds();
335
336 /// RAII object to destroy TemplateIdAnnotations where possible, from a
337 /// likely-good position during parsing.
338 struct DestroyTemplateIdAnnotationsRAIIObj {
339 Parser &Self;
340
341 DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
342 ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
343 };
344
345 struct DelayTemplateIdDestructionRAII {
346 Parser &Self;
347 bool PrevDelayTemplateIdDestruction;
348
349 DelayTemplateIdDestructionRAII(Parser &Self,
350 bool DelayTemplateIdDestruction) noexcept
351 : Self(Self),
352 PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) {
353 Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction;
354 }
355
356 ~DelayTemplateIdDestructionRAII() noexcept {
357 Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction;
358 }
359 };
360
361 /// Identifiers which have been declared within a tentative parse.
362 SmallVector<const IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
363
364 /// Tracker for '<' tokens that might have been intended to be treated as an
365 /// angle bracket instead of a less-than comparison.
366 ///
367 /// This happens when the user intends to form a template-id, but typoes the
368 /// template-name or forgets a 'template' keyword for a dependent template
369 /// name.
370 ///
371 /// We track these locations from the point where we see a '<' with a
372 /// name-like expression on its left until we see a '>' or '>>' that might
373 /// match it.
374 struct AngleBracketTracker {
375 /// Flags used to rank candidate template names when there is more than one
376 /// '<' in a scope.
377 enum Priority : unsigned short {
378 /// A non-dependent name that is a potential typo for a template name.
379 PotentialTypo = 0x0,
380 /// A dependent name that might instantiate to a template-name.
381 DependentName = 0x2,
382
383 /// A space appears before the '<' token.
384 SpaceBeforeLess = 0x0,
385 /// No space before the '<' token
386 NoSpaceBeforeLess = 0x1,
387
388 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
389 };
390
391 struct Loc {
394 AngleBracketTracker::Priority Priority;
396
397 bool isActive(Parser &P) const {
398 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
399 P.BraceCount == BraceCount;
400 }
401
402 bool isActiveOrNested(Parser &P) const {
403 return isActive(P) || P.ParenCount > ParenCount ||
404 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
405 }
406 };
407
409
410 /// Add an expression that might have been intended to be a template name.
411 /// In the case of ambiguity, we arbitrarily select the innermost such
412 /// expression, for example in 'foo < bar < baz', 'bar' is the current
413 /// candidate. No attempt is made to track that 'foo' is also a candidate
414 /// for the case where we see a second suspicious '>' token.
415 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
416 Priority Prio) {
417 if (!Locs.empty() && Locs.back().isActive(P)) {
418 if (Locs.back().Priority <= Prio) {
419 Locs.back().TemplateName = TemplateName;
420 Locs.back().LessLoc = LessLoc;
421 Locs.back().Priority = Prio;
422 }
423 } else {
424 Locs.push_back({TemplateName, LessLoc, Prio,
425 P.ParenCount, P.BracketCount, P.BraceCount});
426 }
427 }
428
429 /// Mark the current potential missing template location as having been
430 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
431 /// or leave a bracket scope).
432 void clear(Parser &P) {
433 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
434 Locs.pop_back();
435 }
436
437 /// Get the current enclosing expression that might hve been intended to be
438 /// a template name.
439 Loc *getCurrent(Parser &P) {
440 if (!Locs.empty() && Locs.back().isActive(P))
441 return &Locs.back();
442 return nullptr;
443 }
444 };
445
446 AngleBracketTracker AngleBrackets;
447
448 IdentifierInfo *getSEHExceptKeyword();
449
450 /// True if we are within an Objective-C container while parsing C-like decls.
451 ///
452 /// This is necessary because Sema thinks we have left the container
453 /// to parse the C-like decls, meaning Actions.ObjC().getObjCDeclContext()
454 /// will be NULL.
455 bool ParsingInObjCContainer;
456
457 /// Whether to skip parsing of function bodies.
458 ///
459 /// This option can be used, for example, to speed up searches for
460 /// declarations/definitions when indexing.
461 bool SkipFunctionBodies;
462
463 /// The location of the expression statement that is being parsed right now.
464 /// Used to determine if an expression that is being parsed is a statement or
465 /// just a regular sub-expression.
466 SourceLocation ExprStatementTokLoc;
467
468 /// Flags describing a context in which we're parsing a statement.
469 enum class ParsedStmtContext {
470 /// This context permits standalone OpenMP directives.
471 AllowStandaloneOpenMPDirectives = 0x1,
472 /// This context is at the top level of a GNU statement expression.
473 InStmtExpr = 0x2,
474
475 /// The context of a regular substatement.
476 SubStmt = 0,
477 /// The context of a compound-statement.
478 Compound = AllowStandaloneOpenMPDirectives,
479
480 LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
481 };
482
483 /// Act on an expression statement that might be the last statement in a
484 /// GNU statement expression. Checks whether we are actually at the end of
485 /// a statement expression and builds a suitable expression statement.
486 StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
487
488public:
489 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
490 ~Parser() override;
491
492 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
493 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
494 Preprocessor &getPreprocessor() const { return PP; }
495 Sema &getActions() const { return Actions; }
496 AttributeFactory &getAttrFactory() { return AttrFactory; }
497
498 const Token &getCurToken() const { return Tok; }
499 Scope *getCurScope() const { return Actions.getCurScope(); }
501 return Actions.incrementMSManglingNumber();
502 }
503
505 return Actions.ObjC().getObjCDeclContext();
506 }
507
508 // Type forwarding. All of these are statically 'void*', but they may all be
509 // different actual classes based on the actions in place.
512
514
516
517 /// A SmallVector of statements.
519
520 // Parsing methods.
521
522 /// Initialize - Warm up the parser.
523 ///
524 void Initialize();
525
526 /// Parse the first top-level declaration in a translation unit.
528 Sema::ModuleImportState &ImportState);
529
530 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
531 /// the EOF was encountered.
533 Sema::ModuleImportState &ImportState);
537 return ParseTopLevelDecl(Result, IS);
538 }
539
540 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
541 /// This does not work with special tokens: string literals, code completion,
542 /// annotation tokens and balanced tokens must be handled using the specific
543 /// consume methods.
544 /// Returns the location of the consumed token.
546 assert(!isTokenSpecial() &&
547 "Should consume special tokens with Consume*Token");
548 PrevTokLocation = Tok.getLocation();
549 PP.Lex(Tok);
550 return PrevTokLocation;
551 }
552
554 if (Tok.isNot(Expected))
555 return false;
556 assert(!isTokenSpecial() &&
557 "Should consume special tokens with Consume*Token");
558 PrevTokLocation = Tok.getLocation();
559 PP.Lex(Tok);
560 return true;
561 }
562
565 return false;
566 Loc = PrevTokLocation;
567 return true;
568 }
569
570 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
571 /// current token type. This should only be used in cases where the type of
572 /// the token really isn't known, e.g. in error recovery.
573 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
574 if (isTokenParen())
575 return ConsumeParen();
576 if (isTokenBracket())
577 return ConsumeBracket();
578 if (isTokenBrace())
579 return ConsumeBrace();
580 if (isTokenStringLiteral())
581 return ConsumeStringToken();
582 if (Tok.is(tok::code_completion))
583 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
584 : handleUnexpectedCodeCompletionToken();
585 if (Tok.isAnnotation())
586 return ConsumeAnnotationToken();
587 return ConsumeToken();
588 }
589
590
592 return PP.getLocForEndOfToken(PrevTokLocation);
593 }
594
595 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
596 /// to the given nullability kind.
598 return Actions.getNullabilityKeyword(nullability);
599 }
600
601private:
602 //===--------------------------------------------------------------------===//
603 // Low-Level token peeking and consumption methods.
604 //
605
606 /// isTokenParen - Return true if the cur token is '(' or ')'.
607 bool isTokenParen() const {
608 return Tok.isOneOf(tok::l_paren, tok::r_paren);
609 }
610 /// isTokenBracket - Return true if the cur token is '[' or ']'.
611 bool isTokenBracket() const {
612 return Tok.isOneOf(tok::l_square, tok::r_square);
613 }
614 /// isTokenBrace - Return true if the cur token is '{' or '}'.
615 bool isTokenBrace() const {
616 return Tok.isOneOf(tok::l_brace, tok::r_brace);
617 }
618 /// isTokenStringLiteral - True if this token is a string-literal.
619 bool isTokenStringLiteral() const {
620 return tok::isStringLiteral(Tok.getKind());
621 }
622 /// isTokenSpecial - True if this token requires special consumption methods.
623 bool isTokenSpecial() const {
624 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
625 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
626 }
627
628 /// Returns true if the current token is '=' or is a type of '='.
629 /// For typos, give a fixit to '='
630 bool isTokenEqualOrEqualTypo();
631
632 /// Return the current token to the token stream and make the given
633 /// token the current token.
634 void UnconsumeToken(Token &Consumed) {
635 Token Next = Tok;
636 PP.EnterToken(Consumed, /*IsReinject*/true);
637 PP.Lex(Tok);
638 PP.EnterToken(Next, /*IsReinject*/true);
639 }
640
641 SourceLocation ConsumeAnnotationToken() {
642 assert(Tok.isAnnotation() && "wrong consume method");
643 SourceLocation Loc = Tok.getLocation();
644 PrevTokLocation = Tok.getAnnotationEndLoc();
645 PP.Lex(Tok);
646 return Loc;
647 }
648
649 /// ConsumeParen - This consume method keeps the paren count up-to-date.
650 ///
651 SourceLocation ConsumeParen() {
652 assert(isTokenParen() && "wrong consume method");
653 if (Tok.getKind() == tok::l_paren)
654 ++ParenCount;
655 else if (ParenCount) {
656 AngleBrackets.clear(*this);
657 --ParenCount; // Don't let unbalanced )'s drive the count negative.
658 }
659 PrevTokLocation = Tok.getLocation();
660 PP.Lex(Tok);
661 return PrevTokLocation;
662 }
663
664 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
665 ///
666 SourceLocation ConsumeBracket() {
667 assert(isTokenBracket() && "wrong consume method");
668 if (Tok.getKind() == tok::l_square)
669 ++BracketCount;
670 else if (BracketCount) {
671 AngleBrackets.clear(*this);
672 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
673 }
674
675 PrevTokLocation = Tok.getLocation();
676 PP.Lex(Tok);
677 return PrevTokLocation;
678 }
679
680 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
681 ///
682 SourceLocation ConsumeBrace() {
683 assert(isTokenBrace() && "wrong consume method");
684 if (Tok.getKind() == tok::l_brace)
685 ++BraceCount;
686 else if (BraceCount) {
687 AngleBrackets.clear(*this);
688 --BraceCount; // Don't let unbalanced }'s drive the count negative.
689 }
690
691 PrevTokLocation = Tok.getLocation();
692 PP.Lex(Tok);
693 return PrevTokLocation;
694 }
695
696 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
697 /// and returning the token kind. This method is specific to strings, as it
698 /// handles string literal concatenation, as per C99 5.1.1.2, translation
699 /// phase #6.
700 SourceLocation ConsumeStringToken() {
701 assert(isTokenStringLiteral() &&
702 "Should only consume string literals with this method");
703 PrevTokLocation = Tok.getLocation();
704 PP.Lex(Tok);
705 return PrevTokLocation;
706 }
707
708 /// Consume the current code-completion token.
709 ///
710 /// This routine can be called to consume the code-completion token and
711 /// continue processing in special cases where \c cutOffParsing() isn't
712 /// desired, such as token caching or completion with lookahead.
713 SourceLocation ConsumeCodeCompletionToken() {
714 assert(Tok.is(tok::code_completion));
715 PrevTokLocation = Tok.getLocation();
716 PP.Lex(Tok);
717 return PrevTokLocation;
718 }
719
720 /// When we are consuming a code-completion token without having matched
721 /// specific position in the grammar, provide code-completion results based
722 /// on context.
723 ///
724 /// \returns the source location of the code-completion token.
725 SourceLocation handleUnexpectedCodeCompletionToken();
726
727 /// Abruptly cut off parsing; mainly used when we have reached the
728 /// code-completion point.
729 void cutOffParsing() {
732 // Cut off parsing by acting as if we reached the end-of-file.
733 Tok.setKind(tok::eof);
734 }
735
736 /// Determine if we're at the end of the file or at a transition
737 /// between modules.
738 bool isEofOrEom() {
740 return Kind == tok::eof || Kind == tok::annot_module_begin ||
741 Kind == tok::annot_module_end || Kind == tok::annot_module_include ||
742 Kind == tok::annot_repl_input_end;
743 }
744
745 /// Checks if the \p Level is valid for use in a fold expression.
746 bool isFoldOperator(prec::Level Level) const;
747
748 /// Checks if the \p Kind is a valid operator for fold expressions.
749 bool isFoldOperator(tok::TokenKind Kind) const;
750
751 /// Initialize all pragma handlers.
752 void initializePragmaHandlers();
753
754 /// Destroy and reset all pragma handlers.
755 void resetPragmaHandlers();
756
757 /// Handle the annotation token produced for #pragma unused(...)
758 void HandlePragmaUnused();
759
760 /// Handle the annotation token produced for
761 /// #pragma GCC visibility...
762 void HandlePragmaVisibility();
763
764 /// Handle the annotation token produced for
765 /// #pragma pack...
766 void HandlePragmaPack();
767
768 /// Handle the annotation token produced for
769 /// #pragma ms_struct...
770 void HandlePragmaMSStruct();
771
772 void HandlePragmaMSPointersToMembers();
773
774 void HandlePragmaMSVtorDisp();
775
776 void HandlePragmaMSPragma();
777 bool HandlePragmaMSSection(StringRef PragmaName,
778 SourceLocation PragmaLocation);
779 bool HandlePragmaMSSegment(StringRef PragmaName,
780 SourceLocation PragmaLocation);
781 bool HandlePragmaMSInitSeg(StringRef PragmaName,
782 SourceLocation PragmaLocation);
783 bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName,
784 SourceLocation PragmaLocation);
785 bool HandlePragmaMSFunction(StringRef PragmaName,
786 SourceLocation PragmaLocation);
787 bool HandlePragmaMSAllocText(StringRef PragmaName,
788 SourceLocation PragmaLocation);
789 bool HandlePragmaMSOptimize(StringRef PragmaName,
790 SourceLocation PragmaLocation);
791
792 /// Handle the annotation token produced for
793 /// #pragma align...
794 void HandlePragmaAlign();
795
796 /// Handle the annotation token produced for
797 /// #pragma clang __debug dump...
798 void HandlePragmaDump();
799
800 /// Handle the annotation token produced for
801 /// #pragma weak id...
802 void HandlePragmaWeak();
803
804 /// Handle the annotation token produced for
805 /// #pragma weak id = id...
806 void HandlePragmaWeakAlias();
807
808 /// Handle the annotation token produced for
809 /// #pragma redefine_extname...
810 void HandlePragmaRedefineExtname();
811
812 /// Handle the annotation token produced for
813 /// #pragma STDC FP_CONTRACT...
814 void HandlePragmaFPContract();
815
816 /// Handle the annotation token produced for
817 /// #pragma STDC FENV_ACCESS...
818 void HandlePragmaFEnvAccess();
819
820 /// Handle the annotation token produced for
821 /// #pragma STDC FENV_ROUND...
822 void HandlePragmaFEnvRound();
823
824 /// Handle the annotation token produced for
825 /// #pragma STDC CX_LIMITED_RANGE...
826 void HandlePragmaCXLimitedRange();
827
828 /// Handle the annotation token produced for
829 /// #pragma float_control
830 void HandlePragmaFloatControl();
831
832 /// \brief Handle the annotation token produced for
833 /// #pragma clang fp ...
834 void HandlePragmaFP();
835
836 /// Handle the annotation token produced for
837 /// #pragma OPENCL EXTENSION...
838 void HandlePragmaOpenCLExtension();
839
840 /// Handle the annotation token produced for
841 /// #pragma clang __debug captured
842 StmtResult HandlePragmaCaptured();
843
844 /// Handle the annotation token produced for
845 /// #pragma clang loop and #pragma unroll.
846 bool HandlePragmaLoopHint(LoopHint &Hint);
847
848 bool ParsePragmaAttributeSubjectMatchRuleSet(
849 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
850 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
851
852 void HandlePragmaAttribute();
853
854 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
855 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
856 /// returns the token after Tok, etc.
857 ///
858 /// Note that this differs from the Preprocessor's LookAhead method, because
859 /// the Parser always has one token lexed that the preprocessor doesn't.
860 ///
861 const Token &GetLookAheadToken(unsigned N) {
862 if (N == 0 || Tok.is(tok::eof)) return Tok;
863 return PP.LookAhead(N-1);
864 }
865
866public:
867 /// NextToken - This peeks ahead one token and returns it without
868 /// consuming it.
869 const Token &NextToken() {
870 return PP.LookAhead(0);
871 }
872
873 /// getTypeAnnotation - Read a parsed type out of an annotation token.
874 static TypeResult getTypeAnnotation(const Token &Tok) {
875 if (!Tok.getAnnotationValue())
876 return TypeError();
878 }
879
880private:
881 static void setTypeAnnotation(Token &Tok, TypeResult T) {
882 assert((T.isInvalid() || T.get()) &&
883 "produced a valid-but-null type annotation?");
884 Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr());
885 }
886
887 static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
888 return static_cast<NamedDecl*>(Tok.getAnnotationValue());
889 }
890
891 static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
892 Tok.setAnnotationValue(ND);
893 }
894
895 static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
896 return static_cast<IdentifierInfo*>(Tok.getAnnotationValue());
897 }
898
899 static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
900 Tok.setAnnotationValue(ND);
901 }
902
903 /// Read an already-translated primary expression out of an annotation
904 /// token.
905 static ExprResult getExprAnnotation(const Token &Tok) {
906 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
907 }
908
909 /// Set the primary expression corresponding to the given annotation
910 /// token.
911 static void setExprAnnotation(Token &Tok, ExprResult ER) {
912 Tok.setAnnotationValue(ER.getAsOpaquePointer());
913 }
914
915public:
916 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
917 // find a type name by attempting typo correction.
918 bool
922 CXXScopeSpec &SS, bool IsNewScope,
923 ImplicitTypenameContext AllowImplicitTypename);
924 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
925
927 return getLangOpts().CPlusPlus &&
928 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
929 (Tok.is(tok::annot_template_id) &&
930 NextToken().is(tok::coloncolon)) ||
931 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super));
932 }
933 bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
934 return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
935 }
936
937private:
938 enum AnnotatedNameKind {
939 /// Annotation has failed and emitted an error.
940 ANK_Error,
941 /// The identifier is a tentatively-declared name.
942 ANK_TentativeDecl,
943 /// The identifier is a template name. FIXME: Add an annotation for that.
944 ANK_TemplateName,
945 /// The identifier can't be resolved.
946 ANK_Unresolved,
947 /// Annotation was successful.
948 ANK_Success
949 };
950
951 AnnotatedNameKind
952 TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr,
953 ImplicitTypenameContext AllowImplicitTypename =
955
956 /// Push a tok::annot_cxxscope token onto the token stream.
957 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
958
959 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
960 /// replacing them with the non-context-sensitive keywords. This returns
961 /// true if the token was replaced.
962 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
963 const char *&PrevSpec, unsigned &DiagID,
964 bool &isInvalid) {
965 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
966 return false;
967
968 if (Tok.getIdentifierInfo() != Ident_vector &&
969 Tok.getIdentifierInfo() != Ident_bool &&
970 Tok.getIdentifierInfo() != Ident_Bool &&
971 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
972 return false;
973
974 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
975 }
976
977 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
978 /// identifier token, replacing it with the non-context-sensitive __vector.
979 /// This returns true if the token was replaced.
980 bool TryAltiVecVectorToken() {
981 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
982 Tok.getIdentifierInfo() != Ident_vector) return false;
983 return TryAltiVecVectorTokenOutOfLine();
984 }
985
986 bool TryAltiVecVectorTokenOutOfLine();
987 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
988 const char *&PrevSpec, unsigned &DiagID,
989 bool &isInvalid);
990
991 /// Returns true if the current token is the identifier 'instancetype'.
992 ///
993 /// Should only be used in Objective-C language modes.
994 bool isObjCInstancetype() {
995 assert(getLangOpts().ObjC);
996 if (Tok.isAnnotation())
997 return false;
998 if (!Ident_instancetype)
999 Ident_instancetype = PP.getIdentifierInfo("instancetype");
1000 return Tok.getIdentifierInfo() == Ident_instancetype;
1001 }
1002
1003 /// TryKeywordIdentFallback - For compatibility with system headers using
1004 /// keywords as identifiers, attempt to convert the current token to an
1005 /// identifier and optionally disable the keyword for the remainder of the
1006 /// translation unit. This returns false if the token was not replaced,
1007 /// otherwise emits a diagnostic and returns true.
1008 bool TryKeywordIdentFallback(bool DisableKeyword);
1009
1010 /// Get the TemplateIdAnnotation from the token.
1011 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
1012
1013 /// TentativeParsingAction - An object that is used as a kind of "tentative
1014 /// parsing transaction". It gets instantiated to mark the token position and
1015 /// after the token consumption is done, Commit() or Revert() is called to
1016 /// either "commit the consumed tokens" or revert to the previously marked
1017 /// token position. Example:
1018 ///
1019 /// TentativeParsingAction TPA(*this);
1020 /// ConsumeToken();
1021 /// ....
1022 /// TPA.Revert();
1023 ///
1024 class TentativeParsingAction {
1025 Parser &P;
1026 PreferredTypeBuilder PrevPreferredType;
1027 Token PrevTok;
1028 size_t PrevTentativelyDeclaredIdentifierCount;
1029 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
1030 bool isActive;
1031
1032 public:
1033 explicit TentativeParsingAction(Parser &p)
1034 : P(p), PrevPreferredType(P.PreferredType) {
1035 PrevTok = P.Tok;
1036 PrevTentativelyDeclaredIdentifierCount =
1037 P.TentativelyDeclaredIdentifiers.size();
1038 PrevParenCount = P.ParenCount;
1039 PrevBracketCount = P.BracketCount;
1040 PrevBraceCount = P.BraceCount;
1041 P.PP.EnableBacktrackAtThisPos();
1042 isActive = true;
1043 }
1044 void Commit() {
1045 assert(isActive && "Parsing action was finished!");
1046 P.TentativelyDeclaredIdentifiers.resize(
1047 PrevTentativelyDeclaredIdentifierCount);
1048 P.PP.CommitBacktrackedTokens();
1049 isActive = false;
1050 }
1051 void Revert() {
1052 assert(isActive && "Parsing action was finished!");
1053 P.PP.Backtrack();
1054 P.PreferredType = PrevPreferredType;
1055 P.Tok = PrevTok;
1056 P.TentativelyDeclaredIdentifiers.resize(
1057 PrevTentativelyDeclaredIdentifierCount);
1058 P.ParenCount = PrevParenCount;
1059 P.BracketCount = PrevBracketCount;
1060 P.BraceCount = PrevBraceCount;
1061 isActive = false;
1062 }
1063 ~TentativeParsingAction() {
1064 assert(!isActive && "Forgot to call Commit or Revert!");
1065 }
1066 };
1067 /// A TentativeParsingAction that automatically reverts in its destructor.
1068 /// Useful for disambiguation parses that will always be reverted.
1069 class RevertingTentativeParsingAction
1070 : private Parser::TentativeParsingAction {
1071 public:
1072 RevertingTentativeParsingAction(Parser &P)
1073 : Parser::TentativeParsingAction(P) {}
1074 ~RevertingTentativeParsingAction() { Revert(); }
1075 };
1076
1077 class UnannotatedTentativeParsingAction;
1078
1079 /// ObjCDeclContextSwitch - An object used to switch context from
1080 /// an objective-c decl context to its enclosing decl context and
1081 /// back.
1082 class ObjCDeclContextSwitch {
1083 Parser &P;
1084 ObjCContainerDecl *DC;
1085 SaveAndRestore<bool> WithinObjCContainer;
1086 public:
1087 explicit ObjCDeclContextSwitch(Parser &p)
1088 : P(p), DC(p.getObjCDeclContext()),
1089 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
1090 if (DC)
1091 P.Actions.ObjC().ActOnObjCTemporaryExitContainerContext(DC);
1092 }
1093 ~ObjCDeclContextSwitch() {
1094 if (DC)
1095 P.Actions.ObjC().ActOnObjCReenterContainerContext(DC);
1096 }
1097 };
1098
1099 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
1100 /// input. If so, it is consumed and false is returned.
1101 ///
1102 /// If a trivial punctuator misspelling is encountered, a FixIt error
1103 /// diagnostic is issued and false is returned after recovery.
1104 ///
1105 /// If the input is malformed, this emits the specified diagnostic and true is
1106 /// returned.
1107 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
1108 unsigned Diag = diag::err_expected,
1109 StringRef DiagMsg = "");
1110
1111 /// The parser expects a semicolon and, if present, will consume it.
1112 ///
1113 /// If the next token is not a semicolon, this emits the specified diagnostic,
1114 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
1115 /// to the semicolon, consumes that extra token.
1116 bool ExpectAndConsumeSemi(unsigned DiagID , StringRef TokenUsed = "");
1117
1118 /// The kind of extra semi diagnostic to emit.
1119 enum ExtraSemiKind {
1120 OutsideFunction = 0,
1121 InsideStruct = 1,
1122 InstanceVariableList = 2,
1123 AfterMemberFunctionDefinition = 3
1124 };
1125
1126 /// Consume any extra semi-colons until the end of the line.
1127 void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
1128
1129 /// Return false if the next token is an identifier. An 'expected identifier'
1130 /// error is emitted otherwise.
1131 ///
1132 /// The parser tries to recover from the error by checking if the next token
1133 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
1134 /// was successful.
1135 bool expectIdentifier();
1136
1137 /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
1138 enum class CompoundToken {
1139 /// A '(' '{' beginning a statement-expression.
1140 StmtExprBegin,
1141 /// A '}' ')' ending a statement-expression.
1142 StmtExprEnd,
1143 /// A '[' '[' beginning a C++11 or C23 attribute.
1144 AttrBegin,
1145 /// A ']' ']' ending a C++11 or C23 attribute.
1146 AttrEnd,
1147 /// A '::' '*' forming a C++ pointer-to-member declaration.
1148 MemberPtr,
1149 };
1150
1151 /// Check that a compound operator was written in a "sensible" way, and warn
1152 /// if not.
1153 void checkCompoundToken(SourceLocation FirstTokLoc,
1154 tok::TokenKind FirstTokKind, CompoundToken Op);
1155
1156 void diagnoseUseOfC11Keyword(const Token &Tok);
1157
1158public:
1159 //===--------------------------------------------------------------------===//
1160 // Scope manipulation
1161
1162 /// ParseScope - Introduces a new scope for parsing. The kind of
1163 /// scope is determined by ScopeFlags. Objects of this type should
1164 /// be created on the stack to coincide with the position where the
1165 /// parser enters the new scope, and this object's constructor will
1166 /// create that new scope. Similarly, once the object is destroyed
1167 /// the parser will exit the scope.
1169 Parser *Self;
1170 ParseScope(const ParseScope &) = delete;
1171 void operator=(const ParseScope &) = delete;
1172
1173 public:
1174 // ParseScope - Construct a new object to manage a scope in the
1175 // parser Self where the new Scope is created with the flags
1176 // ScopeFlags, but only when we aren't about to enter a compound statement.
1177 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
1178 bool BeforeCompoundStmt = false)
1179 : Self(Self) {
1180 if (EnteredScope && !BeforeCompoundStmt)
1181 Self->EnterScope(ScopeFlags);
1182 else {
1183 if (BeforeCompoundStmt)
1184 Self->incrementMSManglingNumber();
1185
1186 this->Self = nullptr;
1187 }
1188 }
1189
1190 // Exit - Exit the scope associated with this object now, rather
1191 // than waiting until the object is destroyed.
1192 void Exit() {
1193 if (Self) {
1194 Self->ExitScope();
1195 Self = nullptr;
1196 }
1197 }
1198
1200 Exit();
1201 }
1202 };
1203
1204 /// Introduces zero or more scopes for parsing. The scopes will all be exited
1205 /// when the object is destroyed.
1207 Parser &Self;
1208 unsigned NumScopes = 0;
1209
1210 MultiParseScope(const MultiParseScope&) = delete;
1211
1212 public:
1213 MultiParseScope(Parser &Self) : Self(Self) {}
1214 void Enter(unsigned ScopeFlags) {
1215 Self.EnterScope(ScopeFlags);
1216 ++NumScopes;
1217 }
1218 void Exit() {
1219 while (NumScopes) {
1220 Self.ExitScope();
1221 --NumScopes;
1222 }
1223 }
1225 Exit();
1226 }
1227 };
1228
1229 /// EnterScope - Start a new scope.
1230 void EnterScope(unsigned ScopeFlags);
1231
1232 /// ExitScope - Pop a scope off the scope stack.
1233 void ExitScope();
1234
1235 /// Re-enter the template scopes for a declaration that might be a template.
1236 unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D);
1237
1238private:
1239 /// RAII object used to modify the scope flags for the current scope.
1240 class ParseScopeFlags {
1241 Scope *CurScope;
1242 unsigned OldFlags = 0;
1243 ParseScopeFlags(const ParseScopeFlags &) = delete;
1244 void operator=(const ParseScopeFlags &) = delete;
1245
1246 public:
1247 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
1248 ~ParseScopeFlags();
1249 };
1250
1251 //===--------------------------------------------------------------------===//
1252 // Diagnostic Emission and Error recovery.
1253
1254public:
1255 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1256 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
1257 DiagnosticBuilder Diag(unsigned DiagID) {
1258 return Diag(Tok, DiagID);
1259 }
1260
1261private:
1262 void SuggestParentheses(SourceLocation Loc, unsigned DK,
1263 SourceRange ParenRange);
1264 void CheckNestedObjCContexts(SourceLocation AtLoc);
1265
1266public:
1267
1268 /// Control flags for SkipUntil functions.
1270 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
1271 /// Stop skipping at specified token, but don't skip the token itself
1273 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
1275
1277 SkipUntilFlags R) {
1278 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
1279 static_cast<unsigned>(R));
1280 }
1281
1282 /// SkipUntil - Read tokens until we get to the specified token, then consume
1283 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
1284 /// that the token will ever occur, this skips to the next token, or to some
1285 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
1286 /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
1287 /// skipping.
1288 ///
1289 /// If SkipUntil finds the specified token, it returns true, otherwise it
1290 /// returns false.
1292 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1293 return SkipUntil(llvm::ArrayRef(T), Flags);
1294 }
1296 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1297 tok::TokenKind TokArray[] = {T1, T2};
1298 return SkipUntil(TokArray, Flags);
1299 }
1301 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1302 tok::TokenKind TokArray[] = {T1, T2, T3};
1303 return SkipUntil(TokArray, Flags);
1304 }
1306 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
1307
1308 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1309 /// point for skipping past a simple-declaration.
1310 void SkipMalformedDecl();
1311
1312 /// The location of the first statement inside an else that might
1313 /// have a missleading indentation. If there is no
1314 /// MisleadingIndentationChecker on an else active, this location is invalid.
1316
1317private:
1318 //===--------------------------------------------------------------------===//
1319 // Lexing and parsing of C++ inline methods.
1320
1321 struct ParsingClass;
1322
1323 /// [class.mem]p1: "... the class is regarded as complete within
1324 /// - function bodies
1325 /// - default arguments
1326 /// - exception-specifications (TODO: C++0x)
1327 /// - and brace-or-equal-initializers for non-static data members
1328 /// (including such things in nested classes)."
1329 /// LateParsedDeclarations build the tree of those elements so they can
1330 /// be parsed after parsing the top-level class.
1331 class LateParsedDeclaration {
1332 public:
1333 virtual ~LateParsedDeclaration();
1334
1335 virtual void ParseLexedMethodDeclarations();
1336 virtual void ParseLexedMemberInitializers();
1337 virtual void ParseLexedMethodDefs();
1338 virtual void ParseLexedAttributes();
1339 virtual void ParseLexedPragmas();
1340 };
1341
1342 /// Inner node of the LateParsedDeclaration tree that parses
1343 /// all its members recursively.
1344 class LateParsedClass : public LateParsedDeclaration {
1345 public:
1346 LateParsedClass(Parser *P, ParsingClass *C);
1347 ~LateParsedClass() override;
1348
1349 void ParseLexedMethodDeclarations() override;
1350 void ParseLexedMemberInitializers() override;
1351 void ParseLexedMethodDefs() override;
1352 void ParseLexedAttributes() override;
1353 void ParseLexedPragmas() override;
1354
1355 private:
1356 Parser *Self;
1357 ParsingClass *Class;
1358 };
1359
1360 /// Contains the lexed tokens of an attribute with arguments that
1361 /// may reference member variables and so need to be parsed at the
1362 /// end of the class declaration after parsing all other member
1363 /// member declarations.
1364 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1365 /// LateParsedTokens.
1366 struct LateParsedAttribute : public LateParsedDeclaration {
1367 Parser *Self;
1368 CachedTokens Toks;
1369 IdentifierInfo &AttrName;
1370 IdentifierInfo *MacroII = nullptr;
1371 SourceLocation AttrNameLoc;
1372 SmallVector<Decl*, 2> Decls;
1373
1374 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1375 SourceLocation Loc)
1376 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1377
1378 void ParseLexedAttributes() override;
1379
1380 void addDecl(Decl *D) { Decls.push_back(D); }
1381 };
1382
1383 /// Contains the lexed tokens of a pragma with arguments that
1384 /// may reference member variables and so need to be parsed at the
1385 /// end of the class declaration after parsing all other member
1386 /// member declarations.
1387 class LateParsedPragma : public LateParsedDeclaration {
1388 Parser *Self = nullptr;
1390 CachedTokens Toks;
1391
1392 public:
1393 explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
1394 : Self(P), AS(AS) {}
1395
1396 void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
1397 const CachedTokens &toks() const { return Toks; }
1398 AccessSpecifier getAccessSpecifier() const { return AS; }
1399
1400 void ParseLexedPragmas() override;
1401 };
1402
1403 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1404 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1405 public:
1406 LateParsedAttrList(bool PSoon = false,
1407 bool LateAttrParseExperimentalExtOnly = false)
1408 : ParseSoon(PSoon),
1409 LateAttrParseExperimentalExtOnly(LateAttrParseExperimentalExtOnly) {}
1410
1411 bool parseSoon() { return ParseSoon; }
1412 /// returns true iff the attribute to be parsed should only be late parsed
1413 /// if it is annotated with `LateAttrParseExperimentalExt`
1414 bool lateAttrParseExperimentalExtOnly() {
1415 return LateAttrParseExperimentalExtOnly;
1416 }
1417
1418 private:
1419 bool ParseSoon; // Are we planning to parse these shortly after creation?
1420 bool LateAttrParseExperimentalExtOnly;
1421 };
1422
1423 /// Contains the lexed tokens of a member function definition
1424 /// which needs to be parsed at the end of the class declaration
1425 /// after parsing all other member declarations.
1426 struct LexedMethod : public LateParsedDeclaration {
1427 Parser *Self;
1428 Decl *D;
1429 CachedTokens Toks;
1430
1431 explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
1432
1433 void ParseLexedMethodDefs() override;
1434 };
1435
1436 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1437 /// have a default argument that cannot be parsed yet because it
1438 /// occurs within a member function declaration inside the class
1439 /// (C++ [class.mem]p2).
1440 struct LateParsedDefaultArgument {
1441 explicit LateParsedDefaultArgument(Decl *P,
1442 std::unique_ptr<CachedTokens> Toks = nullptr)
1443 : Param(P), Toks(std::move(Toks)) { }
1444
1445 /// Param - The parameter declaration for this parameter.
1446 Decl *Param;
1447
1448 /// Toks - The sequence of tokens that comprises the default
1449 /// argument expression, not including the '=' or the terminating
1450 /// ')' or ','. This will be NULL for parameters that have no
1451 /// default argument.
1452 std::unique_ptr<CachedTokens> Toks;
1453 };
1454
1455 /// LateParsedMethodDeclaration - A method declaration inside a class that
1456 /// contains at least one entity whose parsing needs to be delayed
1457 /// until the class itself is completely-defined, such as a default
1458 /// argument (C++ [class.mem]p2).
1459 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1460 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1461 : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
1462
1463 void ParseLexedMethodDeclarations() override;
1464
1465 Parser *Self;
1466
1467 /// Method - The method declaration.
1468 Decl *Method;
1469
1470 /// DefaultArgs - Contains the parameters of the function and
1471 /// their default arguments. At least one of the parameters will
1472 /// have a default argument, but all of the parameters of the
1473 /// method will be stored so that they can be reintroduced into
1474 /// scope at the appropriate times.
1475 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1476
1477 /// The set of tokens that make up an exception-specification that
1478 /// has not yet been parsed.
1479 CachedTokens *ExceptionSpecTokens;
1480 };
1481
1482 /// LateParsedMemberInitializer - An initializer for a non-static class data
1483 /// member whose parsing must to be delayed until the class is completely
1484 /// defined (C++11 [class.mem]p2).
1485 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1486 LateParsedMemberInitializer(Parser *P, Decl *FD)
1487 : Self(P), Field(FD) { }
1488
1489 void ParseLexedMemberInitializers() override;
1490
1491 Parser *Self;
1492
1493 /// Field - The field declaration.
1494 Decl *Field;
1495
1496 /// CachedTokens - The sequence of tokens that comprises the initializer,
1497 /// including any leading '='.
1498 CachedTokens Toks;
1499 };
1500
1501 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1502 /// C++ class, its method declarations that contain parts that won't be
1503 /// parsed until after the definition is completed (C++ [class.mem]p2),
1504 /// the method declarations and possibly attached inline definitions
1505 /// will be stored here with the tokens that will be parsed to create those
1506 /// entities.
1507 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1508
1509 /// Representation of a class that has been parsed, including
1510 /// any member function declarations or definitions that need to be
1511 /// parsed after the corresponding top-level class is complete.
1512 struct ParsingClass {
1513 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1514 : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
1515 TagOrTemplate(TagOrTemplate) {}
1516
1517 /// Whether this is a "top-level" class, meaning that it is
1518 /// not nested within another class.
1519 bool TopLevelClass : 1;
1520
1521 /// Whether this class is an __interface.
1522 bool IsInterface : 1;
1523
1524 /// The class or class template whose definition we are parsing.
1525 Decl *TagOrTemplate;
1526
1527 /// LateParsedDeclarations - Method declarations, inline definitions and
1528 /// nested classes that contain pieces whose parsing will be delayed until
1529 /// the top-level class is fully defined.
1530 LateParsedDeclarationsContainer LateParsedDeclarations;
1531 };
1532
1533 /// The stack of classes that is currently being
1534 /// parsed. Nested and local classes will be pushed onto this stack
1535 /// when they are parsed, and removed afterward.
1536 std::stack<ParsingClass *> ClassStack;
1537
1538 ParsingClass &getCurrentClass() {
1539 assert(!ClassStack.empty() && "No lexed method stacks!");
1540 return *ClassStack.top();
1541 }
1542
1543 /// RAII object used to manage the parsing of a class definition.
1544 class ParsingClassDefinition {
1545 Parser &P;
1546 bool Popped;
1548
1549 public:
1550 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1551 bool IsInterface)
1552 : P(P), Popped(false),
1553 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1554 }
1555
1556 /// Pop this class of the stack.
1557 void Pop() {
1558 assert(!Popped && "Nested class has already been popped");
1559 Popped = true;
1560 P.PopParsingClass(State);
1561 }
1562
1563 ~ParsingClassDefinition() {
1564 if (!Popped)
1565 P.PopParsingClass(State);
1566 }
1567 };
1568
1569 /// Contains information about any template-specific
1570 /// information that has been parsed prior to parsing declaration
1571 /// specifiers.
1572 struct ParsedTemplateInfo {
1573 ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr) {}
1574
1575 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1576 bool isSpecialization,
1577 bool lastParameterListWasEmpty = false)
1578 : Kind(isSpecialization? ExplicitSpecialization : Template),
1579 TemplateParams(TemplateParams),
1580 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1581
1582 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1583 SourceLocation TemplateLoc)
1584 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1585 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1586 LastParameterListWasEmpty(false){ }
1587
1588 /// The kind of template we are parsing.
1589 enum {
1590 /// We are not parsing a template at all.
1591 NonTemplate = 0,
1592 /// We are parsing a template declaration.
1593 Template,
1594 /// We are parsing an explicit specialization.
1595 ExplicitSpecialization,
1596 /// We are parsing an explicit instantiation.
1597 ExplicitInstantiation
1598 } Kind;
1599
1600 /// The template parameter lists, for template declarations
1601 /// and explicit specializations.
1602 TemplateParameterLists *TemplateParams;
1603
1604 /// The location of the 'extern' keyword, if any, for an explicit
1605 /// instantiation
1606 SourceLocation ExternLoc;
1607
1608 /// The location of the 'template' keyword, for an explicit
1609 /// instantiation.
1610 SourceLocation TemplateLoc;
1611
1612 /// Whether the last template parameter list was empty.
1613 bool LastParameterListWasEmpty;
1614
1615 SourceRange getSourceRange() const LLVM_READONLY;
1616 };
1617
1618 // In ParseCXXInlineMethods.cpp.
1619 struct ReenterTemplateScopeRAII;
1620 struct ReenterClassScopeRAII;
1621
1622 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1623 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1624
1625 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1626
1627 Sema::ParsingClassState
1628 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1629 void DeallocateParsedClasses(ParsingClass *Class);
1630 void PopParsingClass(Sema::ParsingClassState);
1631
1632 enum CachedInitKind {
1633 CIK_DefaultArgument,
1634 CIK_DefaultInitializer
1635 };
1636
1637 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1638 const ParsedAttributesView &AccessAttrs,
1639 ParsingDeclarator &D,
1640 const ParsedTemplateInfo &TemplateInfo,
1641 const VirtSpecifiers &VS,
1642 SourceLocation PureSpecLoc);
1643 StringLiteral *ParseCXXDeletedFunctionMessage();
1644 void SkipDeletedFunctionBody();
1645 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1646 void ParseLexedAttributes(ParsingClass &Class);
1647 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1648 bool EnterScope, bool OnDefinition);
1649 void ParseLexedAttribute(LateParsedAttribute &LA,
1650 bool EnterScope, bool OnDefinition);
1651 void ParseLexedMethodDeclarations(ParsingClass &Class);
1652 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1653 void ParseLexedMethodDefs(ParsingClass &Class);
1654 void ParseLexedMethodDef(LexedMethod &LM);
1655 void ParseLexedMemberInitializers(ParsingClass &Class);
1656 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1657 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1658 void ParseLexedPragmas(ParsingClass &Class);
1659 void ParseLexedPragma(LateParsedPragma &LP);
1660 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1661 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1662 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1663 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1664 CachedTokens &Toks,
1665 bool StopAtSemi = true,
1666 bool ConsumeFinalToken = true) {
1667 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1668 }
1669 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1670 CachedTokens &Toks,
1671 bool StopAtSemi = true,
1672 bool ConsumeFinalToken = true);
1673
1674 //===--------------------------------------------------------------------===//
1675 // C99 6.9: External Definitions.
1676 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributes &DeclAttrs,
1677 ParsedAttributes &DeclSpecAttrs,
1678 ParsingDeclSpec *DS = nullptr);
1679 bool isDeclarationAfterDeclarator();
1680 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1681 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1682 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1683 ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none);
1684 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs,
1685 ParsedAttributes &DeclSpecAttrs,
1686 ParsingDeclSpec &DS,
1687 AccessSpecifier AS);
1688
1689 void SkipFunctionBody();
1690 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1691 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1692 LateParsedAttrList *LateParsedAttrs = nullptr);
1693 void ParseKNRParamDeclarations(Declarator &D);
1694 // EndLoc is filled with the location of the last token of the simple-asm.
1695 ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
1696 ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
1697
1698 // Objective-C External Declarations
1699 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1700 DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
1701 ParsedAttributes &DeclSpecAttrs);
1702 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1703 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1704 ParsedAttributes &prefixAttrs);
1705 class ObjCTypeParamListScope;
1706 ObjCTypeParamList *parseObjCTypeParamList();
1707 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1708 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1709 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1710 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1711
1712 void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl,
1713 SourceLocation atLoc,
1715 SmallVectorImpl<Decl *> &AllIvarDecls,
1716 bool RBraceMissing);
1717 void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
1718 tok::ObjCKeywordKind visibility,
1719 SourceLocation atLoc);
1720 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1721 SmallVectorImpl<SourceLocation> &PLocs,
1722 bool WarnOnDeclarations,
1723 bool ForObjCContainer,
1724 SourceLocation &LAngleLoc,
1725 SourceLocation &EndProtoLoc,
1726 bool consumeLastToken);
1727
1728 /// Parse the first angle-bracket-delimited clause for an
1729 /// Objective-C object or object pointer type, which may be either
1730 /// type arguments or protocol qualifiers.
1731 void parseObjCTypeArgsOrProtocolQualifiers(
1732 ParsedType baseType,
1733 SourceLocation &typeArgsLAngleLoc,
1734 SmallVectorImpl<ParsedType> &typeArgs,
1735 SourceLocation &typeArgsRAngleLoc,
1736 SourceLocation &protocolLAngleLoc,
1737 SmallVectorImpl<Decl *> &protocols,
1738 SmallVectorImpl<SourceLocation> &protocolLocs,
1739 SourceLocation &protocolRAngleLoc,
1740 bool consumeLastToken,
1741 bool warnOnIncompleteProtocols);
1742
1743 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1744 /// former, also parse protocol qualifiers afterward.
1745 void parseObjCTypeArgsAndProtocolQualifiers(
1746 ParsedType baseType,
1747 SourceLocation &typeArgsLAngleLoc,
1748 SmallVectorImpl<ParsedType> &typeArgs,
1749 SourceLocation &typeArgsRAngleLoc,
1750 SourceLocation &protocolLAngleLoc,
1751 SmallVectorImpl<Decl *> &protocols,
1752 SmallVectorImpl<SourceLocation> &protocolLocs,
1753 SourceLocation &protocolRAngleLoc,
1754 bool consumeLastToken);
1755
1756 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1757 /// an anachronistic way of writing 'id<NSCopying>'.
1758 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1759
1760 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1761 /// current type with the parsed result.
1762 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1764 bool consumeLastToken,
1765 SourceLocation &endLoc);
1766
1767 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1768 Decl *CDecl);
1769 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1770 ParsedAttributes &prefixAttrs);
1771
1772 struct ObjCImplParsingDataRAII {
1773 Parser &P;
1774 Decl *Dcl;
1775 bool HasCFunction;
1776 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1777 LateParsedObjCMethodContainer LateParsedObjCMethods;
1778
1779 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1780 : P(parser), Dcl(D), HasCFunction(false) {
1781 P.CurParsedObjCImpl = this;
1782 Finished = false;
1783 }
1784 ~ObjCImplParsingDataRAII();
1785
1786 void finish(SourceRange AtEnd);
1787 bool isFinished() const { return Finished; }
1788
1789 private:
1790 bool Finished;
1791 };
1792 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1793 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1794
1795 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
1796 ParsedAttributes &Attrs);
1797 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1798 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1799 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1800 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1801
1802 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1803 // Definitions for Objective-c context sensitive keywords recognition.
1804 enum ObjCTypeQual {
1805 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1806 objc_nonnull, objc_nullable, objc_null_unspecified,
1807 objc_NumQuals
1808 };
1809 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1810
1811 bool isTokIdentifier_in() const;
1812
1813 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
1814 ParsedAttributes *ParamAttrs);
1815 Decl *ParseObjCMethodPrototype(
1816 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1817 bool MethodDefinition = true);
1818 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1819 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1820 bool MethodDefinition=true);
1821 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1822
1823 Decl *ParseObjCMethodDefinition();
1824
1825public:
1826 //===--------------------------------------------------------------------===//
1827 // C99 6.5: Expressions.
1828
1829 /// TypeCastState - State whether an expression is or may be a type cast.
1835
1838 TypeCastState isTypeCast = NotTypeCast);
1844 ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
1845 ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
1846 // Expr that doesn't include commas.
1849
1851 unsigned &NumLineToksConsumed,
1852 bool IsUnevaluated);
1853
1854 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1856
1857private:
1858 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral,
1859 bool Unevaluated);
1860
1861 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1862
1863 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1864
1865 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1866 prec::Level MinPrec);
1867 /// Control what ParseCastExpression will parse.
1868 enum CastParseKind {
1869 AnyCastExpr = 0,
1870 UnaryExprOnly,
1871 PrimaryExprOnly
1872 };
1873 ExprResult ParseCastExpression(CastParseKind ParseKind,
1874 bool isAddressOfOperand,
1875 bool &NotCastExpr,
1876 TypeCastState isTypeCast,
1877 bool isVectorLiteral = false,
1878 bool *NotPrimaryExpression = nullptr);
1879 ExprResult ParseCastExpression(CastParseKind ParseKind,
1880 bool isAddressOfOperand = false,
1881 TypeCastState isTypeCast = NotTypeCast,
1882 bool isVectorLiteral = false,
1883 bool *NotPrimaryExpression = nullptr);
1884
1885 /// Returns true if the next token cannot start an expression.
1886 bool isNotExpressionStart();
1887
1888 /// Returns true if the next token would start a postfix-expression
1889 /// suffix.
1890 bool isPostfixExpressionSuffixStart() {
1891 tok::TokenKind K = Tok.getKind();
1892 return (K == tok::l_square || K == tok::l_paren ||
1893 K == tok::period || K == tok::arrow ||
1894 K == tok::plusplus || K == tok::minusminus);
1895 }
1896
1897 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1898 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
1899 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
1900 const Token &OpToken);
1901 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1902 if (auto *Info = AngleBrackets.getCurrent(*this))
1903 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1904 return false;
1905 }
1906
1907 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1908 ExprResult ParseUnaryExprOrTypeTraitExpression();
1909 ExprResult ParseBuiltinPrimaryExpression();
1910 ExprResult ParseSYCLUniqueStableNameExpression();
1911
1912 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1913 bool &isCastExpr,
1914 ParsedType &CastTy,
1915 SourceRange &CastRange);
1916
1917 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1918 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1919 llvm::function_ref<void()> ExpressionStarts =
1920 llvm::function_ref<void()>(),
1921 bool FailImmediatelyOnInvalidExpr = false,
1922 bool EarlyTypoCorrection = false);
1923
1924 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1925 /// used for misc language extensions.
1926 bool ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs);
1927
1928 /// ParenParseOption - Control what ParseParenExpression will parse.
1929 enum ParenParseOption {
1930 SimpleExpr, // Only parse '(' expression ')'
1931 FoldExpr, // Also allow fold-expression <anything>
1932 CompoundStmt, // Also allow '(' compound-statement ')'
1933 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1934 CastExpr // Also allow '(' type-name ')' <anything>
1935 };
1936 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1937 bool stopIfCastExpr,
1938 bool isTypeCast,
1939 ParsedType &CastTy,
1940 SourceLocation &RParenLoc);
1941
1942 ExprResult ParseCXXAmbiguousParenExpression(
1943 ParenParseOption &ExprType, ParsedType &CastTy,
1945 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1946 SourceLocation LParenLoc,
1947 SourceLocation RParenLoc);
1948
1949 ExprResult ParseGenericSelectionExpression();
1950
1951 ExprResult ParseObjCBoolLiteral();
1952
1953 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1954
1955 //===--------------------------------------------------------------------===//
1956 // C++ Expressions
1957 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1958 Token &Replacement);
1959
1960 ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression);
1961 ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression);
1962
1963 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1964
1965 bool areTokensAdjacent(const Token &A, const Token &B);
1966
1967 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1968 bool EnteringContext, IdentifierInfo &II,
1969 CXXScopeSpec &SS);
1970
1971 bool ParseOptionalCXXScopeSpecifier(
1972 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors,
1973 bool EnteringContext, bool *MayBePseudoDestructor = nullptr,
1974 bool IsTypename = false, const IdentifierInfo **LastII = nullptr,
1975 bool OnlyNamespace = false, bool InUsingDeclaration = false);
1976
1977 //===--------------------------------------------------------------------===//
1978 // C++11 5.1.2: Lambda expressions
1979
1980 /// Result of tentatively parsing a lambda-introducer.
1981 enum class LambdaIntroducerTentativeParse {
1982 /// This appears to be a lambda-introducer, which has been fully parsed.
1983 Success,
1984 /// This is a lambda-introducer, but has not been fully parsed, and this
1985 /// function needs to be called again to parse it.
1986 Incomplete,
1987 /// This is definitely an Objective-C message send expression, rather than
1988 /// a lambda-introducer, attribute-specifier, or array designator.
1989 MessageSend,
1990 /// This is not a lambda-introducer.
1991 Invalid,
1992 };
1993
1994 // [...] () -> type {...}
1995 ExprResult ParseLambdaExpression();
1996 ExprResult TryParseLambdaExpression();
1997 bool
1998 ParseLambdaIntroducer(LambdaIntroducer &Intro,
1999 LambdaIntroducerTentativeParse *Tentative = nullptr);
2000 ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
2001
2002 //===--------------------------------------------------------------------===//
2003 // C++ 5.2p1: C++ Casts
2004 ExprResult ParseCXXCasts();
2005
2006 /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
2007 ExprResult ParseBuiltinBitCast();
2008
2009 //===--------------------------------------------------------------------===//
2010 // C++ 5.2p1: C++ Type Identification
2011 ExprResult ParseCXXTypeid();
2012
2013 //===--------------------------------------------------------------------===//
2014 // C++ : Microsoft __uuidof Expression
2015 ExprResult ParseCXXUuidof();
2016
2017 //===--------------------------------------------------------------------===//
2018 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
2019 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
2020 tok::TokenKind OpKind,
2021 CXXScopeSpec &SS,
2022 ParsedType ObjectType);
2023
2024 //===--------------------------------------------------------------------===//
2025 // C++ 9.3.2: C++ 'this' pointer
2026 ExprResult ParseCXXThis();
2027
2028 //===--------------------------------------------------------------------===//
2029 // C++ 15: C++ Throw Expression
2030 ExprResult ParseThrowExpression();
2031
2032 ExceptionSpecificationType tryParseExceptionSpecification(
2033 bool Delayed,
2034 SourceRange &SpecificationRange,
2035 SmallVectorImpl<ParsedType> &DynamicExceptions,
2036 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2037 ExprResult &NoexceptExpr,
2038 CachedTokens *&ExceptionSpecTokens);
2039
2040 // EndLoc is filled with the location of the last token of the specification.
2041 ExceptionSpecificationType ParseDynamicExceptionSpecification(
2042 SourceRange &SpecificationRange,
2043 SmallVectorImpl<ParsedType> &Exceptions,
2044 SmallVectorImpl<SourceRange> &Ranges);
2045
2046 //===--------------------------------------------------------------------===//
2047 // C++0x 8: Function declaration trailing-return-type
2048 TypeResult ParseTrailingReturnType(SourceRange &Range,
2049 bool MayBeFollowedByDirectInit);
2050
2051 //===--------------------------------------------------------------------===//
2052 // C++ 2.13.5: C++ Boolean Literals
2053 ExprResult ParseCXXBoolLiteral();
2054
2055 //===--------------------------------------------------------------------===//
2056 // C++ 5.2.3: Explicit type conversion (functional notation)
2057 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
2058
2059 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2060 /// This should only be called when the current token is known to be part of
2061 /// simple-type-specifier.
2062 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
2063
2064 bool ParseCXXTypeSpecifierSeq(
2065 DeclSpec &DS, DeclaratorContext Context = DeclaratorContext::TypeName);
2066
2067 //===--------------------------------------------------------------------===//
2068 // C++ 5.3.4 and 5.3.5: C++ new and delete
2069 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
2070 Declarator &D);
2071 void ParseDirectNewDeclarator(Declarator &D);
2072 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
2073 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
2074 SourceLocation Start);
2075
2076 //===--------------------------------------------------------------------===//
2077 // C++ if/switch/while/for condition expression.
2078 struct ForRangeInfo;
2079 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
2080 SourceLocation Loc,
2082 bool MissingOK,
2083 ForRangeInfo *FRI = nullptr,
2084 bool EnterForConditionScope = false);
2085 DeclGroupPtrTy ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
2086 ParsedAttributes &Attrs);
2087
2088 //===--------------------------------------------------------------------===//
2089 // C++ Coroutines
2090
2091 ExprResult ParseCoyieldExpression();
2092
2093 //===--------------------------------------------------------------------===//
2094 // C++ Concepts
2095
2096 ExprResult ParseRequiresExpression();
2097 void ParseTrailingRequiresClause(Declarator &D);
2098
2099 //===--------------------------------------------------------------------===//
2100 // C99 6.7.8: Initialization.
2101
2102 /// ParseInitializer
2103 /// initializer: [C99 6.7.8]
2104 /// assignment-expression
2105 /// '{' ...
2106 ExprResult ParseInitializer() {
2107 if (Tok.isNot(tok::l_brace))
2109 return ParseBraceInitializer();
2110 }
2111 bool MayBeDesignationStart();
2112 ExprResult ParseBraceInitializer();
2113 struct DesignatorCompletionInfo {
2114 SmallVectorImpl<Expr *> &InitExprs;
2115 QualType PreferredBaseType;
2116 };
2117 ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
2118
2119 //===--------------------------------------------------------------------===//
2120 // clang Expressions
2121
2122 ExprResult ParseBlockLiteralExpression(); // ^{...}
2123
2124 //===--------------------------------------------------------------------===//
2125 // Objective-C Expressions
2126 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
2127 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
2128 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
2129 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
2130 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
2131 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
2132 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
2133 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
2134 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
2135 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
2136 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
2137 bool isSimpleObjCMessageExpression();
2138 ExprResult ParseObjCMessageExpression();
2139 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
2140 SourceLocation SuperLoc,
2141 ParsedType ReceiverType,
2142 Expr *ReceiverExpr);
2143 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
2144 SourceLocation LBracloc, SourceLocation SuperLoc,
2145 ParsedType ReceiverType, Expr *ReceiverExpr);
2146 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
2147
2148 //===--------------------------------------------------------------------===//
2149 // C99 6.8: Statements and Blocks.
2150
2151 /// A SmallVector of expressions.
2152 typedef SmallVector<Expr*, 12> ExprVector;
2153
2155 ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
2156 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
2157 StmtResult ParseStatementOrDeclaration(
2158 StmtVector &Stmts, ParsedStmtContext StmtCtx,
2159 SourceLocation *TrailingElseLoc = nullptr);
2160 StmtResult ParseStatementOrDeclarationAfterAttributes(
2161 StmtVector &Stmts, ParsedStmtContext StmtCtx,
2162 SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs,
2163 ParsedAttributes &DeclSpecAttrs);
2164 StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
2165 StmtResult ParseLabeledStatement(ParsedAttributes &Attrs,
2166 ParsedStmtContext StmtCtx);
2167 StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
2168 bool MissingCase = false,
2169 ExprResult Expr = ExprResult());
2170 StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
2171 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
2172 StmtResult ParseCompoundStatement(bool isStmtExpr,
2173 unsigned ScopeFlags);
2174 void ParseCompoundStatementLeadingPragmas();
2175 void DiagnoseLabelAtEndOfCompoundStatement();
2176 bool ConsumeNullStmt(StmtVector &Stmts);
2177 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
2178 bool ParseParenExprOrCondition(StmtResult *InitStmt,
2179 Sema::ConditionResult &CondResult,
2180 SourceLocation Loc, Sema::ConditionKind CK,
2181 SourceLocation &LParenLoc,
2182 SourceLocation &RParenLoc);
2183 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
2184 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
2185 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
2186 StmtResult ParseDoStatement();
2187 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
2188 StmtResult ParseGotoStatement();
2189 StmtResult ParseContinueStatement();
2190 StmtResult ParseBreakStatement();
2191 StmtResult ParseReturnStatement();
2192 StmtResult ParseAsmStatement(bool &msAsm);
2193 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
2194 StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx,
2195 SourceLocation *TrailingElseLoc,
2196 ParsedAttributes &Attrs);
2197
2198 /// Describes the behavior that should be taken for an __if_exists
2199 /// block.
2200 enum IfExistsBehavior {
2201 /// Parse the block; this code is always used.
2202 IEB_Parse,
2203 /// Skip the block entirely; this code is never used.
2204 IEB_Skip,
2205 /// Parse the block as a dependent block, which may be used in
2206 /// some template instantiations but not others.
2207 IEB_Dependent
2208 };
2209
2210 /// Describes the condition of a Microsoft __if_exists or
2211 /// __if_not_exists block.
2212 struct IfExistsCondition {
2213 /// The location of the initial keyword.
2214 SourceLocation KeywordLoc;
2215 /// Whether this is an __if_exists block (rather than an
2216 /// __if_not_exists block).
2217 bool IsIfExists;
2218
2219 /// Nested-name-specifier preceding the name.
2220 CXXScopeSpec SS;
2221
2222 /// The name we're looking for.
2223 UnqualifiedId Name;
2224
2225 /// The behavior of this __if_exists or __if_not_exists block
2226 /// should.
2227 IfExistsBehavior Behavior;
2228 };
2229
2230 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
2231 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
2232 void ParseMicrosoftIfExistsExternalDeclaration();
2233 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
2234 ParsedAttributes &AccessAttrs,
2235 AccessSpecifier &CurAS);
2236 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
2237 bool &InitExprsOk);
2238 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2239 SmallVectorImpl<Expr *> &Constraints,
2240 SmallVectorImpl<Expr *> &Exprs);
2241
2242 //===--------------------------------------------------------------------===//
2243 // C++ 6: Statements and Blocks
2244
2245 StmtResult ParseCXXTryBlock();
2246 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
2247 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
2248
2249 //===--------------------------------------------------------------------===//
2250 // MS: SEH Statements and Blocks
2251
2252 StmtResult ParseSEHTryBlock();
2253 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
2254 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
2255 StmtResult ParseSEHLeaveStatement();
2256
2257 //===--------------------------------------------------------------------===//
2258 // Objective-C Statements
2259
2260 StmtResult ParseObjCAtStatement(SourceLocation atLoc,
2261 ParsedStmtContext StmtCtx);
2262 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
2263 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
2264 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
2265 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
2266
2267
2268 //===--------------------------------------------------------------------===//
2269 // C99 6.7: Declarations.
2270
2271 /// A context for parsing declaration specifiers. TODO: flesh this
2272 /// out, there are other significant restrictions on specifiers than
2273 /// would be best implemented in the parser.
2274 enum class DeclSpecContext {
2275 DSC_normal, // normal context
2276 DSC_class, // class context, enables 'friend'
2277 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
2278 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
2279 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
2280 DSC_conv_operator, // C++ type-specifier-seq in an conversion operator
2281 DSC_top_level, // top-level/namespace declaration context
2282 DSC_template_param, // template parameter context
2283 DSC_template_arg, // template argument context
2284 DSC_template_type_arg, // template type argument context
2285 DSC_objc_method_result, // ObjC method result context, enables
2286 // 'instancetype'
2287 DSC_condition, // condition declaration context
2288 DSC_association, // A _Generic selection expression's type association
2289 DSC_new, // C++ new expression
2290 };
2291
2292 /// Is this a context in which we are parsing just a type-specifier (or
2293 /// trailing-type-specifier)?
2294 static bool isTypeSpecifier(DeclSpecContext DSC) {
2295 switch (DSC) {
2296 case DeclSpecContext::DSC_normal:
2297 case DeclSpecContext::DSC_template_param:
2298 case DeclSpecContext::DSC_template_arg:
2299 case DeclSpecContext::DSC_class:
2300 case DeclSpecContext::DSC_top_level:
2301 case DeclSpecContext::DSC_objc_method_result:
2302 case DeclSpecContext::DSC_condition:
2303 return false;
2304
2305 case DeclSpecContext::DSC_template_type_arg:
2306 case DeclSpecContext::DSC_type_specifier:
2307 case DeclSpecContext::DSC_conv_operator:
2308 case DeclSpecContext::DSC_trailing:
2309 case DeclSpecContext::DSC_alias_declaration:
2310 case DeclSpecContext::DSC_association:
2311 case DeclSpecContext::DSC_new:
2312 return true;
2313 }
2314 llvm_unreachable("Missing DeclSpecContext case");
2315 }
2316
2317 /// Whether a defining-type-specifier is permitted in a given context.
2318 enum class AllowDefiningTypeSpec {
2319 /// The grammar doesn't allow a defining-type-specifier here, and we must
2320 /// not parse one (eg, because a '{' could mean something else).
2321 No,
2322 /// The grammar doesn't allow a defining-type-specifier here, but we permit
2323 /// one for error recovery purposes. Sema will reject.
2324 NoButErrorRecovery,
2325 /// The grammar allows a defining-type-specifier here, even though it's
2326 /// always invalid. Sema will reject.
2327 YesButInvalid,
2328 /// The grammar allows a defining-type-specifier here, and one can be valid.
2329 Yes
2330 };
2331
2332 /// Is this a context in which we are parsing defining-type-specifiers (and
2333 /// so permit class and enum definitions in addition to non-defining class and
2334 /// enum elaborated-type-specifiers)?
2335 static AllowDefiningTypeSpec
2336 isDefiningTypeSpecifierContext(DeclSpecContext DSC, bool IsCPlusPlus) {
2337 switch (DSC) {
2338 case DeclSpecContext::DSC_normal:
2339 case DeclSpecContext::DSC_class:
2340 case DeclSpecContext::DSC_top_level:
2341 case DeclSpecContext::DSC_alias_declaration:
2342 case DeclSpecContext::DSC_objc_method_result:
2343 return AllowDefiningTypeSpec::Yes;
2344
2345 case DeclSpecContext::DSC_condition:
2346 case DeclSpecContext::DSC_template_param:
2347 return AllowDefiningTypeSpec::YesButInvalid;
2348
2349 case DeclSpecContext::DSC_template_type_arg:
2350 case DeclSpecContext::DSC_type_specifier:
2351 return AllowDefiningTypeSpec::NoButErrorRecovery;
2352
2353 case DeclSpecContext::DSC_association:
2354 return IsCPlusPlus ? AllowDefiningTypeSpec::NoButErrorRecovery
2355 : AllowDefiningTypeSpec::Yes;
2356
2357 case DeclSpecContext::DSC_trailing:
2358 case DeclSpecContext::DSC_conv_operator:
2359 case DeclSpecContext::DSC_template_arg:
2360 case DeclSpecContext::DSC_new:
2361 return AllowDefiningTypeSpec::No;
2362 }
2363 llvm_unreachable("Missing DeclSpecContext case");
2364 }
2365
2366 /// Is this a context in which an opaque-enum-declaration can appear?
2367 static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
2368 switch (DSC) {
2369 case DeclSpecContext::DSC_normal:
2370 case DeclSpecContext::DSC_class:
2371 case DeclSpecContext::DSC_top_level:
2372 return true;
2373
2374 case DeclSpecContext::DSC_alias_declaration:
2375 case DeclSpecContext::DSC_objc_method_result:
2376 case DeclSpecContext::DSC_condition:
2377 case DeclSpecContext::DSC_template_param:
2378 case DeclSpecContext::DSC_template_type_arg:
2379 case DeclSpecContext::DSC_type_specifier:
2380 case DeclSpecContext::DSC_trailing:
2381 case DeclSpecContext::DSC_association:
2382 case DeclSpecContext::DSC_conv_operator:
2383 case DeclSpecContext::DSC_template_arg:
2384 case DeclSpecContext::DSC_new:
2385
2386 return false;
2387 }
2388 llvm_unreachable("Missing DeclSpecContext case");
2389 }
2390
2391 /// Is this a context in which we can perform class template argument
2392 /// deduction?
2393 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2394 switch (DSC) {
2395 case DeclSpecContext::DSC_normal:
2396 case DeclSpecContext::DSC_template_param:
2397 case DeclSpecContext::DSC_template_arg:
2398 case DeclSpecContext::DSC_class:
2399 case DeclSpecContext::DSC_top_level:
2400 case DeclSpecContext::DSC_condition:
2401 case DeclSpecContext::DSC_type_specifier:
2402 case DeclSpecContext::DSC_association:
2403 case DeclSpecContext::DSC_conv_operator:
2404 case DeclSpecContext::DSC_new:
2405 return true;
2406
2407 case DeclSpecContext::DSC_objc_method_result:
2408 case DeclSpecContext::DSC_template_type_arg:
2409 case DeclSpecContext::DSC_trailing:
2410 case DeclSpecContext::DSC_alias_declaration:
2411 return false;
2412 }
2413 llvm_unreachable("Missing DeclSpecContext case");
2414 }
2415
2416 // Is this a context in which an implicit 'typename' is allowed?
2418 getImplicitTypenameContext(DeclSpecContext DSC) {
2419 switch (DSC) {
2420 case DeclSpecContext::DSC_class:
2421 case DeclSpecContext::DSC_top_level:
2422 case DeclSpecContext::DSC_type_specifier:
2423 case DeclSpecContext::DSC_template_type_arg:
2424 case DeclSpecContext::DSC_trailing:
2425 case DeclSpecContext::DSC_alias_declaration:
2426 case DeclSpecContext::DSC_template_param:
2427 case DeclSpecContext::DSC_new:
2429
2430 case DeclSpecContext::DSC_normal:
2431 case DeclSpecContext::DSC_objc_method_result:
2432 case DeclSpecContext::DSC_condition:
2433 case DeclSpecContext::DSC_template_arg:
2434 case DeclSpecContext::DSC_conv_operator:
2435 case DeclSpecContext::DSC_association:
2437 }
2438 llvm_unreachable("Missing DeclSpecContext case");
2439 }
2440
2441 /// Information on a C++0x for-range-initializer found while parsing a
2442 /// declaration which turns out to be a for-range-declaration.
2443 struct ForRangeInit {
2444 SourceLocation ColonLoc;
2445 ExprResult RangeExpr;
2446 SmallVector<MaterializeTemporaryExpr *, 8> LifetimeExtendTemps;
2447 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2448 };
2449 struct ForRangeInfo : ForRangeInit {
2450 StmtResult LoopVar;
2451 };
2452
2453 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2454 SourceLocation &DeclEnd,
2455 ParsedAttributes &DeclAttrs,
2456 ParsedAttributes &DeclSpecAttrs,
2457 SourceLocation *DeclSpecStart = nullptr);
2459 ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
2460 ParsedAttributes &DeclAttrs,
2461 ParsedAttributes &DeclSpecAttrs, bool RequireSemi,
2462 ForRangeInit *FRI = nullptr,
2463 SourceLocation *DeclSpecStart = nullptr);
2464 bool MightBeDeclarator(DeclaratorContext Context);
2465 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2466 ParsedAttributes &Attrs,
2467 ParsedTemplateInfo &TemplateInfo,
2468 SourceLocation *DeclEnd = nullptr,
2469 ForRangeInit *FRI = nullptr);
2470 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2471 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2472 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2473 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2474 Declarator &D,
2475 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2476 ForRangeInit *FRI = nullptr);
2477 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2478 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2479
2480 /// When in code-completion, skip parsing of the function/method body
2481 /// unless the body contains the code-completion point.
2482 ///
2483 /// \returns true if the function body was skipped.
2484 bool trySkippingFunctionBody();
2485
2486 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2487 ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
2488 DeclSpecContext DSC, ParsedAttributes &Attrs);
2489 DeclSpecContext
2490 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2491 void
2492 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
2494 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2495 LateParsedAttrList *LateAttrs = nullptr) {
2496 return ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs,
2497 getImplicitTypenameContext(DSC));
2498 }
2499 void
2500 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
2501 AccessSpecifier AS, DeclSpecContext DSC,
2502 LateParsedAttrList *LateAttrs,
2503 ImplicitTypenameContext AllowImplicitTypename);
2504
2505 SourceLocation ParsePackIndexingType(DeclSpec &DS);
2506 void AnnotateExistingIndexedTypeNamePack(ParsedType T,
2507 SourceLocation StartLoc,
2508 SourceLocation EndLoc);
2509
2510 bool DiagnoseMissingSemiAfterTagDefinition(
2511 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2512 LateParsedAttrList *LateAttrs = nullptr);
2513
2514 void ParseSpecifierQualifierList(
2515 DeclSpec &DS, AccessSpecifier AS = AS_none,
2516 DeclSpecContext DSC = DeclSpecContext::DSC_normal) {
2517 ParseSpecifierQualifierList(DS, getImplicitTypenameContext(DSC), AS, DSC);
2518 }
2519
2520 void ParseSpecifierQualifierList(
2521 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2523 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2524
2525 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2526 DeclaratorContext Context);
2527
2528 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2529 const ParsedTemplateInfo &TemplateInfo,
2530 AccessSpecifier AS, DeclSpecContext DSC);
2531 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2532 void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
2533 RecordDecl *TagDecl);
2534
2535 void ParseStructDeclaration(
2536 ParsingDeclSpec &DS,
2537 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2538
2539 DeclGroupPtrTy ParseTopLevelStmtDecl();
2540
2541 bool isDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2542 bool DisambiguatingWithExpression = false);
2543 bool isTypeSpecifierQualifier();
2544
2545 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2546 /// is definitely a type-specifier. Return false if it isn't part of a type
2547 /// specifier or if we're not sure.
2548 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2549
2550 /// Return true if we know that we are definitely looking at a
2551 /// decl-specifier, and isn't part of an expression such as a function-style
2552 /// cast. Return false if it's no a decl-specifier, or we're not sure.
2553 bool isKnownToBeDeclarationSpecifier() {
2554 if (getLangOpts().CPlusPlus)
2555 return isCXXDeclarationSpecifier(ImplicitTypenameContext::No) ==
2556 TPResult::True;
2557 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2558 }
2559
2560 /// isDeclarationStatement - Disambiguates between a declaration or an
2561 /// expression statement, when parsing function bodies.
2562 ///
2563 /// \param DisambiguatingWithExpression - True to indicate that the purpose of
2564 /// this check is to disambiguate between an expression and a declaration.
2565 /// Returns true for declaration, false for expression.
2566 bool isDeclarationStatement(bool DisambiguatingWithExpression = false) {
2567 if (getLangOpts().CPlusPlus)
2568 return isCXXDeclarationStatement(DisambiguatingWithExpression);
2569 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2570 }
2571
2572 /// isForInitDeclaration - Disambiguates between a declaration or an
2573 /// expression in the context of the C 'clause-1' or the C++
2574 // 'for-init-statement' part of a 'for' statement.
2575 /// Returns true for declaration, false for expression.
2576 bool isForInitDeclaration() {
2577 if (getLangOpts().OpenMP)
2578 Actions.OpenMP().startOpenMPLoop();
2579 if (getLangOpts().CPlusPlus)
2580 return Tok.is(tok::kw_using) ||
2581 isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2582 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2583 }
2584
2585 /// Determine whether this is a C++1z for-range-identifier.
2586 bool isForRangeIdentifier();
2587
2588 /// Determine whether we are currently at the start of an Objective-C
2589 /// class message that appears to be missing the open bracket '['.
2590 bool isStartOfObjCClassMessageMissingOpenBracket();
2591
2592 /// Starting with a scope specifier, identifier, or
2593 /// template-id that refers to the current class, determine whether
2594 /// this is a constructor declarator.
2595 bool isConstructorDeclarator(
2596 bool Unqualified, bool DeductionGuide = false,
2598 const ParsedTemplateInfo *TemplateInfo = nullptr);
2599
2600 /// Specifies the context in which type-id/expression
2601 /// disambiguation will occur.
2602 enum TentativeCXXTypeIdContext {
2603 TypeIdInParens,
2604 TypeIdUnambiguous,
2605 TypeIdAsTemplateArgument,
2606 TypeIdInTrailingReturnType,
2607 TypeIdAsGenericSelectionArgument,
2608 };
2609
2610 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2611 /// whether the parens contain an expression or a type-id.
2612 /// Returns true for a type-id and false for an expression.
2613 bool isTypeIdInParens(bool &isAmbiguous) {
2614 if (getLangOpts().CPlusPlus)
2615 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2616 isAmbiguous = false;
2617 return isTypeSpecifierQualifier();
2618 }
2619 bool isTypeIdInParens() {
2620 bool isAmbiguous;
2621 return isTypeIdInParens(isAmbiguous);
2622 }
2623
2624 /// Checks whether the current tokens form a type-id or an expression for the
2625 /// purposes of use as the initial operand to a generic selection expression.
2626 /// This requires special handling in C++ because it accepts either a type or
2627 /// an expression, and we need to disambiguate which is which. However, we
2628 /// cannot use the same logic as we've used for sizeof expressions, because
2629 /// that logic relies on the operator only accepting a single argument,
2630 /// whereas _Generic accepts a list of arguments.
2631 bool isTypeIdForGenericSelection() {
2632 if (getLangOpts().CPlusPlus) {
2633 bool isAmbiguous;
2634 return isCXXTypeId(TypeIdAsGenericSelectionArgument, isAmbiguous);
2635 }
2636 return isTypeSpecifierQualifier();
2637 }
2638
2639 /// Checks if the current tokens form type-id or expression.
2640 /// It is similar to isTypeIdInParens but does not suppose that type-id
2641 /// is in parenthesis.
2642 bool isTypeIdUnambiguously() {
2643 if (getLangOpts().CPlusPlus) {
2644 bool isAmbiguous;
2645 return isCXXTypeId(TypeIdUnambiguous, isAmbiguous);
2646 }
2647 return isTypeSpecifierQualifier();
2648 }
2649
2650 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2651 /// between a declaration or an expression statement, when parsing function
2652 /// bodies. Returns true for declaration, false for expression.
2653 bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false);
2654
2655 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2656 /// between a simple-declaration or an expression-statement.
2657 /// If during the disambiguation process a parsing error is encountered,
2658 /// the function returns true to let the declaration parsing code handle it.
2659 /// Returns false if the statement is disambiguated as expression.
2660 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2661
2662 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2663 /// a constructor-style initializer, when parsing declaration statements.
2664 /// Returns true for function declarator and false for constructor-style
2665 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2666 /// might be a constructor-style initializer.
2667 /// If during the disambiguation process a parsing error is encountered,
2668 /// the function returns true to let the declaration parsing code handle it.
2669 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr,
2670 ImplicitTypenameContext AllowImplicitTypename =
2672
2673 struct ConditionDeclarationOrInitStatementState;
2674 enum class ConditionOrInitStatement {
2675 Expression, ///< Disambiguated as an expression (either kind).
2676 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2677 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2678 ForRangeDecl, ///< Disambiguated as a for-range declaration.
2679 Error ///< Can't be any of the above!
2680 };
2681 /// Disambiguates between the different kinds of things that can happen
2682 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2683 /// declaration (depending on whether there is a ';' later) or an expression.
2684 ConditionOrInitStatement
2685 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
2686 bool CanBeForRangeDecl);
2687
2688 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2689 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2690 bool isAmbiguous;
2691 return isCXXTypeId(Context, isAmbiguous);
2692 }
2693
2694 /// TPResult - Used as the result value for functions whose purpose is to
2695 /// disambiguate C++ constructs by "tentatively parsing" them.
2696 enum class TPResult {
2697 True, False, Ambiguous, Error
2698 };
2699
2700 /// Determine whether we could have an enum-base.
2701 ///
2702 /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
2703 /// only consider this to be an enum-base if the next token is a '{'.
2704 ///
2705 /// \return \c false if this cannot possibly be an enum base; \c true
2706 /// otherwise.
2707 bool isEnumBase(bool AllowSemi);
2708
2709 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2710 /// declaration specifier, TPResult::False if it is not,
2711 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2712 /// function-style cast, and TPResult::Error if a parsing error was
2713 /// encountered. If it could be a braced C++11 function-style cast, returns
2714 /// BracedCastResult.
2715 /// Doesn't consume tokens.
2716 TPResult
2717 isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2718 TPResult BracedCastResult = TPResult::False,
2719 bool *InvalidAsDeclSpec = nullptr);
2720
2721 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2722 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2723 /// a type-specifier other than a cv-qualifier.
2724 bool isCXXDeclarationSpecifierAType();
2725
2726 /// Determine whether the current token sequence might be
2727 /// '<' template-argument-list '>'
2728 /// rather than a less-than expression.
2729 TPResult isTemplateArgumentList(unsigned TokensToSkip);
2730
2731 /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
2732 /// 'explicit(bool)' declaration, in earlier language modes where that is an
2733 /// extension.
2734 TPResult isExplicitBool();
2735
2736 /// Determine whether an identifier has been tentatively declared as a
2737 /// non-type. Such tentative declarations should not be found to name a type
2738 /// during a tentative parse, but also should not be annotated as a non-type.
2739 bool isTentativelyDeclared(IdentifierInfo *II);
2740
2741 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2742 // is encountered they will return TPResult::Error.
2743 // Returning TPResult::True/False indicates that the ambiguity was
2744 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2745 // that more tentative parsing is necessary for disambiguation.
2746 // They all consume tokens, so backtracking should be used after calling them.
2747
2748 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2749 TPResult TryParseTypeofSpecifier();
2750 TPResult TryParseProtocolQualifiers();
2751 TPResult TryParsePtrOperatorSeq();
2752 TPResult TryParseOperatorId();
2753 TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false);
2754 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2755 bool mayHaveDirectInit = false,
2756 bool mayHaveTrailingReturnType = false);
2757 TPResult TryParseParameterDeclarationClause(
2758 bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false,
2759 ImplicitTypenameContext AllowImplicitTypename =
2761 TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false);
2762 bool NameAfterArrowIsNonType();
2763 TPResult TryParseBracketDeclarator();
2764 TPResult TryConsumeDeclarationSpecifier();
2765
2766 /// Try to skip a possibly empty sequence of 'attribute-specifier's without
2767 /// full validation of the syntactic structure of attributes.
2768 bool TrySkipAttributes();
2769
2770 /// Diagnoses use of _ExtInt as being deprecated, and diagnoses use of
2771 /// _BitInt as an extension when appropriate.
2772 void DiagnoseBitIntUse(const Token &Tok);
2773
2774public:
2776 ParseTypeName(SourceRange *Range = nullptr,
2778 AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
2779 ParsedAttributes *Attrs = nullptr);
2780
2781private:
2782 void ParseBlockId(SourceLocation CaretLoc);
2783
2784 /// Return true if the next token should be treated as a [[]] attribute,
2785 /// or as a keyword that behaves like one. The former is only true if
2786 /// [[]] attributes are enabled, whereas the latter is true whenever
2787 /// such a keyword appears. The arguments are as for
2788 /// isCXX11AttributeSpecifier.
2789 bool isAllowedCXX11AttributeSpecifier(bool Disambiguate = false,
2790 bool OuterMightBeMessageSend = false) {
2791 return (Tok.isRegularKeywordAttribute() ||
2792 isCXX11AttributeSpecifier(Disambiguate, OuterMightBeMessageSend));
2793 }
2794
2795 // Check for the start of an attribute-specifier-seq in a context where an
2796 // attribute is not allowed.
2797 bool CheckProhibitedCXX11Attribute() {
2798 assert(Tok.is(tok::l_square));
2799 if (NextToken().isNot(tok::l_square))
2800 return false;
2801 return DiagnoseProhibitedCXX11Attribute();
2802 }
2803
2804 bool DiagnoseProhibitedCXX11Attribute();
2805 void CheckMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2806 SourceLocation CorrectLocation) {
2807 if (!Tok.isRegularKeywordAttribute() &&
2808 (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2809 Tok.isNot(tok::kw_alignas))
2810 return;
2811 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2812 }
2813 void DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2814 SourceLocation CorrectLocation);
2815
2816 void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS,
2817 Sema::TagUseKind TUK);
2818
2819 // FixItLoc = possible correct location for the attributes
2820 void ProhibitAttributes(ParsedAttributes &Attrs,
2821 SourceLocation FixItLoc = SourceLocation()) {
2822 if (Attrs.Range.isInvalid())
2823 return;
2824 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2825 Attrs.clear();
2826 }
2827
2828 void ProhibitAttributes(ParsedAttributesView &Attrs,
2829 SourceLocation FixItLoc = SourceLocation()) {
2830 if (Attrs.Range.isInvalid())
2831 return;
2832 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2833 Attrs.clearListOnly();
2834 }
2835 void DiagnoseProhibitedAttributes(const ParsedAttributesView &Attrs,
2836 SourceLocation FixItLoc);
2837
2838 // Forbid C++11 and C23 attributes that appear on certain syntactic locations
2839 // which standard permits but we don't supported yet, for example, attributes
2840 // appertain to decl specifiers.
2841 // For the most cases we don't want to warn on unknown type attributes, but
2842 // left them to later diagnoses. However, for a few cases like module
2843 // declarations and module import declarations, we should do it.
2844 void ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned AttrDiagID,
2845 unsigned KeywordDiagId,
2846 bool DiagnoseEmptyAttrs = false,
2847 bool WarnOnUnknownAttrs = false);
2848
2849 /// Skip C++11 and C23 attributes and return the end location of the
2850 /// last one.
2851 /// \returns SourceLocation() if there are no attributes.
2852 SourceLocation SkipCXX11Attributes();
2853
2854 /// Diagnose and skip C++11 and C23 attributes that appear in syntactic
2855 /// locations where attributes are not allowed.
2856 void DiagnoseAndSkipCXX11Attributes();
2857
2858 /// Emit warnings for C++11 and C23 attributes that are in a position that
2859 /// clang accepts as an extension.
2860 void DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs);
2861
2862 ExprResult ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName);
2863
2864 bool
2865 ParseAttributeArgumentList(const clang::IdentifierInfo &AttrName,
2866 SmallVectorImpl<Expr *> &Exprs,
2867 ParsedAttributeArgumentsProperties ArgsProperties);
2868
2869 /// Parses syntax-generic attribute arguments for attributes which are
2870 /// known to the implementation, and adds them to the given ParsedAttributes
2871 /// list with the given attribute syntax. Returns the number of arguments
2872 /// parsed for the attribute.
2873 unsigned
2874 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2875 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2876 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2877 ParsedAttr::Form Form);
2878
2879 enum ParseAttrKindMask {
2880 PAKM_GNU = 1 << 0,
2881 PAKM_Declspec = 1 << 1,
2882 PAKM_CXX11 = 1 << 2,
2883 };
2884
2885 /// \brief Parse attributes based on what syntaxes are desired, allowing for
2886 /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2887 /// __attribute__((...)) __declspec(...) __attribute__((...)))
2888 /// Note that Microsoft attributes (spelled with single square brackets) are
2889 /// not supported by this because of parsing ambiguities with other
2890 /// constructs.
2891 ///
2892 /// There are some attribute parse orderings that should not be allowed in
2893 /// arbitrary order. e.g.,
2894 ///
2895 /// [[]] __attribute__(()) int i; // OK
2896 /// __attribute__(()) [[]] int i; // Not OK
2897 ///
2898 /// Such situations should use the specific attribute parsing functionality.
2899 void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2900 LateParsedAttrList *LateAttrs = nullptr);
2901 /// \brief Possibly parse attributes based on what syntaxes are desired,
2902 /// allowing for the order to vary.
2903 bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2904 LateParsedAttrList *LateAttrs = nullptr) {
2905 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2906 isAllowedCXX11AttributeSpecifier()) {
2907 ParseAttributes(WhichAttrKinds, Attrs, LateAttrs);
2908 return true;
2909 }
2910 return false;
2911 }
2912
2913 void MaybeParseGNUAttributes(Declarator &D,
2914 LateParsedAttrList *LateAttrs = nullptr) {
2915 if (Tok.is(tok::kw___attribute)) {
2916 ParsedAttributes Attrs(AttrFactory);
2917 ParseGNUAttributes(Attrs, LateAttrs, &D);
2918 D.takeAttributes(Attrs);
2919 }
2920 }
2921
2922 bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2923 LateParsedAttrList *LateAttrs = nullptr) {
2924 if (Tok.is(tok::kw___attribute)) {
2925 ParseGNUAttributes(Attrs, LateAttrs);
2926 return true;
2927 }
2928 return false;
2929 }
2930
2931 void ParseGNUAttributes(ParsedAttributes &Attrs,
2932 LateParsedAttrList *LateAttrs = nullptr,
2933 Declarator *D = nullptr);
2934 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2935 SourceLocation AttrNameLoc,
2936 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2937 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2938 ParsedAttr::Form Form, Declarator *D);
2939 IdentifierLoc *ParseIdentifierLoc();
2940
2941 unsigned
2942 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2943 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2944 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2945 ParsedAttr::Form Form);
2946
2947 void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) {
2948 // If parsing the attributes found an OpenMP directive, emit those tokens
2949 // to the parse stream now.
2950 if (!OpenMPTokens.empty()) {
2951 PP.EnterToken(Tok, /*IsReinject*/ true);
2952 PP.EnterTokenStream(OpenMPTokens, /*DisableMacroExpansion*/ true,
2953 /*IsReinject*/ true);
2954 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ true);
2955 }
2956 }
2957 void MaybeParseCXX11Attributes(Declarator &D) {
2958 if (isAllowedCXX11AttributeSpecifier()) {
2959 ParsedAttributes Attrs(AttrFactory);
2960 ParseCXX11Attributes(Attrs);
2961 D.takeAttributes(Attrs);
2962 }
2963 }
2964
2965 bool MaybeParseCXX11Attributes(ParsedAttributes &Attrs,
2966 bool OuterMightBeMessageSend = false) {
2967 if (isAllowedCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) {
2968 ParseCXX11Attributes(Attrs);
2969 return true;
2970 }
2971 return false;
2972 }
2973
2974 void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
2975 CachedTokens &OpenMPTokens);
2976
2977 void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
2978 CachedTokens &OpenMPTokens,
2979 SourceLocation *EndLoc = nullptr);
2980 void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs,
2981 SourceLocation *EndLoc = nullptr) {
2982 CachedTokens OpenMPTokens;
2983 ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc);
2984 ReplayOpenMPAttributeTokens(OpenMPTokens);
2985 }
2986 void ParseCXX11Attributes(ParsedAttributes &attrs);
2987 /// Parses a C++11 (or C23)-style attribute argument list. Returns true
2988 /// if this results in adding an attribute to the ParsedAttributes list.
2989 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2990 SourceLocation AttrNameLoc,
2991 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2992 IdentifierInfo *ScopeName,
2993 SourceLocation ScopeLoc,
2994 CachedTokens &OpenMPTokens);
2995
2996 /// Parse a C++23 assume() attribute. Returns true on error.
2997 bool ParseCXXAssumeAttributeArg(ParsedAttributes &Attrs,
2998 IdentifierInfo *AttrName,
2999 SourceLocation AttrNameLoc,
3000 SourceLocation *EndLoc);
3001
3002 IdentifierInfo *TryParseCXX11AttributeIdentifier(
3003 SourceLocation &Loc,
3006 const IdentifierInfo *EnclosingScope = nullptr);
3007
3008 void MaybeParseHLSLAnnotations(Declarator &D,
3009 SourceLocation *EndLoc = nullptr) {
3010 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
3011 if (Tok.is(tok::colon)) {
3012 ParsedAttributes Attrs(AttrFactory);
3013 ParseHLSLAnnotations(Attrs, EndLoc);
3014 D.takeAttributes(Attrs);
3015 }
3016 }
3017
3018 void MaybeParseHLSLAnnotations(ParsedAttributes &Attrs,
3019 SourceLocation *EndLoc = nullptr) {
3020 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
3021 if (getLangOpts().HLSL && Tok.is(tok::colon))
3022 ParseHLSLAnnotations(Attrs, EndLoc);
3023 }
3024
3025 void ParseHLSLAnnotations(ParsedAttributes &Attrs,
3026 SourceLocation *EndLoc = nullptr);
3027 Decl *ParseHLSLBuffer(SourceLocation &DeclEnd);
3028
3029 void MaybeParseMicrosoftAttributes(ParsedAttributes &Attrs) {
3030 if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) &&
3031 Tok.is(tok::l_square)) {
3032 ParsedAttributes AttrsWithRange(AttrFactory);
3033 ParseMicrosoftAttributes(AttrsWithRange);
3034 Attrs.takeAllFrom(AttrsWithRange);
3035 }
3036 }
3037 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
3038 void ParseMicrosoftAttributes(ParsedAttributes &Attrs);
3039 bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
3040 if (getLangOpts().DeclSpecKeyword && Tok.is(tok::kw___declspec)) {
3041 ParseMicrosoftDeclSpecs(Attrs);
3042 return true;
3043 }
3044 return false;
3045 }
3046 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs);
3047 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
3048 SourceLocation AttrNameLoc,
3049 ParsedAttributes &Attrs);
3050 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
3051 void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &Attrs);
3052 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
3053 SourceLocation SkipExtendedMicrosoftTypeAttributes();
3054 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
3055 void ParseNullabilityClassAttributes(ParsedAttributes &attrs);
3056 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
3057 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
3058 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
3059 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
3060 void ParseCUDAFunctionAttributes(ParsedAttributes &attrs);
3061 bool isHLSLQualifier(const Token &Tok) const;
3062 void ParseHLSLQualifiers(ParsedAttributes &Attrs);
3063
3064 VersionTuple ParseVersionTuple(SourceRange &Range);
3065 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
3066 SourceLocation AvailabilityLoc,
3067 ParsedAttributes &attrs,
3068 SourceLocation *endLoc,
3069 IdentifierInfo *ScopeName,
3070 SourceLocation ScopeLoc,
3071 ParsedAttr::Form Form);
3072
3073 std::optional<AvailabilitySpec> ParseAvailabilitySpec();
3074 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
3075
3076 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
3077 SourceLocation Loc,
3078 ParsedAttributes &Attrs,
3079 SourceLocation *EndLoc,
3080 IdentifierInfo *ScopeName,
3081 SourceLocation ScopeLoc,
3082 ParsedAttr::Form Form);
3083
3084 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
3085 SourceLocation ObjCBridgeRelatedLoc,
3086 ParsedAttributes &Attrs,
3087 SourceLocation *EndLoc,
3088 IdentifierInfo *ScopeName,
3089 SourceLocation ScopeLoc,
3090 ParsedAttr::Form Form);
3091
3092 void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
3093 SourceLocation AttrNameLoc,
3094 ParsedAttributes &Attrs,
3095 SourceLocation *EndLoc,
3096 IdentifierInfo *ScopeName,
3097 SourceLocation ScopeLoc,
3098 ParsedAttr::Form Form);
3099
3100 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
3101 SourceLocation AttrNameLoc,
3102 ParsedAttributes &Attrs,
3103 SourceLocation *EndLoc,
3104 IdentifierInfo *ScopeName,
3105 SourceLocation ScopeLoc,
3106 ParsedAttr::Form Form);
3107
3108 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
3109 SourceLocation AttrNameLoc,
3110 ParsedAttributes &Attrs,
3111 IdentifierInfo *ScopeName,
3112 SourceLocation ScopeLoc,
3113 ParsedAttr::Form Form);
3114
3115 void ParseBoundsAttribute(IdentifierInfo &AttrName,
3116 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
3117 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
3118 ParsedAttr::Form Form);
3119
3120 void ParseTypeofSpecifier(DeclSpec &DS);
3121 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
3122 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
3123 SourceLocation StartLoc,
3124 SourceLocation EndLoc);
3125 void ParseAtomicSpecifier(DeclSpec &DS);
3126
3127 ExprResult ParseAlignArgument(StringRef KWName, SourceLocation Start,
3128 SourceLocation &EllipsisLoc, bool &IsType,
3129 ParsedType &Ty);
3130 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3131 SourceLocation *endLoc = nullptr);
3132 ExprResult ParseExtIntegerArgument();
3133
3134 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
3135 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
3136 return isCXX11VirtSpecifier(Tok);
3137 }
3138 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
3139 SourceLocation FriendLoc);
3140
3141 bool isCXX11FinalKeyword() const;
3142 bool isClassCompatibleKeyword() const;
3143
3144 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
3145 /// enter a new C++ declarator scope and exit it when the function is
3146 /// finished.
3147 class DeclaratorScopeObj {
3148 Parser &P;
3149 CXXScopeSpec &SS;
3150 bool EnteredScope;
3151 bool CreatedScope;
3152 public:
3153 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
3154 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
3155
3156 void EnterDeclaratorScope() {
3157 assert(!EnteredScope && "Already entered the scope!");
3158 assert(SS.isSet() && "C++ scope was not set!");
3159
3160 CreatedScope = true;
3161 P.EnterScope(0); // Not a decl scope.
3162
3163 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
3164 EnteredScope = true;
3165 }
3166
3167 ~DeclaratorScopeObj() {
3168 if (EnteredScope) {
3169 assert(SS.isSet() && "C++ scope was cleared ?");
3170 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
3171 }
3172 if (CreatedScope)
3173 P.ExitScope();
3174 }
3175 };
3176
3177 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
3178 void ParseDeclarator(Declarator &D);
3179 /// A function that parses a variant of direct-declarator.
3180 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
3181 void ParseDeclaratorInternal(Declarator &D,
3182 DirectDeclParseFunction DirectDeclParser);
3183
3184 enum AttrRequirements {
3185 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
3186 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
3187 AR_GNUAttributesParsed = 1 << 1,
3188 AR_CXX11AttributesParsed = 1 << 2,
3189 AR_DeclspecAttributesParsed = 1 << 3,
3190 AR_AllAttributesParsed = AR_GNUAttributesParsed |
3191 AR_CXX11AttributesParsed |
3192 AR_DeclspecAttributesParsed,
3193 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
3194 AR_DeclspecAttributesParsed
3195 };
3196
3197 void ParseTypeQualifierListOpt(
3198 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
3199 bool AtomicAllowed = true, bool IdentifierRequired = false,
3200 std::optional<llvm::function_ref<void()>> CodeCompletionHandler =
3201 std::nullopt);
3202 void ParseDirectDeclarator(Declarator &D);
3203 void ParseDecompositionDeclarator(Declarator &D);
3204 void ParseParenDeclarator(Declarator &D);
3205 void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs,
3206 BalancedDelimiterTracker &Tracker,
3207 bool IsAmbiguous, bool RequiresArg = false);
3208 void InitCXXThisScopeForDeclaratorIfRelevant(
3209 const Declarator &D, const DeclSpec &DS,
3210 std::optional<Sema::CXXThisScopeRAII> &ThisScope);
3211 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
3212 SourceLocation &RefQualifierLoc);
3213 bool isFunctionDeclaratorIdentifierList();
3214 void ParseFunctionDeclaratorIdentifierList(
3215 Declarator &D,
3216 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
3217 void ParseParameterDeclarationClause(
3218 Declarator &D, ParsedAttributes &attrs,
3219 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
3220 SourceLocation &EllipsisLoc) {
3221 return ParseParameterDeclarationClause(
3222 D.getContext(), attrs, ParamInfo, EllipsisLoc,
3223 D.getCXXScopeSpec().isSet() &&
3224 D.isFunctionDeclaratorAFunctionDeclaration());
3225 }
3226 void ParseParameterDeclarationClause(
3227 DeclaratorContext DeclaratorContext, ParsedAttributes &attrs,
3228 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
3229 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration = false);
3230
3231 void ParseBracketDeclarator(Declarator &D);
3232 void ParseMisplacedBracketDeclarator(Declarator &D);
3233 bool MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS);
3234 DeclSpec::TST TypeTransformTokToDeclSpec();
3235
3236 //===--------------------------------------------------------------------===//
3237 // C++ 7: Declarations [dcl.dcl]
3238
3239 /// The kind of attribute specifier we have found.
3240 enum CXX11AttributeKind {
3241 /// This is not an attribute specifier.
3242 CAK_NotAttributeSpecifier,
3243 /// This should be treated as an attribute-specifier.
3244 CAK_AttributeSpecifier,
3245 /// The next tokens are '[[', but this is not an attribute-specifier. This
3246 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
3247 CAK_InvalidAttributeSpecifier
3248 };
3249 CXX11AttributeKind
3250 isCXX11AttributeSpecifier(bool Disambiguate = false,
3251 bool OuterMightBeMessageSend = false);
3252
3253 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3254
3255 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3256 SourceLocation &DeclEnd,
3257 SourceLocation InlineLoc = SourceLocation());
3258
3259 struct InnerNamespaceInfo {
3260 SourceLocation NamespaceLoc;
3261 SourceLocation InlineLoc;
3262 SourceLocation IdentLoc;
3263 IdentifierInfo *Ident;
3264 };
3265 using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3266
3267 void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3268 unsigned int index, SourceLocation &InlineLoc,
3269 ParsedAttributes &attrs,
3270 BalancedDelimiterTracker &Tracker);
3271 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3272 Decl *ParseExportDeclaration();
3273 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3274 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3275 SourceLocation &DeclEnd, ParsedAttributes &Attrs);
3276 Decl *ParseUsingDirective(DeclaratorContext Context,
3277 SourceLocation UsingLoc,
3278 SourceLocation &DeclEnd,
3279 ParsedAttributes &attrs);
3280
3281 struct UsingDeclarator {
3282 SourceLocation TypenameLoc;
3283 CXXScopeSpec SS;
3284 UnqualifiedId Name;
3285 SourceLocation EllipsisLoc;
3286
3287 void clear() {
3288 TypenameLoc = EllipsisLoc = SourceLocation();
3289 SS.clear();
3290 Name.clear();
3291 }
3292 };
3293
3294 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3295 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3296 const ParsedTemplateInfo &TemplateInfo,
3297 SourceLocation UsingLoc,
3298 SourceLocation &DeclEnd,
3299 ParsedAttributes &Attrs,
3301 Decl *ParseAliasDeclarationAfterDeclarator(
3302 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3303 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3304 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3305
3306 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3307 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3308 SourceLocation AliasLoc, IdentifierInfo *Alias,
3309 SourceLocation &DeclEnd);
3310
3311 //===--------------------------------------------------------------------===//
3312 // C++ 9: classes [class] and C structs/unions.
3313 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3314 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3315 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
3316 AccessSpecifier AS, bool EnteringContext,
3317 DeclSpecContext DSC, ParsedAttributes &Attributes);
3318 void SkipCXXMemberSpecification(SourceLocation StartLoc,
3319 SourceLocation AttrFixitLoc,
3320 unsigned TagType,
3321 Decl *TagDecl);
3322 void ParseCXXMemberSpecification(SourceLocation StartLoc,
3323 SourceLocation AttrFixitLoc,
3324 ParsedAttributes &Attrs, unsigned TagType,
3325 Decl *TagDecl);
3326 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3327 SourceLocation &EqualLoc);
3328 bool
3329 ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3330 VirtSpecifiers &VS,
3331 ExprResult &BitfieldSize,
3332 LateParsedAttrList &LateAttrs);
3333 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3334 VirtSpecifiers &VS);
3335 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3336 AccessSpecifier AS, ParsedAttributes &Attr,
3337 ParsedTemplateInfo &TemplateInfo,
3338 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3340 ParseCXXClassMemberDeclarationWithPragmas(AccessSpecifier &AS,
3341 ParsedAttributes &AccessAttrs,
3342 DeclSpec::TST TagType, Decl *Tag);
3343 void ParseConstructorInitializer(Decl *ConstructorDecl);
3344 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3345 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
3346 Decl *ThisDecl);
3347
3348 //===--------------------------------------------------------------------===//
3349 // C++ 10: Derived classes [class.derived]
3350 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3351 SourceLocation &EndLocation);
3352 void ParseBaseClause(Decl *ClassDecl);
3353 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3354 AccessSpecifier getAccessSpecifierIfPresent() const;
3355
3356 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
3357 ParsedType ObjectType,
3358 bool ObjectHadErrors,
3359 SourceLocation TemplateKWLoc,
3360 IdentifierInfo *Name,
3361 SourceLocation NameLoc,
3362 bool EnteringContext,
3363 UnqualifiedId &Id,
3364 bool AssumeTemplateId);
3365 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
3366 ParsedType ObjectType,
3367 UnqualifiedId &Result);
3368
3369 //===--------------------------------------------------------------------===//
3370 // OpenMP: Directives and clauses.
3371 /// Parse clauses for '#pragma omp declare simd'.
3372 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
3373 CachedTokens &Toks,
3374 SourceLocation Loc);
3375
3376 /// Parse a property kind into \p TIProperty for the selector set \p Set and
3377 /// selector \p Selector.
3378 void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
3379 llvm::omp::TraitSet Set,
3380 llvm::omp::TraitSelector Selector,
3381 llvm::StringMap<SourceLocation> &Seen);
3382
3383 /// Parse a selector kind into \p TISelector for the selector set \p Set.
3384 void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
3385 llvm::omp::TraitSet Set,
3386 llvm::StringMap<SourceLocation> &Seen);
3387
3388 /// Parse a selector set kind into \p TISet.
3389 void parseOMPTraitSetKind(OMPTraitSet &TISet,
3390 llvm::StringMap<SourceLocation> &Seen);
3391
3392 /// Parses an OpenMP context property.
3393 void parseOMPContextProperty(OMPTraitSelector &TISelector,
3394 llvm::omp::TraitSet Set,
3395 llvm::StringMap<SourceLocation> &Seen);
3396
3397 /// Parses an OpenMP context selector.
3398 void parseOMPContextSelector(OMPTraitSelector &TISelector,
3399 llvm::omp::TraitSet Set,
3400 llvm::StringMap<SourceLocation> &SeenSelectors);
3401
3402 /// Parses an OpenMP context selector set.
3403 void parseOMPContextSelectorSet(OMPTraitSet &TISet,
3404 llvm::StringMap<SourceLocation> &SeenSets);
3405
3406 /// Parses OpenMP context selectors.
3407 bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
3408
3409 /// Parse an 'append_args' clause for '#pragma omp declare variant'.
3410 bool parseOpenMPAppendArgs(SmallVectorImpl<OMPInteropInfo> &InteropInfos);
3411
3412 /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
3413 /// if there was an error.
3414 bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
3415 OMPTraitInfo *ParentTI);
3416
3417 /// Parse clauses for '#pragma omp declare variant'.
3418 void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
3419 SourceLocation Loc);
3420
3421 /// Parse 'omp [begin] assume[s]' directive.
3422 void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
3423 SourceLocation Loc);
3424
3425 /// Parse 'omp end assumes' directive.
3426 void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
3427
3428 /// Parses clauses for directive.
3429 ///
3430 /// \param DKind Kind of current directive.
3431 /// \param clauses for current directive.
3432 /// \param start location for clauses of current directive
3433 void ParseOpenMPClauses(OpenMPDirectiveKind DKind,
3434 SmallVectorImpl<clang::OMPClause *> &Clauses,
3435 SourceLocation Loc);
3436
3437 /// Parse clauses for '#pragma omp [begin] declare target'.
3438 void ParseOMPDeclareTargetClauses(SemaOpenMP::DeclareTargetContextInfo &DTCI);
3439
3440 /// Parse '#pragma omp end declare target'.
3441 void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
3442 OpenMPDirectiveKind EndDKind,
3443 SourceLocation Loc);
3444
3445 /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
3446 /// it is not the current token.
3447 void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
3448
3449 /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
3450 /// that the "end" matching the "begin" directive of kind \p BeginKind was not
3451 /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
3452 /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
3453 void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
3454 OpenMPDirectiveKind ExpectedKind,
3455 OpenMPDirectiveKind FoundKind,
3456 SourceLocation MatchingLoc,
3457 SourceLocation FoundLoc,
3458 bool SkipUntilOpenMPEnd);
3459
3460 /// Parses declarative OpenMP directives.
3461 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
3462 AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed = false,
3464 Decl *TagDecl = nullptr);
3465 /// Parse 'omp declare reduction' construct.
3466 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
3467 /// Parses initializer for provided omp_priv declaration inside the reduction
3468 /// initializer.
3469 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
3470
3471 /// Parses 'omp declare mapper' directive.
3472 DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
3473 /// Parses variable declaration in 'omp declare mapper' directive.
3474 TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
3475 DeclarationName &Name,
3477
3478 /// Tries to parse cast part of OpenMP array shaping operation:
3479 /// '[' expression ']' { '[' expression ']' } ')'.
3480 bool tryParseOpenMPArrayShapingCastPart();
3481
3482 /// Parses simple list of variables.
3483 ///
3484 /// \param Kind Kind of the directive.
3485 /// \param Callback Callback function to be called for the list elements.
3486 /// \param AllowScopeSpecifier true, if the variables can have fully
3487 /// qualified names.
3488 ///
3489 bool ParseOpenMPSimpleVarList(
3491 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
3492 Callback,
3493 bool AllowScopeSpecifier);
3494 /// Parses declarative or executable directive.
3495 ///
3496 /// \param StmtCtx The context in which we're parsing the directive.
3497 /// \param ReadDirectiveWithinMetadirective true if directive is within a
3498 /// metadirective and therefore ends on the closing paren.
3499 StmtResult ParseOpenMPDeclarativeOrExecutableDirective(
3500 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective = false);
3501 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
3502 ///
3503 /// \param DKind Kind of current directive.
3504 /// \param CKind Kind of current clause.
3505 /// \param FirstClause true, if this is the first clause of a kind \a CKind
3506 /// in current directive.
3507 ///
3508 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
3509 OpenMPClauseKind CKind, bool FirstClause);
3510 /// Parses clause with a single expression of a kind \a Kind.
3511 ///
3512 /// \param Kind Kind of current clause.
3513 /// \param ParseOnly true to skip the clause's semantic actions and return
3514 /// nullptr.
3515 ///
3516 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3517 bool ParseOnly);
3518 /// Parses simple clause of a kind \a Kind.
3519 ///
3520 /// \param Kind Kind of current clause.
3521 /// \param ParseOnly true to skip the clause's semantic actions and return
3522 /// nullptr.
3523 ///
3524 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
3525 /// Parses indirect clause
3526 /// \param ParseOnly true to skip the clause's semantic actions and return
3527 // false;
3528 bool ParseOpenMPIndirectClause(SemaOpenMP::DeclareTargetContextInfo &DTCI,
3529 bool ParseOnly);
3530 /// Parses clause with a single expression and an additional argument
3531 /// of a kind \a Kind.
3532 ///
3533 /// \param DKind Directive kind.
3534 /// \param Kind Kind of current clause.
3535 /// \param ParseOnly true to skip the clause's semantic actions and return
3536 /// nullptr.
3537 ///
3538 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3539 OpenMPClauseKind Kind,
3540 bool ParseOnly);
3541
3542 /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
3543 OMPClause *ParseOpenMPSizesClause();
3544
3545 /// Parses clause without any additional arguments.
3546 ///
3547 /// \param Kind Kind of current clause.
3548 /// \param ParseOnly true to skip the clause's semantic actions and return
3549 /// nullptr.
3550 ///
3551 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
3552 /// Parses clause with the list of variables of a kind \a Kind.
3553 ///
3554 /// \param Kind Kind of current clause.
3555 /// \param ParseOnly true to skip the clause's semantic actions and return
3556 /// nullptr.
3557 ///
3558 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
3559 OpenMPClauseKind Kind, bool ParseOnly);
3560
3561 /// Parses a clause consisting of a list of expressions.
3562 ///
3563 /// \param Kind The clause to parse.
3564 /// \param ClauseNameLoc [out] The location of the clause name.
3565 /// \param OpenLoc [out] The location of '('.
3566 /// \param CloseLoc [out] The location of ')'.
3567 /// \param Exprs [out] The parsed expressions.
3568 /// \param ReqIntConst If true, each expression must be an integer constant.
3569 ///
3570 /// \return Whether the clause was parsed successfully.
3571 bool ParseOpenMPExprListClause(OpenMPClauseKind Kind,
3572 SourceLocation &ClauseNameLoc,
3573 SourceLocation &OpenLoc,
3574 SourceLocation &CloseLoc,
3575 SmallVectorImpl<Expr *> &Exprs,
3576 bool ReqIntConst = false);
3577
3578 /// Parses and creates OpenMP 5.0 iterators expression:
3579 /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
3580 /// <range-specification> }+ ')'
3581 ExprResult ParseOpenMPIteratorsExpr();
3582
3583 /// Parses allocators and traits in the context of the uses_allocator clause.
3584 /// Expected format:
3585 /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
3586 OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
3587
3588 /// Parses the 'interop' parts of the 'append_args' and 'init' clauses.
3589 bool ParseOMPInteropInfo(OMPInteropInfo &InteropInfo, OpenMPClauseKind Kind);
3590
3591 /// Parses clause with an interop variable of kind \a Kind.
3592 ///
3593 /// \param Kind Kind of current clause.
3594 /// \param ParseOnly true to skip the clause's semantic actions and return
3595 /// nullptr.
3596 //
3597 OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
3598
3599 /// Parses a ompx_attribute clause
3600 ///
3601 /// \param ParseOnly true to skip the clause's semantic actions and return
3602 /// nullptr.
3603 //
3604 OMPClause *ParseOpenMPOMPXAttributesClause(bool ParseOnly);
3605
3606public:
3607 /// Parses simple expression in parens for single-expression clauses of OpenMP
3608 /// constructs.
3609 /// \param RLoc Returned location of right paren.
3610 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
3611 bool IsAddressOfOperand = false);
3612
3613 /// Parses a reserved locator like 'omp_all_memory'.
3615 SemaOpenMP::OpenMPVarListDataTy &Data,
3616 const LangOptions &LangOpts);
3617 /// Parses clauses with list.
3619 SmallVectorImpl<Expr *> &Vars,
3620 SemaOpenMP::OpenMPVarListDataTy &Data);
3621 bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
3622 bool ObjectHadErrors, bool EnteringContext,
3623 bool AllowDestructorName, bool AllowConstructorName,
3624 bool AllowDeductionGuide,
3625 SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
3626
3627 /// Parses the mapper modifier in map, to, and from clauses.
3628 bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data);
3629 /// Parses map-type-modifiers in map clause.
3630 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3631 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
3632 bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data);
3633
3634 //===--------------------------------------------------------------------===//
3635 // OpenACC Parsing.
3636
3637 /// Placeholder for now, should just ignore the directives after emitting a
3638 /// diagnostic. Eventually will be split into a few functions to parse
3639 /// different situations.
3640public:
3643
3644private:
3645 /// A struct to hold the information that got parsed by ParseOpenACCDirective,
3646 /// so that the callers of it can use that to construct the appropriate AST
3647 /// nodes.
3648 struct OpenACCDirectiveParseInfo {
3649 OpenACCDirectiveKind DirKind;
3650 SourceLocation StartLoc;
3651 SourceLocation EndLoc;
3652 SmallVector<OpenACCClause *> Clauses;
3653 // TODO OpenACC: As we implement support for the Atomic, Routine, Cache, and
3654 // Wait constructs, we likely want to put that information in here as well.
3655 };
3656
3657 struct OpenACCWaitParseInfo {
3658 bool Failed = false;
3659 Expr *DevNumExpr = nullptr;
3660 SourceLocation QueuesLoc;
3661 SmallVector<Expr *> QueueIdExprs;
3662 };
3663
3664 /// Represents the 'error' state of parsing an OpenACC Clause, and stores
3665 /// whether we can continue parsing, or should give up on the directive.
3666 enum class OpenACCParseCanContinue { Cannot = 0, Can = 1 };
3667
3668 /// A type to represent the state of parsing an OpenACC Clause. Situations
3669 /// that result in an OpenACCClause pointer are a success and can continue
3670 /// parsing, however some other situations can also continue.
3671 /// FIXME: This is better represented as a std::expected when we get C++23.
3672 using OpenACCClauseParseResult =
3673 llvm::PointerIntPair<OpenACCClause *, 1, OpenACCParseCanContinue>;
3674
3675 OpenACCClauseParseResult OpenACCCanContinue();
3676 OpenACCClauseParseResult OpenACCCannotContinue();
3677 OpenACCClauseParseResult OpenACCSuccess(OpenACCClause *Clause);
3678
3679 /// Parses the OpenACC directive (the entire pragma) including the clause
3680 /// list, but does not produce the main AST node.
3681 OpenACCDirectiveParseInfo ParseOpenACCDirective();
3682 /// Helper that parses an ID Expression based on the language options.
3683 ExprResult ParseOpenACCIDExpression();
3684 /// Parses the variable list for the `cache` construct.
3685 void ParseOpenACCCacheVarList();
3686
3687 using OpenACCVarParseResult = std::pair<ExprResult, OpenACCParseCanContinue>;
3688 /// Parses a single variable in a variable list for OpenACC.
3689 OpenACCVarParseResult ParseOpenACCVar();
3690 /// Parses the variable list for the variety of places that take a var-list.
3691 llvm::SmallVector<Expr *> ParseOpenACCVarList();
3692 /// Parses any parameters for an OpenACC Clause, including required/optional
3693 /// parens.
3694 OpenACCClauseParseResult
3695 ParseOpenACCClauseParams(ArrayRef<const OpenACCClause *> ExistingClauses,
3697 SourceLocation ClauseLoc);
3698 /// Parses a single clause in a clause-list for OpenACC. Returns nullptr on
3699 /// error.
3700 OpenACCClauseParseResult
3701 ParseOpenACCClause(ArrayRef<const OpenACCClause *> ExistingClauses,
3702 OpenACCDirectiveKind DirKind);
3703 /// Parses the clause-list for an OpenACC directive.
3704 SmallVector<OpenACCClause *>
3705 ParseOpenACCClauseList(OpenACCDirectiveKind DirKind);
3706 OpenACCWaitParseInfo ParseOpenACCWaitArgument(SourceLocation Loc,
3707 bool IsDirective);
3708 /// Parses the clause of the 'bind' argument, which can be a string literal or
3709 /// an ID expression.
3710 ExprResult ParseOpenACCBindClauseArgument();
3711
3712 /// A type to represent the state of parsing after an attempt to parse an
3713 /// OpenACC int-expr. This is useful to determine whether an int-expr list can
3714 /// continue parsing after a failed int-expr.
3715 using OpenACCIntExprParseResult =
3716 std::pair<ExprResult, OpenACCParseCanContinue>;
3717 /// Parses the clause kind of 'int-expr', which can be any integral
3718 /// expression.
3719 OpenACCIntExprParseResult ParseOpenACCIntExpr(OpenACCDirectiveKind DK,
3721 SourceLocation Loc);
3722 /// Parses the argument list for 'num_gangs', which allows up to 3
3723 /// 'int-expr's.
3724 bool ParseOpenACCIntExprList(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
3725 SourceLocation Loc,
3727 /// Parses the 'device-type-list', which is a list of identifiers.
3728 bool ParseOpenACCDeviceTypeList(
3729 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>> &Archs);
3730 /// Parses the 'async-argument', which is an integral value with two
3731 /// 'special' values that are likely negative (but come from Macros).
3732 OpenACCIntExprParseResult ParseOpenACCAsyncArgument(OpenACCDirectiveKind DK,
3734 SourceLocation Loc);
3735 /// Parses the 'size-expr', which is an integral value, or an asterisk.
3736 bool ParseOpenACCSizeExpr();
3737 /// Parses a comma delimited list of 'size-expr's.
3738 bool ParseOpenACCSizeExprList();
3739 /// Parses a 'gang-arg-list', used for the 'gang' clause.
3740 bool ParseOpenACCGangArgList(SourceLocation GangLoc);
3741 /// Parses a 'gang-arg', used for the 'gang' clause.
3742 bool ParseOpenACCGangArg(SourceLocation GangLoc);
3743 /// Parses a 'condition' expr, ensuring it results in a
3744 ExprResult ParseOpenACCConditionExpr();
3745
3746private:
3747 //===--------------------------------------------------------------------===//
3748 // C++ 14: Templates [temp]
3749
3750 // C++ 14.1: Template Parameters [temp.param]
3752 ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
3753 SourceLocation &DeclEnd,
3754 ParsedAttributes &AccessAttrs);
3755 DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
3756 DeclaratorContext Context, SourceLocation &DeclEnd,
3757 ParsedAttributes &AccessAttrs, AccessSpecifier AS);
3758 DeclGroupPtrTy ParseDeclarationAfterTemplate(
3759 DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo,
3760 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
3761 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
3762 bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
3763 SmallVectorImpl<NamedDecl *> &TemplateParams,
3764 SourceLocation &LAngleLoc,
3765 SourceLocation &RAngleLoc);
3766 bool ParseTemplateParameterList(unsigned Depth,
3767 SmallVectorImpl<NamedDecl*> &TemplateParams);
3768 TPResult isStartOfTemplateTypeParameter();
3769 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
3770 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
3771 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
3772 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
3773 bool isTypeConstraintAnnotation();
3774 bool TryAnnotateTypeConstraint();
3775 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
3776 SourceLocation CorrectLoc,
3777 bool AlreadyHasEllipsis,
3778 bool IdentifierHasName);
3779 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
3780 Declarator &D);
3781 // C++ 14.3: Template arguments [temp.arg]
3782 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
3783
3784 bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
3785 SourceLocation &RAngleLoc,
3786 bool ConsumeLastToken,
3787 bool ObjCGenericList);
3788 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
3789 SourceLocation &LAngleLoc,
3790 TemplateArgList &TemplateArgs,
3791 SourceLocation &RAngleLoc,
3792 TemplateTy NameHint = nullptr);
3793
3794 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
3795 CXXScopeSpec &SS,
3796 SourceLocation TemplateKWLoc,
3797 UnqualifiedId &TemplateName,
3798 bool AllowTypeAnnotation = true,
3799 bool TypeConstraint = false);
3800 void
3801 AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
3802 ImplicitTypenameContext AllowImplicitTypename,
3803 bool IsClassName = false);
3804 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
3805 TemplateTy Template, SourceLocation OpenLoc);
3806 ParsedTemplateArgument ParseTemplateTemplateArgument();
3807 ParsedTemplateArgument ParseTemplateArgument();
3808 DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context,
3809 SourceLocation ExternLoc,
3810 SourceLocation TemplateLoc,
3811 SourceLocation &DeclEnd,
3812 ParsedAttributes &AccessAttrs,
3814 // C++2a: Template, concept definition [temp]
3815 Decl *
3816 ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
3817 SourceLocation &DeclEnd);
3818
3819 /// Parse the given string as a type.
3820 ///
3821 /// This is a dangerous utility function currently employed only by API notes.
3822 /// It is not a general entry-point for safely parsing types from strings.
3823 ///
3824 /// \param TypeStr The string to be parsed as a type.
3825 /// \param Context The name of the context in which this string is being
3826 /// parsed, which will be used in diagnostics.
3827 /// \param IncludeLoc The location at which this parse was triggered.
3828 TypeResult ParseTypeFromString(StringRef TypeStr, StringRef Context,
3829 SourceLocation IncludeLoc);
3830
3831 //===--------------------------------------------------------------------===//
3832 // Modules
3833 DeclGroupPtrTy ParseModuleDecl(Sema::ModuleImportState &ImportState);
3834 Decl *ParseModuleImport(SourceLocation AtLoc,
3835 Sema::ModuleImportState &ImportState);
3836 bool parseMisplacedModuleImport();
3837 bool tryParseMisplacedModuleImport() {
3838 tok::TokenKind Kind = Tok.getKind();
3839 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
3840 Kind == tok::annot_module_include)
3841 return parseMisplacedModuleImport();
3842 return false;
3843 }
3844
3845 bool ParseModuleName(
3846 SourceLocation UseLoc,
3847 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
3848 bool IsImport);
3849
3850 //===--------------------------------------------------------------------===//
3851 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
3852 ExprResult ParseTypeTrait();
3853
3854 //===--------------------------------------------------------------------===//
3855 // Embarcadero: Arary and Expression Traits
3856 ExprResult ParseArrayTypeTrait();
3857 ExprResult ParseExpressionTrait();
3858
3859 //===--------------------------------------------------------------------===//
3860 // Preprocessor code-completion pass-through
3861 void CodeCompleteDirective(bool InConditional) override;
3862 void CodeCompleteInConditionalExclusion() override;
3863 void CodeCompleteMacroName(bool IsDefinition) override;
3864 void CodeCompletePreprocessorExpression() override;
3865 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
3866 unsigned ArgumentIndex) override;
3867 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
3868 void CodeCompleteNaturalLanguage() override;
3869
3870 class GNUAsmQualifiers {
3871 unsigned Qualifiers = AQ_unspecified;
3872
3873 public:
3874 enum AQ {
3875 AQ_unspecified = 0,
3876 AQ_volatile = 1,
3877 AQ_inline = 2,
3878 AQ_goto = 4,
3879 };
3880 static const char *getQualifierName(AQ Qualifier);
3881 bool setAsmQualifier(AQ Qualifier);
3882 inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
3883 inline bool isInline() const { return Qualifiers & AQ_inline; };
3884 inline bool isGoto() const { return Qualifiers & AQ_goto; }
3885 };
3886 bool isGCCAsmStatement(const Token &TokAfterAsm) const;
3887 bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
3888 GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
3889 bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
3890};
3891
3892} // end namespace clang
3893
3894#endif
int Id
Definition: ASTDiff.cpp:190
StringRef P
int Priority
Definition: Format.cpp:2979
Defines some OpenACC-specific enums and functions.
Defines and computes precedence levels for binary/ternary operators.
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
bool isInvalid() const
Definition: Ownership.h:166
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:639
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Callback handler that receives notifications when performing code completion within the preprocessor.
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
TypeSpecifierType TST
Definition: DeclSpec.h:277
static const TST TST_unspecified
Definition: DeclSpec.h:278
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
This represents one expression.
Definition: Expr.h:110
One of these records is kept for each identifier that is lexed.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
Wrapper for void* pointer.
Definition: Ownership.h:50
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
Introduces zero or more scopes for parsing.
Definition: Parser.h:1206
MultiParseScope(Parser &Self)
Definition: Parser.h:1213
void Enter(unsigned ScopeFlags)
Definition: Parser.h:1214
ParseScope - Introduces a new scope for parsing.
Definition: Parser.h:1168
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope=true, bool BeforeCompoundStmt=false)
Definition: Parser.h:1177
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl< Expr * > &Vars, SemaOpenMP::OpenMPVarListDataTy &Data)
Parses clauses with list.
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName type-name: [C99 6.7.6] specifier-qualifier-list abstract-declarator[opt].
Definition: ParseDecl.cpp:50
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:81
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope, ImplicitTypenameContext AllowImplicitTypename)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
Definition: Parser.cpp:2119
Preprocessor & getPreprocessor() const
Definition: Parser.h:494
bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data)
Parses map-type-modifiers in map clause.
Sema::FullExprArg FullExprArg
Definition: Parser.h:515
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:545
DeclGroupPtrTy ParseOpenACCDirectiveDecl()
Placeholder for now, should just ignore the directives after emitting a diagnostic.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition: Parser.cpp:54
AttributeFactory & getAttrFactory()
Definition: Parser.h:496
void incrementMSManglingNumber() const
Definition: Parser.h:500
Sema & getActions() const
Definition: Parser.h:495
bool ParseTopLevelDecl()
Definition: Parser.h:534
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:874
ExprResult ParseCaseExpression(SourceLocation CaseLoc)
Definition: ParseExpr.cpp:252
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition: Parser.cpp:420
bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data)
Parses the mapper modifier in map, to, and from clauses.
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:380
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl< Token > &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated)
Parse an identifier in an MS-style inline assembly block.
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext=false)
Definition: Parser.h:933
friend class ColonProtectionRAIIObject
Definition: Parser.h:59
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
Definition: Parser.h:1295
~Parser() override
Definition: Parser.cpp:470
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:573
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:233
StmtResult ParseOpenACCDirectiveStmt()
ExprResult ParseConditionalExpression()
Definition: ParseExpr.cpp:188
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:553
friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R)
Definition: Parser.h:1276
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:510
Scope * getCurScope() const
Definition: Parser.h:499
SourceLocation getEndOfPreviousToken()
Definition: Parser.h:591
ExprResult ParseArrayBoundExpression()
Definition: ParseExpr.cpp:243
ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-and-expression.
Definition: ParseExpr.cpp:288
const TargetInfo & getTargetInfo() const
Definition: Parser.h:493
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:511
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:1291
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:2160
const Token & getCurToken() const
Definition: Parser.h:498
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds to the given nullability kind...
Definition: Parser.h:597
friend class ObjCDeclContextSwitch
Definition: Parser.h:65
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
Definition: Parser.h:1300
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition: Parser.cpp:431
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:169
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand=false)
Parses simple expression in parens for single-expression clauses of OpenMP constructs.
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:223
SourceLocation MisleadingIndentationElseLoc
The location of the first statement inside an else that might have a missleading indentation.
Definition: Parser.h:1315
const LangOptions & getLangOpts() const
Definition: Parser.h:492
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:132
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
Definition: Parser.cpp:601
DiagnosticBuilder Diag(unsigned DiagID)
Definition: Parser.h:1257
SmallVector< Stmt *, 32 > StmtVector
A SmallVector of statements.
Definition: Parser.h:518
SkipUntilFlags
Control flags for SkipUntil functions.
Definition: Parser.h:1269
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1272
@ StopAtCodeCompletion
Stop at code completion.
Definition: Parser.h:1273
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1270
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:2000
bool MightBeCXXScopeToken()
Definition: Parser.h:926
TypeCastState
TypeCastState - State whether an expression is or may be a type cast.
Definition: Parser.h:1830
ExprResult ParseUnevaluatedStringLiteralExpression()
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
bool ParseOpenMPReservedLocator(OpenMPClauseKind Kind, SemaOpenMP::OpenMPVarListDataTy &Data, const LangOptions &LangOpts)
Parses a reserved locator like 'omp_all_memory'.
ObjCContainerDecl * getObjCDeclContext() const
Definition: Parser.h:504
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:869
friend class BalancedDelimiterTracker
Definition: Parser.h:67
bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc)
Definition: Parser.h:563
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:266
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:513
void Initialize()
Initialize - Warm up the parser.
Definition: Parser.cpp:490
unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D)
Re-enter the template scopes for a declaration that might be a template.
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:2234
Activates OpenACC parsing mode to preseve OpenACC specific annotation tokens.
Activates OpenMP parsing mode to preseve OpenMP specific annotation tokens.
Tracks expected type during expression parsing, for use in code completion.
Definition: Sema.h:292
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
void setCodeCompletionReached()
Note that we hit the code-completion point.
bool mightHavePendingAnnotationTokens()
Determine whether it's possible for a future call to Lex to produce an annotation token created by a ...
void Lex(Token &Result)
Lex the next token for this preprocessor.
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
const TargetInfo & getTargetInfo() const
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
const LangOptions & getLangOpts() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ObjCContainerDecl * getObjCDeclContext() const
void startOpenMPLoop()
If the current region is a loop-based region, mark the start of the loop construct.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:688
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
ConditionKind
Definition: Sema.h:5828
SemaObjC & ObjC()
Definition: Sema.h:1003
ProcessingContextState ParsingClassState
Definition: Sema.h:4801
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
Definition: SemaType.cpp:3825
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition: Sema.h:7688
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
void incrementMSManglingNumber() const
Definition: Sema.h:824
OffsetOfKind
Definition: Sema.h:3172
@ OOK_Outside
Definition: Sema.h:3174
Encodes a location in the source.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition: TargetInfo.h:218
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
void setKind(tok::TokenKind K)
Definition: Token.h:95
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:146
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
void * getAnnotationValue() const
Definition: Token.h:234
tok::TokenKind getKind() const
Definition: Token.h:94
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
void setAnnotationValue(void *val)
Definition: Token.h:238
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
bool Pop(InterpState &S, CodePtr OpPC)
Definition: Interp.h:929
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
Definition: OpenACCKinds.h:164
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ TST_unspecified
Definition: Specifiers.h:56
ImplicitTypenameContext
Definition: DeclSpec.h:1883
@ CPlusPlus
Definition: LangStandard.h:55
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition: OpenMPKinds.h:24
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:333
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
TypeResult TypeError()
Definition: Ownership.h:266
ActionResult< CXXCtorInitializer * > MemInitResult
Definition: Ownership.h:252
DeclaratorContext
Definition: DeclSpec.h:1850
@ Result
The result type of a method or function.
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
OpenACCDirectiveKind
Definition: OpenACCKinds.h:25
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition: DeclSpec.h:1242
@ Class
The "class" keyword introduces the elaborated-type-specifier.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
ActionResult< CXXBaseSpecifier * > BaseResult
Definition: Ownership.h:251
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_none
Definition: Specifiers.h:124
Definition: Format.h:5428
#define false
Definition: stdbool.h:26
AngleBracketTracker::Priority Priority
Definition: Parser.h:394
bool isActive(Parser &P) const
Definition: Parser.h:397
bool isActiveOrNested(Parser &P) const
Definition: Parser.h:402