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