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