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