Warning: This file is not a C or C++ file. It does not have highlighting.

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

Warning: This file is not a C or C++ file. It does not have highlighting.

source code of clang/include/clang/Parse/Parser.h