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