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