clang 20.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/SmallVector.h"
25#include "llvm/Frontend/OpenMP/OMPContext.h"
26#include "llvm/Support/SaveAndRestore.h"
27#include <optional>
28#include <stack>
29
30namespace clang {
31 class PragmaHandler;
32 class Scope;
33 class BalancedDelimiterTracker;
34 class CorrectionCandidateCallback;
35 class DeclGroupRef;
36 class DiagnosticBuilder;
37 struct LoopHint;
38 class Parser;
39 class ParsingDeclRAIIObject;
40 class ParsingDeclSpec;
41 class ParsingDeclarator;
42 class ParsingFieldDeclarator;
43 class ColonProtectionRAIIObject;
44 class InMessageExpressionRAIIObject;
45 class PoisonSEHIdentifiersRAIIObject;
46 class OMPClause;
47 class OpenACCClause;
48 class ObjCTypeParamList;
49 struct OMPTraitProperty;
50 struct OMPTraitSelector;
51 struct OMPTraitSet;
52 class OMPTraitInfo;
53
54/// Parser - This implements a parser for the C family of languages. After
55/// parsing units of the grammar, productions are invoked to handle whatever has
56/// been read.
57///
68
69 Preprocessor &PP;
70
71 /// Tok - The current token we are peeking ahead. All parsing methods assume
72 /// that this is valid.
73 Token Tok;
74
75 // PrevTokLocation - The location of the token we previously
76 // consumed. This token is used for diagnostics where we expected to
77 // see a token following another token (e.g., the ';' at the end of
78 // a statement).
79 SourceLocation PrevTokLocation;
80
81 /// Tracks an expected type for the current token when parsing an expression.
82 /// Used by code completion for ranking.
83 PreferredTypeBuilder PreferredType;
84
85 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
86 unsigned short MisplacedModuleBeginCount = 0;
87
88 /// Actions - These are the callbacks we invoke as we parse various constructs
89 /// in the file.
90 Sema &Actions;
91
92 DiagnosticsEngine &Diags;
93
94 /// ScopeCache - Cache scopes to reduce malloc traffic.
95 enum { ScopeCacheSize = 16 };
96 unsigned NumCachedScopes;
97 Scope *ScopeCache[ScopeCacheSize];
98
99 /// Identifiers used for SEH handling in Borland. These are only
100 /// allowed in particular circumstances
101 // __except block
102 IdentifierInfo *Ident__exception_code,
103 *Ident___exception_code,
104 *Ident_GetExceptionCode;
105 // __except filter expression
106 IdentifierInfo *Ident__exception_info,
107 *Ident___exception_info,
108 *Ident_GetExceptionInfo;
109 // __finally
110 IdentifierInfo *Ident__abnormal_termination,
111 *Ident___abnormal_termination,
112 *Ident_AbnormalTermination;
113
114 /// Contextual keywords for Microsoft extensions.
115 IdentifierInfo *Ident__except;
116 mutable IdentifierInfo *Ident_sealed;
117 mutable IdentifierInfo *Ident_abstract;
118
119 /// Ident_super - IdentifierInfo for "super", to support fast
120 /// comparison.
121 IdentifierInfo *Ident_super;
122 /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
123 /// and "bool" fast comparison. Only present if AltiVec or ZVector are
124 /// enabled.
125 IdentifierInfo *Ident_vector;
126 IdentifierInfo *Ident_bool;
127 IdentifierInfo *Ident_Bool;
128 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
129 /// Only present if AltiVec enabled.
130 IdentifierInfo *Ident_pixel;
131
132 /// Objective-C contextual keywords.
133 IdentifierInfo *Ident_instancetype;
134
135 /// Identifier for "introduced".
136 IdentifierInfo *Ident_introduced;
137
138 /// Identifier for "deprecated".
139 IdentifierInfo *Ident_deprecated;
140
141 /// Identifier for "obsoleted".
142 IdentifierInfo *Ident_obsoleted;
143
144 /// Identifier for "unavailable".
145 IdentifierInfo *Ident_unavailable;
146
147 /// Identifier for "message".
148 IdentifierInfo *Ident_message;
149
150 /// Identifier for "strict".
151 IdentifierInfo *Ident_strict;
152
153 /// Identifier for "replacement".
154 IdentifierInfo *Ident_replacement;
155
156 /// Identifier for "environment".
157 IdentifierInfo *Ident_environment;
158
159 /// Identifiers used by the 'external_source_symbol' attribute.
160 IdentifierInfo *Ident_language, *Ident_defined_in,
161 *Ident_generated_declaration, *Ident_USR;
162
163 /// C++11 contextual keywords.
164 mutable IdentifierInfo *Ident_final;
165 mutable IdentifierInfo *Ident_GNU_final;
166 mutable IdentifierInfo *Ident_override;
167
168 // C++2a contextual keywords.
169 mutable IdentifierInfo *Ident_import;
170 mutable IdentifierInfo *Ident_module;
171
172 // C++ type trait keywords that can be reverted to identifiers and still be
173 // used as type traits.
174 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
175
176 std::unique_ptr<PragmaHandler> AlignHandler;
177 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
178 std::unique_ptr<PragmaHandler> OptionsHandler;
179 std::unique_ptr<PragmaHandler> PackHandler;
180 std::unique_ptr<PragmaHandler> MSStructHandler;
181 std::unique_ptr<PragmaHandler> UnusedHandler;
182 std::unique_ptr<PragmaHandler> WeakHandler;
183 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
184 std::unique_ptr<PragmaHandler> FPContractHandler;
185 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
186 std::unique_ptr<PragmaHandler> OpenMPHandler;
187 std::unique_ptr<PragmaHandler> OpenACCHandler;
188 std::unique_ptr<PragmaHandler> PCSectionHandler;
189 std::unique_ptr<PragmaHandler> MSCommentHandler;
190 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
191 std::unique_ptr<PragmaHandler> FPEvalMethodHandler;
192 std::unique_ptr<PragmaHandler> FloatControlHandler;
193 std::unique_ptr<PragmaHandler> MSPointersToMembers;
194 std::unique_ptr<PragmaHandler> MSVtorDisp;
195 std::unique_ptr<PragmaHandler> MSInitSeg;
196 std::unique_ptr<PragmaHandler> MSDataSeg;
197 std::unique_ptr<PragmaHandler> MSBSSSeg;
198 std::unique_ptr<PragmaHandler> MSConstSeg;
199 std::unique_ptr<PragmaHandler> MSCodeSeg;
200 std::unique_ptr<PragmaHandler> MSSection;
201 std::unique_ptr<PragmaHandler> MSStrictGuardStackCheck;
202 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
203 std::unique_ptr<PragmaHandler> MSIntrinsic;
204 std::unique_ptr<PragmaHandler> MSFunction;
205 std::unique_ptr<PragmaHandler> MSOptimize;
206 std::unique_ptr<PragmaHandler> MSFenvAccess;
207 std::unique_ptr<PragmaHandler> MSAllocText;
208 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
209 std::unique_ptr<PragmaHandler> OptimizeHandler;
210 std::unique_ptr<PragmaHandler> LoopHintHandler;
211 std::unique_ptr<PragmaHandler> UnrollHintHandler;
212 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
213 std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
214 std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
215 std::unique_ptr<PragmaHandler> FPHandler;
216 std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
217 std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
218 std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
219 std::unique_ptr<PragmaHandler> STDCUnknownHandler;
220 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
221 std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
222 std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
223 std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
224
225 std::unique_ptr<CommentHandler> CommentSemaHandler;
226
227 /// Whether the '>' token acts as an operator or not. This will be
228 /// true except when we are parsing an expression within a C++
229 /// template argument list, where the '>' closes the template
230 /// argument list.
231 bool GreaterThanIsOperator;
232
233 /// ColonIsSacred - When this is false, we aggressively try to recover from
234 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
235 /// safe in case statements and a few other things. This is managed by the
236 /// ColonProtectionRAIIObject RAII object.
237 bool ColonIsSacred;
238
239 /// Parsing OpenMP directive mode.
240 bool OpenMPDirectiveParsing = false;
241
242 /// Parsing OpenACC directive mode.
243 bool OpenACCDirectiveParsing = false;
244
245 /// Currently parsing a situation where an OpenACC array section could be
246 /// legal, such as a 'var-list'.
247 bool AllowOpenACCArraySections = false;
248
249 /// RAII object to set reset OpenACC parsing a context where Array Sections
250 /// are allowed.
251 class OpenACCArraySectionRAII {
252 Parser &P;
253
254 public:
255 OpenACCArraySectionRAII(Parser &P) : P(P) {
256 assert(!P.AllowOpenACCArraySections);
257 P.AllowOpenACCArraySections = true;
258 }
259 ~OpenACCArraySectionRAII() {
260 assert(P.AllowOpenACCArraySections);
261 P.AllowOpenACCArraySections = false;
262 }
263 };
264
265 /// When true, we are directly inside an Objective-C message
266 /// send expression.
267 ///
268 /// This is managed by the \c InMessageExpressionRAIIObject class, and
269 /// should not be set directly.
270 bool InMessageExpression;
271
272 /// Gets set to true after calling ProduceSignatureHelp, it is for a
273 /// workaround to make sure ProduceSignatureHelp is only called at the deepest
274 /// function call.
275 bool CalledSignatureHelp = false;
276
278
279 /// The "depth" of the template parameters currently being parsed.
280 unsigned TemplateParameterDepth;
281
282 /// Current kind of OpenMP clause
283 OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
284
285 /// RAII class that manages the template parameter depth.
286 class TemplateParameterDepthRAII {
287 unsigned &Depth;
288 unsigned AddedLevels;
289 public:
290 explicit TemplateParameterDepthRAII(unsigned &Depth)
291 : Depth(Depth), AddedLevels(0) {}
292
293 ~TemplateParameterDepthRAII() {
294 Depth -= AddedLevels;
295 }
296
297 void operator++() {
298 ++Depth;
299 ++AddedLevels;
300 }
301 void addDepth(unsigned D) {
302 Depth += D;
303 AddedLevels += D;
304 }
305 void setAddedDepth(unsigned D) {
306 Depth = Depth - AddedLevels + D;
307 AddedLevels = D;
308 }
309
310 unsigned getDepth() const { return Depth; }
311 unsigned getOriginalDepth() const { return Depth - AddedLevels; }
312 };
313
314 /// Factory object for creating ParsedAttr objects.
315 AttributeFactory AttrFactory;
316
317 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
318 /// top-level declaration is finished.
319 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
320
321 /// Don't destroy template annotations in MaybeDestroyTemplateIds even if
322 /// we're at the end of a declaration. Instead, we defer the destruction until
323 /// after a top-level declaration.
324 /// Use DelayTemplateIdDestructionRAII rather than setting it directly.
325 bool DelayTemplateIdDestruction = false;
326
327 void MaybeDestroyTemplateIds() {
328 if (DelayTemplateIdDestruction)
329 return;
330 if (!TemplateIds.empty() &&
331 (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
332 DestroyTemplateIds();
333 }
334 void DestroyTemplateIds();
335
336 /// RAII object to destroy TemplateIdAnnotations where possible, from a
337 /// likely-good position during parsing.
338 struct DestroyTemplateIdAnnotationsRAIIObj {
339 Parser &Self;
340
341 DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
342 ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
343 };
344
345 struct DelayTemplateIdDestructionRAII {
346 Parser &Self;
347 bool PrevDelayTemplateIdDestruction;
348
349 DelayTemplateIdDestructionRAII(Parser &Self,
350 bool DelayTemplateIdDestruction) noexcept
351 : Self(Self),
352 PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) {
353 Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction;
354 }
355
356 ~DelayTemplateIdDestructionRAII() noexcept {
357 Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction;
358 }
359 };
360
361 /// Identifiers which have been declared within a tentative parse.
362 SmallVector<const IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
363
364 /// Tracker for '<' tokens that might have been intended to be treated as an
365 /// angle bracket instead of a less-than comparison.
366 ///
367 /// This happens when the user intends to form a template-id, but typoes the
368 /// template-name or forgets a 'template' keyword for a dependent template
369 /// name.
370 ///
371 /// We track these locations from the point where we see a '<' with a
372 /// name-like expression on its left until we see a '>' or '>>' that might
373 /// match it.
374 struct AngleBracketTracker {
375 /// Flags used to rank candidate template names when there is more than one
376 /// '<' in a scope.
377 enum Priority : unsigned short {
378 /// A non-dependent name that is a potential typo for a template name.
379 PotentialTypo = 0x0,
380 /// A dependent name that might instantiate to a template-name.
381 DependentName = 0x2,
382
383 /// A space appears before the '<' token.
384 SpaceBeforeLess = 0x0,
385 /// No space before the '<' token
386 NoSpaceBeforeLess = 0x1,
387
388 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
389 };
390
391 struct Loc {
394 AngleBracketTracker::Priority Priority;
396
397 bool isActive(Parser &P) const {
398 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
399 P.BraceCount == BraceCount;
400 }
401
402 bool isActiveOrNested(Parser &P) const {
403 return isActive(P) || P.ParenCount > ParenCount ||
404 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
405 }
406 };
407
409
410 /// Add an expression that might have been intended to be a template name.
411 /// In the case of ambiguity, we arbitrarily select the innermost such
412 /// expression, for example in 'foo < bar < baz', 'bar' is the current
413 /// candidate. No attempt is made to track that 'foo' is also a candidate
414 /// for the case where we see a second suspicious '>' token.
415 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
416 Priority Prio) {
417 if (!Locs.empty() && Locs.back().isActive(P)) {
418 if (Locs.back().Priority <= Prio) {
419 Locs.back().TemplateName = TemplateName;
420 Locs.back().LessLoc = LessLoc;
421 Locs.back().Priority = Prio;
422 }
423 } else {
424 Locs.push_back({TemplateName, LessLoc, Prio,
425 P.ParenCount, P.BracketCount, P.BraceCount});
426 }
427 }
428
429 /// Mark the current potential missing template location as having been
430 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
431 /// or leave a bracket scope).
432 void clear(Parser &P) {
433 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
434 Locs.pop_back();
435 }
436
437 /// Get the current enclosing expression that might hve been intended to be
438 /// a template name.
439 Loc *getCurrent(Parser &P) {
440 if (!Locs.empty() && Locs.back().isActive(P))
441 return &Locs.back();
442 return nullptr;
443 }
444 };
445
446 AngleBracketTracker AngleBrackets;
447
448 IdentifierInfo *getSEHExceptKeyword();
449
450 /// True if we are within an Objective-C container while parsing C-like decls.
451 ///
452 /// This is necessary because Sema thinks we have left the container
453 /// to parse the C-like decls, meaning Actions.ObjC().getObjCDeclContext()
454 /// will be NULL.
455 bool ParsingInObjCContainer;
456
457 /// Whether to skip parsing of function bodies.
458 ///
459 /// This option can be used, for example, to speed up searches for
460 /// declarations/definitions when indexing.
461 bool SkipFunctionBodies;
462
463 /// The location of the expression statement that is being parsed right now.
464 /// Used to determine if an expression that is being parsed is a statement or
465 /// just a regular sub-expression.
466 SourceLocation ExprStatementTokLoc;
467
468 /// Flags describing a context in which we're parsing a statement.
469 enum class ParsedStmtContext {
470 /// This context permits declarations in language modes where declarations
471 /// are not statements.
472 AllowDeclarationsInC = 0x1,
473 /// This context permits standalone OpenMP directives.
474 AllowStandaloneOpenMPDirectives = 0x2,
475 /// This context is at the top level of a GNU statement expression.
476 InStmtExpr = 0x4,
477
478 /// The context of a regular substatement.
479 SubStmt = 0,
480 /// The context of a compound-statement.
481 Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
482
483 LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
484 };
485
486 /// Act on an expression statement that might be the last statement in a
487 /// GNU statement expression. Checks whether we are actually at the end of
488 /// a statement expression and builds a suitable expression statement.
489 StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
490
491public:
492 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
493 ~Parser() override;
494
495 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
496 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
497 Preprocessor &getPreprocessor() const { return PP; }
498 Sema &getActions() const { return Actions; }
499 AttributeFactory &getAttrFactory() { return AttrFactory; }
500
501 const Token &getCurToken() const { return Tok; }
502 Scope *getCurScope() const { return Actions.getCurScope(); }
504 return Actions.incrementMSManglingNumber();
505 }
506
508 return Actions.ObjC().getObjCDeclContext();
509 }
510
511 // Type forwarding. All of these are statically 'void*', but they may all be
512 // different actual classes based on the actions in place.
515
517
519
520 /// A SmallVector of statements.
522
523 // Parsing methods.
524
525 /// Initialize - Warm up the parser.
526 ///
527 void Initialize();
528
529 /// Parse the first top-level declaration in a translation unit.
531 Sema::ModuleImportState &ImportState);
532
533 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
534 /// the EOF was encountered.
536 Sema::ModuleImportState &ImportState);
540 return ParseTopLevelDecl(Result, IS);
541 }
542
543 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
544 /// This does not work with special tokens: string literals, code completion,
545 /// annotation tokens and balanced tokens must be handled using the specific
546 /// consume methods.
547 /// Returns the location of the consumed token.
549 assert(!isTokenSpecial() &&
550 "Should consume special tokens with Consume*Token");
551 PrevTokLocation = Tok.getLocation();
552 PP.Lex(Tok);
553 return PrevTokLocation;
554 }
555
557 if (Tok.isNot(Expected))
558 return false;
559 assert(!isTokenSpecial() &&
560 "Should consume special tokens with Consume*Token");
561 PrevTokLocation = Tok.getLocation();
562 PP.Lex(Tok);
563 return true;
564 }
565
568 return false;
569 Loc = PrevTokLocation;
570 return true;
571 }
572
573 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
574 /// current token type. This should only be used in cases where the type of
575 /// the token really isn't known, e.g. in error recovery.
576 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
577 if (isTokenParen())
578 return ConsumeParen();
579 if (isTokenBracket())
580 return ConsumeBracket();
581 if (isTokenBrace())
582 return ConsumeBrace();
583 if (isTokenStringLiteral())
584 return ConsumeStringToken();
585 if (Tok.is(tok::code_completion))
586 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
587 : handleUnexpectedCodeCompletionToken();
588 if (Tok.isAnnotation())
589 return ConsumeAnnotationToken();
590 return ConsumeToken();
591 }
592
593
595 return PP.getLocForEndOfToken(PrevTokLocation);
596 }
597
598 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
599 /// to the given nullability kind.
601 return Actions.getNullabilityKeyword(nullability);
602 }
603
604private:
605 //===--------------------------------------------------------------------===//
606 // Low-Level token peeking and consumption methods.
607 //
608
609 /// isTokenParen - Return true if the cur token is '(' or ')'.
610 bool isTokenParen() const {
611 return Tok.isOneOf(tok::l_paren, tok::r_paren);
612 }
613 /// isTokenBracket - Return true if the cur token is '[' or ']'.
614 bool isTokenBracket() const {
615 return Tok.isOneOf(tok::l_square, tok::r_square);
616 }
617 /// isTokenBrace - Return true if the cur token is '{' or '}'.
618 bool isTokenBrace() const {
619 return Tok.isOneOf(tok::l_brace, tok::r_brace);
620 }
621 /// isTokenStringLiteral - True if this token is a string-literal.
622 bool isTokenStringLiteral() const {
623 return tok::isStringLiteral(Tok.getKind());
624 }
625 /// isTokenSpecial - True if this token requires special consumption methods.
626 bool isTokenSpecial() const {
627 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
628 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
629 }
630
631 /// Returns true if the current token is '=' or is a type of '='.
632 /// For typos, give a fixit to '='
633 bool isTokenEqualOrEqualTypo();
634
635 /// Return the current token to the token stream and make the given
636 /// token the current token.
637 void UnconsumeToken(Token &Consumed) {
638 Token Next = Tok;
639 PP.EnterToken(Consumed, /*IsReinject*/true);
640 PP.Lex(Tok);
641 PP.EnterToken(Next, /*IsReinject*/true);
642 }
643
644 SourceLocation ConsumeAnnotationToken() {
645 assert(Tok.isAnnotation() && "wrong consume method");
646 SourceLocation Loc = Tok.getLocation();
647 PrevTokLocation = Tok.getAnnotationEndLoc();
648 PP.Lex(Tok);
649 return Loc;
650 }
651
652 /// ConsumeParen - This consume method keeps the paren count up-to-date.
653 ///
654 SourceLocation ConsumeParen() {
655 assert(isTokenParen() && "wrong consume method");
656 if (Tok.getKind() == tok::l_paren)
657 ++ParenCount;
658 else if (ParenCount) {
659 AngleBrackets.clear(*this);
660 --ParenCount; // Don't let unbalanced )'s drive the count negative.
661 }
662 PrevTokLocation = Tok.getLocation();
663 PP.Lex(Tok);
664 return PrevTokLocation;
665 }
666
667 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
668 ///
669 SourceLocation ConsumeBracket() {
670 assert(isTokenBracket() && "wrong consume method");
671 if (Tok.getKind() == tok::l_square)
672 ++BracketCount;
673 else if (BracketCount) {
674 AngleBrackets.clear(*this);
675 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
676 }
677
678 PrevTokLocation = Tok.getLocation();
679 PP.Lex(Tok);
680 return PrevTokLocation;
681 }
682
683 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
684 ///
685 SourceLocation ConsumeBrace() {
686 assert(isTokenBrace() && "wrong consume method");
687 if (Tok.getKind() == tok::l_brace)
688 ++BraceCount;
689 else if (BraceCount) {
690 AngleBrackets.clear(*this);
691 --BraceCount; // Don't let unbalanced }'s drive the count negative.
692 }
693
694 PrevTokLocation = Tok.getLocation();
695 PP.Lex(Tok);
696 return PrevTokLocation;
697 }
698
699 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
700 /// and returning the token kind. This method is specific to strings, as it
701 /// handles string literal concatenation, as per C99 5.1.1.2, translation
702 /// phase #6.
703 SourceLocation ConsumeStringToken() {
704 assert(isTokenStringLiteral() &&
705 "Should only consume string literals with this method");
706 PrevTokLocation = Tok.getLocation();
707 PP.Lex(Tok);
708 return PrevTokLocation;
709 }
710
711 /// Consume the current code-completion token.
712 ///
713 /// This routine can be called to consume the code-completion token and
714 /// continue processing in special cases where \c cutOffParsing() isn't
715 /// desired, such as token caching or completion with lookahead.
716 SourceLocation ConsumeCodeCompletionToken() {
717 assert(Tok.is(tok::code_completion));
718 PrevTokLocation = Tok.getLocation();
719 PP.Lex(Tok);
720 return PrevTokLocation;
721 }
722
723 /// When we are consuming a code-completion token without having matched
724 /// specific position in the grammar, provide code-completion results based
725 /// on context.
726 ///
727 /// \returns the source location of the code-completion token.
728 SourceLocation handleUnexpectedCodeCompletionToken();
729
730 /// Abruptly cut off parsing; mainly used when we have reached the
731 /// code-completion point.
732 void cutOffParsing() {
735 // Cut off parsing by acting as if we reached the end-of-file.
736 Tok.setKind(tok::eof);
737 }
738
739 /// Determine if we're at the end of the file or at a transition
740 /// between modules.
741 bool isEofOrEom() {
743 return Kind == tok::eof || Kind == tok::annot_module_begin ||
744 Kind == tok::annot_module_end || Kind == tok::annot_module_include ||
745 Kind == tok::annot_repl_input_end;
746 }
747
748 /// Checks if the \p Level is valid for use in a fold expression.
749 bool isFoldOperator(prec::Level Level) const;
750
751 /// Checks if the \p Kind is a valid operator for fold expressions.
752 bool isFoldOperator(tok::TokenKind Kind) const;
753
754 /// Initialize all pragma handlers.
755 void initializePragmaHandlers();
756
757 /// Destroy and reset all pragma handlers.
758 void resetPragmaHandlers();
759
760 /// Handle the annotation token produced for #pragma unused(...)
761 void HandlePragmaUnused();
762
763 /// Handle the annotation token produced for
764 /// #pragma GCC visibility...
765 void HandlePragmaVisibility();
766
767 /// Handle the annotation token produced for
768 /// #pragma pack...
769 void HandlePragmaPack();
770
771 /// Handle the annotation token produced for
772 /// #pragma ms_struct...
773 void HandlePragmaMSStruct();
774
775 void HandlePragmaMSPointersToMembers();
776
777 void HandlePragmaMSVtorDisp();
778
779 void HandlePragmaMSPragma();
780 bool HandlePragmaMSSection(StringRef PragmaName,
781 SourceLocation PragmaLocation);
782 bool HandlePragmaMSSegment(StringRef PragmaName,
783 SourceLocation PragmaLocation);
784 bool HandlePragmaMSInitSeg(StringRef PragmaName,
785 SourceLocation PragmaLocation);
786 bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName,
787 SourceLocation PragmaLocation);
788 bool HandlePragmaMSFunction(StringRef PragmaName,
789 SourceLocation PragmaLocation);
790 bool HandlePragmaMSAllocText(StringRef PragmaName,
791 SourceLocation PragmaLocation);
792 bool HandlePragmaMSOptimize(StringRef PragmaName,
793 SourceLocation PragmaLocation);
794
795 /// Handle the annotation token produced for
796 /// #pragma align...
797 void HandlePragmaAlign();
798
799 /// Handle the annotation token produced for
800 /// #pragma clang __debug dump...
801 void HandlePragmaDump();
802
803 /// Handle the annotation token produced for
804 /// #pragma weak id...
805 void HandlePragmaWeak();
806
807 /// Handle the annotation token produced for
808 /// #pragma weak id = id...
809 void HandlePragmaWeakAlias();
810
811 /// Handle the annotation token produced for
812 /// #pragma redefine_extname...
813 void HandlePragmaRedefineExtname();
814
815 /// Handle the annotation token produced for
816 /// #pragma STDC FP_CONTRACT...
817 void HandlePragmaFPContract();
818
819 /// Handle the annotation token produced for
820 /// #pragma STDC FENV_ACCESS...
821 void HandlePragmaFEnvAccess();
822
823 /// Handle the annotation token produced for
824 /// #pragma STDC FENV_ROUND...
825 void HandlePragmaFEnvRound();
826
827 /// Handle the annotation token produced for
828 /// #pragma STDC CX_LIMITED_RANGE...
829 void HandlePragmaCXLimitedRange();
830
831 /// Handle the annotation token produced for
832 /// #pragma float_control
833 void HandlePragmaFloatControl();
834
835 /// \brief Handle the annotation token produced for
836 /// #pragma clang fp ...
837 void HandlePragmaFP();
838
839 /// Handle the annotation token produced for
840 /// #pragma OPENCL EXTENSION...
841 void HandlePragmaOpenCLExtension();
842
843 /// Handle the annotation token produced for
844 /// #pragma clang __debug captured
845 StmtResult HandlePragmaCaptured();
846
847 /// Handle the annotation token produced for
848 /// #pragma clang loop and #pragma unroll.
849 bool HandlePragmaLoopHint(LoopHint &Hint);
850
851 bool ParsePragmaAttributeSubjectMatchRuleSet(
852 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
853 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
854
855 void HandlePragmaAttribute();
856
857 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
858 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
859 /// returns the token after Tok, etc.
860 ///
861 /// Note that this differs from the Preprocessor's LookAhead method, because
862 /// the Parser always has one token lexed that the preprocessor doesn't.
863 ///
864 const Token &GetLookAheadToken(unsigned N) {
865 if (N == 0 || Tok.is(tok::eof)) return Tok;
866 return PP.LookAhead(N-1);
867 }
868
869public:
870 /// NextToken - This peeks ahead one token and returns it without
871 /// consuming it.
872 const Token &NextToken() {
873 return PP.LookAhead(0);
874 }
875
876 /// getTypeAnnotation - Read a parsed type out of an annotation token.
877 static TypeResult getTypeAnnotation(const Token &Tok) {
878 if (!Tok.getAnnotationValue())
879 return TypeError();
881 }
882
883private:
884 static void setTypeAnnotation(Token &Tok, TypeResult T) {
885 assert((T.isInvalid() || T.get()) &&
886 "produced a valid-but-null type annotation?");
887 Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr());
888 }
889
890 static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
891 return static_cast<NamedDecl*>(Tok.getAnnotationValue());
892 }
893
894 static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
895 Tok.setAnnotationValue(ND);
896 }
897
898 static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
899 return static_cast<IdentifierInfo*>(Tok.getAnnotationValue());
900 }
901
902 static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
903 Tok.setAnnotationValue(ND);
904 }
905
906 /// Read an already-translated primary expression out of an annotation
907 /// token.
908 static ExprResult getExprAnnotation(const Token &Tok) {
909 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
910 }
911
912 /// Set the primary expression corresponding to the given annotation
913 /// token.
914 static void setExprAnnotation(Token &Tok, ExprResult ER) {
915 Tok.setAnnotationValue(ER.getAsOpaquePointer());
916 }
917
918public:
919 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
920 // find a type name by attempting typo correction.
921 bool
925 CXXScopeSpec &SS, bool IsNewScope,
926 ImplicitTypenameContext AllowImplicitTypename);
927 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
928
930 return getLangOpts().CPlusPlus &&
931 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
932 (Tok.is(tok::annot_template_id) &&
933 NextToken().is(tok::coloncolon)) ||
934 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super));
935 }
936 bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
937 return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
938 }
939
940private:
941 enum AnnotatedNameKind {
942 /// Annotation has failed and emitted an error.
943 ANK_Error,
944 /// The identifier is a tentatively-declared name.
945 ANK_TentativeDecl,
946 /// The identifier is a template name. FIXME: Add an annotation for that.
947 ANK_TemplateName,
948 /// The identifier can't be resolved.
949 ANK_Unresolved,
950 /// Annotation was successful.
951 ANK_Success
952 };
953
954 AnnotatedNameKind
955 TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr,
956 ImplicitTypenameContext AllowImplicitTypename =
958
959 /// Push a tok::annot_cxxscope token onto the token stream.
960 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
961
962 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
963 /// replacing them with the non-context-sensitive keywords. This returns
964 /// true if the token was replaced.
965 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
966 const char *&PrevSpec, unsigned &DiagID,
967 bool &isInvalid) {
968 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
969 return false;
970
971 if (Tok.getIdentifierInfo() != Ident_vector &&
972 Tok.getIdentifierInfo() != Ident_bool &&
973 Tok.getIdentifierInfo() != Ident_Bool &&
974 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
975 return false;
976
977 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
978 }
979
980 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
981 /// identifier token, replacing it with the non-context-sensitive __vector.
982 /// This returns true if the token was replaced.
983 bool TryAltiVecVectorToken() {
984 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
985 Tok.getIdentifierInfo() != Ident_vector) return false;
986 return TryAltiVecVectorTokenOutOfLine();
987 }
988
989 bool TryAltiVecVectorTokenOutOfLine();
990 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
991 const char *&PrevSpec, unsigned &DiagID,
992 bool &isInvalid);
993
994 /// Returns true if the current token is the identifier 'instancetype'.
995 ///
996 /// Should only be used in Objective-C language modes.
997 bool isObjCInstancetype() {
998 assert(getLangOpts().ObjC);
999 if (Tok.isAnnotation())
1000 return false;
1001 if (!Ident_instancetype)
1002 Ident_instancetype = PP.getIdentifierInfo("instancetype");
1003 return Tok.getIdentifierInfo() == Ident_instancetype;
1004 }
1005
1006 /// TryKeywordIdentFallback - For compatibility with system headers using
1007 /// keywords as identifiers, attempt to convert the current token to an
1008 /// identifier and optionally disable the keyword for the remainder of the
1009 /// translation unit. This returns false if the token was not replaced,
1010 /// otherwise emits a diagnostic and returns true.
1011 bool TryKeywordIdentFallback(bool DisableKeyword);
1012
1013 /// Get the TemplateIdAnnotation from the token.
1014 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
1015
1016 /// TentativeParsingAction - An object that is used as a kind of "tentative
1017 /// parsing transaction". It gets instantiated to mark the token position and
1018 /// after the token consumption is done, Commit() or Revert() is called to
1019 /// either "commit the consumed tokens" or revert to the previously marked
1020 /// token position. Example:
1021 ///
1022 /// TentativeParsingAction TPA(*this);
1023 /// ConsumeToken();
1024 /// ....
1025 /// TPA.Revert();
1026 ///
1027 /// If the Unannotated parameter is true, any token annotations created
1028 /// during the tentative parse are reverted.
1029 class TentativeParsingAction {
1030 Parser &P;
1031 PreferredTypeBuilder PrevPreferredType;
1032 Token PrevTok;
1033 size_t PrevTentativelyDeclaredIdentifierCount;
1034 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
1035 bool isActive;
1036
1037 public:
1038 explicit TentativeParsingAction(Parser &p, bool Unannotated = false)
1039 : P(p), PrevPreferredType(P.PreferredType) {
1040 PrevTok = P.Tok;
1041 PrevTentativelyDeclaredIdentifierCount =
1042 P.TentativelyDeclaredIdentifiers.size();
1043 PrevParenCount = P.ParenCount;
1044 PrevBracketCount = P.BracketCount;
1045 PrevBraceCount = P.BraceCount;
1046 P.PP.EnableBacktrackAtThisPos(Unannotated);
1047 isActive = true;
1048 }
1049 void Commit() {
1050 assert(isActive && "Parsing action was finished!");
1051 P.TentativelyDeclaredIdentifiers.resize(
1052 PrevTentativelyDeclaredIdentifierCount);
1053 P.PP.CommitBacktrackedTokens();
1054 isActive = false;
1055 }
1056 void Revert() {
1057 assert(isActive && "Parsing action was finished!");
1058 P.PP.Backtrack();
1059 P.PreferredType = PrevPreferredType;
1060 P.Tok = PrevTok;
1061 P.TentativelyDeclaredIdentifiers.resize(
1062 PrevTentativelyDeclaredIdentifierCount);
1063 P.ParenCount = PrevParenCount;
1064 P.BracketCount = PrevBracketCount;
1065 P.BraceCount = PrevBraceCount;
1066 isActive = false;
1067 }
1068 ~TentativeParsingAction() {
1069 assert(!isActive && "Forgot to call Commit or Revert!");
1070 }
1071 };
1072 /// A TentativeParsingAction that automatically reverts in its destructor.
1073 /// Useful for disambiguation parses that will always be reverted.
1074 class RevertingTentativeParsingAction
1075 : private Parser::TentativeParsingAction {
1076 public:
1077 using TentativeParsingAction::TentativeParsingAction;
1078
1079 ~RevertingTentativeParsingAction() { Revert(); }
1080 };
1081
1082 /// ObjCDeclContextSwitch - An object used to switch context from
1083 /// an objective-c decl context to its enclosing decl context and
1084 /// back.
1085 class ObjCDeclContextSwitch {
1086 Parser &P;
1087 ObjCContainerDecl *DC;
1088 SaveAndRestore<bool> WithinObjCContainer;
1089 public:
1090 explicit ObjCDeclContextSwitch(Parser &p)
1091 : P(p), DC(p.getObjCDeclContext()),
1092 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
1093 if (DC)
1094 P.Actions.ObjC().ActOnObjCTemporaryExitContainerContext(DC);
1095 }
1096 ~ObjCDeclContextSwitch() {
1097 if (DC)
1098 P.Actions.ObjC().ActOnObjCReenterContainerContext(DC);
1099 }
1100 };
1101
1102 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
1103 /// input. If so, it is consumed and false is returned.
1104 ///
1105 /// If a trivial punctuator misspelling is encountered, a FixIt error
1106 /// diagnostic is issued and false is returned after recovery.
1107 ///
1108 /// If the input is malformed, this emits the specified diagnostic and true is
1109 /// returned.
1110 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
1111 unsigned Diag = diag::err_expected,
1112 StringRef DiagMsg = "");
1113
1114 /// The parser expects a semicolon and, if present, will consume it.
1115 ///
1116 /// If the next token is not a semicolon, this emits the specified diagnostic,
1117 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
1118 /// to the semicolon, consumes that extra token.
1119 bool ExpectAndConsumeSemi(unsigned DiagID , StringRef TokenUsed = "");
1120
1121 /// The kind of extra semi diagnostic to emit.
1122 enum ExtraSemiKind {
1123 OutsideFunction = 0,
1124 InsideStruct = 1,
1125 InstanceVariableList = 2,
1126 AfterMemberFunctionDefinition = 3
1127 };
1128
1129 /// Consume any extra semi-colons until the end of the line.
1130 void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
1131
1132 /// Return false if the next token is an identifier. An 'expected identifier'
1133 /// error is emitted otherwise.
1134 ///
1135 /// The parser tries to recover from the error by checking if the next token
1136 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
1137 /// was successful.
1138 bool expectIdentifier();
1139
1140 /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
1141 enum class CompoundToken {
1142 /// A '(' '{' beginning a statement-expression.
1143 StmtExprBegin,
1144 /// A '}' ')' ending a statement-expression.
1145 StmtExprEnd,
1146 /// A '[' '[' beginning a C++11 or C23 attribute.
1147 AttrBegin,
1148 /// A ']' ']' ending a C++11 or C23 attribute.
1149 AttrEnd,
1150 /// A '::' '*' forming a C++ pointer-to-member declaration.
1151 MemberPtr,
1152 };
1153
1154 /// Check that a compound operator was written in a "sensible" way, and warn
1155 /// if not.
1156 void checkCompoundToken(SourceLocation FirstTokLoc,
1157 tok::TokenKind FirstTokKind, CompoundToken Op);
1158
1159 void diagnoseUseOfC11Keyword(const Token &Tok);
1160
1161public:
1162 //===--------------------------------------------------------------------===//
1163 // Scope manipulation
1164
1165 /// ParseScope - Introduces a new scope for parsing. The kind of
1166 /// scope is determined by ScopeFlags. Objects of this type should
1167 /// be created on the stack to coincide with the position where the
1168 /// parser enters the new scope, and this object's constructor will
1169 /// create that new scope. Similarly, once the object is destroyed
1170 /// the parser will exit the scope.
1172 Parser *Self;
1173 ParseScope(const ParseScope &) = delete;
1174 void operator=(const ParseScope &) = delete;
1175
1176 public:
1177 // ParseScope - Construct a new object to manage a scope in the
1178 // parser Self where the new Scope is created with the flags
1179 // ScopeFlags, but only when we aren't about to enter a compound statement.
1180 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
1181 bool BeforeCompoundStmt = false)
1182 : Self(Self) {
1183 if (EnteredScope && !BeforeCompoundStmt)
1184 Self->EnterScope(ScopeFlags);
1185 else {
1186 if (BeforeCompoundStmt)
1187 Self->incrementMSManglingNumber();
1188
1189 this->Self = nullptr;
1190 }
1191 }
1192
1193 // Exit - Exit the scope associated with this object now, rather
1194 // than waiting until the object is destroyed.
1195 void Exit() {
1196 if (Self) {
1197 Self->ExitScope();
1198 Self = nullptr;
1199 }
1200 }
1201
1203 Exit();
1204 }
1205 };
1206
1207 /// Introduces zero or more scopes for parsing. The scopes will all be exited
1208 /// when the object is destroyed.
1210 Parser &Self;
1211 unsigned NumScopes = 0;
1212
1213 MultiParseScope(const MultiParseScope&) = delete;
1214
1215 public:
1216 MultiParseScope(Parser &Self) : Self(Self) {}
1217 void Enter(unsigned ScopeFlags) {
1218 Self.EnterScope(ScopeFlags);
1219 ++NumScopes;
1220 }
1221 void Exit() {
1222 while (NumScopes) {
1223 Self.ExitScope();
1224 --NumScopes;
1225 }
1226 }
1228 Exit();
1229 }
1230 };
1231
1232 /// EnterScope - Start a new scope.
1233 void EnterScope(unsigned ScopeFlags);
1234
1235 /// ExitScope - Pop a scope off the scope stack.
1236 void ExitScope();
1237
1238 /// Re-enter the template scopes for a declaration that might be a template.
1239 unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D);
1240
1241private:
1242 /// RAII object used to modify the scope flags for the current scope.
1243 class ParseScopeFlags {
1244 Scope *CurScope;
1245 unsigned OldFlags = 0;
1246 ParseScopeFlags(const ParseScopeFlags &) = delete;
1247 void operator=(const ParseScopeFlags &) = delete;
1248
1249 public:
1250 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
1251 ~ParseScopeFlags();
1252 };
1253
1254 //===--------------------------------------------------------------------===//
1255 // Diagnostic Emission and Error recovery.
1256
1257public:
1258 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1259 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
1260 DiagnosticBuilder Diag(unsigned DiagID) {
1261 return Diag(Tok, DiagID);
1262 }
1263
1264private:
1265 void SuggestParentheses(SourceLocation Loc, unsigned DK,
1266 SourceRange ParenRange);
1267 void CheckNestedObjCContexts(SourceLocation AtLoc);
1268
1269public:
1270
1271 /// Control flags for SkipUntil functions.
1273 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
1274 /// Stop skipping at specified token, but don't skip the token itself
1276 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
1278
1280 SkipUntilFlags R) {
1281 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
1282 static_cast<unsigned>(R));
1283 }
1284
1285 /// SkipUntil - Read tokens until we get to the specified token, then consume
1286 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
1287 /// that the token will ever occur, this skips to the next token, or to some
1288 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
1289 /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
1290 /// skipping.
1291 ///
1292 /// If SkipUntil finds the specified token, it returns true, otherwise it
1293 /// returns false.
1295 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1296 return SkipUntil(llvm::ArrayRef(T), Flags);
1297 }
1299 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1300 tok::TokenKind TokArray[] = {T1, T2};
1301 return SkipUntil(TokArray, Flags);
1302 }
1304 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1305 tok::TokenKind TokArray[] = {T1, T2, T3};
1306 return SkipUntil(TokArray, Flags);
1307 }
1309 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
1310
1311 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1312 /// point for skipping past a simple-declaration.
1313 void SkipMalformedDecl();
1314
1315 /// The location of the first statement inside an else that might
1316 /// have a missleading indentation. If there is no
1317 /// MisleadingIndentationChecker on an else active, this location is invalid.
1319
1320private:
1321 //===--------------------------------------------------------------------===//
1322 // Lexing and parsing of C++ inline methods.
1323
1324 struct ParsingClass;
1325
1326 /// [class.mem]p1: "... the class is regarded as complete within
1327 /// - function bodies
1328 /// - default arguments
1329 /// - exception-specifications (TODO: C++0x)
1330 /// - and brace-or-equal-initializers for non-static data members
1331 /// (including such things in nested classes)."
1332 /// LateParsedDeclarations build the tree of those elements so they can
1333 /// be parsed after parsing the top-level class.
1334 class LateParsedDeclaration {
1335 public:
1336 virtual ~LateParsedDeclaration();
1337
1338 virtual void ParseLexedMethodDeclarations();
1339 virtual void ParseLexedMemberInitializers();
1340 virtual void ParseLexedMethodDefs();
1341 virtual void ParseLexedAttributes();
1342 virtual void ParseLexedPragmas();
1343 };
1344
1345 /// Inner node of the LateParsedDeclaration tree that parses
1346 /// all its members recursively.
1347 class LateParsedClass : public LateParsedDeclaration {
1348 public:
1349 LateParsedClass(Parser *P, ParsingClass *C);
1350 ~LateParsedClass() override;
1351
1352 void ParseLexedMethodDeclarations() override;
1353 void ParseLexedMemberInitializers() override;
1354 void ParseLexedMethodDefs() override;
1355 void ParseLexedAttributes() override;
1356 void ParseLexedPragmas() override;
1357
1358 private:
1359 Parser *Self;
1360 ParsingClass *Class;
1361 };
1362
1363 /// Contains the lexed tokens of an attribute with arguments that
1364 /// may reference member variables and so need to be parsed at the
1365 /// end of the class declaration after parsing all other member
1366 /// member declarations.
1367 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1368 /// LateParsedTokens.
1369 struct LateParsedAttribute : public LateParsedDeclaration {
1370 Parser *Self;
1371 CachedTokens Toks;
1372 IdentifierInfo &AttrName;
1373 IdentifierInfo *MacroII = nullptr;
1374 SourceLocation AttrNameLoc;
1375 SmallVector<Decl*, 2> Decls;
1376
1377 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1378 SourceLocation Loc)
1379 : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1380
1381 void ParseLexedAttributes() override;
1382
1383 void addDecl(Decl *D) { Decls.push_back(D); }
1384 };
1385
1386 /// Contains the lexed tokens of a pragma with arguments that
1387 /// may reference member variables and so need to be parsed at the
1388 /// end of the class declaration after parsing all other member
1389 /// member declarations.
1390 class LateParsedPragma : public LateParsedDeclaration {
1391 Parser *Self = nullptr;
1393 CachedTokens Toks;
1394
1395 public:
1396 explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
1397 : Self(P), AS(AS) {}
1398
1399 void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
1400 const CachedTokens &toks() const { return Toks; }
1401 AccessSpecifier getAccessSpecifier() const { return AS; }
1402
1403 void ParseLexedPragmas() override;
1404 };
1405
1406 // A list of late-parsed attributes. Used by ParseGNUAttributes.
1407 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1408 public:
1409 LateParsedAttrList(bool PSoon = false,
1410 bool LateAttrParseExperimentalExtOnly = false)
1411 : ParseSoon(PSoon),
1412 LateAttrParseExperimentalExtOnly(LateAttrParseExperimentalExtOnly) {}
1413
1414 bool parseSoon() { return ParseSoon; }
1415 /// returns true iff the attribute to be parsed should only be late parsed
1416 /// if it is annotated with `LateAttrParseExperimentalExt`
1417 bool lateAttrParseExperimentalExtOnly() {
1418 return LateAttrParseExperimentalExtOnly;
1419 }
1420
1421 private:
1422 bool ParseSoon; // Are we planning to parse these shortly after creation?
1423 bool LateAttrParseExperimentalExtOnly;
1424 };
1425
1426 /// Contains the lexed tokens of a member function definition
1427 /// which needs to be parsed at the end of the class declaration
1428 /// after parsing all other member declarations.
1429 struct LexedMethod : public LateParsedDeclaration {
1430 Parser *Self;
1431 Decl *D;
1432 CachedTokens Toks;
1433
1434 explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
1435
1436 void ParseLexedMethodDefs() override;
1437 };
1438
1439 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1440 /// have a default argument that cannot be parsed yet because it
1441 /// occurs within a member function declaration inside the class
1442 /// (C++ [class.mem]p2).
1443 struct LateParsedDefaultArgument {
1444 explicit LateParsedDefaultArgument(Decl *P,
1445 std::unique_ptr<CachedTokens> Toks = nullptr)
1446 : Param(P), Toks(std::move(Toks)) { }
1447
1448 /// Param - The parameter declaration for this parameter.
1449 Decl *Param;
1450
1451 /// Toks - The sequence of tokens that comprises the default
1452 /// argument expression, not including the '=' or the terminating
1453 /// ')' or ','. This will be NULL for parameters that have no
1454 /// default argument.
1455 std::unique_ptr<CachedTokens> Toks;
1456 };
1457
1458 /// LateParsedMethodDeclaration - A method declaration inside a class that
1459 /// contains at least one entity whose parsing needs to be delayed
1460 /// until the class itself is completely-defined, such as a default
1461 /// argument (C++ [class.mem]p2).
1462 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1463 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1464 : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
1465
1466 void ParseLexedMethodDeclarations() override;
1467
1468 Parser *Self;
1469
1470 /// Method - The method declaration.
1471 Decl *Method;
1472
1473 /// DefaultArgs - Contains the parameters of the function and
1474 /// their default arguments. At least one of the parameters will
1475 /// have a default argument, but all of the parameters of the
1476 /// method will be stored so that they can be reintroduced into
1477 /// scope at the appropriate times.
1478 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1479
1480 /// The set of tokens that make up an exception-specification that
1481 /// has not yet been parsed.
1482 CachedTokens *ExceptionSpecTokens;
1483 };
1484
1485 /// LateParsedMemberInitializer - An initializer for a non-static class data
1486 /// member whose parsing must to be delayed until the class is completely
1487 /// defined (C++11 [class.mem]p2).
1488 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1489 LateParsedMemberInitializer(Parser *P, Decl *FD)
1490 : Self(P), Field(FD) { }
1491
1492 void ParseLexedMemberInitializers() override;
1493
1494 Parser *Self;
1495
1496 /// Field - The field declaration.
1497 Decl *Field;
1498
1499 /// CachedTokens - The sequence of tokens that comprises the initializer,
1500 /// including any leading '='.
1501 CachedTokens Toks;
1502 };
1503
1504 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1505 /// C++ class, its method declarations that contain parts that won't be
1506 /// parsed until after the definition is completed (C++ [class.mem]p2),
1507 /// the method declarations and possibly attached inline definitions
1508 /// will be stored here with the tokens that will be parsed to create those
1509 /// entities.
1510 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1511
1512 /// Representation of a class that has been parsed, including
1513 /// any member function declarations or definitions that need to be
1514 /// parsed after the corresponding top-level class is complete.
1515 struct ParsingClass {
1516 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1517 : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
1518 TagOrTemplate(TagOrTemplate) {}
1519
1520 /// Whether this is a "top-level" class, meaning that it is
1521 /// not nested within another class.
1522 bool TopLevelClass : 1;
1523
1524 /// Whether this class is an __interface.
1525 bool IsInterface : 1;
1526
1527 /// The class or class template whose definition we are parsing.
1528 Decl *TagOrTemplate;
1529
1530 /// LateParsedDeclarations - Method declarations, inline definitions and
1531 /// nested classes that contain pieces whose parsing will be delayed until
1532 /// the top-level class is fully defined.
1533 LateParsedDeclarationsContainer LateParsedDeclarations;
1534 };
1535
1536 /// The stack of classes that is currently being
1537 /// parsed. Nested and local classes will be pushed onto this stack
1538 /// when they are parsed, and removed afterward.
1539 std::stack<ParsingClass *> ClassStack;
1540
1541 ParsingClass &getCurrentClass() {
1542 assert(!ClassStack.empty() && "No lexed method stacks!");
1543 return *ClassStack.top();
1544 }
1545
1546 /// RAII object used to manage the parsing of a class definition.
1547 class ParsingClassDefinition {
1548 Parser &P;
1549 bool Popped;
1551
1552 public:
1553 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1554 bool IsInterface)
1555 : P(P), Popped(false),
1556 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1557 }
1558
1559 /// Pop this class of the stack.
1560 void Pop() {
1561 assert(!Popped && "Nested class has already been popped");
1562 Popped = true;
1563 P.PopParsingClass(State);
1564 }
1565
1566 ~ParsingClassDefinition() {
1567 if (!Popped)
1568 P.PopParsingClass(State);
1569 }
1570 };
1571
1572 /// Contains information about any template-specific
1573 /// information that has been parsed prior to parsing declaration
1574 /// specifiers.
1575 struct ParsedTemplateInfo {
1576 ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr) {}
1577
1578 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1579 bool isSpecialization,
1580 bool lastParameterListWasEmpty = false)
1581 : Kind(isSpecialization? ExplicitSpecialization : Template),
1582 TemplateParams(TemplateParams),
1583 LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1584
1585 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1586 SourceLocation TemplateLoc)
1587 : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1588 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1589 LastParameterListWasEmpty(false){ }
1590
1591 /// The kind of template we are parsing.
1592 enum {
1593 /// We are not parsing a template at all.
1594 NonTemplate = 0,
1595 /// We are parsing a template declaration.
1596 Template,
1597 /// We are parsing an explicit specialization.
1598 ExplicitSpecialization,
1599 /// We are parsing an explicit instantiation.
1600 ExplicitInstantiation
1601 } Kind;
1602
1603 /// The template parameter lists, for template declarations
1604 /// and explicit specializations.
1605 TemplateParameterLists *TemplateParams;
1606
1607 /// The location of the 'extern' keyword, if any, for an explicit
1608 /// instantiation
1609 SourceLocation ExternLoc;
1610
1611 /// The location of the 'template' keyword, for an explicit
1612 /// instantiation.
1613 SourceLocation TemplateLoc;
1614
1615 /// Whether the last template parameter list was empty.
1616 bool LastParameterListWasEmpty;
1617
1618 SourceRange getSourceRange() const LLVM_READONLY;
1619 };
1620
1621 // In ParseCXXInlineMethods.cpp.
1622 struct ReenterTemplateScopeRAII;
1623 struct ReenterClassScopeRAII;
1624
1625 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1626 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1627
1628 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1629
1630 Sema::ParsingClassState
1631 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1632 void DeallocateParsedClasses(ParsingClass *Class);
1633 void PopParsingClass(Sema::ParsingClassState);
1634
1635 enum CachedInitKind {
1636 CIK_DefaultArgument,
1637 CIK_DefaultInitializer
1638 };
1639
1640 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1641 const ParsedAttributesView &AccessAttrs,
1642 ParsingDeclarator &D,
1643 const ParsedTemplateInfo &TemplateInfo,
1644 const VirtSpecifiers &VS,
1645 SourceLocation PureSpecLoc);
1646 StringLiteral *ParseCXXDeletedFunctionMessage();
1647 void SkipDeletedFunctionBody();
1648 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1649 void ParseLexedAttributes(ParsingClass &Class);
1650 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1651 bool EnterScope, bool OnDefinition);
1652 void ParseLexedCAttributeList(LateParsedAttrList &LA, bool EnterScope,
1653 ParsedAttributes *OutAttrs = nullptr);
1654 void ParseLexedAttribute(LateParsedAttribute &LA,
1655 bool EnterScope, bool OnDefinition);
1656 void ParseLexedCAttribute(LateParsedAttribute &LA, bool EnterScope,
1657 ParsedAttributes *OutAttrs = nullptr);
1658 void ParseLexedMethodDeclarations(ParsingClass &Class);
1659 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1660 void ParseLexedMethodDefs(ParsingClass &Class);
1661 void ParseLexedMethodDef(LexedMethod &LM);
1662 void ParseLexedMemberInitializers(ParsingClass &Class);
1663 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1664 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1665 void ParseLexedPragmas(ParsingClass &Class);
1666 void ParseLexedPragma(LateParsedPragma &LP);
1667 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1668 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1669 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1670 bool ConsumeAndStoreUntil(tok::TokenKind T1,
1671 CachedTokens &Toks,
1672 bool StopAtSemi = true,
1673 bool ConsumeFinalToken = true) {
1674 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1675 }
1676 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1677 CachedTokens &Toks,
1678 bool StopAtSemi = true,
1679 bool ConsumeFinalToken = true);
1680
1681 //===--------------------------------------------------------------------===//
1682 // C99 6.9: External Definitions.
1683 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributes &DeclAttrs,
1684 ParsedAttributes &DeclSpecAttrs,
1685 ParsingDeclSpec *DS = nullptr);
1686 bool isDeclarationAfterDeclarator();
1687 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1688 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1689 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1690 ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none);
1691 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs,
1692 ParsedAttributes &DeclSpecAttrs,
1693 ParsingDeclSpec &DS,
1694 AccessSpecifier AS);
1695
1696 void SkipFunctionBody();
1697 Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1698 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1699 LateParsedAttrList *LateParsedAttrs = nullptr);
1700 void ParseKNRParamDeclarations(Declarator &D);
1701 // EndLoc is filled with the location of the last token of the simple-asm.
1702 ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
1703 ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
1704
1705 // Objective-C External Declarations
1706 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1707 DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
1708 ParsedAttributes &DeclSpecAttrs);
1709 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1710 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1711 ParsedAttributes &prefixAttrs);
1712 class ObjCTypeParamListScope;
1713 ObjCTypeParamList *parseObjCTypeParamList();
1714 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1715 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1716 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1717 SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1718
1719 void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl,
1720 SourceLocation atLoc,
1722 SmallVectorImpl<Decl *> &AllIvarDecls,
1723 bool RBraceMissing);
1724 void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
1725 tok::ObjCKeywordKind visibility,
1726 SourceLocation atLoc);
1727 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1728 SmallVectorImpl<SourceLocation> &PLocs,
1729 bool WarnOnDeclarations,
1730 bool ForObjCContainer,
1731 SourceLocation &LAngleLoc,
1732 SourceLocation &EndProtoLoc,
1733 bool consumeLastToken);
1734
1735 /// Parse the first angle-bracket-delimited clause for an
1736 /// Objective-C object or object pointer type, which may be either
1737 /// type arguments or protocol qualifiers.
1738 void parseObjCTypeArgsOrProtocolQualifiers(
1739 ParsedType baseType,
1740 SourceLocation &typeArgsLAngleLoc,
1741 SmallVectorImpl<ParsedType> &typeArgs,
1742 SourceLocation &typeArgsRAngleLoc,
1743 SourceLocation &protocolLAngleLoc,
1744 SmallVectorImpl<Decl *> &protocols,
1745 SmallVectorImpl<SourceLocation> &protocolLocs,
1746 SourceLocation &protocolRAngleLoc,
1747 bool consumeLastToken,
1748 bool warnOnIncompleteProtocols);
1749
1750 /// Parse either Objective-C type arguments or protocol qualifiers; if the
1751 /// former, also parse protocol qualifiers afterward.
1752 void parseObjCTypeArgsAndProtocolQualifiers(
1753 ParsedType baseType,
1754 SourceLocation &typeArgsLAngleLoc,
1755 SmallVectorImpl<ParsedType> &typeArgs,
1756 SourceLocation &typeArgsRAngleLoc,
1757 SourceLocation &protocolLAngleLoc,
1758 SmallVectorImpl<Decl *> &protocols,
1759 SmallVectorImpl<SourceLocation> &protocolLocs,
1760 SourceLocation &protocolRAngleLoc,
1761 bool consumeLastToken);
1762
1763 /// Parse a protocol qualifier type such as '<NSCopying>', which is
1764 /// an anachronistic way of writing 'id<NSCopying>'.
1765 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1766
1767 /// Parse Objective-C type arguments and protocol qualifiers, extending the
1768 /// current type with the parsed result.
1769 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1771 bool consumeLastToken,
1772 SourceLocation &endLoc);
1773
1774 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1775 Decl *CDecl);
1776 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1777 ParsedAttributes &prefixAttrs);
1778
1779 struct ObjCImplParsingDataRAII {
1780 Parser &P;
1781 Decl *Dcl;
1782 bool HasCFunction;
1783 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1784 LateParsedObjCMethodContainer LateParsedObjCMethods;
1785
1786 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1787 : P(parser), Dcl(D), HasCFunction(false) {
1788 P.CurParsedObjCImpl = this;
1789 Finished = false;
1790 }
1791 ~ObjCImplParsingDataRAII();
1792
1793 void finish(SourceRange AtEnd);
1794 bool isFinished() const { return Finished; }
1795
1796 private:
1797 bool Finished;
1798 };
1799 ObjCImplParsingDataRAII *CurParsedObjCImpl;
1800 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1801
1802 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
1803 ParsedAttributes &Attrs);
1804 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1805 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1806 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1807 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1808
1809 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1810 // Definitions for Objective-c context sensitive keywords recognition.
1811 enum ObjCTypeQual {
1812 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1813 objc_nonnull, objc_nullable, objc_null_unspecified,
1814 objc_NumQuals
1815 };
1816 IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1817
1818 bool isTokIdentifier_in() const;
1819
1820 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
1821 ParsedAttributes *ParamAttrs);
1822 Decl *ParseObjCMethodPrototype(
1823 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1824 bool MethodDefinition = true);
1825 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1826 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1827 bool MethodDefinition=true);
1828 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1829
1830 Decl *ParseObjCMethodDefinition();
1831
1832public:
1833 //===--------------------------------------------------------------------===//
1834 // C99 6.5: Expressions.
1835
1836 /// TypeCastState - State whether an expression is or may be a type cast.
1842
1845 TypeCastState isTypeCast = NotTypeCast);
1851 ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
1852 ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
1853 // Expr that doesn't include commas.
1856
1858 unsigned &NumLineToksConsumed,
1859 bool IsUnevaluated);
1860
1861 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1863
1864private:
1865 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral,
1866 bool Unevaluated);
1867
1868 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1869
1870 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1871
1872 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1873 prec::Level MinPrec);
1874 /// Control what ParseCastExpression will parse.
1875 enum CastParseKind {
1876 AnyCastExpr = 0,
1877 UnaryExprOnly,
1878 PrimaryExprOnly
1879 };
1880
1881 bool isRevertibleTypeTrait(const IdentifierInfo *Id,
1882 clang::tok::TokenKind *Kind = nullptr);
1883
1884 ExprResult ParseCastExpression(CastParseKind ParseKind,
1885 bool isAddressOfOperand,
1886 bool &NotCastExpr,
1887 TypeCastState isTypeCast,
1888 bool isVectorLiteral = false,
1889 bool *NotPrimaryExpression = nullptr);
1890 ExprResult ParseCastExpression(CastParseKind ParseKind,
1891 bool isAddressOfOperand = false,
1892 TypeCastState isTypeCast = NotTypeCast,
1893 bool isVectorLiteral = false,
1894 bool *NotPrimaryExpression = nullptr);
1895
1896 /// Returns true if the next token cannot start an expression.
1897 bool isNotExpressionStart();
1898
1899 /// Returns true if the next token would start a postfix-expression
1900 /// suffix.
1901 bool isPostfixExpressionSuffixStart() {
1902 tok::TokenKind K = Tok.getKind();
1903 return (K == tok::l_square || K == tok::l_paren ||
1904 K == tok::period || K == tok::arrow ||
1905 K == tok::plusplus || K == tok::minusminus);
1906 }
1907
1908 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1909 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
1910 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
1911 const Token &OpToken);
1912 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1913 if (auto *Info = AngleBrackets.getCurrent(*this))
1914 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1915 return false;
1916 }
1917
1918 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1919 ExprResult ParseUnaryExprOrTypeTraitExpression();
1920 ExprResult ParseBuiltinPrimaryExpression();
1921 ExprResult ParseSYCLUniqueStableNameExpression();
1922
1923 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1924 bool &isCastExpr,
1925 ParsedType &CastTy,
1926 SourceRange &CastRange);
1927
1928 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1929 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1930 llvm::function_ref<void()> ExpressionStarts =
1931 llvm::function_ref<void()>(),
1932 bool FailImmediatelyOnInvalidExpr = false,
1933 bool EarlyTypoCorrection = false);
1934
1935 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1936 /// used for misc language extensions.
1937 bool ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs);
1938
1939 /// ParenParseOption - Control what ParseParenExpression will parse.
1940 enum ParenParseOption {
1941 SimpleExpr, // Only parse '(' expression ')'
1942 FoldExpr, // Also allow fold-expression <anything>
1943 CompoundStmt, // Also allow '(' compound-statement ')'
1944 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1945 CastExpr // Also allow '(' type-name ')' <anything>
1946 };
1947 ExprResult ParseParenExpression(ParenParseOption &ExprType,
1948 bool stopIfCastExpr,
1949 bool isTypeCast,
1950 ParsedType &CastTy,
1951 SourceLocation &RParenLoc);
1952
1953 ExprResult ParseCXXAmbiguousParenExpression(
1954 ParenParseOption &ExprType, ParsedType &CastTy,
1956 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1957 SourceLocation LParenLoc,
1958 SourceLocation RParenLoc);
1959
1960 ExprResult ParseGenericSelectionExpression();
1961
1962 ExprResult ParseObjCBoolLiteral();
1963
1964 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1965
1966 //===--------------------------------------------------------------------===//
1967 // C++ Expressions
1968 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1969 Token &Replacement);
1970
1971 ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression);
1972 ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression);
1973
1974 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1975
1976 bool areTokensAdjacent(const Token &A, const Token &B);
1977
1978 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1979 bool EnteringContext, IdentifierInfo &II,
1980 CXXScopeSpec &SS);
1981
1982 bool ParseOptionalCXXScopeSpecifier(
1983 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors,
1984 bool EnteringContext, bool *MayBePseudoDestructor = nullptr,
1985 bool IsTypename = false, const IdentifierInfo **LastII = nullptr,
1986 bool OnlyNamespace = false, bool InUsingDeclaration = false,
1987 bool Disambiguation = false);
1988
1989 //===--------------------------------------------------------------------===//
1990 // C++11 5.1.2: Lambda expressions
1991
1992 /// Result of tentatively parsing a lambda-introducer.
1993 enum class LambdaIntroducerTentativeParse {
1994 /// This appears to be a lambda-introducer, which has been fully parsed.
1995 Success,
1996 /// This is a lambda-introducer, but has not been fully parsed, and this
1997 /// function needs to be called again to parse it.
1998 Incomplete,
1999 /// This is definitely an Objective-C message send expression, rather than
2000 /// a lambda-introducer, attribute-specifier, or array designator.
2001 MessageSend,
2002 /// This is not a lambda-introducer.
2003 Invalid,
2004 };
2005
2006 // [...] () -> type {...}
2007 ExprResult ParseLambdaExpression();
2008 ExprResult TryParseLambdaExpression();
2009 bool
2010 ParseLambdaIntroducer(LambdaIntroducer &Intro,
2011 LambdaIntroducerTentativeParse *Tentative = nullptr);
2012 ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
2013
2014 //===--------------------------------------------------------------------===//
2015 // C++ 5.2p1: C++ Casts
2016 ExprResult ParseCXXCasts();
2017
2018 /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
2019 ExprResult ParseBuiltinBitCast();
2020
2021 //===--------------------------------------------------------------------===//
2022 // C++ 5.2p1: C++ Type Identification
2023 ExprResult ParseCXXTypeid();
2024
2025 //===--------------------------------------------------------------------===//
2026 // C++ : Microsoft __uuidof Expression
2027 ExprResult ParseCXXUuidof();
2028
2029 //===--------------------------------------------------------------------===//
2030 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
2031 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
2032 tok::TokenKind OpKind,
2033 CXXScopeSpec &SS,
2034 ParsedType ObjectType);
2035
2036 //===--------------------------------------------------------------------===//
2037 // C++ 9.3.2: C++ 'this' pointer
2038 ExprResult ParseCXXThis();
2039
2040 //===--------------------------------------------------------------------===//
2041 // C++ 15: C++ Throw Expression
2042 ExprResult ParseThrowExpression();
2043
2044 ExceptionSpecificationType tryParseExceptionSpecification(
2045 bool Delayed,
2046 SourceRange &SpecificationRange,
2047 SmallVectorImpl<ParsedType> &DynamicExceptions,
2048 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2049 ExprResult &NoexceptExpr,
2050 CachedTokens *&ExceptionSpecTokens);
2051
2052 // EndLoc is filled with the location of the last token of the specification.
2053 ExceptionSpecificationType ParseDynamicExceptionSpecification(
2054 SourceRange &SpecificationRange,
2055 SmallVectorImpl<ParsedType> &Exceptions,
2056 SmallVectorImpl<SourceRange> &Ranges);
2057
2058 //===--------------------------------------------------------------------===//
2059 // C++0x 8: Function declaration trailing-return-type
2060 TypeResult ParseTrailingReturnType(SourceRange &Range,
2061 bool MayBeFollowedByDirectInit);
2062
2063 //===--------------------------------------------------------------------===//
2064 // C++ 2.13.5: C++ Boolean Literals
2065 ExprResult ParseCXXBoolLiteral();
2066
2067 //===--------------------------------------------------------------------===//
2068 // C++ 5.2.3: Explicit type conversion (functional notation)
2069 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
2070
2071 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2072 /// This should only be called when the current token is known to be part of
2073 /// simple-type-specifier.
2074 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
2075
2076 bool ParseCXXTypeSpecifierSeq(
2077 DeclSpec &DS, DeclaratorContext Context = DeclaratorContext::TypeName);
2078
2079 //===--------------------------------------------------------------------===//
2080 // C++ 5.3.4 and 5.3.5: C++ new and delete
2081 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
2082 Declarator &D);
2083 void ParseDirectNewDeclarator(Declarator &D);
2084 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
2085 ExprResult ParseCXXDeleteExpression(bool UseGlobal,
2086 SourceLocation Start);
2087
2088 //===--------------------------------------------------------------------===//
2089 // C++ if/switch/while/for condition expression.
2090 struct ForRangeInfo;
2091 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
2092 SourceLocation Loc,
2094 bool MissingOK,
2095 ForRangeInfo *FRI = nullptr,
2096 bool EnterForConditionScope = false);
2097 DeclGroupPtrTy ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
2098 ParsedAttributes &Attrs);
2099
2100 //===--------------------------------------------------------------------===//
2101 // C++ Coroutines
2102
2103 ExprResult ParseCoyieldExpression();
2104
2105 //===--------------------------------------------------------------------===//
2106 // C++ Concepts
2107
2108 ExprResult ParseRequiresExpression();
2109 void ParseTrailingRequiresClause(Declarator &D);
2110
2111 //===--------------------------------------------------------------------===//
2112 // C99 6.7.8: Initialization.
2113
2114 /// ParseInitializer
2115 /// initializer: [C99 6.7.8]
2116 /// assignment-expression
2117 /// '{' ...
2118 ExprResult ParseInitializer() {
2119 if (Tok.isNot(tok::l_brace))
2121 return ParseBraceInitializer();
2122 }
2123 bool MayBeDesignationStart();
2124 ExprResult ParseBraceInitializer();
2125 struct DesignatorCompletionInfo {
2126 SmallVectorImpl<Expr *> &InitExprs;
2127 QualType PreferredBaseType;
2128 };
2129 ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
2130 ExprResult createEmbedExpr();
2131 void injectEmbedTokens();
2132
2133 //===--------------------------------------------------------------------===//
2134 // clang Expressions
2135
2136 ExprResult ParseBlockLiteralExpression(); // ^{...}
2137
2138 //===--------------------------------------------------------------------===//
2139 // Objective-C Expressions
2140 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
2141 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
2142 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
2143 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
2144 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
2145 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
2146 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
2147 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
2148 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
2149 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
2150 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
2151 bool isSimpleObjCMessageExpression();
2152 ExprResult ParseObjCMessageExpression();
2153 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
2154 SourceLocation SuperLoc,
2155 ParsedType ReceiverType,
2156 Expr *ReceiverExpr);
2157 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
2158 SourceLocation LBracloc, SourceLocation SuperLoc,
2159 ParsedType ReceiverType, Expr *ReceiverExpr);
2160 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
2161
2162 //===--------------------------------------------------------------------===//
2163 // C99 6.8: Statements and Blocks.
2164
2165 /// A SmallVector of expressions.
2166 typedef SmallVector<Expr*, 12> ExprVector;
2167
2169 ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
2170 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
2171 StmtResult ParseStatementOrDeclaration(
2172 StmtVector &Stmts, ParsedStmtContext StmtCtx,
2173 SourceLocation *TrailingElseLoc = nullptr);
2174 StmtResult ParseStatementOrDeclarationAfterAttributes(
2175 StmtVector &Stmts, ParsedStmtContext StmtCtx,
2176 SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs,
2177 ParsedAttributes &DeclSpecAttrs);
2178 StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
2179 StmtResult ParseLabeledStatement(ParsedAttributes &Attrs,
2180 ParsedStmtContext StmtCtx);
2181 StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
2182 bool MissingCase = false,
2183 ExprResult Expr = ExprResult());
2184 StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
2185 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
2186 StmtResult ParseCompoundStatement(bool isStmtExpr,
2187 unsigned ScopeFlags);
2188 void ParseCompoundStatementLeadingPragmas();
2189 void DiagnoseLabelAtEndOfCompoundStatement();
2190 bool ConsumeNullStmt(StmtVector &Stmts);
2191 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
2192 bool ParseParenExprOrCondition(StmtResult *InitStmt,
2193 Sema::ConditionResult &CondResult,
2194 SourceLocation Loc, Sema::ConditionKind CK,
2195 SourceLocation &LParenLoc,
2196 SourceLocation &RParenLoc);
2197 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
2198 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
2199 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
2200 StmtResult ParseDoStatement();
2201 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
2202 StmtResult ParseGotoStatement();
2203 StmtResult ParseContinueStatement();
2204 StmtResult ParseBreakStatement();
2205 StmtResult ParseReturnStatement();
2206 StmtResult ParseAsmStatement(bool &msAsm);
2207 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
2208 StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx,
2209 SourceLocation *TrailingElseLoc,
2210 ParsedAttributes &Attrs);
2211
2212 /// Describes the behavior that should be taken for an __if_exists
2213 /// block.
2214 enum IfExistsBehavior {
2215 /// Parse the block; this code is always used.
2216 IEB_Parse,
2217 /// Skip the block entirely; this code is never used.
2218 IEB_Skip,
2219 /// Parse the block as a dependent block, which may be used in
2220 /// some template instantiations but not others.
2221 IEB_Dependent
2222 };
2223
2224 /// Describes the condition of a Microsoft __if_exists or
2225 /// __if_not_exists block.
2226 struct IfExistsCondition {
2227 /// The location of the initial keyword.
2228 SourceLocation KeywordLoc;
2229 /// Whether this is an __if_exists block (rather than an
2230 /// __if_not_exists block).
2231 bool IsIfExists;
2232
2233 /// Nested-name-specifier preceding the name.
2234 CXXScopeSpec SS;
2235
2236 /// The name we're looking for.
2237 UnqualifiedId Name;
2238
2239 /// The behavior of this __if_exists or __if_not_exists block
2240 /// should.
2241 IfExistsBehavior Behavior;
2242 };
2243
2244 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
2245 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
2246 void ParseMicrosoftIfExistsExternalDeclaration();
2247 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
2248 ParsedAttributes &AccessAttrs,
2249 AccessSpecifier &CurAS);
2250 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
2251 bool &InitExprsOk);
2252 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2253 SmallVectorImpl<Expr *> &Constraints,
2254 SmallVectorImpl<Expr *> &Exprs);
2255
2256 //===--------------------------------------------------------------------===//
2257 // C++ 6: Statements and Blocks
2258
2259 StmtResult ParseCXXTryBlock();
2260 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
2261 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
2262
2263 //===--------------------------------------------------------------------===//
2264 // MS: SEH Statements and Blocks
2265
2266 StmtResult ParseSEHTryBlock();
2267 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
2268 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
2269 StmtResult ParseSEHLeaveStatement();
2270
2271 //===--------------------------------------------------------------------===//
2272 // Objective-C Statements
2273
2274 StmtResult ParseObjCAtStatement(SourceLocation atLoc,
2275 ParsedStmtContext StmtCtx);
2276 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
2277 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
2278 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
2279 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
2280
2281
2282 //===--------------------------------------------------------------------===//
2283 // C99 6.7: Declarations.
2284
2285 /// A context for parsing declaration specifiers. TODO: flesh this
2286 /// out, there are other significant restrictions on specifiers than
2287 /// would be best implemented in the parser.
2288 enum class DeclSpecContext {
2289 DSC_normal, // normal context
2290 DSC_class, // class context, enables 'friend'
2291 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
2292 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
2293 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
2294 DSC_conv_operator, // C++ type-specifier-seq in an conversion operator
2295 DSC_top_level, // top-level/namespace declaration context
2296 DSC_template_param, // template parameter context
2297 DSC_template_arg, // template argument context
2298 DSC_template_type_arg, // template type argument context
2299 DSC_objc_method_result, // ObjC method result context, enables
2300 // 'instancetype'
2301 DSC_condition, // condition declaration context
2302 DSC_association, // A _Generic selection expression's type association
2303 DSC_new, // C++ new expression
2304 };
2305
2306 /// Is this a context in which we are parsing just a type-specifier (or
2307 /// trailing-type-specifier)?
2308 static bool isTypeSpecifier(DeclSpecContext DSC) {
2309 switch (DSC) {
2310 case DeclSpecContext::DSC_normal:
2311 case DeclSpecContext::DSC_template_param:
2312 case DeclSpecContext::DSC_template_arg:
2313 case DeclSpecContext::DSC_class:
2314 case DeclSpecContext::DSC_top_level:
2315 case DeclSpecContext::DSC_objc_method_result:
2316 case DeclSpecContext::DSC_condition:
2317 return false;
2318
2319 case DeclSpecContext::DSC_template_type_arg:
2320 case DeclSpecContext::DSC_type_specifier:
2321 case DeclSpecContext::DSC_conv_operator:
2322 case DeclSpecContext::DSC_trailing:
2323 case DeclSpecContext::DSC_alias_declaration:
2324 case DeclSpecContext::DSC_association:
2325 case DeclSpecContext::DSC_new:
2326 return true;
2327 }
2328 llvm_unreachable("Missing DeclSpecContext case");
2329 }
2330
2331 /// Whether a defining-type-specifier is permitted in a given context.
2332 enum class AllowDefiningTypeSpec {
2333 /// The grammar doesn't allow a defining-type-specifier here, and we must
2334 /// not parse one (eg, because a '{' could mean something else).
2335 No,
2336 /// The grammar doesn't allow a defining-type-specifier here, but we permit
2337 /// one for error recovery purposes. Sema will reject.
2338 NoButErrorRecovery,
2339 /// The grammar allows a defining-type-specifier here, even though it's
2340 /// always invalid. Sema will reject.
2341 YesButInvalid,
2342 /// The grammar allows a defining-type-specifier here, and one can be valid.
2343 Yes
2344 };
2345
2346 /// Is this a context in which we are parsing defining-type-specifiers (and
2347 /// so permit class and enum definitions in addition to non-defining class and
2348 /// enum elaborated-type-specifiers)?
2349 static AllowDefiningTypeSpec
2350 isDefiningTypeSpecifierContext(DeclSpecContext DSC, bool IsCPlusPlus) {
2351 switch (DSC) {
2352 case DeclSpecContext::DSC_normal:
2353 case DeclSpecContext::DSC_class:
2354 case DeclSpecContext::DSC_top_level:
2355 case DeclSpecContext::DSC_alias_declaration:
2356 case DeclSpecContext::DSC_objc_method_result:
2357 return AllowDefiningTypeSpec::Yes;
2358
2359 case DeclSpecContext::DSC_condition:
2360 case DeclSpecContext::DSC_template_param:
2361 return AllowDefiningTypeSpec::YesButInvalid;
2362
2363 case DeclSpecContext::DSC_template_type_arg:
2364 case DeclSpecContext::DSC_type_specifier:
2365 return AllowDefiningTypeSpec::NoButErrorRecovery;
2366
2367 case DeclSpecContext::DSC_association:
2368 return IsCPlusPlus ? AllowDefiningTypeSpec::NoButErrorRecovery
2369 : AllowDefiningTypeSpec::Yes;
2370
2371 case DeclSpecContext::DSC_trailing:
2372 case DeclSpecContext::DSC_conv_operator:
2373 case DeclSpecContext::DSC_template_arg:
2374 case DeclSpecContext::DSC_new:
2375 return AllowDefiningTypeSpec::No;
2376 }
2377 llvm_unreachable("Missing DeclSpecContext case");
2378 }
2379
2380 /// Is this a context in which an opaque-enum-declaration can appear?
2381 static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
2382 switch (DSC) {
2383 case DeclSpecContext::DSC_normal:
2384 case DeclSpecContext::DSC_class:
2385 case DeclSpecContext::DSC_top_level:
2386 return true;
2387
2388 case DeclSpecContext::DSC_alias_declaration:
2389 case DeclSpecContext::DSC_objc_method_result:
2390 case DeclSpecContext::DSC_condition:
2391 case DeclSpecContext::DSC_template_param:
2392 case DeclSpecContext::DSC_template_type_arg:
2393 case DeclSpecContext::DSC_type_specifier:
2394 case DeclSpecContext::DSC_trailing:
2395 case DeclSpecContext::DSC_association:
2396 case DeclSpecContext::DSC_conv_operator:
2397 case DeclSpecContext::DSC_template_arg:
2398 case DeclSpecContext::DSC_new:
2399
2400 return false;
2401 }
2402 llvm_unreachable("Missing DeclSpecContext case");
2403 }
2404
2405 /// Is this a context in which we can perform class template argument
2406 /// deduction?
2407 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2408 switch (DSC) {
2409 case DeclSpecContext::DSC_normal:
2410 case DeclSpecContext::DSC_template_param:
2411 case DeclSpecContext::DSC_template_arg:
2412 case DeclSpecContext::DSC_class:
2413 case DeclSpecContext::DSC_top_level:
2414 case DeclSpecContext::DSC_condition:
2415 case DeclSpecContext::DSC_type_specifier:
2416 case DeclSpecContext::DSC_association:
2417 case DeclSpecContext::DSC_conv_operator:
2418 case DeclSpecContext::DSC_new:
2419 return true;
2420
2421 case DeclSpecContext::DSC_objc_method_result:
2422 case DeclSpecContext::DSC_template_type_arg:
2423 case DeclSpecContext::DSC_trailing:
2424 case DeclSpecContext::DSC_alias_declaration:
2425 return false;
2426 }
2427 llvm_unreachable("Missing DeclSpecContext case");
2428 }
2429
2430 // Is this a context in which an implicit 'typename' is allowed?
2432 getImplicitTypenameContext(DeclSpecContext DSC) {
2433 switch (DSC) {
2434 case DeclSpecContext::DSC_class:
2435 case DeclSpecContext::DSC_top_level:
2436 case DeclSpecContext::DSC_type_specifier:
2437 case DeclSpecContext::DSC_template_type_arg:
2438 case DeclSpecContext::DSC_trailing:
2439 case DeclSpecContext::DSC_alias_declaration:
2440 case DeclSpecContext::DSC_template_param:
2441 case DeclSpecContext::DSC_new:
2443
2444 case DeclSpecContext::DSC_normal:
2445 case DeclSpecContext::DSC_objc_method_result:
2446 case DeclSpecContext::DSC_condition:
2447 case DeclSpecContext::DSC_template_arg:
2448 case DeclSpecContext::DSC_conv_operator:
2449 case DeclSpecContext::DSC_association:
2451 }
2452 llvm_unreachable("Missing DeclSpecContext case");
2453 }
2454
2455 /// Information on a C++0x for-range-initializer found while parsing a
2456 /// declaration which turns out to be a for-range-declaration.
2457 struct ForRangeInit {
2458 SourceLocation ColonLoc;
2459 ExprResult RangeExpr;
2460 SmallVector<MaterializeTemporaryExpr *, 8> LifetimeExtendTemps;
2461 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2462 };
2463 struct ForRangeInfo : ForRangeInit {
2464 StmtResult LoopVar;
2465 };
2466
2467 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2468 SourceLocation &DeclEnd,
2469 ParsedAttributes &DeclAttrs,
2470 ParsedAttributes &DeclSpecAttrs,
2471 SourceLocation *DeclSpecStart = nullptr);
2473 ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
2474 ParsedAttributes &DeclAttrs,
2475 ParsedAttributes &DeclSpecAttrs, bool RequireSemi,
2476 ForRangeInit *FRI = nullptr,
2477 SourceLocation *DeclSpecStart = nullptr);
2478 bool MightBeDeclarator(DeclaratorContext Context);
2479 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2480 ParsedAttributes &Attrs,
2481 ParsedTemplateInfo &TemplateInfo,
2482 SourceLocation *DeclEnd = nullptr,
2483 ForRangeInit *FRI = nullptr);
2484 Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2485 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2486 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2487 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2488 Declarator &D,
2489 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2490 ForRangeInit *FRI = nullptr);
2491 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2492 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2493
2494 /// When in code-completion, skip parsing of the function/method body
2495 /// unless the body contains the code-completion point.
2496 ///
2497 /// \returns true if the function body was skipped.
2498 bool trySkippingFunctionBody();
2499
2500 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2501 ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
2502 DeclSpecContext DSC, ParsedAttributes &Attrs);
2503 DeclSpecContext
2504 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2505 void
2506 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
2508 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2509 LateParsedAttrList *LateAttrs = nullptr) {
2510 return ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs,
2511 getImplicitTypenameContext(DSC));
2512 }
2513 void
2514 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
2515 AccessSpecifier AS, DeclSpecContext DSC,
2516 LateParsedAttrList *LateAttrs,
2517 ImplicitTypenameContext AllowImplicitTypename);
2518
2519 SourceLocation ParsePackIndexingType(DeclSpec &DS);
2520 void AnnotateExistingIndexedTypeNamePack(ParsedType T,
2521 SourceLocation StartLoc,
2522 SourceLocation EndLoc);
2523
2524 bool DiagnoseMissingSemiAfterTagDefinition(
2525 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2526 LateParsedAttrList *LateAttrs = nullptr);
2527
2528 void ParseSpecifierQualifierList(
2529 DeclSpec &DS, AccessSpecifier AS = AS_none,
2530 DeclSpecContext DSC = DeclSpecContext::DSC_normal) {
2531 ParseSpecifierQualifierList(DS, getImplicitTypenameContext(DSC), AS, DSC);
2532 }
2533
2534 void ParseSpecifierQualifierList(
2535 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2537 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2538
2539 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2540 DeclaratorContext Context);
2541
2542 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2543 const ParsedTemplateInfo &TemplateInfo,
2544 AccessSpecifier AS, DeclSpecContext DSC);
2545 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2546 void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
2547 RecordDecl *TagDecl);
2548
2549 void ParseStructDeclaration(
2550 ParsingDeclSpec &DS,
2551 llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
2552 LateParsedAttrList *LateFieldAttrs = nullptr);
2553
2554 DeclGroupPtrTy ParseTopLevelStmtDecl();
2555
2556 bool isDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2557 bool DisambiguatingWithExpression = false);
2558 bool isTypeSpecifierQualifier();
2559
2560 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2561 /// is definitely a type-specifier. Return false if it isn't part of a type
2562 /// specifier or if we're not sure.
2563 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2564
2565 /// Return true if we know that we are definitely looking at a
2566 /// decl-specifier, and isn't part of an expression such as a function-style
2567 /// cast. Return false if it's no a decl-specifier, or we're not sure.
2568 bool isKnownToBeDeclarationSpecifier() {
2569 if (getLangOpts().CPlusPlus)
2570 return isCXXDeclarationSpecifier(ImplicitTypenameContext::No) ==
2571 TPResult::True;
2572 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2573 }
2574
2575 /// isDeclarationStatement - Disambiguates between a declaration or an
2576 /// expression statement, when parsing function bodies.
2577 ///
2578 /// \param DisambiguatingWithExpression - True to indicate that the purpose of
2579 /// this check is to disambiguate between an expression and a declaration.
2580 /// Returns true for declaration, false for expression.
2581 bool isDeclarationStatement(bool DisambiguatingWithExpression = false) {
2582 if (getLangOpts().CPlusPlus)
2583 return isCXXDeclarationStatement(DisambiguatingWithExpression);
2584 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2585 }
2586
2587 /// isForInitDeclaration - Disambiguates between a declaration or an
2588 /// expression in the context of the C 'clause-1' or the C++
2589 // 'for-init-statement' part of a 'for' statement.
2590 /// Returns true for declaration, false for expression.
2591 bool isForInitDeclaration() {
2592 if (getLangOpts().OpenMP)
2593 Actions.OpenMP().startOpenMPLoop();
2594 if (getLangOpts().CPlusPlus)
2595 return Tok.is(tok::kw_using) ||
2596 isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2597 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2598 }
2599
2600 /// Determine whether this is a C++1z for-range-identifier.
2601 bool isForRangeIdentifier();
2602
2603 /// Determine whether we are currently at the start of an Objective-C
2604 /// class message that appears to be missing the open bracket '['.
2605 bool isStartOfObjCClassMessageMissingOpenBracket();
2606
2607 /// Starting with a scope specifier, identifier, or
2608 /// template-id that refers to the current class, determine whether
2609 /// this is a constructor declarator.
2610 bool isConstructorDeclarator(
2611 bool Unqualified, bool DeductionGuide = false,
2613 const ParsedTemplateInfo *TemplateInfo = nullptr);
2614
2615 /// Specifies the context in which type-id/expression
2616 /// disambiguation will occur.
2617 enum TentativeCXXTypeIdContext {
2618 TypeIdInParens,
2619 TypeIdUnambiguous,
2620 TypeIdAsTemplateArgument,
2621 TypeIdInTrailingReturnType,
2622 TypeIdAsGenericSelectionArgument,
2623 };
2624
2625 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2626 /// whether the parens contain an expression or a type-id.
2627 /// Returns true for a type-id and false for an expression.
2628 bool isTypeIdInParens(bool &isAmbiguous) {
2629 if (getLangOpts().CPlusPlus)
2630 return isCXXTypeId(TypeIdInParens, isAmbiguous);
2631 isAmbiguous = false;
2632 return isTypeSpecifierQualifier();
2633 }
2634 bool isTypeIdInParens() {
2635 bool isAmbiguous;
2636 return isTypeIdInParens(isAmbiguous);
2637 }
2638
2639 /// Checks whether the current tokens form a type-id or an expression for the
2640 /// purposes of use as the initial operand to a generic selection expression.
2641 /// This requires special handling in C++ because it accepts either a type or
2642 /// an expression, and we need to disambiguate which is which. However, we
2643 /// cannot use the same logic as we've used for sizeof expressions, because
2644 /// that logic relies on the operator only accepting a single argument,
2645 /// whereas _Generic accepts a list of arguments.
2646 bool isTypeIdForGenericSelection() {
2647 if (getLangOpts().CPlusPlus) {
2648 bool isAmbiguous;
2649 return isCXXTypeId(TypeIdAsGenericSelectionArgument, isAmbiguous);
2650 }
2651 return isTypeSpecifierQualifier();
2652 }
2653
2654 /// Checks if the current tokens form type-id or expression.
2655 /// It is similar to isTypeIdInParens but does not suppose that type-id
2656 /// is in parenthesis.
2657 bool isTypeIdUnambiguously() {
2658 if (getLangOpts().CPlusPlus) {
2659 bool isAmbiguous;
2660 return isCXXTypeId(TypeIdUnambiguous, isAmbiguous);
2661 }
2662 return isTypeSpecifierQualifier();
2663 }
2664
2665 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2666 /// between a declaration or an expression statement, when parsing function
2667 /// bodies. Returns true for declaration, false for expression.
2668 bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false);
2669
2670 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2671 /// between a simple-declaration or an expression-statement.
2672 /// If during the disambiguation process a parsing error is encountered,
2673 /// the function returns true to let the declaration parsing code handle it.
2674 /// Returns false if the statement is disambiguated as expression.
2675 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2676
2677 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2678 /// a constructor-style initializer, when parsing declaration statements.
2679 /// Returns true for function declarator and false for constructor-style
2680 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2681 /// might be a constructor-style initializer.
2682 /// If during the disambiguation process a parsing error is encountered,
2683 /// the function returns true to let the declaration parsing code handle it.
2684 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr,
2685 ImplicitTypenameContext AllowImplicitTypename =
2687
2688 struct ConditionDeclarationOrInitStatementState;
2689 enum class ConditionOrInitStatement {
2690 Expression, ///< Disambiguated as an expression (either kind).
2691 ConditionDecl, ///< Disambiguated as the declaration form of condition.
2692 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
2693 ForRangeDecl, ///< Disambiguated as a for-range declaration.
2694 Error ///< Can't be any of the above!
2695 };
2696 /// Disambiguates between the different kinds of things that can happen
2697 /// after 'if (' or 'switch ('. This could be one of two different kinds of
2698 /// declaration (depending on whether there is a ';' later) or an expression.
2699 ConditionOrInitStatement
2700 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
2701 bool CanBeForRangeDecl);
2702
2703 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2704 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2705 bool isAmbiguous;
2706 return isCXXTypeId(Context, isAmbiguous);
2707 }
2708
2709 /// TPResult - Used as the result value for functions whose purpose is to
2710 /// disambiguate C++ constructs by "tentatively parsing" them.
2711 enum class TPResult {
2712 True, False, Ambiguous, Error
2713 };
2714
2715 /// Determine whether we could have an enum-base.
2716 ///
2717 /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
2718 /// only consider this to be an enum-base if the next token is a '{'.
2719 ///
2720 /// \return \c false if this cannot possibly be an enum base; \c true
2721 /// otherwise.
2722 bool isEnumBase(bool AllowSemi);
2723
2724 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2725 /// declaration specifier, TPResult::False if it is not,
2726 /// TPResult::Ambiguous if it could be either a decl-specifier or a
2727 /// function-style cast, and TPResult::Error if a parsing error was
2728 /// encountered. If it could be a braced C++11 function-style cast, returns
2729 /// BracedCastResult.
2730 /// Doesn't consume tokens.
2731 TPResult
2732 isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2733 TPResult BracedCastResult = TPResult::False,
2734 bool *InvalidAsDeclSpec = nullptr);
2735
2736 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2737 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2738 /// a type-specifier other than a cv-qualifier.
2739 bool isCXXDeclarationSpecifierAType();
2740
2741 /// Determine whether the current token sequence might be
2742 /// '<' template-argument-list '>'
2743 /// rather than a less-than expression.
2744 TPResult isTemplateArgumentList(unsigned TokensToSkip);
2745
2746 /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
2747 /// 'explicit(bool)' declaration, in earlier language modes where that is an
2748 /// extension.
2749 TPResult isExplicitBool();
2750
2751 /// Determine whether an identifier has been tentatively declared as a
2752 /// non-type. Such tentative declarations should not be found to name a type
2753 /// during a tentative parse, but also should not be annotated as a non-type.
2754 bool isTentativelyDeclared(IdentifierInfo *II);
2755
2756 // "Tentative parsing" functions, used for disambiguation. If a parsing error
2757 // is encountered they will return TPResult::Error.
2758 // Returning TPResult::True/False indicates that the ambiguity was
2759 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2760 // that more tentative parsing is necessary for disambiguation.
2761 // They all consume tokens, so backtracking should be used after calling them.
2762
2763 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2764 TPResult TryParseTypeofSpecifier();
2765 TPResult TryParseProtocolQualifiers();
2766 TPResult TryParsePtrOperatorSeq();
2767 TPResult TryParseOperatorId();
2768 TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false);
2769 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2770 bool mayHaveDirectInit = false,
2771 bool mayHaveTrailingReturnType = false);
2772 TPResult TryParseParameterDeclarationClause(
2773 bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false,
2774 ImplicitTypenameContext AllowImplicitTypename =
2776 TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false);
2777 bool NameAfterArrowIsNonType();
2778 TPResult TryParseBracketDeclarator();
2779 TPResult TryConsumeDeclarationSpecifier();
2780
2781 /// Try to skip a possibly empty sequence of 'attribute-specifier's without
2782 /// full validation of the syntactic structure of attributes.
2783 bool TrySkipAttributes();
2784
2785 /// Diagnoses use of _ExtInt as being deprecated, and diagnoses use of
2786 /// _BitInt as an extension when appropriate.
2787 void DiagnoseBitIntUse(const Token &Tok);
2788
2789public:
2791 ParseTypeName(SourceRange *Range = nullptr,
2793 AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
2794 ParsedAttributes *Attrs = nullptr);
2795
2796private:
2797 void ParseBlockId(SourceLocation CaretLoc);
2798
2799 /// Return true if the next token should be treated as a [[]] attribute,
2800 /// or as a keyword that behaves like one. The former is only true if
2801 /// [[]] attributes are enabled, whereas the latter is true whenever
2802 /// such a keyword appears. The arguments are as for
2803 /// isCXX11AttributeSpecifier.
2804 bool isAllowedCXX11AttributeSpecifier(bool Disambiguate = false,
2805 bool OuterMightBeMessageSend = false) {
2806 return (Tok.isRegularKeywordAttribute() ||
2807 isCXX11AttributeSpecifier(Disambiguate, OuterMightBeMessageSend));
2808 }
2809
2810 // Check for the start of an attribute-specifier-seq in a context where an
2811 // attribute is not allowed.
2812 bool CheckProhibitedCXX11Attribute() {
2813 assert(Tok.is(tok::l_square));
2814 if (NextToken().isNot(tok::l_square))
2815 return false;
2816 return DiagnoseProhibitedCXX11Attribute();
2817 }
2818
2819 bool DiagnoseProhibitedCXX11Attribute();
2820 void CheckMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2821 SourceLocation CorrectLocation) {
2822 if (!Tok.isRegularKeywordAttribute() &&
2823 (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2824 Tok.isNot(tok::kw_alignas))
2825 return;
2826 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2827 }
2828 void DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2829 SourceLocation CorrectLocation);
2830
2831 void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS,
2832 TagUseKind TUK);
2833
2834 // FixItLoc = possible correct location for the attributes
2835 void ProhibitAttributes(ParsedAttributes &Attrs,
2836 SourceLocation FixItLoc = SourceLocation()) {
2837 if (Attrs.Range.isInvalid())
2838 return;
2839 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2840 Attrs.clear();
2841 }
2842
2843 void ProhibitAttributes(ParsedAttributesView &Attrs,
2844 SourceLocation FixItLoc = SourceLocation()) {
2845 if (Attrs.Range.isInvalid())
2846 return;
2847 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2848 Attrs.clearListOnly();
2849 }
2850 void DiagnoseProhibitedAttributes(const ParsedAttributesView &Attrs,
2851 SourceLocation FixItLoc);
2852
2853 // Forbid C++11 and C23 attributes that appear on certain syntactic locations
2854 // which standard permits but we don't supported yet, for example, attributes
2855 // appertain to decl specifiers.
2856 // For the most cases we don't want to warn on unknown type attributes, but
2857 // left them to later diagnoses. However, for a few cases like module
2858 // declarations and module import declarations, we should do it.
2859 void ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned AttrDiagID,
2860 unsigned KeywordDiagId,
2861 bool DiagnoseEmptyAttrs = false,
2862 bool WarnOnUnknownAttrs = false);
2863
2864 /// Skip C++11 and C23 attributes and return the end location of the
2865 /// last one.
2866 /// \returns SourceLocation() if there are no attributes.
2867 SourceLocation SkipCXX11Attributes();
2868
2869 /// Diagnose and skip C++11 and C23 attributes that appear in syntactic
2870 /// locations where attributes are not allowed.
2871 void DiagnoseAndSkipCXX11Attributes();
2872
2873 /// Emit warnings for C++11 and C23 attributes that are in a position that
2874 /// clang accepts as an extension.
2875 void DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs);
2876
2877 ExprResult ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName);
2878
2879 bool
2880 ParseAttributeArgumentList(const clang::IdentifierInfo &AttrName,
2881 SmallVectorImpl<Expr *> &Exprs,
2882 ParsedAttributeArgumentsProperties ArgsProperties);
2883
2884 /// Parses syntax-generic attribute arguments for attributes which are
2885 /// known to the implementation, and adds them to the given ParsedAttributes
2886 /// list with the given attribute syntax. Returns the number of arguments
2887 /// parsed for the attribute.
2888 unsigned
2889 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2890 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2891 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2892 ParsedAttr::Form Form);
2893
2894 enum ParseAttrKindMask {
2895 PAKM_GNU = 1 << 0,
2896 PAKM_Declspec = 1 << 1,
2897 PAKM_CXX11 = 1 << 2,
2898 };
2899
2900 /// \brief Parse attributes based on what syntaxes are desired, allowing for
2901 /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2902 /// __attribute__((...)) __declspec(...) __attribute__((...)))
2903 /// Note that Microsoft attributes (spelled with single square brackets) are
2904 /// not supported by this because of parsing ambiguities with other
2905 /// constructs.
2906 ///
2907 /// There are some attribute parse orderings that should not be allowed in
2908 /// arbitrary order. e.g.,
2909 ///
2910 /// [[]] __attribute__(()) int i; // OK
2911 /// __attribute__(()) [[]] int i; // Not OK
2912 ///
2913 /// Such situations should use the specific attribute parsing functionality.
2914 void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2915 LateParsedAttrList *LateAttrs = nullptr);
2916 /// \brief Possibly parse attributes based on what syntaxes are desired,
2917 /// allowing for the order to vary.
2918 bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2919 LateParsedAttrList *LateAttrs = nullptr) {
2920 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2921 isAllowedCXX11AttributeSpecifier()) {
2922 ParseAttributes(WhichAttrKinds, Attrs, LateAttrs);
2923 return true;
2924 }
2925 return false;
2926 }
2927
2928 void MaybeParseGNUAttributes(Declarator &D,
2929 LateParsedAttrList *LateAttrs = nullptr) {
2930 if (Tok.is(tok::kw___attribute)) {
2931 ParsedAttributes Attrs(AttrFactory);
2932 ParseGNUAttributes(Attrs, LateAttrs, &D);
2933 D.takeAttributes(Attrs);
2934 }
2935 }
2936
2937 bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2938 LateParsedAttrList *LateAttrs = nullptr) {
2939 if (Tok.is(tok::kw___attribute)) {
2940 ParseGNUAttributes(Attrs, LateAttrs);
2941 return true;
2942 }
2943 return false;
2944 }
2945
2946 void ParseGNUAttributes(ParsedAttributes &Attrs,
2947 LateParsedAttrList *LateAttrs = nullptr,
2948 Declarator *D = nullptr);
2949 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2950 SourceLocation AttrNameLoc,
2951 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2952 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2953 ParsedAttr::Form Form, Declarator *D);
2954 IdentifierLoc *ParseIdentifierLoc();
2955
2956 unsigned
2957 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2958 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2959 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2960 ParsedAttr::Form Form);
2961
2962 void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) {
2963 // If parsing the attributes found an OpenMP directive, emit those tokens
2964 // to the parse stream now.
2965 if (!OpenMPTokens.empty()) {
2966 PP.EnterToken(Tok, /*IsReinject*/ true);
2967 PP.EnterTokenStream(OpenMPTokens, /*DisableMacroExpansion*/ true,
2968 /*IsReinject*/ true);
2969 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ true);
2970 }
2971 }
2972 void MaybeParseCXX11Attributes(Declarator &D) {
2973 if (isAllowedCXX11AttributeSpecifier()) {
2974 ParsedAttributes Attrs(AttrFactory);
2975 ParseCXX11Attributes(Attrs);
2976 D.takeAttributes(Attrs);
2977 }
2978 }
2979
2980 bool MaybeParseCXX11Attributes(ParsedAttributes &Attrs,
2981 bool OuterMightBeMessageSend = false) {
2982 if (isAllowedCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) {
2983 ParseCXX11Attributes(Attrs);
2984 return true;
2985 }
2986 return false;
2987 }
2988
2989 void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
2990 CachedTokens &OpenMPTokens);
2991
2992 void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
2993 CachedTokens &OpenMPTokens,
2994 SourceLocation *EndLoc = nullptr);
2995 void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs,
2996 SourceLocation *EndLoc = nullptr) {
2997 CachedTokens OpenMPTokens;
2998 ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc);
2999 ReplayOpenMPAttributeTokens(OpenMPTokens);
3000 }
3001 void ParseCXX11Attributes(ParsedAttributes &attrs);
3002 /// Parses a C++11 (or C23)-style attribute argument list. Returns true
3003 /// if this results in adding an attribute to the ParsedAttributes list.
3004 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3005 SourceLocation AttrNameLoc,
3006 ParsedAttributes &Attrs, SourceLocation *EndLoc,
3007 IdentifierInfo *ScopeName,
3008 SourceLocation ScopeLoc,
3009 CachedTokens &OpenMPTokens);
3010
3011 /// Parse a C++23 assume() attribute. Returns true on error.
3012 bool ParseCXXAssumeAttributeArg(ParsedAttributes &Attrs,
3013 IdentifierInfo *AttrName,
3014 SourceLocation AttrNameLoc,
3015 SourceLocation *EndLoc,
3016 ParsedAttr::Form Form);
3017
3018 IdentifierInfo *TryParseCXX11AttributeIdentifier(
3019 SourceLocation &Loc,
3022 const IdentifierInfo *EnclosingScope = nullptr);
3023
3024 void MaybeParseHLSLAnnotations(Declarator &D,
3025 SourceLocation *EndLoc = nullptr,
3026 bool CouldBeBitField = false) {
3027 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
3028 if (Tok.is(tok::colon)) {
3029 ParsedAttributes Attrs(AttrFactory);
3030 ParseHLSLAnnotations(Attrs, EndLoc, CouldBeBitField);
3031 D.takeAttributes(Attrs);
3032 }
3033 }
3034
3035 void MaybeParseHLSLAnnotations(ParsedAttributes &Attrs,
3036 SourceLocation *EndLoc = nullptr) {
3037 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
3038 if (Tok.is(tok::colon))
3039 ParseHLSLAnnotations(Attrs, EndLoc);
3040 }
3041
3042 void ParseHLSLAnnotations(ParsedAttributes &Attrs,
3043 SourceLocation *EndLoc = nullptr,
3044 bool CouldBeBitField = false);
3045 Decl *ParseHLSLBuffer(SourceLocation &DeclEnd);
3046
3047 void MaybeParseMicrosoftAttributes(ParsedAttributes &Attrs) {
3048 if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) &&
3049 Tok.is(tok::l_square)) {
3050 ParsedAttributes AttrsWithRange(AttrFactory);
3051 ParseMicrosoftAttributes(AttrsWithRange);
3052 Attrs.takeAllFrom(AttrsWithRange);
3053 }
3054 }
3055 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
3056 void ParseMicrosoftAttributes(ParsedAttributes &Attrs);
3057 bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
3058 if (getLangOpts().DeclSpecKeyword && Tok.is(tok::kw___declspec)) {
3059 ParseMicrosoftDeclSpecs(Attrs);
3060 return true;
3061 }
3062 return false;
3063 }
3064 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs);
3065 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
3066 SourceLocation AttrNameLoc,
3067 ParsedAttributes &Attrs);
3068 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
3069 void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &Attrs);
3070 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
3071 SourceLocation SkipExtendedMicrosoftTypeAttributes();
3072 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
3073 void ParseNullabilityClassAttributes(ParsedAttributes &attrs);
3074 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
3075 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
3076 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
3077 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
3078 void ParseCUDAFunctionAttributes(ParsedAttributes &attrs);
3079 bool isHLSLQualifier(const Token &Tok) const;
3080 void ParseHLSLQualifiers(ParsedAttributes &Attrs);
3081
3082 VersionTuple ParseVersionTuple(SourceRange &Range);
3083 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
3084 SourceLocation AvailabilityLoc,
3085 ParsedAttributes &attrs,
3086 SourceLocation *endLoc,
3087 IdentifierInfo *ScopeName,
3088 SourceLocation ScopeLoc,
3089 ParsedAttr::Form Form);
3090
3091 std::optional<AvailabilitySpec> ParseAvailabilitySpec();
3092 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
3093
3094 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
3095 SourceLocation Loc,
3096 ParsedAttributes &Attrs,
3097 SourceLocation *EndLoc,
3098 IdentifierInfo *ScopeName,
3099 SourceLocation ScopeLoc,
3100 ParsedAttr::Form Form);
3101
3102 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
3103 SourceLocation ObjCBridgeRelatedLoc,
3104 ParsedAttributes &Attrs,
3105 SourceLocation *EndLoc,
3106 IdentifierInfo *ScopeName,
3107 SourceLocation ScopeLoc,
3108 ParsedAttr::Form Form);
3109
3110 void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
3111 SourceLocation AttrNameLoc,
3112 ParsedAttributes &Attrs,
3113 SourceLocation *EndLoc,
3114 IdentifierInfo *ScopeName,
3115 SourceLocation ScopeLoc,
3116 ParsedAttr::Form Form);
3117
3118 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
3119 SourceLocation AttrNameLoc,
3120 ParsedAttributes &Attrs,
3121 SourceLocation *EndLoc,
3122 IdentifierInfo *ScopeName,
3123 SourceLocation ScopeLoc,
3124 ParsedAttr::Form Form);
3125
3126 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
3127 SourceLocation AttrNameLoc,
3128 ParsedAttributes &Attrs,
3129 IdentifierInfo *ScopeName,
3130 SourceLocation ScopeLoc,
3131 ParsedAttr::Form Form);
3132
3133 void DistributeCLateParsedAttrs(Decl *Dcl, LateParsedAttrList *LateAttrs);
3134
3135 void ParseBoundsAttribute(IdentifierInfo &AttrName,
3136 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
3137 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
3138 ParsedAttr::Form Form);
3139
3140 void ParseTypeofSpecifier(DeclSpec &DS);
3141 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
3142 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
3143 SourceLocation StartLoc,
3144 SourceLocation EndLoc);
3145 void ParseAtomicSpecifier(DeclSpec &DS);
3146
3147 ExprResult ParseAlignArgument(StringRef KWName, SourceLocation Start,
3148 SourceLocation &EllipsisLoc, bool &IsType,
3149 ParsedType &Ty);
3150 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3151 SourceLocation *endLoc = nullptr);
3152 ExprResult ParseExtIntegerArgument();
3153
3154 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
3155 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
3156 return isCXX11VirtSpecifier(Tok);
3157 }
3158 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
3159 SourceLocation FriendLoc);
3160
3161 bool isCXX11FinalKeyword() const;
3162 bool isClassCompatibleKeyword() const;
3163
3164 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
3165 /// enter a new C++ declarator scope and exit it when the function is
3166 /// finished.
3167 class DeclaratorScopeObj {
3168 Parser &P;
3169 CXXScopeSpec &SS;
3170 bool EnteredScope;
3171 bool CreatedScope;
3172 public:
3173 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
3174 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
3175
3176 void EnterDeclaratorScope() {
3177 assert(!EnteredScope && "Already entered the scope!");
3178 assert(SS.isSet() && "C++ scope was not set!");
3179
3180 CreatedScope = true;
3181 P.EnterScope(0); // Not a decl scope.
3182
3183 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
3184 EnteredScope = true;
3185 }
3186
3187 ~DeclaratorScopeObj() {
3188 if (EnteredScope) {
3189 assert(SS.isSet() && "C++ scope was cleared ?");
3190 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
3191 }
3192 if (CreatedScope)
3193 P.ExitScope();
3194 }
3195 };
3196
3197 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
3198 void ParseDeclarator(Declarator &D);
3199 /// A function that parses a variant of direct-declarator.
3200 typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
3201 void ParseDeclaratorInternal(Declarator &D,
3202 DirectDeclParseFunction DirectDeclParser);
3203
3204 enum AttrRequirements {
3205 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
3206 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
3207 AR_GNUAttributesParsed = 1 << 1,
3208 AR_CXX11AttributesParsed = 1 << 2,
3209 AR_DeclspecAttributesParsed = 1 << 3,
3210 AR_AllAttributesParsed = AR_GNUAttributesParsed |
3211 AR_CXX11AttributesParsed |
3212 AR_DeclspecAttributesParsed,
3213 AR_VendorAttributesParsed = AR_GNUAttributesParsed |
3214 AR_DeclspecAttributesParsed
3215 };
3216
3217 void ParseTypeQualifierListOpt(
3218 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
3219 bool AtomicAllowed = true, bool IdentifierRequired = false,
3220 std::optional<llvm::function_ref<void()>> CodeCompletionHandler =
3221 std::nullopt);
3222 void ParseDirectDeclarator(Declarator &D);
3223 void ParseDecompositionDeclarator(Declarator &D);
3224 void ParseParenDeclarator(Declarator &D);
3225 void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs,
3226 BalancedDelimiterTracker &Tracker,
3227 bool IsAmbiguous, bool RequiresArg = false);
3228 void InitCXXThisScopeForDeclaratorIfRelevant(
3229 const Declarator &D, const DeclSpec &DS,
3230 std::optional<Sema::CXXThisScopeRAII> &ThisScope);
3231 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
3232 SourceLocation &RefQualifierLoc);
3233 bool isFunctionDeclaratorIdentifierList();
3234 void ParseFunctionDeclaratorIdentifierList(
3235 Declarator &D,
3236 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
3237 void ParseParameterDeclarationClause(
3238 Declarator &D, ParsedAttributes &attrs,
3239 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
3240 SourceLocation &EllipsisLoc) {
3241 return ParseParameterDeclarationClause(
3242 D.getContext(), attrs, ParamInfo, EllipsisLoc,
3243 D.getCXXScopeSpec().isSet() &&
3244 D.isFunctionDeclaratorAFunctionDeclaration());
3245 }
3246 void ParseParameterDeclarationClause(
3247 DeclaratorContext DeclaratorContext, ParsedAttributes &attrs,
3248 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
3249 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration = false);
3250
3251 void ParseBracketDeclarator(Declarator &D);
3252 void ParseMisplacedBracketDeclarator(Declarator &D);
3253 bool MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS);
3254 DeclSpec::TST TypeTransformTokToDeclSpec();
3255
3256 //===--------------------------------------------------------------------===//
3257 // C++ 7: Declarations [dcl.dcl]
3258
3259 /// The kind of attribute specifier we have found.
3260 enum CXX11AttributeKind {
3261 /// This is not an attribute specifier.
3262 CAK_NotAttributeSpecifier,
3263 /// This should be treated as an attribute-specifier.
3264 CAK_AttributeSpecifier,
3265 /// The next tokens are '[[', but this is not an attribute-specifier. This
3266 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
3267 CAK_InvalidAttributeSpecifier
3268 };
3269 CXX11AttributeKind
3270 isCXX11AttributeSpecifier(bool Disambiguate = false,
3271 bool OuterMightBeMessageSend = false);
3272
3273 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3274
3275 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3276 SourceLocation &DeclEnd,
3277 SourceLocation InlineLoc = SourceLocation());
3278
3279 struct InnerNamespaceInfo {
3280 SourceLocation NamespaceLoc;
3281 SourceLocation InlineLoc;
3282 SourceLocation IdentLoc;
3283 IdentifierInfo *Ident;
3284 };
3285 using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3286
3287 void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3288 unsigned int index, SourceLocation &InlineLoc,
3289 ParsedAttributes &attrs,
3290 BalancedDelimiterTracker &Tracker);
3291 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3292 Decl *ParseExportDeclaration();
3293 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3294 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3295 SourceLocation &DeclEnd, ParsedAttributes &Attrs);
3296 Decl *ParseUsingDirective(DeclaratorContext Context,
3297 SourceLocation UsingLoc,
3298 SourceLocation &DeclEnd,
3299 ParsedAttributes &attrs);
3300
3301 struct UsingDeclarator {
3302 SourceLocation TypenameLoc;
3303 CXXScopeSpec SS;
3304 UnqualifiedId Name;
3305 SourceLocation EllipsisLoc;
3306
3307 void clear() {
3308 TypenameLoc = EllipsisLoc = SourceLocation();
3309 SS.clear();
3310 Name.clear();
3311 }
3312 };
3313
3314 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3315 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3316 const ParsedTemplateInfo &TemplateInfo,
3317 SourceLocation UsingLoc,
3318 SourceLocation &DeclEnd,
3319 ParsedAttributes &Attrs,
3321 Decl *ParseAliasDeclarationAfterDeclarator(
3322 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3323 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3324 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3325
3326 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3327 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3328 SourceLocation AliasLoc, IdentifierInfo *Alias,
3329 SourceLocation &DeclEnd);
3330
3331 //===--------------------------------------------------------------------===//
3332 // C++ 9: classes [class] and C structs/unions.
3333 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3334 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3335 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
3336 AccessSpecifier AS, bool EnteringContext,
3337 DeclSpecContext DSC, ParsedAttributes &Attributes);
3338 void SkipCXXMemberSpecification(SourceLocation StartLoc,
3339 SourceLocation AttrFixitLoc,
3340 unsigned TagType,
3341 Decl *TagDecl);
3342 void ParseCXXMemberSpecification(SourceLocation StartLoc,
3343 SourceLocation AttrFixitLoc,
3344 ParsedAttributes &Attrs, unsigned TagType,
3345 Decl *TagDecl);
3346 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3347 SourceLocation &EqualLoc);
3348 bool
3349 ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3350 VirtSpecifiers &VS,
3351 ExprResult &BitfieldSize,
3352 LateParsedAttrList &LateAttrs);
3353 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3354 VirtSpecifiers &VS);
3355 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3356 AccessSpecifier AS, ParsedAttributes &Attr,
3357 ParsedTemplateInfo &TemplateInfo,
3358 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3360 ParseCXXClassMemberDeclarationWithPragmas(AccessSpecifier &AS,
3361 ParsedAttributes &AccessAttrs,
3362 DeclSpec::TST TagType, Decl *Tag);
3363 void ParseConstructorInitializer(Decl *ConstructorDecl);
3364 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3365 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
3366 Decl *ThisDecl);
3367
3368 //===--------------------------------------------------------------------===//
3369 // C++ 10: Derived classes [class.derived]
3370 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3371 SourceLocation &EndLocation);
3372 void ParseBaseClause(Decl *ClassDecl);
3373 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3374 AccessSpecifier getAccessSpecifierIfPresent() const;
3375
3376 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
3377 ParsedType ObjectType,
3378 bool ObjectHadErrors,
3379 SourceLocation TemplateKWLoc,
3380 IdentifierInfo *Name,
3381 SourceLocation NameLoc,
3382 bool EnteringContext,
3383 UnqualifiedId &Id,
3384 bool AssumeTemplateId);
3385 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
3386 ParsedType ObjectType,
3387 UnqualifiedId &Result);
3388
3389 //===--------------------------------------------------------------------===//
3390 // OpenMP: Directives and clauses.
3391 /// Parse clauses for '#pragma omp declare simd'.
3392 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
3393 CachedTokens &Toks,
3394 SourceLocation Loc);
3395
3396 /// Parse a property kind into \p TIProperty for the selector set \p Set and
3397 /// selector \p Selector.
3398 void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
3399 llvm::omp::TraitSet Set,
3400 llvm::omp::TraitSelector Selector,
3401 llvm::StringMap<SourceLocation> &Seen);
3402
3403 /// Parse a selector kind into \p TISelector for the selector set \p Set.
3404 void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
3405 llvm::omp::TraitSet Set,
3406 llvm::StringMap<SourceLocation> &Seen);
3407
3408 /// Parse a selector set kind into \p TISet.
3409 void parseOMPTraitSetKind(OMPTraitSet &TISet,
3410 llvm::StringMap<SourceLocation> &Seen);
3411
3412 /// Parses an OpenMP context property.
3413 void parseOMPContextProperty(OMPTraitSelector &TISelector,
3414 llvm::omp::TraitSet Set,
3415 llvm::StringMap<SourceLocation> &Seen);
3416
3417 /// Parses an OpenMP context selector.
3418 void parseOMPContextSelector(OMPTraitSelector &TISelector,
3419 llvm::omp::TraitSet Set,
3420 llvm::StringMap<SourceLocation> &SeenSelectors);
3421
3422 /// Parses an OpenMP context selector set.
3423 void parseOMPContextSelectorSet(OMPTraitSet &TISet,
3424 llvm::StringMap<SourceLocation> &SeenSets);
3425
3426 /// Parses OpenMP context selectors.
3427 bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
3428
3429 /// Parse an 'append_args' clause for '#pragma omp declare variant'.
3430 bool parseOpenMPAppendArgs(SmallVectorImpl<OMPInteropInfo> &InteropInfos);
3431
3432 /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
3433 /// if there was an error.
3434 bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
3435 OMPTraitInfo *ParentTI);
3436
3437 /// Parse clauses for '#pragma omp declare variant'.
3438 void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
3439 SourceLocation Loc);
3440
3441 /// Parse 'omp [begin] assume[s]' directive.
3442 void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
3443 SourceLocation Loc);
3444
3445 /// Parse 'omp end assumes' directive.
3446 void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
3447
3448 /// Parses clauses for directive.
3449 ///
3450 /// \param DKind Kind of current directive.
3451 /// \param clauses for current directive.
3452 /// \param start location for clauses of current directive
3453 void ParseOpenMPClauses(OpenMPDirectiveKind DKind,
3454 SmallVectorImpl<clang::OMPClause *> &Clauses,
3455 SourceLocation Loc);
3456
3457 /// Parse clauses for '#pragma omp [begin] declare target'.
3458 void ParseOMPDeclareTargetClauses(SemaOpenMP::DeclareTargetContextInfo &DTCI);
3459
3460 /// Parse '#pragma omp end declare target'.
3461 void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
3462 OpenMPDirectiveKind EndDKind,
3463 SourceLocation Loc);
3464
3465 /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
3466 /// it is not the current token.
3467 void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
3468
3469 /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
3470 /// that the "end" matching the "begin" directive of kind \p BeginKind was not
3471 /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
3472 /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
3473 void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
3474 OpenMPDirectiveKind ExpectedKind,
3475 OpenMPDirectiveKind FoundKind,
3476 SourceLocation MatchingLoc,
3477 SourceLocation FoundLoc,
3478 bool SkipUntilOpenMPEnd);
3479
3480 /// Parses declarative OpenMP directives.
3481 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
3482 AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed = false,
3484 Decl *TagDecl = nullptr);
3485 /// Parse 'omp declare reduction' construct.
3486 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
3487 /// Parses initializer for provided omp_priv declaration inside the reduction
3488 /// initializer.
3489 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
3490
3491 /// Parses 'omp declare mapper' directive.
3492 DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
3493 /// Parses variable declaration in 'omp declare mapper' directive.
3494 TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
3495 DeclarationName &Name,
3497
3498 /// Tries to parse cast part of OpenMP array shaping operation:
3499 /// '[' expression ']' { '[' expression ']' } ')'.
3500 bool tryParseOpenMPArrayShapingCastPart();
3501
3502 /// Parses simple list of variables.
3503 ///
3504 /// \param Kind Kind of the directive.
3505 /// \param Callback Callback function to be called for the list elements.
3506 /// \param AllowScopeSpecifier true, if the variables can have fully
3507 /// qualified names.
3508 ///
3509 bool ParseOpenMPSimpleVarList(
3511 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
3512 Callback,
3513 bool AllowScopeSpecifier);
3514 /// Parses declarative or executable directive.
3515 ///
3516 /// \param StmtCtx The context in which we're parsing the directive.
3517 /// \param ReadDirectiveWithinMetadirective true if directive is within a
3518 /// metadirective and therefore ends on the closing paren.
3519 StmtResult ParseOpenMPDeclarativeOrExecutableDirective(
3520 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective = false);
3521
3522 /// Parses executable directive.
3523 ///
3524 /// \param StmtCtx The context in which we're parsing the directive.
3525 /// \param DKind The kind of the executable directive.
3526 /// \param Loc Source location of the beginning of the directive.
3527 /// \param ReadDirectiveWithinMetadirective true if directive is within a
3528 /// metadirective and therefore ends on the closing paren.
3530 ParseOpenMPExecutableDirective(ParsedStmtContext StmtCtx,
3531 OpenMPDirectiveKind DKind, SourceLocation Loc,
3532 bool ReadDirectiveWithinMetadirective);
3533
3534 /// Parses informational directive.
3535 ///
3536 /// \param StmtCtx The context in which we're parsing the directive.
3537 /// \param DKind The kind of the informational directive.
3538 /// \param Loc Source location of the beginning of the directive.
3539 /// \param ReadDirectiveWithinMetadirective true if directive is within a
3540 /// metadirective and therefore ends on the closing paren.
3541 StmtResult ParseOpenMPInformationalDirective(
3542 ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
3543 bool ReadDirectiveWithinMetadirective);
3544
3545 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
3546 ///
3547 /// \param DKind Kind of current directive.
3548 /// \param CKind Kind of current clause.
3549 /// \param FirstClause true, if this is the first clause of a kind \a CKind
3550 /// in current directive.
3551 ///
3552 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
3553 OpenMPClauseKind CKind, bool FirstClause);
3554 /// Parses clause with a single expression of a kind \a Kind.
3555 ///
3556 /// \param Kind Kind of current clause.
3557 /// \param ParseOnly true to skip the clause's semantic actions and return
3558 /// nullptr.
3559 ///
3560 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3561 bool ParseOnly);
3562 /// Parses simple clause of a kind \a Kind.
3563 ///
3564 /// \param Kind Kind of current clause.
3565 /// \param ParseOnly true to skip the clause's semantic actions and return
3566 /// nullptr.
3567 ///
3568 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
3569 /// Parses indirect clause
3570 /// \param ParseOnly true to skip the clause's semantic actions and return
3571 // false;
3572 bool ParseOpenMPIndirectClause(SemaOpenMP::DeclareTargetContextInfo &DTCI,
3573 bool ParseOnly);
3574 /// Parses clause with a single expression and an additional argument
3575 /// of a kind \a Kind.
3576 ///
3577 /// \param DKind Directive kind.
3578 /// \param Kind Kind of current clause.
3579 /// \param ParseOnly true to skip the clause's semantic actions and return
3580 /// nullptr.
3581 ///
3582 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3583 OpenMPClauseKind Kind,
3584 bool ParseOnly);
3585
3586 /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
3587 OMPClause *ParseOpenMPSizesClause();
3588
3589 /// Parses clause without any additional arguments.
3590 ///
3591 /// \param Kind Kind of current clause.
3592 /// \param ParseOnly true to skip the clause's semantic actions and return
3593 /// nullptr.
3594 ///
3595 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
3596 /// Parses clause with the list of variables of a kind \a Kind.
3597 ///
3598 /// \param Kind Kind of current clause.
3599 /// \param ParseOnly true to skip the clause's semantic actions and return
3600 /// nullptr.
3601 ///
3602 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
3603 OpenMPClauseKind Kind, bool ParseOnly);
3604
3605 /// Parses a clause consisting of a list of expressions.
3606 ///
3607 /// \param Kind The clause to parse.
3608 /// \param ClauseNameLoc [out] The location of the clause name.
3609 /// \param OpenLoc [out] The location of '('.
3610 /// \param CloseLoc [out] The location of ')'.
3611 /// \param Exprs [out] The parsed expressions.
3612 /// \param ReqIntConst If true, each expression must be an integer constant.
3613 ///
3614 /// \return Whether the clause was parsed successfully.
3615 bool ParseOpenMPExprListClause(OpenMPClauseKind Kind,
3616 SourceLocation &ClauseNameLoc,
3617 SourceLocation &OpenLoc,
3618 SourceLocation &CloseLoc,
3619 SmallVectorImpl<Expr *> &Exprs,
3620 bool ReqIntConst = false);
3621
3622 /// Parses and creates OpenMP 5.0 iterators expression:
3623 /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
3624 /// <range-specification> }+ ')'
3625 ExprResult ParseOpenMPIteratorsExpr();
3626
3627 /// Parses allocators and traits in the context of the uses_allocator clause.
3628 /// Expected format:
3629 /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
3630 OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
3631
3632 /// Parses the 'interop' parts of the 'append_args' and 'init' clauses.
3633 bool ParseOMPInteropInfo(OMPInteropInfo &InteropInfo, OpenMPClauseKind Kind);
3634
3635 /// Parses clause with an interop variable of kind \a Kind.
3636 ///
3637 /// \param Kind Kind of current clause.
3638 /// \param ParseOnly true to skip the clause's semantic actions and return
3639 /// nullptr.
3640 //
3641 OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
3642
3643 /// Parses a ompx_attribute clause
3644 ///
3645 /// \param ParseOnly true to skip the clause's semantic actions and return
3646 /// nullptr.
3647 //
3648 OMPClause *ParseOpenMPOMPXAttributesClause(bool ParseOnly);
3649
3650public:
3651 /// Parses simple expression in parens for single-expression clauses of OpenMP
3652 /// constructs.
3653 /// \param RLoc Returned location of right paren.
3654 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
3655 bool IsAddressOfOperand = false);
3656
3657 /// Parses a reserved locator like 'omp_all_memory'.
3659 SemaOpenMP::OpenMPVarListDataTy &Data,
3660 const LangOptions &LangOpts);
3661 /// Parses clauses with list.
3663 SmallVectorImpl<Expr *> &Vars,
3664 SemaOpenMP::OpenMPVarListDataTy &Data);
3665 bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
3666 bool ObjectHadErrors, bool EnteringContext,
3667 bool AllowDestructorName, bool AllowConstructorName,
3668 bool AllowDeductionGuide,
3669 SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
3670
3671 /// Parses the mapper modifier in map, to, and from clauses.
3672 bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data);
3673 /// Parses map-type-modifiers in map clause.
3674 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3675 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
3676 bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data);
3677
3678 //===--------------------------------------------------------------------===//
3679 // OpenACC Parsing.
3680
3681 /// Placeholder for now, should just ignore the directives after emitting a
3682 /// diagnostic. Eventually will be split into a few functions to parse
3683 /// different situations.
3684public:
3687
3688private:
3689 /// A struct to hold the information that got parsed by ParseOpenACCDirective,
3690 /// so that the callers of it can use that to construct the appropriate AST
3691 /// nodes.
3692 struct OpenACCDirectiveParseInfo {
3693 OpenACCDirectiveKind DirKind;
3694 SourceLocation StartLoc;
3695 SourceLocation DirLoc;
3696 SourceLocation EndLoc;
3697 SmallVector<OpenACCClause *> Clauses;
3698 // TODO OpenACC: As we implement support for the Atomic, Routine, Cache, and
3699 // Wait constructs, we likely want to put that information in here as well.
3700 };
3701
3702 struct OpenACCWaitParseInfo {
3703 bool Failed = false;
3704 Expr *DevNumExpr = nullptr;
3705 SourceLocation QueuesLoc;
3706 SmallVector<Expr *> QueueIdExprs;
3707 };
3708
3709 /// Represents the 'error' state of parsing an OpenACC Clause, and stores
3710 /// whether we can continue parsing, or should give up on the directive.
3711 enum class OpenACCParseCanContinue { Cannot = 0, Can = 1 };
3712
3713 /// A type to represent the state of parsing an OpenACC Clause. Situations
3714 /// that result in an OpenACCClause pointer are a success and can continue
3715 /// parsing, however some other situations can also continue.
3716 /// FIXME: This is better represented as a std::expected when we get C++23.
3717 using OpenACCClauseParseResult =
3718 llvm::PointerIntPair<OpenACCClause *, 1, OpenACCParseCanContinue>;
3719
3720 OpenACCClauseParseResult OpenACCCanContinue();
3721 OpenACCClauseParseResult OpenACCCannotContinue();
3722 OpenACCClauseParseResult OpenACCSuccess(OpenACCClause *Clause);
3723
3724 /// Parses the OpenACC directive (the entire pragma) including the clause
3725 /// list, but does not produce the main AST node.
3726 OpenACCDirectiveParseInfo ParseOpenACCDirective();
3727 /// Helper that parses an ID Expression based on the language options.
3728 ExprResult ParseOpenACCIDExpression();
3729 /// Parses the variable list for the `cache` construct.
3730 void ParseOpenACCCacheVarList();
3731
3732 using OpenACCVarParseResult = std::pair<ExprResult, OpenACCParseCanContinue>;
3733 /// Parses a single variable in a variable list for OpenACC.
3734 OpenACCVarParseResult ParseOpenACCVar(OpenACCClauseKind CK);
3735 /// Parses the variable list for the variety of places that take a var-list.
3736 llvm::SmallVector<Expr *> ParseOpenACCVarList(OpenACCClauseKind CK);
3737 /// Parses any parameters for an OpenACC Clause, including required/optional
3738 /// parens.
3739 OpenACCClauseParseResult
3740 ParseOpenACCClauseParams(ArrayRef<const OpenACCClause *> ExistingClauses,
3742 SourceLocation ClauseLoc);
3743 /// Parses a single clause in a clause-list for OpenACC. Returns nullptr on
3744 /// error.
3745 OpenACCClauseParseResult
3746 ParseOpenACCClause(ArrayRef<const OpenACCClause *> ExistingClauses,
3747 OpenACCDirectiveKind DirKind);
3748 /// Parses the clause-list for an OpenACC directive.
3749 SmallVector<OpenACCClause *>
3750 ParseOpenACCClauseList(OpenACCDirectiveKind DirKind);
3751 OpenACCWaitParseInfo ParseOpenACCWaitArgument(SourceLocation Loc,
3752 bool IsDirective);
3753 /// Parses the clause of the 'bind' argument, which can be a string literal or
3754 /// an ID expression.
3755 ExprResult ParseOpenACCBindClauseArgument();
3756
3757 /// A type to represent the state of parsing after an attempt to parse an
3758 /// OpenACC int-expr. This is useful to determine whether an int-expr list can
3759 /// continue parsing after a failed int-expr.
3760 using OpenACCIntExprParseResult =
3761 std::pair<ExprResult, OpenACCParseCanContinue>;
3762 /// Parses the clause kind of 'int-expr', which can be any integral
3763 /// expression.
3764 OpenACCIntExprParseResult ParseOpenACCIntExpr(OpenACCDirectiveKind DK,
3766 SourceLocation Loc);
3767 /// Parses the argument list for 'num_gangs', which allows up to 3
3768 /// 'int-expr's.
3769 bool ParseOpenACCIntExprList(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
3770 SourceLocation Loc,
3772 /// Parses the 'device-type-list', which is a list of identifiers.
3773 bool ParseOpenACCDeviceTypeList(
3774 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>> &Archs);
3775 /// Parses the 'async-argument', which is an integral value with two
3776 /// 'special' values that are likely negative (but come from Macros).
3777 OpenACCIntExprParseResult ParseOpenACCAsyncArgument(OpenACCDirectiveKind DK,
3779 SourceLocation Loc);
3780 /// Parses the 'size-expr', which is an integral value, or an asterisk.
3781 bool ParseOpenACCSizeExpr();
3782 /// Parses a comma delimited list of 'size-expr's.
3783 bool ParseOpenACCSizeExprList();
3784 /// Parses a 'gang-arg-list', used for the 'gang' clause.
3785 bool ParseOpenACCGangArgList(SourceLocation GangLoc);
3786 /// Parses a 'gang-arg', used for the 'gang' clause.
3787 bool ParseOpenACCGangArg(SourceLocation GangLoc);
3788 /// Parses a 'condition' expr, ensuring it results in a
3789 ExprResult ParseOpenACCConditionExpr();
3790
3791private:
3792 //===--------------------------------------------------------------------===//
3793 // C++ 14: Templates [temp]
3794
3795 // C++ 14.1: Template Parameters [temp.param]
3797 ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
3798 SourceLocation &DeclEnd,
3799 ParsedAttributes &AccessAttrs);
3800 DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
3801 DeclaratorContext Context, SourceLocation &DeclEnd,
3802 ParsedAttributes &AccessAttrs, AccessSpecifier AS);
3803 DeclGroupPtrTy ParseDeclarationAfterTemplate(
3804 DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo,
3805 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
3806 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
3807 bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
3808 SmallVectorImpl<NamedDecl *> &TemplateParams,
3809 SourceLocation &LAngleLoc,
3810 SourceLocation &RAngleLoc);
3811 bool ParseTemplateParameterList(unsigned Depth,
3812 SmallVectorImpl<NamedDecl*> &TemplateParams);
3813 TPResult isStartOfTemplateTypeParameter();
3814 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
3815 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
3816 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
3817 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
3818 bool isTypeConstraintAnnotation();
3819 bool TryAnnotateTypeConstraint();
3820 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
3821 SourceLocation CorrectLoc,
3822 bool AlreadyHasEllipsis,
3823 bool IdentifierHasName);
3824 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
3825 Declarator &D);
3826 // C++ 14.3: Template arguments [temp.arg]
3827 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
3828
3829 bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
3830 SourceLocation &RAngleLoc,
3831 bool ConsumeLastToken,
3832 bool ObjCGenericList);
3833 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
3834 SourceLocation &LAngleLoc,
3835 TemplateArgList &TemplateArgs,
3836 SourceLocation &RAngleLoc,
3837 TemplateTy NameHint = nullptr);
3838
3839 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
3840 CXXScopeSpec &SS,
3841 SourceLocation TemplateKWLoc,
3842 UnqualifiedId &TemplateName,
3843 bool AllowTypeAnnotation = true,
3844 bool TypeConstraint = false);
3845 void
3846 AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
3847 ImplicitTypenameContext AllowImplicitTypename,
3848 bool IsClassName = false);
3849 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
3850 TemplateTy Template, SourceLocation OpenLoc);
3851 ParsedTemplateArgument ParseTemplateTemplateArgument();
3852 ParsedTemplateArgument ParseTemplateArgument();
3853 DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context,
3854 SourceLocation ExternLoc,
3855 SourceLocation TemplateLoc,
3856 SourceLocation &DeclEnd,
3857 ParsedAttributes &AccessAttrs,
3859 // C++2a: Template, concept definition [temp]
3860 Decl *
3861 ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
3862 SourceLocation &DeclEnd);
3863
3864 /// Parse the given string as a type.
3865 ///
3866 /// This is a dangerous utility function currently employed only by API notes.
3867 /// It is not a general entry-point for safely parsing types from strings.
3868 ///
3869 /// \param TypeStr The string to be parsed as a type.
3870 /// \param Context The name of the context in which this string is being
3871 /// parsed, which will be used in diagnostics.
3872 /// \param IncludeLoc The location at which this parse was triggered.
3873 TypeResult ParseTypeFromString(StringRef TypeStr, StringRef Context,
3874 SourceLocation IncludeLoc);
3875
3876 //===--------------------------------------------------------------------===//
3877 // Modules
3878 DeclGroupPtrTy ParseModuleDecl(Sema::ModuleImportState &ImportState);
3879 Decl *ParseModuleImport(SourceLocation AtLoc,
3880 Sema::ModuleImportState &ImportState);
3881 bool parseMisplacedModuleImport();
3882 bool tryParseMisplacedModuleImport() {
3883 tok::TokenKind Kind = Tok.getKind();
3884 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
3885 Kind == tok::annot_module_include)
3886 return parseMisplacedModuleImport();
3887 return false;
3888 }
3889
3890 bool ParseModuleName(
3891 SourceLocation UseLoc,
3892 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
3893 bool IsImport);
3894
3895 //===--------------------------------------------------------------------===//
3896 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
3897 ExprResult ParseTypeTrait();
3898
3899 //===--------------------------------------------------------------------===//
3900 // Embarcadero: Arary and Expression Traits
3901 ExprResult ParseArrayTypeTrait();
3902 ExprResult ParseExpressionTrait();
3903
3904 ExprResult ParseBuiltinPtrauthTypeDiscriminator();
3905
3906 //===--------------------------------------------------------------------===//
3907 // Preprocessor code-completion pass-through
3908 void CodeCompleteDirective(bool InConditional) override;
3909 void CodeCompleteInConditionalExclusion() override;
3910 void CodeCompleteMacroName(bool IsDefinition) override;
3911 void CodeCompletePreprocessorExpression() override;
3912 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
3913 unsigned ArgumentIndex) override;
3914 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
3915 void CodeCompleteNaturalLanguage() override;
3916
3917 class GNUAsmQualifiers {
3918 unsigned Qualifiers = AQ_unspecified;
3919
3920 public:
3921 enum AQ {
3922 AQ_unspecified = 0,
3923 AQ_volatile = 1,
3924 AQ_inline = 2,
3925 AQ_goto = 4,
3926 };
3927 static const char *getQualifierName(AQ Qualifier);
3928 bool setAsmQualifier(AQ Qualifier);
3929 inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
3930 inline bool isInline() const { return Qualifiers & AQ_inline; };
3931 inline bool isGoto() const { return Qualifiers & AQ_goto; }
3932 };
3933 bool isGCCAsmStatement(const Token &TokAfterAsm) const;
3934 bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
3935 GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
3936 bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
3937};
3938
3939} // end namespace clang
3940
3941#endif
StringRef P
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1658::IndirectLocalPathEntry::EntryKind Kind
int Priority
Definition: Format.cpp:3005
Defines some OpenACC-specific enums and functions.
Defines and computes precedence levels for binary/ternary operators.
Defines the clang::Preprocessor interface.
uint32_t Id
Definition: SemaARM.cpp:1143
This file declares facilities that support code completion.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
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)
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
bool isInvalid() const
Definition: Ownership.h:166
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:639
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Callback handler that receives notifications when performing code completion within the preprocessor.
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
TypeSpecifierType TST
Definition: DeclSpec.h:277
static const TST TST_unspecified
Definition: DeclSpec.h:278
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
This represents one expression.
Definition: Expr.h:110
One of these records is kept for each identifier that is lexed.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
Wrapper for void* pointer.
Definition: Ownership.h:50
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
Introduces zero or more scopes for parsing.
Definition: Parser.h:1209
MultiParseScope(Parser &Self)
Definition: Parser.h:1216
void Enter(unsigned ScopeFlags)
Definition: Parser.h:1217
ParseScope - Introduces a new scope for parsing.
Definition: Parser.h:1171
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope=true, bool BeforeCompoundStmt=false)
Definition: Parser.h:1180
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
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 type-name: [C99 6.7.6] specifier-qualifier-list abstract-declarator[opt].
Definition: ParseDecl.cpp:50
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:81
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:2124
Preprocessor & getPreprocessor() const
Definition: Parser.h:497
bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data)
Parses map-type-modifiers in map clause.
Sema::FullExprArg FullExprArg
Definition: Parser.h:518
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:548
DeclGroupPtrTy ParseOpenACCDirectiveDecl()
Placeholder for now, should just ignore the directives after emitting a diagnostic.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition: Parser.cpp:54
AttributeFactory & getAttrFactory()
Definition: Parser.h:499
void incrementMSManglingNumber() const
Definition: Parser.h:503
Sema & getActions() const
Definition: Parser.h:498
bool ParseTopLevelDecl()
Definition: Parser.h:537
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:877
ExprResult ParseCaseExpression(SourceLocation CaseLoc)
Definition: ParseExpr.cpp:252
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition: Parser.cpp:420
bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data)
Parses the mapper modifier in map, to, and from clauses.
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:380
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl< Token > &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated)
Parse an identifier in an MS-style inline assembly block.
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:936
friend class ColonProtectionRAIIObject
Definition: Parser.h:59
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
Definition: Parser.h:1298
~Parser() override
Definition: Parser.cpp:470
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:576
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:233
StmtResult ParseOpenACCDirectiveStmt()
ExprResult ParseConditionalExpression()
Definition: ParseExpr.cpp:188
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:556
friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R)
Definition: Parser.h:1279
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:513
Scope * getCurScope() const
Definition: Parser.h:502
SourceLocation getEndOfPreviousToken()
Definition: Parser.h:594
ExprResult ParseArrayBoundExpression()
Definition: ParseExpr.cpp:243
ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-and-expression.
Definition: ParseExpr.cpp:288
const TargetInfo & getTargetInfo() const
Definition: Parser.h:496
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:514
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:1294
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:2214
const Token & getCurToken() const
Definition: Parser.h:501
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds to the given nullability kind...
Definition: Parser.h:600
friend class ObjCDeclContextSwitch
Definition: Parser.h:65
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
Definition: Parser.h:1303
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition: Parser.cpp:431
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:169
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand=false)
Parses simple expression in parens for single-expression clauses of OpenMP constructs.
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:223
SourceLocation MisleadingIndentationElseLoc
The location of the first statement inside an else that might have a missleading indentation.
Definition: Parser.h:1318
const LangOptions & getLangOpts() const
Definition: Parser.h:495
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:132
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
Definition: Parser.cpp:601
DiagnosticBuilder Diag(unsigned DiagID)
Definition: Parser.h:1260
SmallVector< Stmt *, 32 > StmtVector
A SmallVector of statements.
Definition: Parser.h:521
SkipUntilFlags
Control flags for SkipUntil functions.
Definition: Parser.h:1272
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1275
@ StopAtCodeCompletion
Stop at code completion.
Definition: Parser.h:1276
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1273
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1995
bool MightBeCXXScopeToken()
Definition: Parser.h:929
TypeCastState
TypeCastState - State whether an expression is or may be a type cast.
Definition: Parser.h:1837
ExprResult ParseUnevaluatedStringLiteralExpression()
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
bool ParseOpenMPReservedLocator(OpenMPClauseKind Kind, SemaOpenMP::OpenMPVarListDataTy &Data, const LangOptions &LangOpts)
Parses a reserved locator like 'omp_all_memory'.
ObjCContainerDecl * getObjCDeclContext() const
Definition: Parser.h:507
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:872
friend class BalancedDelimiterTracker
Definition: Parser.h:67
bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc)
Definition: Parser.h:566
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:266
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:516
void Initialize()
Initialize - Warm up the parser.
Definition: Parser.cpp:490
unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D)
Re-enter the template scopes for a declaration that might be a template.
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:2239
Activates OpenACC parsing mode to preseve OpenACC specific annotation tokens.
Activates OpenMP parsing mode to preseve OpenMP specific annotation tokens.
Tracks expected type during expression parsing, for use in code completion.
Definition: Sema.h:312
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
void setCodeCompletionReached()
Note that we hit the code-completion point.
bool mightHavePendingAnnotationTokens()
Determine whether it's possible for a future call to Lex to produce an annotation token created by a ...
void Lex(Token &Result)
Lex the next token for this preprocessor.
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
const TargetInfo & getTargetInfo() const
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
const LangOptions & getLangOpts() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ObjCContainerDecl * getObjCDeclContext() const
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:535
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:803
SemaOpenMP & OpenMP()
Definition: Sema.h:1219
ConditionKind
Definition: Sema.h:7356
SemaObjC & ObjC()
Definition: Sema.h:1204
ProcessingContextState ParsingClassState
Definition: Sema.h:6075
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
Definition: SemaType.cpp:3748
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition: Sema.h:9625
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
void incrementMSManglingNumber() const
Definition: Sema.h:967
OffsetOfKind
Definition: Sema.h:3864
@ OOK_Outside
Definition: Sema.h:3866
Encodes a location in the source.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition: TargetInfo.h:218
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
void setKind(tok::TokenKind K)
Definition: Token.h:95
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:146
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
void * getAnnotationValue() const
Definition: Token.h:234
tok::TokenKind getKind() const
Definition: Token.h:94
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
void setAnnotationValue(void *val)
Definition: Token.h:238
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
bool Pop(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1156
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
Definition: OpenACCKinds.h:164
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ TST_unspecified
Definition: Specifiers.h:56
ImplicitTypenameContext
Definition: DeclSpec.h:1886
@ CPlusPlus
Definition: LangStandard.h:56
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition: OpenMPKinds.h:24
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
TypeResult TypeError()
Definition: Ownership.h:266
ActionResult< CXXCtorInitializer * > MemInitResult
Definition: Ownership.h:252
DeclaratorContext
Definition: DeclSpec.h:1853
@ Result
The result type of a method or function.
TagUseKind
Definition: Sema.h:469
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
OpenACCDirectiveKind
Definition: OpenACCKinds.h:25
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition: DeclSpec.h:1245
@ Class
The "class" keyword introduces the elaborated-type-specifier.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
ActionResult< CXXBaseSpecifier * > BaseResult
Definition: Ownership.h:251
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
#define false
Definition: stdbool.h:26
AngleBracketTracker::Priority Priority
Definition: Parser.h:394
bool isActive(Parser &P) const
Definition: Parser.h:397
bool isActiveOrNested(Parser &P) const
Definition: Parser.h:402