clang 23.0.0git
Parser.h
Go to the documentation of this file.
1//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Parser interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_PARSE_PARSER_H
14#define LLVM_CLANG_PARSE_PARSER_H
15
20#include "clang/Sema/Sema.h"
22#include "clang/Sema/SemaObjC.h"
24#include "llvm/ADT/STLForwardCompat.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/Frontend/OpenMP/OMPContext.h"
27#include "llvm/Support/SaveAndRestore.h"
28#include <optional>
29#include <stack>
30
31namespace clang {
32class PragmaHandler;
33class Scope;
36class DeclGroupRef;
38struct LoopHint;
39class Parser;
41class ParsingDeclSpec;
47class OMPClause;
48class OpenACCClause;
50struct OMPTraitProperty;
51struct OMPTraitSelector;
52struct OMPTraitSet;
53class OMPTraitInfo;
54
56 /// Annotation has failed and emitted an error.
58 /// The identifier is a tentatively-declared name.
60 /// The identifier is a template name. FIXME: Add an annotation for that.
62 /// The identifier can't be resolved.
64 /// Annotation was successful.
66};
67
68/// The kind of extra semi diagnostic to emit.
75
76/// The kind of template we are parsing.
78 /// We are not parsing a template at all.
80 /// We are parsing a template declaration.
82 /// We are parsing an explicit specialization.
84 /// We are parsing an explicit instantiation.
86};
87
89
90// Definitions for Objective-c context sensitive keywords recognition.
103
104/// If a typo should be encountered, should typo correction suggest type names,
105/// non type names, or both?
111
112/// Control what ParseCastExpression will parse.
114
115/// ParenParseOption - Control what ParseParenExpression will parse.
117 SimpleExpr, // Only parse '(' expression ')'
118 FoldExpr, // Also allow fold-expression <anything>
119 CompoundStmt, // Also allow '(' compound-statement ')'
120 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
121 CastExpr // Also allow '(' type-name ')' <anything>
122};
123
124/// In a call to ParseParenExpression, are the initial parentheses part of an
125/// operator that requires the parens be there (like typeof(int)) or could they
126/// be something else, such as part of a compound literal or a sizeof
127/// expression, etc.
128enum class ParenExprKind {
129 PartOfOperator, // typeof(int)
130 Unknown, // sizeof(int) or sizeof (int)1.0f, or compound literal, etc
131};
132
133/// Describes the behavior that should be taken for an __if_exists
134/// block.
136 /// Parse the block; this code is always used.
138 /// Skip the block entirely; this code is never used.
140 /// Parse the block as a dependent block, which may be used in
141 /// some template instantiations but not others.
143};
144
145/// Specifies the context in which type-id/expression
146/// disambiguation will occur.
154
155/// The kind of attribute specifier we have found.
157 /// This is not an attribute specifier.
159 /// This should be treated as an attribute-specifier.
161 /// The next tokens are '[[', but this is not an attribute-specifier. This
162 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
164};
165
166/// Parser - This implements a parser for the C family of languages. After
167/// parsing units of the grammar, productions are invoked to handle whatever has
168/// been read.
169///
170/// \nosubgrouping
172 // Table of Contents
173 // -----------------
174 // 1. Parsing (Parser.cpp)
175 // 2. C++ Class Inline Methods (ParseCXXInlineMethods.cpp)
176 // 3. Declarations (ParseDecl.cpp)
177 // 4. C++ Declarations (ParseDeclCXX.cpp)
178 // 5. Expressions (ParseExpr.cpp)
179 // 6. C++ Expressions (ParseExprCXX.cpp)
180 // 7. HLSL Constructs (ParseHLSL.cpp)
181 // 8. Initializers (ParseInit.cpp)
182 // 9. Objective-C Constructs (ParseObjc.cpp)
183 // 10. OpenACC Constructs (ParseOpenACC.cpp)
184 // 11. OpenMP Constructs (ParseOpenMP.cpp)
185 // 12. Pragmas (ParsePragma.cpp)
186 // 13. Statements (ParseStmt.cpp)
187 // 14. `inline asm` Statement (ParseStmtAsm.cpp)
188 // 15. C++ Templates (ParseTemplate.cpp)
189 // 16. Tentative Parsing (ParseTentative.cpp)
190
191 /// \name Parsing
192 /// Implementations are in Parser.cpp
193 ///@{
194
195public:
200
201 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
202 ~Parser() override;
203
204 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
205 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
206 Preprocessor &getPreprocessor() const { return PP; }
207 Sema &getActions() const { return Actions; }
208 AttributeFactory &getAttrFactory() { return AttrFactory; }
209
210 const Token &getCurToken() const { return Tok; }
211 Scope *getCurScope() const { return Actions.getCurScope(); }
212
214 return Actions.incrementMSManglingNumber();
215 }
216
217 // Type forwarding. All of these are statically 'void*', but they may all be
218 // different actual classes based on the actions in place.
221
222 /// Initialize - Warm up the parser.
223 ///
224 void Initialize();
225
226 /// Parse the first top-level declaration in a translation unit.
227 ///
228 /// \verbatim
229 /// translation-unit:
230 /// [C] external-declaration
231 /// [C] translation-unit external-declaration
232 /// [C++] top-level-declaration-seq[opt]
233 /// [C++20] global-module-fragment[opt] module-declaration
234 /// top-level-declaration-seq[opt] private-module-fragment[opt]
235 /// \endverbatim
236 ///
237 /// Note that in C, it is an error if there is no first declaration.
239 Sema::ModuleImportState &ImportState);
240
241 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
242 /// action tells us to. This returns true if the EOF was encountered.
243 ///
244 /// \verbatim
245 /// top-level-declaration:
246 /// declaration
247 /// [C++20] module-import-declaration
248 /// \endverbatim
250 Sema::ModuleImportState &ImportState);
256
257 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
258 /// This does not work with special tokens: string literals, code completion,
259 /// annotation tokens and balanced tokens must be handled using the specific
260 /// consume methods.
261 /// Returns the location of the consumed token.
263 assert(!isTokenSpecial() &&
264 "Should consume special tokens with Consume*Token");
265 PrevTokLocation = Tok.getLocation();
266 PP.Lex(Tok);
267 return PrevTokLocation;
268 }
269
271 if (Tok.isNot(Expected))
272 return false;
273 assert(!isTokenSpecial() &&
274 "Should consume special tokens with Consume*Token");
275 PrevTokLocation = Tok.getLocation();
276 PP.Lex(Tok);
277 return true;
278 }
279
282 return false;
283 Loc = PrevTokLocation;
284 return true;
285 }
286
287 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
288 /// current token type. This should only be used in cases where the type of
289 /// the token really isn't known, e.g. in error recovery.
290 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
291 if (isTokenParen())
292 return ConsumeParen();
293 if (isTokenBracket())
294 return ConsumeBracket();
295 if (isTokenBrace())
296 return ConsumeBrace();
297 if (isTokenStringLiteral())
298 return ConsumeStringToken();
299 if (Tok.is(tok::code_completion))
300 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
301 : handleUnexpectedCodeCompletionToken();
302 if (Tok.isAnnotation())
303 return ConsumeAnnotationToken();
304 return ConsumeToken();
305 }
306
308
309 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
310 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
311 /// returns the token after Tok, etc.
312 ///
313 /// Note that this differs from the Preprocessor's LookAhead method, because
314 /// the Parser always has one token lexed that the preprocessor doesn't.
315 ///
316 const Token &GetLookAheadToken(unsigned N) {
317 if (N == 0 || Tok.is(tok::eof))
318 return Tok;
319 return PP.LookAhead(N - 1);
320 }
321
322 /// NextToken - This peeks ahead one token and returns it without
323 /// consuming it.
324 const Token &NextToken() { return PP.LookAhead(0); }
325
326 /// getTypeAnnotation - Read a parsed type out of an annotation token.
327 static TypeResult getTypeAnnotation(const Token &Tok) {
328 if (!Tok.getAnnotationValue())
329 return TypeError();
330 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
331 }
332
333 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
334 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
335 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
336 /// with a single annotation token representing the typename or C++ scope
337 /// respectively.
338 /// This simplifies handling of C++ scope specifiers and allows efficient
339 /// backtracking without the need to re-parse and resolve nested-names and
340 /// typenames.
341 /// It will mainly be called when we expect to treat identifiers as typenames
342 /// (if they are typenames). For example, in C we do not expect identifiers
343 /// inside expressions to be treated as typenames so it will not be called
344 /// for expressions in C.
345 /// The benefit for C/ObjC is that a typename will be annotated and
346 /// Actions.getTypeName will not be needed to be called again (e.g.
347 /// getTypeName will not be called twice, once to check whether we have a
348 /// declaration specifier, and another one to get the actual type inside
349 /// ParseDeclarationSpecifiers).
350 ///
351 /// This returns true if an error occurred.
352 ///
353 /// Note that this routine emits an error if you call it with ::new or
354 /// ::delete as the current tokens, so only call it in contexts where these
355 /// are invalid.
356 bool
359
360 /// Try to annotate a type or scope token, having already parsed an
361 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
362 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
364 CXXScopeSpec &SS, bool IsNewScope,
365 ImplicitTypenameContext AllowImplicitTypename);
366
367 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
368 /// annotates C++ scope specifiers and template-ids. This returns
369 /// true if there was an error that could not be recovered from.
370 ///
371 /// Note that this routine emits an error if you call it with ::new or
372 /// ::delete as the current tokens, so only call it in contexts where these
373 /// are invalid.
374 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
375
377 return getLangOpts().CPlusPlus &&
378 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
379 (Tok.is(tok::annot_template_id) &&
380 NextToken().is(tok::coloncolon)) ||
381 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super));
382 }
383 bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
384 return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
385 }
386
387 //===--------------------------------------------------------------------===//
388 // Scope manipulation
389
390 /// ParseScope - Introduces a new scope for parsing. The kind of
391 /// scope is determined by ScopeFlags. Objects of this type should
392 /// be created on the stack to coincide with the position where the
393 /// parser enters the new scope, and this object's constructor will
394 /// create that new scope. Similarly, once the object is destroyed
395 /// the parser will exit the scope.
396 class ParseScope {
397 Parser *Self;
398 ParseScope(const ParseScope &) = delete;
399 void operator=(const ParseScope &) = delete;
400
401 public:
402 // ParseScope - Construct a new object to manage a scope in the
403 // parser Self where the new Scope is created with the flags
404 // ScopeFlags, but only when we aren't about to enter a compound statement.
405 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
406 bool BeforeCompoundStmt = false)
407 : Self(Self) {
408 if (EnteredScope && !BeforeCompoundStmt)
409 Self->EnterScope(ScopeFlags);
410 else {
411 if (BeforeCompoundStmt)
412 Self->incrementMSManglingNumber();
413
414 this->Self = nullptr;
415 }
416 }
417
418 // Exit - Exit the scope associated with this object now, rather
419 // than waiting until the object is destroyed.
420 void Exit() {
421 if (Self) {
422 Self->ExitScope();
423 Self = nullptr;
424 }
425 }
426
428 };
429
430 /// Introduces zero or more scopes for parsing. The scopes will all be exited
431 /// when the object is destroyed.
432 class MultiParseScope {
433 Parser &Self;
434 unsigned NumScopes = 0;
435
436 MultiParseScope(const MultiParseScope &) = delete;
437
438 public:
439 MultiParseScope(Parser &Self) : Self(Self) {}
440 void Enter(unsigned ScopeFlags) {
441 Self.EnterScope(ScopeFlags);
442 ++NumScopes;
443 }
444 void Exit() {
445 while (NumScopes) {
446 Self.ExitScope();
447 --NumScopes;
448 }
449 }
451 };
452
453 /// EnterScope - Start a new scope.
454 void EnterScope(unsigned ScopeFlags);
455
456 /// ExitScope - Pop a scope off the scope stack.
457 void ExitScope();
458
459 //===--------------------------------------------------------------------===//
460 // Diagnostic Emission and Error recovery.
461
462 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
463 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
464 DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); }
465
466 DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId);
467 DiagnosticBuilder DiagCompat(const Token &Tok, unsigned CompatDiagId);
468 DiagnosticBuilder DiagCompat(unsigned CompatDiagId) {
469 return DiagCompat(Tok, CompatDiagId);
470 }
471
472 /// Control flags for SkipUntil functions.
474 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
475 /// Stop skipping at specified token, but don't skip the token itself
477 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
478 };
479
481 SkipUntilFlags R) {
482 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
483 static_cast<unsigned>(R));
484 }
485
486 /// SkipUntil - Read tokens until we get to the specified token, then consume
487 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
488 /// that the token will ever occur, this skips to the next token, or to some
489 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
490 /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
491 /// skipping.
492 ///
493 /// If SkipUntil finds the specified token, it returns true, otherwise it
494 /// returns false.
496 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
497 return SkipUntil(llvm::ArrayRef(T), Flags);
498 }
500 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
501 tok::TokenKind TokArray[] = {T1, T2};
502 return SkipUntil(TokArray, Flags);
503 }
505 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
506 tok::TokenKind TokArray[] = {T1, T2, T3};
507 return SkipUntil(TokArray, Flags);
508 }
509
510 /// SkipUntil - Read tokens until we get to the specified token, then consume
511 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
512 /// token will ever occur, this skips to the next token, or to some likely
513 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
514 /// character.
515 ///
516 /// If SkipUntil finds the specified token, it returns true, otherwise it
517 /// returns false.
519 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
520
521private:
522 Preprocessor &PP;
523
524 /// Tok - The current token we are peeking ahead. All parsing methods assume
525 /// that this is valid.
526 Token Tok;
527
528 // PrevTokLocation - The location of the token we previously
529 // consumed. This token is used for diagnostics where we expected to
530 // see a token following another token (e.g., the ';' at the end of
531 // a statement).
532 SourceLocation PrevTokLocation;
533
534 /// Tracks an expected type for the current token when parsing an expression.
535 /// Used by code completion for ranking.
536 PreferredTypeBuilder PreferredType;
537
538 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
539 unsigned short MisplacedModuleBeginCount = 0;
540
541 /// Actions - These are the callbacks we invoke as we parse various constructs
542 /// in the file.
543 Sema &Actions;
544
545 DiagnosticsEngine &Diags;
546
547 StackExhaustionHandler StackHandler;
548
549 /// ScopeCache - Cache scopes to reduce malloc traffic.
550 static constexpr int ScopeCacheSize = 16;
551 unsigned NumCachedScopes;
552 Scope *ScopeCache[ScopeCacheSize];
553
554 /// Identifiers used for SEH handling in Borland. These are only
555 /// allowed in particular circumstances
556 // __except block
557 IdentifierInfo *Ident__exception_code, *Ident___exception_code,
558 *Ident_GetExceptionCode;
559 // __except filter expression
560 IdentifierInfo *Ident__exception_info, *Ident___exception_info,
561 *Ident_GetExceptionInfo;
562 // __finally
563 IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination,
564 *Ident_AbnormalTermination;
565
566 /// Contextual keywords for Microsoft extensions.
567 IdentifierInfo *Ident__except;
568
569 std::unique_ptr<CommentHandler> CommentSemaHandler;
570
571 /// Gets set to true after calling ProduceSignatureHelp, it is for a
572 /// workaround to make sure ProduceSignatureHelp is only called at the deepest
573 /// function call.
574 bool CalledSignatureHelp = false;
575
576 IdentifierInfo *getSEHExceptKeyword();
577
578 /// Whether to skip parsing of function bodies.
579 ///
580 /// This option can be used, for example, to speed up searches for
581 /// declarations/definitions when indexing.
582 bool SkipFunctionBodies;
583
584 //===--------------------------------------------------------------------===//
585 // Low-Level token peeking and consumption methods.
586 //
587
588 /// isTokenParen - Return true if the cur token is '(' or ')'.
589 bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); }
590 /// isTokenBracket - Return true if the cur token is '[' or ']'.
591 bool isTokenBracket() const {
592 return Tok.isOneOf(tok::l_square, tok::r_square);
593 }
594 /// isTokenBrace - Return true if the cur token is '{' or '}'.
595 bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); }
596 /// isTokenStringLiteral - True if this token is a string-literal.
597 bool isTokenStringLiteral() const {
598 return tok::isStringLiteral(Tok.getKind());
599 }
600 /// isTokenSpecial - True if this token requires special consumption methods.
601 bool isTokenSpecial() const {
602 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
603 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
604 }
605
606 /// Returns true if the current token is '=' or is a type of '='.
607 /// For typos, give a fixit to '='
608 bool isTokenEqualOrEqualTypo();
609
610 /// Return the current token to the token stream and make the given
611 /// token the current token.
612 void UnconsumeToken(Token &Consumed) {
613 Token Next = Tok;
614 PP.EnterToken(Consumed, /*IsReinject*/ true);
615 PP.Lex(Tok);
616 PP.EnterToken(Next, /*IsReinject*/ true);
617 }
618
619 SourceLocation ConsumeAnnotationToken() {
620 assert(Tok.isAnnotation() && "wrong consume method");
621 SourceLocation Loc = Tok.getLocation();
622 PrevTokLocation = Tok.getAnnotationEndLoc();
623 PP.Lex(Tok);
624 return Loc;
625 }
626
627 /// ConsumeParen - This consume method keeps the paren count up-to-date.
628 ///
629 SourceLocation ConsumeParen() {
630 assert(isTokenParen() && "wrong consume method");
631 if (Tok.getKind() == tok::l_paren)
632 ++ParenCount;
633 else if (ParenCount) {
634 AngleBrackets.clear(*this);
635 --ParenCount; // Don't let unbalanced )'s drive the count negative.
636 }
637 PrevTokLocation = Tok.getLocation();
638 PP.Lex(Tok);
639 return PrevTokLocation;
640 }
641
642 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
643 ///
644 SourceLocation ConsumeBracket() {
645 assert(isTokenBracket() && "wrong consume method");
646 if (Tok.getKind() == tok::l_square)
647 ++BracketCount;
648 else if (BracketCount) {
649 AngleBrackets.clear(*this);
650 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
651 }
652
653 PrevTokLocation = Tok.getLocation();
654 PP.Lex(Tok);
655 return PrevTokLocation;
656 }
657
658 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
659 ///
660 SourceLocation ConsumeBrace() {
661 assert(isTokenBrace() && "wrong consume method");
662 if (Tok.getKind() == tok::l_brace)
663 ++BraceCount;
664 else if (BraceCount) {
665 AngleBrackets.clear(*this);
666 --BraceCount; // Don't let unbalanced }'s drive the count negative.
667 }
668
669 PrevTokLocation = Tok.getLocation();
670 PP.Lex(Tok);
671 return PrevTokLocation;
672 }
673
674 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
675 /// and returning the token kind. This method is specific to strings, as it
676 /// handles string literal concatenation, as per C99 5.1.1.2, translation
677 /// phase #6.
678 SourceLocation ConsumeStringToken() {
679 assert(isTokenStringLiteral() &&
680 "Should only consume string literals with this method");
681 PrevTokLocation = Tok.getLocation();
682 PP.Lex(Tok);
683 return PrevTokLocation;
684 }
685
686 /// Consume the current code-completion token.
687 ///
688 /// This routine can be called to consume the code-completion token and
689 /// continue processing in special cases where \c cutOffParsing() isn't
690 /// desired, such as token caching or completion with lookahead.
691 SourceLocation ConsumeCodeCompletionToken() {
692 assert(Tok.is(tok::code_completion));
693 PrevTokLocation = Tok.getLocation();
694 PP.Lex(Tok);
695 return PrevTokLocation;
696 }
697
698 /// When we are consuming a code-completion token without having matched
699 /// specific position in the grammar, provide code-completion results based
700 /// on context.
701 ///
702 /// \returns the source location of the code-completion token.
703 SourceLocation handleUnexpectedCodeCompletionToken();
704
705 /// Abruptly cut off parsing; mainly used when we have reached the
706 /// code-completion point.
707 void cutOffParsing() {
708 if (PP.isCodeCompletionEnabled())
709 PP.setCodeCompletionReached();
710 // Cut off parsing by acting as if we reached the end-of-file.
711 Tok.setKind(tok::eof);
712 }
713
714 /// Determine if we're at the end of the file or at a transition
715 /// between modules.
716 bool isEofOrEom() {
717 tok::TokenKind Kind = Tok.getKind();
718 return Kind == tok::eof || Kind == tok::annot_module_begin ||
719 Kind == tok::annot_module_end || Kind == tok::annot_module_include ||
720 Kind == tok::annot_repl_input_end;
721 }
722
723 static void setTypeAnnotation(Token &Tok, TypeResult T) {
724 assert((T.isInvalid() || T.get()) &&
725 "produced a valid-but-null type annotation?");
726 Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr());
727 }
728
729 static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
730 return static_cast<NamedDecl *>(Tok.getAnnotationValue());
731 }
732
733 static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
734 Tok.setAnnotationValue(ND);
735 }
736
737 static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
738 return static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
739 }
740
741 static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
742 Tok.setAnnotationValue(ND);
743 }
744
745 /// Read an already-translated primary expression out of an annotation
746 /// token.
747 static ExprResult getExprAnnotation(const Token &Tok) {
748 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
749 }
750
751 /// Set the primary expression corresponding to the given annotation
752 /// token.
753 static void setExprAnnotation(Token &Tok, ExprResult ER) {
754 Tok.setAnnotationValue(ER.getAsOpaquePointer());
755 }
756
757 /// Attempt to classify the name at the current token position. This may
758 /// form a type, scope or primary expression annotation, or replace the token
759 /// with a typo-corrected keyword. This is only appropriate when the current
760 /// name must refer to an entity which has already been declared.
761 ///
762 /// \param CCC Indicates how to perform typo-correction for this name. If
763 /// NULL, no typo correction will be performed.
764 /// \param AllowImplicitTypename Whether we are in a context where a dependent
765 /// nested-name-specifier without typename is treated as a type (e.g.
766 /// T::type).
768 TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr,
769 ImplicitTypenameContext AllowImplicitTypename =
771
772 /// Push a tok::annot_cxxscope token onto the token stream.
773 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
774
775 /// TryKeywordIdentFallback - For compatibility with system headers using
776 /// keywords as identifiers, attempt to convert the current token to an
777 /// identifier and optionally disable the keyword for the remainder of the
778 /// translation unit. This returns false if the token was not replaced,
779 /// otherwise emits a diagnostic and returns true.
780 bool TryKeywordIdentFallback(bool DisableKeyword);
781
782 /// Get the TemplateIdAnnotation from the token and put it in the
783 /// cleanup pool so that it gets destroyed when parsing the current top level
784 /// declaration is finished.
785 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
786
787 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
788 /// input. If so, it is consumed and false is returned.
789 ///
790 /// If a trivial punctuator misspelling is encountered, a FixIt error
791 /// diagnostic is issued and false is returned after recovery.
792 ///
793 /// If the input is malformed, this emits the specified diagnostic and true is
794 /// returned.
795 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
796 unsigned Diag = diag::err_expected,
797 StringRef DiagMsg = "");
798
799 /// The parser expects a semicolon and, if present, will consume it.
800 ///
801 /// If the next token is not a semicolon, this emits the specified diagnostic,
802 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
803 /// to the semicolon, consumes that extra token.
804 bool ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed = "");
805
806 /// Consume any extra semi-colons until the end of the line.
807 void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
808
809 /// Return false if the next token is an identifier. An 'expected identifier'
810 /// error is emitted otherwise.
811 ///
812 /// The parser tries to recover from the error by checking if the next token
813 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
814 /// was successful.
815 bool expectIdentifier();
816
817 /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
818 enum class CompoundToken {
819 /// A '(' '{' beginning a statement-expression.
820 StmtExprBegin,
821 /// A '}' ')' ending a statement-expression.
822 StmtExprEnd,
823 /// A '[' '[' beginning a C++11 or C23 attribute.
824 AttrBegin,
825 /// A ']' ']' ending a C++11 or C23 attribute.
826 AttrEnd,
827 /// A '::' '*' forming a C++ pointer-to-member declaration.
828 MemberPtr,
829 };
830
831 /// Check that a compound operator was written in a "sensible" way, and warn
832 /// if not.
833 void checkCompoundToken(SourceLocation FirstTokLoc,
834 tok::TokenKind FirstTokKind, CompoundToken Op);
835
836 void diagnoseUseOfC11Keyword(const Token &Tok);
837
838 /// RAII object used to modify the scope flags for the current scope.
839 class ParseScopeFlags {
840 Scope *CurScope;
841 unsigned OldFlags = 0;
842 ParseScopeFlags(const ParseScopeFlags &) = delete;
843 void operator=(const ParseScopeFlags &) = delete;
844
845 public:
846 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is
847 /// false, this object does nothing.
848 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
849
850 /// Restore the flags for the current scope to what they were before this
851 /// object overrode them.
852 ~ParseScopeFlags();
853 };
854
855 /// Emits a diagnostic suggesting parentheses surrounding a
856 /// given range.
857 ///
858 /// \param Loc The location where we'll emit the diagnostic.
859 /// \param DK The kind of diagnostic to emit.
860 /// \param ParenRange Source range enclosing code that should be
861 /// parenthesized.
862 void SuggestParentheses(SourceLocation Loc, unsigned DK,
863 SourceRange ParenRange);
864
865 //===--------------------------------------------------------------------===//
866 // C99 6.9: External Definitions.
867
868 /// ParseExternalDeclaration:
869 ///
870 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
871 /// declaration.
872 ///
873 /// \verbatim
874 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
875 /// function-definition
876 /// declaration
877 /// [GNU] asm-definition
878 /// [GNU] __extension__ external-declaration
879 /// [OBJC] objc-class-definition
880 /// [OBJC] objc-class-declaration
881 /// [OBJC] objc-alias-declaration
882 /// [OBJC] objc-protocol-definition
883 /// [OBJC] objc-method-definition
884 /// [OBJC] @end
885 /// [C++] linkage-specification
886 /// [GNU] asm-definition:
887 /// simple-asm-expr ';'
888 /// [C++11] empty-declaration
889 /// [C++11] attribute-declaration
890 ///
891 /// [C++11] empty-declaration:
892 /// ';'
893 ///
894 /// [C++0x/GNU] 'extern' 'template' declaration
895 ///
896 /// [C++20] module-import-declaration
897 /// \endverbatim
898 ///
899 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributes &DeclAttrs,
900 ParsedAttributes &DeclSpecAttrs,
901 ParsingDeclSpec *DS = nullptr);
902
903 /// Determine whether the current token, if it occurs after a
904 /// declarator, continues a declaration or declaration list.
905 bool isDeclarationAfterDeclarator();
906
907 /// Determine whether the current token, if it occurs after a
908 /// declarator, indicates the start of a function definition.
909 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
910
911 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
912 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
913 ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none);
914
915 /// Parse either a function-definition or a declaration. We can't tell which
916 /// we have until we read up to the compound-statement in function-definition.
917 /// TemplateParams, if non-NULL, provides the template parameters when we're
918 /// parsing a C++ template-declaration.
919 ///
920 /// \verbatim
921 /// function-definition: [C99 6.9.1]
922 /// decl-specs declarator declaration-list[opt] compound-statement
923 /// [C90] function-definition: [C99 6.7.1] - implicit int result
924 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
925 ///
926 /// declaration: [C99 6.7]
927 /// declaration-specifiers init-declarator-list[opt] ';'
928 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
929 /// [OMP] threadprivate-directive
930 /// [OMP] allocate-directive [TODO]
931 /// \endverbatim
932 ///
933 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs,
934 ParsedAttributes &DeclSpecAttrs,
935 ParsingDeclSpec &DS,
936 AccessSpecifier AS);
937
938 void SkipFunctionBody();
939
940 struct ParsedTemplateInfo;
941 class LateParsedAttrList;
942
943 /// ParseFunctionDefinition - We parsed and verified that the specified
944 /// Declarator is well formed. If this is a K&R-style function, read the
945 /// parameters declaration-list, then start the compound-statement.
946 ///
947 /// \verbatim
948 /// function-definition: [C99 6.9.1]
949 /// decl-specs declarator declaration-list[opt] compound-statement
950 /// [C90] function-definition: [C99 6.7.1] - implicit int result
951 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
952 /// [C++] function-definition: [C++ 8.4]
953 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
954 /// function-body
955 /// [C++] function-definition: [C++ 8.4]
956 /// decl-specifier-seq[opt] declarator function-try-block
957 /// \endverbatim
958 ///
959 Decl *ParseFunctionDefinition(
960 ParsingDeclarator &D,
961 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
962 LateParsedAttrList *LateParsedAttrs = nullptr);
963
964 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
965 /// types for a function with a K&R-style identifier list for arguments.
966 void ParseKNRParamDeclarations(Declarator &D);
967
968 /// ParseSimpleAsm
969 ///
970 /// \verbatim
971 /// [GNU] simple-asm-expr:
972 /// 'asm' '(' asm-string-literal ')'
973 /// \endverbatim
974 ///
975 /// EndLoc is filled with the location of the last token of the simple-asm.
976 ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
977
978 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
979 /// allowed to be a wide string, and is not subject to character translation.
980 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
981 /// asm label as opposed to an asm statement, because such a construct does
982 /// not behave well.
983 ///
984 /// \verbatim
985 /// [GNU] asm-string-literal:
986 /// string-literal
987 /// \endverbatim
988 ///
989 ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
990
991 /// Describes the condition of a Microsoft __if_exists or
992 /// __if_not_exists block.
993 struct IfExistsCondition {
994 /// The location of the initial keyword.
995 SourceLocation KeywordLoc;
996 /// Whether this is an __if_exists block (rather than an
997 /// __if_not_exists block).
998 bool IsIfExists;
999
1000 /// Nested-name-specifier preceding the name.
1001 CXXScopeSpec SS;
1002
1003 /// The name we're looking for.
1004 UnqualifiedId Name;
1005
1006 /// The behavior of this __if_exists or __if_not_exists block
1007 /// should.
1008 IfExistsBehavior Behavior;
1009 };
1010
1011 bool ParseMicrosoftIfExistsCondition(IfExistsCondition &Result);
1012 void ParseMicrosoftIfExistsExternalDeclaration();
1013
1014 //===--------------------------------------------------------------------===//
1015 // Modules
1016
1017 /// Parse a declaration beginning with the 'module' keyword or C++20
1018 /// context-sensitive keyword (optionally preceded by 'export').
1019 ///
1020 /// \verbatim
1021 /// module-declaration: [C++20]
1022 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
1023 ///
1024 /// global-module-fragment: [C++2a]
1025 /// 'module' ';' top-level-declaration-seq[opt]
1026 /// module-declaration: [C++2a]
1027 /// 'export'[opt] 'module' module-name module-partition[opt]
1028 /// attribute-specifier-seq[opt] ';'
1029 /// private-module-fragment: [C++2a]
1030 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
1031 /// \endverbatim
1032 DeclGroupPtrTy ParseModuleDecl(Sema::ModuleImportState &ImportState);
1033
1034 /// Parse a module import declaration. This is essentially the same for
1035 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
1036 /// trailing optional attributes (in C++).
1037 ///
1038 /// \verbatim
1039 /// [ObjC] @import declaration:
1040 /// '@' 'import' module-name ';'
1041 /// [ModTS] module-import-declaration:
1042 /// 'import' module-name attribute-specifier-seq[opt] ';'
1043 /// [C++20] module-import-declaration:
1044 /// 'export'[opt] 'import' module-name
1045 /// attribute-specifier-seq[opt] ';'
1046 /// 'export'[opt] 'import' module-partition
1047 /// attribute-specifier-seq[opt] ';'
1048 /// 'export'[opt] 'import' header-name
1049 /// attribute-specifier-seq[opt] ';'
1050 /// \endverbatim
1051 Decl *ParseModuleImport(SourceLocation AtLoc,
1052 Sema::ModuleImportState &ImportState);
1053
1054 /// Try recover parser when module annotation appears where it must not
1055 /// be found.
1056 /// \returns false if the recover was successful and parsing may be continued,
1057 /// or true if parser must bail out to top level and handle the token there.
1058 bool parseMisplacedModuleImport();
1059
1060 bool tryParseMisplacedModuleImport() {
1061 tok::TokenKind Kind = Tok.getKind();
1062 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
1063 Kind == tok::annot_module_include)
1064 return parseMisplacedModuleImport();
1065 return false;
1066 }
1067
1068 /// Parse a C++ / Objective-C module name (both forms use the same
1069 /// grammar).
1070 ///
1071 /// \verbatim
1072 /// module-name:
1073 /// module-name-qualifier[opt] identifier
1074 /// module-name-qualifier:
1075 /// module-name-qualifier[opt] identifier '.'
1076 /// \endverbatim
1077 bool ParseModuleName(SourceLocation UseLoc,
1078 SmallVectorImpl<IdentifierLoc> &Path, bool IsImport);
1079
1080 void DiagnoseInvalidCXXModuleDecl(const Sema::ModuleImportState &ImportState);
1081 void DiagnoseInvalidCXXModuleImport();
1082
1083 //===--------------------------------------------------------------------===//
1084 // Preprocessor code-completion pass-through
1085 void CodeCompleteDirective(bool InConditional) override;
1086 void CodeCompleteInConditionalExclusion() override;
1087 void CodeCompleteMacroName(bool IsDefinition) override;
1088 void CodeCompletePreprocessorExpression() override;
1089 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
1090 unsigned ArgumentIndex) override;
1091 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
1092 void CodeCompleteNaturalLanguage() override;
1093 void CodeCompleteModuleImport(SourceLocation ImportLoc,
1094 ModuleIdPath Path) override;
1095
1096 ///@}
1097
1098 //
1099 //
1100 // -------------------------------------------------------------------------
1101 //
1102 //
1103
1104 /// \name C++ Class Inline Methods
1105 /// Implementations are in ParseCXXInlineMethods.cpp
1106 ///@{
1107
1108private:
1109 struct ParsingClass;
1110
1111 /// [class.mem]p1: "... the class is regarded as complete within
1112 /// - function bodies
1113 /// - default arguments
1114 /// - exception-specifications (TODO: C++0x)
1115 /// - and brace-or-equal-initializers for non-static data members
1116 /// (including such things in nested classes)."
1117 /// LateParsedDeclarations build the tree of those elements so they can
1118 /// be parsed after parsing the top-level class.
1119 class LateParsedDeclaration {
1120 public:
1121 virtual ~LateParsedDeclaration();
1122
1123 virtual void ParseLexedMethodDeclarations();
1124 virtual void ParseLexedMemberInitializers();
1125 virtual void ParseLexedMethodDefs();
1126 virtual void ParseLexedAttributes();
1127 virtual void ParseLexedPragmas();
1128 };
1129
1130 /// Inner node of the LateParsedDeclaration tree that parses
1131 /// all its members recursively.
1132 class LateParsedClass : public LateParsedDeclaration {
1133 public:
1134 LateParsedClass(Parser *P, ParsingClass *C);
1135 ~LateParsedClass() override;
1136
1137 void ParseLexedMethodDeclarations() override;
1138 void ParseLexedMemberInitializers() override;
1139 void ParseLexedMethodDefs() override;
1140 void ParseLexedAttributes() override;
1141 void ParseLexedPragmas() override;
1142
1143 // Delete copy constructor and copy assignment operator.
1144 LateParsedClass(const LateParsedClass &) = delete;
1145 LateParsedClass &operator=(const LateParsedClass &) = delete;
1146
1147 private:
1148 Parser *Self;
1149 ParsingClass *Class;
1150 };
1151
1152 /// Contains the lexed tokens of an attribute with arguments that
1153 /// may reference member variables and so need to be parsed at the
1154 /// end of the class declaration after parsing all other member
1155 /// member declarations.
1156 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1157 /// LateParsedTokens.
1158 struct LateParsedAttribute : public LateParsedDeclaration {
1159 Parser *Self;
1160 CachedTokens Toks;
1161 IdentifierInfo &AttrName;
1162 IdentifierInfo *MacroII = nullptr;
1163 SourceLocation AttrNameLoc;
1164 SmallVector<Decl *, 2> Decls;
1165
1166 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1167 SourceLocation Loc)
1168 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1169
1170 void ParseLexedAttributes() override;
1171
1172 void addDecl(Decl *D) { Decls.push_back(D); }
1173 };
1174
1175 /// Contains the lexed tokens of a pragma with arguments that
1176 /// may reference member variables and so need to be parsed at the
1177 /// end of the class declaration after parsing all other member
1178 /// member declarations.
1179 class LateParsedPragma : public LateParsedDeclaration {
1180 Parser *Self = nullptr;
1182 CachedTokens Toks;
1183
1184 public:
1185 explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
1186 : Self(P), AS(AS) {}
1187
1188 void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
1189 const CachedTokens &toks() const { return Toks; }
1190 AccessSpecifier getAccessSpecifier() const { return AS; }
1191
1192 void ParseLexedPragmas() override;
1193 };
1194
1195 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1196 class LateParsedAttrList : public SmallVector<LateParsedAttribute *, 2> {
1197 public:
1198 LateParsedAttrList(bool PSoon = false,
1199 bool LateAttrParseExperimentalExtOnly = false)
1200 : ParseSoon(PSoon),
1201 LateAttrParseExperimentalExtOnly(LateAttrParseExperimentalExtOnly) {}
1202
1203 bool parseSoon() { return ParseSoon; }
1204 /// returns true iff the attribute to be parsed should only be late parsed
1205 /// if it is annotated with `LateAttrParseExperimentalExt`
1206 bool lateAttrParseExperimentalExtOnly() {
1207 return LateAttrParseExperimentalExtOnly;
1208 }
1209
1210 private:
1211 bool ParseSoon; // Are we planning to parse these shortly after creation?
1212 bool LateAttrParseExperimentalExtOnly;
1213 };
1214
1215 /// Contains the lexed tokens of a member function definition
1216 /// which needs to be parsed at the end of the class declaration
1217 /// after parsing all other member declarations.
1218 struct LexedMethod : public LateParsedDeclaration {
1219 Parser *Self;
1220 Decl *D;
1221 CachedTokens Toks;
1222
1223 explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
1224
1225 void ParseLexedMethodDefs() override;
1226 };
1227
1228 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1229 /// have a default argument that cannot be parsed yet because it
1230 /// occurs within a member function declaration inside the class
1231 /// (C++ [class.mem]p2).
1232 struct LateParsedDefaultArgument {
1233 explicit LateParsedDefaultArgument(
1234 Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr)
1235 : Param(P), Toks(std::move(Toks)) {}
1236
1237 /// Param - The parameter declaration for this parameter.
1238 Decl *Param;
1239
1240 /// Toks - The sequence of tokens that comprises the default
1241 /// argument expression, not including the '=' or the terminating
1242 /// ')' or ','. This will be NULL for parameters that have no
1243 /// default argument.
1244 std::unique_ptr<CachedTokens> Toks;
1245 };
1246
1247 /// LateParsedMethodDeclaration - A method declaration inside a class that
1248 /// contains at least one entity whose parsing needs to be delayed
1249 /// until the class itself is completely-defined, such as a default
1250 /// argument (C++ [class.mem]p2).
1251 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1252 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1253 : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
1254
1255 void ParseLexedMethodDeclarations() override;
1256
1257 Parser *Self;
1258
1259 /// Method - The method declaration.
1260 Decl *Method;
1261
1262 /// DefaultArgs - Contains the parameters of the function and
1263 /// their default arguments. At least one of the parameters will
1264 /// have a default argument, but all of the parameters of the
1265 /// method will be stored so that they can be reintroduced into
1266 /// scope at the appropriate times.
1267 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1268
1269 /// The set of tokens that make up an exception-specification that
1270 /// has not yet been parsed.
1271 CachedTokens *ExceptionSpecTokens;
1272 };
1273
1274 /// LateParsedMemberInitializer - An initializer for a non-static class data
1275 /// member whose parsing must to be delayed until the class is completely
1276 /// defined (C++11 [class.mem]p2).
1277 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1278 LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) {}
1279
1280 void ParseLexedMemberInitializers() override;
1281
1282 Parser *Self;
1283
1284 /// Field - The field declaration.
1285 Decl *Field;
1286
1287 /// CachedTokens - The sequence of tokens that comprises the initializer,
1288 /// including any leading '='.
1289 CachedTokens Toks;
1290 };
1291
1292 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1293 /// C++ class, its method declarations that contain parts that won't be
1294 /// parsed until after the definition is completed (C++ [class.mem]p2),
1295 /// the method declarations and possibly attached inline definitions
1296 /// will be stored here with the tokens that will be parsed to create those
1297 /// entities.
1298 typedef SmallVector<LateParsedDeclaration *, 2>
1299 LateParsedDeclarationsContainer;
1300
1301 /// Utility to re-enter a possibly-templated scope while parsing its
1302 /// late-parsed components.
1304
1305 /// Utility to re-enter a class scope while parsing its late-parsed
1306 /// components.
1307 struct ReenterClassScopeRAII;
1308
1309 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
1310 /// Declarator is a well formed C++ inline method definition. Now lex its body
1311 /// and store its tokens for parsing after the C++ class is complete.
1312 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1313 const ParsedAttributesView &AccessAttrs,
1314 ParsingDeclarator &D,
1315 const ParsedTemplateInfo &TemplateInfo,
1316 const VirtSpecifiers &VS,
1317 SourceLocation PureSpecLoc);
1318
1319 /// Parse the optional ("message") part of a deleted-function-body.
1320 StringLiteral *ParseCXXDeletedFunctionMessage();
1321
1322 /// If we've encountered '= delete' in a context where it is ill-formed, such
1323 /// as in the declaration of a non-function, also skip the ("message") part if
1324 /// it is present to avoid issuing further diagnostics.
1325 void SkipDeletedFunctionBody();
1326
1327 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
1328 /// specified Declarator is a well formed C++ non-static data member
1329 /// declaration. Now lex its initializer and store its tokens for parsing
1330 /// after the class is complete.
1331 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1332
1333 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1334 /// scope appropriately.
1335 void ParseLexedAttributes(ParsingClass &Class);
1336
1337 /// Parse all attributes in LAs, and attach them to Decl D.
1338 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1339 bool EnterScope, bool OnDefinition);
1340
1341 /// Finish parsing an attribute for which parsing was delayed.
1342 /// This will be called at the end of parsing a class declaration
1343 /// for each LateParsedAttribute. We consume the saved tokens and
1344 /// create an attribute with the arguments filled in. We add this
1345 /// to the Attribute list for the decl.
1346 void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope,
1347 bool OnDefinition);
1348
1349 /// ParseLexedMethodDeclarations - We finished parsing the member
1350 /// specification of a top (non-nested) C++ class. Now go over the
1351 /// stack of method declarations with some parts for which parsing was
1352 /// delayed (such as default arguments) and parse them.
1353 void ParseLexedMethodDeclarations(ParsingClass &Class);
1354 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1355
1356 /// ParseLexedMethodDefs - We finished parsing the member specification of a
1357 /// top (non-nested) C++ class. Now go over the stack of lexed methods that
1358 /// were collected during its parsing and parse them all.
1359 void ParseLexedMethodDefs(ParsingClass &Class);
1360 void ParseLexedMethodDef(LexedMethod &LM);
1361
1362 /// ParseLexedMemberInitializers - We finished parsing the member
1363 /// specification of a top (non-nested) C++ class. Now go over the stack of
1364 /// lexed data member initializers that were collected during its parsing and
1365 /// parse them all.
1366 void ParseLexedMemberInitializers(ParsingClass &Class);
1367 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1368
1369 ///@}
1370
1371 //
1372 //
1373 // -------------------------------------------------------------------------
1374 //
1375 //
1376
1377 /// \name Declarations
1378 /// Implementations are in ParseDecl.cpp
1379 ///@{
1380
1381public:
1382 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1383 /// point for skipping past a simple-declaration.
1384 ///
1385 /// Skip until we reach something which seems like a sensible place to pick
1386 /// up parsing after a malformed declaration. This will sometimes stop sooner
1387 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1388 void SkipMalformedDecl();
1389
1390 /// ParseTypeName
1391 /// \verbatim
1392 /// type-name: [C99 6.7.6]
1393 /// specifier-qualifier-list abstract-declarator[opt]
1394 /// \endverbatim
1395 ///
1396 /// Called type-id in C++.
1398 ParseTypeName(SourceRange *Range = nullptr,
1400 AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
1401 ParsedAttributes *Attrs = nullptr);
1402
1403private:
1404 /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
1405 /// and "bool" fast comparison. Only present if AltiVec or ZVector are
1406 /// enabled.
1407 IdentifierInfo *Ident_vector;
1408 IdentifierInfo *Ident_bool;
1409 IdentifierInfo *Ident_Bool;
1410
1411 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
1412 /// Only present if AltiVec enabled.
1413 IdentifierInfo *Ident_pixel;
1414
1415 /// Identifier for "introduced".
1416 IdentifierInfo *Ident_introduced;
1417
1418 /// Identifier for "deprecated".
1419 IdentifierInfo *Ident_deprecated;
1420
1421 /// Identifier for "obsoleted".
1422 IdentifierInfo *Ident_obsoleted;
1423
1424 /// Identifier for "unavailable".
1425 IdentifierInfo *Ident_unavailable;
1426
1427 /// Identifier for "message".
1428 IdentifierInfo *Ident_message;
1429
1430 /// Identifier for "strict".
1431 IdentifierInfo *Ident_strict;
1432
1433 /// Identifier for "replacement".
1434 IdentifierInfo *Ident_replacement;
1435
1436 /// Identifier for "environment".
1437 IdentifierInfo *Ident_environment;
1438
1439 /// Identifiers used by the 'external_source_symbol' attribute.
1440 IdentifierInfo *Ident_language, *Ident_defined_in,
1441 *Ident_generated_declaration, *Ident_USR;
1442
1443 /// Factory object for creating ParsedAttr objects.
1444 AttributeFactory AttrFactory;
1445
1446 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
1447 /// replacing them with the non-context-sensitive keywords. This returns
1448 /// true if the token was replaced.
1449 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec,
1450 unsigned &DiagID, bool &isInvalid) {
1451 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
1452 return false;
1453
1454 if (Tok.getIdentifierInfo() != Ident_vector &&
1455 Tok.getIdentifierInfo() != Ident_bool &&
1456 Tok.getIdentifierInfo() != Ident_Bool &&
1457 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
1458 return false;
1459
1460 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
1461 }
1462
1463 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
1464 /// identifier token, replacing it with the non-context-sensitive __vector.
1465 /// This returns true if the token was replaced.
1466 bool TryAltiVecVectorToken() {
1467 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
1468 Tok.getIdentifierInfo() != Ident_vector)
1469 return false;
1470 return TryAltiVecVectorTokenOutOfLine();
1471 }
1472
1473 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be
1474 /// called from TryAltiVecVectorToken.
1475 bool TryAltiVecVectorTokenOutOfLine();
1476 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
1477 const char *&PrevSpec, unsigned &DiagID,
1478 bool &isInvalid);
1479
1480 void ParseLexedCAttributeList(LateParsedAttrList &LA, bool EnterScope,
1481 ParsedAttributes *OutAttrs = nullptr);
1482
1483 /// Finish parsing an attribute for which parsing was delayed.
1484 /// This will be called at the end of parsing a class declaration
1485 /// for each LateParsedAttribute. We consume the saved tokens and
1486 /// create an attribute with the arguments filled in. We add this
1487 /// to the Attribute list for the decl.
1488 void ParseLexedCAttribute(LateParsedAttribute &LA, bool EnterScope,
1489 ParsedAttributes *OutAttrs = nullptr);
1490
1491 void ParseLexedPragmas(ParsingClass &Class);
1492 void ParseLexedPragma(LateParsedPragma &LP);
1493
1494 /// Consume tokens and store them in the passed token container until
1495 /// we've passed the try keyword and constructor initializers and have
1496 /// consumed the opening brace of the function body. The opening brace will be
1497 /// consumed if and only if there was no error.
1498 ///
1499 /// \return True on error.
1500 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1501
1502 /// ConsumeAndStoreInitializer - Consume and store the token at the passed
1503 /// token container until the end of the current initializer expression
1504 /// (either a default argument or an in-class initializer for a non-static
1505 /// data member).
1506 ///
1507 /// Returns \c true if we reached the end of something initializer-shaped,
1508 /// \c false if we bailed out.
1509 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1510
1511 /// Consume and store tokens from the '?' to the ':' in a conditional
1512 /// expression.
1513 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1514 bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks,
1515 bool StopAtSemi = true,
1516 bool ConsumeFinalToken = true) {
1517 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1518 }
1519
1520 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
1521 /// container until the token 'T' is reached (which gets
1522 /// consumed/stored too, if ConsumeFinalToken).
1523 /// If StopAtSemi is true, then we will stop early at a ';' character.
1524 /// Returns true if token 'T1' or 'T2' was found.
1525 /// NOTE: This is a specialized version of Parser::SkipUntil.
1526 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1527 CachedTokens &Toks, bool StopAtSemi = true,
1528 bool ConsumeFinalToken = true);
1529
1530 //===--------------------------------------------------------------------===//
1531 // C99 6.7: Declarations.
1532
1533 /// A context for parsing declaration specifiers. TODO: flesh this
1534 /// out, there are other significant restrictions on specifiers than
1535 /// would be best implemented in the parser.
1536 enum class DeclSpecContext {
1537 DSC_normal, // normal context
1538 DSC_class, // class context, enables 'friend'
1539 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1540 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1541 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1542 DSC_conv_operator, // C++ type-specifier-seq in an conversion operator
1543 DSC_top_level, // top-level/namespace declaration context
1544 DSC_template_param, // template parameter context
1545 DSC_template_arg, // template argument context
1546 DSC_template_type_arg, // template type argument context
1547 DSC_objc_method_result, // ObjC method result context, enables
1548 // 'instancetype'
1549 DSC_condition, // condition declaration context
1550 DSC_association, // A _Generic selection expression's type association
1551 DSC_new, // C++ new expression
1552 };
1553
1554 /// Is this a context in which we are parsing just a type-specifier (or
1555 /// trailing-type-specifier)?
1556 static bool isTypeSpecifier(DeclSpecContext DSC) {
1557 switch (DSC) {
1558 case DeclSpecContext::DSC_normal:
1559 case DeclSpecContext::DSC_template_param:
1560 case DeclSpecContext::DSC_template_arg:
1561 case DeclSpecContext::DSC_class:
1562 case DeclSpecContext::DSC_top_level:
1563 case DeclSpecContext::DSC_objc_method_result:
1564 case DeclSpecContext::DSC_condition:
1565 return false;
1566
1567 case DeclSpecContext::DSC_template_type_arg:
1568 case DeclSpecContext::DSC_type_specifier:
1569 case DeclSpecContext::DSC_conv_operator:
1570 case DeclSpecContext::DSC_trailing:
1571 case DeclSpecContext::DSC_alias_declaration:
1572 case DeclSpecContext::DSC_association:
1573 case DeclSpecContext::DSC_new:
1574 return true;
1575 }
1576 llvm_unreachable("Missing DeclSpecContext case");
1577 }
1578
1579 /// Whether a defining-type-specifier is permitted in a given context.
1580 enum class AllowDefiningTypeSpec {
1581 /// The grammar doesn't allow a defining-type-specifier here, and we must
1582 /// not parse one (eg, because a '{' could mean something else).
1583 No,
1584 /// The grammar doesn't allow a defining-type-specifier here, but we permit
1585 /// one for error recovery purposes. Sema will reject.
1586 NoButErrorRecovery,
1587 /// The grammar allows a defining-type-specifier here, even though it's
1588 /// always invalid. Sema will reject.
1589 YesButInvalid,
1590 /// The grammar allows a defining-type-specifier here, and one can be valid.
1591 Yes
1592 };
1593
1594 /// Is this a context in which we are parsing defining-type-specifiers (and
1595 /// so permit class and enum definitions in addition to non-defining class and
1596 /// enum elaborated-type-specifiers)?
1597 static AllowDefiningTypeSpec
1598 isDefiningTypeSpecifierContext(DeclSpecContext DSC, bool IsCPlusPlus) {
1599 switch (DSC) {
1600 case DeclSpecContext::DSC_normal:
1601 case DeclSpecContext::DSC_class:
1602 case DeclSpecContext::DSC_top_level:
1603 case DeclSpecContext::DSC_alias_declaration:
1604 case DeclSpecContext::DSC_objc_method_result:
1605 return AllowDefiningTypeSpec::Yes;
1606
1607 case DeclSpecContext::DSC_condition:
1608 case DeclSpecContext::DSC_template_param:
1609 return AllowDefiningTypeSpec::YesButInvalid;
1610
1611 case DeclSpecContext::DSC_template_type_arg:
1612 case DeclSpecContext::DSC_type_specifier:
1613 return AllowDefiningTypeSpec::NoButErrorRecovery;
1614
1615 case DeclSpecContext::DSC_association:
1616 return IsCPlusPlus ? AllowDefiningTypeSpec::NoButErrorRecovery
1617 : AllowDefiningTypeSpec::Yes;
1618
1619 case DeclSpecContext::DSC_trailing:
1620 case DeclSpecContext::DSC_conv_operator:
1621 case DeclSpecContext::DSC_template_arg:
1622 case DeclSpecContext::DSC_new:
1623 return AllowDefiningTypeSpec::No;
1624 }
1625 llvm_unreachable("Missing DeclSpecContext case");
1626 }
1627
1628 /// Is this a context in which an opaque-enum-declaration can appear?
1629 static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
1630 switch (DSC) {
1631 case DeclSpecContext::DSC_normal:
1632 case DeclSpecContext::DSC_class:
1633 case DeclSpecContext::DSC_top_level:
1634 return true;
1635
1636 case DeclSpecContext::DSC_alias_declaration:
1637 case DeclSpecContext::DSC_objc_method_result:
1638 case DeclSpecContext::DSC_condition:
1639 case DeclSpecContext::DSC_template_param:
1640 case DeclSpecContext::DSC_template_type_arg:
1641 case DeclSpecContext::DSC_type_specifier:
1642 case DeclSpecContext::DSC_trailing:
1643 case DeclSpecContext::DSC_association:
1644 case DeclSpecContext::DSC_conv_operator:
1645 case DeclSpecContext::DSC_template_arg:
1646 case DeclSpecContext::DSC_new:
1647
1648 return false;
1649 }
1650 llvm_unreachable("Missing DeclSpecContext case");
1651 }
1652
1653 /// Is this a context in which we can perform class template argument
1654 /// deduction?
1655 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
1656 switch (DSC) {
1657 case DeclSpecContext::DSC_normal:
1658 case DeclSpecContext::DSC_template_param:
1659 case DeclSpecContext::DSC_template_arg:
1660 case DeclSpecContext::DSC_class:
1661 case DeclSpecContext::DSC_top_level:
1662 case DeclSpecContext::DSC_condition:
1663 case DeclSpecContext::DSC_type_specifier:
1664 case DeclSpecContext::DSC_association:
1665 case DeclSpecContext::DSC_conv_operator:
1666 case DeclSpecContext::DSC_new:
1667 return true;
1668
1669 case DeclSpecContext::DSC_objc_method_result:
1670 case DeclSpecContext::DSC_template_type_arg:
1671 case DeclSpecContext::DSC_trailing:
1672 case DeclSpecContext::DSC_alias_declaration:
1673 return false;
1674 }
1675 llvm_unreachable("Missing DeclSpecContext case");
1676 }
1677
1678 // Is this a context in which an implicit 'typename' is allowed?
1680 getImplicitTypenameContext(DeclSpecContext DSC) {
1681 switch (DSC) {
1682 case DeclSpecContext::DSC_class:
1683 case DeclSpecContext::DSC_top_level:
1684 case DeclSpecContext::DSC_type_specifier:
1685 case DeclSpecContext::DSC_template_type_arg:
1686 case DeclSpecContext::DSC_trailing:
1687 case DeclSpecContext::DSC_alias_declaration:
1688 case DeclSpecContext::DSC_template_param:
1689 case DeclSpecContext::DSC_new:
1691
1692 case DeclSpecContext::DSC_normal:
1693 case DeclSpecContext::DSC_objc_method_result:
1694 case DeclSpecContext::DSC_condition:
1695 case DeclSpecContext::DSC_template_arg:
1696 case DeclSpecContext::DSC_conv_operator:
1697 case DeclSpecContext::DSC_association:
1699 }
1700 llvm_unreachable("Missing DeclSpecContext case");
1701 }
1702
1703 /// Information on a C++0x for-range-initializer found while parsing a
1704 /// declaration which turns out to be a for-range-declaration.
1705 struct ForRangeInit {
1706 SourceLocation ColonLoc;
1707 ExprResult RangeExpr;
1708 SmallVector<MaterializeTemporaryExpr *, 8> LifetimeExtendTemps;
1709 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1710 };
1711 struct ForRangeInfo : ForRangeInit {
1712 StmtResult LoopVar;
1713 };
1714
1715 /// ParseDeclaration - Parse a full 'declaration', which consists of
1716 /// declaration-specifiers, some number of declarators, and a semicolon.
1717 /// 'Context' should be a DeclaratorContext value. This returns the
1718 /// location of the semicolon in DeclEnd.
1719 ///
1720 /// \verbatim
1721 /// declaration: [C99 6.7]
1722 /// block-declaration ->
1723 /// simple-declaration
1724 /// others [FIXME]
1725 /// [C++] template-declaration
1726 /// [C++] namespace-definition
1727 /// [C++] using-directive
1728 /// [C++] using-declaration
1729 /// [C++11/C11] static_assert-declaration
1730 /// others... [FIXME]
1731 /// \endverbatim
1732 ///
1733 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
1734 SourceLocation &DeclEnd,
1735 ParsedAttributes &DeclAttrs,
1736 ParsedAttributes &DeclSpecAttrs,
1737 SourceLocation *DeclSpecStart = nullptr);
1738
1739 /// \verbatim
1740 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1741 /// declaration-specifiers init-declarator-list[opt] ';'
1742 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1743 /// init-declarator-list ';'
1744 ///[C90/C++]init-declarator-list ';' [TODO]
1745 /// [OMP] threadprivate-directive
1746 /// [OMP] allocate-directive [TODO]
1747 ///
1748 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1749 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1750 /// \endverbatim
1751 ///
1752 /// If RequireSemi is false, this does not check for a ';' at the end of the
1753 /// declaration. If it is true, it checks for and eats it.
1754 ///
1755 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1756 /// of a simple-declaration. If we find that we are, we also parse the
1757 /// for-range-initializer, and place it here.
1758 ///
1759 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1760 /// the Declaration. The SourceLocation for this Decl is set to
1761 /// DeclSpecStart if DeclSpecStart is non-null.
1763 ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1764 ParsedAttributes &DeclAttrs,
1765 ParsedAttributes &DeclSpecAttrs, bool RequireSemi,
1766 ForRangeInit *FRI = nullptr,
1767 SourceLocation *DeclSpecStart = nullptr);
1768
1769 /// ParseDeclGroup - Having concluded that this is either a function
1770 /// definition or a group of object declarations, actually parse the
1771 /// result.
1772 ///
1773 /// Returns true if this might be the start of a declarator, or a common typo
1774 /// for a declarator.
1775 bool MightBeDeclarator(DeclaratorContext Context);
1776 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
1777 ParsedAttributes &Attrs,
1778 ParsedTemplateInfo &TemplateInfo,
1779 SourceLocation *DeclEnd = nullptr,
1780 ForRangeInit *FRI = nullptr);
1781
1782 /// Parse 'declaration' after parsing 'declaration-specifiers
1783 /// declarator'. This method parses the remainder of the declaration
1784 /// (including any attributes or initializer, among other things) and
1785 /// finalizes the declaration.
1786 ///
1787 /// \verbatim
1788 /// init-declarator: [C99 6.7]
1789 /// declarator
1790 /// declarator '=' initializer
1791 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1792 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1793 /// [C++] declarator initializer[opt]
1794 ///
1795 /// [C++] initializer:
1796 /// [C++] '=' initializer-clause
1797 /// [C++] '(' expression-list ')'
1798 /// [C++0x] '=' 'default' [TODO]
1799 /// [C++0x] '=' 'delete'
1800 /// [C++0x] braced-init-list
1801 /// \endverbatim
1802 ///
1803 /// According to the standard grammar, =default and =delete are function
1804 /// definitions, but that definitely doesn't fit with the parser here.
1805 ///
1806 Decl *ParseDeclarationAfterDeclarator(
1807 Declarator &D,
1808 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1809
1810 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1811 /// declarator. Returns true on an error.
1812 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1813 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1814 Declarator &D,
1815 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1816 ForRangeInit *FRI = nullptr);
1817
1818 /// ParseImplicitInt - This method is called when we have an non-typename
1819 /// identifier in a declspec (which normally terminates the decl spec) when
1820 /// the declspec has no type specifier. In this case, the declspec is either
1821 /// malformed or is "implicit int" (in K&R and C89).
1822 ///
1823 /// This method handles diagnosing this prettily and returns false if the
1824 /// declspec is done being processed. If it recovers and thinks there may be
1825 /// other pieces of declspec after it, it returns true.
1826 ///
1827 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1828 ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
1829 DeclSpecContext DSC, ParsedAttributes &Attrs);
1830
1831 /// Determine the declaration specifier context from the declarator
1832 /// context.
1833 ///
1834 /// \param Context the declarator context, which is one of the
1835 /// DeclaratorContext enumerator values.
1836 DeclSpecContext
1837 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
1838 void
1839 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
1841 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
1842 LateParsedAttrList *LateAttrs = nullptr) {
1843 return ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs,
1844 getImplicitTypenameContext(DSC));
1845 }
1846
1847 /// ParseDeclarationSpecifiers
1848 /// \verbatim
1849 /// declaration-specifiers: [C99 6.7]
1850 /// storage-class-specifier declaration-specifiers[opt]
1851 /// type-specifier declaration-specifiers[opt]
1852 /// [C99] function-specifier declaration-specifiers[opt]
1853 /// [C11] alignment-specifier declaration-specifiers[opt]
1854 /// [GNU] attributes declaration-specifiers[opt]
1855 /// [Clang] '__module_private__' declaration-specifiers[opt]
1856 /// [ObjC1] '__kindof' declaration-specifiers[opt]
1857 ///
1858 /// storage-class-specifier: [C99 6.7.1]
1859 /// 'typedef'
1860 /// 'extern'
1861 /// 'static'
1862 /// 'auto'
1863 /// 'register'
1864 /// [C++] 'mutable'
1865 /// [C++11] 'thread_local'
1866 /// [C11] '_Thread_local'
1867 /// [GNU] '__thread'
1868 /// function-specifier: [C99 6.7.4]
1869 /// [C99] 'inline'
1870 /// [C++] 'virtual'
1871 /// [C++] 'explicit'
1872 /// [OpenCL] '__kernel'
1873 /// 'friend': [C++ dcl.friend]
1874 /// 'constexpr': [C++0x dcl.constexpr]
1875 /// \endverbatim
1876 void
1877 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
1878 AccessSpecifier AS, DeclSpecContext DSC,
1879 LateParsedAttrList *LateAttrs,
1880 ImplicitTypenameContext AllowImplicitTypename);
1881
1882 /// Determine whether we're looking at something that might be a declarator
1883 /// in a simple-declaration. If it can't possibly be a declarator, maybe
1884 /// diagnose a missing semicolon after a prior tag definition in the decl
1885 /// specifier.
1886 ///
1887 /// \return \c true if an error occurred and this can't be any kind of
1888 /// declaration.
1889 bool DiagnoseMissingSemiAfterTagDefinition(
1890 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
1891 LateParsedAttrList *LateAttrs = nullptr);
1892
1893 void ParseSpecifierQualifierList(
1894 DeclSpec &DS, AccessSpecifier AS = AS_none,
1895 DeclSpecContext DSC = DeclSpecContext::DSC_normal) {
1896 ParseSpecifierQualifierList(DS, getImplicitTypenameContext(DSC), AS, DSC);
1897 }
1898
1899 /// ParseSpecifierQualifierList
1900 /// \verbatim
1901 /// specifier-qualifier-list:
1902 /// type-specifier specifier-qualifier-list[opt]
1903 /// type-qualifier specifier-qualifier-list[opt]
1904 /// [GNU] attributes specifier-qualifier-list[opt]
1905 /// \endverbatim
1906 ///
1907 void ParseSpecifierQualifierList(
1908 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
1910 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
1911
1912 /// ParseEnumSpecifier
1913 /// \verbatim
1914 /// enum-specifier: [C99 6.7.2.2]
1915 /// 'enum' identifier[opt] '{' enumerator-list '}'
1916 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1917 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1918 /// '}' attributes[opt]
1919 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
1920 /// '}'
1921 /// 'enum' identifier
1922 /// [GNU] 'enum' attributes[opt] identifier
1923 ///
1924 /// [C++11] enum-head '{' enumerator-list[opt] '}'
1925 /// [C++11] enum-head '{' enumerator-list ',' '}'
1926 ///
1927 /// enum-head: [C++11]
1928 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
1929 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
1930 /// identifier enum-base[opt]
1931 ///
1932 /// enum-key: [C++11]
1933 /// 'enum'
1934 /// 'enum' 'class'
1935 /// 'enum' 'struct'
1936 ///
1937 /// enum-base: [C++11]
1938 /// ':' type-specifier-seq
1939 ///
1940 /// [C++] elaborated-type-specifier:
1941 /// [C++] 'enum' nested-name-specifier[opt] identifier
1942 /// \endverbatim
1943 ///
1944 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1945 const ParsedTemplateInfo &TemplateInfo,
1946 AccessSpecifier AS, DeclSpecContext DSC);
1947
1948 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
1949 /// \verbatim
1950 /// enumerator-list:
1951 /// enumerator
1952 /// enumerator-list ',' enumerator
1953 /// enumerator:
1954 /// enumeration-constant attributes[opt]
1955 /// enumeration-constant attributes[opt] '=' constant-expression
1956 /// enumeration-constant:
1957 /// identifier
1958 /// \endverbatim
1959 ///
1960 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl,
1961 SkipBodyInfo *SkipBody = nullptr);
1962
1963 /// ParseStructUnionBody
1964 /// \verbatim
1965 /// struct-contents:
1966 /// struct-declaration-list
1967 /// [EXT] empty
1968 /// [GNU] "struct-declaration-list" without terminating ';'
1969 /// struct-declaration-list:
1970 /// struct-declaration
1971 /// struct-declaration-list struct-declaration
1972 /// [OBC] '@' 'defs' '(' class-name ')'
1973 /// \endverbatim
1974 ///
1975 void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
1976 RecordDecl *TagDecl);
1977
1978 /// ParseStructDeclaration - Parse a struct declaration without the
1979 /// terminating semicolon.
1980 ///
1981 /// Note that a struct declaration refers to a declaration in a struct,
1982 /// not to the declaration of a struct.
1983 ///
1984 /// \verbatim
1985 /// struct-declaration:
1986 /// [C23] attributes-specifier-seq[opt]
1987 /// specifier-qualifier-list struct-declarator-list
1988 /// [GNU] __extension__ struct-declaration
1989 /// [GNU] specifier-qualifier-list
1990 /// struct-declarator-list:
1991 /// struct-declarator
1992 /// struct-declarator-list ',' struct-declarator
1993 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
1994 /// struct-declarator:
1995 /// declarator
1996 /// [GNU] declarator attributes[opt]
1997 /// declarator[opt] ':' constant-expression
1998 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
1999 /// \endverbatim
2000 ///
2001 void ParseStructDeclaration(
2002 ParsingDeclSpec &DS,
2003 llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
2004 LateParsedAttrList *LateFieldAttrs = nullptr);
2005
2006 DeclGroupPtrTy ParseTopLevelStmtDecl();
2007
2008 /// isDeclarationSpecifier() - Return true if the current token is part of a
2009 /// declaration specifier.
2010 ///
2011 /// \param AllowImplicitTypename whether this is a context where T::type [T
2012 /// dependent] can appear.
2013 /// \param DisambiguatingWithExpression True to indicate that the purpose of
2014 /// this check is to disambiguate between an expression and a declaration.
2015 bool isDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2016 bool DisambiguatingWithExpression = false);
2017
2018 /// isTypeSpecifierQualifier - Return true if the current token could be the
2019 /// start of a specifier-qualifier-list.
2020 bool isTypeSpecifierQualifier();
2021
2022 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2023 /// is definitely a type-specifier. Return false if it isn't part of a type
2024 /// specifier or if we're not sure.
2025 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2026
2027 /// Starting with a scope specifier, identifier, or
2028 /// template-id that refers to the current class, determine whether
2029 /// this is a constructor declarator.
2030 bool isConstructorDeclarator(
2031 bool Unqualified, bool DeductionGuide = false,
2033 const ParsedTemplateInfo *TemplateInfo = nullptr);
2034
2035 /// Diagnoses use of _ExtInt as being deprecated, and diagnoses use of
2036 /// _BitInt as an extension when appropriate.
2037 void DiagnoseBitIntUse(const Token &Tok);
2038
2039 // Check for the start of an attribute-specifier-seq in a context where an
2040 // attribute is not allowed.
2041 bool CheckProhibitedCXX11Attribute() {
2042 assert(Tok.is(tok::l_square));
2043 if (NextToken().isNot(tok::l_square))
2044 return false;
2045 return DiagnoseProhibitedCXX11Attribute();
2046 }
2047
2048 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square
2049 /// brackets of a C++11 attribute-specifier in a location where an attribute
2050 /// is not permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed.
2051 /// Diagnose this situation.
2052 ///
2053 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false
2054 /// if this doesn't appear to actually be an attribute-specifier, and the
2055 /// caller should try to parse it.
2056 bool DiagnoseProhibitedCXX11Attribute();
2057
2058 void CheckMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2059 SourceLocation CorrectLocation) {
2060 if (!Tok.isRegularKeywordAttribute() &&
2061 (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2062 Tok.isNot(tok::kw_alignas))
2063 return;
2064 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2065 }
2066
2067 /// We have found the opening square brackets of a C++11
2068 /// attribute-specifier in a location where an attribute is not permitted, but
2069 /// we know where the attributes ought to be written. Parse them anyway, and
2070 /// provide a fixit moving them to the right place.
2071 void DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2072 SourceLocation CorrectLocation);
2073
2074 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
2075 // applies to var, not the type Foo.
2076 // As an exception to the rule, __declspec(align(...)) before the
2077 // class-key affects the type instead of the variable.
2078 // Also, Microsoft-style [attributes] seem to affect the type instead of the
2079 // variable.
2080 // This function moves attributes that should apply to the type off DS to
2081 // Attrs.
2082 void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS,
2083 TagUseKind TUK);
2084
2085 // FixItLoc = possible correct location for the attributes
2086 void ProhibitAttributes(ParsedAttributes &Attrs,
2087 SourceLocation FixItLoc = SourceLocation()) {
2088 if (Attrs.Range.isInvalid())
2089 return;
2090 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2091 Attrs.clear();
2092 }
2093
2094 void ProhibitAttributes(ParsedAttributesView &Attrs,
2095 SourceLocation FixItLoc = SourceLocation()) {
2096 if (Attrs.Range.isInvalid())
2097 return;
2098 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2099 Attrs.clearListOnly();
2100 }
2101 void DiagnoseProhibitedAttributes(const ParsedAttributesView &Attrs,
2102 SourceLocation FixItLoc);
2103
2104 // Forbid C++11 and C23 attributes that appear on certain syntactic locations
2105 // which standard permits but we don't supported yet, for example, attributes
2106 // appertain to decl specifiers.
2107 // For the most cases we don't want to warn on unknown type attributes, but
2108 // left them to later diagnoses. However, for a few cases like module
2109 // declarations and module import declarations, we should do it.
2110 void ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned AttrDiagID,
2111 unsigned KeywordDiagId,
2112 bool DiagnoseEmptyAttrs = false,
2113 bool WarnOnUnknownAttrs = false);
2114
2115 /// Emit warnings for C++11 and C23 attributes that are in a position that
2116 /// clang accepts as an extension.
2117 void DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs);
2118
2119 ExprResult ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName);
2120
2121 /// Parses a comma-delimited list of arguments of an attribute \p AttrName,
2122 /// filling \p Exprs. \p ArgsProperties specifies which of the arguments
2123 /// should be parsed as unevaluated string literals. \p Arg is the number
2124 /// of arguments parsed before calling / this function (the index of the
2125 /// argument to be parsed next).
2126 bool ParseAttributeArgumentList(
2127 const IdentifierInfo &AttrName, SmallVectorImpl<Expr *> &Exprs,
2128 ParsedAttributeArgumentsProperties ArgsProperties, unsigned Arg);
2129
2130 /// Parses syntax-generic attribute arguments for attributes which are
2131 /// known to the implementation, and adds them to the given ParsedAttributes
2132 /// list with the given attribute syntax. Returns the number of arguments
2133 /// parsed for the attribute.
2134 unsigned
2135 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2136 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2137 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2138 ParsedAttr::Form Form);
2139
2140 enum ParseAttrKindMask {
2141 PAKM_GNU = 1 << 0,
2142 PAKM_Declspec = 1 << 1,
2143 PAKM_CXX11 = 1 << 2,
2144 };
2145
2146 /// \brief Parse attributes based on what syntaxes are desired, allowing for
2147 /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2148 /// __attribute__((...)) __declspec(...) __attribute__((...)))
2149 /// Note that Microsoft attributes (spelled with single square brackets) are
2150 /// not supported by this because of parsing ambiguities with other
2151 /// constructs.
2152 ///
2153 /// There are some attribute parse orderings that should not be allowed in
2154 /// arbitrary order. e.g.,
2155 ///
2156 /// \verbatim
2157 /// [[]] __attribute__(()) int i; // OK
2158 /// __attribute__(()) [[]] int i; // Not OK
2159 /// \endverbatim
2160 ///
2161 /// Such situations should use the specific attribute parsing functionality.
2162 void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2163 LateParsedAttrList *LateAttrs = nullptr);
2164 /// \brief Possibly parse attributes based on what syntaxes are desired,
2165 /// allowing for the order to vary.
2166 bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2167 LateParsedAttrList *LateAttrs = nullptr) {
2168 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2169 isAllowedCXX11AttributeSpecifier()) {
2170 ParseAttributes(WhichAttrKinds, Attrs, LateAttrs);
2171 return true;
2172 }
2173 return false;
2174 }
2175
2176 void MaybeParseGNUAttributes(Declarator &D,
2177 LateParsedAttrList *LateAttrs = nullptr) {
2178 if (Tok.is(tok::kw___attribute)) {
2179 ParsedAttributes Attrs(AttrFactory);
2180 ParseGNUAttributes(Attrs, LateAttrs, &D);
2181 D.takeAttributesAppending(Attrs);
2182 }
2183 }
2184
2185 bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2186 LateParsedAttrList *LateAttrs = nullptr) {
2187 if (Tok.is(tok::kw___attribute)) {
2188 ParseGNUAttributes(Attrs, LateAttrs);
2189 return true;
2190 }
2191 return false;
2192 }
2193
2194 /// ParseSingleGNUAttribute - Parse a single GNU attribute.
2195 ///
2196 /// \verbatim
2197 /// [GNU] attrib:
2198 /// empty
2199 /// attrib-name
2200 /// attrib-name '(' identifier ')'
2201 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
2202 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
2203 ///
2204 /// [GNU] attrib-name:
2205 /// identifier
2206 /// typespec
2207 /// typequal
2208 /// storageclass
2209 /// \endverbatim
2210 bool ParseSingleGNUAttribute(ParsedAttributes &Attrs, SourceLocation &EndLoc,
2211 LateParsedAttrList *LateAttrs = nullptr,
2212 Declarator *D = nullptr);
2213
2214 /// ParseGNUAttributes - Parse a non-empty attributes list.
2215 ///
2216 /// \verbatim
2217 /// [GNU] attributes:
2218 /// attribute
2219 /// attributes attribute
2220 ///
2221 /// [GNU] attribute:
2222 /// '__attribute__' '(' '(' attribute-list ')' ')'
2223 ///
2224 /// [GNU] attribute-list:
2225 /// attrib
2226 /// attribute_list ',' attrib
2227 ///
2228 /// [GNU] attrib:
2229 /// empty
2230 /// attrib-name
2231 /// attrib-name '(' identifier ')'
2232 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
2233 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
2234 ///
2235 /// [GNU] attrib-name:
2236 /// identifier
2237 /// typespec
2238 /// typequal
2239 /// storageclass
2240 /// \endverbatim
2241 ///
2242 /// Whether an attribute takes an 'identifier' is determined by the
2243 /// attrib-name. GCC's behavior here is not worth imitating:
2244 ///
2245 /// * In C mode, if the attribute argument list starts with an identifier
2246 /// followed by a ',' or an ')', and the identifier doesn't resolve to
2247 /// a type, it is parsed as an identifier. If the attribute actually
2248 /// wanted an expression, it's out of luck (but it turns out that no
2249 /// attributes work that way, because C constant expressions are very
2250 /// limited).
2251 /// * In C++ mode, if the attribute argument list starts with an identifier,
2252 /// and the attribute *wants* an identifier, it is parsed as an identifier.
2253 /// At block scope, any additional tokens between the identifier and the
2254 /// ',' or ')' are ignored, otherwise they produce a parse error.
2255 ///
2256 /// We follow the C++ model, but don't allow junk after the identifier.
2257 void ParseGNUAttributes(ParsedAttributes &Attrs,
2258 LateParsedAttrList *LateAttrs = nullptr,
2259 Declarator *D = nullptr);
2260
2261 /// Parse the arguments to a parameterized GNU attribute or
2262 /// a C++11 attribute in "gnu" namespace.
2263 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2264 SourceLocation AttrNameLoc,
2265 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2266 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2267 ParsedAttr::Form Form, Declarator *D);
2268 IdentifierLoc *ParseIdentifierLoc();
2269
2270 unsigned
2271 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2272 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2273 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2274 ParsedAttr::Form Form);
2275
2276 void MaybeParseCXX11Attributes(Declarator &D) {
2277 if (isAllowedCXX11AttributeSpecifier()) {
2278 ParsedAttributes Attrs(AttrFactory);
2279 ParseCXX11Attributes(Attrs);
2280 D.takeAttributesAppending(Attrs);
2281 }
2282 }
2283
2284 bool MaybeParseCXX11Attributes(ParsedAttributes &Attrs,
2285 bool OuterMightBeMessageSend = false) {
2286 if (isAllowedCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) {
2287 ParseCXX11Attributes(Attrs);
2288 return true;
2289 }
2290 return false;
2291 }
2292
2293 bool MaybeParseMicrosoftAttributes(ParsedAttributes &Attrs) {
2294 bool AttrsParsed = false;
2295 if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) &&
2296 Tok.is(tok::l_square)) {
2297 ParsedAttributes AttrsWithRange(AttrFactory);
2298 ParseMicrosoftAttributes(AttrsWithRange);
2299 AttrsParsed = !AttrsWithRange.empty();
2300 Attrs.takeAllAppendingFrom(AttrsWithRange);
2301 }
2302 return AttrsParsed;
2303 }
2304 bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
2305 if (getLangOpts().DeclSpecKeyword && Tok.is(tok::kw___declspec)) {
2306 ParseMicrosoftDeclSpecs(Attrs);
2307 return true;
2308 }
2309 return false;
2310 }
2311
2312 /// \verbatim
2313 /// [MS] decl-specifier:
2314 /// __declspec ( extended-decl-modifier-seq )
2315 ///
2316 /// [MS] extended-decl-modifier-seq:
2317 /// extended-decl-modifier[opt]
2318 /// extended-decl-modifier extended-decl-modifier-seq
2319 /// \endverbatim
2320 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs);
2321 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2322 SourceLocation AttrNameLoc,
2323 ParsedAttributes &Attrs);
2324 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2325 void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &Attrs);
2326 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2327 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2328
2329 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2330 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2331 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2332 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2333 void ParseCUDAFunctionAttributes(ParsedAttributes &attrs);
2334 bool isHLSLQualifier(const Token &Tok) const;
2335 void ParseHLSLQualifiers(ParsedAttributes &Attrs);
2336
2337 /// Parse a version number.
2338 ///
2339 /// \verbatim
2340 /// version:
2341 /// simple-integer
2342 /// simple-integer '.' simple-integer
2343 /// simple-integer '_' simple-integer
2344 /// simple-integer '.' simple-integer '.' simple-integer
2345 /// simple-integer '_' simple-integer '_' simple-integer
2346 /// \endverbatim
2347 VersionTuple ParseVersionTuple(SourceRange &Range);
2348
2349 /// Parse the contents of the "availability" attribute.
2350 ///
2351 /// \verbatim
2352 /// availability-attribute:
2353 /// 'availability' '(' platform ',' opt-strict version-arg-list,
2354 /// opt-replacement, opt-message')'
2355 ///
2356 /// platform:
2357 /// identifier
2358 ///
2359 /// opt-strict:
2360 /// 'strict' ','
2361 ///
2362 /// version-arg-list:
2363 /// version-arg
2364 /// version-arg ',' version-arg-list
2365 ///
2366 /// version-arg:
2367 /// 'introduced' '=' version
2368 /// 'deprecated' '=' version
2369 /// 'obsoleted' = version
2370 /// 'unavailable'
2371 /// opt-replacement:
2372 /// 'replacement' '=' <string>
2373 /// opt-message:
2374 /// 'message' '=' <string>
2375 /// \endverbatim
2376 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2377 SourceLocation AvailabilityLoc,
2378 ParsedAttributes &attrs,
2379 SourceLocation *endLoc,
2380 IdentifierInfo *ScopeName,
2381 SourceLocation ScopeLoc,
2382 ParsedAttr::Form Form);
2383
2384 /// Parse the contents of the "external_source_symbol" attribute.
2385 ///
2386 /// \verbatim
2387 /// external-source-symbol-attribute:
2388 /// 'external_source_symbol' '(' keyword-arg-list ')'
2389 ///
2390 /// keyword-arg-list:
2391 /// keyword-arg
2392 /// keyword-arg ',' keyword-arg-list
2393 ///
2394 /// keyword-arg:
2395 /// 'language' '=' <string>
2396 /// 'defined_in' '=' <string>
2397 /// 'USR' '=' <string>
2398 /// 'generated_declaration'
2399 /// \endverbatim
2400 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2401 SourceLocation Loc,
2402 ParsedAttributes &Attrs,
2403 SourceLocation *EndLoc,
2404 IdentifierInfo *ScopeName,
2405 SourceLocation ScopeLoc,
2406 ParsedAttr::Form Form);
2407
2408 /// Parse the contents of the "objc_bridge_related" attribute.
2409 /// \verbatim
2410 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
2411 /// related_class:
2412 /// Identifier
2413 ///
2414 /// opt-class_method:
2415 /// Identifier: | <empty>
2416 ///
2417 /// opt-instance_method:
2418 /// Identifier | <empty>
2419 /// \endverbatim
2420 ///
2421 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2422 SourceLocation ObjCBridgeRelatedLoc,
2423 ParsedAttributes &Attrs,
2424 SourceLocation *EndLoc,
2425 IdentifierInfo *ScopeName,
2426 SourceLocation ScopeLoc,
2427 ParsedAttr::Form Form);
2428
2429 void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
2430 SourceLocation AttrNameLoc,
2431 ParsedAttributes &Attrs,
2432 SourceLocation *EndLoc,
2433 IdentifierInfo *ScopeName,
2434 SourceLocation ScopeLoc,
2435 ParsedAttr::Form Form);
2436
2437 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2438 SourceLocation AttrNameLoc,
2439 ParsedAttributes &Attrs,
2440 SourceLocation *EndLoc,
2441 IdentifierInfo *ScopeName,
2442 SourceLocation ScopeLoc,
2443 ParsedAttr::Form Form);
2444
2445 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2446 SourceLocation AttrNameLoc,
2447 ParsedAttributes &Attrs,
2448 IdentifierInfo *ScopeName,
2449 SourceLocation ScopeLoc,
2450 ParsedAttr::Form Form);
2451
2452 void DistributeCLateParsedAttrs(Decl *Dcl, LateParsedAttrList *LateAttrs);
2453
2454 /// Bounds attributes (e.g., counted_by):
2455 /// \verbatim
2456 /// AttrName '(' expression ')'
2457 /// \endverbatim
2458 void ParseBoundsAttribute(IdentifierInfo &AttrName,
2459 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2460 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2461 ParsedAttr::Form Form);
2462
2463 /// \verbatim
2464 /// [GNU] typeof-specifier:
2465 /// typeof ( expressions )
2466 /// typeof ( type-name )
2467 /// [GNU/C++] typeof unary-expression
2468 /// [C23] typeof-specifier:
2469 /// typeof '(' typeof-specifier-argument ')'
2470 /// typeof_unqual '(' typeof-specifier-argument ')'
2471 ///
2472 /// typeof-specifier-argument:
2473 /// expression
2474 /// type-name
2475 /// \endverbatim
2476 ///
2477 void ParseTypeofSpecifier(DeclSpec &DS);
2478
2479 /// \verbatim
2480 /// [C11] atomic-specifier:
2481 /// _Atomic ( type-name )
2482 /// \endverbatim
2483 ///
2484 void ParseAtomicSpecifier(DeclSpec &DS);
2485
2486 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2487 ///
2488 /// \verbatim
2489 /// [C11] type-id
2490 /// [C11] constant-expression
2491 /// [C++0x] type-id ...[opt]
2492 /// [C++0x] assignment-expression ...[opt]
2493 /// \endverbatim
2494 ExprResult ParseAlignArgument(StringRef KWName, SourceLocation Start,
2495 SourceLocation &EllipsisLoc, bool &IsType,
2496 ParsedType &Ty);
2497
2498 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2499 /// attribute to Attrs.
2500 ///
2501 /// \verbatim
2502 /// alignment-specifier:
2503 /// [C11] '_Alignas' '(' type-id ')'
2504 /// [C11] '_Alignas' '(' constant-expression ')'
2505 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2506 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2507 /// \endverbatim
2508 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2509 SourceLocation *endLoc = nullptr);
2510 ExprResult ParseExtIntegerArgument();
2511
2512 /// \verbatim
2513 /// type-qualifier:
2514 /// ('__ptrauth') '(' constant-expression
2515 /// (',' constant-expression)[opt]
2516 /// (',' constant-expression)[opt] ')'
2517 /// \endverbatim
2518 void ParsePtrauthQualifier(ParsedAttributes &Attrs);
2519
2520 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2521 /// enter a new C++ declarator scope and exit it when the function is
2522 /// finished.
2523 class DeclaratorScopeObj {
2524 Parser &P;
2525 CXXScopeSpec &SS;
2526 bool EnteredScope;
2527 bool CreatedScope;
2528
2529 public:
2530 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2531 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2532
2533 void EnterDeclaratorScope() {
2534 assert(!EnteredScope && "Already entered the scope!");
2535 assert(SS.isSet() && "C++ scope was not set!");
2536
2537 CreatedScope = true;
2538 P.EnterScope(0); // Not a decl scope.
2539
2540 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2541 EnteredScope = true;
2542 }
2543
2544 ~DeclaratorScopeObj() {
2545 if (EnteredScope) {
2546 assert(SS.isSet() && "C++ scope was cleared ?");
2547 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2548 }
2549 if (CreatedScope)
2550 P.ExitScope();
2551 }
2552 };
2553
2554 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2555 void ParseDeclarator(Declarator &D);
2556 /// A function that parses a variant of direct-declarator.
2557 typedef void (Parser::*DirectDeclParseFunction)(Declarator &);
2558
2559 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The
2560 /// direct-declarator is parsed by the function passed to it. Pass null, and
2561 /// the direct-declarator isn't parsed at all, making this function
2562 /// effectively parse the C++ ptr-operator production.
2563 ///
2564 /// If the grammar of this construct is extended, matching changes must also
2565 /// be made to TryParseDeclarator and MightBeDeclarator, and possibly to
2566 /// isConstructorDeclarator.
2567 ///
2568 /// \verbatim
2569 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2570 /// [C] pointer[opt] direct-declarator
2571 /// [C++] direct-declarator
2572 /// [C++] ptr-operator declarator
2573 ///
2574 /// pointer: [C99 6.7.5]
2575 /// '*' type-qualifier-list[opt]
2576 /// '*' type-qualifier-list[opt] pointer
2577 ///
2578 /// ptr-operator:
2579 /// '*' cv-qualifier-seq[opt]
2580 /// '&'
2581 /// [C++0x] '&&'
2582 /// [GNU] '&' restrict[opt] attributes[opt]
2583 /// [GNU?] '&&' restrict[opt] attributes[opt]
2584 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2585 /// \endverbatim
2586 void ParseDeclaratorInternal(Declarator &D,
2587 DirectDeclParseFunction DirectDeclParser);
2588
2589 enum AttrRequirements {
2590 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2591 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2592 AR_GNUAttributesParsed = 1 << 1,
2593 AR_CXX11AttributesParsed = 1 << 2,
2594 AR_DeclspecAttributesParsed = 1 << 3,
2595 AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed |
2596 AR_DeclspecAttributesParsed,
2597 AR_VendorAttributesParsed =
2598 AR_GNUAttributesParsed | AR_DeclspecAttributesParsed
2599 };
2600
2601 /// ParseTypeQualifierListOpt
2602 /// \verbatim
2603 /// type-qualifier-list: [C99 6.7.5]
2604 /// type-qualifier
2605 /// [vendor] attributes
2606 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
2607 /// type-qualifier-list type-qualifier
2608 /// [vendor] type-qualifier-list attributes
2609 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
2610 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2611 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
2612 /// \endverbatim
2613 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
2614 /// AttrRequirements bitmask values.
2615 void ParseTypeQualifierListOpt(
2616 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2617 bool AtomicOrPtrauthAllowed = true, bool IdentifierRequired = false,
2618 llvm::function_ref<void()> CodeCompletionHandler = {});
2619
2620 /// ParseDirectDeclarator
2621 /// \verbatim
2622 /// direct-declarator: [C99 6.7.5]
2623 /// [C99] identifier
2624 /// '(' declarator ')'
2625 /// [GNU] '(' attributes declarator ')'
2626 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2627 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2628 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2629 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2630 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2631 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
2632 /// attribute-specifier-seq[opt]
2633 /// direct-declarator '(' parameter-type-list ')'
2634 /// direct-declarator '(' identifier-list[opt] ')'
2635 /// [GNU] direct-declarator '(' parameter-forward-declarations
2636 /// parameter-type-list[opt] ')'
2637 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
2638 /// cv-qualifier-seq[opt] exception-specification[opt]
2639 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
2640 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
2641 /// ref-qualifier[opt] exception-specification[opt]
2642 /// [C++] declarator-id
2643 /// [C++11] declarator-id attribute-specifier-seq[opt]
2644 ///
2645 /// declarator-id: [C++ 8]
2646 /// '...'[opt] id-expression
2647 /// '::'[opt] nested-name-specifier[opt] type-name
2648 ///
2649 /// id-expression: [C++ 5.1]
2650 /// unqualified-id
2651 /// qualified-id
2652 ///
2653 /// unqualified-id: [C++ 5.1]
2654 /// identifier
2655 /// operator-function-id
2656 /// conversion-function-id
2657 /// '~' class-name
2658 /// template-id
2659 ///
2660 /// C++17 adds the following, which we also handle here:
2661 ///
2662 /// simple-declaration:
2663 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
2664 /// \endverbatim
2665 ///
2666 /// Note, any additional constructs added here may need corresponding changes
2667 /// in isConstructorDeclarator.
2668 void ParseDirectDeclarator(Declarator &D);
2669 void ParseDecompositionDeclarator(Declarator &D);
2670
2671 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
2672 /// only called before the identifier, so these are most likely just grouping
2673 /// parens for precedence. If we find that these are actually function
2674 /// parameter parens in an abstract-declarator, we call
2675 /// ParseFunctionDeclarator.
2676 ///
2677 /// \verbatim
2678 /// direct-declarator:
2679 /// '(' declarator ')'
2680 /// [GNU] '(' attributes declarator ')'
2681 /// direct-declarator '(' parameter-type-list ')'
2682 /// direct-declarator '(' identifier-list[opt] ')'
2683 /// [GNU] direct-declarator '(' parameter-forward-declarations
2684 /// parameter-type-list[opt] ')'
2685 /// \endverbatim
2686 ///
2687 void ParseParenDeclarator(Declarator &D);
2688
2689 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
2690 /// declarator D up to a paren, which indicates that we are parsing function
2691 /// arguments.
2692 ///
2693 /// If FirstArgAttrs is non-null, then the caller parsed those attributes
2694 /// immediately after the open paren - they will be applied to the DeclSpec
2695 /// of the first parameter.
2696 ///
2697 /// If RequiresArg is true, then the first argument of the function is
2698 /// required to be present and required to not be an identifier list.
2699 ///
2700 /// For C++, after the parameter-list, it also parses the
2701 /// cv-qualifier-seq[opt], (C++11) ref-qualifier[opt],
2702 /// exception-specification[opt], (C++11) attribute-specifier-seq[opt],
2703 /// (C++11) trailing-return-type[opt] and (C++2a) the trailing
2704 /// requires-clause.
2705 ///
2706 /// \verbatim
2707 /// [C++11] exception-specification:
2708 /// dynamic-exception-specification
2709 /// noexcept-specification
2710 /// \endverbatim
2711 ///
2712 void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs,
2713 BalancedDelimiterTracker &Tracker,
2714 bool IsAmbiguous, bool RequiresArg = false);
2715 void InitCXXThisScopeForDeclaratorIfRelevant(
2716 const Declarator &D, const DeclSpec &DS,
2717 std::optional<Sema::CXXThisScopeRAII> &ThisScope);
2718
2719 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
2720 /// true if a ref-qualifier is found.
2721 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2722 SourceLocation &RefQualifierLoc);
2723
2724 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
2725 /// identifier list form for a K&R-style function: void foo(a,b,c)
2726 ///
2727 /// Note that identifier-lists are only allowed for normal declarators, not
2728 /// for abstract-declarators.
2729 bool isFunctionDeclaratorIdentifierList();
2730
2731 /// ParseFunctionDeclaratorIdentifierList - While parsing a function
2732 /// declarator we found a K&R-style identifier list instead of a typed
2733 /// parameter list.
2734 ///
2735 /// After returning, ParamInfo will hold the parsed parameters.
2736 ///
2737 /// \verbatim
2738 /// identifier-list: [C99 6.7.5]
2739 /// identifier
2740 /// identifier-list ',' identifier
2741 /// \endverbatim
2742 ///
2743 void ParseFunctionDeclaratorIdentifierList(
2744 Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2745 void ParseParameterDeclarationClause(
2746 Declarator &D, ParsedAttributes &attrs,
2747 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2748 SourceLocation &EllipsisLoc) {
2749 return ParseParameterDeclarationClause(
2750 D.getContext(), attrs, ParamInfo, EllipsisLoc,
2751 D.getCXXScopeSpec().isSet() &&
2752 D.isFunctionDeclaratorAFunctionDeclaration());
2753 }
2754
2755 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
2756 /// after the opening parenthesis. This function will not parse a K&R-style
2757 /// identifier list.
2758 ///
2759 /// DeclContext is the context of the declarator being parsed. If
2760 /// FirstArgAttrs is non-null, then the caller parsed those attributes
2761 /// immediately after the open paren - they will be applied to the DeclSpec of
2762 /// the first parameter.
2763 ///
2764 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc
2765 /// will be the location of the ellipsis, if any was parsed.
2766 ///
2767 /// \verbatim
2768 /// parameter-type-list: [C99 6.7.5]
2769 /// parameter-list
2770 /// parameter-list ',' '...'
2771 /// [C++] parameter-list '...'
2772 ///
2773 /// parameter-list: [C99 6.7.5]
2774 /// parameter-declaration
2775 /// parameter-list ',' parameter-declaration
2776 ///
2777 /// parameter-declaration: [C99 6.7.5]
2778 /// declaration-specifiers declarator
2779 /// [C++] declaration-specifiers declarator '=' assignment-expression
2780 /// [C++11] initializer-clause
2781 /// [GNU] declaration-specifiers declarator attributes
2782 /// declaration-specifiers abstract-declarator[opt]
2783 /// [C++] declaration-specifiers abstract-declarator[opt]
2784 /// '=' assignment-expression
2785 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
2786 /// [C++11] attribute-specifier-seq parameter-declaration
2787 /// [C++2b] attribute-specifier-seq 'this' parameter-declaration
2788 /// \endverbatim
2789 ///
2790 void ParseParameterDeclarationClause(
2791 DeclaratorContext DeclaratorContext, ParsedAttributes &attrs,
2792 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2793 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration = false);
2794
2795 /// \verbatim
2796 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2797 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2798 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2799 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2800 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2801 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
2802 /// attribute-specifier-seq[opt]
2803 /// \endverbatim
2804 void ParseBracketDeclarator(Declarator &D);
2805
2806 /// Diagnose brackets before an identifier.
2807 void ParseMisplacedBracketDeclarator(Declarator &D);
2808
2809 /// Parse the given string as a type.
2810 ///
2811 /// This is a dangerous utility function currently employed only by API notes.
2812 /// It is not a general entry-point for safely parsing types from strings.
2813 ///
2814 /// \param TypeStr The string to be parsed as a type.
2815 /// \param Context The name of the context in which this string is being
2816 /// parsed, which will be used in diagnostics.
2817 /// \param IncludeLoc The location at which this parse was triggered.
2818 TypeResult ParseTypeFromString(StringRef TypeStr, StringRef Context,
2819 SourceLocation IncludeLoc);
2820
2821 ///@}
2822
2823 //
2824 //
2825 // -------------------------------------------------------------------------
2826 //
2827 //
2828
2829 /// \name C++ Declarations
2830 /// Implementations are in ParseDeclCXX.cpp
2831 ///@{
2832
2833private:
2834 /// Contextual keywords for Microsoft extensions.
2835 mutable IdentifierInfo *Ident_sealed;
2836 mutable IdentifierInfo *Ident_abstract;
2837
2838 /// C++11 contextual keywords.
2839 mutable IdentifierInfo *Ident_final;
2840 mutable IdentifierInfo *Ident_GNU_final;
2841 mutable IdentifierInfo *Ident_override;
2842
2843 /// Representation of a class that has been parsed, including
2844 /// any member function declarations or definitions that need to be
2845 /// parsed after the corresponding top-level class is complete.
2846 struct ParsingClass {
2847 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
2848 : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
2849 TagOrTemplate(TagOrTemplate) {}
2850
2851 /// Whether this is a "top-level" class, meaning that it is
2852 /// not nested within another class.
2853 bool TopLevelClass : 1;
2854
2855 /// Whether this class is an __interface.
2856 bool IsInterface : 1;
2857
2858 /// The class or class template whose definition we are parsing.
2859 Decl *TagOrTemplate;
2860
2861 /// LateParsedDeclarations - Method declarations, inline definitions and
2862 /// nested classes that contain pieces whose parsing will be delayed until
2863 /// the top-level class is fully defined.
2864 LateParsedDeclarationsContainer LateParsedDeclarations;
2865 };
2866
2867 /// The stack of classes that is currently being
2868 /// parsed. Nested and local classes will be pushed onto this stack
2869 /// when they are parsed, and removed afterward.
2870 std::stack<ParsingClass *> ClassStack;
2871
2872 ParsingClass &getCurrentClass() {
2873 assert(!ClassStack.empty() && "No lexed method stacks!");
2874 return *ClassStack.top();
2875 }
2876
2877 /// RAII object used to manage the parsing of a class definition.
2878 class ParsingClassDefinition {
2879 Parser &P;
2880 bool Popped;
2882
2883 public:
2884 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
2885 bool IsInterface)
2886 : P(P), Popped(false),
2887 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
2888 }
2889
2890 /// Pop this class of the stack.
2891 void Pop() {
2892 assert(!Popped && "Nested class has already been popped");
2893 Popped = true;
2894 P.PopParsingClass(State);
2895 }
2896
2897 ~ParsingClassDefinition() {
2898 if (!Popped)
2899 P.PopParsingClass(State);
2900 }
2901 };
2902
2903 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
2904 ///
2905 /// \verbatim
2906 /// exception-specification:
2907 /// dynamic-exception-specification
2908 /// noexcept-specification
2909 ///
2910 /// noexcept-specification:
2911 /// 'noexcept'
2912 /// 'noexcept' '(' constant-expression ')'
2913 /// \endverbatim
2914 ExceptionSpecificationType tryParseExceptionSpecification(
2915 bool Delayed, SourceRange &SpecificationRange,
2916 SmallVectorImpl<ParsedType> &DynamicExceptions,
2917 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2918 ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens);
2919
2920 /// ParseDynamicExceptionSpecification - Parse a C++
2921 /// dynamic-exception-specification (C++ [except.spec]).
2922 /// EndLoc is filled with the location of the last token of the specification.
2923 ///
2924 /// \verbatim
2925 /// dynamic-exception-specification:
2926 /// 'throw' '(' type-id-list [opt] ')'
2927 /// [MS] 'throw' '(' '...' ')'
2928 ///
2929 /// type-id-list:
2930 /// type-id ... [opt]
2931 /// type-id-list ',' type-id ... [opt]
2932 /// \endverbatim
2933 ///
2935 ParseDynamicExceptionSpecification(SourceRange &SpecificationRange,
2936 SmallVectorImpl<ParsedType> &Exceptions,
2937 SmallVectorImpl<SourceRange> &Ranges);
2938
2939 //===--------------------------------------------------------------------===//
2940 // C++0x 8: Function declaration trailing-return-type
2941
2942 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2943 /// function declaration.
2944 TypeResult ParseTrailingReturnType(SourceRange &Range,
2945 bool MayBeFollowedByDirectInit);
2946
2947 /// Parse a requires-clause as part of a function declaration.
2948 void ParseTrailingRequiresClause(Declarator &D);
2949
2950 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
2951 ParsedAttributes &AccessAttrs,
2952 AccessSpecifier &CurAS);
2953
2954 SourceLocation ParsePackIndexingType(DeclSpec &DS);
2955 void AnnotateExistingIndexedTypeNamePack(ParsedType T,
2956 SourceLocation StartLoc,
2957 SourceLocation EndLoc);
2958
2959 /// Return true if the next token should be treated as a [[]] attribute,
2960 /// or as a keyword that behaves like one. The former is only true if
2961 /// [[]] attributes are enabled, whereas the latter is true whenever
2962 /// such a keyword appears. The arguments are as for
2963 /// isCXX11AttributeSpecifier.
2964 bool isAllowedCXX11AttributeSpecifier(bool Disambiguate = false,
2965 bool OuterMightBeMessageSend = false) {
2966 return (Tok.isRegularKeywordAttribute() ||
2967 isCXX11AttributeSpecifier(Disambiguate, OuterMightBeMessageSend) !=
2969 }
2970
2971 /// Skip C++11 and C23 attributes and return the end location of the
2972 /// last one.
2973 /// \returns SourceLocation() if there are no attributes.
2974 SourceLocation SkipCXX11Attributes();
2975
2976 /// Diagnose and skip C++11 and C23 attributes that appear in syntactic
2977 /// locations where attributes are not allowed.
2978 void DiagnoseAndSkipCXX11Attributes();
2979
2980 void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
2981 CachedTokens &OpenMPTokens);
2982
2983 /// Parse a C++11 or C23 attribute-specifier.
2984 ///
2985 /// \verbatim
2986 /// [C++11] attribute-specifier:
2987 /// '[' '[' attribute-list ']' ']'
2988 /// alignment-specifier
2989 ///
2990 /// [C++11] attribute-list:
2991 /// attribute[opt]
2992 /// attribute-list ',' attribute[opt]
2993 /// attribute '...'
2994 /// attribute-list ',' attribute '...'
2995 ///
2996 /// [C++11] attribute:
2997 /// attribute-token attribute-argument-clause[opt]
2998 ///
2999 /// [C++11] attribute-token:
3000 /// identifier
3001 /// attribute-scoped-token
3002 ///
3003 /// [C++11] attribute-scoped-token:
3004 /// attribute-namespace '::' identifier
3005 ///
3006 /// [C++11] attribute-namespace:
3007 /// identifier
3008 /// \endverbatim
3009 void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
3010 CachedTokens &OpenMPTokens,
3011 SourceLocation *EndLoc = nullptr);
3012 void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs,
3013 SourceLocation *EndLoc = nullptr) {
3014 CachedTokens OpenMPTokens;
3015 ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc);
3016 ReplayOpenMPAttributeTokens(OpenMPTokens);
3017 }
3018
3019 /// ParseCXX11Attributes - Parse a C++11 or C23 attribute-specifier-seq.
3020 ///
3021 /// \verbatim
3022 /// attribute-specifier-seq:
3023 /// attribute-specifier-seq[opt] attribute-specifier
3024 /// \endverbatim
3025 void ParseCXX11Attributes(ParsedAttributes &attrs);
3026
3027 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3028 /// Parses a C++11 (or C23)-style attribute argument list. Returns true
3029 /// if this results in adding an attribute to the ParsedAttributes list.
3030 ///
3031 /// \verbatim
3032 /// [C++11] attribute-argument-clause:
3033 /// '(' balanced-token-seq ')'
3034 ///
3035 /// [C++11] balanced-token-seq:
3036 /// balanced-token
3037 /// balanced-token-seq balanced-token
3038 ///
3039 /// [C++11] balanced-token:
3040 /// '(' balanced-token-seq ')'
3041 /// '[' balanced-token-seq ']'
3042 /// '{' balanced-token-seq '}'
3043 /// any token but '(', ')', '[', ']', '{', or '}'
3044 /// \endverbatim
3045 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3046 SourceLocation AttrNameLoc,
3047 ParsedAttributes &Attrs, SourceLocation *EndLoc,
3048 IdentifierInfo *ScopeName,
3049 SourceLocation ScopeLoc,
3050 CachedTokens &OpenMPTokens);
3051
3052 /// Parse the argument to C++23's [[assume()]] attribute. Returns true on
3053 /// error.
3054 bool
3055 ParseCXXAssumeAttributeArg(ParsedAttributes &Attrs, IdentifierInfo *AttrName,
3056 SourceLocation AttrNameLoc,
3057 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
3058 SourceLocation *EndLoc, ParsedAttr::Form Form);
3059
3060 /// Try to parse an 'identifier' which appears within an attribute-token.
3061 ///
3062 /// \return the parsed identifier on success, and 0 if the next token is not
3063 /// an attribute-token.
3064 ///
3065 /// C++11 [dcl.attr.grammar]p3:
3066 /// If a keyword or an alternative token that satisfies the syntactic
3067 /// requirements of an identifier is contained in an attribute-token,
3068 /// it is considered an identifier.
3069 IdentifierInfo *TryParseCXX11AttributeIdentifier(
3070 SourceLocation &Loc,
3073 const IdentifierInfo *EnclosingScope = nullptr);
3074
3075 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
3076 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
3077
3078 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
3079 ///
3080 /// \verbatim
3081 /// [MS] ms-attribute:
3082 /// '[' token-seq ']'
3083 ///
3084 /// [MS] ms-attribute-seq:
3085 /// ms-attribute[opt]
3086 /// ms-attribute ms-attribute-seq
3087 /// \endverbatim
3088 void ParseMicrosoftAttributes(ParsedAttributes &Attrs);
3089
3090 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
3091 void ParseNullabilityClassAttributes(ParsedAttributes &attrs);
3092
3093 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
3094 ///
3095 /// \verbatim
3096 /// 'decltype' ( expression )
3097 /// 'decltype' ( 'auto' ) [C++1y]
3098 /// \endverbatim
3099 ///
3100 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
3101 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
3102 SourceLocation StartLoc,
3103 SourceLocation EndLoc);
3104
3105 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
3106 /// virt-specifier.
3107 ///
3108 /// \verbatim
3109 /// virt-specifier:
3110 /// override
3111 /// final
3112 /// __final
3113 /// \endverbatim
3114 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
3115 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
3116 return isCXX11VirtSpecifier(Tok);
3117 }
3118
3119 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
3120 ///
3121 /// \verbatim
3122 /// virt-specifier-seq:
3123 /// virt-specifier
3124 /// virt-specifier-seq virt-specifier
3125 /// \endverbatim
3126 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
3127 SourceLocation FriendLoc);
3128
3129 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
3130 /// 'final' or Microsoft 'sealed' contextual keyword.
3131 bool isCXX11FinalKeyword() const;
3132
3133 /// isClassCompatibleKeyword - Determine whether the next token is a C++11
3134 /// 'final', a C++26 'trivially_relocatable_if_eligible',
3135 /// or Microsoft 'sealed' or 'abstract' contextual
3136 /// keyword.
3137 bool isClassCompatibleKeyword() const;
3138
3139 bool MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS);
3140 DeclSpec::TST TypeTransformTokToDeclSpec();
3141
3142 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3143
3144 /// ParseNamespace - We know that the current token is a namespace keyword.
3145 /// This may either be a top level namespace or a block-level namespace alias.
3146 /// If there was an inline keyword, it has already been parsed.
3147 ///
3148 /// \verbatim
3149 /// namespace-definition: [C++: namespace.def]
3150 /// named-namespace-definition
3151 /// unnamed-namespace-definition
3152 /// nested-namespace-definition
3153 ///
3154 /// named-namespace-definition:
3155 /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
3156 /// namespace-body '}'
3157 ///
3158 /// unnamed-namespace-definition:
3159 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
3160 ///
3161 /// nested-namespace-definition:
3162 /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
3163 /// identifier '{' namespace-body '}'
3164 ///
3165 /// enclosing-namespace-specifier:
3166 /// identifier
3167 /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
3168 ///
3169 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
3170 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
3171 /// \endverbatim
3172 ///
3173 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3174 SourceLocation &DeclEnd,
3175 SourceLocation InlineLoc = SourceLocation());
3176
3177 struct InnerNamespaceInfo {
3178 SourceLocation NamespaceLoc;
3179 SourceLocation InlineLoc;
3180 SourceLocation IdentLoc;
3181 IdentifierInfo *Ident;
3182 };
3183 using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3184
3185 /// ParseInnerNamespace - Parse the contents of a namespace.
3186 void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3187 unsigned int index, SourceLocation &InlineLoc,
3188 ParsedAttributes &attrs,
3189 BalancedDelimiterTracker &Tracker);
3190
3191 /// ParseLinkage - We know that the current token is a string_literal
3192 /// and just before that, that extern was seen.
3193 ///
3194 /// \verbatim
3195 /// linkage-specification: [C++ 7.5p2: dcl.link]
3196 /// 'extern' string-literal '{' declaration-seq[opt] '}'
3197 /// 'extern' string-literal declaration
3198 /// \endverbatim
3199 ///
3200 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3201
3202 /// Parse a standard C++ Modules export-declaration.
3203 ///
3204 /// \verbatim
3205 /// export-declaration:
3206 /// 'export' declaration
3207 /// 'export' '{' declaration-seq[opt] '}'
3208 /// \endverbatim
3209 ///
3210 /// HLSL: Parse export function declaration.
3211 ///
3212 /// \verbatim
3213 /// export-function-declaration:
3214 /// 'export' function-declaration
3215 ///
3216 /// export-declaration-group:
3217 /// 'export' '{' function-declaration-seq[opt] '}'
3218 /// \endverbatim
3219 ///
3220 Decl *ParseExportDeclaration();
3221
3222 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
3223 /// using-directive. Assumes that current token is 'using'.
3224 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3225 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3226 SourceLocation &DeclEnd, ParsedAttributes &Attrs);
3227
3228 /// ParseUsingDirective - Parse C++ using-directive, assumes
3229 /// that current token is 'namespace' and 'using' was already parsed.
3230 ///
3231 /// \verbatim
3232 /// using-directive: [C++ 7.3.p4: namespace.udir]
3233 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
3234 /// namespace-name ;
3235 /// [GNU] using-directive:
3236 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
3237 /// namespace-name attributes[opt] ;
3238 /// \endverbatim
3239 ///
3240 Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc,
3241 SourceLocation &DeclEnd, ParsedAttributes &attrs);
3242
3243 struct UsingDeclarator {
3244 SourceLocation TypenameLoc;
3245 CXXScopeSpec SS;
3246 UnqualifiedId Name;
3247 SourceLocation EllipsisLoc;
3248
3249 void clear() {
3250 TypenameLoc = EllipsisLoc = SourceLocation();
3251 SS.clear();
3252 Name.clear();
3253 }
3254 };
3255
3256 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
3257 ///
3258 /// \verbatim
3259 /// using-declarator:
3260 /// 'typename'[opt] nested-name-specifier unqualified-id
3261 /// \endverbatim
3262 ///
3263 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3264
3265 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
3266 /// Assumes that 'using' was already seen.
3267 ///
3268 /// \verbatim
3269 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
3270 /// 'using' using-declarator-list[opt] ;
3271 ///
3272 /// using-declarator-list: [C++1z]
3273 /// using-declarator '...'[opt]
3274 /// using-declarator-list ',' using-declarator '...'[opt]
3275 ///
3276 /// using-declarator-list: [C++98-14]
3277 /// using-declarator
3278 ///
3279 /// alias-declaration: C++11 [dcl.dcl]p1
3280 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
3281 ///
3282 /// using-enum-declaration: [C++20, dcl.enum]
3283 /// 'using' elaborated-enum-specifier ;
3284 /// The terminal name of the elaborated-enum-specifier undergoes
3285 /// type-only lookup
3286 ///
3287 /// elaborated-enum-specifier:
3288 /// 'enum' nested-name-specifier[opt] identifier
3289 /// \endverbatim
3290 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3291 const ParsedTemplateInfo &TemplateInfo,
3292 SourceLocation UsingLoc,
3293 SourceLocation &DeclEnd,
3294 ParsedAttributes &Attrs,
3296 Decl *ParseAliasDeclarationAfterDeclarator(
3297 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3298 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3299 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3300
3301 /// ParseStaticAssertDeclaration - Parse C++0x or C11
3302 /// static_assert-declaration.
3303 ///
3304 /// \verbatim
3305 /// [C++0x] static_assert-declaration:
3306 /// static_assert ( constant-expression , string-literal ) ;
3307 ///
3308 /// [C11] static_assert-declaration:
3309 /// _Static_assert ( constant-expression , string-literal ) ;
3310 /// \endverbatim
3311 ///
3312 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3313
3314 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
3315 /// alias definition.
3316 ///
3317 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3318 SourceLocation AliasLoc, IdentifierInfo *Alias,
3319 SourceLocation &DeclEnd);
3320
3321 //===--------------------------------------------------------------------===//
3322 // C++ 9: classes [class] and C structs/unions.
3323
3324 /// Determine whether the following tokens are valid after a type-specifier
3325 /// which could be a standalone declaration. This will conservatively return
3326 /// true if there's any doubt, and is appropriate for insert-';' fixits.
3327 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3328
3329 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
3330 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
3331 /// until we reach the start of a definition or see a token that
3332 /// cannot start a definition.
3333 ///
3334 /// \verbatim
3335 /// class-specifier: [C++ class]
3336 /// class-head '{' member-specification[opt] '}'
3337 /// class-head '{' member-specification[opt] '}' attributes[opt]
3338 /// class-head:
3339 /// class-key identifier[opt] base-clause[opt]
3340 /// class-key nested-name-specifier identifier base-clause[opt]
3341 /// class-key nested-name-specifier[opt] simple-template-id
3342 /// base-clause[opt]
3343 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
3344 /// [GNU] class-key attributes[opt] nested-name-specifier
3345 /// identifier base-clause[opt]
3346 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
3347 /// simple-template-id base-clause[opt]
3348 /// class-key:
3349 /// 'class'
3350 /// 'struct'
3351 /// 'union'
3352 ///
3353 /// elaborated-type-specifier: [C++ dcl.type.elab]
3354 /// class-key ::[opt] nested-name-specifier[opt] identifier
3355 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
3356 /// simple-template-id
3357 ///
3358 /// Note that the C++ class-specifier and elaborated-type-specifier,
3359 /// together, subsume the C99 struct-or-union-specifier:
3360 ///
3361 /// struct-or-union-specifier: [C99 6.7.2.1]
3362 /// struct-or-union identifier[opt] '{' struct-contents '}'
3363 /// struct-or-union identifier
3364 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
3365 /// '}' attributes[opt]
3366 /// [GNU] struct-or-union attributes[opt] identifier
3367 /// struct-or-union:
3368 /// 'struct'
3369 /// 'union'
3370 /// \endverbatim
3371 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3372 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
3373 AccessSpecifier AS, bool EnteringContext,
3374 DeclSpecContext DSC, ParsedAttributes &Attributes);
3375 void SkipCXXMemberSpecification(SourceLocation StartLoc,
3376 SourceLocation AttrFixitLoc, unsigned TagType,
3377 Decl *TagDecl);
3378
3379 /// ParseCXXMemberSpecification - Parse the class definition.
3380 ///
3381 /// \verbatim
3382 /// member-specification:
3383 /// member-declaration member-specification[opt]
3384 /// access-specifier ':' member-specification[opt]
3385 /// \endverbatim
3386 ///
3387 void ParseCXXMemberSpecification(SourceLocation StartLoc,
3388 SourceLocation AttrFixitLoc,
3389 ParsedAttributes &Attrs, unsigned TagType,
3390 Decl *TagDecl);
3391
3392 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
3393 /// Also detect and reject any attempted defaulted/deleted function
3394 /// definition. The location of the '=', if any, will be placed in EqualLoc.
3395 ///
3396 /// This does not check for a pure-specifier; that's handled elsewhere.
3397 ///
3398 /// \verbatim
3399 /// brace-or-equal-initializer:
3400 /// '=' initializer-expression
3401 /// braced-init-list
3402 ///
3403 /// initializer-clause:
3404 /// assignment-expression
3405 /// braced-init-list
3406 ///
3407 /// defaulted/deleted function-definition:
3408 /// '=' 'default'
3409 /// '=' 'delete'
3410 /// \endverbatim
3411 ///
3412 /// Prior to C++0x, the assignment-expression in an initializer-clause must
3413 /// be a constant-expression.
3414 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3415 SourceLocation &EqualLoc);
3416
3417 /// Parse a C++ member-declarator up to, but not including, the optional
3418 /// brace-or-equal-initializer or pure-specifier.
3419 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3420 VirtSpecifiers &VS,
3421 ExprResult &BitfieldSize,
3422 LateParsedAttrList &LateAttrs);
3423
3424 /// Look for declaration specifiers possibly occurring after C++11
3425 /// virt-specifier-seq and diagnose them.
3426 void
3427 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3428 VirtSpecifiers &VS);
3429
3430 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
3431 ///
3432 /// \verbatim
3433 /// member-declaration:
3434 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
3435 /// function-definition ';'[opt]
3436 /// [C++26] friend-type-declaration
3437 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
3438 /// using-declaration [TODO]
3439 /// [C++0x] static_assert-declaration
3440 /// template-declaration
3441 /// [GNU] '__extension__' member-declaration
3442 ///
3443 /// member-declarator-list:
3444 /// member-declarator
3445 /// member-declarator-list ',' member-declarator
3446 ///
3447 /// member-declarator:
3448 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
3449 /// [C++2a] declarator requires-clause
3450 /// declarator constant-initializer[opt]
3451 /// [C++11] declarator brace-or-equal-initializer[opt]
3452 /// identifier[opt] ':' constant-expression
3453 ///
3454 /// virt-specifier-seq:
3455 /// virt-specifier
3456 /// virt-specifier-seq virt-specifier
3457 ///
3458 /// virt-specifier:
3459 /// override
3460 /// final
3461 /// [MS] sealed
3462 ///
3463 /// pure-specifier:
3464 /// '= 0'
3465 ///
3466 /// constant-initializer:
3467 /// '=' constant-expression
3468 ///
3469 /// friend-type-declaration:
3470 /// 'friend' friend-type-specifier-list ;
3471 ///
3472 /// friend-type-specifier-list:
3473 /// friend-type-specifier ...[opt]
3474 /// friend-type-specifier-list , friend-type-specifier ...[opt]
3475 ///
3476 /// friend-type-specifier:
3477 /// simple-type-specifier
3478 /// elaborated-type-specifier
3479 /// typename-specifier
3480 /// \endverbatim
3481 ///
3482 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3483 AccessSpecifier AS, ParsedAttributes &Attr,
3484 ParsedTemplateInfo &TemplateInfo,
3485 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3487 ParseCXXClassMemberDeclarationWithPragmas(AccessSpecifier &AS,
3488 ParsedAttributes &AccessAttrs,
3489 DeclSpec::TST TagType, Decl *Tag);
3490
3491 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3492 /// which explicitly initializes the members or base classes of a
3493 /// class (C++ [class.base.init]). For example, the three initializers
3494 /// after the ':' in the Derived constructor below:
3495 ///
3496 /// @code
3497 /// class Base { };
3498 /// class Derived : Base {
3499 /// int x;
3500 /// float f;
3501 /// public:
3502 /// Derived(float f) : Base(), x(17), f(f) { }
3503 /// };
3504 /// @endcode
3505 ///
3506 /// \verbatim
3507 /// [C++] ctor-initializer:
3508 /// ':' mem-initializer-list
3509 ///
3510 /// [C++] mem-initializer-list:
3511 /// mem-initializer ...[opt]
3512 /// mem-initializer ...[opt] , mem-initializer-list
3513 /// \endverbatim
3514 void ParseConstructorInitializer(Decl *ConstructorDecl);
3515
3516 /// ParseMemInitializer - Parse a C++ member initializer, which is
3517 /// part of a constructor initializer that explicitly initializes one
3518 /// member or base class (C++ [class.base.init]). See
3519 /// ParseConstructorInitializer for an example.
3520 ///
3521 /// \verbatim
3522 /// [C++] mem-initializer:
3523 /// mem-initializer-id '(' expression-list[opt] ')'
3524 /// [C++0x] mem-initializer-id braced-init-list
3525 ///
3526 /// [C++] mem-initializer-id:
3527 /// '::'[opt] nested-name-specifier[opt] class-name
3528 /// identifier
3529 /// \endverbatim
3530 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3531
3532 /// If the given declarator has any parts for which parsing has to be
3533 /// delayed, e.g., default arguments or an exception-specification, create a
3534 /// late-parsed method declaration record to handle the parsing at the end of
3535 /// the class definition.
3536 void HandleMemberFunctionDeclDelays(Declarator &DeclaratorInfo,
3537 Decl *ThisDecl);
3538
3539 //===--------------------------------------------------------------------===//
3540 // C++ 10: Derived classes [class.derived]
3541
3542 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
3543 /// class name or decltype-specifier. Note that we only check that the result
3544 /// names a type; semantic analysis will need to verify that the type names a
3545 /// class. The result is either a type or null, depending on whether a type
3546 /// name was found.
3547 ///
3548 /// \verbatim
3549 /// base-type-specifier: [C++11 class.derived]
3550 /// class-or-decltype
3551 /// class-or-decltype: [C++11 class.derived]
3552 /// nested-name-specifier[opt] class-name
3553 /// decltype-specifier
3554 /// class-name: [C++ class.name]
3555 /// identifier
3556 /// simple-template-id
3557 /// \endverbatim
3558 ///
3559 /// In C++98, instead of base-type-specifier, we have:
3560 ///
3561 /// \verbatim
3562 /// ::[opt] nested-name-specifier[opt] class-name
3563 /// \endverbatim
3564 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3565 SourceLocation &EndLocation);
3566
3567 /// ParseBaseClause - Parse the base-clause of a C++ class [C++
3568 /// class.derived].
3569 ///
3570 /// \verbatim
3571 /// base-clause : [C++ class.derived]
3572 /// ':' base-specifier-list
3573 /// base-specifier-list:
3574 /// base-specifier '...'[opt]
3575 /// base-specifier-list ',' base-specifier '...'[opt]
3576 /// \endverbatim
3577 void ParseBaseClause(Decl *ClassDecl);
3578
3579 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
3580 /// one entry in the base class list of a class specifier, for example:
3581 /// class foo : public bar, virtual private baz {
3582 /// 'public bar' and 'virtual private baz' are each base-specifiers.
3583 ///
3584 /// \verbatim
3585 /// base-specifier: [C++ class.derived]
3586 /// attribute-specifier-seq[opt] base-type-specifier
3587 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
3588 /// base-type-specifier
3589 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
3590 /// base-type-specifier
3591 /// \endverbatim
3592 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3593
3594 /// getAccessSpecifierIfPresent - Determine whether the next token is
3595 /// a C++ access-specifier.
3596 ///
3597 /// \verbatim
3598 /// access-specifier: [C++ class.derived]
3599 /// 'private'
3600 /// 'protected'
3601 /// 'public'
3602 /// \endverbatim
3603 AccessSpecifier getAccessSpecifierIfPresent() const;
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> ExportHandler;
7045 std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
7046
7047 /// Initialize all pragma handlers.
7048 void initializePragmaHandlers();
7049
7050 /// Destroy and reset all pragma handlers.
7051 void resetPragmaHandlers();
7052
7053 /// Handle the annotation token produced for #pragma unused(...)
7054 ///
7055 /// Each annot_pragma_unused is followed by the argument token so e.g.
7056 /// "#pragma unused(x,y)" becomes:
7057 /// annot_pragma_unused 'x' annot_pragma_unused 'y'
7058 void HandlePragmaUnused();
7059
7060 /// Handle the annotation token produced for
7061 /// #pragma GCC visibility...
7062 void HandlePragmaVisibility();
7063
7064 /// Handle the annotation token produced for
7065 /// #pragma pack...
7066 void HandlePragmaPack();
7067
7068 /// Handle the annotation token produced for
7069 /// #pragma ms_struct...
7070 void HandlePragmaMSStruct();
7071
7072 void HandlePragmaMSPointersToMembers();
7073
7074 void HandlePragmaMSVtorDisp();
7075
7076 void HandlePragmaMSPragma();
7077 bool HandlePragmaMSSection(StringRef PragmaName,
7078 SourceLocation PragmaLocation);
7079 bool HandlePragmaMSSegment(StringRef PragmaName,
7080 SourceLocation PragmaLocation);
7081
7082 // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
7083 bool HandlePragmaMSInitSeg(StringRef PragmaName,
7084 SourceLocation PragmaLocation);
7085
7086 // #pragma strict_gs_check(pop)
7087 // #pragma strict_gs_check(push, "on" | "off")
7088 // #pragma strict_gs_check("on" | "off")
7089 bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName,
7090 SourceLocation PragmaLocation);
7091 bool HandlePragmaMSFunction(StringRef PragmaName,
7092 SourceLocation PragmaLocation);
7093 bool HandlePragmaMSAllocText(StringRef PragmaName,
7094 SourceLocation PragmaLocation);
7095
7096 // #pragma optimize("gsty", on|off)
7097 bool HandlePragmaMSOptimize(StringRef PragmaName,
7098 SourceLocation PragmaLocation);
7099
7100 // #pragma intrinsic("foo")
7101 bool HandlePragmaMSIntrinsic(StringRef PragmaName,
7102 SourceLocation PragmaLocation);
7103
7104 /// Handle the annotation token produced for
7105 /// #pragma align...
7106 void HandlePragmaAlign();
7107
7108 /// Handle the annotation token produced for
7109 /// #pragma clang __debug dump...
7110 void HandlePragmaDump();
7111
7112 /// Handle the annotation token produced for
7113 /// #pragma weak id...
7114 void HandlePragmaWeak();
7115
7116 /// Handle the annotation token produced for
7117 /// #pragma weak id = id...
7118 void HandlePragmaWeakAlias();
7119
7120 /// Handle the annotation token produced for
7121 /// #pragma redefine_extname...
7122 void HandlePragmaRedefineExtname();
7123
7124 /// Handle the annotation token produced for
7125 /// #pragma STDC FP_CONTRACT...
7126 void HandlePragmaFPContract();
7127
7128 /// Handle the annotation token produced for
7129 /// #pragma STDC FENV_ACCESS...
7130 void HandlePragmaFEnvAccess();
7131
7132 /// Handle the annotation token produced for
7133 /// #pragma STDC FENV_ROUND...
7134 void HandlePragmaFEnvRound();
7135
7136 /// Handle the annotation token produced for
7137 /// #pragma STDC CX_LIMITED_RANGE...
7138 void HandlePragmaCXLimitedRange();
7139
7140 /// Handle the annotation token produced for
7141 /// #pragma float_control
7142 void HandlePragmaFloatControl();
7143
7144 /// \brief Handle the annotation token produced for
7145 /// #pragma clang fp ...
7146 void HandlePragmaFP();
7147
7148 /// Handle the annotation token produced for
7149 /// #pragma OPENCL EXTENSION...
7150 void HandlePragmaOpenCLExtension();
7151
7152 /// Handle the annotation token produced for
7153 /// #pragma clang __debug captured
7154 StmtResult HandlePragmaCaptured();
7155
7156 /// Handle the annotation token produced for
7157 /// #pragma clang loop and #pragma unroll.
7158 bool HandlePragmaLoopHint(LoopHint &Hint);
7159
7160 bool ParsePragmaAttributeSubjectMatchRuleSet(
7161 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
7162 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
7163
7164 void HandlePragmaAttribute();
7165
7166 void zOSHandlePragmaHelper(tok::TokenKind);
7167
7168 /// Handle the annotation token produced for
7169 /// #pragma export ...
7170 void HandlePragmaExport();
7171
7172 ///@}
7173
7174 //
7175 //
7176 // -------------------------------------------------------------------------
7177 //
7178 //
7179
7180 /// \name Statements
7181 /// Implementations are in ParseStmt.cpp
7182 ///@{
7183
7184public:
7185 /// A SmallVector of statements.
7187
7188 /// The location of the first statement inside an else that might
7189 /// have a missleading indentation. If there is no
7190 /// MisleadingIndentationChecker on an else active, this location is invalid.
7192
7193 private:
7194
7195 /// Flags describing a context in which we're parsing a statement.
7196 enum class ParsedStmtContext {
7197 /// This context permits declarations in language modes where declarations
7198 /// are not statements.
7199 AllowDeclarationsInC = 0x1,
7200 /// This context permits standalone OpenMP directives.
7201 AllowStandaloneOpenMPDirectives = 0x2,
7202 /// This context is at the top level of a GNU statement expression.
7203 InStmtExpr = 0x4,
7204
7205 /// The context of a regular substatement.
7206 SubStmt = 0,
7207 /// The context of a compound-statement.
7208 Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
7209
7210 LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
7211 };
7212
7213 /// Act on an expression statement that might be the last statement in a
7214 /// GNU statement expression. Checks whether we are actually at the end of
7215 /// a statement expression and builds a suitable expression statement.
7216 StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
7217
7218 //===--------------------------------------------------------------------===//
7219 // C99 6.8: Statements and Blocks.
7220
7221 /// Parse a standalone statement (for instance, as the body of an 'if',
7222 /// 'while', or 'for').
7224 ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
7225 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt,
7226 LabelDecl *PrecedingLabel = nullptr);
7227
7228 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
7229 /// \verbatim
7230 /// StatementOrDeclaration:
7231 /// statement
7232 /// declaration
7233 ///
7234 /// statement:
7235 /// labeled-statement
7236 /// compound-statement
7237 /// expression-statement
7238 /// selection-statement
7239 /// iteration-statement
7240 /// jump-statement
7241 /// [C++] declaration-statement
7242 /// [C++] try-block
7243 /// [MS] seh-try-block
7244 /// [OBC] objc-throw-statement
7245 /// [OBC] objc-try-catch-statement
7246 /// [OBC] objc-synchronized-statement
7247 /// [GNU] asm-statement
7248 /// [OMP] openmp-construct [TODO]
7249 ///
7250 /// labeled-statement:
7251 /// identifier ':' statement
7252 /// 'case' constant-expression ':' statement
7253 /// 'default' ':' statement
7254 ///
7255 /// selection-statement:
7256 /// if-statement
7257 /// switch-statement
7258 ///
7259 /// iteration-statement:
7260 /// while-statement
7261 /// do-statement
7262 /// for-statement
7263 ///
7264 /// expression-statement:
7265 /// expression[opt] ';'
7266 ///
7267 /// jump-statement:
7268 /// 'goto' identifier ';'
7269 /// 'continue' ';'
7270 /// 'break' ';'
7271 /// 'return' expression[opt] ';'
7272 /// [GNU] 'goto' '*' expression ';'
7273 ///
7274 /// [OBC] objc-throw-statement:
7275 /// [OBC] '@' 'throw' expression ';'
7276 /// [OBC] '@' 'throw' ';'
7277 /// \endverbatim
7278 ///
7280 ParseStatementOrDeclaration(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7281 SourceLocation *TrailingElseLoc = nullptr,
7282 LabelDecl *PrecedingLabel = nullptr);
7283
7284 StmtResult ParseStatementOrDeclarationAfterAttributes(
7285 StmtVector &Stmts, ParsedStmtContext StmtCtx,
7286 SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs,
7287 ParsedAttributes &DeclSpecAttrs, LabelDecl *PrecedingLabel);
7288
7289 /// Parse an expression statement.
7290 StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
7291
7292 /// ParseLabeledStatement - We have an identifier and a ':' after it.
7293 ///
7294 /// \verbatim
7295 /// label:
7296 /// identifier ':'
7297 /// [GNU] identifier ':' attributes[opt]
7298 ///
7299 /// labeled-statement:
7300 /// label statement
7301 /// \endverbatim
7302 ///
7303 StmtResult ParseLabeledStatement(ParsedAttributes &Attrs,
7304 ParsedStmtContext StmtCtx);
7305
7306 /// ParseCaseStatement
7307 /// \verbatim
7308 /// labeled-statement:
7309 /// 'case' constant-expression ':' statement
7310 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
7311 /// \endverbatim
7312 ///
7313 StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
7314 bool MissingCase = false,
7316
7317 /// ParseDefaultStatement
7318 /// \verbatim
7319 /// labeled-statement:
7320 /// 'default' ':' statement
7321 /// \endverbatim
7322 /// Note that this does not parse the 'statement' at the end.
7323 ///
7324 StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
7325
7326 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
7327
7328 /// ParseCompoundStatement - Parse a "{}" block.
7329 ///
7330 /// \verbatim
7331 /// compound-statement: [C99 6.8.2]
7332 /// { block-item-list[opt] }
7333 /// [GNU] { label-declarations block-item-list } [TODO]
7334 ///
7335 /// block-item-list:
7336 /// block-item
7337 /// block-item-list block-item
7338 ///
7339 /// block-item:
7340 /// declaration
7341 /// [GNU] '__extension__' declaration
7342 /// statement
7343 ///
7344 /// [GNU] label-declarations:
7345 /// [GNU] label-declaration
7346 /// [GNU] label-declarations label-declaration
7347 ///
7348 /// [GNU] label-declaration:
7349 /// [GNU] '__label__' identifier-list ';'
7350 /// \endverbatim
7351 ///
7352 StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags);
7353
7354 /// Parse any pragmas at the start of the compound expression. We handle these
7355 /// separately since some pragmas (FP_CONTRACT) must appear before any C
7356 /// statement in the compound, but may be intermingled with other pragmas.
7357 void ParseCompoundStatementLeadingPragmas();
7358
7359 void DiagnoseLabelAtEndOfCompoundStatement();
7360
7361 /// Consume any extra semi-colons resulting in null statements,
7362 /// returning true if any tok::semi were consumed.
7363 bool ConsumeNullStmt(StmtVector &Stmts);
7364
7365 /// ParseCompoundStatementBody - Parse a sequence of statements optionally
7366 /// followed by a label and invoke the ActOnCompoundStmt action. This expects
7367 /// the '{' to be the current token, and consume the '}' at the end of the
7368 /// block. It does not manipulate the scope stack.
7369 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
7370
7371 /// ParseParenExprOrCondition:
7372 /// \verbatim
7373 /// [C ] '(' expression ')'
7374 /// [C++] '(' condition ')'
7375 /// [C++1z] '(' init-statement[opt] condition ')'
7376 /// \endverbatim
7377 ///
7378 /// This function parses and performs error recovery on the specified
7379 /// condition or expression (depending on whether we're in C++ or C mode).
7380 /// This function goes out of its way to recover well. It returns true if
7381 /// there was a parser error (the right paren couldn't be found), which
7382 /// indicates that the caller should try to recover harder. It returns false
7383 /// if the condition is successfully parsed. Note that a successful parse can
7384 /// still have semantic errors in the condition. Additionally, it will assign
7385 /// the location of the outer-most '(' and ')', to LParenLoc and RParenLoc,
7386 /// respectively.
7387 bool ParseParenExprOrCondition(StmtResult *InitStmt,
7388 Sema::ConditionResult &CondResult,
7390 SourceLocation &LParenLoc,
7391 SourceLocation &RParenLoc);
7392
7393 /// ParseIfStatement
7394 /// \verbatim
7395 /// if-statement: [C99 6.8.4.1]
7396 /// 'if' '(' expression ')' statement
7397 /// 'if' '(' expression ')' statement 'else' statement
7398 /// [C++] 'if' '(' condition ')' statement
7399 /// [C++] 'if' '(' condition ')' statement 'else' statement
7400 /// [C++23] 'if' '!' [opt] consteval compound-statement
7401 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
7402 /// \endverbatim
7403 ///
7404 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
7405
7406 /// ParseSwitchStatement
7407 /// \verbatim
7408 /// switch-statement:
7409 /// 'switch' '(' expression ')' statement
7410 /// [C++] 'switch' '(' condition ')' statement
7411 /// \endverbatim
7412 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc,
7413 LabelDecl *PrecedingLabel);
7414
7415 /// ParseWhileStatement
7416 /// \verbatim
7417 /// while-statement: [C99 6.8.5.1]
7418 /// 'while' '(' expression ')' statement
7419 /// [C++] 'while' '(' condition ')' statement
7420 /// \endverbatim
7421 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc,
7422 LabelDecl *PrecedingLabel);
7423
7424 /// ParseDoStatement
7425 /// \verbatim
7426 /// do-statement: [C99 6.8.5.2]
7427 /// 'do' statement 'while' '(' expression ')' ';'
7428 /// \endverbatim
7429 /// Note: this lets the caller parse the end ';'.
7430 StmtResult ParseDoStatement(LabelDecl *PrecedingLabel);
7431
7432 /// ParseForStatement
7433 /// \verbatim
7434 /// for-statement: [C99 6.8.5.3]
7435 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
7436 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
7437 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
7438 /// [C++] statement
7439 /// [C++0x] 'for'
7440 /// 'co_await'[opt] [Coroutines]
7441 /// '(' for-range-declaration ':' for-range-initializer ')'
7442 /// statement
7443 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
7444 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
7445 ///
7446 /// [C++] for-init-statement:
7447 /// [C++] expression-statement
7448 /// [C++] simple-declaration
7449 /// [C++23] alias-declaration
7450 ///
7451 /// [C++0x] for-range-declaration:
7452 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
7453 /// [C++0x] for-range-initializer:
7454 /// [C++0x] expression
7455 /// [C++0x] braced-init-list [TODO]
7456 /// \endverbatim
7457 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc,
7458 LabelDecl *PrecedingLabel);
7459
7460 /// ParseGotoStatement
7461 /// \verbatim
7462 /// jump-statement:
7463 /// 'goto' identifier ';'
7464 /// [GNU] 'goto' '*' expression ';'
7465 /// \endverbatim
7466 ///
7467 /// Note: this lets the caller parse the end ';'.
7468 ///
7469 StmtResult ParseGotoStatement();
7470
7471 /// ParseContinueStatement
7472 /// \verbatim
7473 /// jump-statement:
7474 /// 'continue' ';'
7475 /// [C2y] 'continue' identifier ';'
7476 /// \endverbatim
7477 ///
7478 /// Note: this lets the caller parse the end ';'.
7479 ///
7480 StmtResult ParseContinueStatement();
7481
7482 /// ParseBreakStatement
7483 /// \verbatim
7484 /// jump-statement:
7485 /// 'break' ';'
7486 /// [C2y] 'break' identifier ';'
7487 /// \endverbatim
7488 ///
7489 /// Note: this lets the caller parse the end ';'.
7490 ///
7491 StmtResult ParseBreakStatement();
7492
7493 /// ParseReturnStatement
7494 /// \verbatim
7495 /// jump-statement:
7496 /// 'return' expression[opt] ';'
7497 /// 'return' braced-init-list ';'
7498 /// 'co_return' expression[opt] ';'
7499 /// 'co_return' braced-init-list ';'
7500 /// \endverbatim
7501 StmtResult ParseReturnStatement();
7502
7503 StmtResult ParseBreakOrContinueStatement(bool IsContinue);
7504
7505 /// ParseDeferStatement
7506 /// \verbatim
7507 /// defer-statement:
7508 /// '_Defer' deferred-block
7509 ///
7510 /// deferred-block:
7511 /// unlabeled-statement
7512 /// \endverbatim
7513 StmtResult ParseDeferStatement(SourceLocation *TrailingElseLoc);
7514
7515 StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7516 SourceLocation *TrailingElseLoc,
7517 ParsedAttributes &Attrs,
7518 LabelDecl *PrecedingLabel);
7519
7520 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
7521
7522 //===--------------------------------------------------------------------===//
7523 // C++ 6: Statements and Blocks
7524
7525 /// ParseCXXTryBlock - Parse a C++ try-block.
7526 ///
7527 /// \verbatim
7528 /// try-block:
7529 /// 'try' compound-statement handler-seq
7530 /// \endverbatim
7531 ///
7532 StmtResult ParseCXXTryBlock();
7533
7534 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
7535 /// function-try-block.
7536 ///
7537 /// \verbatim
7538 /// try-block:
7539 /// 'try' compound-statement handler-seq
7540 ///
7541 /// function-try-block:
7542 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7543 ///
7544 /// handler-seq:
7545 /// handler handler-seq[opt]
7546 ///
7547 /// [Borland] try-block:
7548 /// 'try' compound-statement seh-except-block
7549 /// 'try' compound-statement seh-finally-block
7550 /// \endverbatim
7551 ///
7552 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
7553
7554 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the
7555 /// standard
7556 ///
7557 /// \verbatim
7558 /// handler:
7559 /// 'catch' '(' exception-declaration ')' compound-statement
7560 ///
7561 /// exception-declaration:
7562 /// attribute-specifier-seq[opt] type-specifier-seq declarator
7563 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
7564 /// '...'
7565 /// \endverbatim
7566 ///
7567 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
7568
7569 //===--------------------------------------------------------------------===//
7570 // MS: SEH Statements and Blocks
7571
7572 /// ParseSEHTryBlockCommon
7573 ///
7574 /// \verbatim
7575 /// seh-try-block:
7576 /// '__try' compound-statement seh-handler
7577 ///
7578 /// seh-handler:
7579 /// seh-except-block
7580 /// seh-finally-block
7581 /// \endverbatim
7582 ///
7583 StmtResult ParseSEHTryBlock();
7584
7585 /// ParseSEHExceptBlock - Handle __except
7586 ///
7587 /// \verbatim
7588 /// seh-except-block:
7589 /// '__except' '(' seh-filter-expression ')' compound-statement
7590 /// \endverbatim
7591 ///
7592 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
7593
7594 /// ParseSEHFinallyBlock - Handle __finally
7595 ///
7596 /// \verbatim
7597 /// seh-finally-block:
7598 /// '__finally' compound-statement
7599 /// \endverbatim
7600 ///
7601 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
7602
7603 StmtResult ParseSEHLeaveStatement();
7604
7605 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
7606
7607 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
7608 ///
7609 /// \verbatim
7610 /// function-try-block:
7611 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7612 /// \endverbatim
7613 ///
7614 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
7615
7616 /// When in code-completion, skip parsing of the function/method body
7617 /// unless the body contains the code-completion point.
7618 ///
7619 /// \returns true if the function body was skipped.
7620 bool trySkippingFunctionBody();
7621
7622 /// isDeclarationStatement - Disambiguates between a declaration or an
7623 /// expression statement, when parsing function bodies.
7624 ///
7625 /// \param DisambiguatingWithExpression - True to indicate that the purpose of
7626 /// this check is to disambiguate between an expression and a declaration.
7627 /// Returns true for declaration, false for expression.
7628 bool isDeclarationStatement(bool DisambiguatingWithExpression = false) {
7629 if (getLangOpts().CPlusPlus)
7630 return isCXXDeclarationStatement(DisambiguatingWithExpression);
7631 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
7632 }
7633
7634 /// isForInitDeclaration - Disambiguates between a declaration or an
7635 /// expression in the context of the C 'clause-1' or the C++
7636 // 'for-init-statement' part of a 'for' statement.
7637 /// Returns true for declaration, false for expression.
7638 bool isForInitDeclaration() {
7639 if (getLangOpts().OpenMP)
7640 Actions.OpenMP().startOpenMPLoop();
7641 if (getLangOpts().CPlusPlus)
7642 return Tok.is(tok::kw_using) ||
7643 isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
7644 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
7645 }
7646
7647 /// Determine whether this is a C++1z for-range-identifier.
7648 bool isForRangeIdentifier();
7649
7650 ///@}
7651
7652 //
7653 //
7654 // -------------------------------------------------------------------------
7655 //
7656 //
7657
7658 /// \name `inline asm` Statement
7659 /// Implementations are in ParseStmtAsm.cpp
7660 ///@{
7661
7662public:
7663 /// Parse an identifier in an MS-style inline assembly block.
7664 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
7665 unsigned &NumLineToksConsumed,
7666 bool IsUnevaluated);
7667
7668private:
7669 /// ParseAsmStatement - Parse a GNU extended asm statement.
7670 /// \verbatim
7671 /// asm-statement:
7672 /// gnu-asm-statement
7673 /// ms-asm-statement
7674 ///
7675 /// [GNU] gnu-asm-statement:
7676 /// 'asm' asm-qualifier-list[opt] '(' asm-argument ')' ';'
7677 ///
7678 /// [GNU] asm-argument:
7679 /// asm-string-literal
7680 /// asm-string-literal ':' asm-operands[opt]
7681 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7682 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7683 /// ':' asm-clobbers
7684 ///
7685 /// [GNU] asm-clobbers:
7686 /// asm-string-literal
7687 /// asm-clobbers ',' asm-string-literal
7688 /// \endverbatim
7689 ///
7690 StmtResult ParseAsmStatement(bool &msAsm);
7691
7692 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
7693 /// this routine is called to collect the tokens for an MS asm statement.
7694 ///
7695 /// \verbatim
7696 /// [MS] ms-asm-statement:
7697 /// ms-asm-block
7698 /// ms-asm-block ms-asm-statement
7699 ///
7700 /// [MS] ms-asm-block:
7701 /// '__asm' ms-asm-line '\n'
7702 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
7703 ///
7704 /// [MS] ms-asm-instruction-block
7705 /// ms-asm-line
7706 /// ms-asm-line '\n' ms-asm-instruction-block
7707 /// \endverbatim
7708 ///
7709 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
7710
7711 /// ParseAsmOperands - Parse the asm-operands production as used by
7712 /// asm-statement, assuming the leading ':' token was eaten.
7713 ///
7714 /// \verbatim
7715 /// [GNU] asm-operands:
7716 /// asm-operand
7717 /// asm-operands ',' asm-operand
7718 ///
7719 /// [GNU] asm-operand:
7720 /// asm-string-literal '(' expression ')'
7721 /// '[' identifier ']' asm-string-literal '(' expression ')'
7722 /// \endverbatim
7723 ///
7724 // FIXME: Avoid unnecessary std::string trashing.
7725 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
7726 SmallVectorImpl<Expr *> &Constraints,
7727 SmallVectorImpl<Expr *> &Exprs);
7728
7729 class GNUAsmQualifiers {
7730 unsigned Qualifiers = AQ_unspecified;
7731
7732 public:
7733 enum AQ {
7734 AQ_unspecified = 0,
7735 AQ_volatile = 1,
7736 AQ_inline = 2,
7737 AQ_goto = 4,
7738 };
7739 static const char *getQualifierName(AQ Qualifier);
7740 bool setAsmQualifier(AQ Qualifier);
7741 inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
7742 inline bool isInline() const { return Qualifiers & AQ_inline; };
7743 inline bool isGoto() const { return Qualifiers & AQ_goto; }
7744 };
7745
7746 // Determine if this is a GCC-style asm statement.
7747 bool isGCCAsmStatement(const Token &TokAfterAsm) const;
7748
7749 bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
7750 GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
7751
7752 /// parseGNUAsmQualifierListOpt - Parse a GNU extended asm qualifier list.
7753 /// \verbatim
7754 /// asm-qualifier:
7755 /// volatile
7756 /// inline
7757 /// goto
7758 ///
7759 /// asm-qualifier-list:
7760 /// asm-qualifier
7761 /// asm-qualifier-list asm-qualifier
7762 /// \endverbatim
7763 bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
7764
7765 ///@}
7766
7767 //
7768 //
7769 // -------------------------------------------------------------------------
7770 //
7771 //
7772
7773 /// \name C++ Templates
7774 /// Implementations are in ParseTemplate.cpp
7775 ///@{
7776
7777public:
7779
7780 /// Re-enter a possible template scope, creating as many template parameter
7781 /// scopes as necessary.
7782 /// \return The number of template parameter scopes entered.
7784
7785private:
7786 /// The "depth" of the template parameters currently being parsed.
7787 unsigned TemplateParameterDepth;
7788
7789 /// RAII class that manages the template parameter depth.
7790 class TemplateParameterDepthRAII {
7791 unsigned &Depth;
7792 unsigned AddedLevels;
7793
7794 public:
7795 explicit TemplateParameterDepthRAII(unsigned &Depth)
7796 : Depth(Depth), AddedLevels(0) {}
7797
7798 ~TemplateParameterDepthRAII() { Depth -= AddedLevels; }
7799
7800 void operator++() {
7801 ++Depth;
7802 ++AddedLevels;
7803 }
7804 void addDepth(unsigned D) {
7805 Depth += D;
7806 AddedLevels += D;
7807 }
7808 void setAddedDepth(unsigned D) {
7809 Depth = Depth - AddedLevels + D;
7810 AddedLevels = D;
7811 }
7812
7813 unsigned getDepth() const { return Depth; }
7814 unsigned getOriginalDepth() const { return Depth - AddedLevels; }
7815 };
7816
7817 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
7818 /// top-level declaration is finished.
7819 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
7820
7821 /// Don't destroy template annotations in MaybeDestroyTemplateIds even if
7822 /// we're at the end of a declaration. Instead, we defer the destruction until
7823 /// after a top-level declaration.
7824 /// Use DelayTemplateIdDestructionRAII rather than setting it directly.
7825 bool DelayTemplateIdDestruction = false;
7826
7827 void MaybeDestroyTemplateIds() {
7828 if (DelayTemplateIdDestruction)
7829 return;
7830 if (!TemplateIds.empty() &&
7831 (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
7832 DestroyTemplateIds();
7833 }
7834 void DestroyTemplateIds();
7835
7836 /// RAII object to destroy TemplateIdAnnotations where possible, from a
7837 /// likely-good position during parsing.
7838 struct DestroyTemplateIdAnnotationsRAIIObj {
7839 Parser &Self;
7840
7841 DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
7842 ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
7843 };
7844
7845 struct DelayTemplateIdDestructionRAII {
7846 Parser &Self;
7847 bool PrevDelayTemplateIdDestruction;
7848
7849 DelayTemplateIdDestructionRAII(Parser &Self,
7850 bool DelayTemplateIdDestruction) noexcept
7851 : Self(Self),
7852 PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) {
7853 Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction;
7854 }
7855
7856 ~DelayTemplateIdDestructionRAII() noexcept {
7857 Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction;
7858 }
7859 };
7860
7861 /// Identifiers which have been declared within a tentative parse.
7862 SmallVector<const IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
7863
7864 /// Tracker for '<' tokens that might have been intended to be treated as an
7865 /// angle bracket instead of a less-than comparison.
7866 ///
7867 /// This happens when the user intends to form a template-id, but typoes the
7868 /// template-name or forgets a 'template' keyword for a dependent template
7869 /// name.
7870 ///
7871 /// We track these locations from the point where we see a '<' with a
7872 /// name-like expression on its left until we see a '>' or '>>' that might
7873 /// match it.
7874 struct AngleBracketTracker {
7875 /// Flags used to rank candidate template names when there is more than one
7876 /// '<' in a scope.
7877 enum Priority : unsigned short {
7878 /// A non-dependent name that is a potential typo for a template name.
7879 PotentialTypo = 0x0,
7880 /// A dependent name that might instantiate to a template-name.
7881 DependentName = 0x2,
7882
7883 /// A space appears before the '<' token.
7884 SpaceBeforeLess = 0x0,
7885 /// No space before the '<' token
7886 NoSpaceBeforeLess = 0x1,
7887
7888 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
7889 };
7890
7891 struct Loc {
7894 AngleBracketTracker::Priority Priority;
7896
7897 bool isActive(Parser &P) const {
7898 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
7899 P.BraceCount == BraceCount;
7900 }
7901
7902 bool isActiveOrNested(Parser &P) const {
7903 return isActive(P) || P.ParenCount > ParenCount ||
7904 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
7905 }
7906 };
7907
7909
7910 /// Add an expression that might have been intended to be a template name.
7911 /// In the case of ambiguity, we arbitrarily select the innermost such
7912 /// expression, for example in 'foo < bar < baz', 'bar' is the current
7913 /// candidate. No attempt is made to track that 'foo' is also a candidate
7914 /// for the case where we see a second suspicious '>' token.
7915 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
7916 Priority Prio) {
7917 if (!Locs.empty() && Locs.back().isActive(P)) {
7918 if (Locs.back().Priority <= Prio) {
7919 Locs.back().TemplateName = TemplateName;
7920 Locs.back().LessLoc = LessLoc;
7921 Locs.back().Priority = Prio;
7922 }
7923 } else {
7924 Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount,
7925 P.BracketCount, P.BraceCount});
7926 }
7927 }
7928
7929 /// Mark the current potential missing template location as having been
7930 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
7931 /// or leave a bracket scope).
7932 void clear(Parser &P) {
7933 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
7934 Locs.pop_back();
7935 }
7936
7937 /// Get the current enclosing expression that might hve been intended to be
7938 /// a template name.
7939 Loc *getCurrent(Parser &P) {
7940 if (!Locs.empty() && Locs.back().isActive(P))
7941 return &Locs.back();
7942 return nullptr;
7943 }
7944 };
7945
7946 AngleBracketTracker AngleBrackets;
7947
7948 /// Contains information about any template-specific
7949 /// information that has been parsed prior to parsing declaration
7950 /// specifiers.
7951 struct ParsedTemplateInfo {
7952 ParsedTemplateInfo()
7953 : Kind(ParsedTemplateKind::NonTemplate), TemplateParams(nullptr) {}
7954
7955 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
7956 bool isSpecialization,
7957 bool lastParameterListWasEmpty = false)
7958 : Kind(isSpecialization ? ParsedTemplateKind::ExplicitSpecialization
7960 TemplateParams(TemplateParams),
7961 LastParameterListWasEmpty(lastParameterListWasEmpty) {}
7962
7963 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
7964 SourceLocation TemplateLoc)
7966 TemplateParams(nullptr), ExternLoc(ExternLoc),
7967 TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false) {}
7968
7969 ParsedTemplateKind Kind;
7970
7971 /// The template parameter lists, for template declarations
7972 /// and explicit specializations.
7973 TemplateParameterLists *TemplateParams;
7974
7975 /// The location of the 'extern' keyword, if any, for an explicit
7976 /// instantiation
7977 SourceLocation ExternLoc;
7978
7979 /// The location of the 'template' keyword, for an explicit
7980 /// instantiation.
7981 SourceLocation TemplateLoc;
7982
7983 /// Whether the last template parameter list was empty.
7984 bool LastParameterListWasEmpty;
7985
7986 SourceRange getSourceRange() const LLVM_READONLY;
7987 };
7988
7989 /// Lex a delayed template function for late parsing.
7990 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
7991
7992 /// Late parse a C++ function template in Microsoft mode.
7993 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
7994
7995 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
7996
7997 /// We've parsed something that could plausibly be intended to be a template
7998 /// name (\p LHS) followed by a '<' token, and the following code can't
7999 /// possibly be an expression. Determine if this is likely to be a template-id
8000 /// and if so, diagnose it.
8001 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
8002
8003 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
8004 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
8005 const Token &OpToken);
8006 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
8007 if (auto *Info = AngleBrackets.getCurrent(*this))
8008 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
8009 return false;
8010 }
8011
8012 //===--------------------------------------------------------------------===//
8013 // C++ 14: Templates [temp]
8014
8015 /// Parse a template declaration, explicit instantiation, or
8016 /// explicit specialization.
8018 ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
8019 SourceLocation &DeclEnd,
8020 ParsedAttributes &AccessAttrs);
8021
8022 /// Parse a template declaration or an explicit specialization.
8023 ///
8024 /// Template declarations include one or more template parameter lists
8025 /// and either the function or class template declaration. Explicit
8026 /// specializations contain one or more 'template < >' prefixes
8027 /// followed by a (possibly templated) declaration. Since the
8028 /// syntactic form of both features is nearly identical, we parse all
8029 /// of the template headers together and let semantic analysis sort
8030 /// the declarations from the explicit specializations.
8031 ///
8032 /// \verbatim
8033 /// template-declaration: [C++ temp]
8034 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
8035 ///
8036 /// template-declaration: [C++2a]
8037 /// template-head declaration
8038 /// template-head concept-definition
8039 ///
8040 /// TODO: requires-clause
8041 /// template-head: [C++2a]
8042 /// 'template' '<' template-parameter-list '>'
8043 /// requires-clause[opt]
8044 ///
8045 /// explicit-specialization: [ C++ temp.expl.spec]
8046 /// 'template' '<' '>' declaration
8047 /// \endverbatim
8048 DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
8049 DeclaratorContext Context, SourceLocation &DeclEnd,
8050 ParsedAttributes &AccessAttrs, AccessSpecifier AS);
8051
8052 clang::Parser::DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
8053 DeclaratorContext Context, SourceLocation &DeclEnd, AccessSpecifier AS);
8054
8055 /// Parse a single declaration that declares a template,
8056 /// template specialization, or explicit instantiation of a template.
8057 ///
8058 /// \param DeclEnd will receive the source location of the last token
8059 /// within this declaration.
8060 ///
8061 /// \param AS the access specifier associated with this
8062 /// declaration. Will be AS_none for namespace-scope declarations.
8063 ///
8064 /// \returns the new declaration.
8065 DeclGroupPtrTy ParseDeclarationAfterTemplate(
8066 DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo,
8067 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
8068 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
8069
8070 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
8071 /// angle brackets. Depth is the depth of this template-parameter-list, which
8072 /// is the number of template headers directly enclosing this template header.
8073 /// TemplateParams is the current list of template parameters we're building.
8074 /// The template parameter we parse will be added to this list. LAngleLoc and
8075 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
8076 /// that enclose this template parameter list.
8077 ///
8078 /// \returns true if an error occurred, false otherwise.
8079 bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
8080 SmallVectorImpl<NamedDecl *> &TemplateParams,
8081 SourceLocation &LAngleLoc,
8082 SourceLocation &RAngleLoc);
8083
8084 /// ParseTemplateParameterList - Parse a template parameter list. If
8085 /// the parsing fails badly (i.e., closing bracket was left out), this
8086 /// will try to put the token stream in a reasonable position (closing
8087 /// a statement, etc.) and return false.
8088 ///
8089 /// \verbatim
8090 /// template-parameter-list: [C++ temp]
8091 /// template-parameter
8092 /// template-parameter-list ',' template-parameter
8093 /// \endverbatim
8094 bool ParseTemplateParameterList(unsigned Depth,
8095 SmallVectorImpl<NamedDecl *> &TemplateParams);
8096
8097 enum class TPResult;
8098
8099 /// Determine whether the parser is at the start of a template
8100 /// type parameter.
8101 TPResult isStartOfTemplateTypeParameter();
8102
8103 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
8104 ///
8105 /// \verbatim
8106 /// template-parameter: [C++ temp.param]
8107 /// type-parameter
8108 /// parameter-declaration
8109 ///
8110 /// type-parameter: (See below)
8111 /// type-parameter-key ...[opt] identifier[opt]
8112 /// type-parameter-key identifier[opt] = type-id
8113 /// (C++2a) type-constraint ...[opt] identifier[opt]
8114 /// (C++2a) type-constraint identifier[opt] = type-id
8115 /// 'template' '<' template-parameter-list '>' type-parameter-key
8116 /// ...[opt] identifier[opt]
8117 /// 'template' '<' template-parameter-list '>' type-parameter-key
8118 /// identifier[opt] '=' id-expression
8119 ///
8120 /// type-parameter-key:
8121 /// class
8122 /// typename
8123 /// \endverbatim
8124 ///
8125 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
8126
8127 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
8128 /// Other kinds of template parameters are parsed in
8129 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
8130 ///
8131 /// \verbatim
8132 /// type-parameter: [C++ temp.param]
8133 /// 'class' ...[opt][C++0x] identifier[opt]
8134 /// 'class' identifier[opt] '=' type-id
8135 /// 'typename' ...[opt][C++0x] identifier[opt]
8136 /// 'typename' identifier[opt] '=' type-id
8137 /// \endverbatim
8138 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
8139
8140 /// ParseTemplateTemplateParameter - Handle the parsing of template
8141 /// template parameters.
8142 ///
8143 /// \verbatim
8144 /// type-parameter: [C++ temp.param]
8145 /// template-head type-parameter-key ...[opt] identifier[opt]
8146 /// template-head type-parameter-key identifier[opt] = id-expression
8147 /// type-parameter-key:
8148 /// 'class'
8149 /// 'typename' [C++1z]
8150 /// template-head: [C++2a]
8151 /// 'template' '<' template-parameter-list '>'
8152 /// requires-clause[opt]
8153 /// \endverbatim
8154 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
8155
8156 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
8157 /// template parameters (e.g., in "template<int Size> class array;").
8158 ///
8159 /// \verbatim
8160 /// template-parameter:
8161 /// ...
8162 /// parameter-declaration
8163 /// \endverbatim
8164 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
8165
8166 /// Check whether the current token is a template-id annotation denoting a
8167 /// type-constraint.
8168 bool isTypeConstraintAnnotation();
8169
8170 /// Try parsing a type-constraint at the current location.
8171 ///
8172 /// \verbatim
8173 /// type-constraint:
8174 /// nested-name-specifier[opt] concept-name
8175 /// nested-name-specifier[opt] concept-name
8176 /// '<' template-argument-list[opt] '>'[opt]
8177 /// \endverbatim
8178 ///
8179 /// \returns true if an error occurred, and false otherwise.
8180 bool TryAnnotateTypeConstraint();
8181
8182 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
8183 SourceLocation CorrectLoc,
8184 bool AlreadyHasEllipsis,
8185 bool IdentifierHasName);
8186 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
8187 Declarator &D);
8188 // C++ 14.3: Template arguments [temp.arg]
8189 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
8190
8191 /// Parses a '>' at the end of a template list.
8192 ///
8193 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
8194 /// to determine if these tokens were supposed to be a '>' followed by
8195 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
8196 ///
8197 /// \param RAngleLoc the location of the consumed '>'.
8198 ///
8199 /// \param ConsumeLastToken if true, the '>' is consumed.
8200 ///
8201 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
8202 /// type parameter or type argument list, rather than a C++ template parameter
8203 /// or argument list.
8204 ///
8205 /// \returns true, if current token does not start with '>', false otherwise.
8206 bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
8207 SourceLocation &RAngleLoc,
8208 bool ConsumeLastToken,
8209 bool ObjCGenericList);
8210
8211 /// Parses a template-id that after the template name has
8212 /// already been parsed.
8213 ///
8214 /// This routine takes care of parsing the enclosed template argument
8215 /// list ('<' template-parameter-list [opt] '>') and placing the
8216 /// results into a form that can be transferred to semantic analysis.
8217 ///
8218 /// \param ConsumeLastToken if true, then we will consume the last
8219 /// token that forms the template-id. Otherwise, we will leave the
8220 /// last token in the stream (e.g., so that it can be replaced with an
8221 /// annotation token).
8222 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
8223 SourceLocation &LAngleLoc,
8224 TemplateArgList &TemplateArgs,
8225 SourceLocation &RAngleLoc,
8226 TemplateTy NameHint = nullptr);
8227
8228 /// Replace the tokens that form a simple-template-id with an
8229 /// annotation token containing the complete template-id.
8230 ///
8231 /// The first token in the stream must be the name of a template that
8232 /// is followed by a '<'. This routine will parse the complete
8233 /// simple-template-id and replace the tokens with a single annotation
8234 /// token with one of two different kinds: if the template-id names a
8235 /// type (and \p AllowTypeAnnotation is true), the annotation token is
8236 /// a type annotation that includes the optional nested-name-specifier
8237 /// (\p SS). Otherwise, the annotation token is a template-id
8238 /// annotation that does not include the optional
8239 /// nested-name-specifier.
8240 ///
8241 /// \param Template the declaration of the template named by the first
8242 /// token (an identifier), as returned from \c Action::isTemplateName().
8243 ///
8244 /// \param TNK the kind of template that \p Template
8245 /// refers to, as returned from \c Action::isTemplateName().
8246 ///
8247 /// \param SS if non-NULL, the nested-name-specifier that precedes
8248 /// this template name.
8249 ///
8250 /// \param TemplateKWLoc if valid, specifies that this template-id
8251 /// annotation was preceded by the 'template' keyword and gives the
8252 /// location of that keyword. If invalid (the default), then this
8253 /// template-id was not preceded by a 'template' keyword.
8254 ///
8255 /// \param AllowTypeAnnotation if true (the default), then a
8256 /// simple-template-id that refers to a class template, template
8257 /// template parameter, or other template that produces a type will be
8258 /// replaced with a type annotation token. Otherwise, the
8259 /// simple-template-id is always replaced with a template-id
8260 /// annotation token.
8261 ///
8262 /// \param TypeConstraint if true, then this is actually a type-constraint,
8263 /// meaning that the template argument list can be omitted (and the template
8264 /// in question must be a concept).
8265 ///
8266 /// If an unrecoverable parse error occurs and no annotation token can be
8267 /// formed, this function returns true.
8268 ///
8269 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
8270 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8271 UnqualifiedId &TemplateName,
8272 bool AllowTypeAnnotation = true,
8273 bool TypeConstraint = false);
8274
8275 /// Replaces a template-id annotation token with a type
8276 /// annotation token.
8277 ///
8278 /// If there was a failure when forming the type from the template-id,
8279 /// a type annotation token will still be created, but will have a
8280 /// NULL type pointer to signify an error.
8281 ///
8282 /// \param SS The scope specifier appearing before the template-id, if any.
8283 ///
8284 /// \param AllowImplicitTypename whether this is a context where T::type
8285 /// denotes a dependent type.
8286 /// \param IsClassName Is this template-id appearing in a context where we
8287 /// know it names a class, such as in an elaborated-type-specifier or
8288 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
8289 /// in those contexts.)
8290 void
8291 AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
8292 ImplicitTypenameContext AllowImplicitTypename,
8293 bool IsClassName = false);
8294
8295 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
8296 /// (C++ [temp.names]). Returns true if there was an error.
8297 ///
8298 /// \verbatim
8299 /// template-argument-list: [C++ 14.2]
8300 /// template-argument
8301 /// template-argument-list ',' template-argument
8302 /// \endverbatim
8303 ///
8304 /// \param Template is only used for code completion, and may be null.
8305 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
8306 TemplateTy Template, SourceLocation OpenLoc);
8307
8308 /// Parse a C++ template template argument.
8309 ParsedTemplateArgument ParseTemplateTemplateArgument();
8310
8311 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
8312 ///
8313 /// \verbatim
8314 /// template-argument: [C++ 14.2]
8315 /// constant-expression
8316 /// type-id
8317 /// id-expression
8318 /// braced-init-list [C++26, DR]
8319 /// \endverbatim
8320 ///
8321 ParsedTemplateArgument ParseTemplateArgument();
8322
8323 /// Parse a C++ explicit template instantiation
8324 /// (C++ [temp.explicit]).
8325 ///
8326 /// \verbatim
8327 /// explicit-instantiation:
8328 /// 'extern' [opt] 'template' declaration
8329 /// \endverbatim
8330 ///
8331 /// Note that the 'extern' is a GNU extension and C++11 feature.
8332 DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context,
8333 SourceLocation ExternLoc,
8334 SourceLocation TemplateLoc,
8335 SourceLocation &DeclEnd,
8336 ParsedAttributes &AccessAttrs,
8338
8339 /// \brief Parse a single declaration that declares a concept.
8340 ///
8341 /// \param DeclEnd will receive the source location of the last token
8342 /// within this declaration.
8343 ///
8344 /// \returns the new declaration.
8345 Decl *ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
8346 SourceLocation &DeclEnd);
8347
8348 ///@}
8349
8350 //
8351 //
8352 // -------------------------------------------------------------------------
8353 //
8354 //
8355
8356 /// \name Tentative Parsing
8357 /// Implementations are in ParseTentative.cpp
8358 ///@{
8359
8360private:
8361 /// TentativeParsingAction - An object that is used as a kind of "tentative
8362 /// parsing transaction". It gets instantiated to mark the token position and
8363 /// after the token consumption is done, Commit() or Revert() is called to
8364 /// either "commit the consumed tokens" or revert to the previously marked
8365 /// token position. Example:
8366 ///
8367 /// TentativeParsingAction TPA(*this);
8368 /// ConsumeToken();
8369 /// ....
8370 /// TPA.Revert();
8371 ///
8372 /// If the Unannotated parameter is true, any token annotations created
8373 /// during the tentative parse are reverted.
8374 class TentativeParsingAction {
8375 Parser &P;
8376 PreferredTypeBuilder PrevPreferredType;
8377 Token PrevTok;
8378 size_t PrevTentativelyDeclaredIdentifierCount;
8379 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
8380 bool isActive;
8381
8382 public:
8383 explicit TentativeParsingAction(Parser &p, bool Unannotated = false)
8384 : P(p), PrevPreferredType(P.PreferredType) {
8385 PrevTok = P.Tok;
8386 PrevTentativelyDeclaredIdentifierCount =
8387 P.TentativelyDeclaredIdentifiers.size();
8388 PrevParenCount = P.ParenCount;
8389 PrevBracketCount = P.BracketCount;
8390 PrevBraceCount = P.BraceCount;
8391 P.PP.EnableBacktrackAtThisPos(Unannotated);
8392 isActive = true;
8393 }
8394 void Commit() {
8395 assert(isActive && "Parsing action was finished!");
8396 P.TentativelyDeclaredIdentifiers.resize(
8397 PrevTentativelyDeclaredIdentifierCount);
8398 P.PP.CommitBacktrackedTokens();
8399 isActive = false;
8400 }
8401 void Revert() {
8402 assert(isActive && "Parsing action was finished!");
8403 P.PP.Backtrack();
8404 P.PreferredType = PrevPreferredType;
8405 P.Tok = PrevTok;
8406 P.TentativelyDeclaredIdentifiers.resize(
8407 PrevTentativelyDeclaredIdentifierCount);
8408 P.ParenCount = PrevParenCount;
8409 P.BracketCount = PrevBracketCount;
8410 P.BraceCount = PrevBraceCount;
8411 isActive = false;
8412 }
8413 ~TentativeParsingAction() {
8414 assert(!isActive && "Forgot to call Commit or Revert!");
8415 }
8416 };
8417
8418 /// A TentativeParsingAction that automatically reverts in its destructor.
8419 /// Useful for disambiguation parses that will always be reverted.
8420 class RevertingTentativeParsingAction
8421 : private Parser::TentativeParsingAction {
8422 public:
8423 using TentativeParsingAction::TentativeParsingAction;
8424
8425 ~RevertingTentativeParsingAction() { Revert(); }
8426 };
8427
8428 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
8429 /// between a declaration or an expression statement, when parsing function
8430 /// bodies. Returns true for declaration, false for expression.
8431 ///
8432 /// \verbatim
8433 /// declaration-statement:
8434 /// block-declaration
8435 ///
8436 /// block-declaration:
8437 /// simple-declaration
8438 /// asm-definition
8439 /// namespace-alias-definition
8440 /// using-declaration
8441 /// using-directive
8442 /// [C++0x] static_assert-declaration
8443 ///
8444 /// asm-definition:
8445 /// 'asm' '(' string-literal ')' ';'
8446 ///
8447 /// namespace-alias-definition:
8448 /// 'namespace' identifier = qualified-namespace-specifier ';'
8449 ///
8450 /// using-declaration:
8451 /// 'using' typename[opt] '::'[opt] nested-name-specifier
8452 /// unqualified-id ';'
8453 /// 'using' '::' unqualified-id ;
8454 ///
8455 /// using-directive:
8456 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
8457 /// namespace-name ';'
8458 /// \endverbatim
8459 ///
8460 bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false);
8461
8462 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
8463 /// between a simple-declaration or an expression-statement.
8464 /// If during the disambiguation process a parsing error is encountered,
8465 /// the function returns true to let the declaration parsing code handle it.
8466 /// Returns false if the statement is disambiguated as expression.
8467 ///
8468 /// \verbatim
8469 /// simple-declaration:
8470 /// decl-specifier-seq init-declarator-list[opt] ';'
8471 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8472 /// brace-or-equal-initializer ';' [C++17]
8473 /// \endverbatim
8474 ///
8475 /// (if AllowForRangeDecl specified)
8476 /// for ( for-range-declaration : for-range-initializer ) statement
8477 ///
8478 /// \verbatim
8479 /// for-range-declaration:
8480 /// decl-specifier-seq declarator
8481 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8482 /// \endverbatim
8483 ///
8484 /// In any of the above cases there can be a preceding
8485 /// attribute-specifier-seq, but the caller is expected to handle that.
8486 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
8487
8488 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
8489 /// a constructor-style initializer, when parsing declaration statements.
8490 /// Returns true for function declarator and false for constructor-style
8491 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
8492 /// might be a constructor-style initializer.
8493 /// If during the disambiguation process a parsing error is encountered,
8494 /// the function returns true to let the declaration parsing code handle it.
8495 ///
8496 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8497 /// exception-specification[opt]
8498 ///
8499 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr,
8500 ImplicitTypenameContext AllowImplicitTypename =
8502
8503 struct ConditionDeclarationOrInitStatementState;
8504 enum class ConditionOrInitStatement {
8505 Expression, ///< Disambiguated as an expression (either kind).
8506 ConditionDecl, ///< Disambiguated as the declaration form of condition.
8507 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
8508 ForRangeDecl, ///< Disambiguated as a for-range declaration.
8509 Error ///< Can't be any of the above!
8510 };
8511
8512 /// Disambiguates between a declaration in a condition, a
8513 /// simple-declaration in an init-statement, and an expression for
8514 /// a condition of a if/switch statement.
8515 ///
8516 /// \verbatim
8517 /// condition:
8518 /// expression
8519 /// type-specifier-seq declarator '=' assignment-expression
8520 /// [C++11] type-specifier-seq declarator '=' initializer-clause
8521 /// [C++11] type-specifier-seq declarator braced-init-list
8522 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
8523 /// '=' assignment-expression
8524 /// simple-declaration:
8525 /// decl-specifier-seq init-declarator-list[opt] ';'
8526 /// \endverbatim
8527 ///
8528 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
8529 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
8530 /// 'int(x);' (a simple-declaration in an init-statement).
8531 ConditionOrInitStatement
8532 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
8533 bool CanBeForRangeDecl);
8534
8535 /// Determine whether the next set of tokens contains a type-id.
8536 ///
8537 /// The context parameter states what context we're parsing right
8538 /// now, which affects how this routine copes with the token
8539 /// following the type-id. If the context is
8540 /// TentativeCXXTypeIdContext::InParens, we have already parsed the '(' and we
8541 /// will cease lookahead when we hit the corresponding ')'. If the context is
8542 /// TentativeCXXTypeIdContext::AsTemplateArgument, we've already parsed the
8543 /// '<' or ',' before this template argument, and will cease lookahead when we
8544 /// hit a
8545 /// '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
8546 /// preceding such. Returns true for a type-id and false for an expression.
8547 /// If during the disambiguation process a parsing error is encountered,
8548 /// the function returns true to let the declaration parsing code handle it.
8549 ///
8550 /// \verbatim
8551 /// type-id:
8552 /// type-specifier-seq abstract-declarator[opt]
8553 /// \endverbatim
8554 ///
8555 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
8556
8557 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
8558 bool isAmbiguous;
8559 return isCXXTypeId(Context, isAmbiguous);
8560 }
8561
8562 /// TPResult - Used as the result value for functions whose purpose is to
8563 /// disambiguate C++ constructs by "tentatively parsing" them.
8564 enum class TPResult { True, False, Ambiguous, Error };
8565
8566 /// Determine whether we could have an enum-base.
8567 ///
8568 /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
8569 /// only consider this to be an enum-base if the next token is a '{'.
8570 ///
8571 /// \return \c false if this cannot possibly be an enum base; \c true
8572 /// otherwise.
8573 bool isEnumBase(bool AllowSemi);
8574
8575 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
8576 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
8577 /// be either a decl-specifier or a function-style cast, and TPResult::Error
8578 /// if a parsing error was found and reported.
8579 ///
8580 /// Does not consume tokens.
8581 ///
8582 /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
8583 /// declaration specifiers but possibly valid as some other kind of construct
8584 /// return TPResult::Ambiguous instead of TPResult::False. When this happens,
8585 /// the intent is to keep trying to disambiguate, on the basis that we might
8586 /// find a better reason to treat this construct as a declaration later on.
8587 /// When this happens and the name could possibly be valid in some other
8588 /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
8589 /// that trigger this are:
8590 ///
8591 /// * When parsing X::Y (with no 'typename') where X is dependent
8592 /// * When parsing X<Y> where X is undeclared
8593 ///
8594 /// \verbatim
8595 /// decl-specifier:
8596 /// storage-class-specifier
8597 /// type-specifier
8598 /// function-specifier
8599 /// 'friend'
8600 /// 'typedef'
8601 /// [C++11] 'constexpr'
8602 /// [C++20] 'consteval'
8603 /// [GNU] attributes declaration-specifiers[opt]
8604 ///
8605 /// storage-class-specifier:
8606 /// 'register'
8607 /// 'static'
8608 /// 'extern'
8609 /// 'mutable'
8610 /// 'auto'
8611 /// [GNU] '__thread'
8612 /// [C++11] 'thread_local'
8613 /// [C11] '_Thread_local'
8614 ///
8615 /// function-specifier:
8616 /// 'inline'
8617 /// 'virtual'
8618 /// 'explicit'
8619 ///
8620 /// typedef-name:
8621 /// identifier
8622 ///
8623 /// type-specifier:
8624 /// simple-type-specifier
8625 /// class-specifier
8626 /// enum-specifier
8627 /// elaborated-type-specifier
8628 /// typename-specifier
8629 /// cv-qualifier
8630 ///
8631 /// simple-type-specifier:
8632 /// '::'[opt] nested-name-specifier[opt] type-name
8633 /// '::'[opt] nested-name-specifier 'template'
8634 /// simple-template-id [TODO]
8635 /// 'char'
8636 /// 'wchar_t'
8637 /// 'bool'
8638 /// 'short'
8639 /// 'int'
8640 /// 'long'
8641 /// 'signed'
8642 /// 'unsigned'
8643 /// 'float'
8644 /// 'double'
8645 /// 'void'
8646 /// [GNU] typeof-specifier
8647 /// [GNU] '_Complex'
8648 /// [C++11] 'auto'
8649 /// [GNU] '__auto_type'
8650 /// [C++11] 'decltype' ( expression )
8651 /// [C++1y] 'decltype' ( 'auto' )
8652 ///
8653 /// type-name:
8654 /// class-name
8655 /// enum-name
8656 /// typedef-name
8657 ///
8658 /// elaborated-type-specifier:
8659 /// class-key '::'[opt] nested-name-specifier[opt] identifier
8660 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
8661 /// simple-template-id
8662 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
8663 ///
8664 /// enum-name:
8665 /// identifier
8666 ///
8667 /// enum-specifier:
8668 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
8669 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
8670 ///
8671 /// class-specifier:
8672 /// class-head '{' member-specification[opt] '}'
8673 ///
8674 /// class-head:
8675 /// class-key identifier[opt] base-clause[opt]
8676 /// class-key nested-name-specifier identifier base-clause[opt]
8677 /// class-key nested-name-specifier[opt] simple-template-id
8678 /// base-clause[opt]
8679 ///
8680 /// class-key:
8681 /// 'class'
8682 /// 'struct'
8683 /// 'union'
8684 ///
8685 /// cv-qualifier:
8686 /// 'const'
8687 /// 'volatile'
8688 /// [GNU] restrict
8689 /// \endverbatim
8690 ///
8691 TPResult
8692 isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
8693 TPResult BracedCastResult = TPResult::False,
8694 bool *InvalidAsDeclSpec = nullptr);
8695
8696 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
8697 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
8698 /// a type-specifier other than a cv-qualifier.
8699 bool isCXXDeclarationSpecifierAType();
8700
8701 /// Determine whether we might be looking at the '<' template-argument-list
8702 /// '>' of a template-id or simple-template-id, rather than a less-than
8703 /// comparison. This will often fail and produce an ambiguity, but should
8704 /// never be wrong if it returns True or False.
8705 TPResult isTemplateArgumentList(unsigned TokensToSkip);
8706
8707 /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
8708 /// 'explicit(bool)' declaration, in earlier language modes where that is an
8709 /// extension.
8710 TPResult isExplicitBool();
8711
8712 /// Determine whether an identifier has been tentatively declared as a
8713 /// non-type. Such tentative declarations should not be found to name a type
8714 /// during a tentative parse, but also should not be annotated as a non-type.
8715 bool isTentativelyDeclared(IdentifierInfo *II);
8716
8717 // "Tentative parsing" functions, used for disambiguation. If a parsing error
8718 // is encountered they will return TPResult::Error.
8719 // Returning TPResult::True/False indicates that the ambiguity was
8720 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
8721 // that more tentative parsing is necessary for disambiguation.
8722 // They all consume tokens, so backtracking should be used after calling them.
8723
8724 /// \verbatim
8725 /// simple-declaration:
8726 /// decl-specifier-seq init-declarator-list[opt] ';'
8727 ///
8728 /// (if AllowForRangeDecl specified)
8729 /// for ( for-range-declaration : for-range-initializer ) statement
8730 /// for-range-declaration:
8731 /// attribute-specifier-seqopt type-specifier-seq declarator
8732 /// \endverbatim
8733 ///
8734 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
8735
8736 /// \verbatim
8737 /// [GNU] typeof-specifier:
8738 /// 'typeof' '(' expressions ')'
8739 /// 'typeof' '(' type-name ')'
8740 /// \endverbatim
8741 ///
8742 TPResult TryParseTypeofSpecifier();
8743
8744 /// [ObjC] protocol-qualifiers:
8745 /// '<' identifier-list '>'
8746 TPResult TryParseProtocolQualifiers();
8747
8748 TPResult TryParsePtrOperatorSeq();
8749
8750 /// \verbatim
8751 /// operator-function-id:
8752 /// 'operator' operator
8753 ///
8754 /// operator: one of
8755 /// new delete new[] delete[] + - * / % ^ [...]
8756 ///
8757 /// conversion-function-id:
8758 /// 'operator' conversion-type-id
8759 ///
8760 /// conversion-type-id:
8761 /// type-specifier-seq conversion-declarator[opt]
8762 ///
8763 /// conversion-declarator:
8764 /// ptr-operator conversion-declarator[opt]
8765 ///
8766 /// literal-operator-id:
8767 /// 'operator' string-literal identifier
8768 /// 'operator' user-defined-string-literal
8769 /// \endverbatim
8770 TPResult TryParseOperatorId();
8771
8772 /// Tentatively parse an init-declarator-list in order to disambiguate it from
8773 /// an expression.
8774 ///
8775 /// \verbatim
8776 /// init-declarator-list:
8777 /// init-declarator
8778 /// init-declarator-list ',' init-declarator
8779 ///
8780 /// init-declarator:
8781 /// declarator initializer[opt]
8782 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
8783 ///
8784 /// initializer:
8785 /// brace-or-equal-initializer
8786 /// '(' expression-list ')'
8787 ///
8788 /// brace-or-equal-initializer:
8789 /// '=' initializer-clause
8790 /// [C++11] braced-init-list
8791 ///
8792 /// initializer-clause:
8793 /// assignment-expression
8794 /// braced-init-list
8795 ///
8796 /// braced-init-list:
8797 /// '{' initializer-list ','[opt] '}'
8798 /// '{' '}'
8799 /// \endverbatim
8800 ///
8801 TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false);
8802
8803 /// \verbatim
8804 /// declarator:
8805 /// direct-declarator
8806 /// ptr-operator declarator
8807 ///
8808 /// direct-declarator:
8809 /// declarator-id
8810 /// direct-declarator '(' parameter-declaration-clause ')'
8811 /// cv-qualifier-seq[opt] exception-specification[opt]
8812 /// direct-declarator '[' constant-expression[opt] ']'
8813 /// '(' declarator ')'
8814 /// [GNU] '(' attributes declarator ')'
8815 ///
8816 /// abstract-declarator:
8817 /// ptr-operator abstract-declarator[opt]
8818 /// direct-abstract-declarator
8819 ///
8820 /// direct-abstract-declarator:
8821 /// direct-abstract-declarator[opt]
8822 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8823 /// exception-specification[opt]
8824 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
8825 /// '(' abstract-declarator ')'
8826 /// [C++0x] ...
8827 ///
8828 /// ptr-operator:
8829 /// '*' cv-qualifier-seq[opt]
8830 /// '&'
8831 /// [C++0x] '&&' [TODO]
8832 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
8833 ///
8834 /// cv-qualifier-seq:
8835 /// cv-qualifier cv-qualifier-seq[opt]
8836 ///
8837 /// cv-qualifier:
8838 /// 'const'
8839 /// 'volatile'
8840 ///
8841 /// declarator-id:
8842 /// '...'[opt] id-expression
8843 ///
8844 /// id-expression:
8845 /// unqualified-id
8846 /// qualified-id [TODO]
8847 ///
8848 /// unqualified-id:
8849 /// identifier
8850 /// operator-function-id
8851 /// conversion-function-id
8852 /// literal-operator-id
8853 /// '~' class-name [TODO]
8854 /// '~' decltype-specifier [TODO]
8855 /// template-id [TODO]
8856 /// \endverbatim
8857 ///
8858 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
8859 bool mayHaveDirectInit = false,
8860 bool mayHaveTrailingReturnType = false);
8861
8862 /// \verbatim
8863 /// parameter-declaration-clause:
8864 /// parameter-declaration-list[opt] '...'[opt]
8865 /// parameter-declaration-list ',' '...'
8866 ///
8867 /// parameter-declaration-list:
8868 /// parameter-declaration
8869 /// parameter-declaration-list ',' parameter-declaration
8870 ///
8871 /// parameter-declaration:
8872 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
8873 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
8874 /// '=' assignment-expression
8875 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
8876 /// attributes[opt]
8877 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
8878 /// attributes[opt] '=' assignment-expression
8879 /// \endverbatim
8880 ///
8881 TPResult TryParseParameterDeclarationClause(
8882 bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false,
8883 ImplicitTypenameContext AllowImplicitTypename =
8885
8886 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to
8887 /// continue parsing as a function declarator. If TryParseFunctionDeclarator
8888 /// fully parsed the function declarator, it will return TPResult::Ambiguous,
8889 /// otherwise it will return either False() or Error().
8890 ///
8891 /// \verbatim
8892 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8893 /// exception-specification[opt]
8894 ///
8895 /// exception-specification:
8896 /// 'throw' '(' type-id-list[opt] ')'
8897 /// \endverbatim
8898 ///
8899 TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false);
8900
8901 // When parsing an identifier after an arrow it may be a member expression,
8902 // in which case we should not annotate it as an independant expression
8903 // so we just lookup that name, if it's not a type the construct is not
8904 // a function declaration.
8905 bool NameAfterArrowIsNonType();
8906
8907 /// \verbatim
8908 /// '[' constant-expression[opt] ']'
8909 /// \endverbatim
8910 ///
8911 TPResult TryParseBracketDeclarator();
8912
8913 /// Try to consume a token sequence that we've already identified as
8914 /// (potentially) starting a decl-specifier.
8915 TPResult TryConsumeDeclarationSpecifier();
8916
8917 /// Try to skip a possibly empty sequence of 'attribute-specifier's without
8918 /// full validation of the syntactic structure of attributes.
8919 bool TrySkipAttributes();
8920
8921 //===--------------------------------------------------------------------===//
8922 // C++ 7: Declarations [dcl.dcl]
8923
8924 /// Returns true if this is a C++11 attribute-specifier. Per
8925 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
8926 /// always introduce an attribute. In Objective-C++11, this rule does not
8927 /// apply if either '[' begins a message-send.
8928 ///
8929 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
8930 /// an attribute-specifier, and return
8931 /// CXX11AttributeKind::InvalidAttributeSpecifier if not.
8932 ///
8933 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
8934 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
8935 /// is not an Obj-C message send.
8936 ///
8937 /// C++11 [dcl.attr.grammar]:
8938 ///
8939 /// \verbatim
8940 /// attribute-specifier:
8941 /// '[' '[' attribute-list ']' ']'
8942 /// alignment-specifier
8943 ///
8944 /// attribute-list:
8945 /// attribute[opt]
8946 /// attribute-list ',' attribute[opt]
8947 /// attribute '...'
8948 /// attribute-list ',' attribute '...'
8949 ///
8950 /// attribute:
8951 /// attribute-token attribute-argument-clause[opt]
8952 ///
8953 /// attribute-token:
8954 /// identifier
8955 /// identifier '::' identifier
8956 ///
8957 /// attribute-argument-clause:
8958 /// '(' balanced-token-seq ')'
8959 /// \endverbatim
8961 isCXX11AttributeSpecifier(bool Disambiguate = false,
8962 bool OuterMightBeMessageSend = false);
8963
8964 ///@}
8965};
8966
8967} // end namespace clang
8968
8969#endif
bool isNot(T Kind) const
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
Token Tok
The Token.
FormatToken * Next
The next token in the unwrapped line.
bool is(tok::TokenKind Kind) const
Defines some OpenACC-specific enums and functions.
Defines and computes precedence levels for binary/ternary operators.
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
bool isInvalid() const
Definition Ownership.h:167
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:622
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3676
Callback handler that receives notifications when performing code completion within the preprocessor.
virtual void CodeCompletePreprocessorExpression()
Callback invoked when performing code completion in a preprocessor expression, such as the condition ...
virtual void CodeCompleteNaturalLanguage()
Callback invoked when performing code completion in a part of the file where we expect natural langua...
virtual void CodeCompleteInConditionalExclusion()
Callback invoked when performing code completion within a block of code that was excluded due to prep...
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1732
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.
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:88
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1838
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:1980
DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Definition Parser.cpp:96
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:59
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:423
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:7186
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:468
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:433
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:7191
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:588
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:1854
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:7778
void Initialize()
Initialize - Warm up the parser.
Definition Parser.cpp:486
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:2097
bool ParseOpenMPDeclareBeginVariantDirective(SourceLocation Loc)
Parses 'omp begin declare variant' directive.
RAII object used to inform the actions that we're currently parsing a declaration.
A class for parsing a DeclSpec.
A class for parsing a declarator.
A class for parsing a field declarator.
PragmaHandler - Instances of this interface defined to handle the various pragmas that the language f...
Definition Pragma.h:65
Tracks expected type during expression parsing, for use in code completion.
Definition Sema.h:292
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void startOpenMPLoop()
If the current region is a loop-based region, mark the start of the loop construct.
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:856
SemaOpenMP & OpenMP()
Definition Sema.h:1508
ProcessingContextState ParsingClassState
Definition Sema.h:6571
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9906
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9915
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:93
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition TokenKinds.h:41
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ TST_unspecified
Definition Specifiers.h: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
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h: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:616
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:451
ExtraSemiKind
The kind of extra semi diagnostic to emit.
Definition Parser.h:69
@ AfterMemberFunctionDefinition
Definition Parser.h:73
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
ParenExprKind
In a call to ParseParenExpression, are the initial parentheses part of an operator that requires the ...
Definition Parser.h:128
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h: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:7894
bool isActiveOrNested(Parser &P) const
Definition Parser.h:7902