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