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