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