xref: /aosp_15_r20/external/clang/lib/Parse/ParseStmt.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements the Statement and Block portions of the Parser
11*67e74705SXin Li // interface.
12*67e74705SXin Li //
13*67e74705SXin Li //===----------------------------------------------------------------------===//
14*67e74705SXin Li 
15*67e74705SXin Li #include "clang/Parse/Parser.h"
16*67e74705SXin Li #include "RAIIObjectsForParser.h"
17*67e74705SXin Li #include "clang/AST/ASTContext.h"
18*67e74705SXin Li #include "clang/Basic/Attributes.h"
19*67e74705SXin Li #include "clang/Basic/Diagnostic.h"
20*67e74705SXin Li #include "clang/Basic/PrettyStackTrace.h"
21*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
22*67e74705SXin Li #include "clang/Sema/LoopHint.h"
23*67e74705SXin Li #include "clang/Sema/PrettyDeclStackTrace.h"
24*67e74705SXin Li #include "clang/Sema/Scope.h"
25*67e74705SXin Li #include "clang/Sema/TypoCorrection.h"
26*67e74705SXin Li #include "llvm/ADT/SmallString.h"
27*67e74705SXin Li using namespace clang;
28*67e74705SXin Li 
29*67e74705SXin Li //===----------------------------------------------------------------------===//
30*67e74705SXin Li // C99 6.8: Statements and Blocks.
31*67e74705SXin Li //===----------------------------------------------------------------------===//
32*67e74705SXin Li 
33*67e74705SXin Li /// \brief Parse a standalone statement (for instance, as the body of an 'if',
34*67e74705SXin Li /// 'while', or 'for').
ParseStatement(SourceLocation * TrailingElseLoc,bool AllowOpenMPStandalone)35*67e74705SXin Li StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
36*67e74705SXin Li                                   bool AllowOpenMPStandalone) {
37*67e74705SXin Li   StmtResult Res;
38*67e74705SXin Li 
39*67e74705SXin Li   // We may get back a null statement if we found a #pragma. Keep going until
40*67e74705SXin Li   // we get an actual statement.
41*67e74705SXin Li   do {
42*67e74705SXin Li     StmtVector Stmts;
43*67e74705SXin Li     Res = ParseStatementOrDeclaration(
44*67e74705SXin Li         Stmts, AllowOpenMPStandalone ? ACK_StatementsOpenMPAnyExecutable
45*67e74705SXin Li                                      : ACK_StatementsOpenMPNonStandalone,
46*67e74705SXin Li         TrailingElseLoc);
47*67e74705SXin Li   } while (!Res.isInvalid() && !Res.get());
48*67e74705SXin Li 
49*67e74705SXin Li   return Res;
50*67e74705SXin Li }
51*67e74705SXin Li 
52*67e74705SXin Li /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
53*67e74705SXin Li ///       StatementOrDeclaration:
54*67e74705SXin Li ///         statement
55*67e74705SXin Li ///         declaration
56*67e74705SXin Li ///
57*67e74705SXin Li ///       statement:
58*67e74705SXin Li ///         labeled-statement
59*67e74705SXin Li ///         compound-statement
60*67e74705SXin Li ///         expression-statement
61*67e74705SXin Li ///         selection-statement
62*67e74705SXin Li ///         iteration-statement
63*67e74705SXin Li ///         jump-statement
64*67e74705SXin Li /// [C++]   declaration-statement
65*67e74705SXin Li /// [C++]   try-block
66*67e74705SXin Li /// [MS]    seh-try-block
67*67e74705SXin Li /// [OBC]   objc-throw-statement
68*67e74705SXin Li /// [OBC]   objc-try-catch-statement
69*67e74705SXin Li /// [OBC]   objc-synchronized-statement
70*67e74705SXin Li /// [GNU]   asm-statement
71*67e74705SXin Li /// [OMP]   openmp-construct             [TODO]
72*67e74705SXin Li ///
73*67e74705SXin Li ///       labeled-statement:
74*67e74705SXin Li ///         identifier ':' statement
75*67e74705SXin Li ///         'case' constant-expression ':' statement
76*67e74705SXin Li ///         'default' ':' statement
77*67e74705SXin Li ///
78*67e74705SXin Li ///       selection-statement:
79*67e74705SXin Li ///         if-statement
80*67e74705SXin Li ///         switch-statement
81*67e74705SXin Li ///
82*67e74705SXin Li ///       iteration-statement:
83*67e74705SXin Li ///         while-statement
84*67e74705SXin Li ///         do-statement
85*67e74705SXin Li ///         for-statement
86*67e74705SXin Li ///
87*67e74705SXin Li ///       expression-statement:
88*67e74705SXin Li ///         expression[opt] ';'
89*67e74705SXin Li ///
90*67e74705SXin Li ///       jump-statement:
91*67e74705SXin Li ///         'goto' identifier ';'
92*67e74705SXin Li ///         'continue' ';'
93*67e74705SXin Li ///         'break' ';'
94*67e74705SXin Li ///         'return' expression[opt] ';'
95*67e74705SXin Li /// [GNU]   'goto' '*' expression ';'
96*67e74705SXin Li ///
97*67e74705SXin Li /// [OBC] objc-throw-statement:
98*67e74705SXin Li /// [OBC]   '@' 'throw' expression ';'
99*67e74705SXin Li /// [OBC]   '@' 'throw' ';'
100*67e74705SXin Li ///
101*67e74705SXin Li StmtResult
ParseStatementOrDeclaration(StmtVector & Stmts,AllowedContsructsKind Allowed,SourceLocation * TrailingElseLoc)102*67e74705SXin Li Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
103*67e74705SXin Li                                     AllowedContsructsKind Allowed,
104*67e74705SXin Li                                     SourceLocation *TrailingElseLoc) {
105*67e74705SXin Li 
106*67e74705SXin Li   ParenBraceBracketBalancer BalancerRAIIObj(*this);
107*67e74705SXin Li 
108*67e74705SXin Li   ParsedAttributesWithRange Attrs(AttrFactory);
109*67e74705SXin Li   MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
110*67e74705SXin Li   if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
111*67e74705SXin Li     return StmtError();
112*67e74705SXin Li 
113*67e74705SXin Li   StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
114*67e74705SXin Li       Stmts, Allowed, TrailingElseLoc, Attrs);
115*67e74705SXin Li 
116*67e74705SXin Li   assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
117*67e74705SXin Li          "attributes on empty statement");
118*67e74705SXin Li 
119*67e74705SXin Li   if (Attrs.empty() || Res.isInvalid())
120*67e74705SXin Li     return Res;
121*67e74705SXin Li 
122*67e74705SXin Li   return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
123*67e74705SXin Li }
124*67e74705SXin Li 
125*67e74705SXin Li namespace {
126*67e74705SXin Li class StatementFilterCCC : public CorrectionCandidateCallback {
127*67e74705SXin Li public:
StatementFilterCCC(Token nextTok)128*67e74705SXin Li   StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
129*67e74705SXin Li     WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
130*67e74705SXin Li                                          tok::identifier, tok::star, tok::amp);
131*67e74705SXin Li     WantExpressionKeywords =
132*67e74705SXin Li         nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
133*67e74705SXin Li     WantRemainingKeywords =
134*67e74705SXin Li         nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
135*67e74705SXin Li     WantCXXNamedCasts = false;
136*67e74705SXin Li   }
137*67e74705SXin Li 
ValidateCandidate(const TypoCorrection & candidate)138*67e74705SXin Li   bool ValidateCandidate(const TypoCorrection &candidate) override {
139*67e74705SXin Li     if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
140*67e74705SXin Li       return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
141*67e74705SXin Li     if (NextToken.is(tok::equal))
142*67e74705SXin Li       return candidate.getCorrectionDeclAs<VarDecl>();
143*67e74705SXin Li     if (NextToken.is(tok::period) &&
144*67e74705SXin Li         candidate.getCorrectionDeclAs<NamespaceDecl>())
145*67e74705SXin Li       return false;
146*67e74705SXin Li     return CorrectionCandidateCallback::ValidateCandidate(candidate);
147*67e74705SXin Li   }
148*67e74705SXin Li 
149*67e74705SXin Li private:
150*67e74705SXin Li   Token NextToken;
151*67e74705SXin Li };
152*67e74705SXin Li }
153*67e74705SXin Li 
154*67e74705SXin Li StmtResult
ParseStatementOrDeclarationAfterAttributes(StmtVector & Stmts,AllowedContsructsKind Allowed,SourceLocation * TrailingElseLoc,ParsedAttributesWithRange & Attrs)155*67e74705SXin Li Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
156*67e74705SXin Li           AllowedContsructsKind Allowed, SourceLocation *TrailingElseLoc,
157*67e74705SXin Li           ParsedAttributesWithRange &Attrs) {
158*67e74705SXin Li   const char *SemiError = nullptr;
159*67e74705SXin Li   StmtResult Res;
160*67e74705SXin Li 
161*67e74705SXin Li   // Cases in this switch statement should fall through if the parser expects
162*67e74705SXin Li   // the token to end in a semicolon (in which case SemiError should be set),
163*67e74705SXin Li   // or they directly 'return;' if not.
164*67e74705SXin Li Retry:
165*67e74705SXin Li   tok::TokenKind Kind  = Tok.getKind();
166*67e74705SXin Li   SourceLocation AtLoc;
167*67e74705SXin Li   switch (Kind) {
168*67e74705SXin Li   case tok::at: // May be a @try or @throw statement
169*67e74705SXin Li     {
170*67e74705SXin Li       ProhibitAttributes(Attrs); // TODO: is it correct?
171*67e74705SXin Li       AtLoc = ConsumeToken();  // consume @
172*67e74705SXin Li       return ParseObjCAtStatement(AtLoc);
173*67e74705SXin Li     }
174*67e74705SXin Li 
175*67e74705SXin Li   case tok::code_completion:
176*67e74705SXin Li     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
177*67e74705SXin Li     cutOffParsing();
178*67e74705SXin Li     return StmtError();
179*67e74705SXin Li 
180*67e74705SXin Li   case tok::identifier: {
181*67e74705SXin Li     Token Next = NextToken();
182*67e74705SXin Li     if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
183*67e74705SXin Li       // identifier ':' statement
184*67e74705SXin Li       return ParseLabeledStatement(Attrs);
185*67e74705SXin Li     }
186*67e74705SXin Li 
187*67e74705SXin Li     // Look up the identifier, and typo-correct it to a keyword if it's not
188*67e74705SXin Li     // found.
189*67e74705SXin Li     if (Next.isNot(tok::coloncolon)) {
190*67e74705SXin Li       // Try to limit which sets of keywords should be included in typo
191*67e74705SXin Li       // correction based on what the next token is.
192*67e74705SXin Li       if (TryAnnotateName(/*IsAddressOfOperand*/ false,
193*67e74705SXin Li                           llvm::make_unique<StatementFilterCCC>(Next)) ==
194*67e74705SXin Li           ANK_Error) {
195*67e74705SXin Li         // Handle errors here by skipping up to the next semicolon or '}', and
196*67e74705SXin Li         // eat the semicolon if that's what stopped us.
197*67e74705SXin Li         SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
198*67e74705SXin Li         if (Tok.is(tok::semi))
199*67e74705SXin Li           ConsumeToken();
200*67e74705SXin Li         return StmtError();
201*67e74705SXin Li       }
202*67e74705SXin Li 
203*67e74705SXin Li       // If the identifier was typo-corrected, try again.
204*67e74705SXin Li       if (Tok.isNot(tok::identifier))
205*67e74705SXin Li         goto Retry;
206*67e74705SXin Li     }
207*67e74705SXin Li 
208*67e74705SXin Li     // Fall through
209*67e74705SXin Li   }
210*67e74705SXin Li 
211*67e74705SXin Li   default: {
212*67e74705SXin Li     if ((getLangOpts().CPlusPlus || Allowed == ACK_Any) &&
213*67e74705SXin Li         isDeclarationStatement()) {
214*67e74705SXin Li       SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
215*67e74705SXin Li       DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
216*67e74705SXin Li                                              DeclEnd, Attrs);
217*67e74705SXin Li       return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
218*67e74705SXin Li     }
219*67e74705SXin Li 
220*67e74705SXin Li     if (Tok.is(tok::r_brace)) {
221*67e74705SXin Li       Diag(Tok, diag::err_expected_statement);
222*67e74705SXin Li       return StmtError();
223*67e74705SXin Li     }
224*67e74705SXin Li 
225*67e74705SXin Li     return ParseExprStatement();
226*67e74705SXin Li   }
227*67e74705SXin Li 
228*67e74705SXin Li   case tok::kw_case:                // C99 6.8.1: labeled-statement
229*67e74705SXin Li     return ParseCaseStatement();
230*67e74705SXin Li   case tok::kw_default:             // C99 6.8.1: labeled-statement
231*67e74705SXin Li     return ParseDefaultStatement();
232*67e74705SXin Li 
233*67e74705SXin Li   case tok::l_brace:                // C99 6.8.2: compound-statement
234*67e74705SXin Li     return ParseCompoundStatement();
235*67e74705SXin Li   case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
236*67e74705SXin Li     bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
237*67e74705SXin Li     return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
238*67e74705SXin Li   }
239*67e74705SXin Li 
240*67e74705SXin Li   case tok::kw_if:                  // C99 6.8.4.1: if-statement
241*67e74705SXin Li     return ParseIfStatement(TrailingElseLoc);
242*67e74705SXin Li   case tok::kw_switch:              // C99 6.8.4.2: switch-statement
243*67e74705SXin Li     return ParseSwitchStatement(TrailingElseLoc);
244*67e74705SXin Li 
245*67e74705SXin Li   case tok::kw_while:               // C99 6.8.5.1: while-statement
246*67e74705SXin Li     return ParseWhileStatement(TrailingElseLoc);
247*67e74705SXin Li   case tok::kw_do:                  // C99 6.8.5.2: do-statement
248*67e74705SXin Li     Res = ParseDoStatement();
249*67e74705SXin Li     SemiError = "do/while";
250*67e74705SXin Li     break;
251*67e74705SXin Li   case tok::kw_for:                 // C99 6.8.5.3: for-statement
252*67e74705SXin Li     return ParseForStatement(TrailingElseLoc);
253*67e74705SXin Li 
254*67e74705SXin Li   case tok::kw_goto:                // C99 6.8.6.1: goto-statement
255*67e74705SXin Li     Res = ParseGotoStatement();
256*67e74705SXin Li     SemiError = "goto";
257*67e74705SXin Li     break;
258*67e74705SXin Li   case tok::kw_continue:            // C99 6.8.6.2: continue-statement
259*67e74705SXin Li     Res = ParseContinueStatement();
260*67e74705SXin Li     SemiError = "continue";
261*67e74705SXin Li     break;
262*67e74705SXin Li   case tok::kw_break:               // C99 6.8.6.3: break-statement
263*67e74705SXin Li     Res = ParseBreakStatement();
264*67e74705SXin Li     SemiError = "break";
265*67e74705SXin Li     break;
266*67e74705SXin Li   case tok::kw_return:              // C99 6.8.6.4: return-statement
267*67e74705SXin Li     Res = ParseReturnStatement();
268*67e74705SXin Li     SemiError = "return";
269*67e74705SXin Li     break;
270*67e74705SXin Li   case tok::kw_co_return:            // C++ Coroutines: co_return statement
271*67e74705SXin Li     Res = ParseReturnStatement();
272*67e74705SXin Li     SemiError = "co_return";
273*67e74705SXin Li     break;
274*67e74705SXin Li 
275*67e74705SXin Li   case tok::kw_asm: {
276*67e74705SXin Li     ProhibitAttributes(Attrs);
277*67e74705SXin Li     bool msAsm = false;
278*67e74705SXin Li     Res = ParseAsmStatement(msAsm);
279*67e74705SXin Li     Res = Actions.ActOnFinishFullStmt(Res.get());
280*67e74705SXin Li     if (msAsm) return Res;
281*67e74705SXin Li     SemiError = "asm";
282*67e74705SXin Li     break;
283*67e74705SXin Li   }
284*67e74705SXin Li 
285*67e74705SXin Li   case tok::kw___if_exists:
286*67e74705SXin Li   case tok::kw___if_not_exists:
287*67e74705SXin Li     ProhibitAttributes(Attrs);
288*67e74705SXin Li     ParseMicrosoftIfExistsStatement(Stmts);
289*67e74705SXin Li     // An __if_exists block is like a compound statement, but it doesn't create
290*67e74705SXin Li     // a new scope.
291*67e74705SXin Li     return StmtEmpty();
292*67e74705SXin Li 
293*67e74705SXin Li   case tok::kw_try:                 // C++ 15: try-block
294*67e74705SXin Li     return ParseCXXTryBlock();
295*67e74705SXin Li 
296*67e74705SXin Li   case tok::kw___try:
297*67e74705SXin Li     ProhibitAttributes(Attrs); // TODO: is it correct?
298*67e74705SXin Li     return ParseSEHTryBlock();
299*67e74705SXin Li 
300*67e74705SXin Li   case tok::kw___leave:
301*67e74705SXin Li     Res = ParseSEHLeaveStatement();
302*67e74705SXin Li     SemiError = "__leave";
303*67e74705SXin Li     break;
304*67e74705SXin Li 
305*67e74705SXin Li   case tok::annot_pragma_vis:
306*67e74705SXin Li     ProhibitAttributes(Attrs);
307*67e74705SXin Li     HandlePragmaVisibility();
308*67e74705SXin Li     return StmtEmpty();
309*67e74705SXin Li 
310*67e74705SXin Li   case tok::annot_pragma_pack:
311*67e74705SXin Li     ProhibitAttributes(Attrs);
312*67e74705SXin Li     HandlePragmaPack();
313*67e74705SXin Li     return StmtEmpty();
314*67e74705SXin Li 
315*67e74705SXin Li   case tok::annot_pragma_msstruct:
316*67e74705SXin Li     ProhibitAttributes(Attrs);
317*67e74705SXin Li     HandlePragmaMSStruct();
318*67e74705SXin Li     return StmtEmpty();
319*67e74705SXin Li 
320*67e74705SXin Li   case tok::annot_pragma_align:
321*67e74705SXin Li     ProhibitAttributes(Attrs);
322*67e74705SXin Li     HandlePragmaAlign();
323*67e74705SXin Li     return StmtEmpty();
324*67e74705SXin Li 
325*67e74705SXin Li   case tok::annot_pragma_weak:
326*67e74705SXin Li     ProhibitAttributes(Attrs);
327*67e74705SXin Li     HandlePragmaWeak();
328*67e74705SXin Li     return StmtEmpty();
329*67e74705SXin Li 
330*67e74705SXin Li   case tok::annot_pragma_weakalias:
331*67e74705SXin Li     ProhibitAttributes(Attrs);
332*67e74705SXin Li     HandlePragmaWeakAlias();
333*67e74705SXin Li     return StmtEmpty();
334*67e74705SXin Li 
335*67e74705SXin Li   case tok::annot_pragma_redefine_extname:
336*67e74705SXin Li     ProhibitAttributes(Attrs);
337*67e74705SXin Li     HandlePragmaRedefineExtname();
338*67e74705SXin Li     return StmtEmpty();
339*67e74705SXin Li 
340*67e74705SXin Li   case tok::annot_pragma_fp_contract:
341*67e74705SXin Li     ProhibitAttributes(Attrs);
342*67e74705SXin Li     Diag(Tok, diag::err_pragma_fp_contract_scope);
343*67e74705SXin Li     ConsumeToken();
344*67e74705SXin Li     return StmtError();
345*67e74705SXin Li 
346*67e74705SXin Li   case tok::annot_pragma_opencl_extension:
347*67e74705SXin Li     ProhibitAttributes(Attrs);
348*67e74705SXin Li     HandlePragmaOpenCLExtension();
349*67e74705SXin Li     return StmtEmpty();
350*67e74705SXin Li 
351*67e74705SXin Li   case tok::annot_pragma_captured:
352*67e74705SXin Li     ProhibitAttributes(Attrs);
353*67e74705SXin Li     return HandlePragmaCaptured();
354*67e74705SXin Li 
355*67e74705SXin Li   case tok::annot_pragma_openmp:
356*67e74705SXin Li     ProhibitAttributes(Attrs);
357*67e74705SXin Li     return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
358*67e74705SXin Li 
359*67e74705SXin Li   case tok::annot_pragma_ms_pointers_to_members:
360*67e74705SXin Li     ProhibitAttributes(Attrs);
361*67e74705SXin Li     HandlePragmaMSPointersToMembers();
362*67e74705SXin Li     return StmtEmpty();
363*67e74705SXin Li 
364*67e74705SXin Li   case tok::annot_pragma_ms_pragma:
365*67e74705SXin Li     ProhibitAttributes(Attrs);
366*67e74705SXin Li     HandlePragmaMSPragma();
367*67e74705SXin Li     return StmtEmpty();
368*67e74705SXin Li 
369*67e74705SXin Li   case tok::annot_pragma_ms_vtordisp:
370*67e74705SXin Li     ProhibitAttributes(Attrs);
371*67e74705SXin Li     HandlePragmaMSVtorDisp();
372*67e74705SXin Li     return StmtEmpty();
373*67e74705SXin Li 
374*67e74705SXin Li   case tok::annot_pragma_loop_hint:
375*67e74705SXin Li     ProhibitAttributes(Attrs);
376*67e74705SXin Li     return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
377*67e74705SXin Li 
378*67e74705SXin Li   case tok::annot_pragma_dump:
379*67e74705SXin Li     HandlePragmaDump();
380*67e74705SXin Li     return StmtEmpty();
381*67e74705SXin Li   }
382*67e74705SXin Li 
383*67e74705SXin Li   // If we reached this code, the statement must end in a semicolon.
384*67e74705SXin Li   if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
385*67e74705SXin Li     // If the result was valid, then we do want to diagnose this.  Use
386*67e74705SXin Li     // ExpectAndConsume to emit the diagnostic, even though we know it won't
387*67e74705SXin Li     // succeed.
388*67e74705SXin Li     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
389*67e74705SXin Li     // Skip until we see a } or ;, but don't eat it.
390*67e74705SXin Li     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
391*67e74705SXin Li   }
392*67e74705SXin Li 
393*67e74705SXin Li   return Res;
394*67e74705SXin Li }
395*67e74705SXin Li 
396*67e74705SXin Li /// \brief Parse an expression statement.
ParseExprStatement()397*67e74705SXin Li StmtResult Parser::ParseExprStatement() {
398*67e74705SXin Li   // If a case keyword is missing, this is where it should be inserted.
399*67e74705SXin Li   Token OldToken = Tok;
400*67e74705SXin Li 
401*67e74705SXin Li   // expression[opt] ';'
402*67e74705SXin Li   ExprResult Expr(ParseExpression());
403*67e74705SXin Li   if (Expr.isInvalid()) {
404*67e74705SXin Li     // If the expression is invalid, skip ahead to the next semicolon or '}'.
405*67e74705SXin Li     // Not doing this opens us up to the possibility of infinite loops if
406*67e74705SXin Li     // ParseExpression does not consume any tokens.
407*67e74705SXin Li     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
408*67e74705SXin Li     if (Tok.is(tok::semi))
409*67e74705SXin Li       ConsumeToken();
410*67e74705SXin Li     return Actions.ActOnExprStmtError();
411*67e74705SXin Li   }
412*67e74705SXin Li 
413*67e74705SXin Li   if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
414*67e74705SXin Li       Actions.CheckCaseExpression(Expr.get())) {
415*67e74705SXin Li     // If a constant expression is followed by a colon inside a switch block,
416*67e74705SXin Li     // suggest a missing case keyword.
417*67e74705SXin Li     Diag(OldToken, diag::err_expected_case_before_expression)
418*67e74705SXin Li       << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
419*67e74705SXin Li 
420*67e74705SXin Li     // Recover parsing as a case statement.
421*67e74705SXin Li     return ParseCaseStatement(/*MissingCase=*/true, Expr);
422*67e74705SXin Li   }
423*67e74705SXin Li 
424*67e74705SXin Li   // Otherwise, eat the semicolon.
425*67e74705SXin Li   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
426*67e74705SXin Li   return Actions.ActOnExprStmt(Expr);
427*67e74705SXin Li }
428*67e74705SXin Li 
429*67e74705SXin Li /// ParseSEHTryBlockCommon
430*67e74705SXin Li ///
431*67e74705SXin Li /// seh-try-block:
432*67e74705SXin Li ///   '__try' compound-statement seh-handler
433*67e74705SXin Li ///
434*67e74705SXin Li /// seh-handler:
435*67e74705SXin Li ///   seh-except-block
436*67e74705SXin Li ///   seh-finally-block
437*67e74705SXin Li ///
ParseSEHTryBlock()438*67e74705SXin Li StmtResult Parser::ParseSEHTryBlock() {
439*67e74705SXin Li   assert(Tok.is(tok::kw___try) && "Expected '__try'");
440*67e74705SXin Li   SourceLocation TryLoc = ConsumeToken();
441*67e74705SXin Li 
442*67e74705SXin Li   if (Tok.isNot(tok::l_brace))
443*67e74705SXin Li     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
444*67e74705SXin Li 
445*67e74705SXin Li   StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
446*67e74705SXin Li                       Scope::DeclScope | Scope::SEHTryScope));
447*67e74705SXin Li   if(TryBlock.isInvalid())
448*67e74705SXin Li     return TryBlock;
449*67e74705SXin Li 
450*67e74705SXin Li   StmtResult Handler;
451*67e74705SXin Li   if (Tok.is(tok::identifier) &&
452*67e74705SXin Li       Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
453*67e74705SXin Li     SourceLocation Loc = ConsumeToken();
454*67e74705SXin Li     Handler = ParseSEHExceptBlock(Loc);
455*67e74705SXin Li   } else if (Tok.is(tok::kw___finally)) {
456*67e74705SXin Li     SourceLocation Loc = ConsumeToken();
457*67e74705SXin Li     Handler = ParseSEHFinallyBlock(Loc);
458*67e74705SXin Li   } else {
459*67e74705SXin Li     return StmtError(Diag(Tok, diag::err_seh_expected_handler));
460*67e74705SXin Li   }
461*67e74705SXin Li 
462*67e74705SXin Li   if(Handler.isInvalid())
463*67e74705SXin Li     return Handler;
464*67e74705SXin Li 
465*67e74705SXin Li   return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
466*67e74705SXin Li                                   TryLoc,
467*67e74705SXin Li                                   TryBlock.get(),
468*67e74705SXin Li                                   Handler.get());
469*67e74705SXin Li }
470*67e74705SXin Li 
471*67e74705SXin Li /// ParseSEHExceptBlock - Handle __except
472*67e74705SXin Li ///
473*67e74705SXin Li /// seh-except-block:
474*67e74705SXin Li ///   '__except' '(' seh-filter-expression ')' compound-statement
475*67e74705SXin Li ///
ParseSEHExceptBlock(SourceLocation ExceptLoc)476*67e74705SXin Li StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
477*67e74705SXin Li   PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
478*67e74705SXin Li     raii2(Ident___exception_code, false),
479*67e74705SXin Li     raii3(Ident_GetExceptionCode, false);
480*67e74705SXin Li 
481*67e74705SXin Li   if (ExpectAndConsume(tok::l_paren))
482*67e74705SXin Li     return StmtError();
483*67e74705SXin Li 
484*67e74705SXin Li   ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
485*67e74705SXin Li                                    Scope::SEHExceptScope);
486*67e74705SXin Li 
487*67e74705SXin Li   if (getLangOpts().Borland) {
488*67e74705SXin Li     Ident__exception_info->setIsPoisoned(false);
489*67e74705SXin Li     Ident___exception_info->setIsPoisoned(false);
490*67e74705SXin Li     Ident_GetExceptionInfo->setIsPoisoned(false);
491*67e74705SXin Li   }
492*67e74705SXin Li 
493*67e74705SXin Li   ExprResult FilterExpr;
494*67e74705SXin Li   {
495*67e74705SXin Li     ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
496*67e74705SXin Li                                           Scope::SEHFilterScope);
497*67e74705SXin Li     FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
498*67e74705SXin Li   }
499*67e74705SXin Li 
500*67e74705SXin Li   if (getLangOpts().Borland) {
501*67e74705SXin Li     Ident__exception_info->setIsPoisoned(true);
502*67e74705SXin Li     Ident___exception_info->setIsPoisoned(true);
503*67e74705SXin Li     Ident_GetExceptionInfo->setIsPoisoned(true);
504*67e74705SXin Li   }
505*67e74705SXin Li 
506*67e74705SXin Li   if(FilterExpr.isInvalid())
507*67e74705SXin Li     return StmtError();
508*67e74705SXin Li 
509*67e74705SXin Li   if (ExpectAndConsume(tok::r_paren))
510*67e74705SXin Li     return StmtError();
511*67e74705SXin Li 
512*67e74705SXin Li   if (Tok.isNot(tok::l_brace))
513*67e74705SXin Li     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
514*67e74705SXin Li 
515*67e74705SXin Li   StmtResult Block(ParseCompoundStatement());
516*67e74705SXin Li 
517*67e74705SXin Li   if(Block.isInvalid())
518*67e74705SXin Li     return Block;
519*67e74705SXin Li 
520*67e74705SXin Li   return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
521*67e74705SXin Li }
522*67e74705SXin Li 
523*67e74705SXin Li /// ParseSEHFinallyBlock - Handle __finally
524*67e74705SXin Li ///
525*67e74705SXin Li /// seh-finally-block:
526*67e74705SXin Li ///   '__finally' compound-statement
527*67e74705SXin Li ///
ParseSEHFinallyBlock(SourceLocation FinallyLoc)528*67e74705SXin Li StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
529*67e74705SXin Li   PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
530*67e74705SXin Li     raii2(Ident___abnormal_termination, false),
531*67e74705SXin Li     raii3(Ident_AbnormalTermination, false);
532*67e74705SXin Li 
533*67e74705SXin Li   if (Tok.isNot(tok::l_brace))
534*67e74705SXin Li     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
535*67e74705SXin Li 
536*67e74705SXin Li   ParseScope FinallyScope(this, 0);
537*67e74705SXin Li   Actions.ActOnStartSEHFinallyBlock();
538*67e74705SXin Li 
539*67e74705SXin Li   StmtResult Block(ParseCompoundStatement());
540*67e74705SXin Li   if(Block.isInvalid()) {
541*67e74705SXin Li     Actions.ActOnAbortSEHFinallyBlock();
542*67e74705SXin Li     return Block;
543*67e74705SXin Li   }
544*67e74705SXin Li 
545*67e74705SXin Li   return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
546*67e74705SXin Li }
547*67e74705SXin Li 
548*67e74705SXin Li /// Handle __leave
549*67e74705SXin Li ///
550*67e74705SXin Li /// seh-leave-statement:
551*67e74705SXin Li ///   '__leave' ';'
552*67e74705SXin Li ///
ParseSEHLeaveStatement()553*67e74705SXin Li StmtResult Parser::ParseSEHLeaveStatement() {
554*67e74705SXin Li   SourceLocation LeaveLoc = ConsumeToken();  // eat the '__leave'.
555*67e74705SXin Li   return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
556*67e74705SXin Li }
557*67e74705SXin Li 
558*67e74705SXin Li /// ParseLabeledStatement - We have an identifier and a ':' after it.
559*67e74705SXin Li ///
560*67e74705SXin Li ///       labeled-statement:
561*67e74705SXin Li ///         identifier ':' statement
562*67e74705SXin Li /// [GNU]   identifier ':' attributes[opt] statement
563*67e74705SXin Li ///
ParseLabeledStatement(ParsedAttributesWithRange & attrs)564*67e74705SXin Li StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
565*67e74705SXin Li   assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
566*67e74705SXin Li          "Not an identifier!");
567*67e74705SXin Li 
568*67e74705SXin Li   Token IdentTok = Tok;  // Save the whole token.
569*67e74705SXin Li   ConsumeToken();  // eat the identifier.
570*67e74705SXin Li 
571*67e74705SXin Li   assert(Tok.is(tok::colon) && "Not a label!");
572*67e74705SXin Li 
573*67e74705SXin Li   // identifier ':' statement
574*67e74705SXin Li   SourceLocation ColonLoc = ConsumeToken();
575*67e74705SXin Li 
576*67e74705SXin Li   // Read label attributes, if present.
577*67e74705SXin Li   StmtResult SubStmt;
578*67e74705SXin Li   if (Tok.is(tok::kw___attribute)) {
579*67e74705SXin Li     ParsedAttributesWithRange TempAttrs(AttrFactory);
580*67e74705SXin Li     ParseGNUAttributes(TempAttrs);
581*67e74705SXin Li 
582*67e74705SXin Li     // In C++, GNU attributes only apply to the label if they are followed by a
583*67e74705SXin Li     // semicolon, to disambiguate label attributes from attributes on a labeled
584*67e74705SXin Li     // declaration.
585*67e74705SXin Li     //
586*67e74705SXin Li     // This doesn't quite match what GCC does; if the attribute list is empty
587*67e74705SXin Li     // and followed by a semicolon, GCC will reject (it appears to parse the
588*67e74705SXin Li     // attributes as part of a statement in that case). That looks like a bug.
589*67e74705SXin Li     if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
590*67e74705SXin Li       attrs.takeAllFrom(TempAttrs);
591*67e74705SXin Li     else if (isDeclarationStatement()) {
592*67e74705SXin Li       StmtVector Stmts;
593*67e74705SXin Li       // FIXME: We should do this whether or not we have a declaration
594*67e74705SXin Li       // statement, but that doesn't work correctly (because ProhibitAttributes
595*67e74705SXin Li       // can't handle GNU attributes), so only call it in the one case where
596*67e74705SXin Li       // GNU attributes are allowed.
597*67e74705SXin Li       SubStmt = ParseStatementOrDeclarationAfterAttributes(
598*67e74705SXin Li           Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
599*67e74705SXin Li           TempAttrs);
600*67e74705SXin Li       if (!TempAttrs.empty() && !SubStmt.isInvalid())
601*67e74705SXin Li         SubStmt = Actions.ProcessStmtAttributes(
602*67e74705SXin Li             SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
603*67e74705SXin Li     } else {
604*67e74705SXin Li       Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
605*67e74705SXin Li     }
606*67e74705SXin Li   }
607*67e74705SXin Li 
608*67e74705SXin Li   // If we've not parsed a statement yet, parse one now.
609*67e74705SXin Li   if (!SubStmt.isInvalid() && !SubStmt.isUsable())
610*67e74705SXin Li     SubStmt = ParseStatement();
611*67e74705SXin Li 
612*67e74705SXin Li   // Broken substmt shouldn't prevent the label from being added to the AST.
613*67e74705SXin Li   if (SubStmt.isInvalid())
614*67e74705SXin Li     SubStmt = Actions.ActOnNullStmt(ColonLoc);
615*67e74705SXin Li 
616*67e74705SXin Li   LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
617*67e74705SXin Li                                               IdentTok.getLocation());
618*67e74705SXin Li   if (AttributeList *Attrs = attrs.getList()) {
619*67e74705SXin Li     Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
620*67e74705SXin Li     attrs.clear();
621*67e74705SXin Li   }
622*67e74705SXin Li 
623*67e74705SXin Li   return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
624*67e74705SXin Li                                 SubStmt.get());
625*67e74705SXin Li }
626*67e74705SXin Li 
627*67e74705SXin Li /// ParseCaseStatement
628*67e74705SXin Li ///       labeled-statement:
629*67e74705SXin Li ///         'case' constant-expression ':' statement
630*67e74705SXin Li /// [GNU]   'case' constant-expression '...' constant-expression ':' statement
631*67e74705SXin Li ///
ParseCaseStatement(bool MissingCase,ExprResult Expr)632*67e74705SXin Li StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
633*67e74705SXin Li   assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
634*67e74705SXin Li 
635*67e74705SXin Li   // It is very very common for code to contain many case statements recursively
636*67e74705SXin Li   // nested, as in (but usually without indentation):
637*67e74705SXin Li   //  case 1:
638*67e74705SXin Li   //    case 2:
639*67e74705SXin Li   //      case 3:
640*67e74705SXin Li   //         case 4:
641*67e74705SXin Li   //           case 5: etc.
642*67e74705SXin Li   //
643*67e74705SXin Li   // Parsing this naively works, but is both inefficient and can cause us to run
644*67e74705SXin Li   // out of stack space in our recursive descent parser.  As a special case,
645*67e74705SXin Li   // flatten this recursion into an iterative loop.  This is complex and gross,
646*67e74705SXin Li   // but all the grossness is constrained to ParseCaseStatement (and some
647*67e74705SXin Li   // weirdness in the actions), so this is just local grossness :).
648*67e74705SXin Li 
649*67e74705SXin Li   // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
650*67e74705SXin Li   // example above.
651*67e74705SXin Li   StmtResult TopLevelCase(true);
652*67e74705SXin Li 
653*67e74705SXin Li   // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
654*67e74705SXin Li   // gets updated each time a new case is parsed, and whose body is unset so
655*67e74705SXin Li   // far.  When parsing 'case 4', this is the 'case 3' node.
656*67e74705SXin Li   Stmt *DeepestParsedCaseStmt = nullptr;
657*67e74705SXin Li 
658*67e74705SXin Li   // While we have case statements, eat and stack them.
659*67e74705SXin Li   SourceLocation ColonLoc;
660*67e74705SXin Li   do {
661*67e74705SXin Li     SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
662*67e74705SXin Li                                            ConsumeToken();  // eat the 'case'.
663*67e74705SXin Li     ColonLoc = SourceLocation();
664*67e74705SXin Li 
665*67e74705SXin Li     if (Tok.is(tok::code_completion)) {
666*67e74705SXin Li       Actions.CodeCompleteCase(getCurScope());
667*67e74705SXin Li       cutOffParsing();
668*67e74705SXin Li       return StmtError();
669*67e74705SXin Li     }
670*67e74705SXin Li 
671*67e74705SXin Li     /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
672*67e74705SXin Li     /// Disable this form of error recovery while we're parsing the case
673*67e74705SXin Li     /// expression.
674*67e74705SXin Li     ColonProtectionRAIIObject ColonProtection(*this);
675*67e74705SXin Li 
676*67e74705SXin Li     ExprResult LHS;
677*67e74705SXin Li     if (!MissingCase) {
678*67e74705SXin Li       LHS = ParseConstantExpression();
679*67e74705SXin Li       if (!getLangOpts().CPlusPlus11) {
680*67e74705SXin Li         LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
681*67e74705SXin Li           return Actions.VerifyIntegerConstantExpression(E);
682*67e74705SXin Li         });
683*67e74705SXin Li       }
684*67e74705SXin Li       if (LHS.isInvalid()) {
685*67e74705SXin Li         // If constant-expression is parsed unsuccessfully, recover by skipping
686*67e74705SXin Li         // current case statement (moving to the colon that ends it).
687*67e74705SXin Li         if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
688*67e74705SXin Li           TryConsumeToken(tok::colon, ColonLoc);
689*67e74705SXin Li           continue;
690*67e74705SXin Li         }
691*67e74705SXin Li         return StmtError();
692*67e74705SXin Li       }
693*67e74705SXin Li     } else {
694*67e74705SXin Li       LHS = Expr;
695*67e74705SXin Li       MissingCase = false;
696*67e74705SXin Li     }
697*67e74705SXin Li 
698*67e74705SXin Li     // GNU case range extension.
699*67e74705SXin Li     SourceLocation DotDotDotLoc;
700*67e74705SXin Li     ExprResult RHS;
701*67e74705SXin Li     if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
702*67e74705SXin Li       Diag(DotDotDotLoc, diag::ext_gnu_case_range);
703*67e74705SXin Li       RHS = ParseConstantExpression();
704*67e74705SXin Li       if (RHS.isInvalid()) {
705*67e74705SXin Li         if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
706*67e74705SXin Li           TryConsumeToken(tok::colon, ColonLoc);
707*67e74705SXin Li           continue;
708*67e74705SXin Li         }
709*67e74705SXin Li         return StmtError();
710*67e74705SXin Li       }
711*67e74705SXin Li     }
712*67e74705SXin Li 
713*67e74705SXin Li     ColonProtection.restore();
714*67e74705SXin Li 
715*67e74705SXin Li     if (TryConsumeToken(tok::colon, ColonLoc)) {
716*67e74705SXin Li     } else if (TryConsumeToken(tok::semi, ColonLoc) ||
717*67e74705SXin Li                TryConsumeToken(tok::coloncolon, ColonLoc)) {
718*67e74705SXin Li       // Treat "case blah;" or "case blah::" as a typo for "case blah:".
719*67e74705SXin Li       Diag(ColonLoc, diag::err_expected_after)
720*67e74705SXin Li           << "'case'" << tok::colon
721*67e74705SXin Li           << FixItHint::CreateReplacement(ColonLoc, ":");
722*67e74705SXin Li     } else {
723*67e74705SXin Li       SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
724*67e74705SXin Li       Diag(ExpectedLoc, diag::err_expected_after)
725*67e74705SXin Li           << "'case'" << tok::colon
726*67e74705SXin Li           << FixItHint::CreateInsertion(ExpectedLoc, ":");
727*67e74705SXin Li       ColonLoc = ExpectedLoc;
728*67e74705SXin Li     }
729*67e74705SXin Li 
730*67e74705SXin Li     StmtResult Case =
731*67e74705SXin Li       Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
732*67e74705SXin Li                             RHS.get(), ColonLoc);
733*67e74705SXin Li 
734*67e74705SXin Li     // If we had a sema error parsing this case, then just ignore it and
735*67e74705SXin Li     // continue parsing the sub-stmt.
736*67e74705SXin Li     if (Case.isInvalid()) {
737*67e74705SXin Li       if (TopLevelCase.isInvalid())  // No parsed case stmts.
738*67e74705SXin Li         return ParseStatement(/*TrailingElseLoc=*/nullptr,
739*67e74705SXin Li                               /*AllowOpenMPStandalone=*/true);
740*67e74705SXin Li       // Otherwise, just don't add it as a nested case.
741*67e74705SXin Li     } else {
742*67e74705SXin Li       // If this is the first case statement we parsed, it becomes TopLevelCase.
743*67e74705SXin Li       // Otherwise we link it into the current chain.
744*67e74705SXin Li       Stmt *NextDeepest = Case.get();
745*67e74705SXin Li       if (TopLevelCase.isInvalid())
746*67e74705SXin Li         TopLevelCase = Case;
747*67e74705SXin Li       else
748*67e74705SXin Li         Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
749*67e74705SXin Li       DeepestParsedCaseStmt = NextDeepest;
750*67e74705SXin Li     }
751*67e74705SXin Li 
752*67e74705SXin Li     // Handle all case statements.
753*67e74705SXin Li   } while (Tok.is(tok::kw_case));
754*67e74705SXin Li 
755*67e74705SXin Li   // If we found a non-case statement, start by parsing it.
756*67e74705SXin Li   StmtResult SubStmt;
757*67e74705SXin Li 
758*67e74705SXin Li   if (Tok.isNot(tok::r_brace)) {
759*67e74705SXin Li     SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
760*67e74705SXin Li                              /*AllowOpenMPStandalone=*/true);
761*67e74705SXin Li   } else {
762*67e74705SXin Li     // Nicely diagnose the common error "switch (X) { case 4: }", which is
763*67e74705SXin Li     // not valid.  If ColonLoc doesn't point to a valid text location, there was
764*67e74705SXin Li     // another parsing error, so avoid producing extra diagnostics.
765*67e74705SXin Li     if (ColonLoc.isValid()) {
766*67e74705SXin Li       SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
767*67e74705SXin Li       Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
768*67e74705SXin Li         << FixItHint::CreateInsertion(AfterColonLoc, " ;");
769*67e74705SXin Li     }
770*67e74705SXin Li     SubStmt = StmtError();
771*67e74705SXin Li   }
772*67e74705SXin Li 
773*67e74705SXin Li   // Install the body into the most deeply-nested case.
774*67e74705SXin Li   if (DeepestParsedCaseStmt) {
775*67e74705SXin Li     // Broken sub-stmt shouldn't prevent forming the case statement properly.
776*67e74705SXin Li     if (SubStmt.isInvalid())
777*67e74705SXin Li       SubStmt = Actions.ActOnNullStmt(SourceLocation());
778*67e74705SXin Li     Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
779*67e74705SXin Li   }
780*67e74705SXin Li 
781*67e74705SXin Li   // Return the top level parsed statement tree.
782*67e74705SXin Li   return TopLevelCase;
783*67e74705SXin Li }
784*67e74705SXin Li 
785*67e74705SXin Li /// ParseDefaultStatement
786*67e74705SXin Li ///       labeled-statement:
787*67e74705SXin Li ///         'default' ':' statement
788*67e74705SXin Li /// Note that this does not parse the 'statement' at the end.
789*67e74705SXin Li ///
ParseDefaultStatement()790*67e74705SXin Li StmtResult Parser::ParseDefaultStatement() {
791*67e74705SXin Li   assert(Tok.is(tok::kw_default) && "Not a default stmt!");
792*67e74705SXin Li   SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
793*67e74705SXin Li 
794*67e74705SXin Li   SourceLocation ColonLoc;
795*67e74705SXin Li   if (TryConsumeToken(tok::colon, ColonLoc)) {
796*67e74705SXin Li   } else if (TryConsumeToken(tok::semi, ColonLoc)) {
797*67e74705SXin Li     // Treat "default;" as a typo for "default:".
798*67e74705SXin Li     Diag(ColonLoc, diag::err_expected_after)
799*67e74705SXin Li         << "'default'" << tok::colon
800*67e74705SXin Li         << FixItHint::CreateReplacement(ColonLoc, ":");
801*67e74705SXin Li   } else {
802*67e74705SXin Li     SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
803*67e74705SXin Li     Diag(ExpectedLoc, diag::err_expected_after)
804*67e74705SXin Li         << "'default'" << tok::colon
805*67e74705SXin Li         << FixItHint::CreateInsertion(ExpectedLoc, ":");
806*67e74705SXin Li     ColonLoc = ExpectedLoc;
807*67e74705SXin Li   }
808*67e74705SXin Li 
809*67e74705SXin Li   StmtResult SubStmt;
810*67e74705SXin Li 
811*67e74705SXin Li   if (Tok.isNot(tok::r_brace)) {
812*67e74705SXin Li     SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
813*67e74705SXin Li                              /*AllowOpenMPStandalone=*/true);
814*67e74705SXin Li   } else {
815*67e74705SXin Li     // Diagnose the common error "switch (X) {... default: }", which is
816*67e74705SXin Li     // not valid.
817*67e74705SXin Li     SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
818*67e74705SXin Li     Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
819*67e74705SXin Li       << FixItHint::CreateInsertion(AfterColonLoc, " ;");
820*67e74705SXin Li     SubStmt = true;
821*67e74705SXin Li   }
822*67e74705SXin Li 
823*67e74705SXin Li   // Broken sub-stmt shouldn't prevent forming the case statement properly.
824*67e74705SXin Li   if (SubStmt.isInvalid())
825*67e74705SXin Li     SubStmt = Actions.ActOnNullStmt(ColonLoc);
826*67e74705SXin Li 
827*67e74705SXin Li   return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
828*67e74705SXin Li                                   SubStmt.get(), getCurScope());
829*67e74705SXin Li }
830*67e74705SXin Li 
ParseCompoundStatement(bool isStmtExpr)831*67e74705SXin Li StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
832*67e74705SXin Li   return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
833*67e74705SXin Li }
834*67e74705SXin Li 
835*67e74705SXin Li /// ParseCompoundStatement - Parse a "{}" block.
836*67e74705SXin Li ///
837*67e74705SXin Li ///       compound-statement: [C99 6.8.2]
838*67e74705SXin Li ///         { block-item-list[opt] }
839*67e74705SXin Li /// [GNU]   { label-declarations block-item-list } [TODO]
840*67e74705SXin Li ///
841*67e74705SXin Li ///       block-item-list:
842*67e74705SXin Li ///         block-item
843*67e74705SXin Li ///         block-item-list block-item
844*67e74705SXin Li ///
845*67e74705SXin Li ///       block-item:
846*67e74705SXin Li ///         declaration
847*67e74705SXin Li /// [GNU]   '__extension__' declaration
848*67e74705SXin Li ///         statement
849*67e74705SXin Li ///
850*67e74705SXin Li /// [GNU] label-declarations:
851*67e74705SXin Li /// [GNU]   label-declaration
852*67e74705SXin Li /// [GNU]   label-declarations label-declaration
853*67e74705SXin Li ///
854*67e74705SXin Li /// [GNU] label-declaration:
855*67e74705SXin Li /// [GNU]   '__label__' identifier-list ';'
856*67e74705SXin Li ///
ParseCompoundStatement(bool isStmtExpr,unsigned ScopeFlags)857*67e74705SXin Li StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
858*67e74705SXin Li                                           unsigned ScopeFlags) {
859*67e74705SXin Li   assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
860*67e74705SXin Li 
861*67e74705SXin Li   // Enter a scope to hold everything within the compound stmt.  Compound
862*67e74705SXin Li   // statements can always hold declarations.
863*67e74705SXin Li   ParseScope CompoundScope(this, ScopeFlags);
864*67e74705SXin Li 
865*67e74705SXin Li   // Parse the statements in the body.
866*67e74705SXin Li   return ParseCompoundStatementBody(isStmtExpr);
867*67e74705SXin Li }
868*67e74705SXin Li 
869*67e74705SXin Li /// Parse any pragmas at the start of the compound expression. We handle these
870*67e74705SXin Li /// separately since some pragmas (FP_CONTRACT) must appear before any C
871*67e74705SXin Li /// statement in the compound, but may be intermingled with other pragmas.
ParseCompoundStatementLeadingPragmas()872*67e74705SXin Li void Parser::ParseCompoundStatementLeadingPragmas() {
873*67e74705SXin Li   bool checkForPragmas = true;
874*67e74705SXin Li   while (checkForPragmas) {
875*67e74705SXin Li     switch (Tok.getKind()) {
876*67e74705SXin Li     case tok::annot_pragma_vis:
877*67e74705SXin Li       HandlePragmaVisibility();
878*67e74705SXin Li       break;
879*67e74705SXin Li     case tok::annot_pragma_pack:
880*67e74705SXin Li       HandlePragmaPack();
881*67e74705SXin Li       break;
882*67e74705SXin Li     case tok::annot_pragma_msstruct:
883*67e74705SXin Li       HandlePragmaMSStruct();
884*67e74705SXin Li       break;
885*67e74705SXin Li     case tok::annot_pragma_align:
886*67e74705SXin Li       HandlePragmaAlign();
887*67e74705SXin Li       break;
888*67e74705SXin Li     case tok::annot_pragma_weak:
889*67e74705SXin Li       HandlePragmaWeak();
890*67e74705SXin Li       break;
891*67e74705SXin Li     case tok::annot_pragma_weakalias:
892*67e74705SXin Li       HandlePragmaWeakAlias();
893*67e74705SXin Li       break;
894*67e74705SXin Li     case tok::annot_pragma_redefine_extname:
895*67e74705SXin Li       HandlePragmaRedefineExtname();
896*67e74705SXin Li       break;
897*67e74705SXin Li     case tok::annot_pragma_opencl_extension:
898*67e74705SXin Li       HandlePragmaOpenCLExtension();
899*67e74705SXin Li       break;
900*67e74705SXin Li     case tok::annot_pragma_fp_contract:
901*67e74705SXin Li       HandlePragmaFPContract();
902*67e74705SXin Li       break;
903*67e74705SXin Li     case tok::annot_pragma_ms_pointers_to_members:
904*67e74705SXin Li       HandlePragmaMSPointersToMembers();
905*67e74705SXin Li       break;
906*67e74705SXin Li     case tok::annot_pragma_ms_pragma:
907*67e74705SXin Li       HandlePragmaMSPragma();
908*67e74705SXin Li       break;
909*67e74705SXin Li     case tok::annot_pragma_ms_vtordisp:
910*67e74705SXin Li       HandlePragmaMSVtorDisp();
911*67e74705SXin Li       break;
912*67e74705SXin Li     case tok::annot_pragma_dump:
913*67e74705SXin Li       HandlePragmaDump();
914*67e74705SXin Li       break;
915*67e74705SXin Li     default:
916*67e74705SXin Li       checkForPragmas = false;
917*67e74705SXin Li       break;
918*67e74705SXin Li     }
919*67e74705SXin Li   }
920*67e74705SXin Li 
921*67e74705SXin Li }
922*67e74705SXin Li 
923*67e74705SXin Li /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
924*67e74705SXin Li /// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
925*67e74705SXin Li /// consume the '}' at the end of the block.  It does not manipulate the scope
926*67e74705SXin Li /// stack.
ParseCompoundStatementBody(bool isStmtExpr)927*67e74705SXin Li StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
928*67e74705SXin Li   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
929*67e74705SXin Li                                 Tok.getLocation(),
930*67e74705SXin Li                                 "in compound statement ('{}')");
931*67e74705SXin Li 
932*67e74705SXin Li   // Record the state of the FP_CONTRACT pragma, restore on leaving the
933*67e74705SXin Li   // compound statement.
934*67e74705SXin Li   Sema::FPContractStateRAII SaveFPContractState(Actions);
935*67e74705SXin Li 
936*67e74705SXin Li   InMessageExpressionRAIIObject InMessage(*this, false);
937*67e74705SXin Li   BalancedDelimiterTracker T(*this, tok::l_brace);
938*67e74705SXin Li   if (T.consumeOpen())
939*67e74705SXin Li     return StmtError();
940*67e74705SXin Li 
941*67e74705SXin Li   Sema::CompoundScopeRAII CompoundScope(Actions);
942*67e74705SXin Li 
943*67e74705SXin Li   // Parse any pragmas at the beginning of the compound statement.
944*67e74705SXin Li   ParseCompoundStatementLeadingPragmas();
945*67e74705SXin Li 
946*67e74705SXin Li   StmtVector Stmts;
947*67e74705SXin Li 
948*67e74705SXin Li   // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
949*67e74705SXin Li   // only allowed at the start of a compound stmt regardless of the language.
950*67e74705SXin Li   while (Tok.is(tok::kw___label__)) {
951*67e74705SXin Li     SourceLocation LabelLoc = ConsumeToken();
952*67e74705SXin Li 
953*67e74705SXin Li     SmallVector<Decl *, 8> DeclsInGroup;
954*67e74705SXin Li     while (1) {
955*67e74705SXin Li       if (Tok.isNot(tok::identifier)) {
956*67e74705SXin Li         Diag(Tok, diag::err_expected) << tok::identifier;
957*67e74705SXin Li         break;
958*67e74705SXin Li       }
959*67e74705SXin Li 
960*67e74705SXin Li       IdentifierInfo *II = Tok.getIdentifierInfo();
961*67e74705SXin Li       SourceLocation IdLoc = ConsumeToken();
962*67e74705SXin Li       DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
963*67e74705SXin Li 
964*67e74705SXin Li       if (!TryConsumeToken(tok::comma))
965*67e74705SXin Li         break;
966*67e74705SXin Li     }
967*67e74705SXin Li 
968*67e74705SXin Li     DeclSpec DS(AttrFactory);
969*67e74705SXin Li     DeclGroupPtrTy Res =
970*67e74705SXin Li         Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
971*67e74705SXin Li     StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
972*67e74705SXin Li 
973*67e74705SXin Li     ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
974*67e74705SXin Li     if (R.isUsable())
975*67e74705SXin Li       Stmts.push_back(R.get());
976*67e74705SXin Li   }
977*67e74705SXin Li 
978*67e74705SXin Li   while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
979*67e74705SXin Li          Tok.isNot(tok::eof)) {
980*67e74705SXin Li     if (Tok.is(tok::annot_pragma_unused)) {
981*67e74705SXin Li       HandlePragmaUnused();
982*67e74705SXin Li       continue;
983*67e74705SXin Li     }
984*67e74705SXin Li 
985*67e74705SXin Li     StmtResult R;
986*67e74705SXin Li     if (Tok.isNot(tok::kw___extension__)) {
987*67e74705SXin Li       R = ParseStatementOrDeclaration(Stmts, ACK_Any);
988*67e74705SXin Li     } else {
989*67e74705SXin Li       // __extension__ can start declarations and it can also be a unary
990*67e74705SXin Li       // operator for expressions.  Consume multiple __extension__ markers here
991*67e74705SXin Li       // until we can determine which is which.
992*67e74705SXin Li       // FIXME: This loses extension expressions in the AST!
993*67e74705SXin Li       SourceLocation ExtLoc = ConsumeToken();
994*67e74705SXin Li       while (Tok.is(tok::kw___extension__))
995*67e74705SXin Li         ConsumeToken();
996*67e74705SXin Li 
997*67e74705SXin Li       ParsedAttributesWithRange attrs(AttrFactory);
998*67e74705SXin Li       MaybeParseCXX11Attributes(attrs, nullptr,
999*67e74705SXin Li                                 /*MightBeObjCMessageSend*/ true);
1000*67e74705SXin Li 
1001*67e74705SXin Li       // If this is the start of a declaration, parse it as such.
1002*67e74705SXin Li       if (isDeclarationStatement()) {
1003*67e74705SXin Li         // __extension__ silences extension warnings in the subdeclaration.
1004*67e74705SXin Li         // FIXME: Save the __extension__ on the decl as a node somehow?
1005*67e74705SXin Li         ExtensionRAIIObject O(Diags);
1006*67e74705SXin Li 
1007*67e74705SXin Li         SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1008*67e74705SXin Li         DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
1009*67e74705SXin Li                                               attrs);
1010*67e74705SXin Li         R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1011*67e74705SXin Li       } else {
1012*67e74705SXin Li         // Otherwise this was a unary __extension__ marker.
1013*67e74705SXin Li         ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1014*67e74705SXin Li 
1015*67e74705SXin Li         if (Res.isInvalid()) {
1016*67e74705SXin Li           SkipUntil(tok::semi);
1017*67e74705SXin Li           continue;
1018*67e74705SXin Li         }
1019*67e74705SXin Li 
1020*67e74705SXin Li         // FIXME: Use attributes?
1021*67e74705SXin Li         // Eat the semicolon at the end of stmt and convert the expr into a
1022*67e74705SXin Li         // statement.
1023*67e74705SXin Li         ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1024*67e74705SXin Li         R = Actions.ActOnExprStmt(Res);
1025*67e74705SXin Li       }
1026*67e74705SXin Li     }
1027*67e74705SXin Li 
1028*67e74705SXin Li     if (R.isUsable())
1029*67e74705SXin Li       Stmts.push_back(R.get());
1030*67e74705SXin Li   }
1031*67e74705SXin Li 
1032*67e74705SXin Li   SourceLocation CloseLoc = Tok.getLocation();
1033*67e74705SXin Li 
1034*67e74705SXin Li   // We broke out of the while loop because we found a '}' or EOF.
1035*67e74705SXin Li   if (!T.consumeClose())
1036*67e74705SXin Li     // Recover by creating a compound statement with what we parsed so far,
1037*67e74705SXin Li     // instead of dropping everything and returning StmtError();
1038*67e74705SXin Li     CloseLoc = T.getCloseLocation();
1039*67e74705SXin Li 
1040*67e74705SXin Li   return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1041*67e74705SXin Li                                    Stmts, isStmtExpr);
1042*67e74705SXin Li }
1043*67e74705SXin Li 
1044*67e74705SXin Li /// ParseParenExprOrCondition:
1045*67e74705SXin Li /// [C  ]     '(' expression ')'
1046*67e74705SXin Li /// [C++]     '(' condition ')'
1047*67e74705SXin Li /// [C++1z]   '(' init-statement[opt] condition ')'
1048*67e74705SXin Li ///
1049*67e74705SXin Li /// This function parses and performs error recovery on the specified condition
1050*67e74705SXin Li /// or expression (depending on whether we're in C++ or C mode).  This function
1051*67e74705SXin Li /// goes out of its way to recover well.  It returns true if there was a parser
1052*67e74705SXin Li /// error (the right paren couldn't be found), which indicates that the caller
1053*67e74705SXin Li /// should try to recover harder.  It returns false if the condition is
1054*67e74705SXin Li /// successfully parsed.  Note that a successful parse can still have semantic
1055*67e74705SXin Li /// errors in the condition.
ParseParenExprOrCondition(StmtResult * InitStmt,Sema::ConditionResult & Cond,SourceLocation Loc,Sema::ConditionKind CK)1056*67e74705SXin Li bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1057*67e74705SXin Li                                        Sema::ConditionResult &Cond,
1058*67e74705SXin Li                                        SourceLocation Loc,
1059*67e74705SXin Li                                        Sema::ConditionKind CK) {
1060*67e74705SXin Li   BalancedDelimiterTracker T(*this, tok::l_paren);
1061*67e74705SXin Li   T.consumeOpen();
1062*67e74705SXin Li 
1063*67e74705SXin Li   if (getLangOpts().CPlusPlus)
1064*67e74705SXin Li     Cond = ParseCXXCondition(InitStmt, Loc, CK);
1065*67e74705SXin Li   else {
1066*67e74705SXin Li     ExprResult CondExpr = ParseExpression();
1067*67e74705SXin Li 
1068*67e74705SXin Li     // If required, convert to a boolean value.
1069*67e74705SXin Li     if (CondExpr.isInvalid())
1070*67e74705SXin Li       Cond = Sema::ConditionError();
1071*67e74705SXin Li     else
1072*67e74705SXin Li       Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1073*67e74705SXin Li   }
1074*67e74705SXin Li 
1075*67e74705SXin Li   // If the parser was confused by the condition and we don't have a ')', try to
1076*67e74705SXin Li   // recover by skipping ahead to a semi and bailing out.  If condexp is
1077*67e74705SXin Li   // semantically invalid but we have well formed code, keep going.
1078*67e74705SXin Li   if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1079*67e74705SXin Li     SkipUntil(tok::semi);
1080*67e74705SXin Li     // Skipping may have stopped if it found the containing ')'.  If so, we can
1081*67e74705SXin Li     // continue parsing the if statement.
1082*67e74705SXin Li     if (Tok.isNot(tok::r_paren))
1083*67e74705SXin Li       return true;
1084*67e74705SXin Li   }
1085*67e74705SXin Li 
1086*67e74705SXin Li   // Otherwise the condition is valid or the rparen is present.
1087*67e74705SXin Li   T.consumeClose();
1088*67e74705SXin Li 
1089*67e74705SXin Li   // Check for extraneous ')'s to catch things like "if (foo())) {".  We know
1090*67e74705SXin Li   // that all callers are looking for a statement after the condition, so ")"
1091*67e74705SXin Li   // isn't valid.
1092*67e74705SXin Li   while (Tok.is(tok::r_paren)) {
1093*67e74705SXin Li     Diag(Tok, diag::err_extraneous_rparen_in_condition)
1094*67e74705SXin Li       << FixItHint::CreateRemoval(Tok.getLocation());
1095*67e74705SXin Li     ConsumeParen();
1096*67e74705SXin Li   }
1097*67e74705SXin Li 
1098*67e74705SXin Li   return false;
1099*67e74705SXin Li }
1100*67e74705SXin Li 
1101*67e74705SXin Li 
1102*67e74705SXin Li /// ParseIfStatement
1103*67e74705SXin Li ///       if-statement: [C99 6.8.4.1]
1104*67e74705SXin Li ///         'if' '(' expression ')' statement
1105*67e74705SXin Li ///         'if' '(' expression ')' statement 'else' statement
1106*67e74705SXin Li /// [C++]   'if' '(' condition ')' statement
1107*67e74705SXin Li /// [C++]   'if' '(' condition ')' statement 'else' statement
1108*67e74705SXin Li ///
ParseIfStatement(SourceLocation * TrailingElseLoc)1109*67e74705SXin Li StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1110*67e74705SXin Li   assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1111*67e74705SXin Li   SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
1112*67e74705SXin Li 
1113*67e74705SXin Li   bool IsConstexpr = false;
1114*67e74705SXin Li   if (Tok.is(tok::kw_constexpr)) {
1115*67e74705SXin Li     Diag(Tok, getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_constexpr_if
1116*67e74705SXin Li                                         : diag::ext_constexpr_if);
1117*67e74705SXin Li     IsConstexpr = true;
1118*67e74705SXin Li     ConsumeToken();
1119*67e74705SXin Li   }
1120*67e74705SXin Li 
1121*67e74705SXin Li   if (Tok.isNot(tok::l_paren)) {
1122*67e74705SXin Li     Diag(Tok, diag::err_expected_lparen_after) << "if";
1123*67e74705SXin Li     SkipUntil(tok::semi);
1124*67e74705SXin Li     return StmtError();
1125*67e74705SXin Li   }
1126*67e74705SXin Li 
1127*67e74705SXin Li   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1128*67e74705SXin Li 
1129*67e74705SXin Li   // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
1130*67e74705SXin Li   // the case for C90.
1131*67e74705SXin Li   //
1132*67e74705SXin Li   // C++ 6.4p3:
1133*67e74705SXin Li   // A name introduced by a declaration in a condition is in scope from its
1134*67e74705SXin Li   // point of declaration until the end of the substatements controlled by the
1135*67e74705SXin Li   // condition.
1136*67e74705SXin Li   // C++ 3.3.2p4:
1137*67e74705SXin Li   // Names declared in the for-init-statement, and in the condition of if,
1138*67e74705SXin Li   // while, for, and switch statements are local to the if, while, for, or
1139*67e74705SXin Li   // switch statement (including the controlled statement).
1140*67e74705SXin Li   //
1141*67e74705SXin Li   ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1142*67e74705SXin Li 
1143*67e74705SXin Li   // Parse the condition.
1144*67e74705SXin Li   StmtResult InitStmt;
1145*67e74705SXin Li   Sema::ConditionResult Cond;
1146*67e74705SXin Li   if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1147*67e74705SXin Li                                 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1148*67e74705SXin Li                                             : Sema::ConditionKind::Boolean))
1149*67e74705SXin Li     return StmtError();
1150*67e74705SXin Li 
1151*67e74705SXin Li   llvm::Optional<bool> ConstexprCondition;
1152*67e74705SXin Li   if (IsConstexpr)
1153*67e74705SXin Li     ConstexprCondition = Cond.getKnownValue();
1154*67e74705SXin Li 
1155*67e74705SXin Li   // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1156*67e74705SXin Li   // there is no compound stmt.  C90 does not have this clause.  We only do this
1157*67e74705SXin Li   // if the body isn't a compound statement to avoid push/pop in common cases.
1158*67e74705SXin Li   //
1159*67e74705SXin Li   // C++ 6.4p1:
1160*67e74705SXin Li   // The substatement in a selection-statement (each substatement, in the else
1161*67e74705SXin Li   // form of the if statement) implicitly defines a local scope.
1162*67e74705SXin Li   //
1163*67e74705SXin Li   // For C++ we create a scope for the condition and a new scope for
1164*67e74705SXin Li   // substatements because:
1165*67e74705SXin Li   // -When the 'then' scope exits, we want the condition declaration to still be
1166*67e74705SXin Li   //    active for the 'else' scope too.
1167*67e74705SXin Li   // -Sema will detect name clashes by considering declarations of a
1168*67e74705SXin Li   //    'ControlScope' as part of its direct subscope.
1169*67e74705SXin Li   // -If we wanted the condition and substatement to be in the same scope, we
1170*67e74705SXin Li   //    would have to notify ParseStatement not to create a new scope. It's
1171*67e74705SXin Li   //    simpler to let it create a new scope.
1172*67e74705SXin Li   //
1173*67e74705SXin Li   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1174*67e74705SXin Li 
1175*67e74705SXin Li   // Read the 'then' stmt.
1176*67e74705SXin Li   SourceLocation ThenStmtLoc = Tok.getLocation();
1177*67e74705SXin Li 
1178*67e74705SXin Li   SourceLocation InnerStatementTrailingElseLoc;
1179*67e74705SXin Li   StmtResult ThenStmt;
1180*67e74705SXin Li   {
1181*67e74705SXin Li     EnterExpressionEvaluationContext PotentiallyDiscarded(
1182*67e74705SXin Li         Actions, Sema::DiscardedStatement, nullptr, false,
1183*67e74705SXin Li         /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1184*67e74705SXin Li     ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1185*67e74705SXin Li   }
1186*67e74705SXin Li 
1187*67e74705SXin Li   // Pop the 'if' scope if needed.
1188*67e74705SXin Li   InnerScope.Exit();
1189*67e74705SXin Li 
1190*67e74705SXin Li   // If it has an else, parse it.
1191*67e74705SXin Li   SourceLocation ElseLoc;
1192*67e74705SXin Li   SourceLocation ElseStmtLoc;
1193*67e74705SXin Li   StmtResult ElseStmt;
1194*67e74705SXin Li 
1195*67e74705SXin Li   if (Tok.is(tok::kw_else)) {
1196*67e74705SXin Li     if (TrailingElseLoc)
1197*67e74705SXin Li       *TrailingElseLoc = Tok.getLocation();
1198*67e74705SXin Li 
1199*67e74705SXin Li     ElseLoc = ConsumeToken();
1200*67e74705SXin Li     ElseStmtLoc = Tok.getLocation();
1201*67e74705SXin Li 
1202*67e74705SXin Li     // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1203*67e74705SXin Li     // there is no compound stmt.  C90 does not have this clause.  We only do
1204*67e74705SXin Li     // this if the body isn't a compound statement to avoid push/pop in common
1205*67e74705SXin Li     // cases.
1206*67e74705SXin Li     //
1207*67e74705SXin Li     // C++ 6.4p1:
1208*67e74705SXin Li     // The substatement in a selection-statement (each substatement, in the else
1209*67e74705SXin Li     // form of the if statement) implicitly defines a local scope.
1210*67e74705SXin Li     //
1211*67e74705SXin Li     ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1212*67e74705SXin Li                           Tok.is(tok::l_brace));
1213*67e74705SXin Li 
1214*67e74705SXin Li     EnterExpressionEvaluationContext PotentiallyDiscarded(
1215*67e74705SXin Li         Actions, Sema::DiscardedStatement, nullptr, false,
1216*67e74705SXin Li         /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1217*67e74705SXin Li     ElseStmt = ParseStatement();
1218*67e74705SXin Li 
1219*67e74705SXin Li     // Pop the 'else' scope if needed.
1220*67e74705SXin Li     InnerScope.Exit();
1221*67e74705SXin Li   } else if (Tok.is(tok::code_completion)) {
1222*67e74705SXin Li     Actions.CodeCompleteAfterIf(getCurScope());
1223*67e74705SXin Li     cutOffParsing();
1224*67e74705SXin Li     return StmtError();
1225*67e74705SXin Li   } else if (InnerStatementTrailingElseLoc.isValid()) {
1226*67e74705SXin Li     Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1227*67e74705SXin Li   }
1228*67e74705SXin Li 
1229*67e74705SXin Li   IfScope.Exit();
1230*67e74705SXin Li 
1231*67e74705SXin Li   // If the then or else stmt is invalid and the other is valid (and present),
1232*67e74705SXin Li   // make turn the invalid one into a null stmt to avoid dropping the other
1233*67e74705SXin Li   // part.  If both are invalid, return error.
1234*67e74705SXin Li   if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1235*67e74705SXin Li       (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1236*67e74705SXin Li       (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1237*67e74705SXin Li     // Both invalid, or one is invalid and other is non-present: return error.
1238*67e74705SXin Li     return StmtError();
1239*67e74705SXin Li   }
1240*67e74705SXin Li 
1241*67e74705SXin Li   // Now if either are invalid, replace with a ';'.
1242*67e74705SXin Li   if (ThenStmt.isInvalid())
1243*67e74705SXin Li     ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1244*67e74705SXin Li   if (ElseStmt.isInvalid())
1245*67e74705SXin Li     ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1246*67e74705SXin Li 
1247*67e74705SXin Li   return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1248*67e74705SXin Li                              ThenStmt.get(), ElseLoc, ElseStmt.get());
1249*67e74705SXin Li }
1250*67e74705SXin Li 
1251*67e74705SXin Li /// ParseSwitchStatement
1252*67e74705SXin Li ///       switch-statement:
1253*67e74705SXin Li ///         'switch' '(' expression ')' statement
1254*67e74705SXin Li /// [C++]   'switch' '(' condition ')' statement
ParseSwitchStatement(SourceLocation * TrailingElseLoc)1255*67e74705SXin Li StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1256*67e74705SXin Li   assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1257*67e74705SXin Li   SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
1258*67e74705SXin Li 
1259*67e74705SXin Li   if (Tok.isNot(tok::l_paren)) {
1260*67e74705SXin Li     Diag(Tok, diag::err_expected_lparen_after) << "switch";
1261*67e74705SXin Li     SkipUntil(tok::semi);
1262*67e74705SXin Li     return StmtError();
1263*67e74705SXin Li   }
1264*67e74705SXin Li 
1265*67e74705SXin Li   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1266*67e74705SXin Li 
1267*67e74705SXin Li   // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
1268*67e74705SXin Li   // not the case for C90.  Start the switch scope.
1269*67e74705SXin Li   //
1270*67e74705SXin Li   // C++ 6.4p3:
1271*67e74705SXin Li   // A name introduced by a declaration in a condition is in scope from its
1272*67e74705SXin Li   // point of declaration until the end of the substatements controlled by the
1273*67e74705SXin Li   // condition.
1274*67e74705SXin Li   // C++ 3.3.2p4:
1275*67e74705SXin Li   // Names declared in the for-init-statement, and in the condition of if,
1276*67e74705SXin Li   // while, for, and switch statements are local to the if, while, for, or
1277*67e74705SXin Li   // switch statement (including the controlled statement).
1278*67e74705SXin Li   //
1279*67e74705SXin Li   unsigned ScopeFlags = Scope::SwitchScope;
1280*67e74705SXin Li   if (C99orCXX)
1281*67e74705SXin Li     ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1282*67e74705SXin Li   ParseScope SwitchScope(this, ScopeFlags);
1283*67e74705SXin Li 
1284*67e74705SXin Li   // Parse the condition.
1285*67e74705SXin Li   StmtResult InitStmt;
1286*67e74705SXin Li   Sema::ConditionResult Cond;
1287*67e74705SXin Li   if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1288*67e74705SXin Li                                 Sema::ConditionKind::Switch))
1289*67e74705SXin Li     return StmtError();
1290*67e74705SXin Li 
1291*67e74705SXin Li   StmtResult Switch =
1292*67e74705SXin Li       Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1293*67e74705SXin Li 
1294*67e74705SXin Li   if (Switch.isInvalid()) {
1295*67e74705SXin Li     // Skip the switch body.
1296*67e74705SXin Li     // FIXME: This is not optimal recovery, but parsing the body is more
1297*67e74705SXin Li     // dangerous due to the presence of case and default statements, which
1298*67e74705SXin Li     // will have no place to connect back with the switch.
1299*67e74705SXin Li     if (Tok.is(tok::l_brace)) {
1300*67e74705SXin Li       ConsumeBrace();
1301*67e74705SXin Li       SkipUntil(tok::r_brace);
1302*67e74705SXin Li     } else
1303*67e74705SXin Li       SkipUntil(tok::semi);
1304*67e74705SXin Li     return Switch;
1305*67e74705SXin Li   }
1306*67e74705SXin Li 
1307*67e74705SXin Li   // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1308*67e74705SXin Li   // there is no compound stmt.  C90 does not have this clause.  We only do this
1309*67e74705SXin Li   // if the body isn't a compound statement to avoid push/pop in common cases.
1310*67e74705SXin Li   //
1311*67e74705SXin Li   // C++ 6.4p1:
1312*67e74705SXin Li   // The substatement in a selection-statement (each substatement, in the else
1313*67e74705SXin Li   // form of the if statement) implicitly defines a local scope.
1314*67e74705SXin Li   //
1315*67e74705SXin Li   // See comments in ParseIfStatement for why we create a scope for the
1316*67e74705SXin Li   // condition and a new scope for substatement in C++.
1317*67e74705SXin Li   //
1318*67e74705SXin Li   getCurScope()->AddFlags(Scope::BreakScope);
1319*67e74705SXin Li   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1320*67e74705SXin Li 
1321*67e74705SXin Li   // We have incremented the mangling number for the SwitchScope and the
1322*67e74705SXin Li   // InnerScope, which is one too many.
1323*67e74705SXin Li   if (C99orCXX)
1324*67e74705SXin Li     getCurScope()->decrementMSManglingNumber();
1325*67e74705SXin Li 
1326*67e74705SXin Li   // Read the body statement.
1327*67e74705SXin Li   StmtResult Body(ParseStatement(TrailingElseLoc));
1328*67e74705SXin Li 
1329*67e74705SXin Li   // Pop the scopes.
1330*67e74705SXin Li   InnerScope.Exit();
1331*67e74705SXin Li   SwitchScope.Exit();
1332*67e74705SXin Li 
1333*67e74705SXin Li   return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1334*67e74705SXin Li }
1335*67e74705SXin Li 
1336*67e74705SXin Li /// ParseWhileStatement
1337*67e74705SXin Li ///       while-statement: [C99 6.8.5.1]
1338*67e74705SXin Li ///         'while' '(' expression ')' statement
1339*67e74705SXin Li /// [C++]   'while' '(' condition ')' statement
ParseWhileStatement(SourceLocation * TrailingElseLoc)1340*67e74705SXin Li StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1341*67e74705SXin Li   assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1342*67e74705SXin Li   SourceLocation WhileLoc = Tok.getLocation();
1343*67e74705SXin Li   ConsumeToken();  // eat the 'while'.
1344*67e74705SXin Li 
1345*67e74705SXin Li   if (Tok.isNot(tok::l_paren)) {
1346*67e74705SXin Li     Diag(Tok, diag::err_expected_lparen_after) << "while";
1347*67e74705SXin Li     SkipUntil(tok::semi);
1348*67e74705SXin Li     return StmtError();
1349*67e74705SXin Li   }
1350*67e74705SXin Li 
1351*67e74705SXin Li   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1352*67e74705SXin Li 
1353*67e74705SXin Li   // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
1354*67e74705SXin Li   // the case for C90.  Start the loop scope.
1355*67e74705SXin Li   //
1356*67e74705SXin Li   // C++ 6.4p3:
1357*67e74705SXin Li   // A name introduced by a declaration in a condition is in scope from its
1358*67e74705SXin Li   // point of declaration until the end of the substatements controlled by the
1359*67e74705SXin Li   // condition.
1360*67e74705SXin Li   // C++ 3.3.2p4:
1361*67e74705SXin Li   // Names declared in the for-init-statement, and in the condition of if,
1362*67e74705SXin Li   // while, for, and switch statements are local to the if, while, for, or
1363*67e74705SXin Li   // switch statement (including the controlled statement).
1364*67e74705SXin Li   //
1365*67e74705SXin Li   unsigned ScopeFlags;
1366*67e74705SXin Li   if (C99orCXX)
1367*67e74705SXin Li     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1368*67e74705SXin Li                  Scope::DeclScope  | Scope::ControlScope;
1369*67e74705SXin Li   else
1370*67e74705SXin Li     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1371*67e74705SXin Li   ParseScope WhileScope(this, ScopeFlags);
1372*67e74705SXin Li 
1373*67e74705SXin Li   // Parse the condition.
1374*67e74705SXin Li   Sema::ConditionResult Cond;
1375*67e74705SXin Li   if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1376*67e74705SXin Li                                 Sema::ConditionKind::Boolean))
1377*67e74705SXin Li     return StmtError();
1378*67e74705SXin Li 
1379*67e74705SXin Li   // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1380*67e74705SXin Li   // there is no compound stmt.  C90 does not have this clause.  We only do this
1381*67e74705SXin Li   // if the body isn't a compound statement to avoid push/pop in common cases.
1382*67e74705SXin Li   //
1383*67e74705SXin Li   // C++ 6.5p2:
1384*67e74705SXin Li   // The substatement in an iteration-statement implicitly defines a local scope
1385*67e74705SXin Li   // which is entered and exited each time through the loop.
1386*67e74705SXin Li   //
1387*67e74705SXin Li   // See comments in ParseIfStatement for why we create a scope for the
1388*67e74705SXin Li   // condition and a new scope for substatement in C++.
1389*67e74705SXin Li   //
1390*67e74705SXin Li   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1391*67e74705SXin Li 
1392*67e74705SXin Li   // Read the body statement.
1393*67e74705SXin Li   StmtResult Body(ParseStatement(TrailingElseLoc));
1394*67e74705SXin Li 
1395*67e74705SXin Li   // Pop the body scope if needed.
1396*67e74705SXin Li   InnerScope.Exit();
1397*67e74705SXin Li   WhileScope.Exit();
1398*67e74705SXin Li 
1399*67e74705SXin Li   if (Cond.isInvalid() || Body.isInvalid())
1400*67e74705SXin Li     return StmtError();
1401*67e74705SXin Li 
1402*67e74705SXin Li   return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1403*67e74705SXin Li }
1404*67e74705SXin Li 
1405*67e74705SXin Li /// ParseDoStatement
1406*67e74705SXin Li ///       do-statement: [C99 6.8.5.2]
1407*67e74705SXin Li ///         'do' statement 'while' '(' expression ')' ';'
1408*67e74705SXin Li /// Note: this lets the caller parse the end ';'.
ParseDoStatement()1409*67e74705SXin Li StmtResult Parser::ParseDoStatement() {
1410*67e74705SXin Li   assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1411*67e74705SXin Li   SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
1412*67e74705SXin Li 
1413*67e74705SXin Li   // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
1414*67e74705SXin Li   // the case for C90.  Start the loop scope.
1415*67e74705SXin Li   unsigned ScopeFlags;
1416*67e74705SXin Li   if (getLangOpts().C99)
1417*67e74705SXin Li     ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1418*67e74705SXin Li   else
1419*67e74705SXin Li     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1420*67e74705SXin Li 
1421*67e74705SXin Li   ParseScope DoScope(this, ScopeFlags);
1422*67e74705SXin Li 
1423*67e74705SXin Li   // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1424*67e74705SXin Li   // there is no compound stmt.  C90 does not have this clause. We only do this
1425*67e74705SXin Li   // if the body isn't a compound statement to avoid push/pop in common cases.
1426*67e74705SXin Li   //
1427*67e74705SXin Li   // C++ 6.5p2:
1428*67e74705SXin Li   // The substatement in an iteration-statement implicitly defines a local scope
1429*67e74705SXin Li   // which is entered and exited each time through the loop.
1430*67e74705SXin Li   //
1431*67e74705SXin Li   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1432*67e74705SXin Li   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1433*67e74705SXin Li 
1434*67e74705SXin Li   // Read the body statement.
1435*67e74705SXin Li   StmtResult Body(ParseStatement());
1436*67e74705SXin Li 
1437*67e74705SXin Li   // Pop the body scope if needed.
1438*67e74705SXin Li   InnerScope.Exit();
1439*67e74705SXin Li 
1440*67e74705SXin Li   if (Tok.isNot(tok::kw_while)) {
1441*67e74705SXin Li     if (!Body.isInvalid()) {
1442*67e74705SXin Li       Diag(Tok, diag::err_expected_while);
1443*67e74705SXin Li       Diag(DoLoc, diag::note_matching) << "'do'";
1444*67e74705SXin Li       SkipUntil(tok::semi, StopBeforeMatch);
1445*67e74705SXin Li     }
1446*67e74705SXin Li     return StmtError();
1447*67e74705SXin Li   }
1448*67e74705SXin Li   SourceLocation WhileLoc = ConsumeToken();
1449*67e74705SXin Li 
1450*67e74705SXin Li   if (Tok.isNot(tok::l_paren)) {
1451*67e74705SXin Li     Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1452*67e74705SXin Li     SkipUntil(tok::semi, StopBeforeMatch);
1453*67e74705SXin Li     return StmtError();
1454*67e74705SXin Li   }
1455*67e74705SXin Li 
1456*67e74705SXin Li   // Parse the parenthesized expression.
1457*67e74705SXin Li   BalancedDelimiterTracker T(*this, tok::l_paren);
1458*67e74705SXin Li   T.consumeOpen();
1459*67e74705SXin Li 
1460*67e74705SXin Li   // A do-while expression is not a condition, so can't have attributes.
1461*67e74705SXin Li   DiagnoseAndSkipCXX11Attributes();
1462*67e74705SXin Li 
1463*67e74705SXin Li   ExprResult Cond = ParseExpression();
1464*67e74705SXin Li   T.consumeClose();
1465*67e74705SXin Li   DoScope.Exit();
1466*67e74705SXin Li 
1467*67e74705SXin Li   if (Cond.isInvalid() || Body.isInvalid())
1468*67e74705SXin Li     return StmtError();
1469*67e74705SXin Li 
1470*67e74705SXin Li   return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1471*67e74705SXin Li                              Cond.get(), T.getCloseLocation());
1472*67e74705SXin Li }
1473*67e74705SXin Li 
isForRangeIdentifier()1474*67e74705SXin Li bool Parser::isForRangeIdentifier() {
1475*67e74705SXin Li   assert(Tok.is(tok::identifier));
1476*67e74705SXin Li 
1477*67e74705SXin Li   const Token &Next = NextToken();
1478*67e74705SXin Li   if (Next.is(tok::colon))
1479*67e74705SXin Li     return true;
1480*67e74705SXin Li 
1481*67e74705SXin Li   if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1482*67e74705SXin Li     TentativeParsingAction PA(*this);
1483*67e74705SXin Li     ConsumeToken();
1484*67e74705SXin Li     SkipCXX11Attributes();
1485*67e74705SXin Li     bool Result = Tok.is(tok::colon);
1486*67e74705SXin Li     PA.Revert();
1487*67e74705SXin Li     return Result;
1488*67e74705SXin Li   }
1489*67e74705SXin Li 
1490*67e74705SXin Li   return false;
1491*67e74705SXin Li }
1492*67e74705SXin Li 
1493*67e74705SXin Li /// ParseForStatement
1494*67e74705SXin Li ///       for-statement: [C99 6.8.5.3]
1495*67e74705SXin Li ///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1496*67e74705SXin Li ///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1497*67e74705SXin Li /// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1498*67e74705SXin Li /// [C++]       statement
1499*67e74705SXin Li /// [C++0x] 'for'
1500*67e74705SXin Li ///             'co_await'[opt]    [Coroutines]
1501*67e74705SXin Li ///             '(' for-range-declaration ':' for-range-initializer ')'
1502*67e74705SXin Li ///             statement
1503*67e74705SXin Li /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1504*67e74705SXin Li /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1505*67e74705SXin Li ///
1506*67e74705SXin Li /// [C++] for-init-statement:
1507*67e74705SXin Li /// [C++]   expression-statement
1508*67e74705SXin Li /// [C++]   simple-declaration
1509*67e74705SXin Li ///
1510*67e74705SXin Li /// [C++0x] for-range-declaration:
1511*67e74705SXin Li /// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
1512*67e74705SXin Li /// [C++0x] for-range-initializer:
1513*67e74705SXin Li /// [C++0x]   expression
1514*67e74705SXin Li /// [C++0x]   braced-init-list            [TODO]
ParseForStatement(SourceLocation * TrailingElseLoc)1515*67e74705SXin Li StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1516*67e74705SXin Li   assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1517*67e74705SXin Li   SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
1518*67e74705SXin Li 
1519*67e74705SXin Li   SourceLocation CoawaitLoc;
1520*67e74705SXin Li   if (Tok.is(tok::kw_co_await))
1521*67e74705SXin Li     CoawaitLoc = ConsumeToken();
1522*67e74705SXin Li 
1523*67e74705SXin Li   if (Tok.isNot(tok::l_paren)) {
1524*67e74705SXin Li     Diag(Tok, diag::err_expected_lparen_after) << "for";
1525*67e74705SXin Li     SkipUntil(tok::semi);
1526*67e74705SXin Li     return StmtError();
1527*67e74705SXin Li   }
1528*67e74705SXin Li 
1529*67e74705SXin Li   bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1530*67e74705SXin Li     getLangOpts().ObjC1;
1531*67e74705SXin Li 
1532*67e74705SXin Li   // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1533*67e74705SXin Li   // the case for C90.  Start the loop scope.
1534*67e74705SXin Li   //
1535*67e74705SXin Li   // C++ 6.4p3:
1536*67e74705SXin Li   // A name introduced by a declaration in a condition is in scope from its
1537*67e74705SXin Li   // point of declaration until the end of the substatements controlled by the
1538*67e74705SXin Li   // condition.
1539*67e74705SXin Li   // C++ 3.3.2p4:
1540*67e74705SXin Li   // Names declared in the for-init-statement, and in the condition of if,
1541*67e74705SXin Li   // while, for, and switch statements are local to the if, while, for, or
1542*67e74705SXin Li   // switch statement (including the controlled statement).
1543*67e74705SXin Li   // C++ 6.5.3p1:
1544*67e74705SXin Li   // Names declared in the for-init-statement are in the same declarative-region
1545*67e74705SXin Li   // as those declared in the condition.
1546*67e74705SXin Li   //
1547*67e74705SXin Li   unsigned ScopeFlags = 0;
1548*67e74705SXin Li   if (C99orCXXorObjC)
1549*67e74705SXin Li     ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1550*67e74705SXin Li 
1551*67e74705SXin Li   ParseScope ForScope(this, ScopeFlags);
1552*67e74705SXin Li 
1553*67e74705SXin Li   BalancedDelimiterTracker T(*this, tok::l_paren);
1554*67e74705SXin Li   T.consumeOpen();
1555*67e74705SXin Li 
1556*67e74705SXin Li   ExprResult Value;
1557*67e74705SXin Li 
1558*67e74705SXin Li   bool ForEach = false, ForRange = false;
1559*67e74705SXin Li   StmtResult FirstPart;
1560*67e74705SXin Li   Sema::ConditionResult SecondPart;
1561*67e74705SXin Li   ExprResult Collection;
1562*67e74705SXin Li   ForRangeInit ForRangeInit;
1563*67e74705SXin Li   FullExprArg ThirdPart(Actions);
1564*67e74705SXin Li 
1565*67e74705SXin Li   if (Tok.is(tok::code_completion)) {
1566*67e74705SXin Li     Actions.CodeCompleteOrdinaryName(getCurScope(),
1567*67e74705SXin Li                                      C99orCXXorObjC? Sema::PCC_ForInit
1568*67e74705SXin Li                                                    : Sema::PCC_Expression);
1569*67e74705SXin Li     cutOffParsing();
1570*67e74705SXin Li     return StmtError();
1571*67e74705SXin Li   }
1572*67e74705SXin Li 
1573*67e74705SXin Li   ParsedAttributesWithRange attrs(AttrFactory);
1574*67e74705SXin Li   MaybeParseCXX11Attributes(attrs);
1575*67e74705SXin Li 
1576*67e74705SXin Li   // Parse the first part of the for specifier.
1577*67e74705SXin Li   if (Tok.is(tok::semi)) {  // for (;
1578*67e74705SXin Li     ProhibitAttributes(attrs);
1579*67e74705SXin Li     // no first part, eat the ';'.
1580*67e74705SXin Li     ConsumeToken();
1581*67e74705SXin Li   } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1582*67e74705SXin Li              isForRangeIdentifier()) {
1583*67e74705SXin Li     ProhibitAttributes(attrs);
1584*67e74705SXin Li     IdentifierInfo *Name = Tok.getIdentifierInfo();
1585*67e74705SXin Li     SourceLocation Loc = ConsumeToken();
1586*67e74705SXin Li     MaybeParseCXX11Attributes(attrs);
1587*67e74705SXin Li 
1588*67e74705SXin Li     ForRangeInit.ColonLoc = ConsumeToken();
1589*67e74705SXin Li     if (Tok.is(tok::l_brace))
1590*67e74705SXin Li       ForRangeInit.RangeExpr = ParseBraceInitializer();
1591*67e74705SXin Li     else
1592*67e74705SXin Li       ForRangeInit.RangeExpr = ParseExpression();
1593*67e74705SXin Li 
1594*67e74705SXin Li     Diag(Loc, diag::err_for_range_identifier)
1595*67e74705SXin Li       << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1596*67e74705SXin Li               ? FixItHint::CreateInsertion(Loc, "auto &&")
1597*67e74705SXin Li               : FixItHint());
1598*67e74705SXin Li 
1599*67e74705SXin Li     FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1600*67e74705SXin Li                                                    attrs, attrs.Range.getEnd());
1601*67e74705SXin Li     ForRange = true;
1602*67e74705SXin Li   } else if (isForInitDeclaration()) {  // for (int X = 4;
1603*67e74705SXin Li     // Parse declaration, which eats the ';'.
1604*67e74705SXin Li     if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
1605*67e74705SXin Li       Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1606*67e74705SXin Li 
1607*67e74705SXin Li     // In C++0x, "for (T NS:a" might not be a typo for ::
1608*67e74705SXin Li     bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1609*67e74705SXin Li     ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1610*67e74705SXin Li 
1611*67e74705SXin Li     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1612*67e74705SXin Li     DeclGroupPtrTy DG = ParseSimpleDeclaration(
1613*67e74705SXin Li         Declarator::ForContext, DeclEnd, attrs, false,
1614*67e74705SXin Li         MightBeForRangeStmt ? &ForRangeInit : nullptr);
1615*67e74705SXin Li     FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1616*67e74705SXin Li     if (ForRangeInit.ParsedForRangeDecl()) {
1617*67e74705SXin Li       Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1618*67e74705SXin Li            diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1619*67e74705SXin Li 
1620*67e74705SXin Li       ForRange = true;
1621*67e74705SXin Li     } else if (Tok.is(tok::semi)) {  // for (int x = 4;
1622*67e74705SXin Li       ConsumeToken();
1623*67e74705SXin Li     } else if ((ForEach = isTokIdentifier_in())) {
1624*67e74705SXin Li       Actions.ActOnForEachDeclStmt(DG);
1625*67e74705SXin Li       // ObjC: for (id x in expr)
1626*67e74705SXin Li       ConsumeToken(); // consume 'in'
1627*67e74705SXin Li 
1628*67e74705SXin Li       if (Tok.is(tok::code_completion)) {
1629*67e74705SXin Li         Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1630*67e74705SXin Li         cutOffParsing();
1631*67e74705SXin Li         return StmtError();
1632*67e74705SXin Li       }
1633*67e74705SXin Li       Collection = ParseExpression();
1634*67e74705SXin Li     } else {
1635*67e74705SXin Li       Diag(Tok, diag::err_expected_semi_for);
1636*67e74705SXin Li     }
1637*67e74705SXin Li   } else {
1638*67e74705SXin Li     ProhibitAttributes(attrs);
1639*67e74705SXin Li     Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1640*67e74705SXin Li 
1641*67e74705SXin Li     ForEach = isTokIdentifier_in();
1642*67e74705SXin Li 
1643*67e74705SXin Li     // Turn the expression into a stmt.
1644*67e74705SXin Li     if (!Value.isInvalid()) {
1645*67e74705SXin Li       if (ForEach)
1646*67e74705SXin Li         FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1647*67e74705SXin Li       else
1648*67e74705SXin Li         FirstPart = Actions.ActOnExprStmt(Value);
1649*67e74705SXin Li     }
1650*67e74705SXin Li 
1651*67e74705SXin Li     if (Tok.is(tok::semi)) {
1652*67e74705SXin Li       ConsumeToken();
1653*67e74705SXin Li     } else if (ForEach) {
1654*67e74705SXin Li       ConsumeToken(); // consume 'in'
1655*67e74705SXin Li 
1656*67e74705SXin Li       if (Tok.is(tok::code_completion)) {
1657*67e74705SXin Li         Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1658*67e74705SXin Li         cutOffParsing();
1659*67e74705SXin Li         return StmtError();
1660*67e74705SXin Li       }
1661*67e74705SXin Li       Collection = ParseExpression();
1662*67e74705SXin Li     } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1663*67e74705SXin Li       // User tried to write the reasonable, but ill-formed, for-range-statement
1664*67e74705SXin Li       //   for (expr : expr) { ... }
1665*67e74705SXin Li       Diag(Tok, diag::err_for_range_expected_decl)
1666*67e74705SXin Li         << FirstPart.get()->getSourceRange();
1667*67e74705SXin Li       SkipUntil(tok::r_paren, StopBeforeMatch);
1668*67e74705SXin Li       SecondPart = Sema::ConditionError();
1669*67e74705SXin Li     } else {
1670*67e74705SXin Li       if (!Value.isInvalid()) {
1671*67e74705SXin Li         Diag(Tok, diag::err_expected_semi_for);
1672*67e74705SXin Li       } else {
1673*67e74705SXin Li         // Skip until semicolon or rparen, don't consume it.
1674*67e74705SXin Li         SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1675*67e74705SXin Li         if (Tok.is(tok::semi))
1676*67e74705SXin Li           ConsumeToken();
1677*67e74705SXin Li       }
1678*67e74705SXin Li     }
1679*67e74705SXin Li   }
1680*67e74705SXin Li 
1681*67e74705SXin Li   // Parse the second part of the for specifier.
1682*67e74705SXin Li   getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1683*67e74705SXin Li   if (!ForEach && !ForRange && !SecondPart.isInvalid()) {
1684*67e74705SXin Li     // Parse the second part of the for specifier.
1685*67e74705SXin Li     if (Tok.is(tok::semi)) {  // for (...;;
1686*67e74705SXin Li       // no second part.
1687*67e74705SXin Li     } else if (Tok.is(tok::r_paren)) {
1688*67e74705SXin Li       // missing both semicolons.
1689*67e74705SXin Li     } else {
1690*67e74705SXin Li       if (getLangOpts().CPlusPlus)
1691*67e74705SXin Li         SecondPart =
1692*67e74705SXin Li             ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean);
1693*67e74705SXin Li       else {
1694*67e74705SXin Li         ExprResult SecondExpr = ParseExpression();
1695*67e74705SXin Li         if (SecondExpr.isInvalid())
1696*67e74705SXin Li           SecondPart = Sema::ConditionError();
1697*67e74705SXin Li         else
1698*67e74705SXin Li           SecondPart =
1699*67e74705SXin Li               Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1700*67e74705SXin Li                                      Sema::ConditionKind::Boolean);
1701*67e74705SXin Li       }
1702*67e74705SXin Li     }
1703*67e74705SXin Li 
1704*67e74705SXin Li     if (Tok.isNot(tok::semi)) {
1705*67e74705SXin Li       if (!SecondPart.isInvalid())
1706*67e74705SXin Li         Diag(Tok, diag::err_expected_semi_for);
1707*67e74705SXin Li       else
1708*67e74705SXin Li         // Skip until semicolon or rparen, don't consume it.
1709*67e74705SXin Li         SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1710*67e74705SXin Li     }
1711*67e74705SXin Li 
1712*67e74705SXin Li     if (Tok.is(tok::semi)) {
1713*67e74705SXin Li       ConsumeToken();
1714*67e74705SXin Li     }
1715*67e74705SXin Li 
1716*67e74705SXin Li     // Parse the third part of the for specifier.
1717*67e74705SXin Li     if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
1718*67e74705SXin Li       ExprResult Third = ParseExpression();
1719*67e74705SXin Li       // FIXME: The C++11 standard doesn't actually say that this is a
1720*67e74705SXin Li       // discarded-value expression, but it clearly should be.
1721*67e74705SXin Li       ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1722*67e74705SXin Li     }
1723*67e74705SXin Li   }
1724*67e74705SXin Li   // Match the ')'.
1725*67e74705SXin Li   T.consumeClose();
1726*67e74705SXin Li 
1727*67e74705SXin Li   // C++ Coroutines [stmt.iter]:
1728*67e74705SXin Li   //   'co_await' can only be used for a range-based for statement.
1729*67e74705SXin Li   if (CoawaitLoc.isValid() && !ForRange) {
1730*67e74705SXin Li     Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1731*67e74705SXin Li     CoawaitLoc = SourceLocation();
1732*67e74705SXin Li   }
1733*67e74705SXin Li 
1734*67e74705SXin Li   // We need to perform most of the semantic analysis for a C++0x for-range
1735*67e74705SXin Li   // statememt before parsing the body, in order to be able to deduce the type
1736*67e74705SXin Li   // of an auto-typed loop variable.
1737*67e74705SXin Li   StmtResult ForRangeStmt;
1738*67e74705SXin Li   StmtResult ForEachStmt;
1739*67e74705SXin Li 
1740*67e74705SXin Li   if (ForRange) {
1741*67e74705SXin Li     ExprResult CorrectedRange =
1742*67e74705SXin Li         Actions.CorrectDelayedTyposInExpr(ForRangeInit.RangeExpr.get());
1743*67e74705SXin Li     ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1744*67e74705SXin Li         getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1745*67e74705SXin Li         ForRangeInit.ColonLoc, CorrectedRange.get(),
1746*67e74705SXin Li         T.getCloseLocation(), Sema::BFRK_Build);
1747*67e74705SXin Li 
1748*67e74705SXin Li   // Similarly, we need to do the semantic analysis for a for-range
1749*67e74705SXin Li   // statement immediately in order to close over temporaries correctly.
1750*67e74705SXin Li   } else if (ForEach) {
1751*67e74705SXin Li     ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1752*67e74705SXin Li                                                      FirstPart.get(),
1753*67e74705SXin Li                                                      Collection.get(),
1754*67e74705SXin Li                                                      T.getCloseLocation());
1755*67e74705SXin Li   } else {
1756*67e74705SXin Li     // In OpenMP loop region loop control variable must be captured and be
1757*67e74705SXin Li     // private. Perform analysis of first part (if any).
1758*67e74705SXin Li     if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1759*67e74705SXin Li       Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1760*67e74705SXin Li     }
1761*67e74705SXin Li   }
1762*67e74705SXin Li 
1763*67e74705SXin Li   // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1764*67e74705SXin Li   // there is no compound stmt.  C90 does not have this clause.  We only do this
1765*67e74705SXin Li   // if the body isn't a compound statement to avoid push/pop in common cases.
1766*67e74705SXin Li   //
1767*67e74705SXin Li   // C++ 6.5p2:
1768*67e74705SXin Li   // The substatement in an iteration-statement implicitly defines a local scope
1769*67e74705SXin Li   // which is entered and exited each time through the loop.
1770*67e74705SXin Li   //
1771*67e74705SXin Li   // See comments in ParseIfStatement for why we create a scope for
1772*67e74705SXin Li   // for-init-statement/condition and a new scope for substatement in C++.
1773*67e74705SXin Li   //
1774*67e74705SXin Li   ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1775*67e74705SXin Li                         Tok.is(tok::l_brace));
1776*67e74705SXin Li 
1777*67e74705SXin Li   // The body of the for loop has the same local mangling number as the
1778*67e74705SXin Li   // for-init-statement.
1779*67e74705SXin Li   // It will only be incremented if the body contains other things that would
1780*67e74705SXin Li   // normally increment the mangling number (like a compound statement).
1781*67e74705SXin Li   if (C99orCXXorObjC)
1782*67e74705SXin Li     getCurScope()->decrementMSManglingNumber();
1783*67e74705SXin Li 
1784*67e74705SXin Li   // Read the body statement.
1785*67e74705SXin Li   StmtResult Body(ParseStatement(TrailingElseLoc));
1786*67e74705SXin Li 
1787*67e74705SXin Li   // Pop the body scope if needed.
1788*67e74705SXin Li   InnerScope.Exit();
1789*67e74705SXin Li 
1790*67e74705SXin Li   // Leave the for-scope.
1791*67e74705SXin Li   ForScope.Exit();
1792*67e74705SXin Li 
1793*67e74705SXin Li   if (Body.isInvalid())
1794*67e74705SXin Li     return StmtError();
1795*67e74705SXin Li 
1796*67e74705SXin Li   if (ForEach)
1797*67e74705SXin Li    return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1798*67e74705SXin Li                                               Body.get());
1799*67e74705SXin Li 
1800*67e74705SXin Li   if (ForRange)
1801*67e74705SXin Li     return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1802*67e74705SXin Li 
1803*67e74705SXin Li   return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1804*67e74705SXin Li                               SecondPart, ThirdPart, T.getCloseLocation(),
1805*67e74705SXin Li                               Body.get());
1806*67e74705SXin Li }
1807*67e74705SXin Li 
1808*67e74705SXin Li /// ParseGotoStatement
1809*67e74705SXin Li ///       jump-statement:
1810*67e74705SXin Li ///         'goto' identifier ';'
1811*67e74705SXin Li /// [GNU]   'goto' '*' expression ';'
1812*67e74705SXin Li ///
1813*67e74705SXin Li /// Note: this lets the caller parse the end ';'.
1814*67e74705SXin Li ///
ParseGotoStatement()1815*67e74705SXin Li StmtResult Parser::ParseGotoStatement() {
1816*67e74705SXin Li   assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1817*67e74705SXin Li   SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
1818*67e74705SXin Li 
1819*67e74705SXin Li   StmtResult Res;
1820*67e74705SXin Li   if (Tok.is(tok::identifier)) {
1821*67e74705SXin Li     LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1822*67e74705SXin Li                                                 Tok.getLocation());
1823*67e74705SXin Li     Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1824*67e74705SXin Li     ConsumeToken();
1825*67e74705SXin Li   } else if (Tok.is(tok::star)) {
1826*67e74705SXin Li     // GNU indirect goto extension.
1827*67e74705SXin Li     Diag(Tok, diag::ext_gnu_indirect_goto);
1828*67e74705SXin Li     SourceLocation StarLoc = ConsumeToken();
1829*67e74705SXin Li     ExprResult R(ParseExpression());
1830*67e74705SXin Li     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1831*67e74705SXin Li       SkipUntil(tok::semi, StopBeforeMatch);
1832*67e74705SXin Li       return StmtError();
1833*67e74705SXin Li     }
1834*67e74705SXin Li     Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1835*67e74705SXin Li   } else {
1836*67e74705SXin Li     Diag(Tok, diag::err_expected) << tok::identifier;
1837*67e74705SXin Li     return StmtError();
1838*67e74705SXin Li   }
1839*67e74705SXin Li 
1840*67e74705SXin Li   return Res;
1841*67e74705SXin Li }
1842*67e74705SXin Li 
1843*67e74705SXin Li /// ParseContinueStatement
1844*67e74705SXin Li ///       jump-statement:
1845*67e74705SXin Li ///         'continue' ';'
1846*67e74705SXin Li ///
1847*67e74705SXin Li /// Note: this lets the caller parse the end ';'.
1848*67e74705SXin Li ///
ParseContinueStatement()1849*67e74705SXin Li StmtResult Parser::ParseContinueStatement() {
1850*67e74705SXin Li   SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
1851*67e74705SXin Li   return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1852*67e74705SXin Li }
1853*67e74705SXin Li 
1854*67e74705SXin Li /// ParseBreakStatement
1855*67e74705SXin Li ///       jump-statement:
1856*67e74705SXin Li ///         'break' ';'
1857*67e74705SXin Li ///
1858*67e74705SXin Li /// Note: this lets the caller parse the end ';'.
1859*67e74705SXin Li ///
ParseBreakStatement()1860*67e74705SXin Li StmtResult Parser::ParseBreakStatement() {
1861*67e74705SXin Li   SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
1862*67e74705SXin Li   return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1863*67e74705SXin Li }
1864*67e74705SXin Li 
1865*67e74705SXin Li /// ParseReturnStatement
1866*67e74705SXin Li ///       jump-statement:
1867*67e74705SXin Li ///         'return' expression[opt] ';'
1868*67e74705SXin Li ///         'return' braced-init-list ';'
1869*67e74705SXin Li ///         'co_return' expression[opt] ';'
1870*67e74705SXin Li ///         'co_return' braced-init-list ';'
ParseReturnStatement()1871*67e74705SXin Li StmtResult Parser::ParseReturnStatement() {
1872*67e74705SXin Li   assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1873*67e74705SXin Li          "Not a return stmt!");
1874*67e74705SXin Li   bool IsCoreturn = Tok.is(tok::kw_co_return);
1875*67e74705SXin Li   SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
1876*67e74705SXin Li 
1877*67e74705SXin Li   ExprResult R;
1878*67e74705SXin Li   if (Tok.isNot(tok::semi)) {
1879*67e74705SXin Li     // FIXME: Code completion for co_return.
1880*67e74705SXin Li     if (Tok.is(tok::code_completion) && !IsCoreturn) {
1881*67e74705SXin Li       Actions.CodeCompleteReturn(getCurScope());
1882*67e74705SXin Li       cutOffParsing();
1883*67e74705SXin Li       return StmtError();
1884*67e74705SXin Li     }
1885*67e74705SXin Li 
1886*67e74705SXin Li     if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1887*67e74705SXin Li       R = ParseInitializer();
1888*67e74705SXin Li       if (R.isUsable())
1889*67e74705SXin Li         Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1890*67e74705SXin Li              diag::warn_cxx98_compat_generalized_initializer_lists :
1891*67e74705SXin Li              diag::ext_generalized_initializer_lists)
1892*67e74705SXin Li           << R.get()->getSourceRange();
1893*67e74705SXin Li     } else
1894*67e74705SXin Li       R = ParseExpression();
1895*67e74705SXin Li     if (R.isInvalid()) {
1896*67e74705SXin Li       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1897*67e74705SXin Li       return StmtError();
1898*67e74705SXin Li     }
1899*67e74705SXin Li   }
1900*67e74705SXin Li   if (IsCoreturn)
1901*67e74705SXin Li     return Actions.ActOnCoreturnStmt(ReturnLoc, R.get());
1902*67e74705SXin Li   return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1903*67e74705SXin Li }
1904*67e74705SXin Li 
ParsePragmaLoopHint(StmtVector & Stmts,AllowedContsructsKind Allowed,SourceLocation * TrailingElseLoc,ParsedAttributesWithRange & Attrs)1905*67e74705SXin Li StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1906*67e74705SXin Li                                        AllowedContsructsKind Allowed,
1907*67e74705SXin Li                                        SourceLocation *TrailingElseLoc,
1908*67e74705SXin Li                                        ParsedAttributesWithRange &Attrs) {
1909*67e74705SXin Li   // Create temporary attribute list.
1910*67e74705SXin Li   ParsedAttributesWithRange TempAttrs(AttrFactory);
1911*67e74705SXin Li 
1912*67e74705SXin Li   // Get loop hints and consume annotated token.
1913*67e74705SXin Li   while (Tok.is(tok::annot_pragma_loop_hint)) {
1914*67e74705SXin Li     LoopHint Hint;
1915*67e74705SXin Li     if (!HandlePragmaLoopHint(Hint))
1916*67e74705SXin Li       continue;
1917*67e74705SXin Li 
1918*67e74705SXin Li     ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1919*67e74705SXin Li                             ArgsUnion(Hint.ValueExpr)};
1920*67e74705SXin Li     TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1921*67e74705SXin Li                      Hint.PragmaNameLoc->Loc, ArgHints, 4,
1922*67e74705SXin Li                      AttributeList::AS_Pragma);
1923*67e74705SXin Li   }
1924*67e74705SXin Li 
1925*67e74705SXin Li   // Get the next statement.
1926*67e74705SXin Li   MaybeParseCXX11Attributes(Attrs);
1927*67e74705SXin Li 
1928*67e74705SXin Li   StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1929*67e74705SXin Li       Stmts, Allowed, TrailingElseLoc, Attrs);
1930*67e74705SXin Li 
1931*67e74705SXin Li   Attrs.takeAllFrom(TempAttrs);
1932*67e74705SXin Li   return S;
1933*67e74705SXin Li }
1934*67e74705SXin Li 
ParseFunctionStatementBody(Decl * Decl,ParseScope & BodyScope)1935*67e74705SXin Li Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1936*67e74705SXin Li   assert(Tok.is(tok::l_brace));
1937*67e74705SXin Li   SourceLocation LBraceLoc = Tok.getLocation();
1938*67e74705SXin Li 
1939*67e74705SXin Li   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1940*67e74705SXin Li                                       "parsing function body");
1941*67e74705SXin Li 
1942*67e74705SXin Li   // Save and reset current vtordisp stack if we have entered a C++ method body.
1943*67e74705SXin Li   bool IsCXXMethod =
1944*67e74705SXin Li       getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1945*67e74705SXin Li   Sema::PragmaStackSentinelRAII
1946*67e74705SXin Li     PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1947*67e74705SXin Li 
1948*67e74705SXin Li   // Do not enter a scope for the brace, as the arguments are in the same scope
1949*67e74705SXin Li   // (the function body) as the body itself.  Instead, just read the statement
1950*67e74705SXin Li   // list and put it into a CompoundStmt for safe keeping.
1951*67e74705SXin Li   StmtResult FnBody(ParseCompoundStatementBody());
1952*67e74705SXin Li 
1953*67e74705SXin Li   // If the function body could not be parsed, make a bogus compoundstmt.
1954*67e74705SXin Li   if (FnBody.isInvalid()) {
1955*67e74705SXin Li     Sema::CompoundScopeRAII CompoundScope(Actions);
1956*67e74705SXin Li     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1957*67e74705SXin Li   }
1958*67e74705SXin Li 
1959*67e74705SXin Li   BodyScope.Exit();
1960*67e74705SXin Li   return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1961*67e74705SXin Li }
1962*67e74705SXin Li 
1963*67e74705SXin Li /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1964*67e74705SXin Li ///
1965*67e74705SXin Li ///       function-try-block:
1966*67e74705SXin Li ///         'try' ctor-initializer[opt] compound-statement handler-seq
1967*67e74705SXin Li ///
ParseFunctionTryBlock(Decl * Decl,ParseScope & BodyScope)1968*67e74705SXin Li Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1969*67e74705SXin Li   assert(Tok.is(tok::kw_try) && "Expected 'try'");
1970*67e74705SXin Li   SourceLocation TryLoc = ConsumeToken();
1971*67e74705SXin Li 
1972*67e74705SXin Li   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1973*67e74705SXin Li                                       "parsing function try block");
1974*67e74705SXin Li 
1975*67e74705SXin Li   // Constructor initializer list?
1976*67e74705SXin Li   if (Tok.is(tok::colon))
1977*67e74705SXin Li     ParseConstructorInitializer(Decl);
1978*67e74705SXin Li   else
1979*67e74705SXin Li     Actions.ActOnDefaultCtorInitializers(Decl);
1980*67e74705SXin Li 
1981*67e74705SXin Li   // Save and reset current vtordisp stack if we have entered a C++ method body.
1982*67e74705SXin Li   bool IsCXXMethod =
1983*67e74705SXin Li       getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1984*67e74705SXin Li   Sema::PragmaStackSentinelRAII
1985*67e74705SXin Li     PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1986*67e74705SXin Li 
1987*67e74705SXin Li   SourceLocation LBraceLoc = Tok.getLocation();
1988*67e74705SXin Li   StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
1989*67e74705SXin Li   // If we failed to parse the try-catch, we just give the function an empty
1990*67e74705SXin Li   // compound statement as the body.
1991*67e74705SXin Li   if (FnBody.isInvalid()) {
1992*67e74705SXin Li     Sema::CompoundScopeRAII CompoundScope(Actions);
1993*67e74705SXin Li     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1994*67e74705SXin Li   }
1995*67e74705SXin Li 
1996*67e74705SXin Li   BodyScope.Exit();
1997*67e74705SXin Li   return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1998*67e74705SXin Li }
1999*67e74705SXin Li 
trySkippingFunctionBody()2000*67e74705SXin Li bool Parser::trySkippingFunctionBody() {
2001*67e74705SXin Li   assert(SkipFunctionBodies &&
2002*67e74705SXin Li          "Should only be called when SkipFunctionBodies is enabled");
2003*67e74705SXin Li   if (!PP.isCodeCompletionEnabled()) {
2004*67e74705SXin Li     SkipFunctionBody();
2005*67e74705SXin Li     return true;
2006*67e74705SXin Li   }
2007*67e74705SXin Li 
2008*67e74705SXin Li   // We're in code-completion mode. Skip parsing for all function bodies unless
2009*67e74705SXin Li   // the body contains the code-completion point.
2010*67e74705SXin Li   TentativeParsingAction PA(*this);
2011*67e74705SXin Li   bool IsTryCatch = Tok.is(tok::kw_try);
2012*67e74705SXin Li   CachedTokens Toks;
2013*67e74705SXin Li   bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2014*67e74705SXin Li   if (llvm::any_of(Toks, [](const Token &Tok) {
2015*67e74705SXin Li         return Tok.is(tok::code_completion);
2016*67e74705SXin Li       })) {
2017*67e74705SXin Li     PA.Revert();
2018*67e74705SXin Li     return false;
2019*67e74705SXin Li   }
2020*67e74705SXin Li   if (ErrorInPrologue) {
2021*67e74705SXin Li     PA.Commit();
2022*67e74705SXin Li     SkipMalformedDecl();
2023*67e74705SXin Li     return true;
2024*67e74705SXin Li   }
2025*67e74705SXin Li   if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2026*67e74705SXin Li     PA.Revert();
2027*67e74705SXin Li     return false;
2028*67e74705SXin Li   }
2029*67e74705SXin Li   while (IsTryCatch && Tok.is(tok::kw_catch)) {
2030*67e74705SXin Li     if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2031*67e74705SXin Li         !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2032*67e74705SXin Li       PA.Revert();
2033*67e74705SXin Li       return false;
2034*67e74705SXin Li     }
2035*67e74705SXin Li   }
2036*67e74705SXin Li   PA.Commit();
2037*67e74705SXin Li   return true;
2038*67e74705SXin Li }
2039*67e74705SXin Li 
2040*67e74705SXin Li /// ParseCXXTryBlock - Parse a C++ try-block.
2041*67e74705SXin Li ///
2042*67e74705SXin Li ///       try-block:
2043*67e74705SXin Li ///         'try' compound-statement handler-seq
2044*67e74705SXin Li ///
ParseCXXTryBlock()2045*67e74705SXin Li StmtResult Parser::ParseCXXTryBlock() {
2046*67e74705SXin Li   assert(Tok.is(tok::kw_try) && "Expected 'try'");
2047*67e74705SXin Li 
2048*67e74705SXin Li   SourceLocation TryLoc = ConsumeToken();
2049*67e74705SXin Li   return ParseCXXTryBlockCommon(TryLoc);
2050*67e74705SXin Li }
2051*67e74705SXin Li 
2052*67e74705SXin Li /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2053*67e74705SXin Li /// function-try-block.
2054*67e74705SXin Li ///
2055*67e74705SXin Li ///       try-block:
2056*67e74705SXin Li ///         'try' compound-statement handler-seq
2057*67e74705SXin Li ///
2058*67e74705SXin Li ///       function-try-block:
2059*67e74705SXin Li ///         'try' ctor-initializer[opt] compound-statement handler-seq
2060*67e74705SXin Li ///
2061*67e74705SXin Li ///       handler-seq:
2062*67e74705SXin Li ///         handler handler-seq[opt]
2063*67e74705SXin Li ///
2064*67e74705SXin Li ///       [Borland] try-block:
2065*67e74705SXin Li ///         'try' compound-statement seh-except-block
2066*67e74705SXin Li ///         'try' compound-statement seh-finally-block
2067*67e74705SXin Li ///
ParseCXXTryBlockCommon(SourceLocation TryLoc,bool FnTry)2068*67e74705SXin Li StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2069*67e74705SXin Li   if (Tok.isNot(tok::l_brace))
2070*67e74705SXin Li     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2071*67e74705SXin Li 
2072*67e74705SXin Li   StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2073*67e74705SXin Li                       Scope::DeclScope | Scope::TryScope |
2074*67e74705SXin Li                         (FnTry ? Scope::FnTryCatchScope : 0)));
2075*67e74705SXin Li   if (TryBlock.isInvalid())
2076*67e74705SXin Li     return TryBlock;
2077*67e74705SXin Li 
2078*67e74705SXin Li   // Borland allows SEH-handlers with 'try'
2079*67e74705SXin Li 
2080*67e74705SXin Li   if ((Tok.is(tok::identifier) &&
2081*67e74705SXin Li        Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2082*67e74705SXin Li       Tok.is(tok::kw___finally)) {
2083*67e74705SXin Li     // TODO: Factor into common return ParseSEHHandlerCommon(...)
2084*67e74705SXin Li     StmtResult Handler;
2085*67e74705SXin Li     if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2086*67e74705SXin Li       SourceLocation Loc = ConsumeToken();
2087*67e74705SXin Li       Handler = ParseSEHExceptBlock(Loc);
2088*67e74705SXin Li     }
2089*67e74705SXin Li     else {
2090*67e74705SXin Li       SourceLocation Loc = ConsumeToken();
2091*67e74705SXin Li       Handler = ParseSEHFinallyBlock(Loc);
2092*67e74705SXin Li     }
2093*67e74705SXin Li     if(Handler.isInvalid())
2094*67e74705SXin Li       return Handler;
2095*67e74705SXin Li 
2096*67e74705SXin Li     return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2097*67e74705SXin Li                                     TryLoc,
2098*67e74705SXin Li                                     TryBlock.get(),
2099*67e74705SXin Li                                     Handler.get());
2100*67e74705SXin Li   }
2101*67e74705SXin Li   else {
2102*67e74705SXin Li     StmtVector Handlers;
2103*67e74705SXin Li 
2104*67e74705SXin Li     // C++11 attributes can't appear here, despite this context seeming
2105*67e74705SXin Li     // statement-like.
2106*67e74705SXin Li     DiagnoseAndSkipCXX11Attributes();
2107*67e74705SXin Li 
2108*67e74705SXin Li     if (Tok.isNot(tok::kw_catch))
2109*67e74705SXin Li       return StmtError(Diag(Tok, diag::err_expected_catch));
2110*67e74705SXin Li     while (Tok.is(tok::kw_catch)) {
2111*67e74705SXin Li       StmtResult Handler(ParseCXXCatchBlock(FnTry));
2112*67e74705SXin Li       if (!Handler.isInvalid())
2113*67e74705SXin Li         Handlers.push_back(Handler.get());
2114*67e74705SXin Li     }
2115*67e74705SXin Li     // Don't bother creating the full statement if we don't have any usable
2116*67e74705SXin Li     // handlers.
2117*67e74705SXin Li     if (Handlers.empty())
2118*67e74705SXin Li       return StmtError();
2119*67e74705SXin Li 
2120*67e74705SXin Li     return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2121*67e74705SXin Li   }
2122*67e74705SXin Li }
2123*67e74705SXin Li 
2124*67e74705SXin Li /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2125*67e74705SXin Li ///
2126*67e74705SXin Li ///   handler:
2127*67e74705SXin Li ///     'catch' '(' exception-declaration ')' compound-statement
2128*67e74705SXin Li ///
2129*67e74705SXin Li ///   exception-declaration:
2130*67e74705SXin Li ///     attribute-specifier-seq[opt] type-specifier-seq declarator
2131*67e74705SXin Li ///     attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2132*67e74705SXin Li ///     '...'
2133*67e74705SXin Li ///
ParseCXXCatchBlock(bool FnCatch)2134*67e74705SXin Li StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2135*67e74705SXin Li   assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2136*67e74705SXin Li 
2137*67e74705SXin Li   SourceLocation CatchLoc = ConsumeToken();
2138*67e74705SXin Li 
2139*67e74705SXin Li   BalancedDelimiterTracker T(*this, tok::l_paren);
2140*67e74705SXin Li   if (T.expectAndConsume())
2141*67e74705SXin Li     return StmtError();
2142*67e74705SXin Li 
2143*67e74705SXin Li   // C++ 3.3.2p3:
2144*67e74705SXin Li   // The name in a catch exception-declaration is local to the handler and
2145*67e74705SXin Li   // shall not be redeclared in the outermost block of the handler.
2146*67e74705SXin Li   ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2147*67e74705SXin Li                           (FnCatch ? Scope::FnTryCatchScope : 0));
2148*67e74705SXin Li 
2149*67e74705SXin Li   // exception-declaration is equivalent to '...' or a parameter-declaration
2150*67e74705SXin Li   // without default arguments.
2151*67e74705SXin Li   Decl *ExceptionDecl = nullptr;
2152*67e74705SXin Li   if (Tok.isNot(tok::ellipsis)) {
2153*67e74705SXin Li     ParsedAttributesWithRange Attributes(AttrFactory);
2154*67e74705SXin Li     MaybeParseCXX11Attributes(Attributes);
2155*67e74705SXin Li 
2156*67e74705SXin Li     DeclSpec DS(AttrFactory);
2157*67e74705SXin Li     DS.takeAttributesFrom(Attributes);
2158*67e74705SXin Li 
2159*67e74705SXin Li     if (ParseCXXTypeSpecifierSeq(DS))
2160*67e74705SXin Li       return StmtError();
2161*67e74705SXin Li 
2162*67e74705SXin Li     Declarator ExDecl(DS, Declarator::CXXCatchContext);
2163*67e74705SXin Li     ParseDeclarator(ExDecl);
2164*67e74705SXin Li     ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2165*67e74705SXin Li   } else
2166*67e74705SXin Li     ConsumeToken();
2167*67e74705SXin Li 
2168*67e74705SXin Li   T.consumeClose();
2169*67e74705SXin Li   if (T.getCloseLocation().isInvalid())
2170*67e74705SXin Li     return StmtError();
2171*67e74705SXin Li 
2172*67e74705SXin Li   if (Tok.isNot(tok::l_brace))
2173*67e74705SXin Li     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2174*67e74705SXin Li 
2175*67e74705SXin Li   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2176*67e74705SXin Li   StmtResult Block(ParseCompoundStatement());
2177*67e74705SXin Li   if (Block.isInvalid())
2178*67e74705SXin Li     return Block;
2179*67e74705SXin Li 
2180*67e74705SXin Li   return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2181*67e74705SXin Li }
2182*67e74705SXin Li 
ParseMicrosoftIfExistsStatement(StmtVector & Stmts)2183*67e74705SXin Li void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2184*67e74705SXin Li   IfExistsCondition Result;
2185*67e74705SXin Li   if (ParseMicrosoftIfExistsCondition(Result))
2186*67e74705SXin Li     return;
2187*67e74705SXin Li 
2188*67e74705SXin Li   // Handle dependent statements by parsing the braces as a compound statement.
2189*67e74705SXin Li   // This is not the same behavior as Visual C++, which don't treat this as a
2190*67e74705SXin Li   // compound statement, but for Clang's type checking we can't have anything
2191*67e74705SXin Li   // inside these braces escaping to the surrounding code.
2192*67e74705SXin Li   if (Result.Behavior == IEB_Dependent) {
2193*67e74705SXin Li     if (!Tok.is(tok::l_brace)) {
2194*67e74705SXin Li       Diag(Tok, diag::err_expected) << tok::l_brace;
2195*67e74705SXin Li       return;
2196*67e74705SXin Li     }
2197*67e74705SXin Li 
2198*67e74705SXin Li     StmtResult Compound = ParseCompoundStatement();
2199*67e74705SXin Li     if (Compound.isInvalid())
2200*67e74705SXin Li       return;
2201*67e74705SXin Li 
2202*67e74705SXin Li     StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2203*67e74705SXin Li                                                               Result.IsIfExists,
2204*67e74705SXin Li                                                               Result.SS,
2205*67e74705SXin Li                                                               Result.Name,
2206*67e74705SXin Li                                                               Compound.get());
2207*67e74705SXin Li     if (DepResult.isUsable())
2208*67e74705SXin Li       Stmts.push_back(DepResult.get());
2209*67e74705SXin Li     return;
2210*67e74705SXin Li   }
2211*67e74705SXin Li 
2212*67e74705SXin Li   BalancedDelimiterTracker Braces(*this, tok::l_brace);
2213*67e74705SXin Li   if (Braces.consumeOpen()) {
2214*67e74705SXin Li     Diag(Tok, diag::err_expected) << tok::l_brace;
2215*67e74705SXin Li     return;
2216*67e74705SXin Li   }
2217*67e74705SXin Li 
2218*67e74705SXin Li   switch (Result.Behavior) {
2219*67e74705SXin Li   case IEB_Parse:
2220*67e74705SXin Li     // Parse the statements below.
2221*67e74705SXin Li     break;
2222*67e74705SXin Li 
2223*67e74705SXin Li   case IEB_Dependent:
2224*67e74705SXin Li     llvm_unreachable("Dependent case handled above");
2225*67e74705SXin Li 
2226*67e74705SXin Li   case IEB_Skip:
2227*67e74705SXin Li     Braces.skipToEnd();
2228*67e74705SXin Li     return;
2229*67e74705SXin Li   }
2230*67e74705SXin Li 
2231*67e74705SXin Li   // Condition is true, parse the statements.
2232*67e74705SXin Li   while (Tok.isNot(tok::r_brace)) {
2233*67e74705SXin Li     StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2234*67e74705SXin Li     if (R.isUsable())
2235*67e74705SXin Li       Stmts.push_back(R.get());
2236*67e74705SXin Li   }
2237*67e74705SXin Li   Braces.consumeClose();
2238*67e74705SXin Li }
2239*67e74705SXin Li 
ParseOpenCLUnrollHintAttribute(ParsedAttributes & Attrs)2240*67e74705SXin Li bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2241*67e74705SXin Li   MaybeParseGNUAttributes(Attrs);
2242*67e74705SXin Li 
2243*67e74705SXin Li   if (Attrs.empty())
2244*67e74705SXin Li     return true;
2245*67e74705SXin Li 
2246*67e74705SXin Li   if (Attrs.getList()->getKind() != AttributeList::AT_OpenCLUnrollHint)
2247*67e74705SXin Li     return true;
2248*67e74705SXin Li 
2249*67e74705SXin Li   if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2250*67e74705SXin Li     Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
2251*67e74705SXin Li     return false;
2252*67e74705SXin Li   }
2253*67e74705SXin Li   return true;
2254*67e74705SXin Li }
2255