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/SemaCodeCompletion.h"
22#include "clang/Sema/SemaObjC.h"
23#include "clang/Sema/SemaOpenMP.h"
24#include "llvm/ADT/STLForwardCompat.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/Frontend/OpenMP/OMPContext.h"
27#include "llvm/Support/SaveAndRestore.h"
28#include <optional>
29#include <stack>
30
31namespace clang {
32class PragmaHandler;
33class Scope;
34class BalancedDelimiterTracker;
35class CorrectionCandidateCallback;
36class DeclGroupRef;
37class DiagnosticBuilder;
38struct LoopHint;
39class Parser;
40class ParsingDeclRAIIObject;
41class ParsingDeclSpec;
42class ParsingDeclarator;
43class ParsingFieldDeclarator;
44class ColonProtectionRAIIObject;
45class InMessageExpressionRAIIObject;
46class PoisonSEHIdentifiersRAIIObject;
47class OMPClause;
48class OpenACCClause;
49class ObjCTypeParamList;
50struct OMPTraitProperty;
51struct OMPTraitSelector;
52struct OMPTraitSet;
53class OMPTraitInfo;
54
55enum class AnnotatedNameKind {
56 /// Annotation has failed and emitted an error.
57 Error,
58 /// The identifier is a tentatively-declared name.
59 TentativeDecl,
60 /// The identifier is a template name. FIXME: Add an annotation for that.
61 TemplateName,
62 /// The identifier can't be resolved.
63 Unresolved,
64 /// Annotation was successful.
65 Success
66};
67
68/// The kind of extra semi diagnostic to emit.
69enum class ExtraSemiKind {
70 OutsideFunction = 0,
71 InsideStruct = 1,
72 InstanceVariableList = 2,
73 AfterMemberFunctionDefinition = 3
74};
75
76/// The kind of template we are parsing.
77enum class ParsedTemplateKind {
78 /// We are not parsing a template at all.
79 NonTemplate = 0,
80 /// We are parsing a template declaration.
81 Template,
82 /// We are parsing an explicit specialization.
83 ExplicitSpecialization,
84 /// We are parsing an explicit instantiation.
85 ExplicitInstantiation
86};
87
88enum class CachedInitKind { DefaultArgument, DefaultInitializer };
89
90// Definitions for Objective-c context sensitive keywords recognition.
91enum class ObjCTypeQual {
92 in = 0,
93 out,
94 inout,
95 oneway,
96 bycopy,
97 byref,
98 nonnull,
99 nullable,
100 null_unspecified,
101 NumQuals
102};
103
104/// TypeCastState - State whether an expression is or may be a type cast.
105enum class TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast };
106
107/// Control what ParseCastExpression will parse.
108enum class CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly };
109
110/// ParenParseOption - Control what ParseParenExpression will parse.
111enum class ParenParseOption {
112 SimpleExpr, // Only parse '(' expression ')'
113 FoldExpr, // Also allow fold-expression <anything>
114 CompoundStmt, // Also allow '(' compound-statement ')'
115 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
116 CastExpr // Also allow '(' type-name ')' <anything>
117};
118
119/// Describes the behavior that should be taken for an __if_exists
120/// block.
121enum class IfExistsBehavior {
122 /// Parse the block; this code is always used.
123 Parse,
124 /// Skip the block entirely; this code is never used.
125 Skip,
126 /// Parse the block as a dependent block, which may be used in
127 /// some template instantiations but not others.
128 Dependent
129};
130
131/// Specifies the context in which type-id/expression
132/// disambiguation will occur.
133enum class TentativeCXXTypeIdContext {
134 InParens,
135 Unambiguous,
136 AsTemplateArgument,
137 InTrailingReturnType,
138 AsGenericSelectionArgument,
139};
140
141/// The kind of attribute specifier we have found.
142enum class CXX11AttributeKind {
143 /// This is not an attribute specifier.
144 NotAttributeSpecifier,
145 /// This should be treated as an attribute-specifier.
146 AttributeSpecifier,
147 /// The next tokens are '[[', but this is not an attribute-specifier. This
148 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
149 InvalidAttributeSpecifier
150};
151
152/// Parser - This implements a parser for the C family of languages. After
153/// parsing units of the grammar, productions are invoked to handle whatever has
154/// been read.
155///
156/// \nosubgrouping
157class Parser : public CodeCompletionHandler {
158 // Table of Contents
159 // -----------------
160 // 1. Parsing (Parser.cpp)
161 // 2. C++ Class Inline Methods (ParseCXXInlineMethods.cpp)
162 // 3. Declarations (ParseDecl.cpp)
163 // 4. C++ Declarations (ParseDeclCXX.cpp)
164 // 5. Expressions (ParseExpr.cpp)
165 // 6. C++ Expressions (ParseExprCXX.cpp)
166 // 7. HLSL Constructs (ParseHLSL.cpp)
167 // 8. Initializers (ParseInit.cpp)
168 // 9. Objective-C Constructs (ParseObjc.cpp)
169 // 10. OpenACC Constructs (ParseOpenACC.cpp)
170 // 11. OpenMP Constructs (ParseOpenMP.cpp)
171 // 12. Pragmas (ParsePragma.cpp)
172 // 13. Statements (ParseStmt.cpp)
173 // 14. `inline asm` Statement (ParseStmtAsm.cpp)
174 // 15. C++ Templates (ParseTemplate.cpp)
175 // 16. Tentative Parsing (ParseTentative.cpp)
176
177 /// \name Parsing
178 /// Implementations are in Parser.cpp
179 ///@{
180
181public:
182 friend class ColonProtectionRAIIObject;
183 friend class PoisonSEHIdentifiersRAIIObject;
184 friend class ParenBraceBracketBalancer;
185 friend class BalancedDelimiterTracker;
186
187 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
188 ~Parser() override;
189
190 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
191 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
192 Preprocessor &getPreprocessor() const { return PP; }
193 Sema &getActions() const { return Actions; }
194 AttributeFactory &getAttrFactory() { return AttrFactory; }
195
196 const Token &getCurToken() const { return Tok; }
197 Scope *getCurScope() const { return Actions.getCurScope(); }
198
199 void incrementMSManglingNumber() const {
200 return Actions.incrementMSManglingNumber();
201 }
202
203 // Type forwarding. All of these are statically 'void*', but they may all be
204 // different actual classes based on the actions in place.
205 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
206 typedef OpaquePtr<TemplateName> TemplateTy;
207
208 /// Initialize - Warm up the parser.
209 ///
210 void Initialize();
211
212 /// Parse the first top-level declaration in a translation unit.
213 ///
214 /// \verbatim
215 /// translation-unit:
216 /// [C] external-declaration
217 /// [C] translation-unit external-declaration
218 /// [C++] top-level-declaration-seq[opt]
219 /// [C++20] global-module-fragment[opt] module-declaration
220 /// top-level-declaration-seq[opt] private-module-fragment[opt]
221 /// \endverbatim
222 ///
223 /// Note that in C, it is an error if there is no first declaration.
224 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
225 Sema::ModuleImportState &ImportState);
226
227 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
228 /// action tells us to. This returns true if the EOF was encountered.
229 ///
230 /// \verbatim
231 /// top-level-declaration:
232 /// declaration
233 /// [C++20] module-import-declaration
234 /// \endverbatim
235 bool ParseTopLevelDecl(DeclGroupPtrTy &Result,
236 Sema::ModuleImportState &ImportState);
237 bool ParseTopLevelDecl() {
238 DeclGroupPtrTy Result;
239 Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
240 return ParseTopLevelDecl(Result, ImportState&: IS);
241 }
242
243 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
244 /// This does not work with special tokens: string literals, code completion,
245 /// annotation tokens and balanced tokens must be handled using the specific
246 /// consume methods.
247 /// Returns the location of the consumed token.
248 SourceLocation ConsumeToken() {
249 assert(!isTokenSpecial() &&
250 "Should consume special tokens with Consume*Token");
251 PrevTokLocation = Tok.getLocation();
252 PP.Lex(Result&: Tok);
253 return PrevTokLocation;
254 }
255
256 bool TryConsumeToken(tok::TokenKind Expected) {
257 if (Tok.isNot(K: Expected))
258 return false;
259 assert(!isTokenSpecial() &&
260 "Should consume special tokens with Consume*Token");
261 PrevTokLocation = Tok.getLocation();
262 PP.Lex(Result&: Tok);
263 return true;
264 }
265
266 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
267 if (!TryConsumeToken(Expected))
268 return false;
269 Loc = PrevTokLocation;
270 return true;
271 }
272
273 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
274 /// current token type. This should only be used in cases where the type of
275 /// the token really isn't known, e.g. in error recovery.
276 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
277 if (isTokenParen())
278 return ConsumeParen();
279 if (isTokenBracket())
280 return ConsumeBracket();
281 if (isTokenBrace())
282 return ConsumeBrace();
283 if (isTokenStringLiteral())
284 return ConsumeStringToken();
285 if (Tok.is(K: tok::code_completion))
286 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
287 : handleUnexpectedCodeCompletionToken();
288 if (Tok.isAnnotation())
289 return ConsumeAnnotationToken();
290 return ConsumeToken();
291 }
292
293 SourceLocation getEndOfPreviousToken() const;
294
295 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
296 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
297 /// returns the token after Tok, etc.
298 ///
299 /// Note that this differs from the Preprocessor's LookAhead method, because
300 /// the Parser always has one token lexed that the preprocessor doesn't.
301 ///
302 const Token &GetLookAheadToken(unsigned N) {
303 if (N == 0 || Tok.is(K: tok::eof))
304 return Tok;
305 return PP.LookAhead(N: N - 1);
306 }
307
308 /// NextToken - This peeks ahead one token and returns it without
309 /// consuming it.
310 const Token &NextToken() { return PP.LookAhead(N: 0); }
311
312 /// getTypeAnnotation - Read a parsed type out of an annotation token.
313 static TypeResult getTypeAnnotation(const Token &Tok) {
314 if (!Tok.getAnnotationValue())
315 return TypeError();
316 return ParsedType::getFromOpaquePtr(P: Tok.getAnnotationValue());
317 }
318
319 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
320 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
321 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
322 /// with a single annotation token representing the typename or C++ scope
323 /// respectively.
324 /// This simplifies handling of C++ scope specifiers and allows efficient
325 /// backtracking without the need to re-parse and resolve nested-names and
326 /// typenames.
327 /// It will mainly be called when we expect to treat identifiers as typenames
328 /// (if they are typenames). For example, in C we do not expect identifiers
329 /// inside expressions to be treated as typenames so it will not be called
330 /// for expressions in C.
331 /// The benefit for C/ObjC is that a typename will be annotated and
332 /// Actions.getTypeName will not be needed to be called again (e.g.
333 /// getTypeName will not be called twice, once to check whether we have a
334 /// declaration specifier, and another one to get the actual type inside
335 /// ParseDeclarationSpecifiers).
336 ///
337 /// This returns true if an error occurred.
338 ///
339 /// Note that this routine emits an error if you call it with ::new or
340 /// ::delete as the current tokens, so only call it in contexts where these
341 /// are invalid.
342 bool
343 TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename =
344 ImplicitTypenameContext::No);
345
346 /// Try to annotate a type or scope token, having already parsed an
347 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
348 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
349 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(
350 CXXScopeSpec &SS, bool IsNewScope,
351 ImplicitTypenameContext AllowImplicitTypename);
352
353 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
354 /// annotates C++ scope specifiers and template-ids. This returns
355 /// true if there was an error that could not be recovered from.
356 ///
357 /// Note that this routine emits an error if you call it with ::new or
358 /// ::delete as the current tokens, so only call it in contexts where these
359 /// are invalid.
360 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
361
362 bool MightBeCXXScopeToken() {
363 return getLangOpts().CPlusPlus &&
364 (Tok.is(K: tok::identifier) || Tok.is(K: tok::coloncolon) ||
365 (Tok.is(K: tok::annot_template_id) &&
366 NextToken().is(K: tok::coloncolon)) ||
367 Tok.is(K: tok::kw_decltype) || Tok.is(K: tok::kw___super));
368 }
369 bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
370 return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
371 }
372
373 //===--------------------------------------------------------------------===//
374 // Scope manipulation
375
376 /// ParseScope - Introduces a new scope for parsing. The kind of
377 /// scope is determined by ScopeFlags. Objects of this type should
378 /// be created on the stack to coincide with the position where the
379 /// parser enters the new scope, and this object's constructor will
380 /// create that new scope. Similarly, once the object is destroyed
381 /// the parser will exit the scope.
382 class ParseScope {
383 Parser *Self;
384 ParseScope(const ParseScope &) = delete;
385 void operator=(const ParseScope &) = delete;
386
387 public:
388 // ParseScope - Construct a new object to manage a scope in the
389 // parser Self where the new Scope is created with the flags
390 // ScopeFlags, but only when we aren't about to enter a compound statement.
391 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
392 bool BeforeCompoundStmt = false)
393 : Self(Self) {
394 if (EnteredScope && !BeforeCompoundStmt)
395 Self->EnterScope(ScopeFlags);
396 else {
397 if (BeforeCompoundStmt)
398 Self->incrementMSManglingNumber();
399
400 this->Self = nullptr;
401 }
402 }
403
404 // Exit - Exit the scope associated with this object now, rather
405 // than waiting until the object is destroyed.
406 void Exit() {
407 if (Self) {
408 Self->ExitScope();
409 Self = nullptr;
410 }
411 }
412
413 ~ParseScope() { Exit(); }
414 };
415
416 /// Introduces zero or more scopes for parsing. The scopes will all be exited
417 /// when the object is destroyed.
418 class MultiParseScope {
419 Parser &Self;
420 unsigned NumScopes = 0;
421
422 MultiParseScope(const MultiParseScope &) = delete;
423
424 public:
425 MultiParseScope(Parser &Self) : Self(Self) {}
426 void Enter(unsigned ScopeFlags) {
427 Self.EnterScope(ScopeFlags);
428 ++NumScopes;
429 }
430 void Exit() {
431 while (NumScopes) {
432 Self.ExitScope();
433 --NumScopes;
434 }
435 }
436 ~MultiParseScope() { Exit(); }
437 };
438
439 /// EnterScope - Start a new scope.
440 void EnterScope(unsigned ScopeFlags);
441
442 /// ExitScope - Pop a scope off the scope stack.
443 void ExitScope();
444
445 //===--------------------------------------------------------------------===//
446 // Diagnostic Emission and Error recovery.
447
448 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
449 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
450 DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); }
451
452 DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId);
453 DiagnosticBuilder DiagCompat(const Token &Tok, unsigned CompatDiagId);
454 DiagnosticBuilder DiagCompat(unsigned CompatDiagId) {
455 return DiagCompat(Tok, CompatDiagId);
456 }
457
458 /// Control flags for SkipUntil functions.
459 enum SkipUntilFlags {
460 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
461 /// Stop skipping at specified token, but don't skip the token itself
462 StopBeforeMatch = 1 << 1,
463 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
464 };
465
466 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
467 SkipUntilFlags R) {
468 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
469 static_cast<unsigned>(R));
470 }
471
472 /// SkipUntil - Read tokens until we get to the specified token, then consume
473 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
474 /// that the token will ever occur, this skips to the next token, or to some
475 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
476 /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
477 /// skipping.
478 ///
479 /// If SkipUntil finds the specified token, it returns true, otherwise it
480 /// returns false.
481 bool SkipUntil(tok::TokenKind T,
482 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
483 return SkipUntil(Toks: llvm::ArrayRef(T), Flags);
484 }
485 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
486 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
487 tok::TokenKind TokArray[] = {T1, T2};
488 return SkipUntil(Toks: TokArray, Flags);
489 }
490 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
491 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
492 tok::TokenKind TokArray[] = {T1, T2, T3};
493 return SkipUntil(Toks: TokArray, Flags);
494 }
495
496 /// SkipUntil - Read tokens until we get to the specified token, then consume
497 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
498 /// token will ever occur, this skips to the next token, or to some likely
499 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
500 /// character.
501 ///
502 /// If SkipUntil finds the specified token, it returns true, otherwise it
503 /// returns false.
504 bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
505 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
506
507private:
508 Preprocessor &PP;
509
510 /// Tok - The current token we are peeking ahead. All parsing methods assume
511 /// that this is valid.
512 Token Tok;
513
514 // PrevTokLocation - The location of the token we previously
515 // consumed. This token is used for diagnostics where we expected to
516 // see a token following another token (e.g., the ';' at the end of
517 // a statement).
518 SourceLocation PrevTokLocation;
519
520 /// Tracks an expected type for the current token when parsing an expression.
521 /// Used by code completion for ranking.
522 PreferredTypeBuilder PreferredType;
523
524 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
525 unsigned short MisplacedModuleBeginCount = 0;
526
527 /// Actions - These are the callbacks we invoke as we parse various constructs
528 /// in the file.
529 Sema &Actions;
530
531 DiagnosticsEngine &Diags;
532
533 StackExhaustionHandler StackHandler;
534
535 /// ScopeCache - Cache scopes to reduce malloc traffic.
536 static constexpr int ScopeCacheSize = 16;
537 unsigned NumCachedScopes;
538 Scope *ScopeCache[ScopeCacheSize];
539
540 /// Identifiers used for SEH handling in Borland. These are only
541 /// allowed in particular circumstances
542 // __except block
543 IdentifierInfo *Ident__exception_code, *Ident___exception_code,
544 *Ident_GetExceptionCode;
545 // __except filter expression
546 IdentifierInfo *Ident__exception_info, *Ident___exception_info,
547 *Ident_GetExceptionInfo;
548 // __finally
549 IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination,
550 *Ident_AbnormalTermination;
551
552 /// Contextual keywords for Microsoft extensions.
553 IdentifierInfo *Ident__except;
554
555 // C++2a contextual keywords.
556 mutable IdentifierInfo *Ident_import;
557 mutable IdentifierInfo *Ident_module;
558
559 std::unique_ptr<CommentHandler> CommentSemaHandler;
560
561 /// Gets set to true after calling ProduceSignatureHelp, it is for a
562 /// workaround to make sure ProduceSignatureHelp is only called at the deepest
563 /// function call.
564 bool CalledSignatureHelp = false;
565
566 IdentifierInfo *getSEHExceptKeyword();
567
568 /// Whether to skip parsing of function bodies.
569 ///
570 /// This option can be used, for example, to speed up searches for
571 /// declarations/definitions when indexing.
572 bool SkipFunctionBodies;
573
574 //===--------------------------------------------------------------------===//
575 // Low-Level token peeking and consumption methods.
576 //
577
578 /// isTokenParen - Return true if the cur token is '(' or ')'.
579 bool isTokenParen() const { return Tok.isOneOf(K1: tok::l_paren, K2: tok::r_paren); }
580 /// isTokenBracket - Return true if the cur token is '[' or ']'.
581 bool isTokenBracket() const {
582 return Tok.isOneOf(K1: tok::l_square, K2: tok::r_square);
583 }
584 /// isTokenBrace - Return true if the cur token is '{' or '}'.
585 bool isTokenBrace() const { return Tok.isOneOf(K1: tok::l_brace, K2: tok::r_brace); }
586 /// isTokenStringLiteral - True if this token is a string-literal.
587 bool isTokenStringLiteral() const {
588 return tok::isStringLiteral(K: Tok.getKind());
589 }
590 /// isTokenSpecial - True if this token requires special consumption methods.
591 bool isTokenSpecial() const {
592 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
593 isTokenBrace() || Tok.is(K: tok::code_completion) || Tok.isAnnotation();
594 }
595
596 /// Returns true if the current token is '=' or is a type of '='.
597 /// For typos, give a fixit to '='
598 bool isTokenEqualOrEqualTypo();
599
600 /// Return the current token to the token stream and make the given
601 /// token the current token.
602 void UnconsumeToken(Token &Consumed) {
603 Token Next = Tok;
604 PP.EnterToken(Tok: Consumed, /*IsReinject*/ IsReinject: true);
605 PP.Lex(Result&: Tok);
606 PP.EnterToken(Tok: Next, /*IsReinject*/ IsReinject: true);
607 }
608
609 SourceLocation ConsumeAnnotationToken() {
610 assert(Tok.isAnnotation() && "wrong consume method");
611 SourceLocation Loc = Tok.getLocation();
612 PrevTokLocation = Tok.getAnnotationEndLoc();
613 PP.Lex(Result&: Tok);
614 return Loc;
615 }
616
617 /// ConsumeParen - This consume method keeps the paren count up-to-date.
618 ///
619 SourceLocation ConsumeParen() {
620 assert(isTokenParen() && "wrong consume method");
621 if (Tok.getKind() == tok::l_paren)
622 ++ParenCount;
623 else if (ParenCount) {
624 AngleBrackets.clear(P&: *this);
625 --ParenCount; // Don't let unbalanced )'s drive the count negative.
626 }
627 PrevTokLocation = Tok.getLocation();
628 PP.Lex(Result&: Tok);
629 return PrevTokLocation;
630 }
631
632 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
633 ///
634 SourceLocation ConsumeBracket() {
635 assert(isTokenBracket() && "wrong consume method");
636 if (Tok.getKind() == tok::l_square)
637 ++BracketCount;
638 else if (BracketCount) {
639 AngleBrackets.clear(P&: *this);
640 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
641 }
642
643 PrevTokLocation = Tok.getLocation();
644 PP.Lex(Result&: Tok);
645 return PrevTokLocation;
646 }
647
648 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
649 ///
650 SourceLocation ConsumeBrace() {
651 assert(isTokenBrace() && "wrong consume method");
652 if (Tok.getKind() == tok::l_brace)
653 ++BraceCount;
654 else if (BraceCount) {
655 AngleBrackets.clear(P&: *this);
656 --BraceCount; // Don't let unbalanced }'s drive the count negative.
657 }
658
659 PrevTokLocation = Tok.getLocation();
660 PP.Lex(Result&: Tok);
661 return PrevTokLocation;
662 }
663
664 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
665 /// and returning the token kind. This method is specific to strings, as it
666 /// handles string literal concatenation, as per C99 5.1.1.2, translation
667 /// phase #6.
668 SourceLocation ConsumeStringToken() {
669 assert(isTokenStringLiteral() &&
670 "Should only consume string literals with this method");
671 PrevTokLocation = Tok.getLocation();
672 PP.Lex(Result&: Tok);
673 return PrevTokLocation;
674 }
675
676 /// Consume the current code-completion token.
677 ///
678 /// This routine can be called to consume the code-completion token and
679 /// continue processing in special cases where \c cutOffParsing() isn't
680 /// desired, such as token caching or completion with lookahead.
681 SourceLocation ConsumeCodeCompletionToken() {
682 assert(Tok.is(tok::code_completion));
683 PrevTokLocation = Tok.getLocation();
684 PP.Lex(Result&: Tok);
685 return PrevTokLocation;
686 }
687
688 /// When we are consuming a code-completion token without having matched
689 /// specific position in the grammar, provide code-completion results based
690 /// on context.
691 ///
692 /// \returns the source location of the code-completion token.
693 SourceLocation handleUnexpectedCodeCompletionToken();
694
695 /// Abruptly cut off parsing; mainly used when we have reached the
696 /// code-completion point.
697 void cutOffParsing() {
698 if (PP.isCodeCompletionEnabled())
699 PP.setCodeCompletionReached();
700 // Cut off parsing by acting as if we reached the end-of-file.
701 Tok.setKind(tok::eof);
702 }
703
704 /// Determine if we're at the end of the file or at a transition
705 /// between modules.
706 bool isEofOrEom() {
707 tok::TokenKind Kind = Tok.getKind();
708 return Kind == tok::eof || Kind == tok::annot_module_begin ||
709 Kind == tok::annot_module_end || Kind == tok::annot_module_include ||
710 Kind == tok::annot_repl_input_end;
711 }
712
713 static void setTypeAnnotation(Token &Tok, TypeResult T) {
714 assert((T.isInvalid() || T.get()) &&
715 "produced a valid-but-null type annotation?");
716 Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr());
717 }
718
719 static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
720 return static_cast<NamedDecl *>(Tok.getAnnotationValue());
721 }
722
723 static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
724 Tok.setAnnotationValue(ND);
725 }
726
727 static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
728 return static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
729 }
730
731 static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
732 Tok.setAnnotationValue(ND);
733 }
734
735 /// Read an already-translated primary expression out of an annotation
736 /// token.
737 static ExprResult getExprAnnotation(const Token &Tok) {
738 return ExprResult::getFromOpaquePointer(P: Tok.getAnnotationValue());
739 }
740
741 /// Set the primary expression corresponding to the given annotation
742 /// token.
743 static void setExprAnnotation(Token &Tok, ExprResult ER) {
744 Tok.setAnnotationValue(ER.getAsOpaquePointer());
745 }
746
747 /// Attempt to classify the name at the current token position. This may
748 /// form a type, scope or primary expression annotation, or replace the token
749 /// with a typo-corrected keyword. This is only appropriate when the current
750 /// name must refer to an entity which has already been declared.
751 ///
752 /// \param CCC Indicates how to perform typo-correction for this name. If
753 /// NULL, no typo correction will be performed.
754 /// \param AllowImplicitTypename Whether we are in a context where a dependent
755 /// nested-name-specifier without typename is treated as a type (e.g.
756 /// T::type).
757 AnnotatedNameKind
758 TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr,
759 ImplicitTypenameContext AllowImplicitTypename =
760 ImplicitTypenameContext::No);
761
762 /// Push a tok::annot_cxxscope token onto the token stream.
763 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
764
765 /// TryKeywordIdentFallback - For compatibility with system headers using
766 /// keywords as identifiers, attempt to convert the current token to an
767 /// identifier and optionally disable the keyword for the remainder of the
768 /// translation unit. This returns false if the token was not replaced,
769 /// otherwise emits a diagnostic and returns true.
770 bool TryKeywordIdentFallback(bool DisableKeyword);
771
772 /// Get the TemplateIdAnnotation from the token and put it in the
773 /// cleanup pool so that it gets destroyed when parsing the current top level
774 /// declaration is finished.
775 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
776
777 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
778 /// input. If so, it is consumed and false is returned.
779 ///
780 /// If a trivial punctuator misspelling is encountered, a FixIt error
781 /// diagnostic is issued and false is returned after recovery.
782 ///
783 /// If the input is malformed, this emits the specified diagnostic and true is
784 /// returned.
785 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
786 unsigned Diag = diag::err_expected,
787 StringRef DiagMsg = "");
788
789 /// The parser expects a semicolon and, if present, will consume it.
790 ///
791 /// If the next token is not a semicolon, this emits the specified diagnostic,
792 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
793 /// to the semicolon, consumes that extra token.
794 bool ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed = "");
795
796 /// Consume any extra semi-colons until the end of the line.
797 void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
798
799 /// Return false if the next token is an identifier. An 'expected identifier'
800 /// error is emitted otherwise.
801 ///
802 /// The parser tries to recover from the error by checking if the next token
803 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
804 /// was successful.
805 bool expectIdentifier();
806
807 /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
808 enum class CompoundToken {
809 /// A '(' '{' beginning a statement-expression.
810 StmtExprBegin,
811 /// A '}' ')' ending a statement-expression.
812 StmtExprEnd,
813 /// A '[' '[' beginning a C++11 or C23 attribute.
814 AttrBegin,
815 /// A ']' ']' ending a C++11 or C23 attribute.
816 AttrEnd,
817 /// A '::' '*' forming a C++ pointer-to-member declaration.
818 MemberPtr,
819 };
820
821 /// Check that a compound operator was written in a "sensible" way, and warn
822 /// if not.
823 void checkCompoundToken(SourceLocation FirstTokLoc,
824 tok::TokenKind FirstTokKind, CompoundToken Op);
825
826 void diagnoseUseOfC11Keyword(const Token &Tok);
827
828 /// RAII object used to modify the scope flags for the current scope.
829 class ParseScopeFlags {
830 Scope *CurScope;
831 unsigned OldFlags = 0;
832 ParseScopeFlags(const ParseScopeFlags &) = delete;
833 void operator=(const ParseScopeFlags &) = delete;
834
835 public:
836 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is
837 /// false, this object does nothing.
838 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
839
840 /// Restore the flags for the current scope to what they were before this
841 /// object overrode them.
842 ~ParseScopeFlags();
843 };
844
845 /// Emits a diagnostic suggesting parentheses surrounding a
846 /// given range.
847 ///
848 /// \param Loc The location where we'll emit the diagnostic.
849 /// \param DK The kind of diagnostic to emit.
850 /// \param ParenRange Source range enclosing code that should be
851 /// parenthesized.
852 void SuggestParentheses(SourceLocation Loc, unsigned DK,
853 SourceRange ParenRange);
854
855 //===--------------------------------------------------------------------===//
856 // C99 6.9: External Definitions.
857
858 /// ParseExternalDeclaration:
859 ///
860 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
861 /// declaration.
862 ///
863 /// \verbatim
864 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
865 /// function-definition
866 /// declaration
867 /// [GNU] asm-definition
868 /// [GNU] __extension__ external-declaration
869 /// [OBJC] objc-class-definition
870 /// [OBJC] objc-class-declaration
871 /// [OBJC] objc-alias-declaration
872 /// [OBJC] objc-protocol-definition
873 /// [OBJC] objc-method-definition
874 /// [OBJC] @end
875 /// [C++] linkage-specification
876 /// [GNU] asm-definition:
877 /// simple-asm-expr ';'
878 /// [C++11] empty-declaration
879 /// [C++11] attribute-declaration
880 ///
881 /// [C++11] empty-declaration:
882 /// ';'
883 ///
884 /// [C++0x/GNU] 'extern' 'template' declaration
885 ///
886 /// [C++20] module-import-declaration
887 /// \endverbatim
888 ///
889 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributes &DeclAttrs,
890 ParsedAttributes &DeclSpecAttrs,
891 ParsingDeclSpec *DS = nullptr);
892
893 /// Determine whether the current token, if it occurs after a
894 /// declarator, continues a declaration or declaration list.
895 bool isDeclarationAfterDeclarator();
896
897 /// Determine whether the current token, if it occurs after a
898 /// declarator, indicates the start of a function definition.
899 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
900
901 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
902 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
903 ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none);
904
905 /// Parse either a function-definition or a declaration. We can't tell which
906 /// we have until we read up to the compound-statement in function-definition.
907 /// TemplateParams, if non-NULL, provides the template parameters when we're
908 /// parsing a C++ template-declaration.
909 ///
910 /// \verbatim
911 /// function-definition: [C99 6.9.1]
912 /// decl-specs declarator declaration-list[opt] compound-statement
913 /// [C90] function-definition: [C99 6.7.1] - implicit int result
914 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
915 ///
916 /// declaration: [C99 6.7]
917 /// declaration-specifiers init-declarator-list[opt] ';'
918 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
919 /// [OMP] threadprivate-directive
920 /// [OMP] allocate-directive [TODO]
921 /// \endverbatim
922 ///
923 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs,
924 ParsedAttributes &DeclSpecAttrs,
925 ParsingDeclSpec &DS,
926 AccessSpecifier AS);
927
928 void SkipFunctionBody();
929
930 struct ParsedTemplateInfo;
931 class LateParsedAttrList;
932
933 /// ParseFunctionDefinition - We parsed and verified that the specified
934 /// Declarator is well formed. If this is a K&R-style function, read the
935 /// parameters declaration-list, then start the compound-statement.
936 ///
937 /// \verbatim
938 /// function-definition: [C99 6.9.1]
939 /// decl-specs declarator declaration-list[opt] compound-statement
940 /// [C90] function-definition: [C99 6.7.1] - implicit int result
941 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
942 /// [C++] function-definition: [C++ 8.4]
943 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
944 /// function-body
945 /// [C++] function-definition: [C++ 8.4]
946 /// decl-specifier-seq[opt] declarator function-try-block
947 /// \endverbatim
948 ///
949 Decl *ParseFunctionDefinition(
950 ParsingDeclarator &D,
951 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
952 LateParsedAttrList *LateParsedAttrs = nullptr);
953
954 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
955 /// types for a function with a K&R-style identifier list for arguments.
956 void ParseKNRParamDeclarations(Declarator &D);
957
958 /// ParseSimpleAsm
959 ///
960 /// \verbatim
961 /// [GNU] simple-asm-expr:
962 /// 'asm' '(' asm-string-literal ')'
963 /// \endverbatim
964 ///
965 /// EndLoc is filled with the location of the last token of the simple-asm.
966 ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
967
968 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
969 /// allowed to be a wide string, and is not subject to character translation.
970 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
971 /// asm label as opposed to an asm statement, because such a construct does
972 /// not behave well.
973 ///
974 /// \verbatim
975 /// [GNU] asm-string-literal:
976 /// string-literal
977 /// \endverbatim
978 ///
979 ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
980
981 /// Describes the condition of a Microsoft __if_exists or
982 /// __if_not_exists block.
983 struct IfExistsCondition {
984 /// The location of the initial keyword.
985 SourceLocation KeywordLoc;
986 /// Whether this is an __if_exists block (rather than an
987 /// __if_not_exists block).
988 bool IsIfExists;
989
990 /// Nested-name-specifier preceding the name.
991 CXXScopeSpec SS;
992
993 /// The name we're looking for.
994 UnqualifiedId Name;
995
996 /// The behavior of this __if_exists or __if_not_exists block
997 /// should.
998 IfExistsBehavior Behavior;
999 };
1000
1001 bool ParseMicrosoftIfExistsCondition(IfExistsCondition &Result);
1002 void ParseMicrosoftIfExistsExternalDeclaration();
1003
1004 //===--------------------------------------------------------------------===//
1005 // Modules
1006
1007 /// Parse a declaration beginning with the 'module' keyword or C++20
1008 /// context-sensitive keyword (optionally preceded by 'export').
1009 ///
1010 /// \verbatim
1011 /// module-declaration: [C++20]
1012 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
1013 ///
1014 /// global-module-fragment: [C++2a]
1015 /// 'module' ';' top-level-declaration-seq[opt]
1016 /// module-declaration: [C++2a]
1017 /// 'export'[opt] 'module' module-name module-partition[opt]
1018 /// attribute-specifier-seq[opt] ';'
1019 /// private-module-fragment: [C++2a]
1020 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
1021 /// \endverbatim
1022 DeclGroupPtrTy ParseModuleDecl(Sema::ModuleImportState &ImportState);
1023
1024 /// Parse a module import declaration. This is essentially the same for
1025 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
1026 /// trailing optional attributes (in C++).
1027 ///
1028 /// \verbatim
1029 /// [ObjC] @import declaration:
1030 /// '@' 'import' module-name ';'
1031 /// [ModTS] module-import-declaration:
1032 /// 'import' module-name attribute-specifier-seq[opt] ';'
1033 /// [C++20] module-import-declaration:
1034 /// 'export'[opt] 'import' module-name
1035 /// attribute-specifier-seq[opt] ';'
1036 /// 'export'[opt] 'import' module-partition
1037 /// attribute-specifier-seq[opt] ';'
1038 /// 'export'[opt] 'import' header-name
1039 /// attribute-specifier-seq[opt] ';'
1040 /// \endverbatim
1041 Decl *ParseModuleImport(SourceLocation AtLoc,
1042 Sema::ModuleImportState &ImportState);
1043
1044 /// Try recover parser when module annotation appears where it must not
1045 /// be found.
1046 /// \returns false if the recover was successful and parsing may be continued,
1047 /// or true if parser must bail out to top level and handle the token there.
1048 bool parseMisplacedModuleImport();
1049
1050 bool tryParseMisplacedModuleImport() {
1051 tok::TokenKind Kind = Tok.getKind();
1052 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
1053 Kind == tok::annot_module_include)
1054 return parseMisplacedModuleImport();
1055 return false;
1056 }
1057
1058 /// Parse a C++ / Objective-C module name (both forms use the same
1059 /// grammar).
1060 ///
1061 /// \verbatim
1062 /// module-name:
1063 /// module-name-qualifier[opt] identifier
1064 /// module-name-qualifier:
1065 /// module-name-qualifier[opt] identifier '.'
1066 /// \endverbatim
1067 bool ParseModuleName(SourceLocation UseLoc,
1068 SmallVectorImpl<IdentifierLoc> &Path, bool IsImport);
1069
1070 //===--------------------------------------------------------------------===//
1071 // Preprocessor code-completion pass-through
1072 void CodeCompleteDirective(bool InConditional) override;
1073 void CodeCompleteInConditionalExclusion() override;
1074 void CodeCompleteMacroName(bool IsDefinition) override;
1075 void CodeCompletePreprocessorExpression() override;
1076 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
1077 unsigned ArgumentIndex) override;
1078 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
1079 void CodeCompleteNaturalLanguage() override;
1080
1081 ///@}
1082
1083 //
1084 //
1085 // -------------------------------------------------------------------------
1086 //
1087 //
1088
1089 /// \name C++ Class Inline Methods
1090 /// Implementations are in ParseCXXInlineMethods.cpp
1091 ///@{
1092
1093private:
1094 struct ParsingClass;
1095
1096 /// [class.mem]p1: "... the class is regarded as complete within
1097 /// - function bodies
1098 /// - default arguments
1099 /// - exception-specifications (TODO: C++0x)
1100 /// - and brace-or-equal-initializers for non-static data members
1101 /// (including such things in nested classes)."
1102 /// LateParsedDeclarations build the tree of those elements so they can
1103 /// be parsed after parsing the top-level class.
1104 class LateParsedDeclaration {
1105 public:
1106 virtual ~LateParsedDeclaration();
1107
1108 virtual void ParseLexedMethodDeclarations();
1109 virtual void ParseLexedMemberInitializers();
1110 virtual void ParseLexedMethodDefs();
1111 virtual void ParseLexedAttributes();
1112 virtual void ParseLexedPragmas();
1113 };
1114
1115 /// Inner node of the LateParsedDeclaration tree that parses
1116 /// all its members recursively.
1117 class LateParsedClass : public LateParsedDeclaration {
1118 public:
1119 LateParsedClass(Parser *P, ParsingClass *C);
1120 ~LateParsedClass() override;
1121
1122 void ParseLexedMethodDeclarations() override;
1123 void ParseLexedMemberInitializers() override;
1124 void ParseLexedMethodDefs() override;
1125 void ParseLexedAttributes() override;
1126 void ParseLexedPragmas() override;
1127
1128 // Delete copy constructor and copy assignment operator.
1129 LateParsedClass(const LateParsedClass &) = delete;
1130 LateParsedClass &operator=(const LateParsedClass &) = delete;
1131
1132 private:
1133 Parser *Self;
1134 ParsingClass *Class;
1135 };
1136
1137 /// Contains the lexed tokens of an attribute with arguments that
1138 /// may reference member variables and so need to be parsed at the
1139 /// end of the class declaration after parsing all other member
1140 /// member declarations.
1141 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1142 /// LateParsedTokens.
1143 struct LateParsedAttribute : public LateParsedDeclaration {
1144 Parser *Self;
1145 CachedTokens Toks;
1146 IdentifierInfo &AttrName;
1147 IdentifierInfo *MacroII = nullptr;
1148 SourceLocation AttrNameLoc;
1149 SmallVector<Decl *, 2> Decls;
1150
1151 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1152 SourceLocation Loc)
1153 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1154
1155 void ParseLexedAttributes() override;
1156
1157 void addDecl(Decl *D) { Decls.push_back(Elt: D); }
1158 };
1159
1160 /// Contains the lexed tokens of a pragma with arguments that
1161 /// may reference member variables and so need to be parsed at the
1162 /// end of the class declaration after parsing all other member
1163 /// member declarations.
1164 class LateParsedPragma : public LateParsedDeclaration {
1165 Parser *Self = nullptr;
1166 AccessSpecifier AS = AS_none;
1167 CachedTokens Toks;
1168
1169 public:
1170 explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
1171 : Self(P), AS(AS) {}
1172
1173 void takeToks(CachedTokens &Cached) { Toks.swap(RHS&: Cached); }
1174 const CachedTokens &toks() const { return Toks; }
1175 AccessSpecifier getAccessSpecifier() const { return AS; }
1176
1177 void ParseLexedPragmas() override;
1178 };
1179
1180 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1181 class LateParsedAttrList : public SmallVector<LateParsedAttribute *, 2> {
1182 public:
1183 LateParsedAttrList(bool PSoon = false,
1184 bool LateAttrParseExperimentalExtOnly = false)
1185 : ParseSoon(PSoon),
1186 LateAttrParseExperimentalExtOnly(LateAttrParseExperimentalExtOnly) {}
1187
1188 bool parseSoon() { return ParseSoon; }
1189 /// returns true iff the attribute to be parsed should only be late parsed
1190 /// if it is annotated with `LateAttrParseExperimentalExt`
1191 bool lateAttrParseExperimentalExtOnly() {
1192 return LateAttrParseExperimentalExtOnly;
1193 }
1194
1195 private:
1196 bool ParseSoon; // Are we planning to parse these shortly after creation?
1197 bool LateAttrParseExperimentalExtOnly;
1198 };
1199
1200 /// Contains the lexed tokens of a member function definition
1201 /// which needs to be parsed at the end of the class declaration
1202 /// after parsing all other member declarations.
1203 struct LexedMethod : public LateParsedDeclaration {
1204 Parser *Self;
1205 Decl *D;
1206 CachedTokens Toks;
1207
1208 explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
1209
1210 void ParseLexedMethodDefs() override;
1211 };
1212
1213 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1214 /// have a default argument that cannot be parsed yet because it
1215 /// occurs within a member function declaration inside the class
1216 /// (C++ [class.mem]p2).
1217 struct LateParsedDefaultArgument {
1218 explicit LateParsedDefaultArgument(
1219 Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr)
1220 : Param(P), Toks(std::move(Toks)) {}
1221
1222 /// Param - The parameter declaration for this parameter.
1223 Decl *Param;
1224
1225 /// Toks - The sequence of tokens that comprises the default
1226 /// argument expression, not including the '=' or the terminating
1227 /// ')' or ','. This will be NULL for parameters that have no
1228 /// default argument.
1229 std::unique_ptr<CachedTokens> Toks;
1230 };
1231
1232 /// LateParsedMethodDeclaration - A method declaration inside a class that
1233 /// contains at least one entity whose parsing needs to be delayed
1234 /// until the class itself is completely-defined, such as a default
1235 /// argument (C++ [class.mem]p2).
1236 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1237 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1238 : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
1239
1240 void ParseLexedMethodDeclarations() override;
1241
1242 Parser *Self;
1243
1244 /// Method - The method declaration.
1245 Decl *Method;
1246
1247 /// DefaultArgs - Contains the parameters of the function and
1248 /// their default arguments. At least one of the parameters will
1249 /// have a default argument, but all of the parameters of the
1250 /// method will be stored so that they can be reintroduced into
1251 /// scope at the appropriate times.
1252 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1253
1254 /// The set of tokens that make up an exception-specification that
1255 /// has not yet been parsed.
1256 CachedTokens *ExceptionSpecTokens;
1257 };
1258
1259 /// LateParsedMemberInitializer - An initializer for a non-static class data
1260 /// member whose parsing must to be delayed until the class is completely
1261 /// defined (C++11 [class.mem]p2).
1262 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1263 LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) {}
1264
1265 void ParseLexedMemberInitializers() override;
1266
1267 Parser *Self;
1268
1269 /// Field - The field declaration.
1270 Decl *Field;
1271
1272 /// CachedTokens - The sequence of tokens that comprises the initializer,
1273 /// including any leading '='.
1274 CachedTokens Toks;
1275 };
1276
1277 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1278 /// C++ class, its method declarations that contain parts that won't be
1279 /// parsed until after the definition is completed (C++ [class.mem]p2),
1280 /// the method declarations and possibly attached inline definitions
1281 /// will be stored here with the tokens that will be parsed to create those
1282 /// entities.
1283 typedef SmallVector<LateParsedDeclaration *, 2>
1284 LateParsedDeclarationsContainer;
1285
1286 /// Utility to re-enter a possibly-templated scope while parsing its
1287 /// late-parsed components.
1288 struct ReenterTemplateScopeRAII;
1289
1290 /// Utility to re-enter a class scope while parsing its late-parsed
1291 /// components.
1292 struct ReenterClassScopeRAII;
1293
1294 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
1295 /// Declarator is a well formed C++ inline method definition. Now lex its body
1296 /// and store its tokens for parsing after the C++ class is complete.
1297 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1298 const ParsedAttributesView &AccessAttrs,
1299 ParsingDeclarator &D,
1300 const ParsedTemplateInfo &TemplateInfo,
1301 const VirtSpecifiers &VS,
1302 SourceLocation PureSpecLoc);
1303
1304 /// Parse the optional ("message") part of a deleted-function-body.
1305 StringLiteral *ParseCXXDeletedFunctionMessage();
1306
1307 /// If we've encountered '= delete' in a context where it is ill-formed, such
1308 /// as in the declaration of a non-function, also skip the ("message") part if
1309 /// it is present to avoid issuing further diagnostics.
1310 void SkipDeletedFunctionBody();
1311
1312 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
1313 /// specified Declarator is a well formed C++ non-static data member
1314 /// declaration. Now lex its initializer and store its tokens for parsing
1315 /// after the class is complete.
1316 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1317
1318 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1319 /// scope appropriately.
1320 void ParseLexedAttributes(ParsingClass &Class);
1321
1322 /// Parse all attributes in LAs, and attach them to Decl D.
1323 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1324 bool EnterScope, bool OnDefinition);
1325
1326 /// Finish parsing an attribute for which parsing was delayed.
1327 /// This will be called at the end of parsing a class declaration
1328 /// for each LateParsedAttribute. We consume the saved tokens and
1329 /// create an attribute with the arguments filled in. We add this
1330 /// to the Attribute list for the decl.
1331 void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope,
1332 bool OnDefinition);
1333
1334 /// ParseLexedMethodDeclarations - We finished parsing the member
1335 /// specification of a top (non-nested) C++ class. Now go over the
1336 /// stack of method declarations with some parts for which parsing was
1337 /// delayed (such as default arguments) and parse them.
1338 void ParseLexedMethodDeclarations(ParsingClass &Class);
1339 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1340
1341 /// ParseLexedMethodDefs - We finished parsing the member specification of a
1342 /// top (non-nested) C++ class. Now go over the stack of lexed methods that
1343 /// were collected during its parsing and parse them all.
1344 void ParseLexedMethodDefs(ParsingClass &Class);
1345 void ParseLexedMethodDef(LexedMethod &LM);
1346
1347 /// ParseLexedMemberInitializers - We finished parsing the member
1348 /// specification of a top (non-nested) C++ class. Now go over the stack of
1349 /// lexed data member initializers that were collected during its parsing and
1350 /// parse them all.
1351 void ParseLexedMemberInitializers(ParsingClass &Class);
1352 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1353
1354 ///@}
1355
1356 //
1357 //
1358 // -------------------------------------------------------------------------
1359 //
1360 //
1361
1362 /// \name Declarations
1363 /// Implementations are in ParseDecl.cpp
1364 ///@{
1365
1366public:
1367 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1368 /// point for skipping past a simple-declaration.
1369 ///
1370 /// Skip until we reach something which seems like a sensible place to pick
1371 /// up parsing after a malformed declaration. This will sometimes stop sooner
1372 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1373 void SkipMalformedDecl();
1374
1375 /// ParseTypeName
1376 /// \verbatim
1377 /// type-name: [C99 6.7.6]
1378 /// specifier-qualifier-list abstract-declarator[opt]
1379 /// \endverbatim
1380 ///
1381 /// Called type-id in C++.
1382 TypeResult
1383 ParseTypeName(SourceRange *Range = nullptr,
1384 DeclaratorContext Context = DeclaratorContext::TypeName,
1385 AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
1386 ParsedAttributes *Attrs = nullptr);
1387
1388private:
1389 /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
1390 /// and "bool" fast comparison. Only present if AltiVec or ZVector are
1391 /// enabled.
1392 IdentifierInfo *Ident_vector;
1393 IdentifierInfo *Ident_bool;
1394 IdentifierInfo *Ident_Bool;
1395
1396 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
1397 /// Only present if AltiVec enabled.
1398 IdentifierInfo *Ident_pixel;
1399
1400 /// Identifier for "introduced".
1401 IdentifierInfo *Ident_introduced;
1402
1403 /// Identifier for "deprecated".
1404 IdentifierInfo *Ident_deprecated;
1405
1406 /// Identifier for "obsoleted".
1407 IdentifierInfo *Ident_obsoleted;
1408
1409 /// Identifier for "unavailable".
1410 IdentifierInfo *Ident_unavailable;
1411
1412 /// Identifier for "message".
1413 IdentifierInfo *Ident_message;
1414
1415 /// Identifier for "strict".
1416 IdentifierInfo *Ident_strict;
1417
1418 /// Identifier for "replacement".
1419 IdentifierInfo *Ident_replacement;
1420
1421 /// Identifier for "environment".
1422 IdentifierInfo *Ident_environment;
1423
1424 /// Identifiers used by the 'external_source_symbol' attribute.
1425 IdentifierInfo *Ident_language, *Ident_defined_in,
1426 *Ident_generated_declaration, *Ident_USR;
1427
1428 /// Factory object for creating ParsedAttr objects.
1429 AttributeFactory AttrFactory;
1430
1431 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
1432 /// replacing them with the non-context-sensitive keywords. This returns
1433 /// true if the token was replaced.
1434 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec,
1435 unsigned &DiagID, bool &isInvalid) {
1436 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
1437 return false;
1438
1439 if (Tok.getIdentifierInfo() != Ident_vector &&
1440 Tok.getIdentifierInfo() != Ident_bool &&
1441 Tok.getIdentifierInfo() != Ident_Bool &&
1442 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
1443 return false;
1444
1445 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
1446 }
1447
1448 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
1449 /// identifier token, replacing it with the non-context-sensitive __vector.
1450 /// This returns true if the token was replaced.
1451 bool TryAltiVecVectorToken() {
1452 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
1453 Tok.getIdentifierInfo() != Ident_vector)
1454 return false;
1455 return TryAltiVecVectorTokenOutOfLine();
1456 }
1457
1458 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be
1459 /// called from TryAltiVecVectorToken.
1460 bool TryAltiVecVectorTokenOutOfLine();
1461 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
1462 const char *&PrevSpec, unsigned &DiagID,
1463 bool &isInvalid);
1464
1465 void ParseLexedCAttributeList(LateParsedAttrList &LA, bool EnterScope,
1466 ParsedAttributes *OutAttrs = nullptr);
1467
1468 /// Finish parsing an attribute for which parsing was delayed.
1469 /// This will be called at the end of parsing a class declaration
1470 /// for each LateParsedAttribute. We consume the saved tokens and
1471 /// create an attribute with the arguments filled in. We add this
1472 /// to the Attribute list for the decl.
1473 void ParseLexedCAttribute(LateParsedAttribute &LA, bool EnterScope,
1474 ParsedAttributes *OutAttrs = nullptr);
1475
1476 void ParseLexedPragmas(ParsingClass &Class);
1477 void ParseLexedPragma(LateParsedPragma &LP);
1478
1479 /// Consume tokens and store them in the passed token container until
1480 /// we've passed the try keyword and constructor initializers and have
1481 /// consumed the opening brace of the function body. The opening brace will be
1482 /// consumed if and only if there was no error.
1483 ///
1484 /// \return True on error.
1485 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1486
1487 /// ConsumeAndStoreInitializer - Consume and store the token at the passed
1488 /// token container until the end of the current initializer expression
1489 /// (either a default argument or an in-class initializer for a non-static
1490 /// data member).
1491 ///
1492 /// Returns \c true if we reached the end of something initializer-shaped,
1493 /// \c false if we bailed out.
1494 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1495
1496 /// Consume and store tokens from the '?' to the ':' in a conditional
1497 /// expression.
1498 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1499 bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks,
1500 bool StopAtSemi = true,
1501 bool ConsumeFinalToken = true) {
1502 return ConsumeAndStoreUntil(T1, T2: T1, Toks, StopAtSemi, ConsumeFinalToken);
1503 }
1504
1505 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
1506 /// container until the token 'T' is reached (which gets
1507 /// consumed/stored too, if ConsumeFinalToken).
1508 /// If StopAtSemi is true, then we will stop early at a ';' character.
1509 /// Returns true if token 'T1' or 'T2' was found.
1510 /// NOTE: This is a specialized version of Parser::SkipUntil.
1511 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1512 CachedTokens &Toks, bool StopAtSemi = true,
1513 bool ConsumeFinalToken = true);
1514
1515 //===--------------------------------------------------------------------===//
1516 // C99 6.7: Declarations.
1517
1518 /// A context for parsing declaration specifiers. TODO: flesh this
1519 /// out, there are other significant restrictions on specifiers than
1520 /// would be best implemented in the parser.
1521 enum class DeclSpecContext {
1522 DSC_normal, // normal context
1523 DSC_class, // class context, enables 'friend'
1524 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1525 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1526 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1527 DSC_conv_operator, // C++ type-specifier-seq in an conversion operator
1528 DSC_top_level, // top-level/namespace declaration context
1529 DSC_template_param, // template parameter context
1530 DSC_template_arg, // template argument context
1531 DSC_template_type_arg, // template type argument context
1532 DSC_objc_method_result, // ObjC method result context, enables
1533 // 'instancetype'
1534 DSC_condition, // condition declaration context
1535 DSC_association, // A _Generic selection expression's type association
1536 DSC_new, // C++ new expression
1537 };
1538
1539 /// Is this a context in which we are parsing just a type-specifier (or
1540 /// trailing-type-specifier)?
1541 static bool isTypeSpecifier(DeclSpecContext DSC) {
1542 switch (DSC) {
1543 case DeclSpecContext::DSC_normal:
1544 case DeclSpecContext::DSC_template_param:
1545 case DeclSpecContext::DSC_template_arg:
1546 case DeclSpecContext::DSC_class:
1547 case DeclSpecContext::DSC_top_level:
1548 case DeclSpecContext::DSC_objc_method_result:
1549 case DeclSpecContext::DSC_condition:
1550 return false;
1551
1552 case DeclSpecContext::DSC_template_type_arg:
1553 case DeclSpecContext::DSC_type_specifier:
1554 case DeclSpecContext::DSC_conv_operator:
1555 case DeclSpecContext::DSC_trailing:
1556 case DeclSpecContext::DSC_alias_declaration:
1557 case DeclSpecContext::DSC_association:
1558 case DeclSpecContext::DSC_new:
1559 return true;
1560 }
1561 llvm_unreachable("Missing DeclSpecContext case");
1562 }
1563
1564 /// Whether a defining-type-specifier is permitted in a given context.
1565 enum class AllowDefiningTypeSpec {
1566 /// The grammar doesn't allow a defining-type-specifier here, and we must
1567 /// not parse one (eg, because a '{' could mean something else).
1568 No,
1569 /// The grammar doesn't allow a defining-type-specifier here, but we permit
1570 /// one for error recovery purposes. Sema will reject.
1571 NoButErrorRecovery,
1572 /// The grammar allows a defining-type-specifier here, even though it's
1573 /// always invalid. Sema will reject.
1574 YesButInvalid,
1575 /// The grammar allows a defining-type-specifier here, and one can be valid.
1576 Yes
1577 };
1578
1579 /// Is this a context in which we are parsing defining-type-specifiers (and
1580 /// so permit class and enum definitions in addition to non-defining class and
1581 /// enum elaborated-type-specifiers)?
1582 static AllowDefiningTypeSpec
1583 isDefiningTypeSpecifierContext(DeclSpecContext DSC, bool IsCPlusPlus) {
1584 switch (DSC) {
1585 case DeclSpecContext::DSC_normal:
1586 case DeclSpecContext::DSC_class:
1587 case DeclSpecContext::DSC_top_level:
1588 case DeclSpecContext::DSC_alias_declaration:
1589 case DeclSpecContext::DSC_objc_method_result:
1590 return AllowDefiningTypeSpec::Yes;
1591
1592 case DeclSpecContext::DSC_condition:
1593 case DeclSpecContext::DSC_template_param:
1594 return AllowDefiningTypeSpec::YesButInvalid;
1595
1596 case DeclSpecContext::DSC_template_type_arg:
1597 case DeclSpecContext::DSC_type_specifier:
1598 return AllowDefiningTypeSpec::NoButErrorRecovery;
1599
1600 case DeclSpecContext::DSC_association:
1601 return IsCPlusPlus ? AllowDefiningTypeSpec::NoButErrorRecovery
1602 : AllowDefiningTypeSpec::Yes;
1603
1604 case DeclSpecContext::DSC_trailing:
1605 case DeclSpecContext::DSC_conv_operator:
1606 case DeclSpecContext::DSC_template_arg:
1607 case DeclSpecContext::DSC_new:
1608 return AllowDefiningTypeSpec::No;
1609 }
1610 llvm_unreachable("Missing DeclSpecContext case");
1611 }
1612
1613 /// Is this a context in which an opaque-enum-declaration can appear?
1614 static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
1615 switch (DSC) {
1616 case DeclSpecContext::DSC_normal:
1617 case DeclSpecContext::DSC_class:
1618 case DeclSpecContext::DSC_top_level:
1619 return true;
1620
1621 case DeclSpecContext::DSC_alias_declaration:
1622 case DeclSpecContext::DSC_objc_method_result:
1623 case DeclSpecContext::DSC_condition:
1624 case DeclSpecContext::DSC_template_param:
1625 case DeclSpecContext::DSC_template_type_arg:
1626 case DeclSpecContext::DSC_type_specifier:
1627 case DeclSpecContext::DSC_trailing:
1628 case DeclSpecContext::DSC_association:
1629 case DeclSpecContext::DSC_conv_operator:
1630 case DeclSpecContext::DSC_template_arg:
1631 case DeclSpecContext::DSC_new:
1632
1633 return false;
1634 }
1635 llvm_unreachable("Missing DeclSpecContext case");
1636 }
1637
1638 /// Is this a context in which we can perform class template argument
1639 /// deduction?
1640 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
1641 switch (DSC) {
1642 case DeclSpecContext::DSC_normal:
1643 case DeclSpecContext::DSC_template_param:
1644 case DeclSpecContext::DSC_template_arg:
1645 case DeclSpecContext::DSC_class:
1646 case DeclSpecContext::DSC_top_level:
1647 case DeclSpecContext::DSC_condition:
1648 case DeclSpecContext::DSC_type_specifier:
1649 case DeclSpecContext::DSC_association:
1650 case DeclSpecContext::DSC_conv_operator:
1651 case DeclSpecContext::DSC_new:
1652 return true;
1653
1654 case DeclSpecContext::DSC_objc_method_result:
1655 case DeclSpecContext::DSC_template_type_arg:
1656 case DeclSpecContext::DSC_trailing:
1657 case DeclSpecContext::DSC_alias_declaration:
1658 return false;
1659 }
1660 llvm_unreachable("Missing DeclSpecContext case");
1661 }
1662
1663 // Is this a context in which an implicit 'typename' is allowed?
1664 static ImplicitTypenameContext
1665 getImplicitTypenameContext(DeclSpecContext DSC) {
1666 switch (DSC) {
1667 case DeclSpecContext::DSC_class:
1668 case DeclSpecContext::DSC_top_level:
1669 case DeclSpecContext::DSC_type_specifier:
1670 case DeclSpecContext::DSC_template_type_arg:
1671 case DeclSpecContext::DSC_trailing:
1672 case DeclSpecContext::DSC_alias_declaration:
1673 case DeclSpecContext::DSC_template_param:
1674 case DeclSpecContext::DSC_new:
1675 return ImplicitTypenameContext::Yes;
1676
1677 case DeclSpecContext::DSC_normal:
1678 case DeclSpecContext::DSC_objc_method_result:
1679 case DeclSpecContext::DSC_condition:
1680 case DeclSpecContext::DSC_template_arg:
1681 case DeclSpecContext::DSC_conv_operator:
1682 case DeclSpecContext::DSC_association:
1683 return ImplicitTypenameContext::No;
1684 }
1685 llvm_unreachable("Missing DeclSpecContext case");
1686 }
1687
1688 /// Information on a C++0x for-range-initializer found while parsing a
1689 /// declaration which turns out to be a for-range-declaration.
1690 struct ForRangeInit {
1691 SourceLocation ColonLoc;
1692 ExprResult RangeExpr;
1693 SmallVector<MaterializeTemporaryExpr *, 8> LifetimeExtendTemps;
1694 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1695 };
1696 struct ForRangeInfo : ForRangeInit {
1697 StmtResult LoopVar;
1698 };
1699
1700 /// ParseDeclaration - Parse a full 'declaration', which consists of
1701 /// declaration-specifiers, some number of declarators, and a semicolon.
1702 /// 'Context' should be a DeclaratorContext value. This returns the
1703 /// location of the semicolon in DeclEnd.
1704 ///
1705 /// \verbatim
1706 /// declaration: [C99 6.7]
1707 /// block-declaration ->
1708 /// simple-declaration
1709 /// others [FIXME]
1710 /// [C++] template-declaration
1711 /// [C++] namespace-definition
1712 /// [C++] using-directive
1713 /// [C++] using-declaration
1714 /// [C++11/C11] static_assert-declaration
1715 /// others... [FIXME]
1716 /// \endverbatim
1717 ///
1718 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
1719 SourceLocation &DeclEnd,
1720 ParsedAttributes &DeclAttrs,
1721 ParsedAttributes &DeclSpecAttrs,
1722 SourceLocation *DeclSpecStart = nullptr);
1723
1724 /// \verbatim
1725 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1726 /// declaration-specifiers init-declarator-list[opt] ';'
1727 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1728 /// init-declarator-list ';'
1729 ///[C90/C++]init-declarator-list ';' [TODO]
1730 /// [OMP] threadprivate-directive
1731 /// [OMP] allocate-directive [TODO]
1732 ///
1733 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1734 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1735 /// \endverbatim
1736 ///
1737 /// If RequireSemi is false, this does not check for a ';' at the end of the
1738 /// declaration. If it is true, it checks for and eats it.
1739 ///
1740 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1741 /// of a simple-declaration. If we find that we are, we also parse the
1742 /// for-range-initializer, and place it here.
1743 ///
1744 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1745 /// the Declaration. The SourceLocation for this Decl is set to
1746 /// DeclSpecStart if DeclSpecStart is non-null.
1747 DeclGroupPtrTy
1748 ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1749 ParsedAttributes &DeclAttrs,
1750 ParsedAttributes &DeclSpecAttrs, bool RequireSemi,
1751 ForRangeInit *FRI = nullptr,
1752 SourceLocation *DeclSpecStart = nullptr);
1753
1754 /// ParseDeclGroup - Having concluded that this is either a function
1755 /// definition or a group of object declarations, actually parse the
1756 /// result.
1757 ///
1758 /// Returns true if this might be the start of a declarator, or a common typo
1759 /// for a declarator.
1760 bool MightBeDeclarator(DeclaratorContext Context);
1761 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
1762 ParsedAttributes &Attrs,
1763 ParsedTemplateInfo &TemplateInfo,
1764 SourceLocation *DeclEnd = nullptr,
1765 ForRangeInit *FRI = nullptr);
1766
1767 /// Parse 'declaration' after parsing 'declaration-specifiers
1768 /// declarator'. This method parses the remainder of the declaration
1769 /// (including any attributes or initializer, among other things) and
1770 /// finalizes the declaration.
1771 ///
1772 /// \verbatim
1773 /// init-declarator: [C99 6.7]
1774 /// declarator
1775 /// declarator '=' initializer
1776 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1777 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1778 /// [C++] declarator initializer[opt]
1779 ///
1780 /// [C++] initializer:
1781 /// [C++] '=' initializer-clause
1782 /// [C++] '(' expression-list ')'
1783 /// [C++0x] '=' 'default' [TODO]
1784 /// [C++0x] '=' 'delete'
1785 /// [C++0x] braced-init-list
1786 /// \endverbatim
1787 ///
1788 /// According to the standard grammar, =default and =delete are function
1789 /// definitions, but that definitely doesn't fit with the parser here.
1790 ///
1791 Decl *ParseDeclarationAfterDeclarator(
1792 Declarator &D,
1793 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1794
1795 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1796 /// declarator. Returns true on an error.
1797 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1798 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1799 Declarator &D,
1800 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1801 ForRangeInit *FRI = nullptr);
1802
1803 /// ParseImplicitInt - This method is called when we have an non-typename
1804 /// identifier in a declspec (which normally terminates the decl spec) when
1805 /// the declspec has no type specifier. In this case, the declspec is either
1806 /// malformed or is "implicit int" (in K&R and C89).
1807 ///
1808 /// This method handles diagnosing this prettily and returns false if the
1809 /// declspec is done being processed. If it recovers and thinks there may be
1810 /// other pieces of declspec after it, it returns true.
1811 ///
1812 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1813 ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
1814 DeclSpecContext DSC, ParsedAttributes &Attrs);
1815
1816 /// Determine the declaration specifier context from the declarator
1817 /// context.
1818 ///
1819 /// \param Context the declarator context, which is one of the
1820 /// DeclaratorContext enumerator values.
1821 DeclSpecContext
1822 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
1823 void
1824 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
1825 AccessSpecifier AS = AS_none,
1826 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
1827 LateParsedAttrList *LateAttrs = nullptr) {
1828 return ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs,
1829 AllowImplicitTypename: getImplicitTypenameContext(DSC));
1830 }
1831
1832 /// ParseDeclarationSpecifiers
1833 /// \verbatim
1834 /// declaration-specifiers: [C99 6.7]
1835 /// storage-class-specifier declaration-specifiers[opt]
1836 /// type-specifier declaration-specifiers[opt]
1837 /// [C99] function-specifier declaration-specifiers[opt]
1838 /// [C11] alignment-specifier declaration-specifiers[opt]
1839 /// [GNU] attributes declaration-specifiers[opt]
1840 /// [Clang] '__module_private__' declaration-specifiers[opt]
1841 /// [ObjC1] '__kindof' declaration-specifiers[opt]
1842 ///
1843 /// storage-class-specifier: [C99 6.7.1]
1844 /// 'typedef'
1845 /// 'extern'
1846 /// 'static'
1847 /// 'auto'
1848 /// 'register'
1849 /// [C++] 'mutable'
1850 /// [C++11] 'thread_local'
1851 /// [C11] '_Thread_local'
1852 /// [GNU] '__thread'
1853 /// function-specifier: [C99 6.7.4]
1854 /// [C99] 'inline'
1855 /// [C++] 'virtual'
1856 /// [C++] 'explicit'
1857 /// [OpenCL] '__kernel'
1858 /// 'friend': [C++ dcl.friend]
1859 /// 'constexpr': [C++0x dcl.constexpr]
1860 /// \endverbatim
1861 void
1862 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
1863 AccessSpecifier AS, DeclSpecContext DSC,
1864 LateParsedAttrList *LateAttrs,
1865 ImplicitTypenameContext AllowImplicitTypename);
1866
1867 /// Determine whether we're looking at something that might be a declarator
1868 /// in a simple-declaration. If it can't possibly be a declarator, maybe
1869 /// diagnose a missing semicolon after a prior tag definition in the decl
1870 /// specifier.
1871 ///
1872 /// \return \c true if an error occurred and this can't be any kind of
1873 /// declaration.
1874 bool DiagnoseMissingSemiAfterTagDefinition(
1875 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
1876 LateParsedAttrList *LateAttrs = nullptr);
1877
1878 void ParseSpecifierQualifierList(
1879 DeclSpec &DS, AccessSpecifier AS = AS_none,
1880 DeclSpecContext DSC = DeclSpecContext::DSC_normal) {
1881 ParseSpecifierQualifierList(DS, AllowImplicitTypename: getImplicitTypenameContext(DSC), AS, DSC);
1882 }
1883
1884 /// ParseSpecifierQualifierList
1885 /// \verbatim
1886 /// specifier-qualifier-list:
1887 /// type-specifier specifier-qualifier-list[opt]
1888 /// type-qualifier specifier-qualifier-list[opt]
1889 /// [GNU] attributes specifier-qualifier-list[opt]
1890 /// \endverbatim
1891 ///
1892 void ParseSpecifierQualifierList(
1893 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
1894 AccessSpecifier AS = AS_none,
1895 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
1896
1897 /// ParseEnumSpecifier
1898 /// \verbatim
1899 /// enum-specifier: [C99 6.7.2.2]
1900 /// 'enum' identifier[opt] '{' enumerator-list '}'
1901 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1902 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1903 /// '}' attributes[opt]
1904 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
1905 /// '}'
1906 /// 'enum' identifier
1907 /// [GNU] 'enum' attributes[opt] identifier
1908 ///
1909 /// [C++11] enum-head '{' enumerator-list[opt] '}'
1910 /// [C++11] enum-head '{' enumerator-list ',' '}'
1911 ///
1912 /// enum-head: [C++11]
1913 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
1914 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
1915 /// identifier enum-base[opt]
1916 ///
1917 /// enum-key: [C++11]
1918 /// 'enum'
1919 /// 'enum' 'class'
1920 /// 'enum' 'struct'
1921 ///
1922 /// enum-base: [C++11]
1923 /// ':' type-specifier-seq
1924 ///
1925 /// [C++] elaborated-type-specifier:
1926 /// [C++] 'enum' nested-name-specifier[opt] identifier
1927 /// \endverbatim
1928 ///
1929 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1930 const ParsedTemplateInfo &TemplateInfo,
1931 AccessSpecifier AS, DeclSpecContext DSC);
1932
1933 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
1934 /// \verbatim
1935 /// enumerator-list:
1936 /// enumerator
1937 /// enumerator-list ',' enumerator
1938 /// enumerator:
1939 /// enumeration-constant attributes[opt]
1940 /// enumeration-constant attributes[opt] '=' constant-expression
1941 /// enumeration-constant:
1942 /// identifier
1943 /// \endverbatim
1944 ///
1945 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl,
1946 SkipBodyInfo *SkipBody = nullptr);
1947
1948 /// ParseStructUnionBody
1949 /// \verbatim
1950 /// struct-contents:
1951 /// struct-declaration-list
1952 /// [EXT] empty
1953 /// [GNU] "struct-declaration-list" without terminating ';'
1954 /// struct-declaration-list:
1955 /// struct-declaration
1956 /// struct-declaration-list struct-declaration
1957 /// [OBC] '@' 'defs' '(' class-name ')'
1958 /// \endverbatim
1959 ///
1960 void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
1961 RecordDecl *TagDecl);
1962
1963 /// ParseStructDeclaration - Parse a struct declaration without the
1964 /// terminating semicolon.
1965 ///
1966 /// Note that a struct declaration refers to a declaration in a struct,
1967 /// not to the declaration of a struct.
1968 ///
1969 /// \verbatim
1970 /// struct-declaration:
1971 /// [C23] attributes-specifier-seq[opt]
1972 /// specifier-qualifier-list struct-declarator-list
1973 /// [GNU] __extension__ struct-declaration
1974 /// [GNU] specifier-qualifier-list
1975 /// struct-declarator-list:
1976 /// struct-declarator
1977 /// struct-declarator-list ',' struct-declarator
1978 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
1979 /// struct-declarator:
1980 /// declarator
1981 /// [GNU] declarator attributes[opt]
1982 /// declarator[opt] ':' constant-expression
1983 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
1984 /// \endverbatim
1985 ///
1986 void ParseStructDeclaration(
1987 ParsingDeclSpec &DS,
1988 llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
1989 LateParsedAttrList *LateFieldAttrs = nullptr);
1990
1991 DeclGroupPtrTy ParseTopLevelStmtDecl();
1992
1993 /// isDeclarationSpecifier() - Return true if the current token is part of a
1994 /// declaration specifier.
1995 ///
1996 /// \param AllowImplicitTypename whether this is a context where T::type [T
1997 /// dependent] can appear.
1998 /// \param DisambiguatingWithExpression True to indicate that the purpose of
1999 /// this check is to disambiguate between an expression and a declaration.
2000 bool isDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2001 bool DisambiguatingWithExpression = false);
2002
2003 /// isTypeSpecifierQualifier - Return true if the current token could be the
2004 /// start of a specifier-qualifier-list.
2005 bool isTypeSpecifierQualifier();
2006
2007 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2008 /// is definitely a type-specifier. Return false if it isn't part of a type
2009 /// specifier or if we're not sure.
2010 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2011
2012 /// Starting with a scope specifier, identifier, or
2013 /// template-id that refers to the current class, determine whether
2014 /// this is a constructor declarator.
2015 bool isConstructorDeclarator(
2016 bool Unqualified, bool DeductionGuide = false,
2017 DeclSpec::FriendSpecified IsFriend = DeclSpec::FriendSpecified::No,
2018 const ParsedTemplateInfo *TemplateInfo = nullptr);
2019
2020 /// Diagnoses use of _ExtInt as being deprecated, and diagnoses use of
2021 /// _BitInt as an extension when appropriate.
2022 void DiagnoseBitIntUse(const Token &Tok);
2023
2024 // Check for the start of an attribute-specifier-seq in a context where an
2025 // attribute is not allowed.
2026 bool CheckProhibitedCXX11Attribute() {
2027 assert(Tok.is(tok::l_square));
2028 if (NextToken().isNot(K: tok::l_square))
2029 return false;
2030 return DiagnoseProhibitedCXX11Attribute();
2031 }
2032
2033 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square
2034 /// brackets of a C++11 attribute-specifier in a location where an attribute
2035 /// is not permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed.
2036 /// Diagnose this situation.
2037 ///
2038 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false
2039 /// if this doesn't appear to actually be an attribute-specifier, and the
2040 /// caller should try to parse it.
2041 bool DiagnoseProhibitedCXX11Attribute();
2042
2043 void CheckMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2044 SourceLocation CorrectLocation) {
2045 if (!Tok.isRegularKeywordAttribute() &&
2046 (Tok.isNot(K: tok::l_square) || NextToken().isNot(K: tok::l_square)) &&
2047 Tok.isNot(K: tok::kw_alignas))
2048 return;
2049 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2050 }
2051
2052 /// We have found the opening square brackets of a C++11
2053 /// attribute-specifier in a location where an attribute is not permitted, but
2054 /// we know where the attributes ought to be written. Parse them anyway, and
2055 /// provide a fixit moving them to the right place.
2056 void DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2057 SourceLocation CorrectLocation);
2058
2059 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
2060 // applies to var, not the type Foo.
2061 // As an exception to the rule, __declspec(align(...)) before the
2062 // class-key affects the type instead of the variable.
2063 // Also, Microsoft-style [attributes] seem to affect the type instead of the
2064 // variable.
2065 // This function moves attributes that should apply to the type off DS to
2066 // Attrs.
2067 void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS,
2068 TagUseKind TUK);
2069
2070 // FixItLoc = possible correct location for the attributes
2071 void ProhibitAttributes(ParsedAttributes &Attrs,
2072 SourceLocation FixItLoc = SourceLocation()) {
2073 if (Attrs.Range.isInvalid())
2074 return;
2075 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2076 Attrs.clear();
2077 }
2078
2079 void ProhibitAttributes(ParsedAttributesView &Attrs,
2080 SourceLocation FixItLoc = SourceLocation()) {
2081 if (Attrs.Range.isInvalid())
2082 return;
2083 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2084 Attrs.clearListOnly();
2085 }
2086 void DiagnoseProhibitedAttributes(const ParsedAttributesView &Attrs,
2087 SourceLocation FixItLoc);
2088
2089 // Forbid C++11 and C23 attributes that appear on certain syntactic locations
2090 // which standard permits but we don't supported yet, for example, attributes
2091 // appertain to decl specifiers.
2092 // For the most cases we don't want to warn on unknown type attributes, but
2093 // left them to later diagnoses. However, for a few cases like module
2094 // declarations and module import declarations, we should do it.
2095 void ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned AttrDiagID,
2096 unsigned KeywordDiagId,
2097 bool DiagnoseEmptyAttrs = false,
2098 bool WarnOnUnknownAttrs = false);
2099
2100 /// Emit warnings for C++11 and C23 attributes that are in a position that
2101 /// clang accepts as an extension.
2102 void DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs);
2103
2104 ExprResult ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName);
2105
2106 bool
2107 ParseAttributeArgumentList(const clang::IdentifierInfo &AttrName,
2108 SmallVectorImpl<Expr *> &Exprs,
2109 ParsedAttributeArgumentsProperties ArgsProperties);
2110
2111 /// Parses syntax-generic attribute arguments for attributes which are
2112 /// known to the implementation, and adds them to the given ParsedAttributes
2113 /// list with the given attribute syntax. Returns the number of arguments
2114 /// parsed for the attribute.
2115 unsigned
2116 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2117 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2118 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2119 ParsedAttr::Form Form);
2120
2121 enum ParseAttrKindMask {
2122 PAKM_GNU = 1 << 0,
2123 PAKM_Declspec = 1 << 1,
2124 PAKM_CXX11 = 1 << 2,
2125 };
2126
2127 /// \brief Parse attributes based on what syntaxes are desired, allowing for
2128 /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2129 /// __attribute__((...)) __declspec(...) __attribute__((...)))
2130 /// Note that Microsoft attributes (spelled with single square brackets) are
2131 /// not supported by this because of parsing ambiguities with other
2132 /// constructs.
2133 ///
2134 /// There are some attribute parse orderings that should not be allowed in
2135 /// arbitrary order. e.g.,
2136 ///
2137 /// \verbatim
2138 /// [[]] __attribute__(()) int i; // OK
2139 /// __attribute__(()) [[]] int i; // Not OK
2140 /// \endverbatim
2141 ///
2142 /// Such situations should use the specific attribute parsing functionality.
2143 void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2144 LateParsedAttrList *LateAttrs = nullptr);
2145 /// \brief Possibly parse attributes based on what syntaxes are desired,
2146 /// allowing for the order to vary.
2147 bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2148 LateParsedAttrList *LateAttrs = nullptr) {
2149 if (Tok.isOneOf(K1: tok::kw___attribute, K2: tok::kw___declspec) ||
2150 isAllowedCXX11AttributeSpecifier()) {
2151 ParseAttributes(WhichAttrKinds, Attrs, LateAttrs);
2152 return true;
2153 }
2154 return false;
2155 }
2156
2157 void MaybeParseGNUAttributes(Declarator &D,
2158 LateParsedAttrList *LateAttrs = nullptr) {
2159 if (Tok.is(K: tok::kw___attribute)) {
2160 ParsedAttributes Attrs(AttrFactory);
2161 ParseGNUAttributes(Attrs, LateAttrs, D: &D);
2162 D.takeAttributes(attrs&: Attrs);
2163 }
2164 }
2165
2166 bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2167 LateParsedAttrList *LateAttrs = nullptr) {
2168 if (Tok.is(K: tok::kw___attribute)) {
2169 ParseGNUAttributes(Attrs, LateAttrs);
2170 return true;
2171 }
2172 return false;
2173 }
2174
2175 /// ParseSingleGNUAttribute - Parse a single GNU attribute.
2176 ///
2177 /// \verbatim
2178 /// [GNU] attrib:
2179 /// empty
2180 /// attrib-name
2181 /// attrib-name '(' identifier ')'
2182 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
2183 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
2184 ///
2185 /// [GNU] attrib-name:
2186 /// identifier
2187 /// typespec
2188 /// typequal
2189 /// storageclass
2190 /// \endverbatim
2191 bool ParseSingleGNUAttribute(ParsedAttributes &Attrs, SourceLocation &EndLoc,
2192 LateParsedAttrList *LateAttrs = nullptr,
2193 Declarator *D = nullptr);
2194
2195 /// ParseGNUAttributes - Parse a non-empty attributes list.
2196 ///
2197 /// \verbatim
2198 /// [GNU] attributes:
2199 /// attribute
2200 /// attributes attribute
2201 ///
2202 /// [GNU] attribute:
2203 /// '__attribute__' '(' '(' attribute-list ')' ')'
2204 ///
2205 /// [GNU] attribute-list:
2206 /// attrib
2207 /// attribute_list ',' attrib
2208 ///
2209 /// [GNU] attrib:
2210 /// empty
2211 /// attrib-name
2212 /// attrib-name '(' identifier ')'
2213 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
2214 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
2215 ///
2216 /// [GNU] attrib-name:
2217 /// identifier
2218 /// typespec
2219 /// typequal
2220 /// storageclass
2221 /// \endverbatim
2222 ///
2223 /// Whether an attribute takes an 'identifier' is determined by the
2224 /// attrib-name. GCC's behavior here is not worth imitating:
2225 ///
2226 /// * In C mode, if the attribute argument list starts with an identifier
2227 /// followed by a ',' or an ')', and the identifier doesn't resolve to
2228 /// a type, it is parsed as an identifier. If the attribute actually
2229 /// wanted an expression, it's out of luck (but it turns out that no
2230 /// attributes work that way, because C constant expressions are very
2231 /// limited).
2232 /// * In C++ mode, if the attribute argument list starts with an identifier,
2233 /// and the attribute *wants* an identifier, it is parsed as an identifier.
2234 /// At block scope, any additional tokens between the identifier and the
2235 /// ',' or ')' are ignored, otherwise they produce a parse error.
2236 ///
2237 /// We follow the C++ model, but don't allow junk after the identifier.
2238 void ParseGNUAttributes(ParsedAttributes &Attrs,
2239 LateParsedAttrList *LateAttrs = nullptr,
2240 Declarator *D = nullptr);
2241
2242 /// Parse the arguments to a parameterized GNU attribute or
2243 /// a C++11 attribute in "gnu" namespace.
2244 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2245 SourceLocation AttrNameLoc,
2246 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2247 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2248 ParsedAttr::Form Form, Declarator *D);
2249 IdentifierLoc *ParseIdentifierLoc();
2250
2251 unsigned
2252 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2253 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2254 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2255 ParsedAttr::Form Form);
2256
2257 void MaybeParseCXX11Attributes(Declarator &D) {
2258 if (isAllowedCXX11AttributeSpecifier()) {
2259 ParsedAttributes Attrs(AttrFactory);
2260 ParseCXX11Attributes(attrs&: Attrs);
2261 D.takeAttributes(attrs&: Attrs);
2262 }
2263 }
2264
2265 bool MaybeParseCXX11Attributes(ParsedAttributes &Attrs,
2266 bool OuterMightBeMessageSend = false) {
2267 if (isAllowedCXX11AttributeSpecifier(Disambiguate: false, OuterMightBeMessageSend)) {
2268 ParseCXX11Attributes(attrs&: Attrs);
2269 return true;
2270 }
2271 return false;
2272 }
2273
2274 bool MaybeParseMicrosoftAttributes(ParsedAttributes &Attrs) {
2275 bool AttrsParsed = false;
2276 if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) &&
2277 Tok.is(K: tok::l_square)) {
2278 ParsedAttributes AttrsWithRange(AttrFactory);
2279 ParseMicrosoftAttributes(Attrs&: AttrsWithRange);
2280 AttrsParsed = !AttrsWithRange.empty();
2281 Attrs.takeAllFrom(Other&: AttrsWithRange);
2282 }
2283 return AttrsParsed;
2284 }
2285 bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
2286 if (getLangOpts().DeclSpecKeyword && Tok.is(K: tok::kw___declspec)) {
2287 ParseMicrosoftDeclSpecs(Attrs);
2288 return true;
2289 }
2290 return false;
2291 }
2292
2293 /// \verbatim
2294 /// [MS] decl-specifier:
2295 /// __declspec ( extended-decl-modifier-seq )
2296 ///
2297 /// [MS] extended-decl-modifier-seq:
2298 /// extended-decl-modifier[opt]
2299 /// extended-decl-modifier extended-decl-modifier-seq
2300 /// \endverbatim
2301 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs);
2302 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2303 SourceLocation AttrNameLoc,
2304 ParsedAttributes &Attrs);
2305 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2306 void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &Attrs);
2307 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2308 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2309
2310 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2311 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2312 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2313 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2314 void ParseCUDAFunctionAttributes(ParsedAttributes &attrs);
2315 bool isHLSLQualifier(const Token &Tok) const;
2316 void ParseHLSLQualifiers(ParsedAttributes &Attrs);
2317
2318 /// Parse a version number.
2319 ///
2320 /// \verbatim
2321 /// version:
2322 /// simple-integer
2323 /// simple-integer '.' simple-integer
2324 /// simple-integer '_' simple-integer
2325 /// simple-integer '.' simple-integer '.' simple-integer
2326 /// simple-integer '_' simple-integer '_' simple-integer
2327 /// \endverbatim
2328 VersionTuple ParseVersionTuple(SourceRange &Range);
2329
2330 /// Parse the contents of the "availability" attribute.
2331 ///
2332 /// \verbatim
2333 /// availability-attribute:
2334 /// 'availability' '(' platform ',' opt-strict version-arg-list,
2335 /// opt-replacement, opt-message')'
2336 ///
2337 /// platform:
2338 /// identifier
2339 ///
2340 /// opt-strict:
2341 /// 'strict' ','
2342 ///
2343 /// version-arg-list:
2344 /// version-arg
2345 /// version-arg ',' version-arg-list
2346 ///
2347 /// version-arg:
2348 /// 'introduced' '=' version
2349 /// 'deprecated' '=' version
2350 /// 'obsoleted' = version
2351 /// 'unavailable'
2352 /// opt-replacement:
2353 /// 'replacement' '=' <string>
2354 /// opt-message:
2355 /// 'message' '=' <string>
2356 /// \endverbatim
2357 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2358 SourceLocation AvailabilityLoc,
2359 ParsedAttributes &attrs,
2360 SourceLocation *endLoc,
2361 IdentifierInfo *ScopeName,
2362 SourceLocation ScopeLoc,
2363 ParsedAttr::Form Form);
2364
2365 /// Parse the contents of the "external_source_symbol" attribute.
2366 ///
2367 /// \verbatim
2368 /// external-source-symbol-attribute:
2369 /// 'external_source_symbol' '(' keyword-arg-list ')'
2370 ///
2371 /// keyword-arg-list:
2372 /// keyword-arg
2373 /// keyword-arg ',' keyword-arg-list
2374 ///
2375 /// keyword-arg:
2376 /// 'language' '=' <string>
2377 /// 'defined_in' '=' <string>
2378 /// 'USR' '=' <string>
2379 /// 'generated_declaration'
2380 /// \endverbatim
2381 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2382 SourceLocation Loc,
2383 ParsedAttributes &Attrs,
2384 SourceLocation *EndLoc,
2385 IdentifierInfo *ScopeName,
2386 SourceLocation ScopeLoc,
2387 ParsedAttr::Form Form);
2388
2389 /// Parse the contents of the "objc_bridge_related" attribute.
2390 /// \verbatim
2391 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
2392 /// related_class:
2393 /// Identifier
2394 ///
2395 /// opt-class_method:
2396 /// Identifier: | <empty>
2397 ///
2398 /// opt-instance_method:
2399 /// Identifier | <empty>
2400 /// \endverbatim
2401 ///
2402 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2403 SourceLocation ObjCBridgeRelatedLoc,
2404 ParsedAttributes &Attrs,
2405 SourceLocation *EndLoc,
2406 IdentifierInfo *ScopeName,
2407 SourceLocation ScopeLoc,
2408 ParsedAttr::Form Form);
2409
2410 void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
2411 SourceLocation AttrNameLoc,
2412 ParsedAttributes &Attrs,
2413 SourceLocation *EndLoc,
2414 IdentifierInfo *ScopeName,
2415 SourceLocation ScopeLoc,
2416 ParsedAttr::Form Form);
2417
2418 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2419 SourceLocation AttrNameLoc,
2420 ParsedAttributes &Attrs,
2421 SourceLocation *EndLoc,
2422 IdentifierInfo *ScopeName,
2423 SourceLocation ScopeLoc,
2424 ParsedAttr::Form Form);
2425
2426 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2427 SourceLocation AttrNameLoc,
2428 ParsedAttributes &Attrs,
2429 IdentifierInfo *ScopeName,
2430 SourceLocation ScopeLoc,
2431 ParsedAttr::Form Form);
2432
2433 void DistributeCLateParsedAttrs(Decl *Dcl, LateParsedAttrList *LateAttrs);
2434
2435 /// Bounds attributes (e.g., counted_by):
2436 /// \verbatim
2437 /// AttrName '(' expression ')'
2438 /// \endverbatim
2439 void ParseBoundsAttribute(IdentifierInfo &AttrName,
2440 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2441 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2442 ParsedAttr::Form Form);
2443
2444 /// \verbatim
2445 /// [GNU] typeof-specifier:
2446 /// typeof ( expressions )
2447 /// typeof ( type-name )
2448 /// [GNU/C++] typeof unary-expression
2449 /// [C23] typeof-specifier:
2450 /// typeof '(' typeof-specifier-argument ')'
2451 /// typeof_unqual '(' typeof-specifier-argument ')'
2452 ///
2453 /// typeof-specifier-argument:
2454 /// expression
2455 /// type-name
2456 /// \endverbatim
2457 ///
2458 void ParseTypeofSpecifier(DeclSpec &DS);
2459
2460 /// \verbatim
2461 /// [C11] atomic-specifier:
2462 /// _Atomic ( type-name )
2463 /// \endverbatim
2464 ///
2465 void ParseAtomicSpecifier(DeclSpec &DS);
2466
2467 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2468 ///
2469 /// \verbatim
2470 /// [C11] type-id
2471 /// [C11] constant-expression
2472 /// [C++0x] type-id ...[opt]
2473 /// [C++0x] assignment-expression ...[opt]
2474 /// \endverbatim
2475 ExprResult ParseAlignArgument(StringRef KWName, SourceLocation Start,
2476 SourceLocation &EllipsisLoc, bool &IsType,
2477 ParsedType &Ty);
2478
2479 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2480 /// attribute to Attrs.
2481 ///
2482 /// \verbatim
2483 /// alignment-specifier:
2484 /// [C11] '_Alignas' '(' type-id ')'
2485 /// [C11] '_Alignas' '(' constant-expression ')'
2486 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2487 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2488 /// \endverbatim
2489 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2490 SourceLocation *endLoc = nullptr);
2491 ExprResult ParseExtIntegerArgument();
2492
2493 /// \verbatim
2494 /// type-qualifier:
2495 /// ('__ptrauth') '(' constant-expression
2496 /// (',' constant-expression)[opt]
2497 /// (',' constant-expression)[opt] ')'
2498 /// \endverbatim
2499 void ParsePtrauthQualifier(ParsedAttributes &Attrs);
2500
2501 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2502 /// enter a new C++ declarator scope and exit it when the function is
2503 /// finished.
2504 class DeclaratorScopeObj {
2505 Parser &P;
2506 CXXScopeSpec &SS;
2507 bool EnteredScope;
2508 bool CreatedScope;
2509
2510 public:
2511 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2512 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2513
2514 void EnterDeclaratorScope() {
2515 assert(!EnteredScope && "Already entered the scope!");
2516 assert(SS.isSet() && "C++ scope was not set!");
2517
2518 CreatedScope = true;
2519 P.EnterScope(ScopeFlags: 0); // Not a decl scope.
2520
2521 if (!P.Actions.ActOnCXXEnterDeclaratorScope(S: P.getCurScope(), SS))
2522 EnteredScope = true;
2523 }
2524
2525 ~DeclaratorScopeObj() {
2526 if (EnteredScope) {
2527 assert(SS.isSet() && "C++ scope was cleared ?");
2528 P.Actions.ActOnCXXExitDeclaratorScope(S: P.getCurScope(), SS);
2529 }
2530 if (CreatedScope)
2531 P.ExitScope();
2532 }
2533 };
2534
2535 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2536 void ParseDeclarator(Declarator &D);
2537 /// A function that parses a variant of direct-declarator.
2538 typedef void (Parser::*DirectDeclParseFunction)(Declarator &);
2539
2540 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The
2541 /// direct-declarator is parsed by the function passed to it. Pass null, and
2542 /// the direct-declarator isn't parsed at all, making this function
2543 /// effectively parse the C++ ptr-operator production.
2544 ///
2545 /// If the grammar of this construct is extended, matching changes must also
2546 /// be made to TryParseDeclarator and MightBeDeclarator, and possibly to
2547 /// isConstructorDeclarator.
2548 ///
2549 /// \verbatim
2550 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2551 /// [C] pointer[opt] direct-declarator
2552 /// [C++] direct-declarator
2553 /// [C++] ptr-operator declarator
2554 ///
2555 /// pointer: [C99 6.7.5]
2556 /// '*' type-qualifier-list[opt]
2557 /// '*' type-qualifier-list[opt] pointer
2558 ///
2559 /// ptr-operator:
2560 /// '*' cv-qualifier-seq[opt]
2561 /// '&'
2562 /// [C++0x] '&&'
2563 /// [GNU] '&' restrict[opt] attributes[opt]
2564 /// [GNU?] '&&' restrict[opt] attributes[opt]
2565 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2566 /// \endverbatim
2567 void ParseDeclaratorInternal(Declarator &D,
2568 DirectDeclParseFunction DirectDeclParser);
2569
2570 enum AttrRequirements {
2571 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2572 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2573 AR_GNUAttributesParsed = 1 << 1,
2574 AR_CXX11AttributesParsed = 1 << 2,
2575 AR_DeclspecAttributesParsed = 1 << 3,
2576 AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed |
2577 AR_DeclspecAttributesParsed,
2578 AR_VendorAttributesParsed =
2579 AR_GNUAttributesParsed | AR_DeclspecAttributesParsed
2580 };
2581
2582 /// ParseTypeQualifierListOpt
2583 /// \verbatim
2584 /// type-qualifier-list: [C99 6.7.5]
2585 /// type-qualifier
2586 /// [vendor] attributes
2587 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
2588 /// type-qualifier-list type-qualifier
2589 /// [vendor] type-qualifier-list attributes
2590 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
2591 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2592 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
2593 /// \endverbatim
2594 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
2595 /// AttrRequirements bitmask values.
2596 void ParseTypeQualifierListOpt(
2597 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2598 bool AtomicOrPtrauthAllowed = true, bool IdentifierRequired = false,
2599 llvm::function_ref<void()> CodeCompletionHandler = {});
2600
2601 /// ParseDirectDeclarator
2602 /// \verbatim
2603 /// direct-declarator: [C99 6.7.5]
2604 /// [C99] identifier
2605 /// '(' declarator ')'
2606 /// [GNU] '(' attributes declarator ')'
2607 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2608 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2609 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2610 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2611 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2612 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
2613 /// attribute-specifier-seq[opt]
2614 /// direct-declarator '(' parameter-type-list ')'
2615 /// direct-declarator '(' identifier-list[opt] ')'
2616 /// [GNU] direct-declarator '(' parameter-forward-declarations
2617 /// parameter-type-list[opt] ')'
2618 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
2619 /// cv-qualifier-seq[opt] exception-specification[opt]
2620 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
2621 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
2622 /// ref-qualifier[opt] exception-specification[opt]
2623 /// [C++] declarator-id
2624 /// [C++11] declarator-id attribute-specifier-seq[opt]
2625 ///
2626 /// declarator-id: [C++ 8]
2627 /// '...'[opt] id-expression
2628 /// '::'[opt] nested-name-specifier[opt] type-name
2629 ///
2630 /// id-expression: [C++ 5.1]
2631 /// unqualified-id
2632 /// qualified-id
2633 ///
2634 /// unqualified-id: [C++ 5.1]
2635 /// identifier
2636 /// operator-function-id
2637 /// conversion-function-id
2638 /// '~' class-name
2639 /// template-id
2640 ///
2641 /// C++17 adds the following, which we also handle here:
2642 ///
2643 /// simple-declaration:
2644 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
2645 /// \endverbatim
2646 ///
2647 /// Note, any additional constructs added here may need corresponding changes
2648 /// in isConstructorDeclarator.
2649 void ParseDirectDeclarator(Declarator &D);
2650 void ParseDecompositionDeclarator(Declarator &D);
2651
2652 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
2653 /// only called before the identifier, so these are most likely just grouping
2654 /// parens for precedence. If we find that these are actually function
2655 /// parameter parens in an abstract-declarator, we call
2656 /// ParseFunctionDeclarator.
2657 ///
2658 /// \verbatim
2659 /// direct-declarator:
2660 /// '(' declarator ')'
2661 /// [GNU] '(' attributes declarator ')'
2662 /// direct-declarator '(' parameter-type-list ')'
2663 /// direct-declarator '(' identifier-list[opt] ')'
2664 /// [GNU] direct-declarator '(' parameter-forward-declarations
2665 /// parameter-type-list[opt] ')'
2666 /// \endverbatim
2667 ///
2668 void ParseParenDeclarator(Declarator &D);
2669
2670 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
2671 /// declarator D up to a paren, which indicates that we are parsing function
2672 /// arguments.
2673 ///
2674 /// If FirstArgAttrs is non-null, then the caller parsed those attributes
2675 /// immediately after the open paren - they will be applied to the DeclSpec
2676 /// of the first parameter.
2677 ///
2678 /// If RequiresArg is true, then the first argument of the function is
2679 /// required to be present and required to not be an identifier list.
2680 ///
2681 /// For C++, after the parameter-list, it also parses the
2682 /// cv-qualifier-seq[opt], (C++11) ref-qualifier[opt],
2683 /// exception-specification[opt], (C++11) attribute-specifier-seq[opt],
2684 /// (C++11) trailing-return-type[opt] and (C++2a) the trailing
2685 /// requires-clause.
2686 ///
2687 /// \verbatim
2688 /// [C++11] exception-specification:
2689 /// dynamic-exception-specification
2690 /// noexcept-specification
2691 /// \endverbatim
2692 ///
2693 void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs,
2694 BalancedDelimiterTracker &Tracker,
2695 bool IsAmbiguous, bool RequiresArg = false);
2696 void InitCXXThisScopeForDeclaratorIfRelevant(
2697 const Declarator &D, const DeclSpec &DS,
2698 std::optional<Sema::CXXThisScopeRAII> &ThisScope);
2699
2700 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
2701 /// true if a ref-qualifier is found.
2702 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2703 SourceLocation &RefQualifierLoc);
2704
2705 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
2706 /// identifier list form for a K&R-style function: void foo(a,b,c)
2707 ///
2708 /// Note that identifier-lists are only allowed for normal declarators, not
2709 /// for abstract-declarators.
2710 bool isFunctionDeclaratorIdentifierList();
2711
2712 /// ParseFunctionDeclaratorIdentifierList - While parsing a function
2713 /// declarator we found a K&R-style identifier list instead of a typed
2714 /// parameter list.
2715 ///
2716 /// After returning, ParamInfo will hold the parsed parameters.
2717 ///
2718 /// \verbatim
2719 /// identifier-list: [C99 6.7.5]
2720 /// identifier
2721 /// identifier-list ',' identifier
2722 /// \endverbatim
2723 ///
2724 void ParseFunctionDeclaratorIdentifierList(
2725 Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2726 void ParseParameterDeclarationClause(
2727 Declarator &D, ParsedAttributes &attrs,
2728 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2729 SourceLocation &EllipsisLoc) {
2730 return ParseParameterDeclarationClause(
2731 DeclaratorContext: D.getContext(), attrs, ParamInfo, EllipsisLoc,
2732 IsACXXFunctionDeclaration: D.getCXXScopeSpec().isSet() &&
2733 D.isFunctionDeclaratorAFunctionDeclaration());
2734 }
2735
2736 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
2737 /// after the opening parenthesis. This function will not parse a K&R-style
2738 /// identifier list.
2739 ///
2740 /// DeclContext is the context of the declarator being parsed. If
2741 /// FirstArgAttrs is non-null, then the caller parsed those attributes
2742 /// immediately after the open paren - they will be applied to the DeclSpec of
2743 /// the first parameter.
2744 ///
2745 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc
2746 /// will be the location of the ellipsis, if any was parsed.
2747 ///
2748 /// \verbatim
2749 /// parameter-type-list: [C99 6.7.5]
2750 /// parameter-list
2751 /// parameter-list ',' '...'
2752 /// [C++] parameter-list '...'
2753 ///
2754 /// parameter-list: [C99 6.7.5]
2755 /// parameter-declaration
2756 /// parameter-list ',' parameter-declaration
2757 ///
2758 /// parameter-declaration: [C99 6.7.5]
2759 /// declaration-specifiers declarator
2760 /// [C++] declaration-specifiers declarator '=' assignment-expression
2761 /// [C++11] initializer-clause
2762 /// [GNU] declaration-specifiers declarator attributes
2763 /// declaration-specifiers abstract-declarator[opt]
2764 /// [C++] declaration-specifiers abstract-declarator[opt]
2765 /// '=' assignment-expression
2766 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
2767 /// [C++11] attribute-specifier-seq parameter-declaration
2768 /// [C++2b] attribute-specifier-seq 'this' parameter-declaration
2769 /// \endverbatim
2770 ///
2771 void ParseParameterDeclarationClause(
2772 DeclaratorContext DeclaratorContext, ParsedAttributes &attrs,
2773 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2774 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration = false);
2775
2776 /// \verbatim
2777 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2778 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2779 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2780 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2781 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2782 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
2783 /// attribute-specifier-seq[opt]
2784 /// \endverbatim
2785 void ParseBracketDeclarator(Declarator &D);
2786
2787 /// Diagnose brackets before an identifier.
2788 void ParseMisplacedBracketDeclarator(Declarator &D);
2789
2790 /// Parse the given string as a type.
2791 ///
2792 /// This is a dangerous utility function currently employed only by API notes.
2793 /// It is not a general entry-point for safely parsing types from strings.
2794 ///
2795 /// \param TypeStr The string to be parsed as a type.
2796 /// \param Context The name of the context in which this string is being
2797 /// parsed, which will be used in diagnostics.
2798 /// \param IncludeLoc The location at which this parse was triggered.
2799 TypeResult ParseTypeFromString(StringRef TypeStr, StringRef Context,
2800 SourceLocation IncludeLoc);
2801
2802 ///@}
2803
2804 //
2805 //
2806 // -------------------------------------------------------------------------
2807 //
2808 //
2809
2810 /// \name C++ Declarations
2811 /// Implementations are in ParseDeclCXX.cpp
2812 ///@{
2813
2814private:
2815 /// Contextual keywords for Microsoft extensions.
2816 mutable IdentifierInfo *Ident_sealed;
2817 mutable IdentifierInfo *Ident_abstract;
2818
2819 /// C++11 contextual keywords.
2820 mutable IdentifierInfo *Ident_final;
2821 mutable IdentifierInfo *Ident_GNU_final;
2822 mutable IdentifierInfo *Ident_override;
2823 mutable IdentifierInfo *Ident_trivially_relocatable_if_eligible;
2824 mutable IdentifierInfo *Ident_replaceable_if_eligible;
2825
2826 /// Representation of a class that has been parsed, including
2827 /// any member function declarations or definitions that need to be
2828 /// parsed after the corresponding top-level class is complete.
2829 struct ParsingClass {
2830 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
2831 : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
2832 TagOrTemplate(TagOrTemplate) {}
2833
2834 /// Whether this is a "top-level" class, meaning that it is
2835 /// not nested within another class.
2836 bool TopLevelClass : 1;
2837
2838 /// Whether this class is an __interface.
2839 bool IsInterface : 1;
2840
2841 /// The class or class template whose definition we are parsing.
2842 Decl *TagOrTemplate;
2843
2844 /// LateParsedDeclarations - Method declarations, inline definitions and
2845 /// nested classes that contain pieces whose parsing will be delayed until
2846 /// the top-level class is fully defined.
2847 LateParsedDeclarationsContainer LateParsedDeclarations;
2848 };
2849
2850 /// The stack of classes that is currently being
2851 /// parsed. Nested and local classes will be pushed onto this stack
2852 /// when they are parsed, and removed afterward.
2853 std::stack<ParsingClass *> ClassStack;
2854
2855 ParsingClass &getCurrentClass() {
2856 assert(!ClassStack.empty() && "No lexed method stacks!");
2857 return *ClassStack.top();
2858 }
2859
2860 /// RAII object used to manage the parsing of a class definition.
2861 class ParsingClassDefinition {
2862 Parser &P;
2863 bool Popped;
2864 Sema::ParsingClassState State;
2865
2866 public:
2867 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
2868 bool IsInterface)
2869 : P(P), Popped(false),
2870 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
2871 }
2872
2873 /// Pop this class of the stack.
2874 void Pop() {
2875 assert(!Popped && "Nested class has already been popped");
2876 Popped = true;
2877 P.PopParsingClass(State);
2878 }
2879
2880 ~ParsingClassDefinition() {
2881 if (!Popped)
2882 P.PopParsingClass(State);
2883 }
2884 };
2885
2886 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
2887 ///
2888 /// \verbatim
2889 /// exception-specification:
2890 /// dynamic-exception-specification
2891 /// noexcept-specification
2892 ///
2893 /// noexcept-specification:
2894 /// 'noexcept'
2895 /// 'noexcept' '(' constant-expression ')'
2896 /// \endverbatim
2897 ExceptionSpecificationType tryParseExceptionSpecification(
2898 bool Delayed, SourceRange &SpecificationRange,
2899 SmallVectorImpl<ParsedType> &DynamicExceptions,
2900 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2901 ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens);
2902
2903 /// ParseDynamicExceptionSpecification - Parse a C++
2904 /// dynamic-exception-specification (C++ [except.spec]).
2905 /// EndLoc is filled with the location of the last token of the specification.
2906 ///
2907 /// \verbatim
2908 /// dynamic-exception-specification:
2909 /// 'throw' '(' type-id-list [opt] ')'
2910 /// [MS] 'throw' '(' '...' ')'
2911 ///
2912 /// type-id-list:
2913 /// type-id ... [opt]
2914 /// type-id-list ',' type-id ... [opt]
2915 /// \endverbatim
2916 ///
2917 ExceptionSpecificationType
2918 ParseDynamicExceptionSpecification(SourceRange &SpecificationRange,
2919 SmallVectorImpl<ParsedType> &Exceptions,
2920 SmallVectorImpl<SourceRange> &Ranges);
2921
2922 //===--------------------------------------------------------------------===//
2923 // C++0x 8: Function declaration trailing-return-type
2924
2925 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2926 /// function declaration.
2927 TypeResult ParseTrailingReturnType(SourceRange &Range,
2928 bool MayBeFollowedByDirectInit);
2929
2930 /// Parse a requires-clause as part of a function declaration.
2931 void ParseTrailingRequiresClause(Declarator &D);
2932
2933 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
2934 ParsedAttributes &AccessAttrs,
2935 AccessSpecifier &CurAS);
2936
2937 SourceLocation ParsePackIndexingType(DeclSpec &DS);
2938 void AnnotateExistingIndexedTypeNamePack(ParsedType T,
2939 SourceLocation StartLoc,
2940 SourceLocation EndLoc);
2941
2942 /// Return true if the next token should be treated as a [[]] attribute,
2943 /// or as a keyword that behaves like one. The former is only true if
2944 /// [[]] attributes are enabled, whereas the latter is true whenever
2945 /// such a keyword appears. The arguments are as for
2946 /// isCXX11AttributeSpecifier.
2947 bool isAllowedCXX11AttributeSpecifier(bool Disambiguate = false,
2948 bool OuterMightBeMessageSend = false) {
2949 return (Tok.isRegularKeywordAttribute() ||
2950 isCXX11AttributeSpecifier(Disambiguate, OuterMightBeMessageSend) !=
2951 CXX11AttributeKind::NotAttributeSpecifier);
2952 }
2953
2954 /// Skip C++11 and C23 attributes and return the end location of the
2955 /// last one.
2956 /// \returns SourceLocation() if there are no attributes.
2957 SourceLocation SkipCXX11Attributes();
2958
2959 /// Diagnose and skip C++11 and C23 attributes that appear in syntactic
2960 /// locations where attributes are not allowed.
2961 void DiagnoseAndSkipCXX11Attributes();
2962
2963 void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
2964 CachedTokens &OpenMPTokens);
2965
2966 /// Parse a C++11 or C23 attribute-specifier.
2967 ///
2968 /// \verbatim
2969 /// [C++11] attribute-specifier:
2970 /// '[' '[' attribute-list ']' ']'
2971 /// alignment-specifier
2972 ///
2973 /// [C++11] attribute-list:
2974 /// attribute[opt]
2975 /// attribute-list ',' attribute[opt]
2976 /// attribute '...'
2977 /// attribute-list ',' attribute '...'
2978 ///
2979 /// [C++11] attribute:
2980 /// attribute-token attribute-argument-clause[opt]
2981 ///
2982 /// [C++11] attribute-token:
2983 /// identifier
2984 /// attribute-scoped-token
2985 ///
2986 /// [C++11] attribute-scoped-token:
2987 /// attribute-namespace '::' identifier
2988 ///
2989 /// [C++11] attribute-namespace:
2990 /// identifier
2991 /// \endverbatim
2992 void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
2993 CachedTokens &OpenMPTokens,
2994 SourceLocation *EndLoc = nullptr);
2995 void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs,
2996 SourceLocation *EndLoc = nullptr) {
2997 CachedTokens OpenMPTokens;
2998 ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc);
2999 ReplayOpenMPAttributeTokens(OpenMPTokens);
3000 }
3001
3002 /// ParseCXX11Attributes - Parse a C++11 or C23 attribute-specifier-seq.
3003 ///
3004 /// \verbatim
3005 /// attribute-specifier-seq:
3006 /// attribute-specifier-seq[opt] attribute-specifier
3007 /// \endverbatim
3008 void ParseCXX11Attributes(ParsedAttributes &attrs);
3009
3010 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3011 /// Parses a C++11 (or C23)-style attribute argument list. Returns true
3012 /// if this results in adding an attribute to the ParsedAttributes list.
3013 ///
3014 /// \verbatim
3015 /// [C++11] attribute-argument-clause:
3016 /// '(' balanced-token-seq ')'
3017 ///
3018 /// [C++11] balanced-token-seq:
3019 /// balanced-token
3020 /// balanced-token-seq balanced-token
3021 ///
3022 /// [C++11] balanced-token:
3023 /// '(' balanced-token-seq ')'
3024 /// '[' balanced-token-seq ']'
3025 /// '{' balanced-token-seq '}'
3026 /// any token but '(', ')', '[', ']', '{', or '}'
3027 /// \endverbatim
3028 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3029 SourceLocation AttrNameLoc,
3030 ParsedAttributes &Attrs, SourceLocation *EndLoc,
3031 IdentifierInfo *ScopeName,
3032 SourceLocation ScopeLoc,
3033 CachedTokens &OpenMPTokens);
3034
3035 /// Parse the argument to C++23's [[assume()]] attribute. Returns true on
3036 /// error.
3037 bool
3038 ParseCXXAssumeAttributeArg(ParsedAttributes &Attrs, IdentifierInfo *AttrName,
3039 SourceLocation AttrNameLoc,
3040 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
3041 SourceLocation *EndLoc, ParsedAttr::Form Form);
3042
3043 /// Try to parse an 'identifier' which appears within an attribute-token.
3044 ///
3045 /// \return the parsed identifier on success, and 0 if the next token is not
3046 /// an attribute-token.
3047 ///
3048 /// C++11 [dcl.attr.grammar]p3:
3049 /// If a keyword or an alternative token that satisfies the syntactic
3050 /// requirements of an identifier is contained in an attribute-token,
3051 /// it is considered an identifier.
3052 IdentifierInfo *TryParseCXX11AttributeIdentifier(
3053 SourceLocation &Loc,
3054 SemaCodeCompletion::AttributeCompletion Completion =
3055 SemaCodeCompletion::AttributeCompletion::None,
3056 const IdentifierInfo *EnclosingScope = nullptr);
3057
3058 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
3059 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
3060
3061 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
3062 ///
3063 /// \verbatim
3064 /// [MS] ms-attribute:
3065 /// '[' token-seq ']'
3066 ///
3067 /// [MS] ms-attribute-seq:
3068 /// ms-attribute[opt]
3069 /// ms-attribute ms-attribute-seq
3070 /// \endverbatim
3071 void ParseMicrosoftAttributes(ParsedAttributes &Attrs);
3072
3073 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
3074 void ParseNullabilityClassAttributes(ParsedAttributes &attrs);
3075
3076 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
3077 ///
3078 /// \verbatim
3079 /// 'decltype' ( expression )
3080 /// 'decltype' ( 'auto' ) [C++1y]
3081 /// \endverbatim
3082 ///
3083 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
3084 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
3085 SourceLocation StartLoc,
3086 SourceLocation EndLoc);
3087
3088 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
3089 /// virt-specifier.
3090 ///
3091 /// \verbatim
3092 /// virt-specifier:
3093 /// override
3094 /// final
3095 /// __final
3096 /// \endverbatim
3097 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
3098 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
3099 return isCXX11VirtSpecifier(Tok);
3100 }
3101
3102 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
3103 ///
3104 /// \verbatim
3105 /// virt-specifier-seq:
3106 /// virt-specifier
3107 /// virt-specifier-seq virt-specifier
3108 /// \endverbatim
3109 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
3110 SourceLocation FriendLoc);
3111
3112 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
3113 /// 'final' or Microsoft 'sealed' contextual keyword.
3114 bool isCXX11FinalKeyword() const;
3115
3116 /// isClassCompatibleKeyword - Determine whether the next token is a C++11
3117 /// 'final', a C++26 'trivially_relocatable_if_eligible',
3118 /// 'replaceable_if_eligible', or Microsoft 'sealed' or 'abstract' contextual
3119 /// keyword.
3120 bool isClassCompatibleKeyword() const;
3121
3122 bool MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS);
3123 DeclSpec::TST TypeTransformTokToDeclSpec();
3124
3125 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3126
3127 /// ParseNamespace - We know that the current token is a namespace keyword.
3128 /// This may either be a top level namespace or a block-level namespace alias.
3129 /// If there was an inline keyword, it has already been parsed.
3130 ///
3131 /// \verbatim
3132 /// namespace-definition: [C++: namespace.def]
3133 /// named-namespace-definition
3134 /// unnamed-namespace-definition
3135 /// nested-namespace-definition
3136 ///
3137 /// named-namespace-definition:
3138 /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
3139 /// namespace-body '}'
3140 ///
3141 /// unnamed-namespace-definition:
3142 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
3143 ///
3144 /// nested-namespace-definition:
3145 /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
3146 /// identifier '{' namespace-body '}'
3147 ///
3148 /// enclosing-namespace-specifier:
3149 /// identifier
3150 /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
3151 ///
3152 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
3153 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
3154 /// \endverbatim
3155 ///
3156 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3157 SourceLocation &DeclEnd,
3158 SourceLocation InlineLoc = SourceLocation());
3159
3160 struct InnerNamespaceInfo {
3161 SourceLocation NamespaceLoc;
3162 SourceLocation InlineLoc;
3163 SourceLocation IdentLoc;
3164 IdentifierInfo *Ident;
3165 };
3166 using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3167
3168 /// ParseInnerNamespace - Parse the contents of a namespace.
3169 void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3170 unsigned int index, SourceLocation &InlineLoc,
3171 ParsedAttributes &attrs,
3172 BalancedDelimiterTracker &Tracker);
3173
3174 /// ParseLinkage - We know that the current token is a string_literal
3175 /// and just before that, that extern was seen.
3176 ///
3177 /// \verbatim
3178 /// linkage-specification: [C++ 7.5p2: dcl.link]
3179 /// 'extern' string-literal '{' declaration-seq[opt] '}'
3180 /// 'extern' string-literal declaration
3181 /// \endverbatim
3182 ///
3183 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3184
3185 /// Parse a standard C++ Modules export-declaration.
3186 ///
3187 /// \verbatim
3188 /// export-declaration:
3189 /// 'export' declaration
3190 /// 'export' '{' declaration-seq[opt] '}'
3191 /// \endverbatim
3192 ///
3193 /// HLSL: Parse export function declaration.
3194 ///
3195 /// \verbatim
3196 /// export-function-declaration:
3197 /// 'export' function-declaration
3198 ///
3199 /// export-declaration-group:
3200 /// 'export' '{' function-declaration-seq[opt] '}'
3201 /// \endverbatim
3202 ///
3203 Decl *ParseExportDeclaration();
3204
3205 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
3206 /// using-directive. Assumes that current token is 'using'.
3207 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3208 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3209 SourceLocation &DeclEnd, ParsedAttributes &Attrs);
3210
3211 /// ParseUsingDirective - Parse C++ using-directive, assumes
3212 /// that current token is 'namespace' and 'using' was already parsed.
3213 ///
3214 /// \verbatim
3215 /// using-directive: [C++ 7.3.p4: namespace.udir]
3216 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
3217 /// namespace-name ;
3218 /// [GNU] using-directive:
3219 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
3220 /// namespace-name attributes[opt] ;
3221 /// \endverbatim
3222 ///
3223 Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc,
3224 SourceLocation &DeclEnd, ParsedAttributes &attrs);
3225
3226 struct UsingDeclarator {
3227 SourceLocation TypenameLoc;
3228 CXXScopeSpec SS;
3229 UnqualifiedId Name;
3230 SourceLocation EllipsisLoc;
3231
3232 void clear() {
3233 TypenameLoc = EllipsisLoc = SourceLocation();
3234 SS.clear();
3235 Name.clear();
3236 }
3237 };
3238
3239 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
3240 ///
3241 /// \verbatim
3242 /// using-declarator:
3243 /// 'typename'[opt] nested-name-specifier unqualified-id
3244 /// \endverbatim
3245 ///
3246 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3247
3248 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
3249 /// Assumes that 'using' was already seen.
3250 ///
3251 /// \verbatim
3252 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
3253 /// 'using' using-declarator-list[opt] ;
3254 ///
3255 /// using-declarator-list: [C++1z]
3256 /// using-declarator '...'[opt]
3257 /// using-declarator-list ',' using-declarator '...'[opt]
3258 ///
3259 /// using-declarator-list: [C++98-14]
3260 /// using-declarator
3261 ///
3262 /// alias-declaration: C++11 [dcl.dcl]p1
3263 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
3264 ///
3265 /// using-enum-declaration: [C++20, dcl.enum]
3266 /// 'using' elaborated-enum-specifier ;
3267 /// The terminal name of the elaborated-enum-specifier undergoes
3268 /// type-only lookup
3269 ///
3270 /// elaborated-enum-specifier:
3271 /// 'enum' nested-name-specifier[opt] identifier
3272 /// \endverbatim
3273 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3274 const ParsedTemplateInfo &TemplateInfo,
3275 SourceLocation UsingLoc,
3276 SourceLocation &DeclEnd,
3277 ParsedAttributes &Attrs,
3278 AccessSpecifier AS = AS_none);
3279 Decl *ParseAliasDeclarationAfterDeclarator(
3280 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3281 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3282 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3283
3284 /// ParseStaticAssertDeclaration - Parse C++0x or C11
3285 /// static_assert-declaration.
3286 ///
3287 /// \verbatim
3288 /// [C++0x] static_assert-declaration:
3289 /// static_assert ( constant-expression , string-literal ) ;
3290 ///
3291 /// [C11] static_assert-declaration:
3292 /// _Static_assert ( constant-expression , string-literal ) ;
3293 /// \endverbatim
3294 ///
3295 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3296
3297 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
3298 /// alias definition.
3299 ///
3300 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3301 SourceLocation AliasLoc, IdentifierInfo *Alias,
3302 SourceLocation &DeclEnd);
3303
3304 //===--------------------------------------------------------------------===//
3305 // C++ 9: classes [class] and C structs/unions.
3306
3307 /// Determine whether the following tokens are valid after a type-specifier
3308 /// which could be a standalone declaration. This will conservatively return
3309 /// true if there's any doubt, and is appropriate for insert-';' fixits.
3310 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3311
3312 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
3313 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
3314 /// until we reach the start of a definition or see a token that
3315 /// cannot start a definition.
3316 ///
3317 /// \verbatim
3318 /// class-specifier: [C++ class]
3319 /// class-head '{' member-specification[opt] '}'
3320 /// class-head '{' member-specification[opt] '}' attributes[opt]
3321 /// class-head:
3322 /// class-key identifier[opt] base-clause[opt]
3323 /// class-key nested-name-specifier identifier base-clause[opt]
3324 /// class-key nested-name-specifier[opt] simple-template-id
3325 /// base-clause[opt]
3326 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
3327 /// [GNU] class-key attributes[opt] nested-name-specifier
3328 /// identifier base-clause[opt]
3329 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
3330 /// simple-template-id base-clause[opt]
3331 /// class-key:
3332 /// 'class'
3333 /// 'struct'
3334 /// 'union'
3335 ///
3336 /// elaborated-type-specifier: [C++ dcl.type.elab]
3337 /// class-key ::[opt] nested-name-specifier[opt] identifier
3338 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
3339 /// simple-template-id
3340 ///
3341 /// Note that the C++ class-specifier and elaborated-type-specifier,
3342 /// together, subsume the C99 struct-or-union-specifier:
3343 ///
3344 /// struct-or-union-specifier: [C99 6.7.2.1]
3345 /// struct-or-union identifier[opt] '{' struct-contents '}'
3346 /// struct-or-union identifier
3347 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
3348 /// '}' attributes[opt]
3349 /// [GNU] struct-or-union attributes[opt] identifier
3350 /// struct-or-union:
3351 /// 'struct'
3352 /// 'union'
3353 /// \endverbatim
3354 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3355 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
3356 AccessSpecifier AS, bool EnteringContext,
3357 DeclSpecContext DSC, ParsedAttributes &Attributes);
3358 void SkipCXXMemberSpecification(SourceLocation StartLoc,
3359 SourceLocation AttrFixitLoc, unsigned TagType,
3360 Decl *TagDecl);
3361
3362 /// ParseCXXMemberSpecification - Parse the class definition.
3363 ///
3364 /// \verbatim
3365 /// member-specification:
3366 /// member-declaration member-specification[opt]
3367 /// access-specifier ':' member-specification[opt]
3368 /// \endverbatim
3369 ///
3370 void ParseCXXMemberSpecification(SourceLocation StartLoc,
3371 SourceLocation AttrFixitLoc,
3372 ParsedAttributes &Attrs, unsigned TagType,
3373 Decl *TagDecl);
3374
3375 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
3376 /// Also detect and reject any attempted defaulted/deleted function
3377 /// definition. The location of the '=', if any, will be placed in EqualLoc.
3378 ///
3379 /// This does not check for a pure-specifier; that's handled elsewhere.
3380 ///
3381 /// \verbatim
3382 /// brace-or-equal-initializer:
3383 /// '=' initializer-expression
3384 /// braced-init-list
3385 ///
3386 /// initializer-clause:
3387 /// assignment-expression
3388 /// braced-init-list
3389 ///
3390 /// defaulted/deleted function-definition:
3391 /// '=' 'default'
3392 /// '=' 'delete'
3393 /// \endverbatim
3394 ///
3395 /// Prior to C++0x, the assignment-expression in an initializer-clause must
3396 /// be a constant-expression.
3397 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3398 SourceLocation &EqualLoc);
3399
3400 /// Parse a C++ member-declarator up to, but not including, the optional
3401 /// brace-or-equal-initializer or pure-specifier.
3402 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3403 VirtSpecifiers &VS,
3404 ExprResult &BitfieldSize,
3405 LateParsedAttrList &LateAttrs);
3406
3407 /// Look for declaration specifiers possibly occurring after C++11
3408 /// virt-specifier-seq and diagnose them.
3409 void
3410 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3411 VirtSpecifiers &VS);
3412
3413 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
3414 ///
3415 /// \verbatim
3416 /// member-declaration:
3417 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
3418 /// function-definition ';'[opt]
3419 /// [C++26] friend-type-declaration
3420 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
3421 /// using-declaration [TODO]
3422 /// [C++0x] static_assert-declaration
3423 /// template-declaration
3424 /// [GNU] '__extension__' member-declaration
3425 ///
3426 /// member-declarator-list:
3427 /// member-declarator
3428 /// member-declarator-list ',' member-declarator
3429 ///
3430 /// member-declarator:
3431 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
3432 /// [C++2a] declarator requires-clause
3433 /// declarator constant-initializer[opt]
3434 /// [C++11] declarator brace-or-equal-initializer[opt]
3435 /// identifier[opt] ':' constant-expression
3436 ///
3437 /// virt-specifier-seq:
3438 /// virt-specifier
3439 /// virt-specifier-seq virt-specifier
3440 ///
3441 /// virt-specifier:
3442 /// override
3443 /// final
3444 /// [MS] sealed
3445 ///
3446 /// pure-specifier:
3447 /// '= 0'
3448 ///
3449 /// constant-initializer:
3450 /// '=' constant-expression
3451 ///
3452 /// friend-type-declaration:
3453 /// 'friend' friend-type-specifier-list ;
3454 ///
3455 /// friend-type-specifier-list:
3456 /// friend-type-specifier ...[opt]
3457 /// friend-type-specifier-list , friend-type-specifier ...[opt]
3458 ///
3459 /// friend-type-specifier:
3460 /// simple-type-specifier
3461 /// elaborated-type-specifier
3462 /// typename-specifier
3463 /// \endverbatim
3464 ///
3465 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3466 AccessSpecifier AS, ParsedAttributes &Attr,
3467 ParsedTemplateInfo &TemplateInfo,
3468 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3469 DeclGroupPtrTy
3470 ParseCXXClassMemberDeclarationWithPragmas(AccessSpecifier &AS,
3471 ParsedAttributes &AccessAttrs,
3472 DeclSpec::TST TagType, Decl *Tag);
3473
3474 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3475 /// which explicitly initializes the members or base classes of a
3476 /// class (C++ [class.base.init]). For example, the three initializers
3477 /// after the ':' in the Derived constructor below:
3478 ///
3479 /// @code
3480 /// class Base { };
3481 /// class Derived : Base {
3482 /// int x;
3483 /// float f;
3484 /// public:
3485 /// Derived(float f) : Base(), x(17), f(f) { }
3486 /// };
3487 /// @endcode
3488 ///
3489 /// \verbatim
3490 /// [C++] ctor-initializer:
3491 /// ':' mem-initializer-list
3492 ///
3493 /// [C++] mem-initializer-list:
3494 /// mem-initializer ...[opt]
3495 /// mem-initializer ...[opt] , mem-initializer-list
3496 /// \endverbatim
3497 void ParseConstructorInitializer(Decl *ConstructorDecl);
3498
3499 /// ParseMemInitializer - Parse a C++ member initializer, which is
3500 /// part of a constructor initializer that explicitly initializes one
3501 /// member or base class (C++ [class.base.init]). See
3502 /// ParseConstructorInitializer for an example.
3503 ///
3504 /// \verbatim
3505 /// [C++] mem-initializer:
3506 /// mem-initializer-id '(' expression-list[opt] ')'
3507 /// [C++0x] mem-initializer-id braced-init-list
3508 ///
3509 /// [C++] mem-initializer-id:
3510 /// '::'[opt] nested-name-specifier[opt] class-name
3511 /// identifier
3512 /// \endverbatim
3513 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3514
3515 /// If the given declarator has any parts for which parsing has to be
3516 /// delayed, e.g., default arguments or an exception-specification, create a
3517 /// late-parsed method declaration record to handle the parsing at the end of
3518 /// the class definition.
3519 void HandleMemberFunctionDeclDelays(Declarator &DeclaratorInfo,
3520 Decl *ThisDecl);
3521
3522 //===--------------------------------------------------------------------===//
3523 // C++ 10: Derived classes [class.derived]
3524
3525 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
3526 /// class name or decltype-specifier. Note that we only check that the result
3527 /// names a type; semantic analysis will need to verify that the type names a
3528 /// class. The result is either a type or null, depending on whether a type
3529 /// name was found.
3530 ///
3531 /// \verbatim
3532 /// base-type-specifier: [C++11 class.derived]
3533 /// class-or-decltype
3534 /// class-or-decltype: [C++11 class.derived]
3535 /// nested-name-specifier[opt] class-name
3536 /// decltype-specifier
3537 /// class-name: [C++ class.name]
3538 /// identifier
3539 /// simple-template-id
3540 /// \endverbatim
3541 ///
3542 /// In C++98, instead of base-type-specifier, we have:
3543 ///
3544 /// \verbatim
3545 /// ::[opt] nested-name-specifier[opt] class-name
3546 /// \endverbatim
3547 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3548 SourceLocation &EndLocation);
3549
3550 /// ParseBaseClause - Parse the base-clause of a C++ class [C++
3551 /// class.derived].
3552 ///
3553 /// \verbatim
3554 /// base-clause : [C++ class.derived]
3555 /// ':' base-specifier-list
3556 /// base-specifier-list:
3557 /// base-specifier '...'[opt]
3558 /// base-specifier-list ',' base-specifier '...'[opt]
3559 /// \endverbatim
3560 void ParseBaseClause(Decl *ClassDecl);
3561
3562 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
3563 /// one entry in the base class list of a class specifier, for example:
3564 /// class foo : public bar, virtual private baz {
3565 /// 'public bar' and 'virtual private baz' are each base-specifiers.
3566 ///
3567 /// \verbatim
3568 /// base-specifier: [C++ class.derived]
3569 /// attribute-specifier-seq[opt] base-type-specifier
3570 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
3571 /// base-type-specifier
3572 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
3573 /// base-type-specifier
3574 /// \endverbatim
3575 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3576
3577 /// getAccessSpecifierIfPresent - Determine whether the next token is
3578 /// a C++ access-specifier.
3579 ///
3580 /// \verbatim
3581 /// access-specifier: [C++ class.derived]
3582 /// 'private'
3583 /// 'protected'
3584 /// 'public'
3585 /// \endverbatim
3586 AccessSpecifier getAccessSpecifierIfPresent() const;
3587
3588 bool isCXX2CTriviallyRelocatableKeyword(Token Tok) const;
3589 bool isCXX2CTriviallyRelocatableKeyword() const;
3590 void ParseCXX2CTriviallyRelocatableSpecifier(SourceLocation &TRS);
3591
3592 bool isCXX2CReplaceableKeyword(Token Tok) const;
3593 bool isCXX2CReplaceableKeyword() const;
3594 void ParseCXX2CReplaceableSpecifier(SourceLocation &MRS);
3595
3596 /// 'final', a C++26 'trivially_relocatable_if_eligible',
3597 /// 'replaceable_if_eligible', or Microsoft 'sealed' or 'abstract' contextual
3598 /// keyword.
3599 bool isClassCompatibleKeyword(Token Tok) const;
3600
3601 void ParseMicrosoftRootSignatureAttributeArgs(ParsedAttributes &Attrs);
3602
3603 ///@}
3604
3605 //
3606 //
3607 // -------------------------------------------------------------------------
3608 //
3609 //
3610
3611 /// \name Expressions
3612 /// Implementations are in ParseExpr.cpp
3613 ///@{
3614
3615public:
3616 friend class OffsetOfStateRAIIObject;
3617
3618 typedef Sema::FullExprArg FullExprArg;
3619
3620 //===--------------------------------------------------------------------===//
3621 // C99 6.5: Expressions.
3622
3623 /// Simple precedence-based parser for binary/ternary operators.
3624 ///
3625 /// Note: we diverge from the C99 grammar when parsing the
3626 /// assignment-expression production. C99 specifies that the LHS of an
3627 /// assignment operator should be parsed as a unary-expression, but
3628 /// consistency dictates that it be a conditional-expession. In practice, the
3629 /// important thing here is that the LHS of an assignment has to be an
3630 /// l-value, which productions between unary-expression and
3631 /// conditional-expression don't produce. Because we want consistency, we
3632 /// parse the LHS as a conditional-expression, then check for l-value-ness in
3633 /// semantic analysis stages.
3634 ///
3635 /// \verbatim
3636 /// pm-expression: [C++ 5.5]
3637 /// cast-expression
3638 /// pm-expression '.*' cast-expression
3639 /// pm-expression '->*' cast-expression
3640 ///
3641 /// multiplicative-expression: [C99 6.5.5]
3642 /// Note: in C++, apply pm-expression instead of cast-expression
3643 /// cast-expression
3644 /// multiplicative-expression '*' cast-expression
3645 /// multiplicative-expression '/' cast-expression
3646 /// multiplicative-expression '%' cast-expression
3647 ///
3648 /// additive-expression: [C99 6.5.6]
3649 /// multiplicative-expression
3650 /// additive-expression '+' multiplicative-expression
3651 /// additive-expression '-' multiplicative-expression
3652 ///
3653 /// shift-expression: [C99 6.5.7]
3654 /// additive-expression
3655 /// shift-expression '<<' additive-expression
3656 /// shift-expression '>>' additive-expression
3657 ///
3658 /// compare-expression: [C++20 expr.spaceship]
3659 /// shift-expression
3660 /// compare-expression '<=>' shift-expression
3661 ///
3662 /// relational-expression: [C99 6.5.8]
3663 /// compare-expression
3664 /// relational-expression '<' compare-expression
3665 /// relational-expression '>' compare-expression
3666 /// relational-expression '<=' compare-expression
3667 /// relational-expression '>=' compare-expression
3668 ///
3669 /// equality-expression: [C99 6.5.9]
3670 /// relational-expression
3671 /// equality-expression '==' relational-expression
3672 /// equality-expression '!=' relational-expression
3673 ///
3674 /// AND-expression: [C99 6.5.10]
3675 /// equality-expression
3676 /// AND-expression '&' equality-expression
3677 ///
3678 /// exclusive-OR-expression: [C99 6.5.11]
3679 /// AND-expression
3680 /// exclusive-OR-expression '^' AND-expression
3681 ///
3682 /// inclusive-OR-expression: [C99 6.5.12]
3683 /// exclusive-OR-expression
3684 /// inclusive-OR-expression '|' exclusive-OR-expression
3685 ///
3686 /// logical-AND-expression: [C99 6.5.13]
3687 /// inclusive-OR-expression
3688 /// logical-AND-expression '&&' inclusive-OR-expression
3689 ///
3690 /// logical-OR-expression: [C99 6.5.14]
3691 /// logical-AND-expression
3692 /// logical-OR-expression '||' logical-AND-expression
3693 ///
3694 /// conditional-expression: [C99 6.5.15]
3695 /// logical-OR-expression
3696 /// logical-OR-expression '?' expression ':' conditional-expression
3697 /// [GNU] logical-OR-expression '?' ':' conditional-expression
3698 /// [C++] the third operand is an assignment-expression
3699 ///
3700 /// assignment-expression: [C99 6.5.16]
3701 /// conditional-expression
3702 /// unary-expression assignment-operator assignment-expression
3703 /// [C++] throw-expression [C++ 15]
3704 ///
3705 /// assignment-operator: one of
3706 /// = *= /= %= += -= <<= >>= &= ^= |=
3707 ///
3708 /// expression: [C99 6.5.17]
3709 /// assignment-expression ...[opt]
3710 /// expression ',' assignment-expression ...[opt]
3711 /// \endverbatim
3712 ExprResult
3713 ParseExpression(TypeCastState isTypeCast = TypeCastState::NotTypeCast);
3714
3715 ExprResult ParseConstantExpressionInExprEvalContext(
3716 TypeCastState isTypeCast = TypeCastState::NotTypeCast);
3717 ExprResult ParseConstantExpression();
3718 ExprResult ParseArrayBoundExpression();
3719 ExprResult ParseCaseExpression(SourceLocation CaseLoc);
3720
3721 /// Parse a constraint-expression.
3722 ///
3723 /// \verbatim
3724 /// constraint-expression: C++2a[temp.constr.decl]p1
3725 /// logical-or-expression
3726 /// \endverbatim
3727 ExprResult ParseConstraintExpression();
3728
3729 /// \brief Parse a constraint-logical-and-expression.
3730 ///
3731 /// \verbatim
3732 /// C++2a[temp.constr.decl]p1
3733 /// constraint-logical-and-expression:
3734 /// primary-expression
3735 /// constraint-logical-and-expression '&&' primary-expression
3736 ///
3737 /// \endverbatim
3738 ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
3739
3740 /// \brief Parse a constraint-logical-or-expression.
3741 ///
3742 /// \verbatim
3743 /// C++2a[temp.constr.decl]p1
3744 /// constraint-logical-or-expression:
3745 /// constraint-logical-and-expression
3746 /// constraint-logical-or-expression '||'
3747 /// constraint-logical-and-expression
3748 ///
3749 /// \endverbatim
3750 ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
3751
3752 /// Parse an expr that doesn't include (top-level) commas.
3753 ExprResult ParseAssignmentExpression(
3754 TypeCastState isTypeCast = TypeCastState::NotTypeCast);
3755
3756 ExprResult ParseConditionalExpression();
3757
3758 /// ParseStringLiteralExpression - This handles the various token types that
3759 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
3760 /// translation phase #6].
3761 ///
3762 /// \verbatim
3763 /// primary-expression: [C99 6.5.1]
3764 /// string-literal
3765 /// \endverbatim
3766 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
3767 ExprResult ParseUnevaluatedStringLiteralExpression();
3768
3769private:
3770 /// Whether the '>' token acts as an operator or not. This will be
3771 /// true except when we are parsing an expression within a C++
3772 /// template argument list, where the '>' closes the template
3773 /// argument list.
3774 bool GreaterThanIsOperator;
3775
3776 // C++ type trait keywords that can be reverted to identifiers and still be
3777 // used as type traits.
3778 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
3779
3780 OffsetOfKind OffsetOfState = OffsetOfKind::Outside;
3781
3782 /// The location of the expression statement that is being parsed right now.
3783 /// Used to determine if an expression that is being parsed is a statement or
3784 /// just a regular sub-expression.
3785 SourceLocation ExprStatementTokLoc;
3786
3787 /// Checks if the \p Level is valid for use in a fold expression.
3788 bool isFoldOperator(prec::Level Level) const;
3789
3790 /// Checks if the \p Kind is a valid operator for fold expressions.
3791 bool isFoldOperator(tok::TokenKind Kind) const;
3792
3793 /// We have just started parsing the definition of a new class,
3794 /// so push that class onto our stack of classes that is currently
3795 /// being parsed.
3796 Sema::ParsingClassState
3797 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
3798
3799 /// Deallocate the given parsed class and all of its nested
3800 /// classes.
3801 void DeallocateParsedClasses(ParsingClass *Class);
3802
3803 /// Pop the top class of the stack of classes that are
3804 /// currently being parsed.
3805 ///
3806 /// This routine should be called when we have finished parsing the
3807 /// definition of a class, but have not yet popped the Scope
3808 /// associated with the class's definition.
3809 void PopParsingClass(Sema::ParsingClassState);
3810
3811 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral,
3812 bool Unevaluated);
3813
3814 /// This routine is called when the '@' is seen and consumed.
3815 /// Current token is an Identifier and is not a 'try'. This
3816 /// routine is necessary to disambiguate \@try-statement from,
3817 /// for example, \@encode-expression.
3818 ///
3819 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
3820
3821 /// This routine is called when a leading '__extension__' is seen and
3822 /// consumed. This is necessary because the token gets consumed in the
3823 /// process of disambiguating between an expression and a declaration.
3824 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
3825
3826 /// Parse a binary expression that starts with \p LHS and has a
3827 /// precedence of at least \p MinPrec.
3828 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec);
3829
3830 bool isRevertibleTypeTrait(const IdentifierInfo *Id,
3831 clang::tok::TokenKind *Kind = nullptr);
3832
3833 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
3834 /// a unary-expression.
3835 ///
3836 /// \p isAddressOfOperand exists because an id-expression that is the operand
3837 /// of address-of gets special treatment due to member pointers. NotCastExpr
3838 /// is set to true if the token is not the start of a cast-expression, and no
3839 /// diagnostic is emitted in this case and no tokens are consumed.
3840 ///
3841 /// \verbatim
3842 /// cast-expression: [C99 6.5.4]
3843 /// unary-expression
3844 /// '(' type-name ')' cast-expression
3845 ///
3846 /// unary-expression: [C99 6.5.3]
3847 /// postfix-expression
3848 /// '++' unary-expression
3849 /// '--' unary-expression
3850 /// [Coro] 'co_await' cast-expression
3851 /// unary-operator cast-expression
3852 /// 'sizeof' unary-expression
3853 /// 'sizeof' '(' type-name ')'
3854 /// [C++11] 'sizeof' '...' '(' identifier ')'
3855 /// [GNU] '__alignof' unary-expression
3856 /// [GNU] '__alignof' '(' type-name ')'
3857 /// [C11] '_Alignof' '(' type-name ')'
3858 /// [C++11] 'alignof' '(' type-id ')'
3859 /// [C2y] '_Countof' unary-expression
3860 /// [C2y] '_Countof' '(' type-name ')'
3861 /// [GNU] '&&' identifier
3862 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
3863 /// [C++] new-expression
3864 /// [C++] delete-expression
3865 ///
3866 /// unary-operator: one of
3867 /// '&' '*' '+' '-' '~' '!'
3868 /// [GNU] '__extension__' '__real' '__imag'
3869 ///
3870 /// primary-expression: [C99 6.5.1]
3871 /// [C99] identifier
3872 /// [C++] id-expression
3873 /// constant
3874 /// string-literal
3875 /// [C++] boolean-literal [C++ 2.13.5]
3876 /// [C++11] 'nullptr' [C++11 2.14.7]
3877 /// [C++11] user-defined-literal
3878 /// '(' expression ')'
3879 /// [C11] generic-selection
3880 /// [C++2a] requires-expression
3881 /// '__func__' [C99 6.4.2.2]
3882 /// [GNU] '__FUNCTION__'
3883 /// [MS] '__FUNCDNAME__'
3884 /// [MS] 'L__FUNCTION__'
3885 /// [MS] '__FUNCSIG__'
3886 /// [MS] 'L__FUNCSIG__'
3887 /// [GNU] '__PRETTY_FUNCTION__'
3888 /// [GNU] '(' compound-statement ')'
3889 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
3890 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
3891 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
3892 /// assign-expr ')'
3893 /// [GNU] '__builtin_FILE' '(' ')'
3894 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
3895 /// [GNU] '__builtin_FUNCTION' '(' ')'
3896 /// [MS] '__builtin_FUNCSIG' '(' ')'
3897 /// [GNU] '__builtin_LINE' '(' ')'
3898 /// [CLANG] '__builtin_COLUMN' '(' ')'
3899 /// [GNU] '__builtin_source_location' '(' ')'
3900 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
3901 /// [GNU] '__null'
3902 /// [OBJC] '[' objc-message-expr ']'
3903 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
3904 /// [OBJC] '\@protocol' '(' identifier ')'
3905 /// [OBJC] '\@encode' '(' type-name ')'
3906 /// [OBJC] objc-string-literal
3907 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
3908 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
3909 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
3910 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
3911 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3912 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3913 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3914 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3915 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
3916 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
3917 /// [C++] 'this' [C++ 9.3.2]
3918 /// [G++] unary-type-trait '(' type-id ')'
3919 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
3920 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
3921 /// [clang] '^' block-literal
3922 ///
3923 /// constant: [C99 6.4.4]
3924 /// integer-constant
3925 /// floating-constant
3926 /// enumeration-constant -> identifier
3927 /// character-constant
3928 ///
3929 /// id-expression: [C++ 5.1]
3930 /// unqualified-id
3931 /// qualified-id
3932 ///
3933 /// unqualified-id: [C++ 5.1]
3934 /// identifier
3935 /// operator-function-id
3936 /// conversion-function-id
3937 /// '~' class-name
3938 /// template-id
3939 ///
3940 /// new-expression: [C++ 5.3.4]
3941 /// '::'[opt] 'new' new-placement[opt] new-type-id
3942 /// new-initializer[opt]
3943 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3944 /// new-initializer[opt]
3945 ///
3946 /// delete-expression: [C++ 5.3.5]
3947 /// '::'[opt] 'delete' cast-expression
3948 /// '::'[opt] 'delete' '[' ']' cast-expression
3949 ///
3950 /// [GNU/Embarcadero] unary-type-trait:
3951 /// '__is_arithmetic'
3952 /// '__is_floating_point'
3953 /// '__is_integral'
3954 /// '__is_lvalue_expr'
3955 /// '__is_rvalue_expr'
3956 /// '__is_complete_type'
3957 /// '__is_void'
3958 /// '__is_array'
3959 /// '__is_function'
3960 /// '__is_reference'
3961 /// '__is_lvalue_reference'
3962 /// '__is_rvalue_reference'
3963 /// '__is_fundamental'
3964 /// '__is_object'
3965 /// '__is_scalar'
3966 /// '__is_compound'
3967 /// '__is_pointer'
3968 /// '__is_member_object_pointer'
3969 /// '__is_member_function_pointer'
3970 /// '__is_member_pointer'
3971 /// '__is_const'
3972 /// '__is_volatile'
3973 /// '__is_trivial'
3974 /// '__is_standard_layout'
3975 /// '__is_signed'
3976 /// '__is_unsigned'
3977 ///
3978 /// [GNU] unary-type-trait:
3979 /// '__has_nothrow_assign'
3980 /// '__has_nothrow_copy'
3981 /// '__has_nothrow_constructor'
3982 /// '__has_trivial_assign' [TODO]
3983 /// '__has_trivial_copy' [TODO]
3984 /// '__has_trivial_constructor'
3985 /// '__has_trivial_destructor'
3986 /// '__has_virtual_destructor'
3987 /// '__is_abstract' [TODO]
3988 /// '__is_class'
3989 /// '__is_empty' [TODO]
3990 /// '__is_enum'
3991 /// '__is_final'
3992 /// '__is_pod'
3993 /// '__is_polymorphic'
3994 /// '__is_sealed' [MS]
3995 /// '__is_trivial'
3996 /// '__is_union'
3997 /// '__has_unique_object_representations'
3998 ///
3999 /// [Clang] unary-type-trait:
4000 /// '__is_aggregate'
4001 /// '__trivially_copyable'
4002 ///
4003 /// binary-type-trait:
4004 /// [GNU] '__is_base_of'
4005 /// [MS] '__is_convertible_to'
4006 /// '__is_convertible'
4007 /// '__is_same'
4008 ///
4009 /// [Embarcadero] array-type-trait:
4010 /// '__array_rank'
4011 /// '__array_extent'
4012 ///
4013 /// [Embarcadero] expression-trait:
4014 /// '__is_lvalue_expr'
4015 /// '__is_rvalue_expr'
4016 /// \endverbatim
4017 ///
4018 ExprResult ParseCastExpression(CastParseKind ParseKind,
4019 bool isAddressOfOperand, bool &NotCastExpr,
4020 TypeCastState isTypeCast,
4021 bool isVectorLiteral = false,
4022 bool *NotPrimaryExpression = nullptr);
4023 ExprResult
4024 ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false,
4025 TypeCastState isTypeCast = TypeCastState::NotTypeCast,
4026 bool isVectorLiteral = false,
4027 bool *NotPrimaryExpression = nullptr);
4028
4029 /// Returns true if the next token cannot start an expression.
4030 bool isNotExpressionStart();
4031
4032 /// Returns true if the next token would start a postfix-expression
4033 /// suffix.
4034 bool isPostfixExpressionSuffixStart() {
4035 tok::TokenKind K = Tok.getKind();
4036 return (K == tok::l_square || K == tok::l_paren || K == tok::period ||
4037 K == tok::arrow || K == tok::plusplus || K == tok::minusminus);
4038 }
4039
4040 /// Once the leading part of a postfix-expression is parsed, this
4041 /// method parses any suffixes that apply.
4042 ///
4043 /// \verbatim
4044 /// postfix-expression: [C99 6.5.2]
4045 /// primary-expression
4046 /// postfix-expression '[' expression ']'
4047 /// postfix-expression '[' braced-init-list ']'
4048 /// postfix-expression '[' expression-list [opt] ']' [C++23 12.4.5]
4049 /// postfix-expression '(' argument-expression-list[opt] ')'
4050 /// postfix-expression '.' identifier
4051 /// postfix-expression '->' identifier
4052 /// postfix-expression '++'
4053 /// postfix-expression '--'
4054 /// '(' type-name ')' '{' initializer-list '}'
4055 /// '(' type-name ')' '{' initializer-list ',' '}'
4056 ///
4057 /// argument-expression-list: [C99 6.5.2]
4058 /// argument-expression ...[opt]
4059 /// argument-expression-list ',' assignment-expression ...[opt]
4060 /// \endverbatim
4061 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
4062
4063 /// Parse a sizeof or alignof expression.
4064 ///
4065 /// \verbatim
4066 /// unary-expression: [C99 6.5.3]
4067 /// 'sizeof' unary-expression
4068 /// 'sizeof' '(' type-name ')'
4069 /// [C++11] 'sizeof' '...' '(' identifier ')'
4070 /// [Clang] '__datasizeof' unary-expression
4071 /// [Clang] '__datasizeof' '(' type-name ')'
4072 /// [GNU] '__alignof' unary-expression
4073 /// [GNU] '__alignof' '(' type-name ')'
4074 /// [C11] '_Alignof' '(' type-name ')'
4075 /// [C++11] 'alignof' '(' type-id ')'
4076 /// [C2y] '_Countof' unary-expression
4077 /// [C2y] '_Countof' '(' type-name ')'
4078 /// \endverbatim
4079 ExprResult ParseUnaryExprOrTypeTraitExpression();
4080
4081 /// ParseBuiltinPrimaryExpression
4082 ///
4083 /// \verbatim
4084 /// primary-expression: [C99 6.5.1]
4085 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
4086 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
4087 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
4088 /// assign-expr ')'
4089 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
4090 /// [GNU] '__builtin_FILE' '(' ')'
4091 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
4092 /// [GNU] '__builtin_FUNCTION' '(' ')'
4093 /// [MS] '__builtin_FUNCSIG' '(' ')'
4094 /// [GNU] '__builtin_LINE' '(' ')'
4095 /// [CLANG] '__builtin_COLUMN' '(' ')'
4096 /// [GNU] '__builtin_source_location' '(' ')'
4097 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
4098 ///
4099 /// [GNU] offsetof-member-designator:
4100 /// [GNU] identifier
4101 /// [GNU] offsetof-member-designator '.' identifier
4102 /// [GNU] offsetof-member-designator '[' expression ']'
4103 /// \endverbatim
4104 ExprResult ParseBuiltinPrimaryExpression();
4105
4106 /// Parse a __builtin_sycl_unique_stable_name expression. Accepts a type-id
4107 /// as a parameter.
4108 ExprResult ParseSYCLUniqueStableNameExpression();
4109
4110 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
4111 /// vec_step and we are at the start of an expression or a parenthesized
4112 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
4113 /// expression (isCastExpr == false) or the type (isCastExpr == true).
4114 ///
4115 /// \verbatim
4116 /// unary-expression: [C99 6.5.3]
4117 /// 'sizeof' unary-expression
4118 /// 'sizeof' '(' type-name ')'
4119 /// [Clang] '__datasizeof' unary-expression
4120 /// [Clang] '__datasizeof' '(' type-name ')'
4121 /// [GNU] '__alignof' unary-expression
4122 /// [GNU] '__alignof' '(' type-name ')'
4123 /// [C11] '_Alignof' '(' type-name ')'
4124 /// [C++0x] 'alignof' '(' type-id ')'
4125 ///
4126 /// [GNU] typeof-specifier:
4127 /// typeof ( expressions )
4128 /// typeof ( type-name )
4129 /// [GNU/C++] typeof unary-expression
4130 /// [C23] typeof-specifier:
4131 /// typeof '(' typeof-specifier-argument ')'
4132 /// typeof_unqual '(' typeof-specifier-argument ')'
4133 ///
4134 /// typeof-specifier-argument:
4135 /// expression
4136 /// type-name
4137 ///
4138 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
4139 /// vec_step ( expressions )
4140 /// vec_step ( type-name )
4141 /// \endverbatim
4142 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
4143 bool &isCastExpr,
4144 ParsedType &CastTy,
4145 SourceRange &CastRange);
4146
4147 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
4148 ///
4149 /// \verbatim
4150 /// argument-expression-list:
4151 /// assignment-expression
4152 /// argument-expression-list , assignment-expression
4153 ///
4154 /// [C++] expression-list:
4155 /// [C++] assignment-expression
4156 /// [C++] expression-list , assignment-expression
4157 ///
4158 /// [C++0x] expression-list:
4159 /// [C++0x] initializer-list
4160 ///
4161 /// [C++0x] initializer-list
4162 /// [C++0x] initializer-clause ...[opt]
4163 /// [C++0x] initializer-list , initializer-clause ...[opt]
4164 ///
4165 /// [C++0x] initializer-clause:
4166 /// [C++0x] assignment-expression
4167 /// [C++0x] braced-init-list
4168 /// \endverbatim
4169 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
4170 llvm::function_ref<void()> ExpressionStarts =
4171 llvm::function_ref<void()>(),
4172 bool FailImmediatelyOnInvalidExpr = false,
4173 bool EarlyTypoCorrection = false);
4174
4175 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
4176 /// used for misc language extensions.
4177 ///
4178 /// \verbatim
4179 /// simple-expression-list:
4180 /// assignment-expression
4181 /// simple-expression-list , assignment-expression
4182 /// \endverbatim
4183 bool ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs);
4184
4185 /// ParseParenExpression - This parses the unit that starts with a '(' token,
4186 /// based on what is allowed by ExprType. The actual thing parsed is returned
4187 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed
4188 /// type, not the parsed cast-expression.
4189 ///
4190 /// \verbatim
4191 /// primary-expression: [C99 6.5.1]
4192 /// '(' expression ')'
4193 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
4194 /// postfix-expression: [C99 6.5.2]
4195 /// '(' type-name ')' '{' initializer-list '}'
4196 /// '(' type-name ')' '{' initializer-list ',' '}'
4197 /// cast-expression: [C99 6.5.4]
4198 /// '(' type-name ')' cast-expression
4199 /// [ARC] bridged-cast-expression
4200 /// [ARC] bridged-cast-expression:
4201 /// (__bridge type-name) cast-expression
4202 /// (__bridge_transfer type-name) cast-expression
4203 /// (__bridge_retained type-name) cast-expression
4204 /// fold-expression: [C++1z]
4205 /// '(' cast-expression fold-operator '...' ')'
4206 /// '(' '...' fold-operator cast-expression ')'
4207 /// '(' cast-expression fold-operator '...'
4208 /// fold-operator cast-expression ')'
4209 /// [OPENMP] Array shaping operation
4210 /// '(' '[' expression ']' { '[' expression ']' } cast-expression
4211 /// \endverbatim
4212 ExprResult ParseParenExpression(ParenParseOption &ExprType,
4213 bool stopIfCastExpr, bool isTypeCast,
4214 ParsedType &CastTy,
4215 SourceLocation &RParenLoc);
4216
4217 /// ParseCompoundLiteralExpression - We have parsed the parenthesized
4218 /// type-name and we are at the left brace.
4219 ///
4220 /// \verbatim
4221 /// postfix-expression: [C99 6.5.2]
4222 /// '(' type-name ')' '{' initializer-list '}'
4223 /// '(' type-name ')' '{' initializer-list ',' '}'
4224 /// \endverbatim
4225 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
4226 SourceLocation LParenLoc,
4227 SourceLocation RParenLoc);
4228
4229 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
4230 /// [C11 6.5.1.1].
4231 ///
4232 /// \verbatim
4233 /// generic-selection:
4234 /// _Generic ( assignment-expression , generic-assoc-list )
4235 /// generic-assoc-list:
4236 /// generic-association
4237 /// generic-assoc-list , generic-association
4238 /// generic-association:
4239 /// type-name : assignment-expression
4240 /// default : assignment-expression
4241 /// \endverbatim
4242 ///
4243 /// As an extension, Clang also accepts:
4244 /// \verbatim
4245 /// generic-selection:
4246 /// _Generic ( type-name, generic-assoc-list )
4247 /// \endverbatim
4248 ExprResult ParseGenericSelectionExpression();
4249
4250 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
4251 ///
4252 /// '__objc_yes'
4253 /// '__objc_no'
4254 ExprResult ParseObjCBoolLiteral();
4255
4256 /// Parse A C++1z fold-expression after the opening paren and optional
4257 /// left-hand-side expression.
4258 ///
4259 /// \verbatim
4260 /// fold-expression:
4261 /// ( cast-expression fold-operator ... )
4262 /// ( ... fold-operator cast-expression )
4263 /// ( cast-expression fold-operator ... fold-operator cast-expression )
4264 /// \endverbatim
4265 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
4266
4267 void injectEmbedTokens();
4268
4269 //===--------------------------------------------------------------------===//
4270 // clang Expressions
4271
4272 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
4273 /// like ^(int x){ return x+1; }
4274 ///
4275 /// \verbatim
4276 /// block-literal:
4277 /// [clang] '^' block-args[opt] compound-statement
4278 /// [clang] '^' block-id compound-statement
4279 /// [clang] block-args:
4280 /// [clang] '(' parameter-list ')'
4281 /// \endverbatim
4282 ExprResult ParseBlockLiteralExpression(); // ^{...}
4283
4284 /// Parse an assignment expression where part of an Objective-C message
4285 /// send has already been parsed.
4286 ///
4287 /// In this case \p LBracLoc indicates the location of the '[' of the message
4288 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
4289 /// the receiver of the message.
4290 ///
4291 /// Since this handles full assignment-expression's, it handles postfix
4292 /// expressions and other binary operators for these expressions as well.
4293 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
4294 SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType,
4295 Expr *ReceiverExpr);
4296
4297 /// Return true if we know that we are definitely looking at a
4298 /// decl-specifier, and isn't part of an expression such as a function-style
4299 /// cast. Return false if it's no a decl-specifier, or we're not sure.
4300 bool isKnownToBeDeclarationSpecifier() {
4301 if (getLangOpts().CPlusPlus)
4302 return isCXXDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No) ==
4303 TPResult::True;
4304 return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No, DisambiguatingWithExpression: true);
4305 }
4306
4307 /// Checks whether the current tokens form a type-id or an expression for the
4308 /// purposes of use as the initial operand to a generic selection expression.
4309 /// This requires special handling in C++ because it accepts either a type or
4310 /// an expression, and we need to disambiguate which is which. However, we
4311 /// cannot use the same logic as we've used for sizeof expressions, because
4312 /// that logic relies on the operator only accepting a single argument,
4313 /// whereas _Generic accepts a list of arguments.
4314 bool isTypeIdForGenericSelection() {
4315 if (getLangOpts().CPlusPlus) {
4316 bool isAmbiguous;
4317 return isCXXTypeId(Context: TentativeCXXTypeIdContext::AsGenericSelectionArgument,
4318 isAmbiguous);
4319 }
4320 return isTypeSpecifierQualifier();
4321 }
4322
4323 /// Checks if the current tokens form type-id or expression.
4324 /// It is similar to isTypeIdInParens but does not suppose that type-id
4325 /// is in parenthesis.
4326 bool isTypeIdUnambiguously() {
4327 if (getLangOpts().CPlusPlus) {
4328 bool isAmbiguous;
4329 return isCXXTypeId(Context: TentativeCXXTypeIdContext::Unambiguous, isAmbiguous);
4330 }
4331 return isTypeSpecifierQualifier();
4332 }
4333
4334 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
4335 ///
4336 /// \verbatim
4337 /// [clang] block-id:
4338 /// [clang] specifier-qualifier-list block-declarator
4339 /// \endverbatim
4340 void ParseBlockId(SourceLocation CaretLoc);
4341
4342 /// Parse availability query specification.
4343 ///
4344 /// \verbatim
4345 /// availability-spec:
4346 /// '*'
4347 /// identifier version-tuple
4348 /// \endverbatim
4349 std::optional<AvailabilitySpec> ParseAvailabilitySpec();
4350 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
4351
4352 /// Tries to parse cast part of OpenMP array shaping operation:
4353 /// \verbatim
4354 /// '[' expression ']' { '[' expression ']' } ')'
4355 /// \endverbatim
4356 bool tryParseOpenMPArrayShapingCastPart();
4357
4358 ExprResult ParseBuiltinPtrauthTypeDiscriminator();
4359
4360 ///@}
4361
4362 //
4363 //
4364 // -------------------------------------------------------------------------
4365 //
4366 //
4367
4368 /// \name C++ Expressions
4369 /// Implementations are in ParseExprCXX.cpp
4370 ///@{
4371
4372public:
4373 /// Parse a C++ unqualified-id (or a C identifier), which describes the
4374 /// name of an entity.
4375 ///
4376 /// \verbatim
4377 /// unqualified-id: [C++ expr.prim.general]
4378 /// identifier
4379 /// operator-function-id
4380 /// conversion-function-id
4381 /// [C++0x] literal-operator-id [TODO]
4382 /// ~ class-name
4383 /// template-id
4384 /// \endverbatim
4385 ///
4386 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
4387 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
4388 ///
4389 /// \param ObjectType if this unqualified-id occurs within a member access
4390 /// expression, the type of the base object whose member is being accessed.
4391 ///
4392 /// \param ObjectHadErrors if this unqualified-id occurs within a member
4393 /// access expression, indicates whether the original subexpressions had any
4394 /// errors. When true, diagnostics for missing 'template' keyword will be
4395 /// supressed.
4396 ///
4397 /// \param EnteringContext whether we are entering the scope of the
4398 /// nested-name-specifier.
4399 ///
4400 /// \param AllowDestructorName whether we allow parsing of a destructor name.
4401 ///
4402 /// \param AllowConstructorName whether we allow parsing a constructor name.
4403 ///
4404 /// \param AllowDeductionGuide whether we allow parsing a deduction guide
4405 /// name.
4406 ///
4407 /// \param Result on a successful parse, contains the parsed unqualified-id.
4408 ///
4409 /// \returns true if parsing fails, false otherwise.
4410 bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
4411 bool ObjectHadErrors, bool EnteringContext,
4412 bool AllowDestructorName, bool AllowConstructorName,
4413 bool AllowDeductionGuide,
4414 SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
4415
4416private:
4417 /// ColonIsSacred - When this is false, we aggressively try to recover from
4418 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
4419 /// safe in case statements and a few other things. This is managed by the
4420 /// ColonProtectionRAIIObject RAII object.
4421 bool ColonIsSacred;
4422
4423 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
4424 /// parenthesized ambiguous type-id. This uses tentative parsing to
4425 /// disambiguate based on the context past the parens.
4426 ExprResult ParseCXXAmbiguousParenExpression(
4427 ParenParseOption &ExprType, ParsedType &CastTy,
4428 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
4429
4430 //===--------------------------------------------------------------------===//
4431 // C++ Expressions
4432 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
4433 Token &Replacement);
4434
4435 ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression);
4436 ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression);
4437
4438 /// ParseCXXIdExpression - Handle id-expression.
4439 ///
4440 /// \verbatim
4441 /// id-expression:
4442 /// unqualified-id
4443 /// qualified-id
4444 ///
4445 /// qualified-id:
4446 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
4447 /// '::' identifier
4448 /// '::' operator-function-id
4449 /// '::' template-id
4450 ///
4451 /// NOTE: The standard specifies that, for qualified-id, the parser does not
4452 /// expect:
4453 ///
4454 /// '::' conversion-function-id
4455 /// '::' '~' class-name
4456 /// \endverbatim
4457 ///
4458 /// This may cause a slight inconsistency on diagnostics:
4459 ///
4460 /// class C {};
4461 /// namespace A {}
4462 /// void f() {
4463 /// :: A :: ~ C(); // Some Sema error about using destructor with a
4464 /// // namespace.
4465 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
4466 /// }
4467 ///
4468 /// We simplify the parser a bit and make it work like:
4469 ///
4470 /// \verbatim
4471 /// qualified-id:
4472 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
4473 /// '::' unqualified-id
4474 /// \endverbatim
4475 ///
4476 /// That way Sema can handle and report similar errors for namespaces and the
4477 /// global scope.
4478 ///
4479 /// The isAddressOfOperand parameter indicates that this id-expression is a
4480 /// direct operand of the address-of operator. This is, besides member
4481 /// contexts, the only place where a qualified-id naming a non-static class
4482 /// member may appear.
4483 ///
4484 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
4485
4486 // Are the two tokens adjacent in the same source file?
4487 bool areTokensAdjacent(const Token &A, const Token &B);
4488
4489 // Check for '<::' which should be '< ::' instead of '[:' when following
4490 // a template name.
4491 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
4492 bool EnteringContext, IdentifierInfo &II,
4493 CXXScopeSpec &SS);
4494
4495 /// Parse global scope or nested-name-specifier if present.
4496 ///
4497 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
4498 /// may be preceded by '::'). Note that this routine will not parse ::new or
4499 /// ::delete; it will just leave them in the token stream.
4500 ///
4501 /// \verbatim
4502 /// '::'[opt] nested-name-specifier
4503 /// '::'
4504 ///
4505 /// nested-name-specifier:
4506 /// type-name '::'
4507 /// namespace-name '::'
4508 /// nested-name-specifier identifier '::'
4509 /// nested-name-specifier 'template'[opt] simple-template-id '::'
4510 /// \endverbatim
4511 ///
4512 ///
4513 /// \param SS the scope specifier that will be set to the parsed
4514 /// nested-name-specifier (or empty)
4515 ///
4516 /// \param ObjectType if this nested-name-specifier is being parsed following
4517 /// the "." or "->" of a member access expression, this parameter provides the
4518 /// type of the object whose members are being accessed.
4519 ///
4520 /// \param ObjectHadErrors if this unqualified-id occurs within a member
4521 /// access expression, indicates whether the original subexpressions had any
4522 /// errors. When true, diagnostics for missing 'template' keyword will be
4523 /// supressed.
4524 ///
4525 /// \param EnteringContext whether we will be entering into the context of
4526 /// the nested-name-specifier after parsing it.
4527 ///
4528 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
4529 /// indicates whether this nested-name-specifier may be part of a
4530 /// pseudo-destructor name. In this case, the flag will be set false
4531 /// if we don't actually end up parsing a destructor name. Moreover,
4532 /// if we do end up determining that we are parsing a destructor name,
4533 /// the last component of the nested-name-specifier is not parsed as
4534 /// part of the scope specifier.
4535 ///
4536 /// \param IsTypename If \c true, this nested-name-specifier is known to be
4537 /// part of a type name. This is used to improve error recovery.
4538 ///
4539 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
4540 /// filled in with the leading identifier in the last component of the
4541 /// nested-name-specifier, if any.
4542 ///
4543 /// \param OnlyNamespace If true, only considers namespaces in lookup.
4544 ///
4545 ///
4546 /// \returns true if there was an error parsing a scope specifier
4547 bool ParseOptionalCXXScopeSpecifier(
4548 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors,
4549 bool EnteringContext, bool *MayBePseudoDestructor = nullptr,
4550 bool IsTypename = false, const IdentifierInfo **LastII = nullptr,
4551 bool OnlyNamespace = false, bool InUsingDeclaration = false,
4552 bool Disambiguation = false);
4553
4554 //===--------------------------------------------------------------------===//
4555 // C++11 5.1.2: Lambda expressions
4556
4557 /// Result of tentatively parsing a lambda-introducer.
4558 enum class LambdaIntroducerTentativeParse {
4559 /// This appears to be a lambda-introducer, which has been fully parsed.
4560 Success,
4561 /// This is a lambda-introducer, but has not been fully parsed, and this
4562 /// function needs to be called again to parse it.
4563 Incomplete,
4564 /// This is definitely an Objective-C message send expression, rather than
4565 /// a lambda-introducer, attribute-specifier, or array designator.
4566 MessageSend,
4567 /// This is not a lambda-introducer.
4568 Invalid,
4569 };
4570
4571 /// ParseLambdaExpression - Parse a C++11 lambda expression.
4572 ///
4573 /// \verbatim
4574 /// lambda-expression:
4575 /// lambda-introducer lambda-declarator compound-statement
4576 /// lambda-introducer '<' template-parameter-list '>'
4577 /// requires-clause[opt] lambda-declarator compound-statement
4578 ///
4579 /// lambda-introducer:
4580 /// '[' lambda-capture[opt] ']'
4581 ///
4582 /// lambda-capture:
4583 /// capture-default
4584 /// capture-list
4585 /// capture-default ',' capture-list
4586 ///
4587 /// capture-default:
4588 /// '&'
4589 /// '='
4590 ///
4591 /// capture-list:
4592 /// capture
4593 /// capture-list ',' capture
4594 ///
4595 /// capture:
4596 /// simple-capture
4597 /// init-capture [C++1y]
4598 ///
4599 /// simple-capture:
4600 /// identifier
4601 /// '&' identifier
4602 /// 'this'
4603 ///
4604 /// init-capture: [C++1y]
4605 /// identifier initializer
4606 /// '&' identifier initializer
4607 ///
4608 /// lambda-declarator:
4609 /// lambda-specifiers [C++23]
4610 /// '(' parameter-declaration-clause ')' lambda-specifiers
4611 /// requires-clause[opt]
4612 ///
4613 /// lambda-specifiers:
4614 /// decl-specifier-seq[opt] noexcept-specifier[opt]
4615 /// attribute-specifier-seq[opt] trailing-return-type[opt]
4616 /// \endverbatim
4617 ///
4618 ExprResult ParseLambdaExpression();
4619
4620 /// Use lookahead and potentially tentative parsing to determine if we are
4621 /// looking at a C++11 lambda expression, and parse it if we are.
4622 ///
4623 /// If we are not looking at a lambda expression, returns ExprError().
4624 ExprResult TryParseLambdaExpression();
4625
4626 /// Parse a lambda introducer.
4627 /// \param Intro A LambdaIntroducer filled in with information about the
4628 /// contents of the lambda-introducer.
4629 /// \param Tentative If non-null, we are disambiguating between a
4630 /// lambda-introducer and some other construct. In this mode, we do not
4631 /// produce any diagnostics or take any other irreversible action
4632 /// unless we're sure that this is a lambda-expression.
4633 /// \return \c true if parsing (or disambiguation) failed with a diagnostic
4634 /// and the caller should bail out / recover.
4635 bool
4636 ParseLambdaIntroducer(LambdaIntroducer &Intro,
4637 LambdaIntroducerTentativeParse *Tentative = nullptr);
4638
4639 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
4640 /// expression.
4641 ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
4642
4643 //===--------------------------------------------------------------------===//
4644 // C++ 5.2p1: C++ Casts
4645
4646 /// ParseCXXCasts - This handles the various ways to cast expressions to
4647 /// another type.
4648 ///
4649 /// \verbatim
4650 /// postfix-expression: [C++ 5.2p1]
4651 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
4652 /// 'static_cast' '<' type-name '>' '(' expression ')'
4653 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
4654 /// 'const_cast' '<' type-name '>' '(' expression ')'
4655 /// \endverbatim
4656 ///
4657 /// C++ for OpenCL s2.3.1 adds:
4658 /// 'addrspace_cast' '<' type-name '>' '(' expression ')'
4659 ExprResult ParseCXXCasts();
4660
4661 /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
4662 ExprResult ParseBuiltinBitCast();
4663
4664 //===--------------------------------------------------------------------===//
4665 // C++ 5.2p1: C++ Type Identification
4666
4667 /// ParseCXXTypeid - This handles the C++ typeid expression.
4668 ///
4669 /// \verbatim
4670 /// postfix-expression: [C++ 5.2p1]
4671 /// 'typeid' '(' expression ')'
4672 /// 'typeid' '(' type-id ')'
4673 /// \endverbatim
4674 ///
4675 ExprResult ParseCXXTypeid();
4676
4677 //===--------------------------------------------------------------------===//
4678 // C++ : Microsoft __uuidof Expression
4679
4680 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
4681 ///
4682 /// \verbatim
4683 /// '__uuidof' '(' expression ')'
4684 /// '__uuidof' '(' type-id ')'
4685 /// \endverbatim
4686 ///
4687 ExprResult ParseCXXUuidof();
4688
4689 //===--------------------------------------------------------------------===//
4690 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
4691
4692 /// Parse a C++ pseudo-destructor expression after the base,
4693 /// . or -> operator, and nested-name-specifier have already been
4694 /// parsed. We're handling this fragment of the grammar:
4695 ///
4696 /// \verbatim
4697 /// postfix-expression: [C++2a expr.post]
4698 /// postfix-expression . template[opt] id-expression
4699 /// postfix-expression -> template[opt] id-expression
4700 ///
4701 /// id-expression:
4702 /// qualified-id
4703 /// unqualified-id
4704 ///
4705 /// qualified-id:
4706 /// nested-name-specifier template[opt] unqualified-id
4707 ///
4708 /// nested-name-specifier:
4709 /// type-name ::
4710 /// decltype-specifier :: FIXME: not implemented, but probably only
4711 /// allowed in C++ grammar by accident
4712 /// nested-name-specifier identifier ::
4713 /// nested-name-specifier template[opt] simple-template-id ::
4714 /// [...]
4715 ///
4716 /// unqualified-id:
4717 /// ~ type-name
4718 /// ~ decltype-specifier
4719 /// [...]
4720 /// \endverbatim
4721 ///
4722 /// ... where the all but the last component of the nested-name-specifier
4723 /// has already been parsed, and the base expression is not of a non-dependent
4724 /// class type.
4725 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
4726 tok::TokenKind OpKind, CXXScopeSpec &SS,
4727 ParsedType ObjectType);
4728
4729 //===--------------------------------------------------------------------===//
4730 // C++ 9.3.2: C++ 'this' pointer
4731
4732 /// ParseCXXThis - This handles the C++ 'this' pointer.
4733 ///
4734 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
4735 /// is a non-lvalue expression whose value is the address of the object for
4736 /// which the function is called.
4737 ExprResult ParseCXXThis();
4738
4739 //===--------------------------------------------------------------------===//
4740 // C++ 15: C++ Throw Expression
4741
4742 /// ParseThrowExpression - This handles the C++ throw expression.
4743 ///
4744 /// \verbatim
4745 /// throw-expression: [C++ 15]
4746 /// 'throw' assignment-expression[opt]
4747 /// \endverbatim
4748 ExprResult ParseThrowExpression();
4749
4750 //===--------------------------------------------------------------------===//
4751 // C++ 2.13.5: C++ Boolean Literals
4752
4753 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
4754 ///
4755 /// \verbatim
4756 /// boolean-literal: [C++ 2.13.5]
4757 /// 'true'
4758 /// 'false'
4759 /// \endverbatim
4760 ExprResult ParseCXXBoolLiteral();
4761
4762 //===--------------------------------------------------------------------===//
4763 // C++ 5.2.3: Explicit type conversion (functional notation)
4764
4765 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
4766 /// Can be interpreted either as function-style casting ("int(x)")
4767 /// or class type construction ("ClassType(x,y,z)")
4768 /// or creation of a value-initialized type ("int()").
4769 /// See [C++ 5.2.3].
4770 ///
4771 /// \verbatim
4772 /// postfix-expression: [C++ 5.2p1]
4773 /// simple-type-specifier '(' expression-list[opt] ')'
4774 /// [C++0x] simple-type-specifier braced-init-list
4775 /// typename-specifier '(' expression-list[opt] ')'
4776 /// [C++0x] typename-specifier braced-init-list
4777 /// \endverbatim
4778 ///
4779 /// In C++1z onwards, the type specifier can also be a template-name.
4780 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
4781
4782 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
4783 /// This should only be called when the current token is known to be part of
4784 /// simple-type-specifier.
4785 ///
4786 /// \verbatim
4787 /// simple-type-specifier:
4788 /// '::'[opt] nested-name-specifier[opt] type-name
4789 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
4790 /// char
4791 /// wchar_t
4792 /// bool
4793 /// short
4794 /// int
4795 /// long
4796 /// signed
4797 /// unsigned
4798 /// float
4799 /// double
4800 /// void
4801 /// [GNU] typeof-specifier
4802 /// [C++0x] auto [TODO]
4803 ///
4804 /// type-name:
4805 /// class-name
4806 /// enum-name
4807 /// typedef-name
4808 /// \endverbatim
4809 ///
4810 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
4811
4812 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
4813 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
4814 /// e.g., "const short int". Note that the DeclSpec is *not* finished
4815 /// by parsing the type-specifier-seq, because these sequences are
4816 /// typically followed by some form of declarator. Returns true and
4817 /// emits diagnostics if this is not a type-specifier-seq, false
4818 /// otherwise.
4819 ///
4820 /// \verbatim
4821 /// type-specifier-seq: [C++ 8.1]
4822 /// type-specifier type-specifier-seq[opt]
4823 /// \endverbatim
4824 ///
4825 bool ParseCXXTypeSpecifierSeq(
4826 DeclSpec &DS, DeclaratorContext Context = DeclaratorContext::TypeName);
4827
4828 //===--------------------------------------------------------------------===//
4829 // C++ 5.3.4 and 5.3.5: C++ new and delete
4830
4831 /// ParseExpressionListOrTypeId - Parse either an expression-list or a
4832 /// type-id. This ambiguity appears in the syntax of the C++ new operator.
4833 ///
4834 /// \verbatim
4835 /// new-expression:
4836 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4837 /// new-initializer[opt]
4838 ///
4839 /// new-placement:
4840 /// '(' expression-list ')'
4841 /// \endverbatim
4842 ///
4843 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr *> &Exprs,
4844 Declarator &D);
4845
4846 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
4847 /// passed to ParseDeclaratorInternal.
4848 ///
4849 /// \verbatim
4850 /// direct-new-declarator:
4851 /// '[' expression[opt] ']'
4852 /// direct-new-declarator '[' constant-expression ']'
4853 /// \endverbatim
4854 ///
4855 void ParseDirectNewDeclarator(Declarator &D);
4856
4857 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to
4858 /// allocate memory in a typesafe manner and call constructors.
4859 ///
4860 /// This method is called to parse the new expression after the optional ::
4861 /// has been already parsed. If the :: was present, "UseGlobal" is true and
4862 /// "Start" is its location. Otherwise, "Start" is the location of the 'new'
4863 /// token.
4864 ///
4865 /// \verbatim
4866 /// new-expression:
4867 /// '::'[opt] 'new' new-placement[opt] new-type-id
4868 /// new-initializer[opt]
4869 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4870 /// new-initializer[opt]
4871 ///
4872 /// new-placement:
4873 /// '(' expression-list ')'
4874 ///
4875 /// new-type-id:
4876 /// type-specifier-seq new-declarator[opt]
4877 /// [GNU] attributes type-specifier-seq new-declarator[opt]
4878 ///
4879 /// new-declarator:
4880 /// ptr-operator new-declarator[opt]
4881 /// direct-new-declarator
4882 ///
4883 /// new-initializer:
4884 /// '(' expression-list[opt] ')'
4885 /// [C++0x] braced-init-list
4886 /// \endverbatim
4887 ///
4888 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
4889
4890 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
4891 /// to free memory allocated by new.
4892 ///
4893 /// This method is called to parse the 'delete' expression after the optional
4894 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is
4895 /// true and "Start" is its location. Otherwise, "Start" is the location of
4896 /// the 'delete' token.
4897 ///
4898 /// \verbatim
4899 /// delete-expression:
4900 /// '::'[opt] 'delete' cast-expression
4901 /// '::'[opt] 'delete' '[' ']' cast-expression
4902 /// \endverbatim
4903 ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start);
4904
4905 //===--------------------------------------------------------------------===//
4906 // C++ if/switch/while/for condition expression.
4907
4908 /// ParseCXXCondition - if/switch/while condition expression.
4909 ///
4910 /// \verbatim
4911 /// condition:
4912 /// expression
4913 /// type-specifier-seq declarator '=' assignment-expression
4914 /// [C++11] type-specifier-seq declarator '=' initializer-clause
4915 /// [C++11] type-specifier-seq declarator braced-init-list
4916 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
4917 /// brace-or-equal-initializer
4918 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
4919 /// '=' assignment-expression
4920 /// \endverbatim
4921 ///
4922 /// In C++1z, a condition may in some contexts be preceded by an
4923 /// optional init-statement. This function will parse that too.
4924 ///
4925 /// \param InitStmt If non-null, an init-statement is permitted, and if
4926 /// present will be parsed and stored here.
4927 ///
4928 /// \param Loc The location of the start of the statement that requires this
4929 /// condition, e.g., the "for" in a for loop.
4930 ///
4931 /// \param MissingOK Whether an empty condition is acceptable here. Otherwise
4932 /// it is considered an error to be recovered from.
4933 ///
4934 /// \param FRI If non-null, a for range declaration is permitted, and if
4935 /// present will be parsed and stored here, and a null result will be
4936 /// returned.
4937 ///
4938 /// \param EnterForConditionScope If true, enter a continue/break scope at the
4939 /// appropriate moment for a 'for' loop.
4940 ///
4941 /// \returns The parsed condition.
4942 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
4943 SourceLocation Loc,
4944 Sema::ConditionKind CK,
4945 bool MissingOK,
4946 ForRangeInfo *FRI = nullptr,
4947 bool EnterForConditionScope = false);
4948 DeclGroupPtrTy ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
4949 ParsedAttributes &Attrs);
4950
4951 //===--------------------------------------------------------------------===//
4952 // C++ Coroutines
4953
4954 /// Parse the C++ Coroutines co_yield expression.
4955 ///
4956 /// \verbatim
4957 /// co_yield-expression:
4958 /// 'co_yield' assignment-expression[opt]
4959 /// \endverbatim
4960 ExprResult ParseCoyieldExpression();
4961
4962 //===--------------------------------------------------------------------===//
4963 // C++ Concepts
4964
4965 /// ParseRequiresExpression - Parse a C++2a requires-expression.
4966 /// C++2a [expr.prim.req]p1
4967 /// A requires-expression provides a concise way to express requirements
4968 /// on template arguments. A requirement is one that can be checked by
4969 /// name lookup (6.4) or by checking properties of types and expressions.
4970 ///
4971 /// \verbatim
4972 /// requires-expression:
4973 /// 'requires' requirement-parameter-list[opt] requirement-body
4974 ///
4975 /// requirement-parameter-list:
4976 /// '(' parameter-declaration-clause[opt] ')'
4977 ///
4978 /// requirement-body:
4979 /// '{' requirement-seq '}'
4980 ///
4981 /// requirement-seq:
4982 /// requirement
4983 /// requirement-seq requirement
4984 ///
4985 /// requirement:
4986 /// simple-requirement
4987 /// type-requirement
4988 /// compound-requirement
4989 /// nested-requirement
4990 /// \endverbatim
4991 ExprResult ParseRequiresExpression();
4992
4993 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
4994 /// whether the parens contain an expression or a type-id.
4995 /// Returns true for a type-id and false for an expression.
4996 bool isTypeIdInParens(bool &isAmbiguous) {
4997 if (getLangOpts().CPlusPlus)
4998 return isCXXTypeId(Context: TentativeCXXTypeIdContext::InParens, isAmbiguous);
4999 isAmbiguous = false;
5000 return isTypeSpecifierQualifier();
5001 }
5002 bool isTypeIdInParens() {
5003 bool isAmbiguous;
5004 return isTypeIdInParens(isAmbiguous);
5005 }
5006
5007 /// Finish parsing a C++ unqualified-id that is a template-id of
5008 /// some form.
5009 ///
5010 /// This routine is invoked when a '<' is encountered after an identifier or
5011 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
5012 /// whether the unqualified-id is actually a template-id. This routine will
5013 /// then parse the template arguments and form the appropriate template-id to
5014 /// return to the caller.
5015 ///
5016 /// \param SS the nested-name-specifier that precedes this template-id, if
5017 /// we're actually parsing a qualified-id.
5018 ///
5019 /// \param ObjectType if this unqualified-id occurs within a member access
5020 /// expression, the type of the base object whose member is being accessed.
5021 ///
5022 /// \param ObjectHadErrors this unqualified-id occurs within a member access
5023 /// expression, indicates whether the original subexpressions had any errors.
5024 ///
5025 /// \param Name for constructor and destructor names, this is the actual
5026 /// identifier that may be a template-name.
5027 ///
5028 /// \param NameLoc the location of the class-name in a constructor or
5029 /// destructor.
5030 ///
5031 /// \param EnteringContext whether we're entering the scope of the
5032 /// nested-name-specifier.
5033 ///
5034 /// \param Id as input, describes the template-name or operator-function-id
5035 /// that precedes the '<'. If template arguments were parsed successfully,
5036 /// will be updated with the template-id.
5037 ///
5038 /// \param AssumeTemplateId When true, this routine will assume that the name
5039 /// refers to a template without performing name lookup to verify.
5040 ///
5041 /// \returns true if a parse error occurred, false otherwise.
5042 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType,
5043 bool ObjectHadErrors,
5044 SourceLocation TemplateKWLoc,
5045 IdentifierInfo *Name,
5046 SourceLocation NameLoc,
5047 bool EnteringContext, UnqualifiedId &Id,
5048 bool AssumeTemplateId);
5049
5050 /// Parse an operator-function-id or conversion-function-id as part
5051 /// of a C++ unqualified-id.
5052 ///
5053 /// This routine is responsible only for parsing the operator-function-id or
5054 /// conversion-function-id; it does not handle template arguments in any way.
5055 ///
5056 /// \verbatim
5057 /// operator-function-id: [C++ 13.5]
5058 /// 'operator' operator
5059 ///
5060 /// operator: one of
5061 /// new delete new[] delete[]
5062 /// + - * / % ^ & | ~
5063 /// ! = < > += -= *= /= %=
5064 /// ^= &= |= << >> >>= <<= == !=
5065 /// <= >= && || ++ -- , ->* ->
5066 /// () [] <=>
5067 ///
5068 /// conversion-function-id: [C++ 12.3.2]
5069 /// operator conversion-type-id
5070 ///
5071 /// conversion-type-id:
5072 /// type-specifier-seq conversion-declarator[opt]
5073 ///
5074 /// conversion-declarator:
5075 /// ptr-operator conversion-declarator[opt]
5076 /// \endverbatim
5077 ///
5078 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
5079 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
5080 ///
5081 /// \param EnteringContext whether we are entering the scope of the
5082 /// nested-name-specifier.
5083 ///
5084 /// \param ObjectType if this unqualified-id occurs within a member access
5085 /// expression, the type of the base object whose member is being accessed.
5086 ///
5087 /// \param Result on a successful parse, contains the parsed unqualified-id.
5088 ///
5089 /// \returns true if parsing fails, false otherwise.
5090 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
5091 ParsedType ObjectType, UnqualifiedId &Result);
5092
5093 //===--------------------------------------------------------------------===//
5094 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
5095
5096 /// Parse the built-in type-trait pseudo-functions that allow
5097 /// implementation of the TR1/C++11 type traits templates.
5098 ///
5099 /// \verbatim
5100 /// primary-expression:
5101 /// unary-type-trait '(' type-id ')'
5102 /// binary-type-trait '(' type-id ',' type-id ')'
5103 /// type-trait '(' type-id-seq ')'
5104 ///
5105 /// type-id-seq:
5106 /// type-id ...[opt] type-id-seq[opt]
5107 /// \endverbatim
5108 ///
5109 ExprResult ParseTypeTrait();
5110
5111 //===--------------------------------------------------------------------===//
5112 // Embarcadero: Arary and Expression Traits
5113
5114 /// ParseArrayTypeTrait - Parse the built-in array type-trait
5115 /// pseudo-functions.
5116 ///
5117 /// \verbatim
5118 /// primary-expression:
5119 /// [Embarcadero] '__array_rank' '(' type-id ')'
5120 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
5121 /// \endverbatim
5122 ///
5123 ExprResult ParseArrayTypeTrait();
5124
5125 /// ParseExpressionTrait - Parse built-in expression-trait
5126 /// pseudo-functions like __is_lvalue_expr( xxx ).
5127 ///
5128 /// \verbatim
5129 /// primary-expression:
5130 /// [Embarcadero] expression-trait '(' expression ')'
5131 /// \endverbatim
5132 ///
5133 ExprResult ParseExpressionTrait();
5134
5135 ///@}
5136
5137 //
5138 //
5139 // -------------------------------------------------------------------------
5140 //
5141 //
5142
5143 /// \name HLSL Constructs
5144 /// Implementations are in ParseHLSL.cpp
5145 ///@{
5146
5147private:
5148 bool MaybeParseHLSLAnnotations(Declarator &D,
5149 SourceLocation *EndLoc = nullptr,
5150 bool CouldBeBitField = false) {
5151 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
5152 if (Tok.is(K: tok::colon)) {
5153 ParsedAttributes Attrs(AttrFactory);
5154 ParseHLSLAnnotations(Attrs, EndLoc, CouldBeBitField);
5155 D.takeAttributes(attrs&: Attrs);
5156 return true;
5157 }
5158 return false;
5159 }
5160
5161 void MaybeParseHLSLAnnotations(ParsedAttributes &Attrs,
5162 SourceLocation *EndLoc = nullptr) {
5163 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
5164 if (Tok.is(K: tok::colon))
5165 ParseHLSLAnnotations(Attrs, EndLoc);
5166 }
5167
5168 void ParseHLSLAnnotations(ParsedAttributes &Attrs,
5169 SourceLocation *EndLoc = nullptr,
5170 bool CouldBeBitField = false);
5171 Decl *ParseHLSLBuffer(SourceLocation &DeclEnd);
5172
5173 ///@}
5174
5175 //
5176 //
5177 // -------------------------------------------------------------------------
5178 //
5179 //
5180
5181 /// \name Initializers
5182 /// Implementations are in ParseInit.cpp
5183 ///@{
5184
5185private:
5186 //===--------------------------------------------------------------------===//
5187 // C99 6.7.8: Initialization.
5188
5189 /// ParseInitializer
5190 /// \verbatim
5191 /// initializer: [C99 6.7.8]
5192 /// assignment-expression
5193 /// '{' ...
5194 /// \endverbatim
5195 ExprResult ParseInitializer() {
5196 if (Tok.isNot(K: tok::l_brace))
5197 return ParseAssignmentExpression();
5198 return ParseBraceInitializer();
5199 }
5200
5201 /// MayBeDesignationStart - Return true if the current token might be the
5202 /// start of a designator. If we can tell it is impossible that it is a
5203 /// designator, return false.
5204 bool MayBeDesignationStart();
5205
5206 /// ParseBraceInitializer - Called when parsing an initializer that has a
5207 /// leading open brace.
5208 ///
5209 /// \verbatim
5210 /// initializer: [C99 6.7.8]
5211 /// '{' initializer-list '}'
5212 /// '{' initializer-list ',' '}'
5213 /// [C23] '{' '}'
5214 ///
5215 /// initializer-list:
5216 /// designation[opt] initializer ...[opt]
5217 /// initializer-list ',' designation[opt] initializer ...[opt]
5218 /// \endverbatim
5219 ///
5220 ExprResult ParseBraceInitializer();
5221
5222 struct DesignatorCompletionInfo {
5223 SmallVectorImpl<Expr *> &InitExprs;
5224 QualType PreferredBaseType;
5225 };
5226
5227 /// ParseInitializerWithPotentialDesignator - Parse the 'initializer'
5228 /// production checking to see if the token stream starts with a designator.
5229 ///
5230 /// C99:
5231 ///
5232 /// \verbatim
5233 /// designation:
5234 /// designator-list '='
5235 /// [GNU] array-designator
5236 /// [GNU] identifier ':'
5237 ///
5238 /// designator-list:
5239 /// designator
5240 /// designator-list designator
5241 ///
5242 /// designator:
5243 /// array-designator
5244 /// '.' identifier
5245 ///
5246 /// array-designator:
5247 /// '[' constant-expression ']'
5248 /// [GNU] '[' constant-expression '...' constant-expression ']'
5249 /// \endverbatim
5250 ///
5251 /// C++20:
5252 ///
5253 /// \verbatim
5254 /// designated-initializer-list:
5255 /// designated-initializer-clause
5256 /// designated-initializer-list ',' designated-initializer-clause
5257 ///
5258 /// designated-initializer-clause:
5259 /// designator brace-or-equal-initializer
5260 ///
5261 /// designator:
5262 /// '.' identifier
5263 /// \endverbatim
5264 ///
5265 /// We allow the C99 syntax extensions in C++20, but do not allow the C++20
5266 /// extension (a braced-init-list after the designator with no '=') in C99.
5267 ///
5268 /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
5269 /// initializer (because it is an expression). We need to consider this case
5270 /// when parsing array designators.
5271 ///
5272 /// \p CodeCompleteCB is called with Designation parsed so far.
5273 ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
5274
5275 ExprResult createEmbedExpr();
5276
5277 /// A SmallVector of expressions.
5278 typedef SmallVector<Expr *, 12> ExprVector;
5279
5280 // Return true if a comma (or closing brace) is necessary after the
5281 // __if_exists/if_not_exists statement.
5282 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
5283 bool &InitExprsOk);
5284
5285 ///@}
5286
5287 //
5288 //
5289 // -------------------------------------------------------------------------
5290 //
5291 //
5292
5293 /// \name Objective-C Constructs
5294 /// Implementations are in ParseObjc.cpp
5295 ///@{
5296
5297public:
5298 friend class InMessageExpressionRAIIObject;
5299 friend class ObjCDeclContextSwitch;
5300
5301 ObjCContainerDecl *getObjCDeclContext() const {
5302 return Actions.ObjC().getObjCDeclContext();
5303 }
5304
5305 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
5306 /// to the given nullability kind.
5307 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
5308 return Actions.getNullabilityKeyword(nullability);
5309 }
5310
5311private:
5312 /// Objective-C contextual keywords.
5313 IdentifierInfo *Ident_instancetype;
5314
5315 /// Ident_super - IdentifierInfo for "super", to support fast
5316 /// comparison.
5317 IdentifierInfo *Ident_super;
5318
5319 /// When true, we are directly inside an Objective-C message
5320 /// send expression.
5321 ///
5322 /// This is managed by the \c InMessageExpressionRAIIObject class, and
5323 /// should not be set directly.
5324 bool InMessageExpression;
5325
5326 /// True if we are within an Objective-C container while parsing C-like decls.
5327 ///
5328 /// This is necessary because Sema thinks we have left the container
5329 /// to parse the C-like decls, meaning Actions.ObjC().getObjCDeclContext()
5330 /// will be NULL.
5331 bool ParsingInObjCContainer;
5332
5333 /// Returns true if the current token is the identifier 'instancetype'.
5334 ///
5335 /// Should only be used in Objective-C language modes.
5336 bool isObjCInstancetype() {
5337 assert(getLangOpts().ObjC);
5338 if (Tok.isAnnotation())
5339 return false;
5340 if (!Ident_instancetype)
5341 Ident_instancetype = PP.getIdentifierInfo(Name: "instancetype");
5342 return Tok.getIdentifierInfo() == Ident_instancetype;
5343 }
5344
5345 /// ObjCDeclContextSwitch - An object used to switch context from
5346 /// an objective-c decl context to its enclosing decl context and
5347 /// back.
5348 class ObjCDeclContextSwitch {
5349 Parser &P;
5350 ObjCContainerDecl *DC;
5351 SaveAndRestore<bool> WithinObjCContainer;
5352
5353 public:
5354 explicit ObjCDeclContextSwitch(Parser &p)
5355 : P(p), DC(p.getObjCDeclContext()),
5356 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
5357 if (DC)
5358 P.Actions.ObjC().ActOnObjCTemporaryExitContainerContext(ObjCCtx: DC);
5359 }
5360 ~ObjCDeclContextSwitch() {
5361 if (DC)
5362 P.Actions.ObjC().ActOnObjCReenterContainerContext(ObjCCtx: DC);
5363 }
5364 };
5365
5366 void CheckNestedObjCContexts(SourceLocation AtLoc);
5367
5368 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
5369
5370 // Objective-C External Declarations
5371
5372 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
5373 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
5374
5375 /// ParseObjCAtDirectives - Handle parts of the external-declaration
5376 /// production:
5377 /// \verbatim
5378 /// external-declaration: [C99 6.9]
5379 /// [OBJC] objc-class-definition
5380 /// [OBJC] objc-class-declaration
5381 /// [OBJC] objc-alias-declaration
5382 /// [OBJC] objc-protocol-definition
5383 /// [OBJC] objc-method-definition
5384 /// [OBJC] '@' 'end'
5385 /// \endverbatim
5386 DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
5387 ParsedAttributes &DeclSpecAttrs);
5388
5389 ///
5390 /// \verbatim
5391 /// objc-class-declaration:
5392 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
5393 ///
5394 /// objc-class-forward-decl:
5395 /// identifier objc-type-parameter-list[opt]
5396 /// \endverbatim
5397 ///
5398 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
5399
5400 ///
5401 /// \verbatim
5402 /// objc-interface:
5403 /// objc-class-interface-attributes[opt] objc-class-interface
5404 /// objc-category-interface
5405 ///
5406 /// objc-class-interface:
5407 /// '@' 'interface' identifier objc-type-parameter-list[opt]
5408 /// objc-superclass[opt] objc-protocol-refs[opt]
5409 /// objc-class-instance-variables[opt]
5410 /// objc-interface-decl-list
5411 /// @end
5412 ///
5413 /// objc-category-interface:
5414 /// '@' 'interface' identifier objc-type-parameter-list[opt]
5415 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
5416 /// objc-interface-decl-list
5417 /// @end
5418 ///
5419 /// objc-superclass:
5420 /// ':' identifier objc-type-arguments[opt]
5421 ///
5422 /// objc-class-interface-attributes:
5423 /// __attribute__((visibility("default")))
5424 /// __attribute__((visibility("hidden")))
5425 /// __attribute__((deprecated))
5426 /// __attribute__((unavailable))
5427 /// __attribute__((objc_exception)) - used by NSException on 64-bit
5428 /// __attribute__((objc_root_class))
5429 /// \endverbatim
5430 ///
5431 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
5432 ParsedAttributes &prefixAttrs);
5433
5434 /// Class to handle popping type parameters when leaving the scope.
5435 class ObjCTypeParamListScope;
5436
5437 /// Parse an objc-type-parameter-list.
5438 ObjCTypeParamList *parseObjCTypeParamList();
5439
5440 /// Parse an Objective-C type parameter list, if present, or capture
5441 /// the locations of the protocol identifiers for a list of protocol
5442 /// references.
5443 ///
5444 /// \verbatim
5445 /// objc-type-parameter-list:
5446 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
5447 ///
5448 /// objc-type-parameter:
5449 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
5450 ///
5451 /// objc-type-parameter-bound:
5452 /// ':' type-name
5453 ///
5454 /// objc-type-parameter-variance:
5455 /// '__covariant'
5456 /// '__contravariant'
5457 /// \endverbatim
5458 ///
5459 /// \param lAngleLoc The location of the starting '<'.
5460 ///
5461 /// \param protocolIdents Will capture the list of identifiers, if the
5462 /// angle brackets contain a list of protocol references rather than a
5463 /// type parameter list.
5464 ///
5465 /// \param rAngleLoc The location of the ending '>'.
5466 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
5467 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
5468 SmallVectorImpl<IdentifierLoc> &protocolIdents, SourceLocation &rAngleLoc,
5469 bool mayBeProtocolList = true);
5470
5471 void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl,
5472 SourceLocation atLoc,
5473 BalancedDelimiterTracker &T,
5474 SmallVectorImpl<Decl *> &AllIvarDecls,
5475 bool RBraceMissing);
5476
5477 /// \verbatim
5478 /// objc-class-instance-variables:
5479 /// '{' objc-instance-variable-decl-list[opt] '}'
5480 ///
5481 /// objc-instance-variable-decl-list:
5482 /// objc-visibility-spec
5483 /// objc-instance-variable-decl ';'
5484 /// ';'
5485 /// objc-instance-variable-decl-list objc-visibility-spec
5486 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
5487 /// objc-instance-variable-decl-list static_assert-declaration
5488 /// objc-instance-variable-decl-list ';'
5489 ///
5490 /// objc-visibility-spec:
5491 /// @private
5492 /// @protected
5493 /// @public
5494 /// @package [OBJC2]
5495 ///
5496 /// objc-instance-variable-decl:
5497 /// struct-declaration
5498 /// \endverbatim
5499 ///
5500 void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
5501 tok::ObjCKeywordKind visibility,
5502 SourceLocation atLoc);
5503
5504 /// \verbatim
5505 /// objc-protocol-refs:
5506 /// '<' identifier-list '>'
5507 /// \endverbatim
5508 ///
5509 bool ParseObjCProtocolReferences(
5510 SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs,
5511 bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc,
5512 SourceLocation &EndProtoLoc, bool consumeLastToken);
5513
5514 /// Parse the first angle-bracket-delimited clause for an
5515 /// Objective-C object or object pointer type, which may be either
5516 /// type arguments or protocol qualifiers.
5517 ///
5518 /// \verbatim
5519 /// objc-type-arguments:
5520 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
5521 /// \endverbatim
5522 ///
5523 void parseObjCTypeArgsOrProtocolQualifiers(
5524 ParsedType baseType, SourceLocation &typeArgsLAngleLoc,
5525 SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc,
5526 SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols,
5527 SmallVectorImpl<SourceLocation> &protocolLocs,
5528 SourceLocation &protocolRAngleLoc, bool consumeLastToken,
5529 bool warnOnIncompleteProtocols);
5530
5531 /// Parse either Objective-C type arguments or protocol qualifiers; if the
5532 /// former, also parse protocol qualifiers afterward.
5533 void parseObjCTypeArgsAndProtocolQualifiers(
5534 ParsedType baseType, SourceLocation &typeArgsLAngleLoc,
5535 SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc,
5536 SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols,
5537 SmallVectorImpl<SourceLocation> &protocolLocs,
5538 SourceLocation &protocolRAngleLoc, bool consumeLastToken);
5539
5540 /// Parse a protocol qualifier type such as '<NSCopying>', which is
5541 /// an anachronistic way of writing 'id<NSCopying>'.
5542 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
5543
5544 /// Parse Objective-C type arguments and protocol qualifiers, extending the
5545 /// current type with the parsed result.
5546 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
5547 ParsedType type,
5548 bool consumeLastToken,
5549 SourceLocation &endLoc);
5550
5551 /// \verbatim
5552 /// objc-interface-decl-list:
5553 /// empty
5554 /// objc-interface-decl-list objc-property-decl [OBJC2]
5555 /// objc-interface-decl-list objc-method-requirement [OBJC2]
5556 /// objc-interface-decl-list objc-method-proto ';'
5557 /// objc-interface-decl-list declaration
5558 /// objc-interface-decl-list ';'
5559 ///
5560 /// objc-method-requirement: [OBJC2]
5561 /// @required
5562 /// @optional
5563 /// \endverbatim
5564 ///
5565 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl);
5566
5567 /// \verbatim
5568 /// objc-protocol-declaration:
5569 /// objc-protocol-definition
5570 /// objc-protocol-forward-reference
5571 ///
5572 /// objc-protocol-definition:
5573 /// \@protocol identifier
5574 /// objc-protocol-refs[opt]
5575 /// objc-interface-decl-list
5576 /// \@end
5577 ///
5578 /// objc-protocol-forward-reference:
5579 /// \@protocol identifier-list ';'
5580 /// \endverbatim
5581 ///
5582 /// "\@protocol identifier ;" should be resolved as "\@protocol
5583 /// identifier-list ;": objc-interface-decl-list may not start with a
5584 /// semicolon in the first alternative if objc-protocol-refs are omitted.
5585 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
5586 ParsedAttributes &prefixAttrs);
5587
5588 struct ObjCImplParsingDataRAII {
5589 Parser &P;
5590 Decl *Dcl;
5591 bool HasCFunction;
5592 typedef SmallVector<LexedMethod *, 8> LateParsedObjCMethodContainer;
5593 LateParsedObjCMethodContainer LateParsedObjCMethods;
5594
5595 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
5596 : P(parser), Dcl(D), HasCFunction(false) {
5597 P.CurParsedObjCImpl = this;
5598 Finished = false;
5599 }
5600 ~ObjCImplParsingDataRAII();
5601
5602 void finish(SourceRange AtEnd);
5603 bool isFinished() const { return Finished; }
5604
5605 private:
5606 bool Finished;
5607 };
5608 ObjCImplParsingDataRAII *CurParsedObjCImpl;
5609
5610 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
5611 /// for later parsing.
5612 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
5613
5614 /// \verbatim
5615 /// objc-implementation:
5616 /// objc-class-implementation-prologue
5617 /// objc-category-implementation-prologue
5618 ///
5619 /// objc-class-implementation-prologue:
5620 /// @implementation identifier objc-superclass[opt]
5621 /// objc-class-instance-variables[opt]
5622 ///
5623 /// objc-category-implementation-prologue:
5624 /// @implementation identifier ( identifier )
5625 /// \endverbatim
5626 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
5627 ParsedAttributes &Attrs);
5628 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
5629
5630 /// \verbatim
5631 /// compatibility-alias-decl:
5632 /// @compatibility_alias alias-name class-name ';'
5633 /// \endverbatim
5634 ///
5635 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
5636
5637 /// \verbatim
5638 /// property-synthesis:
5639 /// @synthesize property-ivar-list ';'
5640 ///
5641 /// property-ivar-list:
5642 /// property-ivar
5643 /// property-ivar-list ',' property-ivar
5644 ///
5645 /// property-ivar:
5646 /// identifier
5647 /// identifier '=' identifier
5648 /// \endverbatim
5649 ///
5650 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
5651
5652 /// \verbatim
5653 /// property-dynamic:
5654 /// @dynamic property-list
5655 ///
5656 /// property-list:
5657 /// identifier
5658 /// property-list ',' identifier
5659 /// \endverbatim
5660 ///
5661 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
5662
5663 /// \verbatim
5664 /// objc-selector:
5665 /// identifier
5666 /// one of
5667 /// enum struct union if else while do for switch case default
5668 /// break continue return goto asm sizeof typeof __alignof
5669 /// unsigned long const short volatile signed restrict _Complex
5670 /// in out inout bycopy byref oneway int char float double void _Bool
5671 /// \endverbatim
5672 ///
5673 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
5674
5675 IdentifierInfo *ObjCTypeQuals[llvm::to_underlying(E: ObjCTypeQual::NumQuals)];
5676
5677 /// \verbatim
5678 /// objc-for-collection-in: 'in'
5679 /// \endverbatim
5680 ///
5681 bool isTokIdentifier_in() const;
5682
5683 /// \verbatim
5684 /// objc-type-name:
5685 /// '(' objc-type-qualifiers[opt] type-name ')'
5686 /// '(' objc-type-qualifiers[opt] ')'
5687 /// \endverbatim
5688 ///
5689 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
5690 ParsedAttributes *ParamAttrs);
5691
5692 /// \verbatim
5693 /// objc-method-proto:
5694 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
5695 /// objc-class-method objc-method-decl objc-method-attributes[opt]
5696 ///
5697 /// objc-instance-method: '-'
5698 /// objc-class-method: '+'
5699 ///
5700 /// objc-method-attributes: [OBJC2]
5701 /// __attribute__((deprecated))
5702 /// \endverbatim
5703 ///
5704 Decl *ParseObjCMethodPrototype(
5705 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
5706 bool MethodDefinition = true);
5707
5708 /// \verbatim
5709 /// objc-method-decl:
5710 /// objc-selector
5711 /// objc-keyword-selector objc-parmlist[opt]
5712 /// objc-type-name objc-selector
5713 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
5714 ///
5715 /// objc-keyword-selector:
5716 /// objc-keyword-decl
5717 /// objc-keyword-selector objc-keyword-decl
5718 ///
5719 /// objc-keyword-decl:
5720 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
5721 /// objc-selector ':' objc-keyword-attributes[opt] identifier
5722 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
5723 /// ':' objc-keyword-attributes[opt] identifier
5724 ///
5725 /// objc-parmlist:
5726 /// objc-parms objc-ellipsis[opt]
5727 ///
5728 /// objc-parms:
5729 /// objc-parms , parameter-declaration
5730 ///
5731 /// objc-ellipsis:
5732 /// , ...
5733 ///
5734 /// objc-keyword-attributes: [OBJC2]
5735 /// __attribute__((unused))
5736 /// \endverbatim
5737 ///
5738 Decl *ParseObjCMethodDecl(
5739 SourceLocation mLoc, tok::TokenKind mType,
5740 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
5741 bool MethodDefinition = true);
5742
5743 /// Parse property attribute declarations.
5744 ///
5745 /// \verbatim
5746 /// property-attr-decl: '(' property-attrlist ')'
5747 /// property-attrlist:
5748 /// property-attribute
5749 /// property-attrlist ',' property-attribute
5750 /// property-attribute:
5751 /// getter '=' identifier
5752 /// setter '=' identifier ':'
5753 /// direct
5754 /// readonly
5755 /// readwrite
5756 /// assign
5757 /// retain
5758 /// copy
5759 /// nonatomic
5760 /// atomic
5761 /// strong
5762 /// weak
5763 /// unsafe_unretained
5764 /// nonnull
5765 /// nullable
5766 /// null_unspecified
5767 /// null_resettable
5768 /// class
5769 /// \endverbatim
5770 ///
5771 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
5772
5773 /// \verbatim
5774 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
5775 /// \endverbatim
5776 ///
5777 Decl *ParseObjCMethodDefinition();
5778
5779 //===--------------------------------------------------------------------===//
5780 // Objective-C Expressions
5781 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
5782 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
5783
5784 /// ParseObjCCharacterLiteral -
5785 /// \verbatim
5786 /// objc-scalar-literal : '@' character-literal
5787 /// ;
5788 /// \endverbatim
5789 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
5790
5791 /// ParseObjCNumericLiteral -
5792 /// \verbatim
5793 /// objc-scalar-literal : '@' scalar-literal
5794 /// ;
5795 /// scalar-literal : | numeric-constant /* any numeric constant. */
5796 /// ;
5797 /// \endverbatim
5798 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
5799
5800 /// ParseObjCBooleanLiteral -
5801 /// \verbatim
5802 /// objc-scalar-literal : '@' boolean-keyword
5803 /// ;
5804 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
5805 /// ;
5806 /// \endverbatim
5807 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
5808
5809 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
5810 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
5811
5812 /// ParseObjCBoxedExpr -
5813 /// \verbatim
5814 /// objc-box-expression:
5815 /// @( assignment-expression )
5816 /// \endverbatim
5817 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
5818
5819 /// \verbatim
5820 /// objc-encode-expression:
5821 /// \@encode ( type-name )
5822 /// \endverbatim
5823 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
5824
5825 /// \verbatim
5826 /// objc-selector-expression
5827 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
5828 /// \endverbatim
5829 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
5830
5831 /// \verbatim
5832 /// objc-protocol-expression
5833 /// \@protocol ( protocol-name )
5834 /// \endverbatim
5835 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
5836
5837 /// Determine whether the parser is currently referring to a an
5838 /// Objective-C message send, using a simplified heuristic to avoid overhead.
5839 ///
5840 /// This routine will only return true for a subset of valid message-send
5841 /// expressions.
5842 bool isSimpleObjCMessageExpression();
5843
5844 /// \verbatim
5845 /// objc-message-expr:
5846 /// '[' objc-receiver objc-message-args ']'
5847 ///
5848 /// objc-receiver: [C]
5849 /// 'super'
5850 /// expression
5851 /// class-name
5852 /// type-name
5853 /// \endverbatim
5854 ///
5855 ExprResult ParseObjCMessageExpression();
5856
5857 /// Parse the remainder of an Objective-C message following the
5858 /// '[' objc-receiver.
5859 ///
5860 /// This routine handles sends to super, class messages (sent to a
5861 /// class name), and instance messages (sent to an object), and the
5862 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
5863 /// ReceiverExpr, respectively. Only one of these parameters may have
5864 /// a valid value.
5865 ///
5866 /// \param LBracLoc The location of the opening '['.
5867 ///
5868 /// \param SuperLoc If this is a send to 'super', the location of the
5869 /// 'super' keyword that indicates a send to the superclass.
5870 ///
5871 /// \param ReceiverType If this is a class message, the type of the
5872 /// class we are sending a message to.
5873 ///
5874 /// \param ReceiverExpr If this is an instance message, the expression
5875 /// used to compute the receiver object.
5876 ///
5877 /// \verbatim
5878 /// objc-message-args:
5879 /// objc-selector
5880 /// objc-keywordarg-list
5881 ///
5882 /// objc-keywordarg-list:
5883 /// objc-keywordarg
5884 /// objc-keywordarg-list objc-keywordarg
5885 ///
5886 /// objc-keywordarg:
5887 /// selector-name[opt] ':' objc-keywordexpr
5888 ///
5889 /// objc-keywordexpr:
5890 /// nonempty-expr-list
5891 ///
5892 /// nonempty-expr-list:
5893 /// assignment-expression
5894 /// nonempty-expr-list , assignment-expression
5895 /// \endverbatim
5896 ///
5897 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
5898 SourceLocation SuperLoc,
5899 ParsedType ReceiverType,
5900 Expr *ReceiverExpr);
5901
5902 /// Parse the receiver of an Objective-C++ message send.
5903 ///
5904 /// This routine parses the receiver of a message send in
5905 /// Objective-C++ either as a type or as an expression. Note that this
5906 /// routine must not be called to parse a send to 'super', since it
5907 /// has no way to return such a result.
5908 ///
5909 /// \param IsExpr Whether the receiver was parsed as an expression.
5910 ///
5911 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
5912 /// IsExpr is true), the parsed expression. If the receiver was parsed
5913 /// as a type (\c IsExpr is false), the parsed type.
5914 ///
5915 /// \returns True if an error occurred during parsing or semantic
5916 /// analysis, in which case the arguments do not have valid
5917 /// values. Otherwise, returns false for a successful parse.
5918 ///
5919 /// \verbatim
5920 /// objc-receiver: [C++]
5921 /// 'super' [not parsed here]
5922 /// expression
5923 /// simple-type-specifier
5924 /// typename-specifier
5925 /// \endverbatim
5926 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
5927
5928 //===--------------------------------------------------------------------===//
5929 // Objective-C Statements
5930
5931 enum class ParsedStmtContext;
5932
5933 StmtResult ParseObjCAtStatement(SourceLocation atLoc,
5934 ParsedStmtContext StmtCtx);
5935
5936 /// \verbatim
5937 /// objc-try-catch-statement:
5938 /// @try compound-statement objc-catch-list[opt]
5939 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
5940 ///
5941 /// objc-catch-list:
5942 /// @catch ( parameter-declaration ) compound-statement
5943 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
5944 /// catch-parameter-declaration:
5945 /// parameter-declaration
5946 /// '...' [OBJC2]
5947 /// \endverbatim
5948 ///
5949 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
5950
5951 /// \verbatim
5952 /// objc-throw-statement:
5953 /// throw expression[opt];
5954 /// \endverbatim
5955 ///
5956 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
5957
5958 /// \verbatim
5959 /// objc-synchronized-statement:
5960 /// @synchronized '(' expression ')' compound-statement
5961 /// \endverbatim
5962 ///
5963 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
5964
5965 /// \verbatim
5966 /// objc-autoreleasepool-statement:
5967 /// @autoreleasepool compound-statement
5968 /// \endverbatim
5969 ///
5970 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
5971
5972 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
5973 /// qualifier list and builds their bitmask representation in the input
5974 /// argument.
5975 ///
5976 /// \verbatim
5977 /// objc-type-qualifiers:
5978 /// objc-type-qualifier
5979 /// objc-type-qualifiers objc-type-qualifier
5980 ///
5981 /// objc-type-qualifier:
5982 /// 'in'
5983 /// 'out'
5984 /// 'inout'
5985 /// 'oneway'
5986 /// 'bycopy's
5987 /// 'byref'
5988 /// 'nonnull'
5989 /// 'nullable'
5990 /// 'null_unspecified'
5991 /// \endverbatim
5992 ///
5993 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context);
5994
5995 /// Determine whether we are currently at the start of an Objective-C
5996 /// class message that appears to be missing the open bracket '['.
5997 bool isStartOfObjCClassMessageMissingOpenBracket();
5998
5999 ///@}
6000
6001 //
6002 //
6003 // -------------------------------------------------------------------------
6004 //
6005 //
6006
6007 /// \name OpenACC Constructs
6008 /// Implementations are in ParseOpenACC.cpp
6009 ///@{
6010
6011public:
6012 friend class ParsingOpenACCDirectiveRAII;
6013
6014 /// Parse OpenACC directive on a declaration.
6015 ///
6016 /// Placeholder for now, should just ignore the directives after emitting a
6017 /// diagnostic. Eventually will be split into a few functions to parse
6018 /// different situations.
6019 DeclGroupPtrTy ParseOpenACCDirectiveDecl(AccessSpecifier &AS,
6020 ParsedAttributes &Attrs,
6021 DeclSpec::TST TagType,
6022 Decl *TagDecl);
6023
6024 // Parse OpenACC Directive on a Statement.
6025 StmtResult ParseOpenACCDirectiveStmt();
6026
6027private:
6028 /// Parsing OpenACC directive mode.
6029 bool OpenACCDirectiveParsing = false;
6030
6031 /// Currently parsing a situation where an OpenACC array section could be
6032 /// legal, such as a 'var-list'.
6033 bool AllowOpenACCArraySections = false;
6034
6035 /// RAII object to set reset OpenACC parsing a context where Array Sections
6036 /// are allowed.
6037 class OpenACCArraySectionRAII {
6038 Parser &P;
6039
6040 public:
6041 OpenACCArraySectionRAII(Parser &P) : P(P) {
6042 assert(!P.AllowOpenACCArraySections);
6043 P.AllowOpenACCArraySections = true;
6044 }
6045 ~OpenACCArraySectionRAII() {
6046 assert(P.AllowOpenACCArraySections);
6047 P.AllowOpenACCArraySections = false;
6048 }
6049 };
6050
6051 /// A struct to hold the information that got parsed by ParseOpenACCDirective,
6052 /// so that the callers of it can use that to construct the appropriate AST
6053 /// nodes.
6054 struct OpenACCDirectiveParseInfo {
6055 OpenACCDirectiveKind DirKind;
6056 SourceLocation StartLoc;
6057 SourceLocation DirLoc;
6058 SourceLocation LParenLoc;
6059 SourceLocation RParenLoc;
6060 SourceLocation EndLoc;
6061 SourceLocation MiscLoc;
6062 OpenACCAtomicKind AtomicKind;
6063 SmallVector<Expr *> Exprs;
6064 SmallVector<OpenACCClause *> Clauses;
6065 // TODO OpenACC: As we implement support for the Atomic, Routine, and Cache
6066 // constructs, we likely want to put that information in here as well.
6067 };
6068
6069 struct OpenACCWaitParseInfo {
6070 bool Failed = false;
6071 Expr *DevNumExpr = nullptr;
6072 SourceLocation QueuesLoc;
6073 SmallVector<Expr *> QueueIdExprs;
6074
6075 SmallVector<Expr *> getAllExprs() {
6076 SmallVector<Expr *> Out;
6077 Out.push_back(Elt: DevNumExpr);
6078 llvm::append_range(C&: Out, R&: QueueIdExprs);
6079 return Out;
6080 }
6081 };
6082 struct OpenACCCacheParseInfo {
6083 bool Failed = false;
6084 SourceLocation ReadOnlyLoc;
6085 SmallVector<Expr *> Vars;
6086 };
6087
6088 /// Represents the 'error' state of parsing an OpenACC Clause, and stores
6089 /// whether we can continue parsing, or should give up on the directive.
6090 enum class OpenACCParseCanContinue { Cannot = 0, Can = 1 };
6091
6092 /// A type to represent the state of parsing an OpenACC Clause. Situations
6093 /// that result in an OpenACCClause pointer are a success and can continue
6094 /// parsing, however some other situations can also continue.
6095 /// FIXME: This is better represented as a std::expected when we get C++23.
6096 using OpenACCClauseParseResult =
6097 llvm::PointerIntPair<OpenACCClause *, 1, OpenACCParseCanContinue>;
6098
6099 OpenACCClauseParseResult OpenACCCanContinue();
6100 OpenACCClauseParseResult OpenACCCannotContinue();
6101 OpenACCClauseParseResult OpenACCSuccess(OpenACCClause *Clause);
6102
6103 /// Parses the OpenACC directive (the entire pragma) including the clause
6104 /// list, but does not produce the main AST node.
6105 OpenACCDirectiveParseInfo ParseOpenACCDirective();
6106 /// Helper that parses an ID Expression based on the language options.
6107 ExprResult ParseOpenACCIDExpression();
6108
6109 /// Parses the variable list for the `cache` construct.
6110 ///
6111 /// OpenACC 3.3, section 2.10:
6112 /// In C and C++, the syntax of the cache directive is:
6113 ///
6114 /// #pragma acc cache ([readonly:]var-list) new-line
6115 OpenACCCacheParseInfo ParseOpenACCCacheVarList();
6116
6117 /// Tries to parse the 'modifier-list' for a 'copy', 'copyin', 'copyout', or
6118 /// 'create' clause.
6119 OpenACCModifierKind tryParseModifierList(OpenACCClauseKind CK);
6120
6121 using OpenACCVarParseResult = std::pair<ExprResult, OpenACCParseCanContinue>;
6122
6123 /// Parses a single variable in a variable list for OpenACC.
6124 ///
6125 /// OpenACC 3.3, section 1.6:
6126 /// In this spec, a 'var' (in italics) is one of the following:
6127 /// - a variable name (a scalar, array, or composite variable name)
6128 /// - a subarray specification with subscript ranges
6129 /// - an array element
6130 /// - a member of a composite variable
6131 /// - a common block name between slashes (fortran only)
6132 OpenACCVarParseResult ParseOpenACCVar(OpenACCDirectiveKind DK,
6133 OpenACCClauseKind CK);
6134
6135 /// Parses the variable list for the variety of places that take a var-list.
6136 llvm::SmallVector<Expr *> ParseOpenACCVarList(OpenACCDirectiveKind DK,
6137 OpenACCClauseKind CK);
6138
6139 /// Parses any parameters for an OpenACC Clause, including required/optional
6140 /// parens.
6141 ///
6142 /// The OpenACC Clause List is a comma or space-delimited list of clauses (see
6143 /// the comment on ParseOpenACCClauseList). The concept of a 'clause' doesn't
6144 /// really have its owner grammar and each individual one has its own
6145 /// definition. However, they all are named with a single-identifier (or
6146 /// auto/default!) token, followed in some cases by either braces or parens.
6147 OpenACCClauseParseResult
6148 ParseOpenACCClauseParams(ArrayRef<const OpenACCClause *> ExistingClauses,
6149 OpenACCDirectiveKind DirKind, OpenACCClauseKind Kind,
6150 SourceLocation ClauseLoc);
6151
6152 /// Parses a single clause in a clause-list for OpenACC. Returns nullptr on
6153 /// error.
6154 OpenACCClauseParseResult
6155 ParseOpenACCClause(ArrayRef<const OpenACCClause *> ExistingClauses,
6156 OpenACCDirectiveKind DirKind);
6157
6158 /// Parses the clause-list for an OpenACC directive.
6159 ///
6160 /// OpenACC 3.3, section 1.7:
6161 /// To simplify the specification and convey appropriate constraint
6162 /// information, a pqr-list is a comma-separated list of pdr items. The one
6163 /// exception is a clause-list, which is a list of one or more clauses
6164 /// optionally separated by commas.
6165 SmallVector<OpenACCClause *>
6166 ParseOpenACCClauseList(OpenACCDirectiveKind DirKind);
6167
6168 /// OpenACC 3.3, section 2.16:
6169 /// In this section and throughout the specification, the term wait-argument
6170 /// means:
6171 /// \verbatim
6172 /// [ devnum : int-expr : ] [ queues : ] async-argument-list
6173 /// \endverbatim
6174 OpenACCWaitParseInfo ParseOpenACCWaitArgument(SourceLocation Loc,
6175 bool IsDirective);
6176
6177 /// Parses the clause of the 'bind' argument, which can be a string literal or
6178 /// an identifier.
6179 std::variant<std::monostate, StringLiteral *, IdentifierInfo *>
6180 ParseOpenACCBindClauseArgument();
6181
6182 /// A type to represent the state of parsing after an attempt to parse an
6183 /// OpenACC int-expr. This is useful to determine whether an int-expr list can
6184 /// continue parsing after a failed int-expr.
6185 using OpenACCIntExprParseResult =
6186 std::pair<ExprResult, OpenACCParseCanContinue>;
6187 /// Parses the clause kind of 'int-expr', which can be any integral
6188 /// expression.
6189 OpenACCIntExprParseResult ParseOpenACCIntExpr(OpenACCDirectiveKind DK,
6190 OpenACCClauseKind CK,
6191 SourceLocation Loc);
6192 /// Parses the argument list for 'num_gangs', which allows up to 3
6193 /// 'int-expr's.
6194 bool ParseOpenACCIntExprList(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
6195 SourceLocation Loc,
6196 llvm::SmallVectorImpl<Expr *> &IntExprs);
6197
6198 /// Parses the 'device-type-list', which is a list of identifiers.
6199 ///
6200 /// OpenACC 3.3 Section 2.4:
6201 /// The argument to the device_type clause is a comma-separated list of one or
6202 /// more device architecture name identifiers, or an asterisk.
6203 ///
6204 /// The syntax of the device_type clause is
6205 /// device_type( * )
6206 /// device_type( device-type-list )
6207 ///
6208 /// The device_type clause may be abbreviated to dtype.
6209 bool ParseOpenACCDeviceTypeList(llvm::SmallVector<IdentifierLoc> &Archs);
6210
6211 /// Parses the 'async-argument', which is an integral value with two
6212 /// 'special' values that are likely negative (but come from Macros).
6213 ///
6214 /// OpenACC 3.3 section 2.16:
6215 /// In this section and throughout the specification, the term async-argument
6216 /// means a nonnegative scalar integer expression (int for C or C++, integer
6217 /// for Fortran), or one of the special values acc_async_noval or
6218 /// acc_async_sync, as defined in the C header file and the Fortran openacc
6219 /// module. The special values are negative values, so as not to conflict with
6220 /// a user-specified nonnegative async-argument.
6221 OpenACCIntExprParseResult ParseOpenACCAsyncArgument(OpenACCDirectiveKind DK,
6222 OpenACCClauseKind CK,
6223 SourceLocation Loc);
6224
6225 /// Parses the 'size-expr', which is an integral value, or an asterisk.
6226 /// Asterisk is represented by a OpenACCAsteriskSizeExpr
6227 ///
6228 /// OpenACC 3.3 Section 2.9:
6229 /// size-expr is one of:
6230 /// *
6231 /// int-expr
6232 /// Note that this is specified under 'gang-arg-list', but also applies to
6233 /// 'tile' via reference.
6234 ExprResult ParseOpenACCSizeExpr(OpenACCClauseKind CK);
6235
6236 /// Parses a comma delimited list of 'size-expr's.
6237 bool ParseOpenACCSizeExprList(OpenACCClauseKind CK,
6238 llvm::SmallVectorImpl<Expr *> &SizeExprs);
6239
6240 /// Parses a 'gang-arg-list', used for the 'gang' clause.
6241 ///
6242 /// OpenACC 3.3 Section 2.9:
6243 ///
6244 /// where gang-arg is one of:
6245 /// \verbatim
6246 /// [num:]int-expr
6247 /// dim:int-expr
6248 /// static:size-expr
6249 /// \endverbatim
6250 bool ParseOpenACCGangArgList(SourceLocation GangLoc,
6251 llvm::SmallVectorImpl<OpenACCGangKind> &GKs,
6252 llvm::SmallVectorImpl<Expr *> &IntExprs);
6253
6254 using OpenACCGangArgRes = std::pair<OpenACCGangKind, ExprResult>;
6255 /// Parses a 'gang-arg', used for the 'gang' clause. Returns a pair of the
6256 /// ExprResult (which contains the validity of the expression), plus the gang
6257 /// kind for the current argument.
6258 OpenACCGangArgRes ParseOpenACCGangArg(SourceLocation GangLoc);
6259 /// Parses a 'condition' expr, ensuring it results in a
6260 ExprResult ParseOpenACCConditionExpr();
6261 DeclGroupPtrTy
6262 ParseOpenACCAfterRoutineDecl(AccessSpecifier &AS, ParsedAttributes &Attrs,
6263 DeclSpec::TST TagType, Decl *TagDecl,
6264 OpenACCDirectiveParseInfo &DirInfo);
6265 StmtResult ParseOpenACCAfterRoutineStmt(OpenACCDirectiveParseInfo &DirInfo);
6266
6267 ///@}
6268
6269 //
6270 //
6271 // -------------------------------------------------------------------------
6272 //
6273 //
6274
6275 /// \name OpenMP Constructs
6276 /// Implementations are in ParseOpenMP.cpp
6277 ///@{
6278
6279private:
6280 friend class ParsingOpenMPDirectiveRAII;
6281
6282 /// Parsing OpenMP directive mode.
6283 bool OpenMPDirectiveParsing = false;
6284
6285 /// Current kind of OpenMP clause
6286 OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
6287
6288 void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) {
6289 // If parsing the attributes found an OpenMP directive, emit those tokens
6290 // to the parse stream now.
6291 if (!OpenMPTokens.empty()) {
6292 PP.EnterToken(Tok, /*IsReinject*/ IsReinject: true);
6293 PP.EnterTokenStream(Toks: OpenMPTokens, /*DisableMacroExpansion*/ DisableMacroExpansion: true,
6294 /*IsReinject*/ IsReinject: true);
6295 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ ConsumeCodeCompletionTok: true);
6296 }
6297 }
6298
6299 //===--------------------------------------------------------------------===//
6300 // OpenMP: Directives and clauses.
6301
6302 /// Parse clauses for '#pragma omp declare simd'.
6303 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
6304 CachedTokens &Toks,
6305 SourceLocation Loc);
6306
6307 /// Parse a property kind into \p TIProperty for the selector set \p Set and
6308 /// selector \p Selector.
6309 void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
6310 llvm::omp::TraitSet Set,
6311 llvm::omp::TraitSelector Selector,
6312 llvm::StringMap<SourceLocation> &Seen);
6313
6314 /// Parse a selector kind into \p TISelector for the selector set \p Set.
6315 void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
6316 llvm::omp::TraitSet Set,
6317 llvm::StringMap<SourceLocation> &Seen);
6318
6319 /// Parse a selector set kind into \p TISet.
6320 void parseOMPTraitSetKind(OMPTraitSet &TISet,
6321 llvm::StringMap<SourceLocation> &Seen);
6322
6323 /// Parses an OpenMP context property.
6324 void parseOMPContextProperty(OMPTraitSelector &TISelector,
6325 llvm::omp::TraitSet Set,
6326 llvm::StringMap<SourceLocation> &Seen);
6327
6328 /// Parses an OpenMP context selector.
6329 ///
6330 /// \verbatim
6331 /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')']
6332 /// \endverbatim
6333 void parseOMPContextSelector(OMPTraitSelector &TISelector,
6334 llvm::omp::TraitSet Set,
6335 llvm::StringMap<SourceLocation> &SeenSelectors);
6336
6337 /// Parses an OpenMP context selector set.
6338 ///
6339 /// \verbatim
6340 /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}'
6341 /// \endverbatim
6342 void parseOMPContextSelectorSet(OMPTraitSet &TISet,
6343 llvm::StringMap<SourceLocation> &SeenSets);
6344
6345 /// Parse OpenMP context selectors:
6346 ///
6347 /// \verbatim
6348 /// <trait-set-selector> [, <trait-set-selector>]*
6349 /// \endverbatim
6350 bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
6351
6352 /// Parse an 'append_args' clause for '#pragma omp declare variant'.
6353 bool parseOpenMPAppendArgs(SmallVectorImpl<OMPInteropInfo> &InteropInfos);
6354
6355 /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
6356 /// if there was an error.
6357 bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
6358 OMPTraitInfo *ParentTI);
6359
6360 /// Parse clauses for '#pragma omp declare variant ( variant-func-id )
6361 /// clause'.
6362 void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
6363 SourceLocation Loc);
6364
6365 /// Parse 'omp [begin] assume[s]' directive.
6366 ///
6367 /// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]...
6368 /// where
6369 ///
6370 /// \verbatim
6371 /// clause:
6372 /// 'ext_IMPL_DEFINED'
6373 /// 'absent' '(' directive-name [, directive-name]* ')'
6374 /// 'contains' '(' directive-name [, directive-name]* ')'
6375 /// 'holds' '(' scalar-expression ')'
6376 /// 'no_openmp'
6377 /// 'no_openmp_routines'
6378 /// 'no_openmp_constructs' (OpenMP 6.0)
6379 /// 'no_parallelism'
6380 /// \endverbatim
6381 ///
6382 void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
6383 SourceLocation Loc);
6384
6385 /// Parse 'omp end assumes' directive.
6386 void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
6387
6388 /// Parses clauses for directive.
6389 ///
6390 /// \verbatim
6391 /// <clause> [clause[ [,] clause] ... ]
6392 ///
6393 /// clauses: for error directive
6394 /// 'at' '(' compilation | execution ')'
6395 /// 'severity' '(' fatal | warning ')'
6396 /// 'message' '(' msg-string ')'
6397 /// ....
6398 /// \endverbatim
6399 ///
6400 /// \param DKind Kind of current directive.
6401 /// \param clauses for current directive.
6402 /// \param start location for clauses of current directive
6403 void ParseOpenMPClauses(OpenMPDirectiveKind DKind,
6404 SmallVectorImpl<clang::OMPClause *> &Clauses,
6405 SourceLocation Loc);
6406
6407 /// Parse clauses for '#pragma omp [begin] declare target'.
6408 void ParseOMPDeclareTargetClauses(SemaOpenMP::DeclareTargetContextInfo &DTCI);
6409
6410 /// Parse '#pragma omp end declare target'.
6411 void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
6412 OpenMPDirectiveKind EndDKind,
6413 SourceLocation Loc);
6414
6415 /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
6416 /// it is not the current token.
6417 void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
6418
6419 /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
6420 /// that the "end" matching the "begin" directive of kind \p BeginKind was not
6421 /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
6422 /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
6423 void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
6424 OpenMPDirectiveKind ExpectedKind,
6425 OpenMPDirectiveKind FoundKind,
6426 SourceLocation MatchingLoc, SourceLocation FoundLoc,
6427 bool SkipUntilOpenMPEnd);
6428
6429 /// Parses declarative OpenMP directives.
6430 ///
6431 /// \verbatim
6432 /// threadprivate-directive:
6433 /// annot_pragma_openmp 'threadprivate' simple-variable-list
6434 /// annot_pragma_openmp_end
6435 ///
6436 /// allocate-directive:
6437 /// annot_pragma_openmp 'allocate' simple-variable-list [<clause>]
6438 /// annot_pragma_openmp_end
6439 ///
6440 /// declare-reduction-directive:
6441 /// annot_pragma_openmp 'declare' 'reduction' [...]
6442 /// annot_pragma_openmp_end
6443 ///
6444 /// declare-mapper-directive:
6445 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
6446 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6447 /// annot_pragma_openmp_end
6448 ///
6449 /// declare-simd-directive:
6450 /// annot_pragma_openmp 'declare simd' {<clause> [,]}
6451 /// annot_pragma_openmp_end
6452 /// <function declaration/definition>
6453 ///
6454 /// requires directive:
6455 /// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
6456 /// annot_pragma_openmp_end
6457 ///
6458 /// assumes directive:
6459 /// annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ]
6460 /// annot_pragma_openmp_end
6461 /// or
6462 /// annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ]
6463 /// annot_pragma_openmp 'end assumes'
6464 /// annot_pragma_openmp_end
6465 /// \endverbatim
6466 ///
6467 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
6468 AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed = false,
6469 DeclSpec::TST TagType = DeclSpec::TST_unspecified,
6470 Decl *TagDecl = nullptr);
6471
6472 /// Parse 'omp declare reduction' construct.
6473 ///
6474 /// \verbatim
6475 /// declare-reduction-directive:
6476 /// annot_pragma_openmp 'declare' 'reduction'
6477 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
6478 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
6479 /// annot_pragma_openmp_end
6480 /// \endverbatim
6481 /// <reduction_id> is either a base language identifier or one of the
6482 /// following operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
6483 ///
6484 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
6485
6486 /// Parses initializer for provided omp_priv declaration inside the reduction
6487 /// initializer.
6488 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
6489
6490 /// Parses 'omp declare mapper' directive.
6491 ///
6492 /// \verbatim
6493 /// declare-mapper-directive:
6494 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
6495 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6496 /// annot_pragma_openmp_end
6497 /// \endverbatim
6498 /// <mapper-identifier> and <var> are base language identifiers.
6499 ///
6500 DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
6501
6502 /// Parses variable declaration in 'omp declare mapper' directive.
6503 TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
6504 DeclarationName &Name,
6505 AccessSpecifier AS = AS_none);
6506
6507 /// Parses simple list of variables.
6508 ///
6509 /// \verbatim
6510 /// simple-variable-list:
6511 /// '(' id-expression {, id-expression} ')'
6512 /// \endverbatim
6513 ///
6514 /// \param Kind Kind of the directive.
6515 /// \param Callback Callback function to be called for the list elements.
6516 /// \param AllowScopeSpecifier true, if the variables can have fully
6517 /// qualified names.
6518 ///
6519 bool ParseOpenMPSimpleVarList(
6520 OpenMPDirectiveKind Kind,
6521 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
6522 &Callback,
6523 bool AllowScopeSpecifier);
6524
6525 /// Parses declarative or executable directive.
6526 ///
6527 /// \verbatim
6528 /// threadprivate-directive:
6529 /// annot_pragma_openmp 'threadprivate' simple-variable-list
6530 /// annot_pragma_openmp_end
6531 ///
6532 /// allocate-directive:
6533 /// annot_pragma_openmp 'allocate' simple-variable-list
6534 /// annot_pragma_openmp_end
6535 ///
6536 /// declare-reduction-directive:
6537 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
6538 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '('
6539 /// ('omp_priv' '=' <expression>|<function_call>) ')']
6540 /// annot_pragma_openmp_end
6541 ///
6542 /// declare-mapper-directive:
6543 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
6544 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6545 /// annot_pragma_openmp_end
6546 ///
6547 /// executable-directive:
6548 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
6549 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
6550 /// 'parallel for' | 'parallel sections' | 'parallel master' | 'task'
6551 /// | 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' |
6552 /// 'error' | 'atomic' | 'for simd' | 'parallel for simd' | 'target' |
6553 /// 'target data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop
6554 /// simd' | 'master taskloop' | 'master taskloop simd' | 'parallel
6555 /// master taskloop' | 'parallel master taskloop simd' | 'distribute'
6556 /// | 'target enter data' | 'target exit data' | 'target parallel' |
6557 /// 'target parallel for' | 'target update' | 'distribute parallel
6558 /// for' | 'distribute paralle for simd' | 'distribute simd' | 'target
6559 /// parallel for simd' | 'target simd' | 'teams distribute' | 'teams
6560 /// distribute simd' | 'teams distribute parallel for simd' | 'teams
6561 /// distribute parallel for' | 'target teams' | 'target teams
6562 /// distribute' | 'target teams distribute parallel for' | 'target
6563 /// teams distribute parallel for simd' | 'target teams distribute
6564 /// simd' | 'masked' | 'parallel masked' {clause}
6565 /// annot_pragma_openmp_end
6566 /// \endverbatim
6567 ///
6568 ///
6569 /// \param StmtCtx The context in which we're parsing the directive.
6570 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6571 /// metadirective and therefore ends on the closing paren.
6572 StmtResult ParseOpenMPDeclarativeOrExecutableDirective(
6573 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective = false);
6574
6575 /// Parses executable directive.
6576 ///
6577 /// \param StmtCtx The context in which we're parsing the directive.
6578 /// \param DKind The kind of the executable directive.
6579 /// \param Loc Source location of the beginning of the directive.
6580 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6581 /// metadirective and therefore ends on the closing paren.
6582 StmtResult
6583 ParseOpenMPExecutableDirective(ParsedStmtContext StmtCtx,
6584 OpenMPDirectiveKind DKind, SourceLocation Loc,
6585 bool ReadDirectiveWithinMetadirective);
6586
6587 /// Parses informational directive.
6588 ///
6589 /// \param StmtCtx The context in which we're parsing the directive.
6590 /// \param DKind The kind of the informational directive.
6591 /// \param Loc Source location of the beginning of the directive.
6592 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6593 /// metadirective and therefore ends on the closing paren.
6594 StmtResult ParseOpenMPInformationalDirective(
6595 ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
6596 bool ReadDirectiveWithinMetadirective);
6597
6598 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
6599 ///
6600 /// \verbatim
6601 /// clause:
6602 /// if-clause | final-clause | num_threads-clause | safelen-clause |
6603 /// default-clause | private-clause | firstprivate-clause |
6604 /// shared-clause | linear-clause | aligned-clause | collapse-clause |
6605 /// bind-clause | lastprivate-clause | reduction-clause |
6606 /// proc_bind-clause | schedule-clause | copyin-clause |
6607 /// copyprivate-clause | untied-clause | mergeable-clause | flush-clause
6608 /// | read-clause | write-clause | update-clause | capture-clause |
6609 /// seq_cst-clause | device-clause | simdlen-clause | threads-clause |
6610 /// simd-clause | num_teams-clause | thread_limit-clause |
6611 /// priority-clause | grainsize-clause | nogroup-clause |
6612 /// num_tasks-clause | hint-clause | to-clause | from-clause |
6613 /// is_device_ptr-clause | task_reduction-clause | in_reduction-clause |
6614 /// allocator-clause | allocate-clause | acq_rel-clause | acquire-clause
6615 /// | release-clause | relaxed-clause | depobj-clause | destroy-clause |
6616 /// detach-clause | inclusive-clause | exclusive-clause |
6617 /// uses_allocators-clause | use_device_addr-clause | has_device_addr
6618 /// \endverbatim
6619 ///
6620 /// \param DKind Kind of current directive.
6621 /// \param CKind Kind of current clause.
6622 /// \param FirstClause true, if this is the first clause of a kind \a CKind
6623 /// in current directive.
6624 ///
6625 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
6626 OpenMPClauseKind CKind, bool FirstClause);
6627
6628 /// Parses clause with a single expression of a kind \a Kind.
6629 ///
6630 /// Parsing of OpenMP clauses with single expressions like 'final',
6631 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
6632 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
6633 /// 'detach'.
6634 ///
6635 /// \verbatim
6636 /// final-clause:
6637 /// 'final' '(' expression ')'
6638 ///
6639 /// num_threads-clause:
6640 /// 'num_threads' '(' expression ')'
6641 ///
6642 /// safelen-clause:
6643 /// 'safelen' '(' expression ')'
6644 ///
6645 /// simdlen-clause:
6646 /// 'simdlen' '(' expression ')'
6647 ///
6648 /// collapse-clause:
6649 /// 'collapse' '(' expression ')'
6650 ///
6651 /// priority-clause:
6652 /// 'priority' '(' expression ')'
6653 ///
6654 /// grainsize-clause:
6655 /// 'grainsize' '(' expression ')'
6656 ///
6657 /// num_tasks-clause:
6658 /// 'num_tasks' '(' expression ')'
6659 ///
6660 /// hint-clause:
6661 /// 'hint' '(' expression ')'
6662 ///
6663 /// allocator-clause:
6664 /// 'allocator' '(' expression ')'
6665 ///
6666 /// detach-clause:
6667 /// 'detach' '(' event-handler-expression ')'
6668 ///
6669 /// align-clause
6670 /// 'align' '(' positive-integer-constant ')'
6671 ///
6672 /// holds-clause
6673 /// 'holds' '(' expression ')'
6674 /// \endverbatim
6675 ///
6676 /// \param Kind Kind of current clause.
6677 /// \param ParseOnly true to skip the clause's semantic actions and return
6678 /// nullptr.
6679 ///
6680 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly);
6681 /// Parses simple clause like 'default' or 'proc_bind' of a kind \a Kind.
6682 ///
6683 /// \verbatim
6684 /// default-clause:
6685 /// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')'
6686 ///
6687 /// proc_bind-clause:
6688 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')'
6689 ///
6690 /// bind-clause:
6691 /// 'bind' '(' 'teams' | 'parallel' | 'thread' ')'
6692 ///
6693 /// update-clause:
6694 /// 'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' |
6695 /// 'inoutset' ')'
6696 /// \endverbatim
6697 ///
6698 /// \param Kind Kind of current clause.
6699 /// \param ParseOnly true to skip the clause's semantic actions and return
6700 /// nullptr.
6701 ///
6702 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
6703
6704 /// Parse indirect clause for '#pragma omp declare target' directive.
6705 /// 'indirect' '[' '(' invoked-by-fptr ')' ']'
6706 /// where invoked-by-fptr is a constant boolean expression that evaluates to
6707 /// true or false at compile time.
6708 /// \param ParseOnly true to skip the clause's semantic actions and return
6709 /// false;
6710 bool ParseOpenMPIndirectClause(SemaOpenMP::DeclareTargetContextInfo &DTCI,
6711 bool ParseOnly);
6712 /// Parses clause with a single expression and an additional argument
6713 /// of a kind \a Kind like 'schedule' or 'dist_schedule'.
6714 ///
6715 /// \verbatim
6716 /// schedule-clause:
6717 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
6718 /// ')'
6719 ///
6720 /// if-clause:
6721 /// 'if' '(' [ directive-name-modifier ':' ] expression ')'
6722 ///
6723 /// defaultmap:
6724 /// 'defaultmap' '(' modifier [ ':' kind ] ')'
6725 ///
6726 /// device-clause:
6727 /// 'device' '(' [ device-modifier ':' ] expression ')'
6728 /// \endverbatim
6729 ///
6730 /// \param DKind Directive kind.
6731 /// \param Kind Kind of current clause.
6732 /// \param ParseOnly true to skip the clause's semantic actions and return
6733 /// nullptr.
6734 ///
6735 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
6736 OpenMPClauseKind Kind,
6737 bool ParseOnly);
6738
6739 /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
6740 OMPClause *ParseOpenMPSizesClause();
6741
6742 /// Parses the 'permutation' clause of a '#pragma omp interchange' directive.
6743 OMPClause *ParseOpenMPPermutationClause();
6744
6745 /// Parses clause without any additional arguments like 'ordered'.
6746 ///
6747 /// \verbatim
6748 /// ordered-clause:
6749 /// 'ordered'
6750 ///
6751 /// nowait-clause:
6752 /// 'nowait'
6753 ///
6754 /// untied-clause:
6755 /// 'untied'
6756 ///
6757 /// mergeable-clause:
6758 /// 'mergeable'
6759 ///
6760 /// read-clause:
6761 /// 'read'
6762 ///
6763 /// threads-clause:
6764 /// 'threads'
6765 ///
6766 /// simd-clause:
6767 /// 'simd'
6768 ///
6769 /// nogroup-clause:
6770 /// 'nogroup'
6771 /// \endverbatim
6772 ///
6773 /// \param Kind Kind of current clause.
6774 /// \param ParseOnly true to skip the clause's semantic actions and return
6775 /// nullptr.
6776 ///
6777 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
6778
6779 /// Parses clause with the list of variables of a kind \a Kind:
6780 /// 'private', 'firstprivate', 'lastprivate',
6781 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
6782 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
6783 ///
6784 /// \verbatim
6785 /// private-clause:
6786 /// 'private' '(' list ')'
6787 /// firstprivate-clause:
6788 /// 'firstprivate' '(' list ')'
6789 /// lastprivate-clause:
6790 /// 'lastprivate' '(' list ')'
6791 /// shared-clause:
6792 /// 'shared' '(' list ')'
6793 /// linear-clause:
6794 /// 'linear' '(' linear-list [ ':' linear-step ] ')'
6795 /// aligned-clause:
6796 /// 'aligned' '(' list [ ':' alignment ] ')'
6797 /// reduction-clause:
6798 /// 'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
6799 /// task_reduction-clause:
6800 /// 'task_reduction' '(' reduction-identifier ':' list ')'
6801 /// in_reduction-clause:
6802 /// 'in_reduction' '(' reduction-identifier ':' list ')'
6803 /// copyprivate-clause:
6804 /// 'copyprivate' '(' list ')'
6805 /// flush-clause:
6806 /// 'flush' '(' list ')'
6807 /// depend-clause:
6808 /// 'depend' '(' in | out | inout : list | source ')'
6809 /// map-clause:
6810 /// 'map' '(' [ [ always [,] ] [ close [,] ]
6811 /// [ mapper '(' mapper-identifier ')' [,] ]
6812 /// to | from | tofrom | alloc | release | delete ':' ] list ')';
6813 /// to-clause:
6814 /// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
6815 /// from-clause:
6816 /// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
6817 /// use_device_ptr-clause:
6818 /// 'use_device_ptr' '(' list ')'
6819 /// use_device_addr-clause:
6820 /// 'use_device_addr' '(' list ')'
6821 /// is_device_ptr-clause:
6822 /// 'is_device_ptr' '(' list ')'
6823 /// has_device_addr-clause:
6824 /// 'has_device_addr' '(' list ')'
6825 /// allocate-clause:
6826 /// 'allocate' '(' [ allocator ':' ] list ')'
6827 /// As of OpenMP 5.1 there's also
6828 /// 'allocate' '(' allocate-modifier: list ')'
6829 /// where allocate-modifier is: 'allocator' '(' allocator ')'
6830 /// nontemporal-clause:
6831 /// 'nontemporal' '(' list ')'
6832 /// inclusive-clause:
6833 /// 'inclusive' '(' list ')'
6834 /// exclusive-clause:
6835 /// 'exclusive' '(' list ')'
6836 /// \endverbatim
6837 ///
6838 /// For 'linear' clause linear-list may have the following forms:
6839 /// list
6840 /// modifier(list)
6841 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
6842 ///
6843 /// \param Kind Kind of current clause.
6844 /// \param ParseOnly true to skip the clause's semantic actions and return
6845 /// nullptr.
6846 ///
6847 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
6848 OpenMPClauseKind Kind, bool ParseOnly);
6849
6850 /// Parses a clause consisting of a list of expressions.
6851 ///
6852 /// \param Kind The clause to parse.
6853 /// \param ClauseNameLoc [out] The location of the clause name.
6854 /// \param OpenLoc [out] The location of '('.
6855 /// \param CloseLoc [out] The location of ')'.
6856 /// \param Exprs [out] The parsed expressions.
6857 /// \param ReqIntConst If true, each expression must be an integer constant.
6858 ///
6859 /// \return Whether the clause was parsed successfully.
6860 bool ParseOpenMPExprListClause(OpenMPClauseKind Kind,
6861 SourceLocation &ClauseNameLoc,
6862 SourceLocation &OpenLoc,
6863 SourceLocation &CloseLoc,
6864 SmallVectorImpl<Expr *> &Exprs,
6865 bool ReqIntConst = false);
6866
6867 /// Parses simple expression in parens for single-expression clauses of OpenMP
6868 /// constructs.
6869 /// \verbatim
6870 /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
6871 /// <range-specification> }+ ')'
6872 /// \endverbatim
6873 ExprResult ParseOpenMPIteratorsExpr();
6874
6875 /// Parses allocators and traits in the context of the uses_allocator clause.
6876 /// Expected format:
6877 /// \verbatim
6878 /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
6879 /// \endverbatim
6880 OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
6881
6882 /// Parses the 'interop' parts of the 'append_args' and 'init' clauses.
6883 bool ParseOMPInteropInfo(OMPInteropInfo &InteropInfo, OpenMPClauseKind Kind);
6884
6885 /// Parses clause with an interop variable of kind \a Kind.
6886 ///
6887 /// \verbatim
6888 /// init-clause:
6889 /// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var)
6890 ///
6891 /// destroy-clause:
6892 /// destroy(interop-var)
6893 ///
6894 /// use-clause:
6895 /// use(interop-var)
6896 ///
6897 /// interop-modifier:
6898 /// prefer_type(preference-list)
6899 ///
6900 /// preference-list:
6901 /// foreign-runtime-id [, foreign-runtime-id]...
6902 ///
6903 /// foreign-runtime-id:
6904 /// <string-literal> | <constant-integral-expression>
6905 ///
6906 /// interop-type:
6907 /// target | targetsync
6908 /// \endverbatim
6909 ///
6910 /// \param Kind Kind of current clause.
6911 /// \param ParseOnly true to skip the clause's semantic actions and return
6912 /// nullptr.
6913 //
6914 OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
6915
6916 /// Parses a ompx_attribute clause
6917 ///
6918 /// \param ParseOnly true to skip the clause's semantic actions and return
6919 /// nullptr.
6920 //
6921 OMPClause *ParseOpenMPOMPXAttributesClause(bool ParseOnly);
6922
6923public:
6924 /// Parses simple expression in parens for single-expression clauses of OpenMP
6925 /// constructs.
6926 /// \param RLoc Returned location of right paren.
6927 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
6928 bool IsAddressOfOperand = false);
6929
6930 /// Parses a reserved locator like 'omp_all_memory'.
6931 bool ParseOpenMPReservedLocator(OpenMPClauseKind Kind,
6932 SemaOpenMP::OpenMPVarListDataTy &Data,
6933 const LangOptions &LangOpts);
6934 /// Parses clauses with list.
6935 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
6936 SmallVectorImpl<Expr *> &Vars,
6937 SemaOpenMP::OpenMPVarListDataTy &Data);
6938
6939 /// Parses the mapper modifier in map, to, and from clauses.
6940 bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data);
6941
6942 /// Parse map-type-modifiers in map clause.
6943 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] [map-type] : ] list)
6944 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
6945 /// present
6946 /// where, map-type ::= alloc | delete | from | release | to | tofrom
6947 bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data);
6948
6949 /// Parses 'omp begin declare variant' directive.
6950 /// The syntax is:
6951 /// \verbatim
6952 /// { #pragma omp begin declare variant clause }
6953 /// <function-declaration-or-definition-sequence>
6954 /// { #pragma omp end declare variant }
6955 /// \endverbatim
6956 ///
6957 bool ParseOpenMPDeclareBeginVariantDirective(SourceLocation Loc);
6958
6959 ///@}
6960
6961 //
6962 //
6963 // -------------------------------------------------------------------------
6964 //
6965 //
6966
6967 /// \name Pragmas
6968 /// Implementations are in ParsePragma.cpp
6969 ///@{
6970
6971private:
6972 std::unique_ptr<PragmaHandler> AlignHandler;
6973 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
6974 std::unique_ptr<PragmaHandler> OptionsHandler;
6975 std::unique_ptr<PragmaHandler> PackHandler;
6976 std::unique_ptr<PragmaHandler> MSStructHandler;
6977 std::unique_ptr<PragmaHandler> UnusedHandler;
6978 std::unique_ptr<PragmaHandler> WeakHandler;
6979 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
6980 std::unique_ptr<PragmaHandler> FPContractHandler;
6981 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
6982 std::unique_ptr<PragmaHandler> OpenMPHandler;
6983 std::unique_ptr<PragmaHandler> OpenACCHandler;
6984 std::unique_ptr<PragmaHandler> PCSectionHandler;
6985 std::unique_ptr<PragmaHandler> MSCommentHandler;
6986 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
6987 std::unique_ptr<PragmaHandler> FPEvalMethodHandler;
6988 std::unique_ptr<PragmaHandler> FloatControlHandler;
6989 std::unique_ptr<PragmaHandler> MSPointersToMembers;
6990 std::unique_ptr<PragmaHandler> MSVtorDisp;
6991 std::unique_ptr<PragmaHandler> MSInitSeg;
6992 std::unique_ptr<PragmaHandler> MSDataSeg;
6993 std::unique_ptr<PragmaHandler> MSBSSSeg;
6994 std::unique_ptr<PragmaHandler> MSConstSeg;
6995 std::unique_ptr<PragmaHandler> MSCodeSeg;
6996 std::unique_ptr<PragmaHandler> MSSection;
6997 std::unique_ptr<PragmaHandler> MSStrictGuardStackCheck;
6998 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
6999 std::unique_ptr<PragmaHandler> MSIntrinsic;
7000 std::unique_ptr<PragmaHandler> MSFunction;
7001 std::unique_ptr<PragmaHandler> MSOptimize;
7002 std::unique_ptr<PragmaHandler> MSFenvAccess;
7003 std::unique_ptr<PragmaHandler> MSAllocText;
7004 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
7005 std::unique_ptr<PragmaHandler> OptimizeHandler;
7006 std::unique_ptr<PragmaHandler> LoopHintHandler;
7007 std::unique_ptr<PragmaHandler> UnrollHintHandler;
7008 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
7009 std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
7010 std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
7011 std::unique_ptr<PragmaHandler> FPHandler;
7012 std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
7013 std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
7014 std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
7015 std::unique_ptr<PragmaHandler> STDCUnknownHandler;
7016 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
7017 std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
7018 std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
7019 std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
7020
7021 /// Initialize all pragma handlers.
7022 void initializePragmaHandlers();
7023
7024 /// Destroy and reset all pragma handlers.
7025 void resetPragmaHandlers();
7026
7027 /// Handle the annotation token produced for #pragma unused(...)
7028 ///
7029 /// Each annot_pragma_unused is followed by the argument token so e.g.
7030 /// "#pragma unused(x,y)" becomes:
7031 /// annot_pragma_unused 'x' annot_pragma_unused 'y'
7032 void HandlePragmaUnused();
7033
7034 /// Handle the annotation token produced for
7035 /// #pragma GCC visibility...
7036 void HandlePragmaVisibility();
7037
7038 /// Handle the annotation token produced for
7039 /// #pragma pack...
7040 void HandlePragmaPack();
7041
7042 /// Handle the annotation token produced for
7043 /// #pragma ms_struct...
7044 void HandlePragmaMSStruct();
7045
7046 void HandlePragmaMSPointersToMembers();
7047
7048 void HandlePragmaMSVtorDisp();
7049
7050 void HandlePragmaMSPragma();
7051 bool HandlePragmaMSSection(StringRef PragmaName,
7052 SourceLocation PragmaLocation);
7053 bool HandlePragmaMSSegment(StringRef PragmaName,
7054 SourceLocation PragmaLocation);
7055
7056 // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
7057 bool HandlePragmaMSInitSeg(StringRef PragmaName,
7058 SourceLocation PragmaLocation);
7059
7060 // #pragma strict_gs_check(pop)
7061 // #pragma strict_gs_check(push, "on" | "off")
7062 // #pragma strict_gs_check("on" | "off")
7063 bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName,
7064 SourceLocation PragmaLocation);
7065 bool HandlePragmaMSFunction(StringRef PragmaName,
7066 SourceLocation PragmaLocation);
7067 bool HandlePragmaMSAllocText(StringRef PragmaName,
7068 SourceLocation PragmaLocation);
7069
7070 // #pragma optimize("gsty", on|off)
7071 bool HandlePragmaMSOptimize(StringRef PragmaName,
7072 SourceLocation PragmaLocation);
7073
7074 // #pragma intrinsic("foo")
7075 bool HandlePragmaMSIntrinsic(StringRef PragmaName,
7076 SourceLocation PragmaLocation);
7077
7078 /// Handle the annotation token produced for
7079 /// #pragma align...
7080 void HandlePragmaAlign();
7081
7082 /// Handle the annotation token produced for
7083 /// #pragma clang __debug dump...
7084 void HandlePragmaDump();
7085
7086 /// Handle the annotation token produced for
7087 /// #pragma weak id...
7088 void HandlePragmaWeak();
7089
7090 /// Handle the annotation token produced for
7091 /// #pragma weak id = id...
7092 void HandlePragmaWeakAlias();
7093
7094 /// Handle the annotation token produced for
7095 /// #pragma redefine_extname...
7096 void HandlePragmaRedefineExtname();
7097
7098 /// Handle the annotation token produced for
7099 /// #pragma STDC FP_CONTRACT...
7100 void HandlePragmaFPContract();
7101
7102 /// Handle the annotation token produced for
7103 /// #pragma STDC FENV_ACCESS...
7104 void HandlePragmaFEnvAccess();
7105
7106 /// Handle the annotation token produced for
7107 /// #pragma STDC FENV_ROUND...
7108 void HandlePragmaFEnvRound();
7109
7110 /// Handle the annotation token produced for
7111 /// #pragma STDC CX_LIMITED_RANGE...
7112 void HandlePragmaCXLimitedRange();
7113
7114 /// Handle the annotation token produced for
7115 /// #pragma float_control
7116 void HandlePragmaFloatControl();
7117
7118 /// \brief Handle the annotation token produced for
7119 /// #pragma clang fp ...
7120 void HandlePragmaFP();
7121
7122 /// Handle the annotation token produced for
7123 /// #pragma OPENCL EXTENSION...
7124 void HandlePragmaOpenCLExtension();
7125
7126 /// Handle the annotation token produced for
7127 /// #pragma clang __debug captured
7128 StmtResult HandlePragmaCaptured();
7129
7130 /// Handle the annotation token produced for
7131 /// #pragma clang loop and #pragma unroll.
7132 bool HandlePragmaLoopHint(LoopHint &Hint);
7133
7134 bool ParsePragmaAttributeSubjectMatchRuleSet(
7135 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
7136 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
7137
7138 void HandlePragmaAttribute();
7139
7140 ///@}
7141
7142 //
7143 //
7144 // -------------------------------------------------------------------------
7145 //
7146 //
7147
7148 /// \name Statements
7149 /// Implementations are in ParseStmt.cpp
7150 ///@{
7151
7152public:
7153 /// A SmallVector of statements.
7154 typedef SmallVector<Stmt *, 24> StmtVector;
7155
7156 /// The location of the first statement inside an else that might
7157 /// have a missleading indentation. If there is no
7158 /// MisleadingIndentationChecker on an else active, this location is invalid.
7159 SourceLocation MisleadingIndentationElseLoc;
7160
7161 private:
7162
7163 /// Flags describing a context in which we're parsing a statement.
7164 enum class ParsedStmtContext {
7165 /// This context permits declarations in language modes where declarations
7166 /// are not statements.
7167 AllowDeclarationsInC = 0x1,
7168 /// This context permits standalone OpenMP directives.
7169 AllowStandaloneOpenMPDirectives = 0x2,
7170 /// This context is at the top level of a GNU statement expression.
7171 InStmtExpr = 0x4,
7172
7173 /// The context of a regular substatement.
7174 SubStmt = 0,
7175 /// The context of a compound-statement.
7176 Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
7177
7178 LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
7179 };
7180
7181 /// Act on an expression statement that might be the last statement in a
7182 /// GNU statement expression. Checks whether we are actually at the end of
7183 /// a statement expression and builds a suitable expression statement.
7184 StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
7185
7186 //===--------------------------------------------------------------------===//
7187 // C99 6.8: Statements and Blocks.
7188
7189 /// Parse a standalone statement (for instance, as the body of an 'if',
7190 /// 'while', or 'for').
7191 StmtResult
7192 ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
7193 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
7194
7195 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
7196 /// \verbatim
7197 /// StatementOrDeclaration:
7198 /// statement
7199 /// declaration
7200 ///
7201 /// statement:
7202 /// labeled-statement
7203 /// compound-statement
7204 /// expression-statement
7205 /// selection-statement
7206 /// iteration-statement
7207 /// jump-statement
7208 /// [C++] declaration-statement
7209 /// [C++] try-block
7210 /// [MS] seh-try-block
7211 /// [OBC] objc-throw-statement
7212 /// [OBC] objc-try-catch-statement
7213 /// [OBC] objc-synchronized-statement
7214 /// [GNU] asm-statement
7215 /// [OMP] openmp-construct [TODO]
7216 ///
7217 /// labeled-statement:
7218 /// identifier ':' statement
7219 /// 'case' constant-expression ':' statement
7220 /// 'default' ':' statement
7221 ///
7222 /// selection-statement:
7223 /// if-statement
7224 /// switch-statement
7225 ///
7226 /// iteration-statement:
7227 /// while-statement
7228 /// do-statement
7229 /// for-statement
7230 ///
7231 /// expression-statement:
7232 /// expression[opt] ';'
7233 ///
7234 /// jump-statement:
7235 /// 'goto' identifier ';'
7236 /// 'continue' ';'
7237 /// 'break' ';'
7238 /// 'return' expression[opt] ';'
7239 /// [GNU] 'goto' '*' expression ';'
7240 ///
7241 /// [OBC] objc-throw-statement:
7242 /// [OBC] '@' 'throw' expression ';'
7243 /// [OBC] '@' 'throw' ';'
7244 /// \endverbatim
7245 ///
7246 StmtResult
7247 ParseStatementOrDeclaration(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7248 SourceLocation *TrailingElseLoc = nullptr);
7249
7250 StmtResult ParseStatementOrDeclarationAfterAttributes(
7251 StmtVector &Stmts, ParsedStmtContext StmtCtx,
7252 SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs,
7253 ParsedAttributes &DeclSpecAttrs);
7254
7255 /// Parse an expression statement.
7256 StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
7257
7258 /// ParseLabeledStatement - We have an identifier and a ':' after it.
7259 ///
7260 /// \verbatim
7261 /// label:
7262 /// identifier ':'
7263 /// [GNU] identifier ':' attributes[opt]
7264 ///
7265 /// labeled-statement:
7266 /// label statement
7267 /// \endverbatim
7268 ///
7269 StmtResult ParseLabeledStatement(ParsedAttributes &Attrs,
7270 ParsedStmtContext StmtCtx);
7271
7272 /// ParseCaseStatement
7273 /// \verbatim
7274 /// labeled-statement:
7275 /// 'case' constant-expression ':' statement
7276 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
7277 /// \endverbatim
7278 ///
7279 StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
7280 bool MissingCase = false,
7281 ExprResult Expr = ExprResult());
7282
7283 /// ParseDefaultStatement
7284 /// \verbatim
7285 /// labeled-statement:
7286 /// 'default' ':' statement
7287 /// \endverbatim
7288 /// Note that this does not parse the 'statement' at the end.
7289 ///
7290 StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
7291
7292 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
7293
7294 /// ParseCompoundStatement - Parse a "{}" block.
7295 ///
7296 /// \verbatim
7297 /// compound-statement: [C99 6.8.2]
7298 /// { block-item-list[opt] }
7299 /// [GNU] { label-declarations block-item-list } [TODO]
7300 ///
7301 /// block-item-list:
7302 /// block-item
7303 /// block-item-list block-item
7304 ///
7305 /// block-item:
7306 /// declaration
7307 /// [GNU] '__extension__' declaration
7308 /// statement
7309 ///
7310 /// [GNU] label-declarations:
7311 /// [GNU] label-declaration
7312 /// [GNU] label-declarations label-declaration
7313 ///
7314 /// [GNU] label-declaration:
7315 /// [GNU] '__label__' identifier-list ';'
7316 /// \endverbatim
7317 ///
7318 StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags);
7319
7320 /// Parse any pragmas at the start of the compound expression. We handle these
7321 /// separately since some pragmas (FP_CONTRACT) must appear before any C
7322 /// statement in the compound, but may be intermingled with other pragmas.
7323 void ParseCompoundStatementLeadingPragmas();
7324
7325 void DiagnoseLabelAtEndOfCompoundStatement();
7326
7327 /// Consume any extra semi-colons resulting in null statements,
7328 /// returning true if any tok::semi were consumed.
7329 bool ConsumeNullStmt(StmtVector &Stmts);
7330
7331 /// ParseCompoundStatementBody - Parse a sequence of statements optionally
7332 /// followed by a label and invoke the ActOnCompoundStmt action. This expects
7333 /// the '{' to be the current token, and consume the '}' at the end of the
7334 /// block. It does not manipulate the scope stack.
7335 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
7336
7337 /// ParseParenExprOrCondition:
7338 /// \verbatim
7339 /// [C ] '(' expression ')'
7340 /// [C++] '(' condition ')'
7341 /// [C++1z] '(' init-statement[opt] condition ')'
7342 /// \endverbatim
7343 ///
7344 /// This function parses and performs error recovery on the specified
7345 /// condition or expression (depending on whether we're in C++ or C mode).
7346 /// This function goes out of its way to recover well. It returns true if
7347 /// there was a parser error (the right paren couldn't be found), which
7348 /// indicates that the caller should try to recover harder. It returns false
7349 /// if the condition is successfully parsed. Note that a successful parse can
7350 /// still have semantic errors in the condition. Additionally, it will assign
7351 /// the location of the outer-most '(' and ')', to LParenLoc and RParenLoc,
7352 /// respectively.
7353 bool ParseParenExprOrCondition(StmtResult *InitStmt,
7354 Sema::ConditionResult &CondResult,
7355 SourceLocation Loc, Sema::ConditionKind CK,
7356 SourceLocation &LParenLoc,
7357 SourceLocation &RParenLoc);
7358
7359 /// ParseIfStatement
7360 /// \verbatim
7361 /// if-statement: [C99 6.8.4.1]
7362 /// 'if' '(' expression ')' statement
7363 /// 'if' '(' expression ')' statement 'else' statement
7364 /// [C++] 'if' '(' condition ')' statement
7365 /// [C++] 'if' '(' condition ')' statement 'else' statement
7366 /// [C++23] 'if' '!' [opt] consteval compound-statement
7367 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
7368 /// \endverbatim
7369 ///
7370 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
7371
7372 /// ParseSwitchStatement
7373 /// \verbatim
7374 /// switch-statement:
7375 /// 'switch' '(' expression ')' statement
7376 /// [C++] 'switch' '(' condition ')' statement
7377 /// \endverbatim
7378 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
7379
7380 /// ParseWhileStatement
7381 /// \verbatim
7382 /// while-statement: [C99 6.8.5.1]
7383 /// 'while' '(' expression ')' statement
7384 /// [C++] 'while' '(' condition ')' statement
7385 /// \endverbatim
7386 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
7387
7388 /// ParseDoStatement
7389 /// \verbatim
7390 /// do-statement: [C99 6.8.5.2]
7391 /// 'do' statement 'while' '(' expression ')' ';'
7392 /// \endverbatim
7393 /// Note: this lets the caller parse the end ';'.
7394 StmtResult ParseDoStatement();
7395
7396 /// ParseForStatement
7397 /// \verbatim
7398 /// for-statement: [C99 6.8.5.3]
7399 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
7400 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
7401 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
7402 /// [C++] statement
7403 /// [C++0x] 'for'
7404 /// 'co_await'[opt] [Coroutines]
7405 /// '(' for-range-declaration ':' for-range-initializer ')'
7406 /// statement
7407 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
7408 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
7409 ///
7410 /// [C++] for-init-statement:
7411 /// [C++] expression-statement
7412 /// [C++] simple-declaration
7413 /// [C++23] alias-declaration
7414 ///
7415 /// [C++0x] for-range-declaration:
7416 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
7417 /// [C++0x] for-range-initializer:
7418 /// [C++0x] expression
7419 /// [C++0x] braced-init-list [TODO]
7420 /// \endverbatim
7421 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
7422
7423 /// ParseGotoStatement
7424 /// \verbatim
7425 /// jump-statement:
7426 /// 'goto' identifier ';'
7427 /// [GNU] 'goto' '*' expression ';'
7428 /// \endverbatim
7429 ///
7430 /// Note: this lets the caller parse the end ';'.
7431 ///
7432 StmtResult ParseGotoStatement();
7433
7434 /// ParseContinueStatement
7435 /// \verbatim
7436 /// jump-statement:
7437 /// 'continue' ';'
7438 /// \endverbatim
7439 ///
7440 /// Note: this lets the caller parse the end ';'.
7441 ///
7442 StmtResult ParseContinueStatement();
7443
7444 /// ParseBreakStatement
7445 /// \verbatim
7446 /// jump-statement:
7447 /// 'break' ';'
7448 /// \endverbatim
7449 ///
7450 /// Note: this lets the caller parse the end ';'.
7451 ///
7452 StmtResult ParseBreakStatement();
7453
7454 /// ParseReturnStatement
7455 /// \verbatim
7456 /// jump-statement:
7457 /// 'return' expression[opt] ';'
7458 /// 'return' braced-init-list ';'
7459 /// 'co_return' expression[opt] ';'
7460 /// 'co_return' braced-init-list ';'
7461 /// \endverbatim
7462 StmtResult ParseReturnStatement();
7463
7464 StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7465 SourceLocation *TrailingElseLoc,
7466 ParsedAttributes &Attrs);
7467
7468 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
7469
7470 //===--------------------------------------------------------------------===//
7471 // C++ 6: Statements and Blocks
7472
7473 /// ParseCXXTryBlock - Parse a C++ try-block.
7474 ///
7475 /// \verbatim
7476 /// try-block:
7477 /// 'try' compound-statement handler-seq
7478 /// \endverbatim
7479 ///
7480 StmtResult ParseCXXTryBlock();
7481
7482 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
7483 /// function-try-block.
7484 ///
7485 /// \verbatim
7486 /// try-block:
7487 /// 'try' compound-statement handler-seq
7488 ///
7489 /// function-try-block:
7490 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7491 ///
7492 /// handler-seq:
7493 /// handler handler-seq[opt]
7494 ///
7495 /// [Borland] try-block:
7496 /// 'try' compound-statement seh-except-block
7497 /// 'try' compound-statement seh-finally-block
7498 /// \endverbatim
7499 ///
7500 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
7501
7502 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the
7503 /// standard
7504 ///
7505 /// \verbatim
7506 /// handler:
7507 /// 'catch' '(' exception-declaration ')' compound-statement
7508 ///
7509 /// exception-declaration:
7510 /// attribute-specifier-seq[opt] type-specifier-seq declarator
7511 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
7512 /// '...'
7513 /// \endverbatim
7514 ///
7515 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
7516
7517 //===--------------------------------------------------------------------===//
7518 // MS: SEH Statements and Blocks
7519
7520 /// ParseSEHTryBlockCommon
7521 ///
7522 /// \verbatim
7523 /// seh-try-block:
7524 /// '__try' compound-statement seh-handler
7525 ///
7526 /// seh-handler:
7527 /// seh-except-block
7528 /// seh-finally-block
7529 /// \endverbatim
7530 ///
7531 StmtResult ParseSEHTryBlock();
7532
7533 /// ParseSEHExceptBlock - Handle __except
7534 ///
7535 /// \verbatim
7536 /// seh-except-block:
7537 /// '__except' '(' seh-filter-expression ')' compound-statement
7538 /// \endverbatim
7539 ///
7540 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
7541
7542 /// ParseSEHFinallyBlock - Handle __finally
7543 ///
7544 /// \verbatim
7545 /// seh-finally-block:
7546 /// '__finally' compound-statement
7547 /// \endverbatim
7548 ///
7549 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
7550
7551 StmtResult ParseSEHLeaveStatement();
7552
7553 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
7554
7555 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
7556 ///
7557 /// \verbatim
7558 /// function-try-block:
7559 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7560 /// \endverbatim
7561 ///
7562 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
7563
7564 /// When in code-completion, skip parsing of the function/method body
7565 /// unless the body contains the code-completion point.
7566 ///
7567 /// \returns true if the function body was skipped.
7568 bool trySkippingFunctionBody();
7569
7570 /// isDeclarationStatement - Disambiguates between a declaration or an
7571 /// expression statement, when parsing function bodies.
7572 ///
7573 /// \param DisambiguatingWithExpression - True to indicate that the purpose of
7574 /// this check is to disambiguate between an expression and a declaration.
7575 /// Returns true for declaration, false for expression.
7576 bool isDeclarationStatement(bool DisambiguatingWithExpression = false) {
7577 if (getLangOpts().CPlusPlus)
7578 return isCXXDeclarationStatement(DisambiguatingWithExpression);
7579 return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No, DisambiguatingWithExpression: true);
7580 }
7581
7582 /// isForInitDeclaration - Disambiguates between a declaration or an
7583 /// expression in the context of the C 'clause-1' or the C++
7584 // 'for-init-statement' part of a 'for' statement.
7585 /// Returns true for declaration, false for expression.
7586 bool isForInitDeclaration() {
7587 if (getLangOpts().OpenMP)
7588 Actions.OpenMP().startOpenMPLoop();
7589 if (getLangOpts().CPlusPlus)
7590 return Tok.is(K: tok::kw_using) ||
7591 isCXXSimpleDeclaration(/*AllowForRangeDecl=*/AllowForRangeDecl: true);
7592 return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No, DisambiguatingWithExpression: true);
7593 }
7594
7595 /// Determine whether this is a C++1z for-range-identifier.
7596 bool isForRangeIdentifier();
7597
7598 ///@}
7599
7600 //
7601 //
7602 // -------------------------------------------------------------------------
7603 //
7604 //
7605
7606 /// \name `inline asm` Statement
7607 /// Implementations are in ParseStmtAsm.cpp
7608 ///@{
7609
7610public:
7611 /// Parse an identifier in an MS-style inline assembly block.
7612 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
7613 unsigned &NumLineToksConsumed,
7614 bool IsUnevaluated);
7615
7616private:
7617 /// ParseAsmStatement - Parse a GNU extended asm statement.
7618 /// \verbatim
7619 /// asm-statement:
7620 /// gnu-asm-statement
7621 /// ms-asm-statement
7622 ///
7623 /// [GNU] gnu-asm-statement:
7624 /// 'asm' asm-qualifier-list[opt] '(' asm-argument ')' ';'
7625 ///
7626 /// [GNU] asm-argument:
7627 /// asm-string-literal
7628 /// asm-string-literal ':' asm-operands[opt]
7629 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7630 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7631 /// ':' asm-clobbers
7632 ///
7633 /// [GNU] asm-clobbers:
7634 /// asm-string-literal
7635 /// asm-clobbers ',' asm-string-literal
7636 /// \endverbatim
7637 ///
7638 StmtResult ParseAsmStatement(bool &msAsm);
7639
7640 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
7641 /// this routine is called to collect the tokens for an MS asm statement.
7642 ///
7643 /// \verbatim
7644 /// [MS] ms-asm-statement:
7645 /// ms-asm-block
7646 /// ms-asm-block ms-asm-statement
7647 ///
7648 /// [MS] ms-asm-block:
7649 /// '__asm' ms-asm-line '\n'
7650 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
7651 ///
7652 /// [MS] ms-asm-instruction-block
7653 /// ms-asm-line
7654 /// ms-asm-line '\n' ms-asm-instruction-block
7655 /// \endverbatim
7656 ///
7657 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
7658
7659 /// ParseAsmOperands - Parse the asm-operands production as used by
7660 /// asm-statement, assuming the leading ':' token was eaten.
7661 ///
7662 /// \verbatim
7663 /// [GNU] asm-operands:
7664 /// asm-operand
7665 /// asm-operands ',' asm-operand
7666 ///
7667 /// [GNU] asm-operand:
7668 /// asm-string-literal '(' expression ')'
7669 /// '[' identifier ']' asm-string-literal '(' expression ')'
7670 /// \endverbatim
7671 ///
7672 // FIXME: Avoid unnecessary std::string trashing.
7673 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
7674 SmallVectorImpl<Expr *> &Constraints,
7675 SmallVectorImpl<Expr *> &Exprs);
7676
7677 class GNUAsmQualifiers {
7678 unsigned Qualifiers = AQ_unspecified;
7679
7680 public:
7681 enum AQ {
7682 AQ_unspecified = 0,
7683 AQ_volatile = 1,
7684 AQ_inline = 2,
7685 AQ_goto = 4,
7686 };
7687 static const char *getQualifierName(AQ Qualifier);
7688 bool setAsmQualifier(AQ Qualifier);
7689 inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
7690 inline bool isInline() const { return Qualifiers & AQ_inline; };
7691 inline bool isGoto() const { return Qualifiers & AQ_goto; }
7692 };
7693
7694 // Determine if this is a GCC-style asm statement.
7695 bool isGCCAsmStatement(const Token &TokAfterAsm) const;
7696
7697 bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
7698 GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
7699
7700 /// parseGNUAsmQualifierListOpt - Parse a GNU extended asm qualifier list.
7701 /// \verbatim
7702 /// asm-qualifier:
7703 /// volatile
7704 /// inline
7705 /// goto
7706 ///
7707 /// asm-qualifier-list:
7708 /// asm-qualifier
7709 /// asm-qualifier-list asm-qualifier
7710 /// \endverbatim
7711 bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
7712
7713 ///@}
7714
7715 //
7716 //
7717 // -------------------------------------------------------------------------
7718 //
7719 //
7720
7721 /// \name C++ Templates
7722 /// Implementations are in ParseTemplate.cpp
7723 ///@{
7724
7725public:
7726 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
7727
7728 /// Re-enter a possible template scope, creating as many template parameter
7729 /// scopes as necessary.
7730 /// \return The number of template parameter scopes entered.
7731 unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D);
7732
7733private:
7734 /// The "depth" of the template parameters currently being parsed.
7735 unsigned TemplateParameterDepth;
7736
7737 /// RAII class that manages the template parameter depth.
7738 class TemplateParameterDepthRAII {
7739 unsigned &Depth;
7740 unsigned AddedLevels;
7741
7742 public:
7743 explicit TemplateParameterDepthRAII(unsigned &Depth)
7744 : Depth(Depth), AddedLevels(0) {}
7745
7746 ~TemplateParameterDepthRAII() { Depth -= AddedLevels; }
7747
7748 void operator++() {
7749 ++Depth;
7750 ++AddedLevels;
7751 }
7752 void addDepth(unsigned D) {
7753 Depth += D;
7754 AddedLevels += D;
7755 }
7756 void setAddedDepth(unsigned D) {
7757 Depth = Depth - AddedLevels + D;
7758 AddedLevels = D;
7759 }
7760
7761 unsigned getDepth() const { return Depth; }
7762 unsigned getOriginalDepth() const { return Depth - AddedLevels; }
7763 };
7764
7765 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
7766 /// top-level declaration is finished.
7767 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
7768
7769 /// Don't destroy template annotations in MaybeDestroyTemplateIds even if
7770 /// we're at the end of a declaration. Instead, we defer the destruction until
7771 /// after a top-level declaration.
7772 /// Use DelayTemplateIdDestructionRAII rather than setting it directly.
7773 bool DelayTemplateIdDestruction = false;
7774
7775 void MaybeDestroyTemplateIds() {
7776 if (DelayTemplateIdDestruction)
7777 return;
7778 if (!TemplateIds.empty() &&
7779 (Tok.is(K: tok::eof) || !PP.mightHavePendingAnnotationTokens()))
7780 DestroyTemplateIds();
7781 }
7782 void DestroyTemplateIds();
7783
7784 /// RAII object to destroy TemplateIdAnnotations where possible, from a
7785 /// likely-good position during parsing.
7786 struct DestroyTemplateIdAnnotationsRAIIObj {
7787 Parser &Self;
7788
7789 DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
7790 ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
7791 };
7792
7793 struct DelayTemplateIdDestructionRAII {
7794 Parser &Self;
7795 bool PrevDelayTemplateIdDestruction;
7796
7797 DelayTemplateIdDestructionRAII(Parser &Self,
7798 bool DelayTemplateIdDestruction) noexcept
7799 : Self(Self),
7800 PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) {
7801 Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction;
7802 }
7803
7804 ~DelayTemplateIdDestructionRAII() noexcept {
7805 Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction;
7806 }
7807 };
7808
7809 /// Identifiers which have been declared within a tentative parse.
7810 SmallVector<const IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
7811
7812 /// Tracker for '<' tokens that might have been intended to be treated as an
7813 /// angle bracket instead of a less-than comparison.
7814 ///
7815 /// This happens when the user intends to form a template-id, but typoes the
7816 /// template-name or forgets a 'template' keyword for a dependent template
7817 /// name.
7818 ///
7819 /// We track these locations from the point where we see a '<' with a
7820 /// name-like expression on its left until we see a '>' or '>>' that might
7821 /// match it.
7822 struct AngleBracketTracker {
7823 /// Flags used to rank candidate template names when there is more than one
7824 /// '<' in a scope.
7825 enum Priority : unsigned short {
7826 /// A non-dependent name that is a potential typo for a template name.
7827 PotentialTypo = 0x0,
7828 /// A dependent name that might instantiate to a template-name.
7829 DependentName = 0x2,
7830
7831 /// A space appears before the '<' token.
7832 SpaceBeforeLess = 0x0,
7833 /// No space before the '<' token
7834 NoSpaceBeforeLess = 0x1,
7835
7836 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
7837 };
7838
7839 struct Loc {
7840 Expr *TemplateName;
7841 SourceLocation LessLoc;
7842 AngleBracketTracker::Priority Priority;
7843 unsigned short ParenCount, BracketCount, BraceCount;
7844
7845 bool isActive(Parser &P) const {
7846 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
7847 P.BraceCount == BraceCount;
7848 }
7849
7850 bool isActiveOrNested(Parser &P) const {
7851 return isActive(P) || P.ParenCount > ParenCount ||
7852 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
7853 }
7854 };
7855
7856 SmallVector<Loc, 8> Locs;
7857
7858 /// Add an expression that might have been intended to be a template name.
7859 /// In the case of ambiguity, we arbitrarily select the innermost such
7860 /// expression, for example in 'foo < bar < baz', 'bar' is the current
7861 /// candidate. No attempt is made to track that 'foo' is also a candidate
7862 /// for the case where we see a second suspicious '>' token.
7863 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
7864 Priority Prio) {
7865 if (!Locs.empty() && Locs.back().isActive(P)) {
7866 if (Locs.back().Priority <= Prio) {
7867 Locs.back().TemplateName = TemplateName;
7868 Locs.back().LessLoc = LessLoc;
7869 Locs.back().Priority = Prio;
7870 }
7871 } else {
7872 Locs.push_back(Elt: {.TemplateName: TemplateName, .LessLoc: LessLoc, .Priority: Prio, .ParenCount: P.ParenCount,
7873 .BracketCount: P.BracketCount, .BraceCount: P.BraceCount});
7874 }
7875 }
7876
7877 /// Mark the current potential missing template location as having been
7878 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
7879 /// or leave a bracket scope).
7880 void clear(Parser &P) {
7881 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
7882 Locs.pop_back();
7883 }
7884
7885 /// Get the current enclosing expression that might hve been intended to be
7886 /// a template name.
7887 Loc *getCurrent(Parser &P) {
7888 if (!Locs.empty() && Locs.back().isActive(P))
7889 return &Locs.back();
7890 return nullptr;
7891 }
7892 };
7893
7894 AngleBracketTracker AngleBrackets;
7895
7896 /// Contains information about any template-specific
7897 /// information that has been parsed prior to parsing declaration
7898 /// specifiers.
7899 struct ParsedTemplateInfo {
7900 ParsedTemplateInfo()
7901 : Kind(ParsedTemplateKind::NonTemplate), TemplateParams(nullptr) {}
7902
7903 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
7904 bool isSpecialization,
7905 bool lastParameterListWasEmpty = false)
7906 : Kind(isSpecialization ? ParsedTemplateKind::ExplicitSpecialization
7907 : ParsedTemplateKind::Template),
7908 TemplateParams(TemplateParams),
7909 LastParameterListWasEmpty(lastParameterListWasEmpty) {}
7910
7911 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
7912 SourceLocation TemplateLoc)
7913 : Kind(ParsedTemplateKind::ExplicitInstantiation),
7914 TemplateParams(nullptr), ExternLoc(ExternLoc),
7915 TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false) {}
7916
7917 ParsedTemplateKind Kind;
7918
7919 /// The template parameter lists, for template declarations
7920 /// and explicit specializations.
7921 TemplateParameterLists *TemplateParams;
7922
7923 /// The location of the 'extern' keyword, if any, for an explicit
7924 /// instantiation
7925 SourceLocation ExternLoc;
7926
7927 /// The location of the 'template' keyword, for an explicit
7928 /// instantiation.
7929 SourceLocation TemplateLoc;
7930
7931 /// Whether the last template parameter list was empty.
7932 bool LastParameterListWasEmpty;
7933
7934 SourceRange getSourceRange() const LLVM_READONLY;
7935 };
7936
7937 /// Lex a delayed template function for late parsing.
7938 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
7939
7940 /// Late parse a C++ function template in Microsoft mode.
7941 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
7942
7943 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
7944
7945 /// We've parsed something that could plausibly be intended to be a template
7946 /// name (\p LHS) followed by a '<' token, and the following code can't
7947 /// possibly be an expression. Determine if this is likely to be a template-id
7948 /// and if so, diagnose it.
7949 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
7950
7951 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
7952 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
7953 const Token &OpToken);
7954 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
7955 if (auto *Info = AngleBrackets.getCurrent(P&: *this))
7956 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
7957 return false;
7958 }
7959
7960 //===--------------------------------------------------------------------===//
7961 // C++ 14: Templates [temp]
7962
7963 /// Parse a template declaration, explicit instantiation, or
7964 /// explicit specialization.
7965 DeclGroupPtrTy
7966 ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
7967 SourceLocation &DeclEnd,
7968 ParsedAttributes &AccessAttrs);
7969
7970 /// Parse a template declaration or an explicit specialization.
7971 ///
7972 /// Template declarations include one or more template parameter lists
7973 /// and either the function or class template declaration. Explicit
7974 /// specializations contain one or more 'template < >' prefixes
7975 /// followed by a (possibly templated) declaration. Since the
7976 /// syntactic form of both features is nearly identical, we parse all
7977 /// of the template headers together and let semantic analysis sort
7978 /// the declarations from the explicit specializations.
7979 ///
7980 /// \verbatim
7981 /// template-declaration: [C++ temp]
7982 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
7983 ///
7984 /// template-declaration: [C++2a]
7985 /// template-head declaration
7986 /// template-head concept-definition
7987 ///
7988 /// TODO: requires-clause
7989 /// template-head: [C++2a]
7990 /// 'template' '<' template-parameter-list '>'
7991 /// requires-clause[opt]
7992 ///
7993 /// explicit-specialization: [ C++ temp.expl.spec]
7994 /// 'template' '<' '>' declaration
7995 /// \endverbatim
7996 DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
7997 DeclaratorContext Context, SourceLocation &DeclEnd,
7998 ParsedAttributes &AccessAttrs, AccessSpecifier AS);
7999
8000 clang::Parser::DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
8001 DeclaratorContext Context, SourceLocation &DeclEnd, AccessSpecifier AS);
8002
8003 /// Parse a single declaration that declares a template,
8004 /// template specialization, or explicit instantiation of a template.
8005 ///
8006 /// \param DeclEnd will receive the source location of the last token
8007 /// within this declaration.
8008 ///
8009 /// \param AS the access specifier associated with this
8010 /// declaration. Will be AS_none for namespace-scope declarations.
8011 ///
8012 /// \returns the new declaration.
8013 DeclGroupPtrTy ParseDeclarationAfterTemplate(
8014 DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo,
8015 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
8016 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
8017
8018 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
8019 /// angle brackets. Depth is the depth of this template-parameter-list, which
8020 /// is the number of template headers directly enclosing this template header.
8021 /// TemplateParams is the current list of template parameters we're building.
8022 /// The template parameter we parse will be added to this list. LAngleLoc and
8023 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
8024 /// that enclose this template parameter list.
8025 ///
8026 /// \returns true if an error occurred, false otherwise.
8027 bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
8028 SmallVectorImpl<NamedDecl *> &TemplateParams,
8029 SourceLocation &LAngleLoc,
8030 SourceLocation &RAngleLoc);
8031
8032 /// ParseTemplateParameterList - Parse a template parameter list. If
8033 /// the parsing fails badly (i.e., closing bracket was left out), this
8034 /// will try to put the token stream in a reasonable position (closing
8035 /// a statement, etc.) and return false.
8036 ///
8037 /// \verbatim
8038 /// template-parameter-list: [C++ temp]
8039 /// template-parameter
8040 /// template-parameter-list ',' template-parameter
8041 /// \endverbatim
8042 bool ParseTemplateParameterList(unsigned Depth,
8043 SmallVectorImpl<NamedDecl *> &TemplateParams);
8044
8045 enum class TPResult;
8046
8047 /// Determine whether the parser is at the start of a template
8048 /// type parameter.
8049 TPResult isStartOfTemplateTypeParameter();
8050
8051 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
8052 ///
8053 /// \verbatim
8054 /// template-parameter: [C++ temp.param]
8055 /// type-parameter
8056 /// parameter-declaration
8057 ///
8058 /// type-parameter: (See below)
8059 /// type-parameter-key ...[opt] identifier[opt]
8060 /// type-parameter-key identifier[opt] = type-id
8061 /// (C++2a) type-constraint ...[opt] identifier[opt]
8062 /// (C++2a) type-constraint identifier[opt] = type-id
8063 /// 'template' '<' template-parameter-list '>' type-parameter-key
8064 /// ...[opt] identifier[opt]
8065 /// 'template' '<' template-parameter-list '>' type-parameter-key
8066 /// identifier[opt] '=' id-expression
8067 ///
8068 /// type-parameter-key:
8069 /// class
8070 /// typename
8071 /// \endverbatim
8072 ///
8073 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
8074
8075 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
8076 /// Other kinds of template parameters are parsed in
8077 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
8078 ///
8079 /// \verbatim
8080 /// type-parameter: [C++ temp.param]
8081 /// 'class' ...[opt][C++0x] identifier[opt]
8082 /// 'class' identifier[opt] '=' type-id
8083 /// 'typename' ...[opt][C++0x] identifier[opt]
8084 /// 'typename' identifier[opt] '=' type-id
8085 /// \endverbatim
8086 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
8087
8088 /// ParseTemplateTemplateParameter - Handle the parsing of template
8089 /// template parameters.
8090 ///
8091 /// \verbatim
8092 /// type-parameter: [C++ temp.param]
8093 /// template-head type-parameter-key ...[opt] identifier[opt]
8094 /// template-head type-parameter-key identifier[opt] = id-expression
8095 /// type-parameter-key:
8096 /// 'class'
8097 /// 'typename' [C++1z]
8098 /// template-head: [C++2a]
8099 /// 'template' '<' template-parameter-list '>'
8100 /// requires-clause[opt]
8101 /// \endverbatim
8102 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
8103
8104 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
8105 /// template parameters (e.g., in "template<int Size> class array;").
8106 ///
8107 /// \verbatim
8108 /// template-parameter:
8109 /// ...
8110 /// parameter-declaration
8111 /// \endverbatim
8112 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
8113
8114 /// Check whether the current token is a template-id annotation denoting a
8115 /// type-constraint.
8116 bool isTypeConstraintAnnotation();
8117
8118 /// Try parsing a type-constraint at the current location.
8119 ///
8120 /// \verbatim
8121 /// type-constraint:
8122 /// nested-name-specifier[opt] concept-name
8123 /// nested-name-specifier[opt] concept-name
8124 /// '<' template-argument-list[opt] '>'[opt]
8125 /// \endverbatim
8126 ///
8127 /// \returns true if an error occurred, and false otherwise.
8128 bool TryAnnotateTypeConstraint();
8129
8130 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
8131 SourceLocation CorrectLoc,
8132 bool AlreadyHasEllipsis,
8133 bool IdentifierHasName);
8134 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
8135 Declarator &D);
8136 // C++ 14.3: Template arguments [temp.arg]
8137 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
8138
8139 /// Parses a '>' at the end of a template list.
8140 ///
8141 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
8142 /// to determine if these tokens were supposed to be a '>' followed by
8143 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
8144 ///
8145 /// \param RAngleLoc the location of the consumed '>'.
8146 ///
8147 /// \param ConsumeLastToken if true, the '>' is consumed.
8148 ///
8149 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
8150 /// type parameter or type argument list, rather than a C++ template parameter
8151 /// or argument list.
8152 ///
8153 /// \returns true, if current token does not start with '>', false otherwise.
8154 bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
8155 SourceLocation &RAngleLoc,
8156 bool ConsumeLastToken,
8157 bool ObjCGenericList);
8158
8159 /// Parses a template-id that after the template name has
8160 /// already been parsed.
8161 ///
8162 /// This routine takes care of parsing the enclosed template argument
8163 /// list ('<' template-parameter-list [opt] '>') and placing the
8164 /// results into a form that can be transferred to semantic analysis.
8165 ///
8166 /// \param ConsumeLastToken if true, then we will consume the last
8167 /// token that forms the template-id. Otherwise, we will leave the
8168 /// last token in the stream (e.g., so that it can be replaced with an
8169 /// annotation token).
8170 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
8171 SourceLocation &LAngleLoc,
8172 TemplateArgList &TemplateArgs,
8173 SourceLocation &RAngleLoc,
8174 TemplateTy NameHint = nullptr);
8175
8176 /// Replace the tokens that form a simple-template-id with an
8177 /// annotation token containing the complete template-id.
8178 ///
8179 /// The first token in the stream must be the name of a template that
8180 /// is followed by a '<'. This routine will parse the complete
8181 /// simple-template-id and replace the tokens with a single annotation
8182 /// token with one of two different kinds: if the template-id names a
8183 /// type (and \p AllowTypeAnnotation is true), the annotation token is
8184 /// a type annotation that includes the optional nested-name-specifier
8185 /// (\p SS). Otherwise, the annotation token is a template-id
8186 /// annotation that does not include the optional
8187 /// nested-name-specifier.
8188 ///
8189 /// \param Template the declaration of the template named by the first
8190 /// token (an identifier), as returned from \c Action::isTemplateName().
8191 ///
8192 /// \param TNK the kind of template that \p Template
8193 /// refers to, as returned from \c Action::isTemplateName().
8194 ///
8195 /// \param SS if non-NULL, the nested-name-specifier that precedes
8196 /// this template name.
8197 ///
8198 /// \param TemplateKWLoc if valid, specifies that this template-id
8199 /// annotation was preceded by the 'template' keyword and gives the
8200 /// location of that keyword. If invalid (the default), then this
8201 /// template-id was not preceded by a 'template' keyword.
8202 ///
8203 /// \param AllowTypeAnnotation if true (the default), then a
8204 /// simple-template-id that refers to a class template, template
8205 /// template parameter, or other template that produces a type will be
8206 /// replaced with a type annotation token. Otherwise, the
8207 /// simple-template-id is always replaced with a template-id
8208 /// annotation token.
8209 ///
8210 /// \param TypeConstraint if true, then this is actually a type-constraint,
8211 /// meaning that the template argument list can be omitted (and the template
8212 /// in question must be a concept).
8213 ///
8214 /// If an unrecoverable parse error occurs and no annotation token can be
8215 /// formed, this function returns true.
8216 ///
8217 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
8218 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8219 UnqualifiedId &TemplateName,
8220 bool AllowTypeAnnotation = true,
8221 bool TypeConstraint = false);
8222
8223 /// Replaces a template-id annotation token with a type
8224 /// annotation token.
8225 ///
8226 /// If there was a failure when forming the type from the template-id,
8227 /// a type annotation token will still be created, but will have a
8228 /// NULL type pointer to signify an error.
8229 ///
8230 /// \param SS The scope specifier appearing before the template-id, if any.
8231 ///
8232 /// \param AllowImplicitTypename whether this is a context where T::type
8233 /// denotes a dependent type.
8234 /// \param IsClassName Is this template-id appearing in a context where we
8235 /// know it names a class, such as in an elaborated-type-specifier or
8236 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
8237 /// in those contexts.)
8238 void
8239 AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
8240 ImplicitTypenameContext AllowImplicitTypename,
8241 bool IsClassName = false);
8242
8243 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
8244 /// (C++ [temp.names]). Returns true if there was an error.
8245 ///
8246 /// \verbatim
8247 /// template-argument-list: [C++ 14.2]
8248 /// template-argument
8249 /// template-argument-list ',' template-argument
8250 /// \endverbatim
8251 ///
8252 /// \param Template is only used for code completion, and may be null.
8253 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
8254 TemplateTy Template, SourceLocation OpenLoc);
8255
8256 /// Parse a C++ template template argument.
8257 ParsedTemplateArgument ParseTemplateTemplateArgument();
8258
8259 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
8260 ///
8261 /// \verbatim
8262 /// template-argument: [C++ 14.2]
8263 /// constant-expression
8264 /// type-id
8265 /// id-expression
8266 /// braced-init-list [C++26, DR]
8267 /// \endverbatim
8268 ///
8269 ParsedTemplateArgument ParseTemplateArgument();
8270
8271 /// Parse a C++ explicit template instantiation
8272 /// (C++ [temp.explicit]).
8273 ///
8274 /// \verbatim
8275 /// explicit-instantiation:
8276 /// 'extern' [opt] 'template' declaration
8277 /// \endverbatim
8278 ///
8279 /// Note that the 'extern' is a GNU extension and C++11 feature.
8280 DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context,
8281 SourceLocation ExternLoc,
8282 SourceLocation TemplateLoc,
8283 SourceLocation &DeclEnd,
8284 ParsedAttributes &AccessAttrs,
8285 AccessSpecifier AS = AS_none);
8286
8287 /// \brief Parse a single declaration that declares a concept.
8288 ///
8289 /// \param DeclEnd will receive the source location of the last token
8290 /// within this declaration.
8291 ///
8292 /// \returns the new declaration.
8293 Decl *ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
8294 SourceLocation &DeclEnd);
8295
8296 ///@}
8297
8298 //
8299 //
8300 // -------------------------------------------------------------------------
8301 //
8302 //
8303
8304 /// \name Tentative Parsing
8305 /// Implementations are in ParseTentative.cpp
8306 ///@{
8307
8308private:
8309 /// TentativeParsingAction - An object that is used as a kind of "tentative
8310 /// parsing transaction". It gets instantiated to mark the token position and
8311 /// after the token consumption is done, Commit() or Revert() is called to
8312 /// either "commit the consumed tokens" or revert to the previously marked
8313 /// token position. Example:
8314 ///
8315 /// TentativeParsingAction TPA(*this);
8316 /// ConsumeToken();
8317 /// ....
8318 /// TPA.Revert();
8319 ///
8320 /// If the Unannotated parameter is true, any token annotations created
8321 /// during the tentative parse are reverted.
8322 class TentativeParsingAction {
8323 Parser &P;
8324 PreferredTypeBuilder PrevPreferredType;
8325 Token PrevTok;
8326 size_t PrevTentativelyDeclaredIdentifierCount;
8327 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
8328 bool isActive;
8329
8330 public:
8331 explicit TentativeParsingAction(Parser &p, bool Unannotated = false)
8332 : P(p), PrevPreferredType(P.PreferredType) {
8333 PrevTok = P.Tok;
8334 PrevTentativelyDeclaredIdentifierCount =
8335 P.TentativelyDeclaredIdentifiers.size();
8336 PrevParenCount = P.ParenCount;
8337 PrevBracketCount = P.BracketCount;
8338 PrevBraceCount = P.BraceCount;
8339 P.PP.EnableBacktrackAtThisPos(Unannotated);
8340 isActive = true;
8341 }
8342 void Commit() {
8343 assert(isActive && "Parsing action was finished!");
8344 P.TentativelyDeclaredIdentifiers.resize(
8345 N: PrevTentativelyDeclaredIdentifierCount);
8346 P.PP.CommitBacktrackedTokens();
8347 isActive = false;
8348 }
8349 void Revert() {
8350 assert(isActive && "Parsing action was finished!");
8351 P.PP.Backtrack();
8352 P.PreferredType = PrevPreferredType;
8353 P.Tok = PrevTok;
8354 P.TentativelyDeclaredIdentifiers.resize(
8355 N: PrevTentativelyDeclaredIdentifierCount);
8356 P.ParenCount = PrevParenCount;
8357 P.BracketCount = PrevBracketCount;
8358 P.BraceCount = PrevBraceCount;
8359 isActive = false;
8360 }
8361 ~TentativeParsingAction() {
8362 assert(!isActive && "Forgot to call Commit or Revert!");
8363 }
8364 };
8365
8366 /// A TentativeParsingAction that automatically reverts in its destructor.
8367 /// Useful for disambiguation parses that will always be reverted.
8368 class RevertingTentativeParsingAction
8369 : private Parser::TentativeParsingAction {
8370 public:
8371 using TentativeParsingAction::TentativeParsingAction;
8372
8373 ~RevertingTentativeParsingAction() { Revert(); }
8374 };
8375
8376 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
8377 /// between a declaration or an expression statement, when parsing function
8378 /// bodies. Returns true for declaration, false for expression.
8379 ///
8380 /// \verbatim
8381 /// declaration-statement:
8382 /// block-declaration
8383 ///
8384 /// block-declaration:
8385 /// simple-declaration
8386 /// asm-definition
8387 /// namespace-alias-definition
8388 /// using-declaration
8389 /// using-directive
8390 /// [C++0x] static_assert-declaration
8391 ///
8392 /// asm-definition:
8393 /// 'asm' '(' string-literal ')' ';'
8394 ///
8395 /// namespace-alias-definition:
8396 /// 'namespace' identifier = qualified-namespace-specifier ';'
8397 ///
8398 /// using-declaration:
8399 /// 'using' typename[opt] '::'[opt] nested-name-specifier
8400 /// unqualified-id ';'
8401 /// 'using' '::' unqualified-id ;
8402 ///
8403 /// using-directive:
8404 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
8405 /// namespace-name ';'
8406 /// \endverbatim
8407 ///
8408 bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false);
8409
8410 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
8411 /// between a simple-declaration or an expression-statement.
8412 /// If during the disambiguation process a parsing error is encountered,
8413 /// the function returns true to let the declaration parsing code handle it.
8414 /// Returns false if the statement is disambiguated as expression.
8415 ///
8416 /// \verbatim
8417 /// simple-declaration:
8418 /// decl-specifier-seq init-declarator-list[opt] ';'
8419 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8420 /// brace-or-equal-initializer ';' [C++17]
8421 /// \endverbatim
8422 ///
8423 /// (if AllowForRangeDecl specified)
8424 /// for ( for-range-declaration : for-range-initializer ) statement
8425 ///
8426 /// \verbatim
8427 /// for-range-declaration:
8428 /// decl-specifier-seq declarator
8429 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8430 /// \endverbatim
8431 ///
8432 /// In any of the above cases there can be a preceding
8433 /// attribute-specifier-seq, but the caller is expected to handle that.
8434 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
8435
8436 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
8437 /// a constructor-style initializer, when parsing declaration statements.
8438 /// Returns true for function declarator and false for constructor-style
8439 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
8440 /// might be a constructor-style initializer.
8441 /// If during the disambiguation process a parsing error is encountered,
8442 /// the function returns true to let the declaration parsing code handle it.
8443 ///
8444 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8445 /// exception-specification[opt]
8446 ///
8447 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr,
8448 ImplicitTypenameContext AllowImplicitTypename =
8449 ImplicitTypenameContext::No);
8450
8451 struct ConditionDeclarationOrInitStatementState;
8452 enum class ConditionOrInitStatement {
8453 Expression, ///< Disambiguated as an expression (either kind).
8454 ConditionDecl, ///< Disambiguated as the declaration form of condition.
8455 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
8456 ForRangeDecl, ///< Disambiguated as a for-range declaration.
8457 Error ///< Can't be any of the above!
8458 };
8459
8460 /// Disambiguates between a declaration in a condition, a
8461 /// simple-declaration in an init-statement, and an expression for
8462 /// a condition of a if/switch statement.
8463 ///
8464 /// \verbatim
8465 /// condition:
8466 /// expression
8467 /// type-specifier-seq declarator '=' assignment-expression
8468 /// [C++11] type-specifier-seq declarator '=' initializer-clause
8469 /// [C++11] type-specifier-seq declarator braced-init-list
8470 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
8471 /// '=' assignment-expression
8472 /// simple-declaration:
8473 /// decl-specifier-seq init-declarator-list[opt] ';'
8474 /// \endverbatim
8475 ///
8476 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
8477 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
8478 /// 'int(x);' (a simple-declaration in an init-statement).
8479 ConditionOrInitStatement
8480 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
8481 bool CanBeForRangeDecl);
8482
8483 /// Determine whether the next set of tokens contains a type-id.
8484 ///
8485 /// The context parameter states what context we're parsing right
8486 /// now, which affects how this routine copes with the token
8487 /// following the type-id. If the context is
8488 /// TentativeCXXTypeIdContext::InParens, we have already parsed the '(' and we
8489 /// will cease lookahead when we hit the corresponding ')'. If the context is
8490 /// TentativeCXXTypeIdContext::AsTemplateArgument, we've already parsed the
8491 /// '<' or ',' before this template argument, and will cease lookahead when we
8492 /// hit a
8493 /// '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
8494 /// preceding such. Returns true for a type-id and false for an expression.
8495 /// If during the disambiguation process a parsing error is encountered,
8496 /// the function returns true to let the declaration parsing code handle it.
8497 ///
8498 /// \verbatim
8499 /// type-id:
8500 /// type-specifier-seq abstract-declarator[opt]
8501 /// \endverbatim
8502 ///
8503 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
8504
8505 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
8506 bool isAmbiguous;
8507 return isCXXTypeId(Context, isAmbiguous);
8508 }
8509
8510 /// TPResult - Used as the result value for functions whose purpose is to
8511 /// disambiguate C++ constructs by "tentatively parsing" them.
8512 enum class TPResult { True, False, Ambiguous, Error };
8513
8514 /// Determine whether we could have an enum-base.
8515 ///
8516 /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
8517 /// only consider this to be an enum-base if the next token is a '{'.
8518 ///
8519 /// \return \c false if this cannot possibly be an enum base; \c true
8520 /// otherwise.
8521 bool isEnumBase(bool AllowSemi);
8522
8523 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
8524 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
8525 /// be either a decl-specifier or a function-style cast, and TPResult::Error
8526 /// if a parsing error was found and reported.
8527 ///
8528 /// Does not consume tokens.
8529 ///
8530 /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
8531 /// declaration specifiers but possibly valid as some other kind of construct
8532 /// return TPResult::Ambiguous instead of TPResult::False. When this happens,
8533 /// the intent is to keep trying to disambiguate, on the basis that we might
8534 /// find a better reason to treat this construct as a declaration later on.
8535 /// When this happens and the name could possibly be valid in some other
8536 /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
8537 /// that trigger this are:
8538 ///
8539 /// * When parsing X::Y (with no 'typename') where X is dependent
8540 /// * When parsing X<Y> where X is undeclared
8541 ///
8542 /// \verbatim
8543 /// decl-specifier:
8544 /// storage-class-specifier
8545 /// type-specifier
8546 /// function-specifier
8547 /// 'friend'
8548 /// 'typedef'
8549 /// [C++11] 'constexpr'
8550 /// [C++20] 'consteval'
8551 /// [GNU] attributes declaration-specifiers[opt]
8552 ///
8553 /// storage-class-specifier:
8554 /// 'register'
8555 /// 'static'
8556 /// 'extern'
8557 /// 'mutable'
8558 /// 'auto'
8559 /// [GNU] '__thread'
8560 /// [C++11] 'thread_local'
8561 /// [C11] '_Thread_local'
8562 ///
8563 /// function-specifier:
8564 /// 'inline'
8565 /// 'virtual'
8566 /// 'explicit'
8567 ///
8568 /// typedef-name:
8569 /// identifier
8570 ///
8571 /// type-specifier:
8572 /// simple-type-specifier
8573 /// class-specifier
8574 /// enum-specifier
8575 /// elaborated-type-specifier
8576 /// typename-specifier
8577 /// cv-qualifier
8578 ///
8579 /// simple-type-specifier:
8580 /// '::'[opt] nested-name-specifier[opt] type-name
8581 /// '::'[opt] nested-name-specifier 'template'
8582 /// simple-template-id [TODO]
8583 /// 'char'
8584 /// 'wchar_t'
8585 /// 'bool'
8586 /// 'short'
8587 /// 'int'
8588 /// 'long'
8589 /// 'signed'
8590 /// 'unsigned'
8591 /// 'float'
8592 /// 'double'
8593 /// 'void'
8594 /// [GNU] typeof-specifier
8595 /// [GNU] '_Complex'
8596 /// [C++11] 'auto'
8597 /// [GNU] '__auto_type'
8598 /// [C++11] 'decltype' ( expression )
8599 /// [C++1y] 'decltype' ( 'auto' )
8600 ///
8601 /// type-name:
8602 /// class-name
8603 /// enum-name
8604 /// typedef-name
8605 ///
8606 /// elaborated-type-specifier:
8607 /// class-key '::'[opt] nested-name-specifier[opt] identifier
8608 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
8609 /// simple-template-id
8610 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
8611 ///
8612 /// enum-name:
8613 /// identifier
8614 ///
8615 /// enum-specifier:
8616 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
8617 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
8618 ///
8619 /// class-specifier:
8620 /// class-head '{' member-specification[opt] '}'
8621 ///
8622 /// class-head:
8623 /// class-key identifier[opt] base-clause[opt]
8624 /// class-key nested-name-specifier identifier base-clause[opt]
8625 /// class-key nested-name-specifier[opt] simple-template-id
8626 /// base-clause[opt]
8627 ///
8628 /// class-key:
8629 /// 'class'
8630 /// 'struct'
8631 /// 'union'
8632 ///
8633 /// cv-qualifier:
8634 /// 'const'
8635 /// 'volatile'
8636 /// [GNU] restrict
8637 /// \endverbatim
8638 ///
8639 TPResult
8640 isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
8641 TPResult BracedCastResult = TPResult::False,
8642 bool *InvalidAsDeclSpec = nullptr);
8643
8644 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
8645 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
8646 /// a type-specifier other than a cv-qualifier.
8647 bool isCXXDeclarationSpecifierAType();
8648
8649 /// Determine whether we might be looking at the '<' template-argument-list
8650 /// '>' of a template-id or simple-template-id, rather than a less-than
8651 /// comparison. This will often fail and produce an ambiguity, but should
8652 /// never be wrong if it returns True or False.
8653 TPResult isTemplateArgumentList(unsigned TokensToSkip);
8654
8655 /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
8656 /// 'explicit(bool)' declaration, in earlier language modes where that is an
8657 /// extension.
8658 TPResult isExplicitBool();
8659
8660 /// Determine whether an identifier has been tentatively declared as a
8661 /// non-type. Such tentative declarations should not be found to name a type
8662 /// during a tentative parse, but also should not be annotated as a non-type.
8663 bool isTentativelyDeclared(IdentifierInfo *II);
8664
8665 // "Tentative parsing" functions, used for disambiguation. If a parsing error
8666 // is encountered they will return TPResult::Error.
8667 // Returning TPResult::True/False indicates that the ambiguity was
8668 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
8669 // that more tentative parsing is necessary for disambiguation.
8670 // They all consume tokens, so backtracking should be used after calling them.
8671
8672 /// \verbatim
8673 /// simple-declaration:
8674 /// decl-specifier-seq init-declarator-list[opt] ';'
8675 ///
8676 /// (if AllowForRangeDecl specified)
8677 /// for ( for-range-declaration : for-range-initializer ) statement
8678 /// for-range-declaration:
8679 /// attribute-specifier-seqopt type-specifier-seq declarator
8680 /// \endverbatim
8681 ///
8682 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
8683
8684 /// \verbatim
8685 /// [GNU] typeof-specifier:
8686 /// 'typeof' '(' expressions ')'
8687 /// 'typeof' '(' type-name ')'
8688 /// \endverbatim
8689 ///
8690 TPResult TryParseTypeofSpecifier();
8691
8692 /// [ObjC] protocol-qualifiers:
8693 /// '<' identifier-list '>'
8694 TPResult TryParseProtocolQualifiers();
8695
8696 TPResult TryParsePtrOperatorSeq();
8697
8698 /// \verbatim
8699 /// operator-function-id:
8700 /// 'operator' operator
8701 ///
8702 /// operator: one of
8703 /// new delete new[] delete[] + - * / % ^ [...]
8704 ///
8705 /// conversion-function-id:
8706 /// 'operator' conversion-type-id
8707 ///
8708 /// conversion-type-id:
8709 /// type-specifier-seq conversion-declarator[opt]
8710 ///
8711 /// conversion-declarator:
8712 /// ptr-operator conversion-declarator[opt]
8713 ///
8714 /// literal-operator-id:
8715 /// 'operator' string-literal identifier
8716 /// 'operator' user-defined-string-literal
8717 /// \endverbatim
8718 TPResult TryParseOperatorId();
8719
8720 /// Tentatively parse an init-declarator-list in order to disambiguate it from
8721 /// an expression.
8722 ///
8723 /// \verbatim
8724 /// init-declarator-list:
8725 /// init-declarator
8726 /// init-declarator-list ',' init-declarator
8727 ///
8728 /// init-declarator:
8729 /// declarator initializer[opt]
8730 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
8731 ///
8732 /// initializer:
8733 /// brace-or-equal-initializer
8734 /// '(' expression-list ')'
8735 ///
8736 /// brace-or-equal-initializer:
8737 /// '=' initializer-clause
8738 /// [C++11] braced-init-list
8739 ///
8740 /// initializer-clause:
8741 /// assignment-expression
8742 /// braced-init-list
8743 ///
8744 /// braced-init-list:
8745 /// '{' initializer-list ','[opt] '}'
8746 /// '{' '}'
8747 /// \endverbatim
8748 ///
8749 TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false);
8750
8751 /// \verbatim
8752 /// declarator:
8753 /// direct-declarator
8754 /// ptr-operator declarator
8755 ///
8756 /// direct-declarator:
8757 /// declarator-id
8758 /// direct-declarator '(' parameter-declaration-clause ')'
8759 /// cv-qualifier-seq[opt] exception-specification[opt]
8760 /// direct-declarator '[' constant-expression[opt] ']'
8761 /// '(' declarator ')'
8762 /// [GNU] '(' attributes declarator ')'
8763 ///
8764 /// abstract-declarator:
8765 /// ptr-operator abstract-declarator[opt]
8766 /// direct-abstract-declarator
8767 ///
8768 /// direct-abstract-declarator:
8769 /// direct-abstract-declarator[opt]
8770 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8771 /// exception-specification[opt]
8772 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
8773 /// '(' abstract-declarator ')'
8774 /// [C++0x] ...
8775 ///
8776 /// ptr-operator:
8777 /// '*' cv-qualifier-seq[opt]
8778 /// '&'
8779 /// [C++0x] '&&' [TODO]
8780 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
8781 ///
8782 /// cv-qualifier-seq:
8783 /// cv-qualifier cv-qualifier-seq[opt]
8784 ///
8785 /// cv-qualifier:
8786 /// 'const'
8787 /// 'volatile'
8788 ///
8789 /// declarator-id:
8790 /// '...'[opt] id-expression
8791 ///
8792 /// id-expression:
8793 /// unqualified-id
8794 /// qualified-id [TODO]
8795 ///
8796 /// unqualified-id:
8797 /// identifier
8798 /// operator-function-id
8799 /// conversion-function-id
8800 /// literal-operator-id
8801 /// '~' class-name [TODO]
8802 /// '~' decltype-specifier [TODO]
8803 /// template-id [TODO]
8804 /// \endverbatim
8805 ///
8806 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
8807 bool mayHaveDirectInit = false,
8808 bool mayHaveTrailingReturnType = false);
8809
8810 /// \verbatim
8811 /// parameter-declaration-clause:
8812 /// parameter-declaration-list[opt] '...'[opt]
8813 /// parameter-declaration-list ',' '...'
8814 ///
8815 /// parameter-declaration-list:
8816 /// parameter-declaration
8817 /// parameter-declaration-list ',' parameter-declaration
8818 ///
8819 /// parameter-declaration:
8820 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
8821 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
8822 /// '=' assignment-expression
8823 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
8824 /// attributes[opt]
8825 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
8826 /// attributes[opt] '=' assignment-expression
8827 /// \endverbatim
8828 ///
8829 TPResult TryParseParameterDeclarationClause(
8830 bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false,
8831 ImplicitTypenameContext AllowImplicitTypename =
8832 ImplicitTypenameContext::No);
8833
8834 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to
8835 /// continue parsing as a function declarator. If TryParseFunctionDeclarator
8836 /// fully parsed the function declarator, it will return TPResult::Ambiguous,
8837 /// otherwise it will return either False() or Error().
8838 ///
8839 /// \verbatim
8840 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8841 /// exception-specification[opt]
8842 ///
8843 /// exception-specification:
8844 /// 'throw' '(' type-id-list[opt] ')'
8845 /// \endverbatim
8846 ///
8847 TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false);
8848
8849 // When parsing an identifier after an arrow it may be a member expression,
8850 // in which case we should not annotate it as an independant expression
8851 // so we just lookup that name, if it's not a type the construct is not
8852 // a function declaration.
8853 bool NameAfterArrowIsNonType();
8854
8855 /// \verbatim
8856 /// '[' constant-expression[opt] ']'
8857 /// \endverbatim
8858 ///
8859 TPResult TryParseBracketDeclarator();
8860
8861 /// Try to consume a token sequence that we've already identified as
8862 /// (potentially) starting a decl-specifier.
8863 TPResult TryConsumeDeclarationSpecifier();
8864
8865 /// Try to skip a possibly empty sequence of 'attribute-specifier's without
8866 /// full validation of the syntactic structure of attributes.
8867 bool TrySkipAttributes();
8868
8869 //===--------------------------------------------------------------------===//
8870 // C++ 7: Declarations [dcl.dcl]
8871
8872 /// Returns true if this is a C++11 attribute-specifier. Per
8873 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
8874 /// always introduce an attribute. In Objective-C++11, this rule does not
8875 /// apply if either '[' begins a message-send.
8876 ///
8877 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
8878 /// an attribute-specifier, and return
8879 /// CXX11AttributeKind::InvalidAttributeSpecifier if not.
8880 ///
8881 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
8882 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
8883 /// is not an Obj-C message send.
8884 ///
8885 /// C++11 [dcl.attr.grammar]:
8886 ///
8887 /// \verbatim
8888 /// attribute-specifier:
8889 /// '[' '[' attribute-list ']' ']'
8890 /// alignment-specifier
8891 ///
8892 /// attribute-list:
8893 /// attribute[opt]
8894 /// attribute-list ',' attribute[opt]
8895 /// attribute '...'
8896 /// attribute-list ',' attribute '...'
8897 ///
8898 /// attribute:
8899 /// attribute-token attribute-argument-clause[opt]
8900 ///
8901 /// attribute-token:
8902 /// identifier
8903 /// identifier '::' identifier
8904 ///
8905 /// attribute-argument-clause:
8906 /// '(' balanced-token-seq ')'
8907 /// \endverbatim
8908 CXX11AttributeKind
8909 isCXX11AttributeSpecifier(bool Disambiguate = false,
8910 bool OuterMightBeMessageSend = false);
8911
8912 ///@}
8913};
8914
8915} // end namespace clang
8916
8917#endif
8918

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