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

source code of clang/include/clang/Parse/Parser.h