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