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