xref: /minix3/external/bsd/llvm/dist/clang/lib/Parse/Parser.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- Parser.cpp - C Language Family Parser ----------------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc //  This file implements the Parser interfaces.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc 
14f4a2713aSLionel Sambuc #include "clang/Parse/Parser.h"
15f4a2713aSLionel Sambuc #include "RAIIObjectsForParser.h"
16f4a2713aSLionel Sambuc #include "clang/AST/ASTConsumer.h"
17*0a6a1f1dSLionel Sambuc #include "clang/AST/ASTContext.h"
18f4a2713aSLionel Sambuc #include "clang/AST/DeclTemplate.h"
19f4a2713aSLionel Sambuc #include "clang/Parse/ParseDiagnostic.h"
20f4a2713aSLionel Sambuc #include "clang/Sema/DeclSpec.h"
21f4a2713aSLionel Sambuc #include "clang/Sema/ParsedTemplate.h"
22f4a2713aSLionel Sambuc #include "clang/Sema/Scope.h"
23f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
24f4a2713aSLionel Sambuc using namespace clang;
25f4a2713aSLionel Sambuc 
26f4a2713aSLionel Sambuc 
27f4a2713aSLionel Sambuc namespace {
28f4a2713aSLionel Sambuc /// \brief A comment handler that passes comments found by the preprocessor
29f4a2713aSLionel Sambuc /// to the parser action.
30f4a2713aSLionel Sambuc class ActionCommentHandler : public CommentHandler {
31f4a2713aSLionel Sambuc   Sema &S;
32f4a2713aSLionel Sambuc 
33f4a2713aSLionel Sambuc public:
ActionCommentHandler(Sema & S)34f4a2713aSLionel Sambuc   explicit ActionCommentHandler(Sema &S) : S(S) { }
35f4a2713aSLionel Sambuc 
HandleComment(Preprocessor & PP,SourceRange Comment)36*0a6a1f1dSLionel Sambuc   bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
37f4a2713aSLionel Sambuc     S.ActOnComment(Comment);
38f4a2713aSLionel Sambuc     return false;
39f4a2713aSLionel Sambuc   }
40f4a2713aSLionel Sambuc };
41f4a2713aSLionel Sambuc } // end anonymous namespace
42f4a2713aSLionel Sambuc 
getSEHExceptKeyword()43f4a2713aSLionel Sambuc IdentifierInfo *Parser::getSEHExceptKeyword() {
44f4a2713aSLionel Sambuc   // __except is accepted as a (contextual) keyword
45f4a2713aSLionel Sambuc   if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
46f4a2713aSLionel Sambuc     Ident__except = PP.getIdentifierInfo("__except");
47f4a2713aSLionel Sambuc 
48f4a2713aSLionel Sambuc   return Ident__except;
49f4a2713aSLionel Sambuc }
50f4a2713aSLionel Sambuc 
Parser(Preprocessor & pp,Sema & actions,bool skipFunctionBodies)51f4a2713aSLionel Sambuc Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52f4a2713aSLionel Sambuc   : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
53f4a2713aSLionel Sambuc     GreaterThanIsOperator(true), ColonIsSacred(false),
54f4a2713aSLionel Sambuc     InMessageExpression(false), TemplateParameterDepth(0),
55f4a2713aSLionel Sambuc     ParsingInObjCContainer(false) {
56f4a2713aSLionel Sambuc   SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
57f4a2713aSLionel Sambuc   Tok.startToken();
58f4a2713aSLionel Sambuc   Tok.setKind(tok::eof);
59*0a6a1f1dSLionel Sambuc   Actions.CurScope = nullptr;
60f4a2713aSLionel Sambuc   NumCachedScopes = 0;
61f4a2713aSLionel Sambuc   ParenCount = BracketCount = BraceCount = 0;
62*0a6a1f1dSLionel Sambuc   CurParsedObjCImpl = nullptr;
63f4a2713aSLionel Sambuc 
64f4a2713aSLionel Sambuc   // Add #pragma handlers. These are removed and destroyed in the
65f4a2713aSLionel Sambuc   // destructor.
66*0a6a1f1dSLionel Sambuc   initializePragmaHandlers();
67f4a2713aSLionel Sambuc 
68f4a2713aSLionel Sambuc   CommentSemaHandler.reset(new ActionCommentHandler(actions));
69f4a2713aSLionel Sambuc   PP.addCommentHandler(CommentSemaHandler.get());
70f4a2713aSLionel Sambuc 
71f4a2713aSLionel Sambuc   PP.setCodeCompletionHandler(*this);
72f4a2713aSLionel Sambuc }
73f4a2713aSLionel Sambuc 
Diag(SourceLocation Loc,unsigned DiagID)74f4a2713aSLionel Sambuc DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
75f4a2713aSLionel Sambuc   return Diags.Report(Loc, DiagID);
76f4a2713aSLionel Sambuc }
77f4a2713aSLionel Sambuc 
Diag(const Token & Tok,unsigned DiagID)78f4a2713aSLionel Sambuc DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
79f4a2713aSLionel Sambuc   return Diag(Tok.getLocation(), DiagID);
80f4a2713aSLionel Sambuc }
81f4a2713aSLionel Sambuc 
82f4a2713aSLionel Sambuc /// \brief Emits a diagnostic suggesting parentheses surrounding a
83f4a2713aSLionel Sambuc /// given range.
84f4a2713aSLionel Sambuc ///
85f4a2713aSLionel Sambuc /// \param Loc The location where we'll emit the diagnostic.
86f4a2713aSLionel Sambuc /// \param DK The kind of diagnostic to emit.
87f4a2713aSLionel Sambuc /// \param ParenRange Source range enclosing code that should be parenthesized.
SuggestParentheses(SourceLocation Loc,unsigned DK,SourceRange ParenRange)88f4a2713aSLionel Sambuc void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
89f4a2713aSLionel Sambuc                                 SourceRange ParenRange) {
90f4a2713aSLionel Sambuc   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
91f4a2713aSLionel Sambuc   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
92f4a2713aSLionel Sambuc     // We can't display the parentheses, so just dig the
93f4a2713aSLionel Sambuc     // warning/error and return.
94f4a2713aSLionel Sambuc     Diag(Loc, DK);
95f4a2713aSLionel Sambuc     return;
96f4a2713aSLionel Sambuc   }
97f4a2713aSLionel Sambuc 
98f4a2713aSLionel Sambuc   Diag(Loc, DK)
99f4a2713aSLionel Sambuc     << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
100f4a2713aSLionel Sambuc     << FixItHint::CreateInsertion(EndLoc, ")");
101f4a2713aSLionel Sambuc }
102f4a2713aSLionel Sambuc 
IsCommonTypo(tok::TokenKind ExpectedTok,const Token & Tok)103f4a2713aSLionel Sambuc static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
104f4a2713aSLionel Sambuc   switch (ExpectedTok) {
105f4a2713aSLionel Sambuc   case tok::semi:
106f4a2713aSLionel Sambuc     return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
107f4a2713aSLionel Sambuc   default: return false;
108f4a2713aSLionel Sambuc   }
109f4a2713aSLionel Sambuc }
110f4a2713aSLionel Sambuc 
ExpectAndConsume(tok::TokenKind ExpectedTok,unsigned DiagID,StringRef Msg)111f4a2713aSLionel Sambuc bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
112*0a6a1f1dSLionel Sambuc                               StringRef Msg) {
113f4a2713aSLionel Sambuc   if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
114f4a2713aSLionel Sambuc     ConsumeAnyToken();
115f4a2713aSLionel Sambuc     return false;
116f4a2713aSLionel Sambuc   }
117f4a2713aSLionel Sambuc 
118f4a2713aSLionel Sambuc   // Detect common single-character typos and resume.
119f4a2713aSLionel Sambuc   if (IsCommonTypo(ExpectedTok, Tok)) {
120f4a2713aSLionel Sambuc     SourceLocation Loc = Tok.getLocation();
121*0a6a1f1dSLionel Sambuc     {
122*0a6a1f1dSLionel Sambuc       DiagnosticBuilder DB = Diag(Loc, DiagID);
123*0a6a1f1dSLionel Sambuc       DB << FixItHint::CreateReplacement(
124*0a6a1f1dSLionel Sambuc                 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
125*0a6a1f1dSLionel Sambuc       if (DiagID == diag::err_expected)
126*0a6a1f1dSLionel Sambuc         DB << ExpectedTok;
127*0a6a1f1dSLionel Sambuc       else if (DiagID == diag::err_expected_after)
128*0a6a1f1dSLionel Sambuc         DB << Msg << ExpectedTok;
129*0a6a1f1dSLionel Sambuc       else
130*0a6a1f1dSLionel Sambuc         DB << Msg;
131*0a6a1f1dSLionel Sambuc     }
132f4a2713aSLionel Sambuc 
133f4a2713aSLionel Sambuc     // Pretend there wasn't a problem.
134*0a6a1f1dSLionel Sambuc     ConsumeAnyToken();
135f4a2713aSLionel Sambuc     return false;
136f4a2713aSLionel Sambuc   }
137f4a2713aSLionel Sambuc 
138f4a2713aSLionel Sambuc   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
139*0a6a1f1dSLionel Sambuc   const char *Spelling = nullptr;
140*0a6a1f1dSLionel Sambuc   if (EndLoc.isValid())
141*0a6a1f1dSLionel Sambuc     Spelling = tok::getPunctuatorSpelling(ExpectedTok);
142f4a2713aSLionel Sambuc 
143*0a6a1f1dSLionel Sambuc   DiagnosticBuilder DB =
144*0a6a1f1dSLionel Sambuc       Spelling
145*0a6a1f1dSLionel Sambuc           ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
146*0a6a1f1dSLionel Sambuc           : Diag(Tok, DiagID);
147*0a6a1f1dSLionel Sambuc   if (DiagID == diag::err_expected)
148*0a6a1f1dSLionel Sambuc     DB << ExpectedTok;
149*0a6a1f1dSLionel Sambuc   else if (DiagID == diag::err_expected_after)
150*0a6a1f1dSLionel Sambuc     DB << Msg << ExpectedTok;
151*0a6a1f1dSLionel Sambuc   else
152*0a6a1f1dSLionel Sambuc     DB << Msg;
153*0a6a1f1dSLionel Sambuc 
154f4a2713aSLionel Sambuc   return true;
155f4a2713aSLionel Sambuc }
156f4a2713aSLionel Sambuc 
ExpectAndConsumeSemi(unsigned DiagID)157f4a2713aSLionel Sambuc bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
158*0a6a1f1dSLionel Sambuc   if (TryConsumeToken(tok::semi))
159*0a6a1f1dSLionel Sambuc     return false;
160*0a6a1f1dSLionel Sambuc 
161*0a6a1f1dSLionel Sambuc   if (Tok.is(tok::code_completion)) {
162*0a6a1f1dSLionel Sambuc     handleUnexpectedCodeCompletionToken();
163f4a2713aSLionel Sambuc     return false;
164f4a2713aSLionel Sambuc   }
165f4a2713aSLionel Sambuc 
166f4a2713aSLionel Sambuc   if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
167f4a2713aSLionel Sambuc       NextToken().is(tok::semi)) {
168f4a2713aSLionel Sambuc     Diag(Tok, diag::err_extraneous_token_before_semi)
169f4a2713aSLionel Sambuc       << PP.getSpelling(Tok)
170f4a2713aSLionel Sambuc       << FixItHint::CreateRemoval(Tok.getLocation());
171f4a2713aSLionel Sambuc     ConsumeAnyToken(); // The ')' or ']'.
172f4a2713aSLionel Sambuc     ConsumeToken(); // The ';'.
173f4a2713aSLionel Sambuc     return false;
174f4a2713aSLionel Sambuc   }
175f4a2713aSLionel Sambuc 
176f4a2713aSLionel Sambuc   return ExpectAndConsume(tok::semi, DiagID);
177f4a2713aSLionel Sambuc }
178f4a2713aSLionel Sambuc 
ConsumeExtraSemi(ExtraSemiKind Kind,unsigned TST)179f4a2713aSLionel Sambuc void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
180f4a2713aSLionel Sambuc   if (!Tok.is(tok::semi)) return;
181f4a2713aSLionel Sambuc 
182f4a2713aSLionel Sambuc   bool HadMultipleSemis = false;
183f4a2713aSLionel Sambuc   SourceLocation StartLoc = Tok.getLocation();
184f4a2713aSLionel Sambuc   SourceLocation EndLoc = Tok.getLocation();
185f4a2713aSLionel Sambuc   ConsumeToken();
186f4a2713aSLionel Sambuc 
187f4a2713aSLionel Sambuc   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
188f4a2713aSLionel Sambuc     HadMultipleSemis = true;
189f4a2713aSLionel Sambuc     EndLoc = Tok.getLocation();
190f4a2713aSLionel Sambuc     ConsumeToken();
191f4a2713aSLionel Sambuc   }
192f4a2713aSLionel Sambuc 
193f4a2713aSLionel Sambuc   // C++11 allows extra semicolons at namespace scope, but not in any of the
194f4a2713aSLionel Sambuc   // other contexts.
195f4a2713aSLionel Sambuc   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
196f4a2713aSLionel Sambuc     if (getLangOpts().CPlusPlus11)
197f4a2713aSLionel Sambuc       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
198f4a2713aSLionel Sambuc           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
199f4a2713aSLionel Sambuc     else
200f4a2713aSLionel Sambuc       Diag(StartLoc, diag::ext_extra_semi_cxx11)
201f4a2713aSLionel Sambuc           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
202f4a2713aSLionel Sambuc     return;
203f4a2713aSLionel Sambuc   }
204f4a2713aSLionel Sambuc 
205f4a2713aSLionel Sambuc   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
206f4a2713aSLionel Sambuc     Diag(StartLoc, diag::ext_extra_semi)
207*0a6a1f1dSLionel Sambuc         << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST,
208*0a6a1f1dSLionel Sambuc                                     Actions.getASTContext().getPrintingPolicy())
209f4a2713aSLionel Sambuc         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
210f4a2713aSLionel Sambuc   else
211f4a2713aSLionel Sambuc     // A single semicolon is valid after a member function definition.
212f4a2713aSLionel Sambuc     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
213f4a2713aSLionel Sambuc       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
214f4a2713aSLionel Sambuc }
215f4a2713aSLionel Sambuc 
216f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
217f4a2713aSLionel Sambuc // Error recovery.
218f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
219f4a2713aSLionel Sambuc 
HasFlagsSet(Parser::SkipUntilFlags L,Parser::SkipUntilFlags R)220f4a2713aSLionel Sambuc static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
221f4a2713aSLionel Sambuc   return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
222f4a2713aSLionel Sambuc }
223f4a2713aSLionel Sambuc 
224f4a2713aSLionel Sambuc /// SkipUntil - Read tokens until we get to the specified token, then consume
225f4a2713aSLionel Sambuc /// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
226f4a2713aSLionel Sambuc /// token will ever occur, this skips to the next token, or to some likely
227f4a2713aSLionel Sambuc /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
228f4a2713aSLionel Sambuc /// character.
229f4a2713aSLionel Sambuc ///
230f4a2713aSLionel Sambuc /// If SkipUntil finds the specified token, it returns true, otherwise it
231f4a2713aSLionel Sambuc /// returns false.
SkipUntil(ArrayRef<tok::TokenKind> Toks,SkipUntilFlags Flags)232f4a2713aSLionel Sambuc bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
233f4a2713aSLionel Sambuc   // We always want this function to skip at least one token if the first token
234f4a2713aSLionel Sambuc   // isn't T and if not at EOF.
235f4a2713aSLionel Sambuc   bool isFirstTokenSkipped = true;
236f4a2713aSLionel Sambuc   while (1) {
237f4a2713aSLionel Sambuc     // If we found one of the tokens, stop and return true.
238f4a2713aSLionel Sambuc     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
239f4a2713aSLionel Sambuc       if (Tok.is(Toks[i])) {
240f4a2713aSLionel Sambuc         if (HasFlagsSet(Flags, StopBeforeMatch)) {
241f4a2713aSLionel Sambuc           // Noop, don't consume the token.
242f4a2713aSLionel Sambuc         } else {
243f4a2713aSLionel Sambuc           ConsumeAnyToken();
244f4a2713aSLionel Sambuc         }
245f4a2713aSLionel Sambuc         return true;
246f4a2713aSLionel Sambuc       }
247f4a2713aSLionel Sambuc     }
248f4a2713aSLionel Sambuc 
249f4a2713aSLionel Sambuc     // Important special case: The caller has given up and just wants us to
250f4a2713aSLionel Sambuc     // skip the rest of the file. Do this without recursing, since we can
251f4a2713aSLionel Sambuc     // get here precisely because the caller detected too much recursion.
252f4a2713aSLionel Sambuc     if (Toks.size() == 1 && Toks[0] == tok::eof &&
253f4a2713aSLionel Sambuc         !HasFlagsSet(Flags, StopAtSemi) &&
254f4a2713aSLionel Sambuc         !HasFlagsSet(Flags, StopAtCodeCompletion)) {
255*0a6a1f1dSLionel Sambuc       while (Tok.isNot(tok::eof))
256f4a2713aSLionel Sambuc         ConsumeAnyToken();
257f4a2713aSLionel Sambuc       return true;
258f4a2713aSLionel Sambuc     }
259f4a2713aSLionel Sambuc 
260f4a2713aSLionel Sambuc     switch (Tok.getKind()) {
261f4a2713aSLionel Sambuc     case tok::eof:
262f4a2713aSLionel Sambuc       // Ran out of tokens.
263f4a2713aSLionel Sambuc       return false;
264f4a2713aSLionel Sambuc 
265*0a6a1f1dSLionel Sambuc     case tok::annot_pragma_openmp_end:
266*0a6a1f1dSLionel Sambuc       // Stop before an OpenMP pragma boundary.
267*0a6a1f1dSLionel Sambuc     case tok::annot_module_begin:
268*0a6a1f1dSLionel Sambuc     case tok::annot_module_end:
269*0a6a1f1dSLionel Sambuc     case tok::annot_module_include:
270*0a6a1f1dSLionel Sambuc       // Stop before we change submodules. They generally indicate a "good"
271*0a6a1f1dSLionel Sambuc       // place to pick up parsing again (except in the special case where
272*0a6a1f1dSLionel Sambuc       // we're trying to skip to EOF).
273*0a6a1f1dSLionel Sambuc       return false;
274*0a6a1f1dSLionel Sambuc 
275f4a2713aSLionel Sambuc     case tok::code_completion:
276f4a2713aSLionel Sambuc       if (!HasFlagsSet(Flags, StopAtCodeCompletion))
277*0a6a1f1dSLionel Sambuc         handleUnexpectedCodeCompletionToken();
278f4a2713aSLionel Sambuc       return false;
279f4a2713aSLionel Sambuc 
280f4a2713aSLionel Sambuc     case tok::l_paren:
281f4a2713aSLionel Sambuc       // Recursively skip properly-nested parens.
282f4a2713aSLionel Sambuc       ConsumeParen();
283f4a2713aSLionel Sambuc       if (HasFlagsSet(Flags, StopAtCodeCompletion))
284f4a2713aSLionel Sambuc         SkipUntil(tok::r_paren, StopAtCodeCompletion);
285f4a2713aSLionel Sambuc       else
286f4a2713aSLionel Sambuc         SkipUntil(tok::r_paren);
287f4a2713aSLionel Sambuc       break;
288f4a2713aSLionel Sambuc     case tok::l_square:
289f4a2713aSLionel Sambuc       // Recursively skip properly-nested square brackets.
290f4a2713aSLionel Sambuc       ConsumeBracket();
291f4a2713aSLionel Sambuc       if (HasFlagsSet(Flags, StopAtCodeCompletion))
292f4a2713aSLionel Sambuc         SkipUntil(tok::r_square, StopAtCodeCompletion);
293f4a2713aSLionel Sambuc       else
294f4a2713aSLionel Sambuc         SkipUntil(tok::r_square);
295f4a2713aSLionel Sambuc       break;
296f4a2713aSLionel Sambuc     case tok::l_brace:
297f4a2713aSLionel Sambuc       // Recursively skip properly-nested braces.
298f4a2713aSLionel Sambuc       ConsumeBrace();
299f4a2713aSLionel Sambuc       if (HasFlagsSet(Flags, StopAtCodeCompletion))
300f4a2713aSLionel Sambuc         SkipUntil(tok::r_brace, StopAtCodeCompletion);
301f4a2713aSLionel Sambuc       else
302f4a2713aSLionel Sambuc         SkipUntil(tok::r_brace);
303f4a2713aSLionel Sambuc       break;
304f4a2713aSLionel Sambuc 
305f4a2713aSLionel Sambuc     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
306f4a2713aSLionel Sambuc     // Since the user wasn't looking for this token (if they were, it would
307f4a2713aSLionel Sambuc     // already be handled), this isn't balanced.  If there is a LHS token at a
308f4a2713aSLionel Sambuc     // higher level, we will assume that this matches the unbalanced token
309f4a2713aSLionel Sambuc     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
310f4a2713aSLionel Sambuc     case tok::r_paren:
311f4a2713aSLionel Sambuc       if (ParenCount && !isFirstTokenSkipped)
312f4a2713aSLionel Sambuc         return false;  // Matches something.
313f4a2713aSLionel Sambuc       ConsumeParen();
314f4a2713aSLionel Sambuc       break;
315f4a2713aSLionel Sambuc     case tok::r_square:
316f4a2713aSLionel Sambuc       if (BracketCount && !isFirstTokenSkipped)
317f4a2713aSLionel Sambuc         return false;  // Matches something.
318f4a2713aSLionel Sambuc       ConsumeBracket();
319f4a2713aSLionel Sambuc       break;
320f4a2713aSLionel Sambuc     case tok::r_brace:
321f4a2713aSLionel Sambuc       if (BraceCount && !isFirstTokenSkipped)
322f4a2713aSLionel Sambuc         return false;  // Matches something.
323f4a2713aSLionel Sambuc       ConsumeBrace();
324f4a2713aSLionel Sambuc       break;
325f4a2713aSLionel Sambuc 
326f4a2713aSLionel Sambuc     case tok::string_literal:
327f4a2713aSLionel Sambuc     case tok::wide_string_literal:
328f4a2713aSLionel Sambuc     case tok::utf8_string_literal:
329f4a2713aSLionel Sambuc     case tok::utf16_string_literal:
330f4a2713aSLionel Sambuc     case tok::utf32_string_literal:
331f4a2713aSLionel Sambuc       ConsumeStringToken();
332f4a2713aSLionel Sambuc       break;
333f4a2713aSLionel Sambuc 
334f4a2713aSLionel Sambuc     case tok::semi:
335f4a2713aSLionel Sambuc       if (HasFlagsSet(Flags, StopAtSemi))
336f4a2713aSLionel Sambuc         return false;
337f4a2713aSLionel Sambuc       // FALL THROUGH.
338f4a2713aSLionel Sambuc     default:
339f4a2713aSLionel Sambuc       // Skip this token.
340f4a2713aSLionel Sambuc       ConsumeToken();
341f4a2713aSLionel Sambuc       break;
342f4a2713aSLionel Sambuc     }
343f4a2713aSLionel Sambuc     isFirstTokenSkipped = false;
344f4a2713aSLionel Sambuc   }
345f4a2713aSLionel Sambuc }
346f4a2713aSLionel Sambuc 
347f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
348f4a2713aSLionel Sambuc // Scope manipulation
349f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
350f4a2713aSLionel Sambuc 
351f4a2713aSLionel Sambuc /// EnterScope - Start a new scope.
EnterScope(unsigned ScopeFlags)352f4a2713aSLionel Sambuc void Parser::EnterScope(unsigned ScopeFlags) {
353f4a2713aSLionel Sambuc   if (NumCachedScopes) {
354f4a2713aSLionel Sambuc     Scope *N = ScopeCache[--NumCachedScopes];
355f4a2713aSLionel Sambuc     N->Init(getCurScope(), ScopeFlags);
356f4a2713aSLionel Sambuc     Actions.CurScope = N;
357f4a2713aSLionel Sambuc   } else {
358f4a2713aSLionel Sambuc     Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
359f4a2713aSLionel Sambuc   }
360f4a2713aSLionel Sambuc }
361f4a2713aSLionel Sambuc 
362f4a2713aSLionel Sambuc /// ExitScope - Pop a scope off the scope stack.
ExitScope()363f4a2713aSLionel Sambuc void Parser::ExitScope() {
364f4a2713aSLionel Sambuc   assert(getCurScope() && "Scope imbalance!");
365f4a2713aSLionel Sambuc 
366f4a2713aSLionel Sambuc   // Inform the actions module that this scope is going away if there are any
367f4a2713aSLionel Sambuc   // decls in it.
368f4a2713aSLionel Sambuc   Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
369f4a2713aSLionel Sambuc 
370f4a2713aSLionel Sambuc   Scope *OldScope = getCurScope();
371f4a2713aSLionel Sambuc   Actions.CurScope = OldScope->getParent();
372f4a2713aSLionel Sambuc 
373f4a2713aSLionel Sambuc   if (NumCachedScopes == ScopeCacheSize)
374f4a2713aSLionel Sambuc     delete OldScope;
375f4a2713aSLionel Sambuc   else
376f4a2713aSLionel Sambuc     ScopeCache[NumCachedScopes++] = OldScope;
377f4a2713aSLionel Sambuc }
378f4a2713aSLionel Sambuc 
379f4a2713aSLionel Sambuc /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
380f4a2713aSLionel Sambuc /// this object does nothing.
ParseScopeFlags(Parser * Self,unsigned ScopeFlags,bool ManageFlags)381f4a2713aSLionel Sambuc Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
382f4a2713aSLionel Sambuc                                  bool ManageFlags)
383*0a6a1f1dSLionel Sambuc   : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
384f4a2713aSLionel Sambuc   if (CurScope) {
385f4a2713aSLionel Sambuc     OldFlags = CurScope->getFlags();
386f4a2713aSLionel Sambuc     CurScope->setFlags(ScopeFlags);
387f4a2713aSLionel Sambuc   }
388f4a2713aSLionel Sambuc }
389f4a2713aSLionel Sambuc 
390f4a2713aSLionel Sambuc /// Restore the flags for the current scope to what they were before this
391f4a2713aSLionel Sambuc /// object overrode them.
~ParseScopeFlags()392f4a2713aSLionel Sambuc Parser::ParseScopeFlags::~ParseScopeFlags() {
393f4a2713aSLionel Sambuc   if (CurScope)
394f4a2713aSLionel Sambuc     CurScope->setFlags(OldFlags);
395f4a2713aSLionel Sambuc }
396f4a2713aSLionel Sambuc 
397f4a2713aSLionel Sambuc 
398f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
399f4a2713aSLionel Sambuc // C99 6.9: External Definitions.
400f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
401f4a2713aSLionel Sambuc 
~Parser()402f4a2713aSLionel Sambuc Parser::~Parser() {
403f4a2713aSLionel Sambuc   // If we still have scopes active, delete the scope tree.
404f4a2713aSLionel Sambuc   delete getCurScope();
405*0a6a1f1dSLionel Sambuc   Actions.CurScope = nullptr;
406f4a2713aSLionel Sambuc 
407f4a2713aSLionel Sambuc   // Free the scope cache.
408f4a2713aSLionel Sambuc   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
409f4a2713aSLionel Sambuc     delete ScopeCache[i];
410f4a2713aSLionel Sambuc 
411*0a6a1f1dSLionel Sambuc   resetPragmaHandlers();
412f4a2713aSLionel Sambuc 
413f4a2713aSLionel Sambuc   PP.removeCommentHandler(CommentSemaHandler.get());
414f4a2713aSLionel Sambuc 
415f4a2713aSLionel Sambuc   PP.clearCodeCompletionHandler();
416f4a2713aSLionel Sambuc 
417f4a2713aSLionel Sambuc   assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
418f4a2713aSLionel Sambuc }
419f4a2713aSLionel Sambuc 
420f4a2713aSLionel Sambuc /// Initialize - Warm up the parser.
421f4a2713aSLionel Sambuc ///
Initialize()422f4a2713aSLionel Sambuc void Parser::Initialize() {
423f4a2713aSLionel Sambuc   // Create the translation unit scope.  Install it as the current scope.
424*0a6a1f1dSLionel Sambuc   assert(getCurScope() == nullptr && "A scope is already active?");
425f4a2713aSLionel Sambuc   EnterScope(Scope::DeclScope);
426f4a2713aSLionel Sambuc   Actions.ActOnTranslationUnitScope(getCurScope());
427f4a2713aSLionel Sambuc 
428f4a2713aSLionel Sambuc   // Initialization for Objective-C context sensitive keywords recognition.
429f4a2713aSLionel Sambuc   // Referenced in Parser::ParseObjCTypeQualifierList.
430f4a2713aSLionel Sambuc   if (getLangOpts().ObjC1) {
431f4a2713aSLionel Sambuc     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
432f4a2713aSLionel Sambuc     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
433f4a2713aSLionel Sambuc     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
434f4a2713aSLionel Sambuc     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
435f4a2713aSLionel Sambuc     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
436f4a2713aSLionel Sambuc     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
437f4a2713aSLionel Sambuc   }
438f4a2713aSLionel Sambuc 
439*0a6a1f1dSLionel Sambuc   Ident_instancetype = nullptr;
440*0a6a1f1dSLionel Sambuc   Ident_final = nullptr;
441*0a6a1f1dSLionel Sambuc   Ident_sealed = nullptr;
442*0a6a1f1dSLionel Sambuc   Ident_override = nullptr;
443f4a2713aSLionel Sambuc 
444f4a2713aSLionel Sambuc   Ident_super = &PP.getIdentifierTable().get("super");
445f4a2713aSLionel Sambuc 
446f4a2713aSLionel Sambuc   if (getLangOpts().AltiVec) {
447f4a2713aSLionel Sambuc     Ident_vector = &PP.getIdentifierTable().get("vector");
448f4a2713aSLionel Sambuc     Ident_pixel = &PP.getIdentifierTable().get("pixel");
449f4a2713aSLionel Sambuc     Ident_bool = &PP.getIdentifierTable().get("bool");
450f4a2713aSLionel Sambuc   }
451f4a2713aSLionel Sambuc 
452*0a6a1f1dSLionel Sambuc   Ident_introduced = nullptr;
453*0a6a1f1dSLionel Sambuc   Ident_deprecated = nullptr;
454*0a6a1f1dSLionel Sambuc   Ident_obsoleted = nullptr;
455*0a6a1f1dSLionel Sambuc   Ident_unavailable = nullptr;
456f4a2713aSLionel Sambuc 
457*0a6a1f1dSLionel Sambuc   Ident__except = nullptr;
458f4a2713aSLionel Sambuc 
459*0a6a1f1dSLionel Sambuc   Ident__exception_code = Ident__exception_info = nullptr;
460*0a6a1f1dSLionel Sambuc   Ident__abnormal_termination = Ident___exception_code = nullptr;
461*0a6a1f1dSLionel Sambuc   Ident___exception_info = Ident___abnormal_termination = nullptr;
462*0a6a1f1dSLionel Sambuc   Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
463*0a6a1f1dSLionel Sambuc   Ident_AbnormalTermination = nullptr;
464f4a2713aSLionel Sambuc 
465f4a2713aSLionel Sambuc   if(getLangOpts().Borland) {
466f4a2713aSLionel Sambuc     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
467f4a2713aSLionel Sambuc     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
468f4a2713aSLionel Sambuc     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
469f4a2713aSLionel Sambuc     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
470f4a2713aSLionel Sambuc     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
471f4a2713aSLionel Sambuc     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
472f4a2713aSLionel Sambuc     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
473f4a2713aSLionel Sambuc     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
474f4a2713aSLionel Sambuc     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
475f4a2713aSLionel Sambuc 
476f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
477f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
478f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
479f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
480f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
481f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
482f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
483f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
484f4a2713aSLionel Sambuc     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
485f4a2713aSLionel Sambuc   }
486f4a2713aSLionel Sambuc 
487f4a2713aSLionel Sambuc   Actions.Initialize();
488f4a2713aSLionel Sambuc 
489f4a2713aSLionel Sambuc   // Prime the lexer look-ahead.
490f4a2713aSLionel Sambuc   ConsumeToken();
491f4a2713aSLionel Sambuc }
492f4a2713aSLionel Sambuc 
493f4a2713aSLionel Sambuc namespace {
494f4a2713aSLionel Sambuc   /// \brief RAIIObject to destroy the contents of a SmallVector of
495f4a2713aSLionel Sambuc   /// TemplateIdAnnotation pointers and clear the vector.
496f4a2713aSLionel Sambuc   class DestroyTemplateIdAnnotationsRAIIObj {
497f4a2713aSLionel Sambuc     SmallVectorImpl<TemplateIdAnnotation *> &Container;
498f4a2713aSLionel Sambuc   public:
DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation * > & Container)499f4a2713aSLionel Sambuc     DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
500f4a2713aSLionel Sambuc                                        &Container)
501f4a2713aSLionel Sambuc       : Container(Container) {}
502f4a2713aSLionel Sambuc 
~DestroyTemplateIdAnnotationsRAIIObj()503f4a2713aSLionel Sambuc     ~DestroyTemplateIdAnnotationsRAIIObj() {
504f4a2713aSLionel Sambuc       for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
505f4a2713aSLionel Sambuc            Container.begin(), E = Container.end();
506f4a2713aSLionel Sambuc            I != E; ++I)
507f4a2713aSLionel Sambuc         (*I)->Destroy();
508f4a2713aSLionel Sambuc       Container.clear();
509f4a2713aSLionel Sambuc     }
510f4a2713aSLionel Sambuc   };
511f4a2713aSLionel Sambuc }
512f4a2713aSLionel Sambuc 
LateTemplateParserCleanupCallback(void * P)513*0a6a1f1dSLionel Sambuc void Parser::LateTemplateParserCleanupCallback(void *P) {
514*0a6a1f1dSLionel Sambuc   // While this RAII helper doesn't bracket any actual work, the destructor will
515*0a6a1f1dSLionel Sambuc   // clean up annotations that were created during ActOnEndOfTranslationUnit
516*0a6a1f1dSLionel Sambuc   // when incremental processing is enabled.
517*0a6a1f1dSLionel Sambuc   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
518*0a6a1f1dSLionel Sambuc }
519*0a6a1f1dSLionel Sambuc 
520f4a2713aSLionel Sambuc /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
521f4a2713aSLionel Sambuc /// action tells us to.  This returns true if the EOF was encountered.
ParseTopLevelDecl(DeclGroupPtrTy & Result)522f4a2713aSLionel Sambuc bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
523f4a2713aSLionel Sambuc   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
524f4a2713aSLionel Sambuc 
525f4a2713aSLionel Sambuc   // Skip over the EOF token, flagging end of previous input for incremental
526f4a2713aSLionel Sambuc   // processing
527f4a2713aSLionel Sambuc   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
528f4a2713aSLionel Sambuc     ConsumeToken();
529f4a2713aSLionel Sambuc 
530f4a2713aSLionel Sambuc   Result = DeclGroupPtrTy();
531f4a2713aSLionel Sambuc   switch (Tok.getKind()) {
532f4a2713aSLionel Sambuc   case tok::annot_pragma_unused:
533f4a2713aSLionel Sambuc     HandlePragmaUnused();
534f4a2713aSLionel Sambuc     return false;
535f4a2713aSLionel Sambuc 
536f4a2713aSLionel Sambuc   case tok::annot_module_include:
537f4a2713aSLionel Sambuc     Actions.ActOnModuleInclude(Tok.getLocation(),
538f4a2713aSLionel Sambuc                                reinterpret_cast<Module *>(
539f4a2713aSLionel Sambuc                                    Tok.getAnnotationValue()));
540f4a2713aSLionel Sambuc     ConsumeToken();
541f4a2713aSLionel Sambuc     return false;
542f4a2713aSLionel Sambuc 
543*0a6a1f1dSLionel Sambuc   case tok::annot_module_begin:
544*0a6a1f1dSLionel Sambuc   case tok::annot_module_end:
545*0a6a1f1dSLionel Sambuc     // FIXME: Update visibility based on the submodule we're in.
546*0a6a1f1dSLionel Sambuc     ConsumeToken();
547*0a6a1f1dSLionel Sambuc     return false;
548*0a6a1f1dSLionel Sambuc 
549f4a2713aSLionel Sambuc   case tok::eof:
550f4a2713aSLionel Sambuc     // Late template parsing can begin.
551f4a2713aSLionel Sambuc     if (getLangOpts().DelayedTemplateParsing)
552*0a6a1f1dSLionel Sambuc       Actions.SetLateTemplateParser(LateTemplateParserCallback,
553*0a6a1f1dSLionel Sambuc                                     PP.isIncrementalProcessingEnabled() ?
554*0a6a1f1dSLionel Sambuc                                     LateTemplateParserCleanupCallback : nullptr,
555*0a6a1f1dSLionel Sambuc                                     this);
556f4a2713aSLionel Sambuc     if (!PP.isIncrementalProcessingEnabled())
557f4a2713aSLionel Sambuc       Actions.ActOnEndOfTranslationUnit();
558f4a2713aSLionel Sambuc     //else don't tell Sema that we ended parsing: more input might come.
559f4a2713aSLionel Sambuc     return true;
560f4a2713aSLionel Sambuc 
561f4a2713aSLionel Sambuc   default:
562f4a2713aSLionel Sambuc     break;
563f4a2713aSLionel Sambuc   }
564f4a2713aSLionel Sambuc 
565f4a2713aSLionel Sambuc   ParsedAttributesWithRange attrs(AttrFactory);
566f4a2713aSLionel Sambuc   MaybeParseCXX11Attributes(attrs);
567f4a2713aSLionel Sambuc   MaybeParseMicrosoftAttributes(attrs);
568f4a2713aSLionel Sambuc 
569f4a2713aSLionel Sambuc   Result = ParseExternalDeclaration(attrs);
570f4a2713aSLionel Sambuc   return false;
571f4a2713aSLionel Sambuc }
572f4a2713aSLionel Sambuc 
573f4a2713aSLionel Sambuc /// ParseExternalDeclaration:
574f4a2713aSLionel Sambuc ///
575f4a2713aSLionel Sambuc ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
576f4a2713aSLionel Sambuc ///         function-definition
577f4a2713aSLionel Sambuc ///         declaration
578f4a2713aSLionel Sambuc /// [GNU]   asm-definition
579f4a2713aSLionel Sambuc /// [GNU]   __extension__ external-declaration
580f4a2713aSLionel Sambuc /// [OBJC]  objc-class-definition
581f4a2713aSLionel Sambuc /// [OBJC]  objc-class-declaration
582f4a2713aSLionel Sambuc /// [OBJC]  objc-alias-declaration
583f4a2713aSLionel Sambuc /// [OBJC]  objc-protocol-definition
584f4a2713aSLionel Sambuc /// [OBJC]  objc-method-definition
585f4a2713aSLionel Sambuc /// [OBJC]  @end
586f4a2713aSLionel Sambuc /// [C++]   linkage-specification
587f4a2713aSLionel Sambuc /// [GNU] asm-definition:
588f4a2713aSLionel Sambuc ///         simple-asm-expr ';'
589f4a2713aSLionel Sambuc /// [C++11] empty-declaration
590f4a2713aSLionel Sambuc /// [C++11] attribute-declaration
591f4a2713aSLionel Sambuc ///
592f4a2713aSLionel Sambuc /// [C++11] empty-declaration:
593f4a2713aSLionel Sambuc ///           ';'
594f4a2713aSLionel Sambuc ///
595f4a2713aSLionel Sambuc /// [C++0x/GNU] 'extern' 'template' declaration
596f4a2713aSLionel Sambuc Parser::DeclGroupPtrTy
ParseExternalDeclaration(ParsedAttributesWithRange & attrs,ParsingDeclSpec * DS)597f4a2713aSLionel Sambuc Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
598f4a2713aSLionel Sambuc                                  ParsingDeclSpec *DS) {
599f4a2713aSLionel Sambuc   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
600f4a2713aSLionel Sambuc   ParenBraceBracketBalancer BalancerRAIIObj(*this);
601f4a2713aSLionel Sambuc 
602f4a2713aSLionel Sambuc   if (PP.isCodeCompletionReached()) {
603f4a2713aSLionel Sambuc     cutOffParsing();
604f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
605f4a2713aSLionel Sambuc   }
606f4a2713aSLionel Sambuc 
607*0a6a1f1dSLionel Sambuc   Decl *SingleDecl = nullptr;
608f4a2713aSLionel Sambuc   switch (Tok.getKind()) {
609f4a2713aSLionel Sambuc   case tok::annot_pragma_vis:
610f4a2713aSLionel Sambuc     HandlePragmaVisibility();
611f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
612f4a2713aSLionel Sambuc   case tok::annot_pragma_pack:
613f4a2713aSLionel Sambuc     HandlePragmaPack();
614f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
615f4a2713aSLionel Sambuc   case tok::annot_pragma_msstruct:
616f4a2713aSLionel Sambuc     HandlePragmaMSStruct();
617f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
618f4a2713aSLionel Sambuc   case tok::annot_pragma_align:
619f4a2713aSLionel Sambuc     HandlePragmaAlign();
620f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
621f4a2713aSLionel Sambuc   case tok::annot_pragma_weak:
622f4a2713aSLionel Sambuc     HandlePragmaWeak();
623f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
624f4a2713aSLionel Sambuc   case tok::annot_pragma_weakalias:
625f4a2713aSLionel Sambuc     HandlePragmaWeakAlias();
626f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
627f4a2713aSLionel Sambuc   case tok::annot_pragma_redefine_extname:
628f4a2713aSLionel Sambuc     HandlePragmaRedefineExtname();
629f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
630f4a2713aSLionel Sambuc   case tok::annot_pragma_fp_contract:
631f4a2713aSLionel Sambuc     HandlePragmaFPContract();
632f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
633f4a2713aSLionel Sambuc   case tok::annot_pragma_opencl_extension:
634f4a2713aSLionel Sambuc     HandlePragmaOpenCLExtension();
635f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
636f4a2713aSLionel Sambuc   case tok::annot_pragma_openmp:
637*0a6a1f1dSLionel Sambuc     return ParseOpenMPDeclarativeDirective();
638*0a6a1f1dSLionel Sambuc   case tok::annot_pragma_ms_pointers_to_members:
639*0a6a1f1dSLionel Sambuc     HandlePragmaMSPointersToMembers();
640*0a6a1f1dSLionel Sambuc     return DeclGroupPtrTy();
641*0a6a1f1dSLionel Sambuc   case tok::annot_pragma_ms_vtordisp:
642*0a6a1f1dSLionel Sambuc     HandlePragmaMSVtorDisp();
643*0a6a1f1dSLionel Sambuc     return DeclGroupPtrTy();
644*0a6a1f1dSLionel Sambuc   case tok::annot_pragma_ms_pragma:
645*0a6a1f1dSLionel Sambuc     HandlePragmaMSPragma();
646f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
647f4a2713aSLionel Sambuc   case tok::semi:
648f4a2713aSLionel Sambuc     // Either a C++11 empty-declaration or attribute-declaration.
649f4a2713aSLionel Sambuc     SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
650f4a2713aSLionel Sambuc                                                attrs.getList(),
651f4a2713aSLionel Sambuc                                                Tok.getLocation());
652f4a2713aSLionel Sambuc     ConsumeExtraSemi(OutsideFunction);
653f4a2713aSLionel Sambuc     break;
654f4a2713aSLionel Sambuc   case tok::r_brace:
655f4a2713aSLionel Sambuc     Diag(Tok, diag::err_extraneous_closing_brace);
656f4a2713aSLionel Sambuc     ConsumeBrace();
657f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
658f4a2713aSLionel Sambuc   case tok::eof:
659f4a2713aSLionel Sambuc     Diag(Tok, diag::err_expected_external_declaration);
660f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
661f4a2713aSLionel Sambuc   case tok::kw___extension__: {
662f4a2713aSLionel Sambuc     // __extension__ silences extension warnings in the subexpression.
663f4a2713aSLionel Sambuc     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
664f4a2713aSLionel Sambuc     ConsumeToken();
665f4a2713aSLionel Sambuc     return ParseExternalDeclaration(attrs);
666f4a2713aSLionel Sambuc   }
667f4a2713aSLionel Sambuc   case tok::kw_asm: {
668f4a2713aSLionel Sambuc     ProhibitAttributes(attrs);
669f4a2713aSLionel Sambuc 
670f4a2713aSLionel Sambuc     SourceLocation StartLoc = Tok.getLocation();
671f4a2713aSLionel Sambuc     SourceLocation EndLoc;
672f4a2713aSLionel Sambuc     ExprResult Result(ParseSimpleAsm(&EndLoc));
673f4a2713aSLionel Sambuc 
674*0a6a1f1dSLionel Sambuc     ExpectAndConsume(tok::semi, diag::err_expected_after,
675f4a2713aSLionel Sambuc                      "top-level asm block");
676f4a2713aSLionel Sambuc 
677f4a2713aSLionel Sambuc     if (Result.isInvalid())
678f4a2713aSLionel Sambuc       return DeclGroupPtrTy();
679f4a2713aSLionel Sambuc     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
680f4a2713aSLionel Sambuc     break;
681f4a2713aSLionel Sambuc   }
682f4a2713aSLionel Sambuc   case tok::at:
683f4a2713aSLionel Sambuc     return ParseObjCAtDirectives();
684f4a2713aSLionel Sambuc   case tok::minus:
685f4a2713aSLionel Sambuc   case tok::plus:
686f4a2713aSLionel Sambuc     if (!getLangOpts().ObjC1) {
687f4a2713aSLionel Sambuc       Diag(Tok, diag::err_expected_external_declaration);
688f4a2713aSLionel Sambuc       ConsumeToken();
689f4a2713aSLionel Sambuc       return DeclGroupPtrTy();
690f4a2713aSLionel Sambuc     }
691f4a2713aSLionel Sambuc     SingleDecl = ParseObjCMethodDefinition();
692f4a2713aSLionel Sambuc     break;
693f4a2713aSLionel Sambuc   case tok::code_completion:
694f4a2713aSLionel Sambuc       Actions.CodeCompleteOrdinaryName(getCurScope(),
695f4a2713aSLionel Sambuc                              CurParsedObjCImpl? Sema::PCC_ObjCImplementation
696f4a2713aSLionel Sambuc                                               : Sema::PCC_Namespace);
697f4a2713aSLionel Sambuc     cutOffParsing();
698f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
699f4a2713aSLionel Sambuc   case tok::kw_using:
700f4a2713aSLionel Sambuc   case tok::kw_namespace:
701f4a2713aSLionel Sambuc   case tok::kw_typedef:
702f4a2713aSLionel Sambuc   case tok::kw_template:
703f4a2713aSLionel Sambuc   case tok::kw_export:    // As in 'export template'
704f4a2713aSLionel Sambuc   case tok::kw_static_assert:
705f4a2713aSLionel Sambuc   case tok::kw__Static_assert:
706f4a2713aSLionel Sambuc     // A function definition cannot start with any of these keywords.
707f4a2713aSLionel Sambuc     {
708f4a2713aSLionel Sambuc       SourceLocation DeclEnd;
709*0a6a1f1dSLionel Sambuc       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
710f4a2713aSLionel Sambuc     }
711f4a2713aSLionel Sambuc 
712f4a2713aSLionel Sambuc   case tok::kw_static:
713f4a2713aSLionel Sambuc     // Parse (then ignore) 'static' prior to a template instantiation. This is
714f4a2713aSLionel Sambuc     // a GCC extension that we intentionally do not support.
715f4a2713aSLionel Sambuc     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
716f4a2713aSLionel Sambuc       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
717f4a2713aSLionel Sambuc         << 0;
718f4a2713aSLionel Sambuc       SourceLocation DeclEnd;
719*0a6a1f1dSLionel Sambuc       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
720f4a2713aSLionel Sambuc     }
721f4a2713aSLionel Sambuc     goto dont_know;
722f4a2713aSLionel Sambuc 
723f4a2713aSLionel Sambuc   case tok::kw_inline:
724f4a2713aSLionel Sambuc     if (getLangOpts().CPlusPlus) {
725f4a2713aSLionel Sambuc       tok::TokenKind NextKind = NextToken().getKind();
726f4a2713aSLionel Sambuc 
727f4a2713aSLionel Sambuc       // Inline namespaces. Allowed as an extension even in C++03.
728f4a2713aSLionel Sambuc       if (NextKind == tok::kw_namespace) {
729f4a2713aSLionel Sambuc         SourceLocation DeclEnd;
730*0a6a1f1dSLionel Sambuc         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
731f4a2713aSLionel Sambuc       }
732f4a2713aSLionel Sambuc 
733f4a2713aSLionel Sambuc       // Parse (then ignore) 'inline' prior to a template instantiation. This is
734f4a2713aSLionel Sambuc       // a GCC extension that we intentionally do not support.
735f4a2713aSLionel Sambuc       if (NextKind == tok::kw_template) {
736f4a2713aSLionel Sambuc         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
737f4a2713aSLionel Sambuc           << 1;
738f4a2713aSLionel Sambuc         SourceLocation DeclEnd;
739*0a6a1f1dSLionel Sambuc         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
740f4a2713aSLionel Sambuc       }
741f4a2713aSLionel Sambuc     }
742f4a2713aSLionel Sambuc     goto dont_know;
743f4a2713aSLionel Sambuc 
744f4a2713aSLionel Sambuc   case tok::kw_extern:
745f4a2713aSLionel Sambuc     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
746f4a2713aSLionel Sambuc       // Extern templates
747f4a2713aSLionel Sambuc       SourceLocation ExternLoc = ConsumeToken();
748f4a2713aSLionel Sambuc       SourceLocation TemplateLoc = ConsumeToken();
749f4a2713aSLionel Sambuc       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
750f4a2713aSLionel Sambuc              diag::warn_cxx98_compat_extern_template :
751f4a2713aSLionel Sambuc              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
752f4a2713aSLionel Sambuc       SourceLocation DeclEnd;
753f4a2713aSLionel Sambuc       return Actions.ConvertDeclToDeclGroup(
754f4a2713aSLionel Sambuc                   ParseExplicitInstantiation(Declarator::FileContext,
755f4a2713aSLionel Sambuc                                              ExternLoc, TemplateLoc, DeclEnd));
756f4a2713aSLionel Sambuc     }
757f4a2713aSLionel Sambuc     goto dont_know;
758f4a2713aSLionel Sambuc 
759f4a2713aSLionel Sambuc   case tok::kw___if_exists:
760f4a2713aSLionel Sambuc   case tok::kw___if_not_exists:
761f4a2713aSLionel Sambuc     ParseMicrosoftIfExistsExternalDeclaration();
762f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
763f4a2713aSLionel Sambuc 
764f4a2713aSLionel Sambuc   default:
765f4a2713aSLionel Sambuc   dont_know:
766f4a2713aSLionel Sambuc     // We can't tell whether this is a function-definition or declaration yet.
767f4a2713aSLionel Sambuc     return ParseDeclarationOrFunctionDefinition(attrs, DS);
768f4a2713aSLionel Sambuc   }
769f4a2713aSLionel Sambuc 
770f4a2713aSLionel Sambuc   // This routine returns a DeclGroup, if the thing we parsed only contains a
771f4a2713aSLionel Sambuc   // single decl, convert it now.
772f4a2713aSLionel Sambuc   return Actions.ConvertDeclToDeclGroup(SingleDecl);
773f4a2713aSLionel Sambuc }
774f4a2713aSLionel Sambuc 
775f4a2713aSLionel Sambuc /// \brief Determine whether the current token, if it occurs after a
776f4a2713aSLionel Sambuc /// declarator, continues a declaration or declaration list.
isDeclarationAfterDeclarator()777f4a2713aSLionel Sambuc bool Parser::isDeclarationAfterDeclarator() {
778f4a2713aSLionel Sambuc   // Check for '= delete' or '= default'
779f4a2713aSLionel Sambuc   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
780f4a2713aSLionel Sambuc     const Token &KW = NextToken();
781f4a2713aSLionel Sambuc     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
782f4a2713aSLionel Sambuc       return false;
783f4a2713aSLionel Sambuc   }
784f4a2713aSLionel Sambuc 
785f4a2713aSLionel Sambuc   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
786f4a2713aSLionel Sambuc     Tok.is(tok::comma) ||           // int X(),  -> not a function def
787f4a2713aSLionel Sambuc     Tok.is(tok::semi)  ||           // int X();  -> not a function def
788f4a2713aSLionel Sambuc     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
789f4a2713aSLionel Sambuc     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
790f4a2713aSLionel Sambuc     (getLangOpts().CPlusPlus &&
791f4a2713aSLionel Sambuc      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
792f4a2713aSLionel Sambuc }
793f4a2713aSLionel Sambuc 
794f4a2713aSLionel Sambuc /// \brief Determine whether the current token, if it occurs after a
795f4a2713aSLionel Sambuc /// declarator, indicates the start of a function definition.
isStartOfFunctionDefinition(const ParsingDeclarator & Declarator)796f4a2713aSLionel Sambuc bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
797f4a2713aSLionel Sambuc   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
798f4a2713aSLionel Sambuc   if (Tok.is(tok::l_brace))   // int X() {}
799f4a2713aSLionel Sambuc     return true;
800f4a2713aSLionel Sambuc 
801f4a2713aSLionel Sambuc   // Handle K&R C argument lists: int X(f) int f; {}
802f4a2713aSLionel Sambuc   if (!getLangOpts().CPlusPlus &&
803f4a2713aSLionel Sambuc       Declarator.getFunctionTypeInfo().isKNRPrototype())
804f4a2713aSLionel Sambuc     return isDeclarationSpecifier();
805f4a2713aSLionel Sambuc 
806f4a2713aSLionel Sambuc   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
807f4a2713aSLionel Sambuc     const Token &KW = NextToken();
808f4a2713aSLionel Sambuc     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
809f4a2713aSLionel Sambuc   }
810f4a2713aSLionel Sambuc 
811f4a2713aSLionel Sambuc   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
812f4a2713aSLionel Sambuc          Tok.is(tok::kw_try);          // X() try { ... }
813f4a2713aSLionel Sambuc }
814f4a2713aSLionel Sambuc 
815f4a2713aSLionel Sambuc /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
816f4a2713aSLionel Sambuc /// a declaration.  We can't tell which we have until we read up to the
817f4a2713aSLionel Sambuc /// compound-statement in function-definition. TemplateParams, if
818f4a2713aSLionel Sambuc /// non-NULL, provides the template parameters when we're parsing a
819f4a2713aSLionel Sambuc /// C++ template-declaration.
820f4a2713aSLionel Sambuc ///
821f4a2713aSLionel Sambuc ///       function-definition: [C99 6.9.1]
822f4a2713aSLionel Sambuc ///         decl-specs      declarator declaration-list[opt] compound-statement
823f4a2713aSLionel Sambuc /// [C90] function-definition: [C99 6.7.1] - implicit int result
824f4a2713aSLionel Sambuc /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
825f4a2713aSLionel Sambuc ///
826f4a2713aSLionel Sambuc ///       declaration: [C99 6.7]
827f4a2713aSLionel Sambuc ///         declaration-specifiers init-declarator-list[opt] ';'
828f4a2713aSLionel Sambuc /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
829f4a2713aSLionel Sambuc /// [OMP]   threadprivate-directive                              [TODO]
830f4a2713aSLionel Sambuc ///
831f4a2713aSLionel Sambuc Parser::DeclGroupPtrTy
ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange & attrs,ParsingDeclSpec & DS,AccessSpecifier AS)832f4a2713aSLionel Sambuc Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
833f4a2713aSLionel Sambuc                                        ParsingDeclSpec &DS,
834f4a2713aSLionel Sambuc                                        AccessSpecifier AS) {
835f4a2713aSLionel Sambuc   // Parse the common declaration-specifiers piece.
836f4a2713aSLionel Sambuc   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
837f4a2713aSLionel Sambuc 
838f4a2713aSLionel Sambuc   // If we had a free-standing type definition with a missing semicolon, we
839f4a2713aSLionel Sambuc   // may get this far before the problem becomes obvious.
840f4a2713aSLionel Sambuc   if (DS.hasTagDefinition() &&
841f4a2713aSLionel Sambuc       DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
842f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
843f4a2713aSLionel Sambuc 
844f4a2713aSLionel Sambuc   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
845f4a2713aSLionel Sambuc   // declaration-specifiers init-declarator-list[opt] ';'
846f4a2713aSLionel Sambuc   if (Tok.is(tok::semi)) {
847f4a2713aSLionel Sambuc     ProhibitAttributes(attrs);
848f4a2713aSLionel Sambuc     ConsumeToken();
849f4a2713aSLionel Sambuc     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
850f4a2713aSLionel Sambuc     DS.complete(TheDecl);
851f4a2713aSLionel Sambuc     return Actions.ConvertDeclToDeclGroup(TheDecl);
852f4a2713aSLionel Sambuc   }
853f4a2713aSLionel Sambuc 
854f4a2713aSLionel Sambuc   DS.takeAttributesFrom(attrs);
855f4a2713aSLionel Sambuc 
856f4a2713aSLionel Sambuc   // ObjC2 allows prefix attributes on class interfaces and protocols.
857f4a2713aSLionel Sambuc   // FIXME: This still needs better diagnostics. We should only accept
858f4a2713aSLionel Sambuc   // attributes here, no types, etc.
859f4a2713aSLionel Sambuc   if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
860f4a2713aSLionel Sambuc     SourceLocation AtLoc = ConsumeToken(); // the "@"
861f4a2713aSLionel Sambuc     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
862f4a2713aSLionel Sambuc         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
863f4a2713aSLionel Sambuc       Diag(Tok, diag::err_objc_unexpected_attr);
864f4a2713aSLionel Sambuc       SkipUntil(tok::semi); // FIXME: better skip?
865f4a2713aSLionel Sambuc       return DeclGroupPtrTy();
866f4a2713aSLionel Sambuc     }
867f4a2713aSLionel Sambuc 
868f4a2713aSLionel Sambuc     DS.abort();
869f4a2713aSLionel Sambuc 
870*0a6a1f1dSLionel Sambuc     const char *PrevSpec = nullptr;
871f4a2713aSLionel Sambuc     unsigned DiagID;
872*0a6a1f1dSLionel Sambuc     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
873*0a6a1f1dSLionel Sambuc                            Actions.getASTContext().getPrintingPolicy()))
874f4a2713aSLionel Sambuc       Diag(AtLoc, DiagID) << PrevSpec;
875f4a2713aSLionel Sambuc 
876f4a2713aSLionel Sambuc     if (Tok.isObjCAtKeyword(tok::objc_protocol))
877f4a2713aSLionel Sambuc       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
878f4a2713aSLionel Sambuc 
879f4a2713aSLionel Sambuc     return Actions.ConvertDeclToDeclGroup(
880f4a2713aSLionel Sambuc             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
881f4a2713aSLionel Sambuc   }
882f4a2713aSLionel Sambuc 
883f4a2713aSLionel Sambuc   // If the declspec consisted only of 'extern' and we have a string
884f4a2713aSLionel Sambuc   // literal following it, this must be a C++ linkage specifier like
885f4a2713aSLionel Sambuc   // 'extern "C"'.
886*0a6a1f1dSLionel Sambuc   if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
887f4a2713aSLionel Sambuc       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
888f4a2713aSLionel Sambuc       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
889f4a2713aSLionel Sambuc     Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
890f4a2713aSLionel Sambuc     return Actions.ConvertDeclToDeclGroup(TheDecl);
891f4a2713aSLionel Sambuc   }
892f4a2713aSLionel Sambuc 
893*0a6a1f1dSLionel Sambuc   return ParseDeclGroup(DS, Declarator::FileContext);
894f4a2713aSLionel Sambuc }
895f4a2713aSLionel Sambuc 
896f4a2713aSLionel Sambuc Parser::DeclGroupPtrTy
ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange & attrs,ParsingDeclSpec * DS,AccessSpecifier AS)897f4a2713aSLionel Sambuc Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
898f4a2713aSLionel Sambuc                                              ParsingDeclSpec *DS,
899f4a2713aSLionel Sambuc                                              AccessSpecifier AS) {
900f4a2713aSLionel Sambuc   if (DS) {
901f4a2713aSLionel Sambuc     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
902f4a2713aSLionel Sambuc   } else {
903f4a2713aSLionel Sambuc     ParsingDeclSpec PDS(*this);
904f4a2713aSLionel Sambuc     // Must temporarily exit the objective-c container scope for
905f4a2713aSLionel Sambuc     // parsing c constructs and re-enter objc container scope
906f4a2713aSLionel Sambuc     // afterwards.
907f4a2713aSLionel Sambuc     ObjCDeclContextSwitch ObjCDC(*this);
908f4a2713aSLionel Sambuc 
909f4a2713aSLionel Sambuc     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
910f4a2713aSLionel Sambuc   }
911f4a2713aSLionel Sambuc }
912f4a2713aSLionel Sambuc 
913f4a2713aSLionel Sambuc /// ParseFunctionDefinition - We parsed and verified that the specified
914f4a2713aSLionel Sambuc /// Declarator is well formed.  If this is a K&R-style function, read the
915f4a2713aSLionel Sambuc /// parameters declaration-list, then start the compound-statement.
916f4a2713aSLionel Sambuc ///
917f4a2713aSLionel Sambuc ///       function-definition: [C99 6.9.1]
918f4a2713aSLionel Sambuc ///         decl-specs      declarator declaration-list[opt] compound-statement
919f4a2713aSLionel Sambuc /// [C90] function-definition: [C99 6.7.1] - implicit int result
920f4a2713aSLionel Sambuc /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
921f4a2713aSLionel Sambuc /// [C++] function-definition: [C++ 8.4]
922f4a2713aSLionel Sambuc ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
923f4a2713aSLionel Sambuc ///         function-body
924f4a2713aSLionel Sambuc /// [C++] function-definition: [C++ 8.4]
925f4a2713aSLionel Sambuc ///         decl-specifier-seq[opt] declarator function-try-block
926f4a2713aSLionel Sambuc ///
ParseFunctionDefinition(ParsingDeclarator & D,const ParsedTemplateInfo & TemplateInfo,LateParsedAttrList * LateParsedAttrs)927f4a2713aSLionel Sambuc Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
928f4a2713aSLionel Sambuc                                       const ParsedTemplateInfo &TemplateInfo,
929f4a2713aSLionel Sambuc                                       LateParsedAttrList *LateParsedAttrs) {
930*0a6a1f1dSLionel Sambuc   // Poison SEH identifiers so they are flagged as illegal in function bodies.
931f4a2713aSLionel Sambuc   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
932f4a2713aSLionel Sambuc   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
933f4a2713aSLionel Sambuc 
934f4a2713aSLionel Sambuc   // If this is C90 and the declspecs were completely missing, fudge in an
935f4a2713aSLionel Sambuc   // implicit int.  We do this here because this is the only place where
936f4a2713aSLionel Sambuc   // declaration-specifiers are completely optional in the grammar.
937f4a2713aSLionel Sambuc   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
938f4a2713aSLionel Sambuc     const char *PrevSpec;
939f4a2713aSLionel Sambuc     unsigned DiagID;
940*0a6a1f1dSLionel Sambuc     const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
941f4a2713aSLionel Sambuc     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
942f4a2713aSLionel Sambuc                                            D.getIdentifierLoc(),
943*0a6a1f1dSLionel Sambuc                                            PrevSpec, DiagID,
944*0a6a1f1dSLionel Sambuc                                            Policy);
945f4a2713aSLionel Sambuc     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
946f4a2713aSLionel Sambuc   }
947f4a2713aSLionel Sambuc 
948f4a2713aSLionel Sambuc   // If this declaration was formed with a K&R-style identifier list for the
949f4a2713aSLionel Sambuc   // arguments, parse declarations for all of the args next.
950f4a2713aSLionel Sambuc   // int foo(a,b) int a; float b; {}
951f4a2713aSLionel Sambuc   if (FTI.isKNRPrototype())
952f4a2713aSLionel Sambuc     ParseKNRParamDeclarations(D);
953f4a2713aSLionel Sambuc 
954f4a2713aSLionel Sambuc   // We should have either an opening brace or, in a C++ constructor,
955f4a2713aSLionel Sambuc   // we may have a colon.
956f4a2713aSLionel Sambuc   if (Tok.isNot(tok::l_brace) &&
957f4a2713aSLionel Sambuc       (!getLangOpts().CPlusPlus ||
958f4a2713aSLionel Sambuc        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
959f4a2713aSLionel Sambuc         Tok.isNot(tok::equal)))) {
960f4a2713aSLionel Sambuc     Diag(Tok, diag::err_expected_fn_body);
961f4a2713aSLionel Sambuc 
962f4a2713aSLionel Sambuc     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
963f4a2713aSLionel Sambuc     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
964f4a2713aSLionel Sambuc 
965f4a2713aSLionel Sambuc     // If we didn't find the '{', bail out.
966f4a2713aSLionel Sambuc     if (Tok.isNot(tok::l_brace))
967*0a6a1f1dSLionel Sambuc       return nullptr;
968f4a2713aSLionel Sambuc   }
969f4a2713aSLionel Sambuc 
970f4a2713aSLionel Sambuc   // Check to make sure that any normal attributes are allowed to be on
971f4a2713aSLionel Sambuc   // a definition.  Late parsed attributes are checked at the end.
972f4a2713aSLionel Sambuc   if (Tok.isNot(tok::equal)) {
973f4a2713aSLionel Sambuc     AttributeList *DtorAttrs = D.getAttributes();
974f4a2713aSLionel Sambuc     while (DtorAttrs) {
975*0a6a1f1dSLionel Sambuc       if (DtorAttrs->isKnownToGCC() &&
976f4a2713aSLionel Sambuc           !DtorAttrs->isCXX11Attribute()) {
977f4a2713aSLionel Sambuc         Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
978*0a6a1f1dSLionel Sambuc           << DtorAttrs->getName();
979f4a2713aSLionel Sambuc       }
980f4a2713aSLionel Sambuc       DtorAttrs = DtorAttrs->getNext();
981f4a2713aSLionel Sambuc     }
982f4a2713aSLionel Sambuc   }
983f4a2713aSLionel Sambuc 
984f4a2713aSLionel Sambuc   // In delayed template parsing mode, for function template we consume the
985f4a2713aSLionel Sambuc   // tokens and store them for late parsing at the end of the translation unit.
986f4a2713aSLionel Sambuc   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
987f4a2713aSLionel Sambuc       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
988*0a6a1f1dSLionel Sambuc       Actions.canDelayFunctionBody(D)) {
989f4a2713aSLionel Sambuc     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
990f4a2713aSLionel Sambuc 
991f4a2713aSLionel Sambuc     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
992f4a2713aSLionel Sambuc     Scope *ParentScope = getCurScope()->getParent();
993f4a2713aSLionel Sambuc 
994f4a2713aSLionel Sambuc     D.setFunctionDefinitionKind(FDK_Definition);
995f4a2713aSLionel Sambuc     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
996f4a2713aSLionel Sambuc                                         TemplateParameterLists);
997f4a2713aSLionel Sambuc     D.complete(DP);
998f4a2713aSLionel Sambuc     D.getMutableDeclSpec().abort();
999f4a2713aSLionel Sambuc 
1000f4a2713aSLionel Sambuc     CachedTokens Toks;
1001f4a2713aSLionel Sambuc     LexTemplateFunctionForLateParsing(Toks);
1002f4a2713aSLionel Sambuc 
1003f4a2713aSLionel Sambuc     if (DP) {
1004*0a6a1f1dSLionel Sambuc       FunctionDecl *FnD = DP->getAsFunction();
1005f4a2713aSLionel Sambuc       Actions.CheckForFunctionRedefinition(FnD);
1006f4a2713aSLionel Sambuc       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1007f4a2713aSLionel Sambuc     }
1008f4a2713aSLionel Sambuc     return DP;
1009f4a2713aSLionel Sambuc   }
1010f4a2713aSLionel Sambuc   else if (CurParsedObjCImpl &&
1011f4a2713aSLionel Sambuc            !TemplateInfo.TemplateParams &&
1012f4a2713aSLionel Sambuc            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1013f4a2713aSLionel Sambuc             Tok.is(tok::colon)) &&
1014f4a2713aSLionel Sambuc       Actions.CurContext->isTranslationUnit()) {
1015f4a2713aSLionel Sambuc     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1016f4a2713aSLionel Sambuc     Scope *ParentScope = getCurScope()->getParent();
1017f4a2713aSLionel Sambuc 
1018f4a2713aSLionel Sambuc     D.setFunctionDefinitionKind(FDK_Definition);
1019f4a2713aSLionel Sambuc     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1020f4a2713aSLionel Sambuc                                               MultiTemplateParamsArg());
1021f4a2713aSLionel Sambuc     D.complete(FuncDecl);
1022f4a2713aSLionel Sambuc     D.getMutableDeclSpec().abort();
1023f4a2713aSLionel Sambuc     if (FuncDecl) {
1024f4a2713aSLionel Sambuc       // Consume the tokens and store them for later parsing.
1025f4a2713aSLionel Sambuc       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1026f4a2713aSLionel Sambuc       CurParsedObjCImpl->HasCFunction = true;
1027f4a2713aSLionel Sambuc       return FuncDecl;
1028f4a2713aSLionel Sambuc     }
1029*0a6a1f1dSLionel Sambuc     // FIXME: Should we really fall through here?
1030f4a2713aSLionel Sambuc   }
1031f4a2713aSLionel Sambuc 
1032f4a2713aSLionel Sambuc   // Enter a scope for the function body.
1033f4a2713aSLionel Sambuc   ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1034f4a2713aSLionel Sambuc 
1035f4a2713aSLionel Sambuc   // Tell the actions module that we have entered a function definition with the
1036f4a2713aSLionel Sambuc   // specified Declarator for the function.
1037f4a2713aSLionel Sambuc   Decl *Res = TemplateInfo.TemplateParams?
1038f4a2713aSLionel Sambuc       Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
1039f4a2713aSLionel Sambuc                                               *TemplateInfo.TemplateParams, D)
1040f4a2713aSLionel Sambuc     : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
1041f4a2713aSLionel Sambuc 
1042f4a2713aSLionel Sambuc   // Break out of the ParsingDeclarator context before we parse the body.
1043f4a2713aSLionel Sambuc   D.complete(Res);
1044f4a2713aSLionel Sambuc 
1045f4a2713aSLionel Sambuc   // Break out of the ParsingDeclSpec context, too.  This const_cast is
1046f4a2713aSLionel Sambuc   // safe because we're always the sole owner.
1047f4a2713aSLionel Sambuc   D.getMutableDeclSpec().abort();
1048f4a2713aSLionel Sambuc 
1049*0a6a1f1dSLionel Sambuc   if (TryConsumeToken(tok::equal)) {
1050f4a2713aSLionel Sambuc     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1051*0a6a1f1dSLionel Sambuc     Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1052f4a2713aSLionel Sambuc 
1053f4a2713aSLionel Sambuc     bool Delete = false;
1054f4a2713aSLionel Sambuc     SourceLocation KWLoc;
1055*0a6a1f1dSLionel Sambuc     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1056*0a6a1f1dSLionel Sambuc       Diag(KWLoc, getLangOpts().CPlusPlus11
1057*0a6a1f1dSLionel Sambuc                       ? diag::warn_cxx98_compat_deleted_function
1058*0a6a1f1dSLionel Sambuc                       : diag::ext_deleted_function);
1059f4a2713aSLionel Sambuc       Actions.SetDeclDeleted(Res, KWLoc);
1060f4a2713aSLionel Sambuc       Delete = true;
1061*0a6a1f1dSLionel Sambuc     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1062*0a6a1f1dSLionel Sambuc       Diag(KWLoc, getLangOpts().CPlusPlus11
1063*0a6a1f1dSLionel Sambuc                       ? diag::warn_cxx98_compat_defaulted_function
1064*0a6a1f1dSLionel Sambuc                       : diag::ext_defaulted_function);
1065f4a2713aSLionel Sambuc       Actions.SetDeclDefaulted(Res, KWLoc);
1066f4a2713aSLionel Sambuc     } else {
1067f4a2713aSLionel Sambuc       llvm_unreachable("function definition after = not 'delete' or 'default'");
1068f4a2713aSLionel Sambuc     }
1069f4a2713aSLionel Sambuc 
1070f4a2713aSLionel Sambuc     if (Tok.is(tok::comma)) {
1071f4a2713aSLionel Sambuc       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1072f4a2713aSLionel Sambuc         << Delete;
1073f4a2713aSLionel Sambuc       SkipUntil(tok::semi);
1074*0a6a1f1dSLionel Sambuc     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1075*0a6a1f1dSLionel Sambuc                                 Delete ? "delete" : "default")) {
1076*0a6a1f1dSLionel Sambuc       SkipUntil(tok::semi);
1077f4a2713aSLionel Sambuc     }
1078f4a2713aSLionel Sambuc 
1079f4a2713aSLionel Sambuc     return Res;
1080f4a2713aSLionel Sambuc   }
1081f4a2713aSLionel Sambuc 
1082f4a2713aSLionel Sambuc   if (Tok.is(tok::kw_try))
1083f4a2713aSLionel Sambuc     return ParseFunctionTryBlock(Res, BodyScope);
1084f4a2713aSLionel Sambuc 
1085f4a2713aSLionel Sambuc   // If we have a colon, then we're probably parsing a C++
1086f4a2713aSLionel Sambuc   // ctor-initializer.
1087f4a2713aSLionel Sambuc   if (Tok.is(tok::colon)) {
1088f4a2713aSLionel Sambuc     ParseConstructorInitializer(Res);
1089f4a2713aSLionel Sambuc 
1090f4a2713aSLionel Sambuc     // Recover from error.
1091f4a2713aSLionel Sambuc     if (!Tok.is(tok::l_brace)) {
1092f4a2713aSLionel Sambuc       BodyScope.Exit();
1093*0a6a1f1dSLionel Sambuc       Actions.ActOnFinishFunctionBody(Res, nullptr);
1094f4a2713aSLionel Sambuc       return Res;
1095f4a2713aSLionel Sambuc     }
1096f4a2713aSLionel Sambuc   } else
1097f4a2713aSLionel Sambuc     Actions.ActOnDefaultCtorInitializers(Res);
1098f4a2713aSLionel Sambuc 
1099f4a2713aSLionel Sambuc   // Late attributes are parsed in the same scope as the function body.
1100f4a2713aSLionel Sambuc   if (LateParsedAttrs)
1101f4a2713aSLionel Sambuc     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1102f4a2713aSLionel Sambuc 
1103f4a2713aSLionel Sambuc   return ParseFunctionStatementBody(Res, BodyScope);
1104f4a2713aSLionel Sambuc }
1105f4a2713aSLionel Sambuc 
1106f4a2713aSLionel Sambuc /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1107f4a2713aSLionel Sambuc /// types for a function with a K&R-style identifier list for arguments.
ParseKNRParamDeclarations(Declarator & D)1108f4a2713aSLionel Sambuc void Parser::ParseKNRParamDeclarations(Declarator &D) {
1109f4a2713aSLionel Sambuc   // We know that the top-level of this declarator is a function.
1110f4a2713aSLionel Sambuc   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1111f4a2713aSLionel Sambuc 
1112f4a2713aSLionel Sambuc   // Enter function-declaration scope, limiting any declarators to the
1113f4a2713aSLionel Sambuc   // function prototype scope, including parameter declarators.
1114f4a2713aSLionel Sambuc   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1115f4a2713aSLionel Sambuc                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1116f4a2713aSLionel Sambuc 
1117f4a2713aSLionel Sambuc   // Read all the argument declarations.
1118f4a2713aSLionel Sambuc   while (isDeclarationSpecifier()) {
1119f4a2713aSLionel Sambuc     SourceLocation DSStart = Tok.getLocation();
1120f4a2713aSLionel Sambuc 
1121f4a2713aSLionel Sambuc     // Parse the common declaration-specifiers piece.
1122f4a2713aSLionel Sambuc     DeclSpec DS(AttrFactory);
1123f4a2713aSLionel Sambuc     ParseDeclarationSpecifiers(DS);
1124f4a2713aSLionel Sambuc 
1125f4a2713aSLionel Sambuc     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1126f4a2713aSLionel Sambuc     // least one declarator'.
1127f4a2713aSLionel Sambuc     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1128f4a2713aSLionel Sambuc     // the declarations though.  It's trivial to ignore them, really hard to do
1129f4a2713aSLionel Sambuc     // anything else with them.
1130*0a6a1f1dSLionel Sambuc     if (TryConsumeToken(tok::semi)) {
1131f4a2713aSLionel Sambuc       Diag(DSStart, diag::err_declaration_does_not_declare_param);
1132f4a2713aSLionel Sambuc       continue;
1133f4a2713aSLionel Sambuc     }
1134f4a2713aSLionel Sambuc 
1135f4a2713aSLionel Sambuc     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1136f4a2713aSLionel Sambuc     // than register.
1137f4a2713aSLionel Sambuc     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1138f4a2713aSLionel Sambuc         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1139f4a2713aSLionel Sambuc       Diag(DS.getStorageClassSpecLoc(),
1140f4a2713aSLionel Sambuc            diag::err_invalid_storage_class_in_func_decl);
1141f4a2713aSLionel Sambuc       DS.ClearStorageClassSpecs();
1142f4a2713aSLionel Sambuc     }
1143f4a2713aSLionel Sambuc     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1144f4a2713aSLionel Sambuc       Diag(DS.getThreadStorageClassSpecLoc(),
1145f4a2713aSLionel Sambuc            diag::err_invalid_storage_class_in_func_decl);
1146f4a2713aSLionel Sambuc       DS.ClearStorageClassSpecs();
1147f4a2713aSLionel Sambuc     }
1148f4a2713aSLionel Sambuc 
1149f4a2713aSLionel Sambuc     // Parse the first declarator attached to this declspec.
1150f4a2713aSLionel Sambuc     Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1151f4a2713aSLionel Sambuc     ParseDeclarator(ParmDeclarator);
1152f4a2713aSLionel Sambuc 
1153f4a2713aSLionel Sambuc     // Handle the full declarator list.
1154f4a2713aSLionel Sambuc     while (1) {
1155f4a2713aSLionel Sambuc       // If attributes are present, parse them.
1156f4a2713aSLionel Sambuc       MaybeParseGNUAttributes(ParmDeclarator);
1157f4a2713aSLionel Sambuc 
1158f4a2713aSLionel Sambuc       // Ask the actions module to compute the type for this declarator.
1159f4a2713aSLionel Sambuc       Decl *Param =
1160f4a2713aSLionel Sambuc         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1161f4a2713aSLionel Sambuc 
1162f4a2713aSLionel Sambuc       if (Param &&
1163f4a2713aSLionel Sambuc           // A missing identifier has already been diagnosed.
1164f4a2713aSLionel Sambuc           ParmDeclarator.getIdentifier()) {
1165f4a2713aSLionel Sambuc 
1166f4a2713aSLionel Sambuc         // Scan the argument list looking for the correct param to apply this
1167f4a2713aSLionel Sambuc         // type.
1168f4a2713aSLionel Sambuc         for (unsigned i = 0; ; ++i) {
1169f4a2713aSLionel Sambuc           // C99 6.9.1p6: those declarators shall declare only identifiers from
1170f4a2713aSLionel Sambuc           // the identifier list.
1171*0a6a1f1dSLionel Sambuc           if (i == FTI.NumParams) {
1172f4a2713aSLionel Sambuc             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1173f4a2713aSLionel Sambuc               << ParmDeclarator.getIdentifier();
1174f4a2713aSLionel Sambuc             break;
1175f4a2713aSLionel Sambuc           }
1176f4a2713aSLionel Sambuc 
1177*0a6a1f1dSLionel Sambuc           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1178f4a2713aSLionel Sambuc             // Reject redefinitions of parameters.
1179*0a6a1f1dSLionel Sambuc             if (FTI.Params[i].Param) {
1180f4a2713aSLionel Sambuc               Diag(ParmDeclarator.getIdentifierLoc(),
1181f4a2713aSLionel Sambuc                    diag::err_param_redefinition)
1182f4a2713aSLionel Sambuc                  << ParmDeclarator.getIdentifier();
1183f4a2713aSLionel Sambuc             } else {
1184*0a6a1f1dSLionel Sambuc               FTI.Params[i].Param = Param;
1185f4a2713aSLionel Sambuc             }
1186f4a2713aSLionel Sambuc             break;
1187f4a2713aSLionel Sambuc           }
1188f4a2713aSLionel Sambuc         }
1189f4a2713aSLionel Sambuc       }
1190f4a2713aSLionel Sambuc 
1191f4a2713aSLionel Sambuc       // If we don't have a comma, it is either the end of the list (a ';') or
1192f4a2713aSLionel Sambuc       // an error, bail out.
1193f4a2713aSLionel Sambuc       if (Tok.isNot(tok::comma))
1194f4a2713aSLionel Sambuc         break;
1195f4a2713aSLionel Sambuc 
1196f4a2713aSLionel Sambuc       ParmDeclarator.clear();
1197f4a2713aSLionel Sambuc 
1198f4a2713aSLionel Sambuc       // Consume the comma.
1199f4a2713aSLionel Sambuc       ParmDeclarator.setCommaLoc(ConsumeToken());
1200f4a2713aSLionel Sambuc 
1201f4a2713aSLionel Sambuc       // Parse the next declarator.
1202f4a2713aSLionel Sambuc       ParseDeclarator(ParmDeclarator);
1203f4a2713aSLionel Sambuc     }
1204f4a2713aSLionel Sambuc 
1205*0a6a1f1dSLionel Sambuc     // Consume ';' and continue parsing.
1206*0a6a1f1dSLionel Sambuc     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1207*0a6a1f1dSLionel Sambuc       continue;
1208*0a6a1f1dSLionel Sambuc 
1209*0a6a1f1dSLionel Sambuc     // Otherwise recover by skipping to next semi or mandatory function body.
1210*0a6a1f1dSLionel Sambuc     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1211*0a6a1f1dSLionel Sambuc       break;
1212*0a6a1f1dSLionel Sambuc     TryConsumeToken(tok::semi);
1213f4a2713aSLionel Sambuc   }
1214f4a2713aSLionel Sambuc 
1215f4a2713aSLionel Sambuc   // The actions module must verify that all arguments were declared.
1216f4a2713aSLionel Sambuc   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1217f4a2713aSLionel Sambuc }
1218f4a2713aSLionel Sambuc 
1219f4a2713aSLionel Sambuc 
1220f4a2713aSLionel Sambuc /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1221f4a2713aSLionel Sambuc /// allowed to be a wide string, and is not subject to character translation.
1222f4a2713aSLionel Sambuc ///
1223f4a2713aSLionel Sambuc /// [GNU] asm-string-literal:
1224f4a2713aSLionel Sambuc ///         string-literal
1225f4a2713aSLionel Sambuc ///
ParseAsmStringLiteral()1226*0a6a1f1dSLionel Sambuc ExprResult Parser::ParseAsmStringLiteral() {
1227*0a6a1f1dSLionel Sambuc   if (!isTokenStringLiteral()) {
1228f4a2713aSLionel Sambuc     Diag(Tok, diag::err_expected_string_literal)
1229f4a2713aSLionel Sambuc       << /*Source='in...'*/0 << "'asm'";
1230f4a2713aSLionel Sambuc     return ExprError();
1231f4a2713aSLionel Sambuc   }
1232f4a2713aSLionel Sambuc 
1233*0a6a1f1dSLionel Sambuc   ExprResult AsmString(ParseStringLiteralExpression());
1234*0a6a1f1dSLionel Sambuc   if (!AsmString.isInvalid()) {
1235*0a6a1f1dSLionel Sambuc     const auto *SL = cast<StringLiteral>(AsmString.get());
1236*0a6a1f1dSLionel Sambuc     if (!SL->isAscii()) {
1237*0a6a1f1dSLionel Sambuc       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1238*0a6a1f1dSLionel Sambuc         << SL->isWide()
1239*0a6a1f1dSLionel Sambuc         << SL->getSourceRange();
1240*0a6a1f1dSLionel Sambuc       return ExprError();
1241*0a6a1f1dSLionel Sambuc     }
1242*0a6a1f1dSLionel Sambuc   }
1243*0a6a1f1dSLionel Sambuc   return AsmString;
1244f4a2713aSLionel Sambuc }
1245f4a2713aSLionel Sambuc 
1246f4a2713aSLionel Sambuc /// ParseSimpleAsm
1247f4a2713aSLionel Sambuc ///
1248f4a2713aSLionel Sambuc /// [GNU] simple-asm-expr:
1249f4a2713aSLionel Sambuc ///         'asm' '(' asm-string-literal ')'
1250f4a2713aSLionel Sambuc ///
ParseSimpleAsm(SourceLocation * EndLoc)1251*0a6a1f1dSLionel Sambuc ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1252f4a2713aSLionel Sambuc   assert(Tok.is(tok::kw_asm) && "Not an asm!");
1253f4a2713aSLionel Sambuc   SourceLocation Loc = ConsumeToken();
1254f4a2713aSLionel Sambuc 
1255f4a2713aSLionel Sambuc   if (Tok.is(tok::kw_volatile)) {
1256f4a2713aSLionel Sambuc     // Remove from the end of 'asm' to the end of 'volatile'.
1257f4a2713aSLionel Sambuc     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1258f4a2713aSLionel Sambuc                              PP.getLocForEndOfToken(Tok.getLocation()));
1259f4a2713aSLionel Sambuc 
1260f4a2713aSLionel Sambuc     Diag(Tok, diag::warn_file_asm_volatile)
1261f4a2713aSLionel Sambuc       << FixItHint::CreateRemoval(RemovalRange);
1262f4a2713aSLionel Sambuc     ConsumeToken();
1263f4a2713aSLionel Sambuc   }
1264f4a2713aSLionel Sambuc 
1265f4a2713aSLionel Sambuc   BalancedDelimiterTracker T(*this, tok::l_paren);
1266f4a2713aSLionel Sambuc   if (T.consumeOpen()) {
1267f4a2713aSLionel Sambuc     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1268f4a2713aSLionel Sambuc     return ExprError();
1269f4a2713aSLionel Sambuc   }
1270f4a2713aSLionel Sambuc 
1271f4a2713aSLionel Sambuc   ExprResult Result(ParseAsmStringLiteral());
1272f4a2713aSLionel Sambuc 
1273*0a6a1f1dSLionel Sambuc   if (!Result.isInvalid()) {
1274f4a2713aSLionel Sambuc     // Close the paren and get the location of the end bracket
1275f4a2713aSLionel Sambuc     T.consumeClose();
1276f4a2713aSLionel Sambuc     if (EndLoc)
1277f4a2713aSLionel Sambuc       *EndLoc = T.getCloseLocation();
1278*0a6a1f1dSLionel Sambuc   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1279*0a6a1f1dSLionel Sambuc     if (EndLoc)
1280*0a6a1f1dSLionel Sambuc       *EndLoc = Tok.getLocation();
1281*0a6a1f1dSLionel Sambuc     ConsumeParen();
1282f4a2713aSLionel Sambuc   }
1283f4a2713aSLionel Sambuc 
1284f4a2713aSLionel Sambuc   return Result;
1285f4a2713aSLionel Sambuc }
1286f4a2713aSLionel Sambuc 
1287f4a2713aSLionel Sambuc /// \brief Get the TemplateIdAnnotation from the token and put it in the
1288f4a2713aSLionel Sambuc /// cleanup pool so that it gets destroyed when parsing the current top level
1289f4a2713aSLionel Sambuc /// declaration is finished.
takeTemplateIdAnnotation(const Token & tok)1290f4a2713aSLionel Sambuc TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1291f4a2713aSLionel Sambuc   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1292f4a2713aSLionel Sambuc   TemplateIdAnnotation *
1293f4a2713aSLionel Sambuc       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1294f4a2713aSLionel Sambuc   return Id;
1295f4a2713aSLionel Sambuc }
1296f4a2713aSLionel Sambuc 
AnnotateScopeToken(CXXScopeSpec & SS,bool IsNewAnnotation)1297f4a2713aSLionel Sambuc void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1298f4a2713aSLionel Sambuc   // Push the current token back into the token stream (or revert it if it is
1299f4a2713aSLionel Sambuc   // cached) and use an annotation scope token for current token.
1300f4a2713aSLionel Sambuc   if (PP.isBacktrackEnabled())
1301f4a2713aSLionel Sambuc     PP.RevertCachedTokens(1);
1302f4a2713aSLionel Sambuc   else
1303f4a2713aSLionel Sambuc     PP.EnterToken(Tok);
1304f4a2713aSLionel Sambuc   Tok.setKind(tok::annot_cxxscope);
1305f4a2713aSLionel Sambuc   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1306f4a2713aSLionel Sambuc   Tok.setAnnotationRange(SS.getRange());
1307f4a2713aSLionel Sambuc 
1308f4a2713aSLionel Sambuc   // In case the tokens were cached, have Preprocessor replace them
1309f4a2713aSLionel Sambuc   // with the annotation token.  We don't need to do this if we've
1310f4a2713aSLionel Sambuc   // just reverted back to a prior state.
1311f4a2713aSLionel Sambuc   if (IsNewAnnotation)
1312f4a2713aSLionel Sambuc     PP.AnnotateCachedTokens(Tok);
1313f4a2713aSLionel Sambuc }
1314f4a2713aSLionel Sambuc 
1315f4a2713aSLionel Sambuc /// \brief Attempt to classify the name at the current token position. This may
1316f4a2713aSLionel Sambuc /// form a type, scope or primary expression annotation, or replace the token
1317f4a2713aSLionel Sambuc /// with a typo-corrected keyword. This is only appropriate when the current
1318f4a2713aSLionel Sambuc /// name must refer to an entity which has already been declared.
1319f4a2713aSLionel Sambuc ///
1320f4a2713aSLionel Sambuc /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1321f4a2713aSLionel Sambuc ///        and might possibly have a dependent nested name specifier.
1322f4a2713aSLionel Sambuc /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1323f4a2713aSLionel Sambuc ///        no typo correction will be performed.
1324f4a2713aSLionel Sambuc Parser::AnnotatedNameKind
TryAnnotateName(bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC)1325f4a2713aSLionel Sambuc Parser::TryAnnotateName(bool IsAddressOfOperand,
1326*0a6a1f1dSLionel Sambuc                         std::unique_ptr<CorrectionCandidateCallback> CCC) {
1327f4a2713aSLionel Sambuc   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1328f4a2713aSLionel Sambuc 
1329f4a2713aSLionel Sambuc   const bool EnteringContext = false;
1330f4a2713aSLionel Sambuc   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1331f4a2713aSLionel Sambuc 
1332f4a2713aSLionel Sambuc   CXXScopeSpec SS;
1333f4a2713aSLionel Sambuc   if (getLangOpts().CPlusPlus &&
1334f4a2713aSLionel Sambuc       ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1335f4a2713aSLionel Sambuc     return ANK_Error;
1336f4a2713aSLionel Sambuc 
1337f4a2713aSLionel Sambuc   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1338f4a2713aSLionel Sambuc     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1339f4a2713aSLionel Sambuc                                                   !WasScopeAnnotation))
1340f4a2713aSLionel Sambuc       return ANK_Error;
1341f4a2713aSLionel Sambuc     return ANK_Unresolved;
1342f4a2713aSLionel Sambuc   }
1343f4a2713aSLionel Sambuc 
1344f4a2713aSLionel Sambuc   IdentifierInfo *Name = Tok.getIdentifierInfo();
1345f4a2713aSLionel Sambuc   SourceLocation NameLoc = Tok.getLocation();
1346f4a2713aSLionel Sambuc 
1347f4a2713aSLionel Sambuc   // FIXME: Move the tentative declaration logic into ClassifyName so we can
1348f4a2713aSLionel Sambuc   // typo-correct to tentatively-declared identifiers.
1349f4a2713aSLionel Sambuc   if (isTentativelyDeclared(Name)) {
1350f4a2713aSLionel Sambuc     // Identifier has been tentatively declared, and thus cannot be resolved as
1351f4a2713aSLionel Sambuc     // an expression. Fall back to annotating it as a type.
1352f4a2713aSLionel Sambuc     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1353f4a2713aSLionel Sambuc                                                   !WasScopeAnnotation))
1354f4a2713aSLionel Sambuc       return ANK_Error;
1355f4a2713aSLionel Sambuc     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1356f4a2713aSLionel Sambuc   }
1357f4a2713aSLionel Sambuc 
1358f4a2713aSLionel Sambuc   Token Next = NextToken();
1359f4a2713aSLionel Sambuc 
1360f4a2713aSLionel Sambuc   // Look up and classify the identifier. We don't perform any typo-correction
1361f4a2713aSLionel Sambuc   // after a scope specifier, because in general we can't recover from typos
1362*0a6a1f1dSLionel Sambuc   // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to
1363*0a6a1f1dSLionel Sambuc   // jump back into scope specifier parsing).
1364*0a6a1f1dSLionel Sambuc   Sema::NameClassification Classification = Actions.ClassifyName(
1365*0a6a1f1dSLionel Sambuc       getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
1366*0a6a1f1dSLionel Sambuc       SS.isEmpty() ? std::move(CCC) : nullptr);
1367f4a2713aSLionel Sambuc 
1368f4a2713aSLionel Sambuc   switch (Classification.getKind()) {
1369f4a2713aSLionel Sambuc   case Sema::NC_Error:
1370f4a2713aSLionel Sambuc     return ANK_Error;
1371f4a2713aSLionel Sambuc 
1372f4a2713aSLionel Sambuc   case Sema::NC_Keyword:
1373f4a2713aSLionel Sambuc     // The identifier was typo-corrected to a keyword.
1374f4a2713aSLionel Sambuc     Tok.setIdentifierInfo(Name);
1375f4a2713aSLionel Sambuc     Tok.setKind(Name->getTokenID());
1376f4a2713aSLionel Sambuc     PP.TypoCorrectToken(Tok);
1377f4a2713aSLionel Sambuc     if (SS.isNotEmpty())
1378f4a2713aSLionel Sambuc       AnnotateScopeToken(SS, !WasScopeAnnotation);
1379f4a2713aSLionel Sambuc     // We've "annotated" this as a keyword.
1380f4a2713aSLionel Sambuc     return ANK_Success;
1381f4a2713aSLionel Sambuc 
1382f4a2713aSLionel Sambuc   case Sema::NC_Unknown:
1383f4a2713aSLionel Sambuc     // It's not something we know about. Leave it unannotated.
1384f4a2713aSLionel Sambuc     break;
1385f4a2713aSLionel Sambuc 
1386f4a2713aSLionel Sambuc   case Sema::NC_Type:
1387f4a2713aSLionel Sambuc     Tok.setKind(tok::annot_typename);
1388f4a2713aSLionel Sambuc     setTypeAnnotation(Tok, Classification.getType());
1389f4a2713aSLionel Sambuc     Tok.setAnnotationEndLoc(NameLoc);
1390f4a2713aSLionel Sambuc     if (SS.isNotEmpty())
1391f4a2713aSLionel Sambuc       Tok.setLocation(SS.getBeginLoc());
1392f4a2713aSLionel Sambuc     PP.AnnotateCachedTokens(Tok);
1393f4a2713aSLionel Sambuc     return ANK_Success;
1394f4a2713aSLionel Sambuc 
1395f4a2713aSLionel Sambuc   case Sema::NC_Expression:
1396f4a2713aSLionel Sambuc     Tok.setKind(tok::annot_primary_expr);
1397f4a2713aSLionel Sambuc     setExprAnnotation(Tok, Classification.getExpression());
1398f4a2713aSLionel Sambuc     Tok.setAnnotationEndLoc(NameLoc);
1399f4a2713aSLionel Sambuc     if (SS.isNotEmpty())
1400f4a2713aSLionel Sambuc       Tok.setLocation(SS.getBeginLoc());
1401f4a2713aSLionel Sambuc     PP.AnnotateCachedTokens(Tok);
1402f4a2713aSLionel Sambuc     return ANK_Success;
1403f4a2713aSLionel Sambuc 
1404f4a2713aSLionel Sambuc   case Sema::NC_TypeTemplate:
1405f4a2713aSLionel Sambuc     if (Next.isNot(tok::less)) {
1406f4a2713aSLionel Sambuc       // This may be a type template being used as a template template argument.
1407f4a2713aSLionel Sambuc       if (SS.isNotEmpty())
1408f4a2713aSLionel Sambuc         AnnotateScopeToken(SS, !WasScopeAnnotation);
1409f4a2713aSLionel Sambuc       return ANK_TemplateName;
1410f4a2713aSLionel Sambuc     }
1411f4a2713aSLionel Sambuc     // Fall through.
1412f4a2713aSLionel Sambuc   case Sema::NC_VarTemplate:
1413f4a2713aSLionel Sambuc   case Sema::NC_FunctionTemplate: {
1414f4a2713aSLionel Sambuc     // We have a type, variable or function template followed by '<'.
1415f4a2713aSLionel Sambuc     ConsumeToken();
1416f4a2713aSLionel Sambuc     UnqualifiedId Id;
1417f4a2713aSLionel Sambuc     Id.setIdentifier(Name, NameLoc);
1418f4a2713aSLionel Sambuc     if (AnnotateTemplateIdToken(
1419f4a2713aSLionel Sambuc             TemplateTy::make(Classification.getTemplateName()),
1420f4a2713aSLionel Sambuc             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1421f4a2713aSLionel Sambuc       return ANK_Error;
1422f4a2713aSLionel Sambuc     return ANK_Success;
1423f4a2713aSLionel Sambuc   }
1424f4a2713aSLionel Sambuc 
1425f4a2713aSLionel Sambuc   case Sema::NC_NestedNameSpecifier:
1426f4a2713aSLionel Sambuc     llvm_unreachable("already parsed nested name specifier");
1427f4a2713aSLionel Sambuc   }
1428f4a2713aSLionel Sambuc 
1429f4a2713aSLionel Sambuc   // Unable to classify the name, but maybe we can annotate a scope specifier.
1430f4a2713aSLionel Sambuc   if (SS.isNotEmpty())
1431f4a2713aSLionel Sambuc     AnnotateScopeToken(SS, !WasScopeAnnotation);
1432f4a2713aSLionel Sambuc   return ANK_Unresolved;
1433f4a2713aSLionel Sambuc }
1434f4a2713aSLionel Sambuc 
TryKeywordIdentFallback(bool DisableKeyword)1435*0a6a1f1dSLionel Sambuc bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1436*0a6a1f1dSLionel Sambuc   assert(Tok.isNot(tok::identifier));
1437*0a6a1f1dSLionel Sambuc   Diag(Tok, diag::ext_keyword_as_ident)
1438*0a6a1f1dSLionel Sambuc     << PP.getSpelling(Tok)
1439*0a6a1f1dSLionel Sambuc     << DisableKeyword;
1440*0a6a1f1dSLionel Sambuc   if (DisableKeyword)
1441*0a6a1f1dSLionel Sambuc     Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1442*0a6a1f1dSLionel Sambuc   Tok.setKind(tok::identifier);
1443*0a6a1f1dSLionel Sambuc   return true;
1444*0a6a1f1dSLionel Sambuc }
1445*0a6a1f1dSLionel Sambuc 
1446f4a2713aSLionel Sambuc /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1447f4a2713aSLionel Sambuc /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1448f4a2713aSLionel Sambuc /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1449f4a2713aSLionel Sambuc /// with a single annotation token representing the typename or C++ scope
1450f4a2713aSLionel Sambuc /// respectively.
1451f4a2713aSLionel Sambuc /// This simplifies handling of C++ scope specifiers and allows efficient
1452f4a2713aSLionel Sambuc /// backtracking without the need to re-parse and resolve nested-names and
1453f4a2713aSLionel Sambuc /// typenames.
1454f4a2713aSLionel Sambuc /// It will mainly be called when we expect to treat identifiers as typenames
1455f4a2713aSLionel Sambuc /// (if they are typenames). For example, in C we do not expect identifiers
1456f4a2713aSLionel Sambuc /// inside expressions to be treated as typenames so it will not be called
1457f4a2713aSLionel Sambuc /// for expressions in C.
1458f4a2713aSLionel Sambuc /// The benefit for C/ObjC is that a typename will be annotated and
1459f4a2713aSLionel Sambuc /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1460f4a2713aSLionel Sambuc /// will not be called twice, once to check whether we have a declaration
1461f4a2713aSLionel Sambuc /// specifier, and another one to get the actual type inside
1462f4a2713aSLionel Sambuc /// ParseDeclarationSpecifiers).
1463f4a2713aSLionel Sambuc ///
1464f4a2713aSLionel Sambuc /// This returns true if an error occurred.
1465f4a2713aSLionel Sambuc ///
1466f4a2713aSLionel Sambuc /// Note that this routine emits an error if you call it with ::new or ::delete
1467f4a2713aSLionel Sambuc /// as the current tokens, so only call it in contexts where these are invalid.
TryAnnotateTypeOrScopeToken(bool EnteringContext,bool NeedType)1468f4a2713aSLionel Sambuc bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1469*0a6a1f1dSLionel Sambuc   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1470*0a6a1f1dSLionel Sambuc           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1471*0a6a1f1dSLionel Sambuc           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1472*0a6a1f1dSLionel Sambuc           Tok.is(tok::kw___super)) &&
1473*0a6a1f1dSLionel Sambuc          "Cannot be a type or scope token!");
1474f4a2713aSLionel Sambuc 
1475f4a2713aSLionel Sambuc   if (Tok.is(tok::kw_typename)) {
1476f4a2713aSLionel Sambuc     // MSVC lets you do stuff like:
1477f4a2713aSLionel Sambuc     //   typename typedef T_::D D;
1478f4a2713aSLionel Sambuc     //
1479f4a2713aSLionel Sambuc     // We will consume the typedef token here and put it back after we have
1480f4a2713aSLionel Sambuc     // parsed the first identifier, transforming it into something more like:
1481f4a2713aSLionel Sambuc     //   typename T_::D typedef D;
1482*0a6a1f1dSLionel Sambuc     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1483f4a2713aSLionel Sambuc       Token TypedefToken;
1484f4a2713aSLionel Sambuc       PP.Lex(TypedefToken);
1485f4a2713aSLionel Sambuc       bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType);
1486f4a2713aSLionel Sambuc       PP.EnterToken(Tok);
1487f4a2713aSLionel Sambuc       Tok = TypedefToken;
1488f4a2713aSLionel Sambuc       if (!Result)
1489f4a2713aSLionel Sambuc         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1490f4a2713aSLionel Sambuc       return Result;
1491f4a2713aSLionel Sambuc     }
1492f4a2713aSLionel Sambuc 
1493f4a2713aSLionel Sambuc     // Parse a C++ typename-specifier, e.g., "typename T::type".
1494f4a2713aSLionel Sambuc     //
1495f4a2713aSLionel Sambuc     //   typename-specifier:
1496f4a2713aSLionel Sambuc     //     'typename' '::' [opt] nested-name-specifier identifier
1497f4a2713aSLionel Sambuc     //     'typename' '::' [opt] nested-name-specifier template [opt]
1498f4a2713aSLionel Sambuc     //            simple-template-id
1499f4a2713aSLionel Sambuc     SourceLocation TypenameLoc = ConsumeToken();
1500f4a2713aSLionel Sambuc     CXXScopeSpec SS;
1501f4a2713aSLionel Sambuc     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1502f4a2713aSLionel Sambuc                                        /*EnteringContext=*/false,
1503*0a6a1f1dSLionel Sambuc                                        nullptr, /*IsTypename*/ true))
1504f4a2713aSLionel Sambuc       return true;
1505f4a2713aSLionel Sambuc     if (!SS.isSet()) {
1506f4a2713aSLionel Sambuc       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1507f4a2713aSLionel Sambuc           Tok.is(tok::annot_decltype)) {
1508f4a2713aSLionel Sambuc         // Attempt to recover by skipping the invalid 'typename'
1509f4a2713aSLionel Sambuc         if (Tok.is(tok::annot_decltype) ||
1510f4a2713aSLionel Sambuc             (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1511f4a2713aSLionel Sambuc              Tok.isAnnotation())) {
1512f4a2713aSLionel Sambuc           unsigned DiagID = diag::err_expected_qualified_after_typename;
1513f4a2713aSLionel Sambuc           // MS compatibility: MSVC permits using known types with typename.
1514f4a2713aSLionel Sambuc           // e.g. "typedef typename T* pointer_type"
1515f4a2713aSLionel Sambuc           if (getLangOpts().MicrosoftExt)
1516f4a2713aSLionel Sambuc             DiagID = diag::warn_expected_qualified_after_typename;
1517f4a2713aSLionel Sambuc           Diag(Tok.getLocation(), DiagID);
1518f4a2713aSLionel Sambuc           return false;
1519f4a2713aSLionel Sambuc         }
1520f4a2713aSLionel Sambuc       }
1521f4a2713aSLionel Sambuc 
1522f4a2713aSLionel Sambuc       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1523f4a2713aSLionel Sambuc       return true;
1524f4a2713aSLionel Sambuc     }
1525f4a2713aSLionel Sambuc 
1526f4a2713aSLionel Sambuc     TypeResult Ty;
1527f4a2713aSLionel Sambuc     if (Tok.is(tok::identifier)) {
1528f4a2713aSLionel Sambuc       // FIXME: check whether the next token is '<', first!
1529f4a2713aSLionel Sambuc       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1530f4a2713aSLionel Sambuc                                      *Tok.getIdentifierInfo(),
1531f4a2713aSLionel Sambuc                                      Tok.getLocation());
1532f4a2713aSLionel Sambuc     } else if (Tok.is(tok::annot_template_id)) {
1533f4a2713aSLionel Sambuc       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1534*0a6a1f1dSLionel Sambuc       if (TemplateId->Kind != TNK_Type_template &&
1535*0a6a1f1dSLionel Sambuc           TemplateId->Kind != TNK_Dependent_template_name) {
1536f4a2713aSLionel Sambuc         Diag(Tok, diag::err_typename_refers_to_non_type_template)
1537f4a2713aSLionel Sambuc           << Tok.getAnnotationRange();
1538f4a2713aSLionel Sambuc         return true;
1539f4a2713aSLionel Sambuc       }
1540f4a2713aSLionel Sambuc 
1541f4a2713aSLionel Sambuc       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1542f4a2713aSLionel Sambuc                                          TemplateId->NumArgs);
1543f4a2713aSLionel Sambuc 
1544f4a2713aSLionel Sambuc       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1545f4a2713aSLionel Sambuc                                      TemplateId->TemplateKWLoc,
1546f4a2713aSLionel Sambuc                                      TemplateId->Template,
1547f4a2713aSLionel Sambuc                                      TemplateId->TemplateNameLoc,
1548f4a2713aSLionel Sambuc                                      TemplateId->LAngleLoc,
1549f4a2713aSLionel Sambuc                                      TemplateArgsPtr,
1550f4a2713aSLionel Sambuc                                      TemplateId->RAngleLoc);
1551f4a2713aSLionel Sambuc     } else {
1552f4a2713aSLionel Sambuc       Diag(Tok, diag::err_expected_type_name_after_typename)
1553f4a2713aSLionel Sambuc         << SS.getRange();
1554f4a2713aSLionel Sambuc       return true;
1555f4a2713aSLionel Sambuc     }
1556f4a2713aSLionel Sambuc 
1557f4a2713aSLionel Sambuc     SourceLocation EndLoc = Tok.getLastLoc();
1558f4a2713aSLionel Sambuc     Tok.setKind(tok::annot_typename);
1559f4a2713aSLionel Sambuc     setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1560f4a2713aSLionel Sambuc     Tok.setAnnotationEndLoc(EndLoc);
1561f4a2713aSLionel Sambuc     Tok.setLocation(TypenameLoc);
1562f4a2713aSLionel Sambuc     PP.AnnotateCachedTokens(Tok);
1563f4a2713aSLionel Sambuc     return false;
1564f4a2713aSLionel Sambuc   }
1565f4a2713aSLionel Sambuc 
1566f4a2713aSLionel Sambuc   // Remembers whether the token was originally a scope annotation.
1567f4a2713aSLionel Sambuc   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1568f4a2713aSLionel Sambuc 
1569f4a2713aSLionel Sambuc   CXXScopeSpec SS;
1570f4a2713aSLionel Sambuc   if (getLangOpts().CPlusPlus)
1571f4a2713aSLionel Sambuc     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1572f4a2713aSLionel Sambuc       return true;
1573f4a2713aSLionel Sambuc 
1574f4a2713aSLionel Sambuc   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1575f4a2713aSLionel Sambuc                                                    SS, !WasScopeAnnotation);
1576f4a2713aSLionel Sambuc }
1577f4a2713aSLionel Sambuc 
1578f4a2713aSLionel Sambuc /// \brief Try to annotate a type or scope token, having already parsed an
1579f4a2713aSLionel Sambuc /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1580f4a2713aSLionel Sambuc /// specifier was extracted from an existing tok::annot_cxxscope annotation.
TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,bool NeedType,CXXScopeSpec & SS,bool IsNewScope)1581f4a2713aSLionel Sambuc bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1582f4a2713aSLionel Sambuc                                                        bool NeedType,
1583f4a2713aSLionel Sambuc                                                        CXXScopeSpec &SS,
1584f4a2713aSLionel Sambuc                                                        bool IsNewScope) {
1585f4a2713aSLionel Sambuc   if (Tok.is(tok::identifier)) {
1586*0a6a1f1dSLionel Sambuc     IdentifierInfo *CorrectedII = nullptr;
1587f4a2713aSLionel Sambuc     // Determine whether the identifier is a type name.
1588f4a2713aSLionel Sambuc     if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1589f4a2713aSLionel Sambuc                                             Tok.getLocation(), getCurScope(),
1590f4a2713aSLionel Sambuc                                             &SS, false,
1591f4a2713aSLionel Sambuc                                             NextToken().is(tok::period),
1592f4a2713aSLionel Sambuc                                             ParsedType(),
1593f4a2713aSLionel Sambuc                                             /*IsCtorOrDtorName=*/false,
1594f4a2713aSLionel Sambuc                                             /*NonTrivialTypeSourceInfo*/ true,
1595*0a6a1f1dSLionel Sambuc                                             NeedType ? &CorrectedII
1596*0a6a1f1dSLionel Sambuc                                                      : nullptr)) {
1597f4a2713aSLionel Sambuc       // A FixIt was applied as a result of typo correction
1598f4a2713aSLionel Sambuc       if (CorrectedII)
1599f4a2713aSLionel Sambuc         Tok.setIdentifierInfo(CorrectedII);
1600f4a2713aSLionel Sambuc       // This is a typename. Replace the current token in-place with an
1601f4a2713aSLionel Sambuc       // annotation type token.
1602f4a2713aSLionel Sambuc       Tok.setKind(tok::annot_typename);
1603f4a2713aSLionel Sambuc       setTypeAnnotation(Tok, Ty);
1604f4a2713aSLionel Sambuc       Tok.setAnnotationEndLoc(Tok.getLocation());
1605f4a2713aSLionel Sambuc       if (SS.isNotEmpty()) // it was a C++ qualified type name.
1606f4a2713aSLionel Sambuc         Tok.setLocation(SS.getBeginLoc());
1607f4a2713aSLionel Sambuc 
1608f4a2713aSLionel Sambuc       // In case the tokens were cached, have Preprocessor replace
1609f4a2713aSLionel Sambuc       // them with the annotation token.
1610f4a2713aSLionel Sambuc       PP.AnnotateCachedTokens(Tok);
1611f4a2713aSLionel Sambuc       return false;
1612f4a2713aSLionel Sambuc     }
1613f4a2713aSLionel Sambuc 
1614f4a2713aSLionel Sambuc     if (!getLangOpts().CPlusPlus) {
1615f4a2713aSLionel Sambuc       // If we're in C, we can't have :: tokens at all (the lexer won't return
1616f4a2713aSLionel Sambuc       // them).  If the identifier is not a type, then it can't be scope either,
1617f4a2713aSLionel Sambuc       // just early exit.
1618f4a2713aSLionel Sambuc       return false;
1619f4a2713aSLionel Sambuc     }
1620f4a2713aSLionel Sambuc 
1621f4a2713aSLionel Sambuc     // If this is a template-id, annotate with a template-id or type token.
1622f4a2713aSLionel Sambuc     if (NextToken().is(tok::less)) {
1623f4a2713aSLionel Sambuc       TemplateTy Template;
1624f4a2713aSLionel Sambuc       UnqualifiedId TemplateName;
1625f4a2713aSLionel Sambuc       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1626f4a2713aSLionel Sambuc       bool MemberOfUnknownSpecialization;
1627f4a2713aSLionel Sambuc       if (TemplateNameKind TNK
1628f4a2713aSLionel Sambuc           = Actions.isTemplateName(getCurScope(), SS,
1629f4a2713aSLionel Sambuc                                    /*hasTemplateKeyword=*/false, TemplateName,
1630f4a2713aSLionel Sambuc                                    /*ObjectType=*/ ParsedType(),
1631f4a2713aSLionel Sambuc                                    EnteringContext,
1632f4a2713aSLionel Sambuc                                    Template, MemberOfUnknownSpecialization)) {
1633f4a2713aSLionel Sambuc         // Consume the identifier.
1634f4a2713aSLionel Sambuc         ConsumeToken();
1635f4a2713aSLionel Sambuc         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1636f4a2713aSLionel Sambuc                                     TemplateName)) {
1637f4a2713aSLionel Sambuc           // If an unrecoverable error occurred, we need to return true here,
1638f4a2713aSLionel Sambuc           // because the token stream is in a damaged state.  We may not return
1639f4a2713aSLionel Sambuc           // a valid identifier.
1640f4a2713aSLionel Sambuc           return true;
1641f4a2713aSLionel Sambuc         }
1642f4a2713aSLionel Sambuc       }
1643f4a2713aSLionel Sambuc     }
1644f4a2713aSLionel Sambuc 
1645f4a2713aSLionel Sambuc     // The current token, which is either an identifier or a
1646f4a2713aSLionel Sambuc     // template-id, is not part of the annotation. Fall through to
1647f4a2713aSLionel Sambuc     // push that token back into the stream and complete the C++ scope
1648f4a2713aSLionel Sambuc     // specifier annotation.
1649f4a2713aSLionel Sambuc   }
1650f4a2713aSLionel Sambuc 
1651f4a2713aSLionel Sambuc   if (Tok.is(tok::annot_template_id)) {
1652f4a2713aSLionel Sambuc     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1653f4a2713aSLionel Sambuc     if (TemplateId->Kind == TNK_Type_template) {
1654f4a2713aSLionel Sambuc       // A template-id that refers to a type was parsed into a
1655f4a2713aSLionel Sambuc       // template-id annotation in a context where we weren't allowed
1656f4a2713aSLionel Sambuc       // to produce a type annotation token. Update the template-id
1657f4a2713aSLionel Sambuc       // annotation token to a type annotation token now.
1658f4a2713aSLionel Sambuc       AnnotateTemplateIdTokenAsType();
1659f4a2713aSLionel Sambuc       return false;
1660*0a6a1f1dSLionel Sambuc     }
1661f4a2713aSLionel Sambuc   }
1662f4a2713aSLionel Sambuc 
1663f4a2713aSLionel Sambuc   if (SS.isEmpty())
1664f4a2713aSLionel Sambuc     return false;
1665f4a2713aSLionel Sambuc 
1666f4a2713aSLionel Sambuc   // A C++ scope specifier that isn't followed by a typename.
1667f4a2713aSLionel Sambuc   AnnotateScopeToken(SS, IsNewScope);
1668f4a2713aSLionel Sambuc   return false;
1669f4a2713aSLionel Sambuc }
1670f4a2713aSLionel Sambuc 
1671f4a2713aSLionel Sambuc /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1672f4a2713aSLionel Sambuc /// annotates C++ scope specifiers and template-ids.  This returns
1673f4a2713aSLionel Sambuc /// true if there was an error that could not be recovered from.
1674f4a2713aSLionel Sambuc ///
1675f4a2713aSLionel Sambuc /// Note that this routine emits an error if you call it with ::new or ::delete
1676f4a2713aSLionel Sambuc /// as the current tokens, so only call it in contexts where these are invalid.
TryAnnotateCXXScopeToken(bool EnteringContext)1677f4a2713aSLionel Sambuc bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1678f4a2713aSLionel Sambuc   assert(getLangOpts().CPlusPlus &&
1679f4a2713aSLionel Sambuc          "Call sites of this function should be guarded by checking for C++");
1680f4a2713aSLionel Sambuc   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1681f4a2713aSLionel Sambuc           (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1682*0a6a1f1dSLionel Sambuc           Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
1683*0a6a1f1dSLionel Sambuc          "Cannot be a type or scope token!");
1684f4a2713aSLionel Sambuc 
1685f4a2713aSLionel Sambuc   CXXScopeSpec SS;
1686f4a2713aSLionel Sambuc   if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1687f4a2713aSLionel Sambuc     return true;
1688f4a2713aSLionel Sambuc   if (SS.isEmpty())
1689f4a2713aSLionel Sambuc     return false;
1690f4a2713aSLionel Sambuc 
1691f4a2713aSLionel Sambuc   AnnotateScopeToken(SS, true);
1692f4a2713aSLionel Sambuc   return false;
1693f4a2713aSLionel Sambuc }
1694f4a2713aSLionel Sambuc 
isTokenEqualOrEqualTypo()1695f4a2713aSLionel Sambuc bool Parser::isTokenEqualOrEqualTypo() {
1696f4a2713aSLionel Sambuc   tok::TokenKind Kind = Tok.getKind();
1697f4a2713aSLionel Sambuc   switch (Kind) {
1698f4a2713aSLionel Sambuc   default:
1699f4a2713aSLionel Sambuc     return false;
1700f4a2713aSLionel Sambuc   case tok::ampequal:            // &=
1701f4a2713aSLionel Sambuc   case tok::starequal:           // *=
1702f4a2713aSLionel Sambuc   case tok::plusequal:           // +=
1703f4a2713aSLionel Sambuc   case tok::minusequal:          // -=
1704f4a2713aSLionel Sambuc   case tok::exclaimequal:        // !=
1705f4a2713aSLionel Sambuc   case tok::slashequal:          // /=
1706f4a2713aSLionel Sambuc   case tok::percentequal:        // %=
1707f4a2713aSLionel Sambuc   case tok::lessequal:           // <=
1708f4a2713aSLionel Sambuc   case tok::lesslessequal:       // <<=
1709f4a2713aSLionel Sambuc   case tok::greaterequal:        // >=
1710f4a2713aSLionel Sambuc   case tok::greatergreaterequal: // >>=
1711f4a2713aSLionel Sambuc   case tok::caretequal:          // ^=
1712f4a2713aSLionel Sambuc   case tok::pipeequal:           // |=
1713f4a2713aSLionel Sambuc   case tok::equalequal:          // ==
1714f4a2713aSLionel Sambuc     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1715*0a6a1f1dSLionel Sambuc         << Kind
1716f4a2713aSLionel Sambuc         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1717f4a2713aSLionel Sambuc   case tok::equal:
1718f4a2713aSLionel Sambuc     return true;
1719f4a2713aSLionel Sambuc   }
1720f4a2713aSLionel Sambuc }
1721f4a2713aSLionel Sambuc 
handleUnexpectedCodeCompletionToken()1722f4a2713aSLionel Sambuc SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1723f4a2713aSLionel Sambuc   assert(Tok.is(tok::code_completion));
1724f4a2713aSLionel Sambuc   PrevTokLocation = Tok.getLocation();
1725f4a2713aSLionel Sambuc 
1726f4a2713aSLionel Sambuc   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1727f4a2713aSLionel Sambuc     if (S->getFlags() & Scope::FnScope) {
1728*0a6a1f1dSLionel Sambuc       Actions.CodeCompleteOrdinaryName(getCurScope(),
1729*0a6a1f1dSLionel Sambuc                                        Sema::PCC_RecoveryInFunction);
1730f4a2713aSLionel Sambuc       cutOffParsing();
1731f4a2713aSLionel Sambuc       return PrevTokLocation;
1732f4a2713aSLionel Sambuc     }
1733f4a2713aSLionel Sambuc 
1734f4a2713aSLionel Sambuc     if (S->getFlags() & Scope::ClassScope) {
1735f4a2713aSLionel Sambuc       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1736f4a2713aSLionel Sambuc       cutOffParsing();
1737f4a2713aSLionel Sambuc       return PrevTokLocation;
1738f4a2713aSLionel Sambuc     }
1739f4a2713aSLionel Sambuc   }
1740f4a2713aSLionel Sambuc 
1741f4a2713aSLionel Sambuc   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1742f4a2713aSLionel Sambuc   cutOffParsing();
1743f4a2713aSLionel Sambuc   return PrevTokLocation;
1744f4a2713aSLionel Sambuc }
1745f4a2713aSLionel Sambuc 
1746f4a2713aSLionel Sambuc // Code-completion pass-through functions
1747f4a2713aSLionel Sambuc 
CodeCompleteDirective(bool InConditional)1748f4a2713aSLionel Sambuc void Parser::CodeCompleteDirective(bool InConditional) {
1749f4a2713aSLionel Sambuc   Actions.CodeCompletePreprocessorDirective(InConditional);
1750f4a2713aSLionel Sambuc }
1751f4a2713aSLionel Sambuc 
CodeCompleteInConditionalExclusion()1752f4a2713aSLionel Sambuc void Parser::CodeCompleteInConditionalExclusion() {
1753f4a2713aSLionel Sambuc   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1754f4a2713aSLionel Sambuc }
1755f4a2713aSLionel Sambuc 
CodeCompleteMacroName(bool IsDefinition)1756f4a2713aSLionel Sambuc void Parser::CodeCompleteMacroName(bool IsDefinition) {
1757f4a2713aSLionel Sambuc   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1758f4a2713aSLionel Sambuc }
1759f4a2713aSLionel Sambuc 
CodeCompletePreprocessorExpression()1760f4a2713aSLionel Sambuc void Parser::CodeCompletePreprocessorExpression() {
1761f4a2713aSLionel Sambuc   Actions.CodeCompletePreprocessorExpression();
1762f4a2713aSLionel Sambuc }
1763f4a2713aSLionel Sambuc 
CodeCompleteMacroArgument(IdentifierInfo * Macro,MacroInfo * MacroInfo,unsigned ArgumentIndex)1764f4a2713aSLionel Sambuc void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1765f4a2713aSLionel Sambuc                                        MacroInfo *MacroInfo,
1766f4a2713aSLionel Sambuc                                        unsigned ArgumentIndex) {
1767f4a2713aSLionel Sambuc   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1768f4a2713aSLionel Sambuc                                                 ArgumentIndex);
1769f4a2713aSLionel Sambuc }
1770f4a2713aSLionel Sambuc 
CodeCompleteNaturalLanguage()1771f4a2713aSLionel Sambuc void Parser::CodeCompleteNaturalLanguage() {
1772f4a2713aSLionel Sambuc   Actions.CodeCompleteNaturalLanguage();
1773f4a2713aSLionel Sambuc }
1774f4a2713aSLionel Sambuc 
ParseMicrosoftIfExistsCondition(IfExistsCondition & Result)1775f4a2713aSLionel Sambuc bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1776f4a2713aSLionel Sambuc   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1777f4a2713aSLionel Sambuc          "Expected '__if_exists' or '__if_not_exists'");
1778f4a2713aSLionel Sambuc   Result.IsIfExists = Tok.is(tok::kw___if_exists);
1779f4a2713aSLionel Sambuc   Result.KeywordLoc = ConsumeToken();
1780f4a2713aSLionel Sambuc 
1781f4a2713aSLionel Sambuc   BalancedDelimiterTracker T(*this, tok::l_paren);
1782f4a2713aSLionel Sambuc   if (T.consumeOpen()) {
1783f4a2713aSLionel Sambuc     Diag(Tok, diag::err_expected_lparen_after)
1784f4a2713aSLionel Sambuc       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1785f4a2713aSLionel Sambuc     return true;
1786f4a2713aSLionel Sambuc   }
1787f4a2713aSLionel Sambuc 
1788f4a2713aSLionel Sambuc   // Parse nested-name-specifier.
1789*0a6a1f1dSLionel Sambuc   if (getLangOpts().CPlusPlus)
1790f4a2713aSLionel Sambuc     ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1791f4a2713aSLionel Sambuc                                    /*EnteringContext=*/false);
1792f4a2713aSLionel Sambuc 
1793f4a2713aSLionel Sambuc   // Check nested-name specifier.
1794f4a2713aSLionel Sambuc   if (Result.SS.isInvalid()) {
1795f4a2713aSLionel Sambuc     T.skipToEnd();
1796f4a2713aSLionel Sambuc     return true;
1797f4a2713aSLionel Sambuc   }
1798f4a2713aSLionel Sambuc 
1799f4a2713aSLionel Sambuc   // Parse the unqualified-id.
1800f4a2713aSLionel Sambuc   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1801f4a2713aSLionel Sambuc   if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1802f4a2713aSLionel Sambuc                          TemplateKWLoc, Result.Name)) {
1803f4a2713aSLionel Sambuc     T.skipToEnd();
1804f4a2713aSLionel Sambuc     return true;
1805f4a2713aSLionel Sambuc   }
1806f4a2713aSLionel Sambuc 
1807f4a2713aSLionel Sambuc   if (T.consumeClose())
1808f4a2713aSLionel Sambuc     return true;
1809f4a2713aSLionel Sambuc 
1810f4a2713aSLionel Sambuc   // Check if the symbol exists.
1811f4a2713aSLionel Sambuc   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1812f4a2713aSLionel Sambuc                                                Result.IsIfExists, Result.SS,
1813f4a2713aSLionel Sambuc                                                Result.Name)) {
1814f4a2713aSLionel Sambuc   case Sema::IER_Exists:
1815f4a2713aSLionel Sambuc     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1816f4a2713aSLionel Sambuc     break;
1817f4a2713aSLionel Sambuc 
1818f4a2713aSLionel Sambuc   case Sema::IER_DoesNotExist:
1819f4a2713aSLionel Sambuc     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1820f4a2713aSLionel Sambuc     break;
1821f4a2713aSLionel Sambuc 
1822f4a2713aSLionel Sambuc   case Sema::IER_Dependent:
1823f4a2713aSLionel Sambuc     Result.Behavior = IEB_Dependent;
1824f4a2713aSLionel Sambuc     break;
1825f4a2713aSLionel Sambuc 
1826f4a2713aSLionel Sambuc   case Sema::IER_Error:
1827f4a2713aSLionel Sambuc     return true;
1828f4a2713aSLionel Sambuc   }
1829f4a2713aSLionel Sambuc 
1830f4a2713aSLionel Sambuc   return false;
1831f4a2713aSLionel Sambuc }
1832f4a2713aSLionel Sambuc 
ParseMicrosoftIfExistsExternalDeclaration()1833f4a2713aSLionel Sambuc void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1834f4a2713aSLionel Sambuc   IfExistsCondition Result;
1835f4a2713aSLionel Sambuc   if (ParseMicrosoftIfExistsCondition(Result))
1836f4a2713aSLionel Sambuc     return;
1837f4a2713aSLionel Sambuc 
1838f4a2713aSLionel Sambuc   BalancedDelimiterTracker Braces(*this, tok::l_brace);
1839f4a2713aSLionel Sambuc   if (Braces.consumeOpen()) {
1840*0a6a1f1dSLionel Sambuc     Diag(Tok, diag::err_expected) << tok::l_brace;
1841f4a2713aSLionel Sambuc     return;
1842f4a2713aSLionel Sambuc   }
1843f4a2713aSLionel Sambuc 
1844f4a2713aSLionel Sambuc   switch (Result.Behavior) {
1845f4a2713aSLionel Sambuc   case IEB_Parse:
1846f4a2713aSLionel Sambuc     // Parse declarations below.
1847f4a2713aSLionel Sambuc     break;
1848f4a2713aSLionel Sambuc 
1849f4a2713aSLionel Sambuc   case IEB_Dependent:
1850f4a2713aSLionel Sambuc     llvm_unreachable("Cannot have a dependent external declaration");
1851f4a2713aSLionel Sambuc 
1852f4a2713aSLionel Sambuc   case IEB_Skip:
1853f4a2713aSLionel Sambuc     Braces.skipToEnd();
1854f4a2713aSLionel Sambuc     return;
1855f4a2713aSLionel Sambuc   }
1856f4a2713aSLionel Sambuc 
1857f4a2713aSLionel Sambuc   // Parse the declarations.
1858*0a6a1f1dSLionel Sambuc   // FIXME: Support module import within __if_exists?
1859*0a6a1f1dSLionel Sambuc   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1860f4a2713aSLionel Sambuc     ParsedAttributesWithRange attrs(AttrFactory);
1861f4a2713aSLionel Sambuc     MaybeParseCXX11Attributes(attrs);
1862f4a2713aSLionel Sambuc     MaybeParseMicrosoftAttributes(attrs);
1863f4a2713aSLionel Sambuc     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1864f4a2713aSLionel Sambuc     if (Result && !getCurScope()->getParent())
1865f4a2713aSLionel Sambuc       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1866f4a2713aSLionel Sambuc   }
1867f4a2713aSLionel Sambuc   Braces.consumeClose();
1868f4a2713aSLionel Sambuc }
1869f4a2713aSLionel Sambuc 
ParseModuleImport(SourceLocation AtLoc)1870f4a2713aSLionel Sambuc Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1871f4a2713aSLionel Sambuc   assert(Tok.isObjCAtKeyword(tok::objc_import) &&
1872f4a2713aSLionel Sambuc          "Improper start to module import");
1873f4a2713aSLionel Sambuc   SourceLocation ImportLoc = ConsumeToken();
1874f4a2713aSLionel Sambuc 
1875f4a2713aSLionel Sambuc   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1876f4a2713aSLionel Sambuc 
1877f4a2713aSLionel Sambuc   // Parse the module path.
1878f4a2713aSLionel Sambuc   do {
1879f4a2713aSLionel Sambuc     if (!Tok.is(tok::identifier)) {
1880f4a2713aSLionel Sambuc       if (Tok.is(tok::code_completion)) {
1881f4a2713aSLionel Sambuc         Actions.CodeCompleteModuleImport(ImportLoc, Path);
1882*0a6a1f1dSLionel Sambuc         cutOffParsing();
1883f4a2713aSLionel Sambuc         return DeclGroupPtrTy();
1884f4a2713aSLionel Sambuc       }
1885f4a2713aSLionel Sambuc 
1886f4a2713aSLionel Sambuc       Diag(Tok, diag::err_module_expected_ident);
1887f4a2713aSLionel Sambuc       SkipUntil(tok::semi);
1888f4a2713aSLionel Sambuc       return DeclGroupPtrTy();
1889f4a2713aSLionel Sambuc     }
1890f4a2713aSLionel Sambuc 
1891f4a2713aSLionel Sambuc     // Record this part of the module path.
1892f4a2713aSLionel Sambuc     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1893f4a2713aSLionel Sambuc     ConsumeToken();
1894f4a2713aSLionel Sambuc 
1895f4a2713aSLionel Sambuc     if (Tok.is(tok::period)) {
1896f4a2713aSLionel Sambuc       ConsumeToken();
1897f4a2713aSLionel Sambuc       continue;
1898f4a2713aSLionel Sambuc     }
1899f4a2713aSLionel Sambuc 
1900f4a2713aSLionel Sambuc     break;
1901f4a2713aSLionel Sambuc   } while (true);
1902f4a2713aSLionel Sambuc 
1903f4a2713aSLionel Sambuc   if (PP.hadModuleLoaderFatalFailure()) {
1904f4a2713aSLionel Sambuc     // With a fatal failure in the module loader, we abort parsing.
1905f4a2713aSLionel Sambuc     cutOffParsing();
1906f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
1907f4a2713aSLionel Sambuc   }
1908f4a2713aSLionel Sambuc 
1909f4a2713aSLionel Sambuc   DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
1910f4a2713aSLionel Sambuc   ExpectAndConsumeSemi(diag::err_module_expected_semi);
1911f4a2713aSLionel Sambuc   if (Import.isInvalid())
1912f4a2713aSLionel Sambuc     return DeclGroupPtrTy();
1913f4a2713aSLionel Sambuc 
1914f4a2713aSLionel Sambuc   return Actions.ConvertDeclToDeclGroup(Import.get());
1915f4a2713aSLionel Sambuc }
1916f4a2713aSLionel Sambuc 
diagnoseOverflow()1917f4a2713aSLionel Sambuc bool BalancedDelimiterTracker::diagnoseOverflow() {
1918f4a2713aSLionel Sambuc   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
1919f4a2713aSLionel Sambuc     << P.getLangOpts().BracketDepth;
1920f4a2713aSLionel Sambuc   P.Diag(P.Tok, diag::note_bracket_depth);
1921*0a6a1f1dSLionel Sambuc   P.cutOffParsing();
1922f4a2713aSLionel Sambuc   return true;
1923f4a2713aSLionel Sambuc }
1924f4a2713aSLionel Sambuc 
expectAndConsume(unsigned DiagID,const char * Msg,tok::TokenKind SkipToTok)1925f4a2713aSLionel Sambuc bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1926f4a2713aSLionel Sambuc                                                 const char *Msg,
1927*0a6a1f1dSLionel Sambuc                                                 tok::TokenKind SkipToTok) {
1928f4a2713aSLionel Sambuc   LOpen = P.Tok.getLocation();
1929*0a6a1f1dSLionel Sambuc   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
1930*0a6a1f1dSLionel Sambuc     if (SkipToTok != tok::unknown)
1931*0a6a1f1dSLionel Sambuc       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
1932f4a2713aSLionel Sambuc     return true;
1933*0a6a1f1dSLionel Sambuc   }
1934f4a2713aSLionel Sambuc 
1935f4a2713aSLionel Sambuc   if (getDepth() < MaxDepth)
1936f4a2713aSLionel Sambuc     return false;
1937f4a2713aSLionel Sambuc 
1938f4a2713aSLionel Sambuc   return diagnoseOverflow();
1939f4a2713aSLionel Sambuc }
1940f4a2713aSLionel Sambuc 
diagnoseMissingClose()1941f4a2713aSLionel Sambuc bool BalancedDelimiterTracker::diagnoseMissingClose() {
1942f4a2713aSLionel Sambuc   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1943f4a2713aSLionel Sambuc 
1944*0a6a1f1dSLionel Sambuc   P.Diag(P.Tok, diag::err_expected) << Close;
1945*0a6a1f1dSLionel Sambuc   P.Diag(LOpen, diag::note_matching) << Kind;
1946f4a2713aSLionel Sambuc 
1947f4a2713aSLionel Sambuc   // If we're not already at some kind of closing bracket, skip to our closing
1948f4a2713aSLionel Sambuc   // token.
1949f4a2713aSLionel Sambuc   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
1950f4a2713aSLionel Sambuc       P.Tok.isNot(tok::r_square) &&
1951f4a2713aSLionel Sambuc       P.SkipUntil(Close, FinalToken,
1952f4a2713aSLionel Sambuc                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
1953f4a2713aSLionel Sambuc       P.Tok.is(Close))
1954f4a2713aSLionel Sambuc     LClose = P.ConsumeAnyToken();
1955f4a2713aSLionel Sambuc   return true;
1956f4a2713aSLionel Sambuc }
1957f4a2713aSLionel Sambuc 
skipToEnd()1958f4a2713aSLionel Sambuc void BalancedDelimiterTracker::skipToEnd() {
1959f4a2713aSLionel Sambuc   P.SkipUntil(Close, Parser::StopBeforeMatch);
1960f4a2713aSLionel Sambuc   consumeClose();
1961f4a2713aSLionel Sambuc }
1962