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