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