1//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Statement and Block portions of the Parser
10// interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/PrettyDeclStackTrace.h"
15#include "clang/Basic/Attributes.h"
16#include "clang/Basic/PrettyStackTrace.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Basic/TokenKinds.h"
19#include "clang/Parse/LoopHint.h"
20#include "clang/Parse/Parser.h"
21#include "clang/Parse/RAIIObjectsForParser.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/EnterExpressionEvaluationContext.h"
24#include "clang/Sema/Scope.h"
25#include "clang/Sema/SemaCodeCompletion.h"
26#include "clang/Sema/SemaObjC.h"
27#include "clang/Sema/SemaOpenACC.h"
28#include "clang/Sema/SemaOpenMP.h"
29#include "clang/Sema/TypoCorrection.h"
30#include "llvm/ADT/STLExtras.h"
31#include <optional>
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// C99 6.8: Statements and Blocks.
37//===----------------------------------------------------------------------===//
38
39StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
40 ParsedStmtContext StmtCtx) {
41 StmtResult Res;
42
43 // We may get back a null statement if we found a #pragma. Keep going until
44 // we get an actual statement.
45 StmtVector Stmts;
46 do {
47 Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
48 } while (!Res.isInvalid() && !Res.get());
49
50 return Res;
51}
52
53StmtResult
54Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
55 ParsedStmtContext StmtCtx,
56 SourceLocation *TrailingElseLoc) {
57
58 ParenBraceBracketBalancer BalancerRAIIObj(*this);
59
60 // Because we're parsing either a statement or a declaration, the order of
61 // attribute parsing is important. [[]] attributes at the start of a
62 // statement are different from [[]] attributes that follow an __attribute__
63 // at the start of the statement. Thus, we're not using MaybeParseAttributes
64 // here because we don't want to allow arbitrary orderings.
65 ParsedAttributes CXX11Attrs(AttrFactory);
66 bool HasStdAttr =
67 MaybeParseCXX11Attributes(Attrs&: CXX11Attrs, /*MightBeObjCMessageSend*/ OuterMightBeMessageSend: true);
68 ParsedAttributes GNUOrMSAttrs(AttrFactory);
69 if (getLangOpts().OpenCL)
70 MaybeParseGNUAttributes(Attrs&: GNUOrMSAttrs);
71
72 if (getLangOpts().HLSL)
73 MaybeParseMicrosoftAttributes(Attrs&: GNUOrMSAttrs);
74
75 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
76 Stmts, StmtCtx, TrailingElseLoc, DeclAttrs&: CXX11Attrs, DeclSpecAttrs&: GNUOrMSAttrs);
77 MaybeDestroyTemplateIds();
78
79 takeAndConcatenateAttrs(First&: CXX11Attrs, Second: std::move(GNUOrMSAttrs));
80
81 assert((CXX11Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
82 "attributes on empty statement");
83
84 if (HasStdAttr && getLangOpts().C23 &&
85 (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
86 ParsedStmtContext{} &&
87 isa_and_present<NullStmt>(Val: Res.get()))
88 Diag(Loc: CXX11Attrs.Range.getBegin(), DiagID: diag::warn_attr_in_secondary_block)
89 << CXX11Attrs.Range;
90
91 if (CXX11Attrs.empty() || Res.isInvalid())
92 return Res;
93
94 return Actions.ActOnAttributedStmt(AttrList: CXX11Attrs, SubStmt: Res.get());
95}
96
97namespace {
98class StatementFilterCCC final : public CorrectionCandidateCallback {
99public:
100 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
101 WantTypeSpecifiers = nextTok.isOneOf(Ks: tok::l_paren, Ks: tok::less, Ks: tok::l_square,
102 Ks: tok::identifier, Ks: tok::star, Ks: tok::amp);
103 WantExpressionKeywords =
104 nextTok.isOneOf(Ks: tok::l_paren, Ks: tok::identifier, Ks: tok::arrow, Ks: tok::period);
105 WantRemainingKeywords =
106 nextTok.isOneOf(Ks: tok::l_paren, Ks: tok::semi, Ks: tok::identifier, Ks: tok::l_brace);
107 WantCXXNamedCasts = false;
108 }
109
110 bool ValidateCandidate(const TypoCorrection &candidate) override {
111 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
112 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(Val: FD);
113 if (NextToken.is(K: tok::equal))
114 return candidate.getCorrectionDeclAs<VarDecl>();
115 if (NextToken.is(K: tok::period) &&
116 candidate.getCorrectionDeclAs<NamespaceDecl>())
117 return false;
118 return CorrectionCandidateCallback::ValidateCandidate(candidate);
119 }
120
121 std::unique_ptr<CorrectionCandidateCallback> clone() override {
122 return std::make_unique<StatementFilterCCC>(args&: *this);
123 }
124
125private:
126 Token NextToken;
127};
128}
129
130StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
131 StmtVector &Stmts, ParsedStmtContext StmtCtx,
132 SourceLocation *TrailingElseLoc, ParsedAttributes &CXX11Attrs,
133 ParsedAttributes &GNUAttrs) {
134 const char *SemiError = nullptr;
135 StmtResult Res;
136 SourceLocation GNUAttributeLoc;
137
138 // Cases in this switch statement should fall through if the parser expects
139 // the token to end in a semicolon (in which case SemiError should be set),
140 // or they directly 'return;' if not.
141Retry:
142 tok::TokenKind Kind = Tok.getKind();
143 SourceLocation AtLoc;
144 switch (Kind) {
145 case tok::at: // May be a @try or @throw statement
146 {
147 AtLoc = ConsumeToken(); // consume @
148 return ParseObjCAtStatement(atLoc: AtLoc, StmtCtx);
149 }
150
151 case tok::code_completion:
152 cutOffParsing();
153 Actions.CodeCompletion().CodeCompleteOrdinaryName(
154 S: getCurScope(), CompletionContext: SemaCodeCompletion::PCC_Statement);
155 return StmtError();
156
157 case tok::identifier:
158 ParseIdentifier: {
159 Token Next = NextToken();
160 if (Next.is(K: tok::colon)) { // C99 6.8.1: labeled-statement
161 // Both C++11 and GNU attributes preceding the label appertain to the
162 // label, so put them in a single list to pass on to
163 // ParseLabeledStatement().
164 takeAndConcatenateAttrs(First&: CXX11Attrs, Second: std::move(GNUAttrs));
165
166 // identifier ':' statement
167 return ParseLabeledStatement(Attrs&: CXX11Attrs, StmtCtx);
168 }
169
170 // Look up the identifier, and typo-correct it to a keyword if it's not
171 // found.
172 if (Next.isNot(K: tok::coloncolon)) {
173 // Try to limit which sets of keywords should be included in typo
174 // correction based on what the next token is.
175 StatementFilterCCC CCC(Next);
176 if (TryAnnotateName(CCC: &CCC) == AnnotatedNameKind::Error) {
177 // Handle errors here by skipping up to the next semicolon or '}', and
178 // eat the semicolon if that's what stopped us.
179 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
180 if (Tok.is(K: tok::semi))
181 ConsumeToken();
182 return StmtError();
183 }
184
185 // If the identifier was annotated, try again.
186 if (Tok.isNot(K: tok::identifier))
187 goto Retry;
188 }
189
190 // Fall through
191 [[fallthrough]];
192 }
193
194 default: {
195 if (getLangOpts().CPlusPlus && MaybeParseCXX11Attributes(Attrs&: CXX11Attrs, OuterMightBeMessageSend: true))
196 goto Retry;
197
198 bool HaveAttrs = !CXX11Attrs.empty() || !GNUAttrs.empty();
199 auto IsStmtAttr = [](ParsedAttr &Attr) { return Attr.isStmtAttr(); };
200 bool AllAttrsAreStmtAttrs = llvm::all_of(Range&: CXX11Attrs, P: IsStmtAttr) &&
201 llvm::all_of(Range&: GNUAttrs, P: IsStmtAttr);
202 // In C, the grammar production for statement (C23 6.8.1p1) does not allow
203 // for declarations, which is different from C++ (C++23 [stmt.pre]p1). So
204 // in C++, we always allow a declaration, but in C we need to check whether
205 // we're in a statement context that allows declarations. e.g., in C, the
206 // following is invalid: if (1) int x;
207 if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
208 (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
209 ParsedStmtContext()) &&
210 ((GNUAttributeLoc.isValid() && !(HaveAttrs && AllAttrsAreStmtAttrs)) ||
211 isDeclarationStatement())) {
212 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
213 DeclGroupPtrTy Decl;
214 if (GNUAttributeLoc.isValid()) {
215 DeclStart = GNUAttributeLoc;
216 Decl = ParseDeclaration(Context: DeclaratorContext::Block, DeclEnd, DeclAttrs&: CXX11Attrs,
217 DeclSpecAttrs&: GNUAttrs, DeclSpecStart: &GNUAttributeLoc);
218 } else {
219 Decl = ParseDeclaration(Context: DeclaratorContext::Block, DeclEnd, DeclAttrs&: CXX11Attrs,
220 DeclSpecAttrs&: GNUAttrs);
221 }
222 if (CXX11Attrs.Range.getBegin().isValid()) {
223 // Order of C++11 and GNU attributes is may be arbitrary.
224 DeclStart = GNUAttrs.Range.getBegin().isInvalid()
225 ? CXX11Attrs.Range.getBegin()
226 : std::min(a: CXX11Attrs.Range.getBegin(),
227 b: GNUAttrs.Range.getBegin());
228 } else if (GNUAttrs.Range.getBegin().isValid())
229 DeclStart = GNUAttrs.Range.getBegin();
230 return Actions.ActOnDeclStmt(Decl, StartLoc: DeclStart, EndLoc: DeclEnd);
231 }
232
233 if (Tok.is(K: tok::r_brace)) {
234 Diag(Tok, DiagID: diag::err_expected_statement);
235 return StmtError();
236 }
237
238 switch (Tok.getKind()) {
239#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
240#include "clang/Basic/TransformTypeTraits.def"
241 if (NextToken().is(K: tok::less)) {
242 Tok.setKind(tok::identifier);
243 Diag(Tok, DiagID: diag::ext_keyword_as_ident)
244 << Tok.getIdentifierInfo()->getName() << 0;
245 goto ParseIdentifier;
246 }
247 [[fallthrough]];
248 default:
249 return ParseExprStatement(StmtCtx);
250 }
251 }
252
253 case tok::kw___attribute: {
254 GNUAttributeLoc = Tok.getLocation();
255 ParseGNUAttributes(Attrs&: GNUAttrs);
256 goto Retry;
257 }
258
259 case tok::kw_template: {
260 SourceLocation DeclEnd;
261 ParseTemplateDeclarationOrSpecialization(Context: DeclaratorContext::Block, DeclEnd,
262 AS: getAccessSpecifierIfPresent());
263 return StmtError();
264 }
265
266 case tok::kw_case: // C99 6.8.1: labeled-statement
267 return ParseCaseStatement(StmtCtx);
268 case tok::kw_default: // C99 6.8.1: labeled-statement
269 return ParseDefaultStatement(StmtCtx);
270
271 case tok::l_brace: // C99 6.8.2: compound-statement
272 return ParseCompoundStatement();
273 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
274 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
275 return Actions.ActOnNullStmt(SemiLoc: ConsumeToken(), HasLeadingEmptyMacro);
276 }
277
278 case tok::kw_if: // C99 6.8.4.1: if-statement
279 return ParseIfStatement(TrailingElseLoc);
280 case tok::kw_switch: // C99 6.8.4.2: switch-statement
281 return ParseSwitchStatement(TrailingElseLoc);
282
283 case tok::kw_while: // C99 6.8.5.1: while-statement
284 return ParseWhileStatement(TrailingElseLoc);
285 case tok::kw_do: // C99 6.8.5.2: do-statement
286 Res = ParseDoStatement();
287 SemiError = "do/while";
288 break;
289 case tok::kw_for: // C99 6.8.5.3: for-statement
290 return ParseForStatement(TrailingElseLoc);
291
292 case tok::kw_goto: // C99 6.8.6.1: goto-statement
293 Res = ParseGotoStatement();
294 SemiError = "goto";
295 break;
296 case tok::kw_continue: // C99 6.8.6.2: continue-statement
297 Res = ParseContinueStatement();
298 SemiError = "continue";
299 break;
300 case tok::kw_break: // C99 6.8.6.3: break-statement
301 Res = ParseBreakStatement();
302 SemiError = "break";
303 break;
304 case tok::kw_return: // C99 6.8.6.4: return-statement
305 Res = ParseReturnStatement();
306 SemiError = "return";
307 break;
308 case tok::kw_co_return: // C++ Coroutines: co_return statement
309 Res = ParseReturnStatement();
310 SemiError = "co_return";
311 break;
312
313 case tok::kw_asm: {
314 for (const ParsedAttr &AL : CXX11Attrs)
315 // Could be relaxed if asm-related regular keyword attributes are
316 // added later.
317 (AL.isRegularKeywordAttribute()
318 ? Diag(Loc: AL.getRange().getBegin(), DiagID: diag::err_keyword_not_allowed)
319 : Diag(Loc: AL.getRange().getBegin(), DiagID: diag::warn_attribute_ignored))
320 << AL;
321 // Prevent these from being interpreted as statement attributes later on.
322 CXX11Attrs.clear();
323 ProhibitAttributes(Attrs&: GNUAttrs);
324 bool msAsm = false;
325 Res = ParseAsmStatement(msAsm);
326 if (msAsm) return Res;
327 SemiError = "asm";
328 break;
329 }
330
331 case tok::kw___if_exists:
332 case tok::kw___if_not_exists:
333 ProhibitAttributes(Attrs&: CXX11Attrs);
334 ProhibitAttributes(Attrs&: GNUAttrs);
335 ParseMicrosoftIfExistsStatement(Stmts);
336 // An __if_exists block is like a compound statement, but it doesn't create
337 // a new scope.
338 return StmtEmpty();
339
340 case tok::kw_try: // C++ 15: try-block
341 return ParseCXXTryBlock();
342
343 case tok::kw___try:
344 ProhibitAttributes(Attrs&: CXX11Attrs);
345 ProhibitAttributes(Attrs&: GNUAttrs);
346 return ParseSEHTryBlock();
347
348 case tok::kw___leave:
349 Res = ParseSEHLeaveStatement();
350 SemiError = "__leave";
351 break;
352
353 case tok::annot_pragma_vis:
354 ProhibitAttributes(Attrs&: CXX11Attrs);
355 ProhibitAttributes(Attrs&: GNUAttrs);
356 HandlePragmaVisibility();
357 return StmtEmpty();
358
359 case tok::annot_pragma_pack:
360 ProhibitAttributes(Attrs&: CXX11Attrs);
361 ProhibitAttributes(Attrs&: GNUAttrs);
362 HandlePragmaPack();
363 return StmtEmpty();
364
365 case tok::annot_pragma_msstruct:
366 ProhibitAttributes(Attrs&: CXX11Attrs);
367 ProhibitAttributes(Attrs&: GNUAttrs);
368 HandlePragmaMSStruct();
369 return StmtEmpty();
370
371 case tok::annot_pragma_align:
372 ProhibitAttributes(Attrs&: CXX11Attrs);
373 ProhibitAttributes(Attrs&: GNUAttrs);
374 HandlePragmaAlign();
375 return StmtEmpty();
376
377 case tok::annot_pragma_weak:
378 ProhibitAttributes(Attrs&: CXX11Attrs);
379 ProhibitAttributes(Attrs&: GNUAttrs);
380 HandlePragmaWeak();
381 return StmtEmpty();
382
383 case tok::annot_pragma_weakalias:
384 ProhibitAttributes(Attrs&: CXX11Attrs);
385 ProhibitAttributes(Attrs&: GNUAttrs);
386 HandlePragmaWeakAlias();
387 return StmtEmpty();
388
389 case tok::annot_pragma_redefine_extname:
390 ProhibitAttributes(Attrs&: CXX11Attrs);
391 ProhibitAttributes(Attrs&: GNUAttrs);
392 HandlePragmaRedefineExtname();
393 return StmtEmpty();
394
395 case tok::annot_pragma_fp_contract:
396 ProhibitAttributes(Attrs&: CXX11Attrs);
397 ProhibitAttributes(Attrs&: GNUAttrs);
398 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "fp_contract";
399 ConsumeAnnotationToken();
400 return StmtError();
401
402 case tok::annot_pragma_fp:
403 ProhibitAttributes(Attrs&: CXX11Attrs);
404 ProhibitAttributes(Attrs&: GNUAttrs);
405 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "clang fp";
406 ConsumeAnnotationToken();
407 return StmtError();
408
409 case tok::annot_pragma_fenv_access:
410 case tok::annot_pragma_fenv_access_ms:
411 ProhibitAttributes(Attrs&: CXX11Attrs);
412 ProhibitAttributes(Attrs&: GNUAttrs);
413 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope)
414 << (Kind == tok::annot_pragma_fenv_access ? "STDC FENV_ACCESS"
415 : "fenv_access");
416 ConsumeAnnotationToken();
417 return StmtEmpty();
418
419 case tok::annot_pragma_fenv_round:
420 ProhibitAttributes(Attrs&: CXX11Attrs);
421 ProhibitAttributes(Attrs&: GNUAttrs);
422 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "STDC FENV_ROUND";
423 ConsumeAnnotationToken();
424 return StmtError();
425
426 case tok::annot_pragma_cx_limited_range:
427 ProhibitAttributes(Attrs&: CXX11Attrs);
428 ProhibitAttributes(Attrs&: GNUAttrs);
429 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope)
430 << "STDC CX_LIMITED_RANGE";
431 ConsumeAnnotationToken();
432 return StmtError();
433
434 case tok::annot_pragma_float_control:
435 ProhibitAttributes(Attrs&: CXX11Attrs);
436 ProhibitAttributes(Attrs&: GNUAttrs);
437 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "float_control";
438 ConsumeAnnotationToken();
439 return StmtError();
440
441 case tok::annot_pragma_opencl_extension:
442 ProhibitAttributes(Attrs&: CXX11Attrs);
443 ProhibitAttributes(Attrs&: GNUAttrs);
444 HandlePragmaOpenCLExtension();
445 return StmtEmpty();
446
447 case tok::annot_pragma_captured:
448 ProhibitAttributes(Attrs&: CXX11Attrs);
449 ProhibitAttributes(Attrs&: GNUAttrs);
450 return HandlePragmaCaptured();
451
452 case tok::annot_pragma_openmp:
453 // Prohibit attributes that are not OpenMP attributes, but only before
454 // processing a #pragma omp clause.
455 ProhibitAttributes(Attrs&: CXX11Attrs);
456 ProhibitAttributes(Attrs&: GNUAttrs);
457 [[fallthrough]];
458 case tok::annot_attr_openmp:
459 // Do not prohibit attributes if they were OpenMP attributes.
460 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
461
462 case tok::annot_pragma_openacc:
463 return ParseOpenACCDirectiveStmt();
464
465 case tok::annot_pragma_ms_pointers_to_members:
466 ProhibitAttributes(Attrs&: CXX11Attrs);
467 ProhibitAttributes(Attrs&: GNUAttrs);
468 HandlePragmaMSPointersToMembers();
469 return StmtEmpty();
470
471 case tok::annot_pragma_ms_pragma:
472 ProhibitAttributes(Attrs&: CXX11Attrs);
473 ProhibitAttributes(Attrs&: GNUAttrs);
474 HandlePragmaMSPragma();
475 return StmtEmpty();
476
477 case tok::annot_pragma_ms_vtordisp:
478 ProhibitAttributes(Attrs&: CXX11Attrs);
479 ProhibitAttributes(Attrs&: GNUAttrs);
480 HandlePragmaMSVtorDisp();
481 return StmtEmpty();
482
483 case tok::annot_pragma_loop_hint:
484 ProhibitAttributes(Attrs&: CXX11Attrs);
485 ProhibitAttributes(Attrs&: GNUAttrs);
486 return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, Attrs&: CXX11Attrs);
487
488 case tok::annot_pragma_dump:
489 ProhibitAttributes(Attrs&: CXX11Attrs);
490 ProhibitAttributes(Attrs&: GNUAttrs);
491 HandlePragmaDump();
492 return StmtEmpty();
493
494 case tok::annot_pragma_attribute:
495 ProhibitAttributes(Attrs&: CXX11Attrs);
496 ProhibitAttributes(Attrs&: GNUAttrs);
497 HandlePragmaAttribute();
498 return StmtEmpty();
499 }
500
501 // If we reached this code, the statement must end in a semicolon.
502 if (!TryConsumeToken(Expected: tok::semi) && !Res.isInvalid()) {
503 // If the result was valid, then we do want to diagnose this. Use
504 // ExpectAndConsume to emit the diagnostic, even though we know it won't
505 // succeed.
506 ExpectAndConsume(ExpectedTok: tok::semi, Diag: diag::err_expected_semi_after_stmt, DiagMsg: SemiError);
507 // Skip until we see a } or ;, but don't eat it.
508 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
509 }
510
511 return Res;
512}
513
514StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
515 // If a case keyword is missing, this is where it should be inserted.
516 Token OldToken = Tok;
517
518 ExprStatementTokLoc = Tok.getLocation();
519
520 // expression[opt] ';'
521 ExprResult Expr(ParseExpression());
522 if (Expr.isInvalid()) {
523 // If the expression is invalid, skip ahead to the next semicolon or '}'.
524 // Not doing this opens us up to the possibility of infinite loops if
525 // ParseExpression does not consume any tokens.
526 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
527 if (Tok.is(K: tok::semi))
528 ConsumeToken();
529 return Actions.ActOnExprStmtError();
530 }
531
532 if (Tok.is(K: tok::colon) && getCurScope()->isSwitchScope() &&
533 Actions.CheckCaseExpression(E: Expr.get())) {
534 // If a constant expression is followed by a colon inside a switch block,
535 // suggest a missing case keyword.
536 Diag(Tok: OldToken, DiagID: diag::err_expected_case_before_expression)
537 << FixItHint::CreateInsertion(InsertionLoc: OldToken.getLocation(), Code: "case ");
538
539 // Recover parsing as a case statement.
540 return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
541 }
542
543 Token *CurTok = nullptr;
544 // Note we shouldn't eat the token since the callback needs it.
545 if (Tok.is(K: tok::annot_repl_input_end))
546 CurTok = &Tok;
547 else
548 // Otherwise, eat the semicolon.
549 ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_after_expr);
550
551 StmtResult R = handleExprStmt(E: Expr, StmtCtx);
552 if (CurTok && !R.isInvalid())
553 CurTok->setAnnotationValue(R.get());
554
555 return R;
556}
557
558StmtResult Parser::ParseSEHTryBlock() {
559 assert(Tok.is(tok::kw___try) && "Expected '__try'");
560 SourceLocation TryLoc = ConsumeToken();
561
562 if (Tok.isNot(K: tok::l_brace))
563 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
564
565 StmtResult TryBlock(ParseCompoundStatement(
566 /*isStmtExpr=*/false,
567 ScopeFlags: Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
568 if (TryBlock.isInvalid())
569 return TryBlock;
570
571 StmtResult Handler;
572 if (Tok.is(K: tok::identifier) &&
573 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
574 SourceLocation Loc = ConsumeToken();
575 Handler = ParseSEHExceptBlock(Loc);
576 } else if (Tok.is(K: tok::kw___finally)) {
577 SourceLocation Loc = ConsumeToken();
578 Handler = ParseSEHFinallyBlock(Loc);
579 } else {
580 return StmtError(Diag(Tok, DiagID: diag::err_seh_expected_handler));
581 }
582
583 if(Handler.isInvalid())
584 return Handler;
585
586 return Actions.ActOnSEHTryBlock(IsCXXTry: false /* IsCXXTry */,
587 TryLoc,
588 TryBlock: TryBlock.get(),
589 Handler: Handler.get());
590}
591
592StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
593 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
594 raii2(Ident___exception_code, false),
595 raii3(Ident_GetExceptionCode, false);
596
597 if (ExpectAndConsume(ExpectedTok: tok::l_paren))
598 return StmtError();
599
600 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
601 Scope::SEHExceptScope);
602
603 if (getLangOpts().Borland) {
604 Ident__exception_info->setIsPoisoned(false);
605 Ident___exception_info->setIsPoisoned(false);
606 Ident_GetExceptionInfo->setIsPoisoned(false);
607 }
608
609 ExprResult FilterExpr;
610 {
611 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
612 Scope::SEHFilterScope);
613 FilterExpr = ParseExpression();
614 }
615
616 if (getLangOpts().Borland) {
617 Ident__exception_info->setIsPoisoned(true);
618 Ident___exception_info->setIsPoisoned(true);
619 Ident_GetExceptionInfo->setIsPoisoned(true);
620 }
621
622 if(FilterExpr.isInvalid())
623 return StmtError();
624
625 if (ExpectAndConsume(ExpectedTok: tok::r_paren))
626 return StmtError();
627
628 if (Tok.isNot(K: tok::l_brace))
629 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
630
631 StmtResult Block(ParseCompoundStatement());
632
633 if(Block.isInvalid())
634 return Block;
635
636 return Actions.ActOnSEHExceptBlock(Loc: ExceptLoc, FilterExpr: FilterExpr.get(), Block: Block.get());
637}
638
639StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
640 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
641 raii2(Ident___abnormal_termination, false),
642 raii3(Ident_AbnormalTermination, false);
643
644 if (Tok.isNot(K: tok::l_brace))
645 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
646
647 ParseScope FinallyScope(this, 0);
648 Actions.ActOnStartSEHFinallyBlock();
649
650 StmtResult Block(ParseCompoundStatement());
651 if(Block.isInvalid()) {
652 Actions.ActOnAbortSEHFinallyBlock();
653 return Block;
654 }
655
656 return Actions.ActOnFinishSEHFinallyBlock(Loc: FinallyLoc, Block: Block.get());
657}
658
659/// Handle __leave
660///
661/// seh-leave-statement:
662/// '__leave' ';'
663///
664StmtResult Parser::ParseSEHLeaveStatement() {
665 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
666 return Actions.ActOnSEHLeaveStmt(Loc: LeaveLoc, CurScope: getCurScope());
667}
668
669static void DiagnoseLabelFollowedByDecl(Parser &P, const Stmt *SubStmt) {
670 // When in C mode (but not Microsoft extensions mode), diagnose use of a
671 // label that is followed by a declaration rather than a statement.
672 if (!P.getLangOpts().CPlusPlus && !P.getLangOpts().MicrosoftExt &&
673 isa<DeclStmt>(Val: SubStmt)) {
674 P.Diag(Loc: SubStmt->getBeginLoc(),
675 DiagID: P.getLangOpts().C23
676 ? diag::warn_c23_compat_label_followed_by_declaration
677 : diag::ext_c_label_followed_by_declaration);
678 }
679}
680
681StmtResult Parser::ParseLabeledStatement(ParsedAttributes &Attrs,
682 ParsedStmtContext StmtCtx) {
683 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
684 "Not an identifier!");
685
686 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
687 // substatement in a selection statement, in place of the loop body in an
688 // iteration statement, or in place of the statement that follows a label.
689 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
690
691 Token IdentTok = Tok; // Save the whole token.
692 ConsumeToken(); // eat the identifier.
693
694 assert(Tok.is(tok::colon) && "Not a label!");
695
696 // identifier ':' statement
697 SourceLocation ColonLoc = ConsumeToken();
698
699 // Read label attributes, if present.
700 StmtResult SubStmt;
701 if (Tok.is(K: tok::kw___attribute)) {
702 ParsedAttributes TempAttrs(AttrFactory);
703 ParseGNUAttributes(Attrs&: TempAttrs);
704
705 // In C++, GNU attributes only apply to the label if they are followed by a
706 // semicolon, to disambiguate label attributes from attributes on a labeled
707 // declaration.
708 //
709 // This doesn't quite match what GCC does; if the attribute list is empty
710 // and followed by a semicolon, GCC will reject (it appears to parse the
711 // attributes as part of a statement in that case). That looks like a bug.
712 if (!getLangOpts().CPlusPlus || Tok.is(K: tok::semi))
713 Attrs.takeAllFrom(Other&: TempAttrs);
714 else {
715 StmtVector Stmts;
716 ParsedAttributes EmptyCXX11Attrs(AttrFactory);
717 SubStmt = ParseStatementOrDeclarationAfterAttributes(
718 Stmts, StmtCtx, TrailingElseLoc: nullptr, CXX11Attrs&: EmptyCXX11Attrs, GNUAttrs&: TempAttrs);
719 if (!TempAttrs.empty() && !SubStmt.isInvalid())
720 SubStmt = Actions.ActOnAttributedStmt(AttrList: TempAttrs, SubStmt: SubStmt.get());
721 }
722 }
723
724 // The label may have no statement following it
725 if (SubStmt.isUnset() && Tok.is(K: tok::r_brace)) {
726 DiagnoseLabelAtEndOfCompoundStatement();
727 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
728 }
729
730 // If we've not parsed a statement yet, parse one now.
731 if (SubStmt.isUnset())
732 SubStmt = ParseStatement(TrailingElseLoc: nullptr, StmtCtx);
733
734 // Broken substmt shouldn't prevent the label from being added to the AST.
735 if (SubStmt.isInvalid())
736 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
737
738 DiagnoseLabelFollowedByDecl(P&: *this, SubStmt: SubStmt.get());
739
740 LabelDecl *LD = Actions.LookupOrCreateLabel(II: IdentTok.getIdentifierInfo(),
741 IdentLoc: IdentTok.getLocation());
742 Actions.ProcessDeclAttributeList(S: Actions.CurScope, D: LD, AttrList: Attrs);
743 Attrs.clear();
744
745 return Actions.ActOnLabelStmt(IdentLoc: IdentTok.getLocation(), TheDecl: LD, ColonLoc,
746 SubStmt: SubStmt.get());
747}
748
749StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
750 bool MissingCase, ExprResult Expr) {
751 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
752
753 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
754 // substatement in a selection statement, in place of the loop body in an
755 // iteration statement, or in place of the statement that follows a label.
756 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
757
758 // It is very common for code to contain many case statements recursively
759 // nested, as in (but usually without indentation):
760 // case 1:
761 // case 2:
762 // case 3:
763 // case 4:
764 // case 5: etc.
765 //
766 // Parsing this naively works, but is both inefficient and can cause us to run
767 // out of stack space in our recursive descent parser. As a special case,
768 // flatten this recursion into an iterative loop. This is complex and gross,
769 // but all the grossness is constrained to ParseCaseStatement (and some
770 // weirdness in the actions), so this is just local grossness :).
771
772 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
773 // example above.
774 StmtResult TopLevelCase(true);
775
776 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
777 // gets updated each time a new case is parsed, and whose body is unset so
778 // far. When parsing 'case 4', this is the 'case 3' node.
779 Stmt *DeepestParsedCaseStmt = nullptr;
780
781 // While we have case statements, eat and stack them.
782 SourceLocation ColonLoc;
783 do {
784 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
785 ConsumeToken(); // eat the 'case'.
786 ColonLoc = SourceLocation();
787
788 if (Tok.is(K: tok::code_completion)) {
789 cutOffParsing();
790 Actions.CodeCompletion().CodeCompleteCase(S: getCurScope());
791 return StmtError();
792 }
793
794 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
795 /// Disable this form of error recovery while we're parsing the case
796 /// expression.
797 ColonProtectionRAIIObject ColonProtection(*this);
798
799 ExprResult LHS;
800 if (!MissingCase) {
801 LHS = ParseCaseExpression(CaseLoc);
802 if (LHS.isInvalid()) {
803 // If constant-expression is parsed unsuccessfully, recover by skipping
804 // current case statement (moving to the colon that ends it).
805 if (!SkipUntil(T1: tok::colon, T2: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch))
806 return StmtError();
807 }
808 } else {
809 LHS = Expr;
810 MissingCase = false;
811 }
812
813 // GNU case range extension.
814 SourceLocation DotDotDotLoc;
815 ExprResult RHS;
816 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: DotDotDotLoc)) {
817 // In C++, this is a GNU extension. In C, it's a C2y extension.
818 unsigned DiagId;
819 if (getLangOpts().CPlusPlus)
820 DiagId = diag::ext_gnu_case_range;
821 else if (getLangOpts().C2y)
822 DiagId = diag::warn_c23_compat_case_range;
823 else
824 DiagId = diag::ext_c2y_case_range;
825 Diag(Loc: DotDotDotLoc, DiagID: DiagId);
826 RHS = ParseCaseExpression(CaseLoc);
827 if (RHS.isInvalid()) {
828 if (!SkipUntil(T1: tok::colon, T2: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch))
829 return StmtError();
830 }
831 }
832
833 ColonProtection.restore();
834
835 if (TryConsumeToken(Expected: tok::colon, Loc&: ColonLoc)) {
836 } else if (TryConsumeToken(Expected: tok::semi, Loc&: ColonLoc) ||
837 TryConsumeToken(Expected: tok::coloncolon, Loc&: ColonLoc)) {
838 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
839 Diag(Loc: ColonLoc, DiagID: diag::err_expected_after)
840 << "'case'" << tok::colon
841 << FixItHint::CreateReplacement(RemoveRange: ColonLoc, Code: ":");
842 } else {
843 SourceLocation ExpectedLoc = getEndOfPreviousToken();
844
845 Diag(Loc: ExpectedLoc, DiagID: diag::err_expected_after)
846 << "'case'" << tok::colon
847 << FixItHint::CreateInsertion(InsertionLoc: ExpectedLoc, Code: ":");
848
849 ColonLoc = ExpectedLoc;
850 }
851
852 StmtResult Case =
853 Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
854
855 // If we had a sema error parsing this case, then just ignore it and
856 // continue parsing the sub-stmt.
857 if (Case.isInvalid()) {
858 if (TopLevelCase.isInvalid()) // No parsed case stmts.
859 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
860 // Otherwise, just don't add it as a nested case.
861 } else {
862 // If this is the first case statement we parsed, it becomes TopLevelCase.
863 // Otherwise we link it into the current chain.
864 Stmt *NextDeepest = Case.get();
865 if (TopLevelCase.isInvalid())
866 TopLevelCase = Case;
867 else
868 Actions.ActOnCaseStmtBody(CaseStmt: DeepestParsedCaseStmt, SubStmt: Case.get());
869 DeepestParsedCaseStmt = NextDeepest;
870 }
871
872 // Handle all case statements.
873 } while (Tok.is(K: tok::kw_case));
874
875 // If we found a non-case statement, start by parsing it.
876 StmtResult SubStmt;
877
878 if (Tok.is(K: tok::r_brace)) {
879 // "switch (X) { case 4: }", is valid and is treated as if label was
880 // followed by a null statement.
881 DiagnoseLabelAtEndOfCompoundStatement();
882 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
883 } else {
884 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
885 }
886
887 // Install the body into the most deeply-nested case.
888 if (DeepestParsedCaseStmt) {
889 // Broken sub-stmt shouldn't prevent forming the case statement properly.
890 if (SubStmt.isInvalid())
891 SubStmt = Actions.ActOnNullStmt(SemiLoc: SourceLocation());
892 DiagnoseLabelFollowedByDecl(P&: *this, SubStmt: SubStmt.get());
893 Actions.ActOnCaseStmtBody(CaseStmt: DeepestParsedCaseStmt, SubStmt: SubStmt.get());
894 }
895
896 // Return the top level parsed statement tree.
897 return TopLevelCase;
898}
899
900StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
901 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
902
903 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
904 // substatement in a selection statement, in place of the loop body in an
905 // iteration statement, or in place of the statement that follows a label.
906 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
907
908 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
909
910 SourceLocation ColonLoc;
911 if (TryConsumeToken(Expected: tok::colon, Loc&: ColonLoc)) {
912 } else if (TryConsumeToken(Expected: tok::semi, Loc&: ColonLoc)) {
913 // Treat "default;" as a typo for "default:".
914 Diag(Loc: ColonLoc, DiagID: diag::err_expected_after)
915 << "'default'" << tok::colon
916 << FixItHint::CreateReplacement(RemoveRange: ColonLoc, Code: ":");
917 } else {
918 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(Loc: PrevTokLocation);
919 Diag(Loc: ExpectedLoc, DiagID: diag::err_expected_after)
920 << "'default'" << tok::colon
921 << FixItHint::CreateInsertion(InsertionLoc: ExpectedLoc, Code: ":");
922 ColonLoc = ExpectedLoc;
923 }
924
925 StmtResult SubStmt;
926
927 if (Tok.is(K: tok::r_brace)) {
928 // "switch (X) {... default: }", is valid and is treated as if label was
929 // followed by a null statement.
930 DiagnoseLabelAtEndOfCompoundStatement();
931 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
932 } else {
933 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
934 }
935
936 // Broken sub-stmt shouldn't prevent forming the case statement properly.
937 if (SubStmt.isInvalid())
938 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
939
940 DiagnoseLabelFollowedByDecl(P&: *this, SubStmt: SubStmt.get());
941 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
942 SubStmt: SubStmt.get(), CurScope: getCurScope());
943}
944
945StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
946 return ParseCompoundStatement(isStmtExpr,
947 ScopeFlags: Scope::DeclScope | Scope::CompoundStmtScope);
948}
949
950StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
951 unsigned ScopeFlags) {
952 assert(Tok.is(tok::l_brace) && "Not a compound stmt!");
953
954 // Enter a scope to hold everything within the compound stmt. Compound
955 // statements can always hold declarations.
956 ParseScope CompoundScope(this, ScopeFlags);
957
958 // Parse the statements in the body.
959 StmtResult R;
960 StackHandler.runWithSufficientStackSpace(Loc: Tok.getLocation(), Fn: [&, this]() {
961 R = ParseCompoundStatementBody(isStmtExpr);
962 });
963 return R;
964}
965
966void Parser::ParseCompoundStatementLeadingPragmas() {
967 bool checkForPragmas = true;
968 while (checkForPragmas) {
969 switch (Tok.getKind()) {
970 case tok::annot_pragma_vis:
971 HandlePragmaVisibility();
972 break;
973 case tok::annot_pragma_pack:
974 HandlePragmaPack();
975 break;
976 case tok::annot_pragma_msstruct:
977 HandlePragmaMSStruct();
978 break;
979 case tok::annot_pragma_align:
980 HandlePragmaAlign();
981 break;
982 case tok::annot_pragma_weak:
983 HandlePragmaWeak();
984 break;
985 case tok::annot_pragma_weakalias:
986 HandlePragmaWeakAlias();
987 break;
988 case tok::annot_pragma_redefine_extname:
989 HandlePragmaRedefineExtname();
990 break;
991 case tok::annot_pragma_opencl_extension:
992 HandlePragmaOpenCLExtension();
993 break;
994 case tok::annot_pragma_fp_contract:
995 HandlePragmaFPContract();
996 break;
997 case tok::annot_pragma_fp:
998 HandlePragmaFP();
999 break;
1000 case tok::annot_pragma_fenv_access:
1001 case tok::annot_pragma_fenv_access_ms:
1002 HandlePragmaFEnvAccess();
1003 break;
1004 case tok::annot_pragma_fenv_round:
1005 HandlePragmaFEnvRound();
1006 break;
1007 case tok::annot_pragma_cx_limited_range:
1008 HandlePragmaCXLimitedRange();
1009 break;
1010 case tok::annot_pragma_float_control:
1011 HandlePragmaFloatControl();
1012 break;
1013 case tok::annot_pragma_ms_pointers_to_members:
1014 HandlePragmaMSPointersToMembers();
1015 break;
1016 case tok::annot_pragma_ms_pragma:
1017 HandlePragmaMSPragma();
1018 break;
1019 case tok::annot_pragma_ms_vtordisp:
1020 HandlePragmaMSVtorDisp();
1021 break;
1022 case tok::annot_pragma_dump:
1023 HandlePragmaDump();
1024 break;
1025 default:
1026 checkForPragmas = false;
1027 break;
1028 }
1029 }
1030
1031}
1032
1033void Parser::DiagnoseLabelAtEndOfCompoundStatement() {
1034 if (getLangOpts().CPlusPlus) {
1035 Diag(Tok, DiagID: getLangOpts().CPlusPlus23
1036 ? diag::warn_cxx20_compat_label_end_of_compound_statement
1037 : diag::ext_cxx_label_end_of_compound_statement);
1038 } else {
1039 Diag(Tok, DiagID: getLangOpts().C23
1040 ? diag::warn_c23_compat_label_end_of_compound_statement
1041 : diag::ext_c_label_end_of_compound_statement);
1042 }
1043}
1044
1045bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
1046 if (!Tok.is(K: tok::semi))
1047 return false;
1048
1049 SourceLocation StartLoc = Tok.getLocation();
1050 SourceLocation EndLoc;
1051
1052 while (Tok.is(K: tok::semi) && !Tok.hasLeadingEmptyMacro() &&
1053 Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
1054 EndLoc = Tok.getLocation();
1055
1056 // Don't just ConsumeToken() this tok::semi, do store it in AST.
1057 StmtResult R =
1058 ParseStatementOrDeclaration(Stmts, StmtCtx: ParsedStmtContext::SubStmt);
1059 if (R.isUsable())
1060 Stmts.push_back(Elt: R.get());
1061 }
1062
1063 // Did not consume any extra semi.
1064 if (EndLoc.isInvalid())
1065 return false;
1066
1067 Diag(Loc: StartLoc, DiagID: diag::warn_null_statement)
1068 << FixItHint::CreateRemoval(RemoveRange: SourceRange(StartLoc, EndLoc));
1069 return true;
1070}
1071
1072StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
1073 bool IsStmtExprResult = false;
1074 if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
1075 // For GCC compatibility we skip past NullStmts.
1076 unsigned LookAhead = 0;
1077 while (GetLookAheadToken(N: LookAhead).is(K: tok::semi)) {
1078 ++LookAhead;
1079 }
1080 // Then look to see if the next two tokens close the statement expression;
1081 // if so, this expression statement is the last statement in a statement
1082 // expression.
1083 IsStmtExprResult = GetLookAheadToken(N: LookAhead).is(K: tok::r_brace) &&
1084 GetLookAheadToken(N: LookAhead + 1).is(K: tok::r_paren);
1085 }
1086
1087 if (IsStmtExprResult)
1088 E = Actions.ActOnStmtExprResult(E);
1089 return Actions.ActOnExprStmt(Arg: E, /*DiscardedValue=*/!IsStmtExprResult);
1090}
1091
1092StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
1093 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
1094 Tok.getLocation(),
1095 "in compound statement ('{}')");
1096
1097 // Record the current FPFeatures, restore on leaving the
1098 // compound statement.
1099 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1100
1101 InMessageExpressionRAIIObject InMessage(*this, false);
1102 BalancedDelimiterTracker T(*this, tok::l_brace);
1103 if (T.consumeOpen())
1104 return StmtError();
1105
1106 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
1107
1108 // Parse any pragmas at the beginning of the compound statement.
1109 ParseCompoundStatementLeadingPragmas();
1110 Actions.ActOnAfterCompoundStatementLeadingPragmas();
1111
1112 StmtVector Stmts;
1113
1114 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1115 // only allowed at the start of a compound stmt regardless of the language.
1116 while (Tok.is(K: tok::kw___label__)) {
1117 SourceLocation LabelLoc = ConsumeToken();
1118
1119 SmallVector<Decl *, 4> DeclsInGroup;
1120 while (true) {
1121 if (Tok.isNot(K: tok::identifier)) {
1122 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
1123 break;
1124 }
1125
1126 IdentifierInfo *II = Tok.getIdentifierInfo();
1127 SourceLocation IdLoc = ConsumeToken();
1128 DeclsInGroup.push_back(Elt: Actions.LookupOrCreateLabel(II, IdentLoc: IdLoc, GnuLabelLoc: LabelLoc));
1129
1130 if (!TryConsumeToken(Expected: tok::comma))
1131 break;
1132 }
1133
1134 DeclSpec DS(AttrFactory);
1135 DeclGroupPtrTy Res =
1136 Actions.FinalizeDeclaratorGroup(S: getCurScope(), DS, Group: DeclsInGroup);
1137 StmtResult R = Actions.ActOnDeclStmt(Decl: Res, StartLoc: LabelLoc, EndLoc: Tok.getLocation());
1138
1139 ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_declaration);
1140 if (R.isUsable())
1141 Stmts.push_back(Elt: R.get());
1142 }
1143
1144 ParsedStmtContext SubStmtCtx =
1145 ParsedStmtContext::Compound |
1146 (isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
1147
1148 bool LastIsError = false;
1149 while (!tryParseMisplacedModuleImport() && Tok.isNot(K: tok::r_brace) &&
1150 Tok.isNot(K: tok::eof)) {
1151 if (Tok.is(K: tok::annot_pragma_unused)) {
1152 HandlePragmaUnused();
1153 continue;
1154 }
1155
1156 if (ConsumeNullStmt(Stmts))
1157 continue;
1158
1159 StmtResult R;
1160 if (Tok.isNot(K: tok::kw___extension__)) {
1161 R = ParseStatementOrDeclaration(Stmts, StmtCtx: SubStmtCtx);
1162 } else {
1163 // __extension__ can start declarations and it can also be a unary
1164 // operator for expressions. Consume multiple __extension__ markers here
1165 // until we can determine which is which.
1166 // FIXME: This loses extension expressions in the AST!
1167 SourceLocation ExtLoc = ConsumeToken();
1168 while (Tok.is(K: tok::kw___extension__))
1169 ConsumeToken();
1170
1171 ParsedAttributes attrs(AttrFactory);
1172 MaybeParseCXX11Attributes(Attrs&: attrs, /*MightBeObjCMessageSend*/ OuterMightBeMessageSend: true);
1173
1174 // If this is the start of a declaration, parse it as such.
1175 if (isDeclarationStatement()) {
1176 // __extension__ silences extension warnings in the subdeclaration.
1177 // FIXME: Save the __extension__ on the decl as a node somehow?
1178 ExtensionRAIIObject O(Diags);
1179
1180 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1181 ParsedAttributes DeclSpecAttrs(AttrFactory);
1182 DeclGroupPtrTy Res = ParseDeclaration(Context: DeclaratorContext::Block, DeclEnd,
1183 DeclAttrs&: attrs, DeclSpecAttrs);
1184 R = Actions.ActOnDeclStmt(Decl: Res, StartLoc: DeclStart, EndLoc: DeclEnd);
1185 } else {
1186 // Otherwise this was a unary __extension__ marker.
1187 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1188
1189 if (Res.isInvalid()) {
1190 SkipUntil(T: tok::semi);
1191 continue;
1192 }
1193
1194 // Eat the semicolon at the end of stmt and convert the expr into a
1195 // statement.
1196 ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_after_expr);
1197 R = handleExprStmt(E: Res, StmtCtx: SubStmtCtx);
1198 if (R.isUsable())
1199 R = Actions.ActOnAttributedStmt(AttrList: attrs, SubStmt: R.get());
1200 }
1201 }
1202
1203 if (R.isUsable())
1204 Stmts.push_back(Elt: R.get());
1205 LastIsError = R.isInvalid();
1206 }
1207 // StmtExpr needs to do copy initialization for last statement.
1208 // If last statement is invalid, the last statement in `Stmts` will be
1209 // incorrect. Then the whole compound statement should also be marked as
1210 // invalid to prevent subsequent errors.
1211 if (isStmtExpr && LastIsError && !Stmts.empty())
1212 return StmtError();
1213
1214 // Warn the user that using option `-ffp-eval-method=source` on a
1215 // 32-bit target and feature `sse` disabled, or using
1216 // `pragma clang fp eval_method=source` and feature `sse` disabled, is not
1217 // supported.
1218 if (!PP.getTargetInfo().supportSourceEvalMethod() &&
1219 (PP.getLastFPEvalPragmaLocation().isValid() ||
1220 PP.getCurrentFPEvalMethod() ==
1221 LangOptions::FPEvalMethodKind::FEM_Source))
1222 Diag(Loc: Tok.getLocation(),
1223 DiagID: diag::warn_no_support_for_eval_method_source_on_m32);
1224
1225 SourceLocation CloseLoc = Tok.getLocation();
1226
1227 // We broke out of the while loop because we found a '}' or EOF.
1228 if (!T.consumeClose()) {
1229 // If this is the '})' of a statement expression, check that it's written
1230 // in a sensible way.
1231 if (isStmtExpr && Tok.is(K: tok::r_paren))
1232 checkCompoundToken(FirstTokLoc: CloseLoc, FirstTokKind: tok::r_brace, Op: CompoundToken::StmtExprEnd);
1233 } else {
1234 // Recover by creating a compound statement with what we parsed so far,
1235 // instead of dropping everything and returning StmtError().
1236 }
1237
1238 if (T.getCloseLocation().isValid())
1239 CloseLoc = T.getCloseLocation();
1240
1241 return Actions.ActOnCompoundStmt(L: T.getOpenLocation(), R: CloseLoc,
1242 Elts: Stmts, isStmtExpr);
1243}
1244
1245bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1246 Sema::ConditionResult &Cond,
1247 SourceLocation Loc,
1248 Sema::ConditionKind CK,
1249 SourceLocation &LParenLoc,
1250 SourceLocation &RParenLoc) {
1251 BalancedDelimiterTracker T(*this, tok::l_paren);
1252 T.consumeOpen();
1253 SourceLocation Start = Tok.getLocation();
1254
1255 if (getLangOpts().CPlusPlus) {
1256 Cond = ParseCXXCondition(InitStmt, Loc, CK, MissingOK: false);
1257 } else {
1258 ExprResult CondExpr = ParseExpression();
1259
1260 // If required, convert to a boolean value.
1261 if (CondExpr.isInvalid())
1262 Cond = Sema::ConditionError();
1263 else
1264 Cond = Actions.ActOnCondition(S: getCurScope(), Loc, SubExpr: CondExpr.get(), CK,
1265 /*MissingOK=*/false);
1266 }
1267
1268 // If the parser was confused by the condition and we don't have a ')', try to
1269 // recover by skipping ahead to a semi and bailing out. If condexp is
1270 // semantically invalid but we have well formed code, keep going.
1271 if (Cond.isInvalid() && Tok.isNot(K: tok::r_paren)) {
1272 SkipUntil(T: tok::semi);
1273 // Skipping may have stopped if it found the containing ')'. If so, we can
1274 // continue parsing the if statement.
1275 if (Tok.isNot(K: tok::r_paren))
1276 return true;
1277 }
1278
1279 if (Cond.isInvalid()) {
1280 ExprResult CondExpr = Actions.CreateRecoveryExpr(
1281 Begin: Start, End: Tok.getLocation() == Start ? Start : PrevTokLocation, SubExprs: {},
1282 T: Actions.PreferredConditionType(K: CK));
1283 if (!CondExpr.isInvalid())
1284 Cond = Actions.ActOnCondition(S: getCurScope(), Loc, SubExpr: CondExpr.get(), CK,
1285 /*MissingOK=*/false);
1286 }
1287
1288 // Either the condition is valid or the rparen is present.
1289 T.consumeClose();
1290 LParenLoc = T.getOpenLocation();
1291 RParenLoc = T.getCloseLocation();
1292
1293 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1294 // that all callers are looking for a statement after the condition, so ")"
1295 // isn't valid.
1296 while (Tok.is(K: tok::r_paren)) {
1297 Diag(Tok, DiagID: diag::err_extraneous_rparen_in_condition)
1298 << FixItHint::CreateRemoval(RemoveRange: Tok.getLocation());
1299 ConsumeParen();
1300 }
1301
1302 return false;
1303}
1304
1305namespace {
1306
1307enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
1308
1309struct MisleadingIndentationChecker {
1310 Parser &P;
1311 SourceLocation StmtLoc;
1312 SourceLocation PrevLoc;
1313 unsigned NumDirectives;
1314 MisleadingStatementKind Kind;
1315 bool ShouldSkip;
1316 MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
1317 SourceLocation SL)
1318 : P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),
1319 NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),
1320 ShouldSkip(P.getCurToken().is(K: tok::l_brace)) {
1321 if (!P.MisleadingIndentationElseLoc.isInvalid()) {
1322 StmtLoc = P.MisleadingIndentationElseLoc;
1323 P.MisleadingIndentationElseLoc = SourceLocation();
1324 }
1325 if (Kind == MSK_else && !ShouldSkip)
1326 P.MisleadingIndentationElseLoc = SL;
1327 }
1328
1329 /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1330 /// gives the visual indentation of the SourceLocation.
1331 static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {
1332 unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;
1333
1334 unsigned ColNo = SM.getSpellingColumnNumber(Loc);
1335 if (ColNo == 0 || TabStop == 1)
1336 return ColNo;
1337
1338 FileIDAndOffset FIDAndOffset = SM.getDecomposedLoc(Loc);
1339
1340 bool Invalid;
1341 StringRef BufData = SM.getBufferData(FID: FIDAndOffset.first, Invalid: &Invalid);
1342 if (Invalid)
1343 return 0;
1344
1345 const char *EndPos = BufData.data() + FIDAndOffset.second;
1346 // FileOffset are 0-based and Column numbers are 1-based
1347 assert(FIDAndOffset.second + 1 >= ColNo &&
1348 "Column number smaller than file offset?");
1349
1350 unsigned VisualColumn = 0; // Stored as 0-based column, here.
1351 // Loop from beginning of line up to Loc's file position, counting columns,
1352 // expanding tabs.
1353 for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
1354 ++CurPos) {
1355 if (*CurPos == '\t')
1356 // Advance visual column to next tabstop.
1357 VisualColumn += (TabStop - VisualColumn % TabStop);
1358 else
1359 VisualColumn++;
1360 }
1361 return VisualColumn + 1;
1362 }
1363
1364 void Check() {
1365 Token Tok = P.getCurToken();
1366 if (P.getActions().getDiagnostics().isIgnored(
1367 DiagID: diag::warn_misleading_indentation, Loc: Tok.getLocation()) ||
1368 ShouldSkip || NumDirectives != P.getPreprocessor().getNumDirectives() ||
1369 Tok.isOneOf(Ks: tok::semi, Ks: tok::r_brace) || Tok.isAnnotation() ||
1370 Tok.getLocation().isMacroID() || PrevLoc.isMacroID() ||
1371 StmtLoc.isMacroID() ||
1372 (Kind == MSK_else && P.MisleadingIndentationElseLoc.isInvalid())) {
1373 P.MisleadingIndentationElseLoc = SourceLocation();
1374 return;
1375 }
1376 if (Kind == MSK_else)
1377 P.MisleadingIndentationElseLoc = SourceLocation();
1378
1379 SourceManager &SM = P.getPreprocessor().getSourceManager();
1380 unsigned PrevColNum = getVisualIndentation(SM, Loc: PrevLoc);
1381 unsigned CurColNum = getVisualIndentation(SM, Loc: Tok.getLocation());
1382 unsigned StmtColNum = getVisualIndentation(SM, Loc: StmtLoc);
1383
1384 if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&
1385 ((PrevColNum > StmtColNum && PrevColNum == CurColNum) ||
1386 !Tok.isAtStartOfLine()) &&
1387 SM.getPresumedLineNumber(Loc: StmtLoc) !=
1388 SM.getPresumedLineNumber(Loc: Tok.getLocation()) &&
1389 (Tok.isNot(K: tok::identifier) ||
1390 P.getPreprocessor().LookAhead(N: 0).isNot(K: tok::colon))) {
1391 P.Diag(Loc: Tok.getLocation(), DiagID: diag::warn_misleading_indentation) << Kind;
1392 P.Diag(Loc: StmtLoc, DiagID: diag::note_previous_statement);
1393 }
1394 }
1395};
1396
1397}
1398
1399StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1400 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1401 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1402
1403 bool IsConstexpr = false;
1404 bool IsConsteval = false;
1405 SourceLocation NotLocation;
1406 SourceLocation ConstevalLoc;
1407
1408 if (Tok.is(K: tok::kw_constexpr)) {
1409 // C23 supports constexpr keyword, but only for object definitions.
1410 if (getLangOpts().CPlusPlus) {
1411 Diag(Tok, DiagID: getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1412 : diag::ext_constexpr_if);
1413 IsConstexpr = true;
1414 ConsumeToken();
1415 }
1416 } else {
1417 if (Tok.is(K: tok::exclaim)) {
1418 NotLocation = ConsumeToken();
1419 }
1420
1421 if (Tok.is(K: tok::kw_consteval)) {
1422 Diag(Tok, DiagID: getLangOpts().CPlusPlus23 ? diag::warn_cxx20_compat_consteval_if
1423 : diag::ext_consteval_if);
1424 IsConsteval = true;
1425 ConstevalLoc = ConsumeToken();
1426 } else if (Tok.is(K: tok::code_completion)) {
1427 cutOffParsing();
1428 Actions.CodeCompletion().CodeCompleteKeywordAfterIf(
1429 AfterExclaim: NotLocation.isValid());
1430 return StmtError();
1431 }
1432 }
1433 if (!IsConsteval && (NotLocation.isValid() || Tok.isNot(K: tok::l_paren))) {
1434 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "if";
1435 SkipUntil(T: tok::semi);
1436 return StmtError();
1437 }
1438
1439 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1440
1441 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1442 // the case for C90.
1443 //
1444 // C++ 6.4p3:
1445 // A name introduced by a declaration in a condition is in scope from its
1446 // point of declaration until the end of the substatements controlled by the
1447 // condition.
1448 // C++ 3.3.2p4:
1449 // Names declared in the for-init-statement, and in the condition of if,
1450 // while, for, and switch statements are local to the if, while, for, or
1451 // switch statement (including the controlled statement).
1452 //
1453 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1454
1455 // Parse the condition.
1456 StmtResult InitStmt;
1457 Sema::ConditionResult Cond;
1458 SourceLocation LParen;
1459 SourceLocation RParen;
1460 std::optional<bool> ConstexprCondition;
1461 if (!IsConsteval) {
1462
1463 if (ParseParenExprOrCondition(InitStmt: &InitStmt, Cond, Loc: IfLoc,
1464 CK: IsConstexpr ? Sema::ConditionKind::ConstexprIf
1465 : Sema::ConditionKind::Boolean,
1466 LParenLoc&: LParen, RParenLoc&: RParen))
1467 return StmtError();
1468
1469 if (IsConstexpr)
1470 ConstexprCondition = Cond.getKnownValue();
1471 }
1472
1473 bool IsBracedThen = Tok.is(K: tok::l_brace);
1474
1475 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1476 // there is no compound stmt. C90 does not have this clause. We only do this
1477 // if the body isn't a compound statement to avoid push/pop in common cases.
1478 //
1479 // C++ 6.4p1:
1480 // The substatement in a selection-statement (each substatement, in the else
1481 // form of the if statement) implicitly defines a local scope.
1482 //
1483 // For C++ we create a scope for the condition and a new scope for
1484 // substatements because:
1485 // -When the 'then' scope exits, we want the condition declaration to still be
1486 // active for the 'else' scope too.
1487 // -Sema will detect name clashes by considering declarations of a
1488 // 'ControlScope' as part of its direct subscope.
1489 // -If we wanted the condition and substatement to be in the same scope, we
1490 // would have to notify ParseStatement not to create a new scope. It's
1491 // simpler to let it create a new scope.
1492 //
1493 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
1494
1495 MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
1496
1497 // Read the 'then' stmt.
1498 SourceLocation ThenStmtLoc = Tok.getLocation();
1499
1500 SourceLocation InnerStatementTrailingElseLoc;
1501 StmtResult ThenStmt;
1502 {
1503 bool ShouldEnter = ConstexprCondition && !*ConstexprCondition;
1504 Sema::ExpressionEvaluationContext Context =
1505 Sema::ExpressionEvaluationContext::DiscardedStatement;
1506 if (NotLocation.isInvalid() && IsConsteval) {
1507 Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
1508 ShouldEnter = true;
1509 }
1510
1511 EnterExpressionEvaluationContext PotentiallyDiscarded(
1512 Actions, Context, nullptr,
1513 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1514 ThenStmt = ParseStatement(TrailingElseLoc: &InnerStatementTrailingElseLoc);
1515 }
1516
1517 if (Tok.isNot(K: tok::kw_else))
1518 MIChecker.Check();
1519
1520 // Pop the 'if' scope if needed.
1521 InnerScope.Exit();
1522
1523 // If it has an else, parse it.
1524 SourceLocation ElseLoc;
1525 SourceLocation ElseStmtLoc;
1526 StmtResult ElseStmt;
1527
1528 if (Tok.is(K: tok::kw_else)) {
1529 if (TrailingElseLoc)
1530 *TrailingElseLoc = Tok.getLocation();
1531
1532 ElseLoc = ConsumeToken();
1533 ElseStmtLoc = Tok.getLocation();
1534
1535 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1536 // there is no compound stmt. C90 does not have this clause. We only do
1537 // this if the body isn't a compound statement to avoid push/pop in common
1538 // cases.
1539 //
1540 // C++ 6.4p1:
1541 // The substatement in a selection-statement (each substatement, in the else
1542 // form of the if statement) implicitly defines a local scope.
1543 //
1544 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1545 Tok.is(K: tok::l_brace));
1546
1547 MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
1548 bool ShouldEnter = ConstexprCondition && *ConstexprCondition;
1549 Sema::ExpressionEvaluationContext Context =
1550 Sema::ExpressionEvaluationContext::DiscardedStatement;
1551 if (NotLocation.isValid() && IsConsteval) {
1552 Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
1553 ShouldEnter = true;
1554 }
1555
1556 EnterExpressionEvaluationContext PotentiallyDiscarded(
1557 Actions, Context, nullptr,
1558 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1559 ElseStmt = ParseStatement();
1560
1561 if (ElseStmt.isUsable())
1562 MIChecker.Check();
1563
1564 // Pop the 'else' scope if needed.
1565 InnerScope.Exit();
1566 } else if (Tok.is(K: tok::code_completion)) {
1567 cutOffParsing();
1568 Actions.CodeCompletion().CodeCompleteAfterIf(S: getCurScope(), IsBracedThen);
1569 return StmtError();
1570 } else if (InnerStatementTrailingElseLoc.isValid()) {
1571 Diag(Loc: InnerStatementTrailingElseLoc, DiagID: diag::warn_dangling_else);
1572 }
1573
1574 IfScope.Exit();
1575
1576 // If the then or else stmt is invalid and the other is valid (and present),
1577 // turn the invalid one into a null stmt to avoid dropping the other
1578 // part. If both are invalid, return error.
1579 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1580 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1581 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1582 // Both invalid, or one is invalid and other is non-present: return error.
1583 return StmtError();
1584 }
1585
1586 if (IsConsteval) {
1587 auto IsCompoundStatement = [](const Stmt *S) {
1588 if (const auto *Outer = dyn_cast_if_present<AttributedStmt>(Val: S))
1589 S = Outer->getSubStmt();
1590 return isa_and_nonnull<clang::CompoundStmt>(Val: S);
1591 };
1592
1593 if (!IsCompoundStatement(ThenStmt.get())) {
1594 Diag(Loc: ConstevalLoc, DiagID: diag::err_expected_after) << "consteval"
1595 << "{";
1596 return StmtError();
1597 }
1598 if (!ElseStmt.isUnset() && !IsCompoundStatement(ElseStmt.get())) {
1599 Diag(Loc: ElseLoc, DiagID: diag::err_expected_after) << "else"
1600 << "{";
1601 return StmtError();
1602 }
1603 }
1604
1605 // Now if either are invalid, replace with a ';'.
1606 if (ThenStmt.isInvalid())
1607 ThenStmt = Actions.ActOnNullStmt(SemiLoc: ThenStmtLoc);
1608 if (ElseStmt.isInvalid())
1609 ElseStmt = Actions.ActOnNullStmt(SemiLoc: ElseStmtLoc);
1610
1611 IfStatementKind Kind = IfStatementKind::Ordinary;
1612 if (IsConstexpr)
1613 Kind = IfStatementKind::Constexpr;
1614 else if (IsConsteval)
1615 Kind = NotLocation.isValid() ? IfStatementKind::ConstevalNegated
1616 : IfStatementKind::ConstevalNonNegated;
1617
1618 return Actions.ActOnIfStmt(IfLoc, StatementKind: Kind, LParenLoc: LParen, InitStmt: InitStmt.get(), Cond, RParenLoc: RParen,
1619 ThenVal: ThenStmt.get(), ElseLoc, ElseVal: ElseStmt.get());
1620}
1621
1622StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1623 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1624 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1625
1626 if (Tok.isNot(K: tok::l_paren)) {
1627 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "switch";
1628 SkipUntil(T: tok::semi);
1629 return StmtError();
1630 }
1631
1632 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1633
1634 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1635 // not the case for C90. Start the switch scope.
1636 //
1637 // C++ 6.4p3:
1638 // A name introduced by a declaration in a condition is in scope from its
1639 // point of declaration until the end of the substatements controlled by the
1640 // condition.
1641 // C++ 3.3.2p4:
1642 // Names declared in the for-init-statement, and in the condition of if,
1643 // while, for, and switch statements are local to the if, while, for, or
1644 // switch statement (including the controlled statement).
1645 //
1646 unsigned ScopeFlags = Scope::SwitchScope;
1647 if (C99orCXX)
1648 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1649 ParseScope SwitchScope(this, ScopeFlags);
1650
1651 // Parse the condition.
1652 StmtResult InitStmt;
1653 Sema::ConditionResult Cond;
1654 SourceLocation LParen;
1655 SourceLocation RParen;
1656 if (ParseParenExprOrCondition(InitStmt: &InitStmt, Cond, Loc: SwitchLoc,
1657 CK: Sema::ConditionKind::Switch, LParenLoc&: LParen, RParenLoc&: RParen))
1658 return StmtError();
1659
1660 StmtResult Switch = Actions.ActOnStartOfSwitchStmt(
1661 SwitchLoc, LParenLoc: LParen, InitStmt: InitStmt.get(), Cond, RParenLoc: RParen);
1662
1663 if (Switch.isInvalid()) {
1664 // Skip the switch body.
1665 // FIXME: This is not optimal recovery, but parsing the body is more
1666 // dangerous due to the presence of case and default statements, which
1667 // will have no place to connect back with the switch.
1668 if (Tok.is(K: tok::l_brace)) {
1669 ConsumeBrace();
1670 SkipUntil(T: tok::r_brace);
1671 } else
1672 SkipUntil(T: tok::semi);
1673 return Switch;
1674 }
1675
1676 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1677 // there is no compound stmt. C90 does not have this clause. We only do this
1678 // if the body isn't a compound statement to avoid push/pop in common cases.
1679 //
1680 // C++ 6.4p1:
1681 // The substatement in a selection-statement (each substatement, in the else
1682 // form of the if statement) implicitly defines a local scope.
1683 //
1684 // See comments in ParseIfStatement for why we create a scope for the
1685 // condition and a new scope for substatement in C++.
1686 //
1687 getCurScope()->AddFlags(Flags: Scope::BreakScope);
1688 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(K: tok::l_brace));
1689
1690 // We have incremented the mangling number for the SwitchScope and the
1691 // InnerScope, which is one too many.
1692 if (C99orCXX)
1693 getCurScope()->decrementMSManglingNumber();
1694
1695 // Read the body statement.
1696 StmtResult Body(ParseStatement(TrailingElseLoc));
1697
1698 // Pop the scopes.
1699 InnerScope.Exit();
1700 SwitchScope.Exit();
1701
1702 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch: Switch.get(), Body: Body.get());
1703}
1704
1705StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1706 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1707 SourceLocation WhileLoc = Tok.getLocation();
1708 ConsumeToken(); // eat the 'while'.
1709
1710 if (Tok.isNot(K: tok::l_paren)) {
1711 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "while";
1712 SkipUntil(T: tok::semi);
1713 return StmtError();
1714 }
1715
1716 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1717
1718 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1719 // the case for C90. Start the loop scope.
1720 //
1721 // C++ 6.4p3:
1722 // A name introduced by a declaration in a condition is in scope from its
1723 // point of declaration until the end of the substatements controlled by the
1724 // condition.
1725 // C++ 3.3.2p4:
1726 // Names declared in the for-init-statement, and in the condition of if,
1727 // while, for, and switch statements are local to the if, while, for, or
1728 // switch statement (including the controlled statement).
1729 //
1730 unsigned ScopeFlags;
1731 if (C99orCXX)
1732 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1733 Scope::DeclScope | Scope::ControlScope;
1734 else
1735 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1736 ParseScope WhileScope(this, ScopeFlags);
1737
1738 // Parse the condition.
1739 Sema::ConditionResult Cond;
1740 SourceLocation LParen;
1741 SourceLocation RParen;
1742 if (ParseParenExprOrCondition(InitStmt: nullptr, Cond, Loc: WhileLoc,
1743 CK: Sema::ConditionKind::Boolean, LParenLoc&: LParen, RParenLoc&: RParen))
1744 return StmtError();
1745
1746 // OpenACC Restricts a while-loop inside of certain construct/clause
1747 // combinations, so diagnose that here in OpenACC mode.
1748 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1749 getActions().OpenACC().ActOnWhileStmt(WhileLoc);
1750
1751 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1752 // there is no compound stmt. C90 does not have this clause. We only do this
1753 // if the body isn't a compound statement to avoid push/pop in common cases.
1754 //
1755 // C++ 6.5p2:
1756 // The substatement in an iteration-statement implicitly defines a local scope
1757 // which is entered and exited each time through the loop.
1758 //
1759 // See comments in ParseIfStatement for why we create a scope for the
1760 // condition and a new scope for substatement in C++.
1761 //
1762 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(K: tok::l_brace));
1763
1764 MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
1765
1766 // Read the body statement.
1767 StmtResult Body(ParseStatement(TrailingElseLoc));
1768
1769 if (Body.isUsable())
1770 MIChecker.Check();
1771 // Pop the body scope if needed.
1772 InnerScope.Exit();
1773 WhileScope.Exit();
1774
1775 if (Cond.isInvalid() || Body.isInvalid())
1776 return StmtError();
1777
1778 return Actions.ActOnWhileStmt(WhileLoc, LParenLoc: LParen, Cond, RParenLoc: RParen, Body: Body.get());
1779}
1780
1781StmtResult Parser::ParseDoStatement() {
1782 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1783 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1784
1785 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1786 // the case for C90. Start the loop scope.
1787 unsigned ScopeFlags;
1788 if (getLangOpts().C99)
1789 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1790 else
1791 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1792
1793 ParseScope DoScope(this, ScopeFlags);
1794
1795 // OpenACC Restricts a do-while-loop inside of certain construct/clause
1796 // combinations, so diagnose that here in OpenACC mode.
1797 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1798 getActions().OpenACC().ActOnDoStmt(DoLoc);
1799
1800 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1801 // there is no compound stmt. C90 does not have this clause. We only do this
1802 // if the body isn't a compound statement to avoid push/pop in common cases.
1803 //
1804 // C++ 6.5p2:
1805 // The substatement in an iteration-statement implicitly defines a local scope
1806 // which is entered and exited each time through the loop.
1807 //
1808 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1809 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(K: tok::l_brace));
1810
1811 // Read the body statement.
1812 StmtResult Body(ParseStatement());
1813
1814 // Pop the body scope if needed.
1815 InnerScope.Exit();
1816
1817 if (Tok.isNot(K: tok::kw_while)) {
1818 if (!Body.isInvalid()) {
1819 Diag(Tok, DiagID: diag::err_expected_while);
1820 Diag(Loc: DoLoc, DiagID: diag::note_matching) << "'do'";
1821 SkipUntil(T: tok::semi, Flags: StopBeforeMatch);
1822 }
1823 return StmtError();
1824 }
1825 SourceLocation WhileLoc = ConsumeToken();
1826
1827 if (Tok.isNot(K: tok::l_paren)) {
1828 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "do/while";
1829 SkipUntil(T: tok::semi, Flags: StopBeforeMatch);
1830 return StmtError();
1831 }
1832
1833 // Parse the parenthesized expression.
1834 BalancedDelimiterTracker T(*this, tok::l_paren);
1835 T.consumeOpen();
1836
1837 // A do-while expression is not a condition, so can't have attributes.
1838 DiagnoseAndSkipCXX11Attributes();
1839
1840 SourceLocation Start = Tok.getLocation();
1841 ExprResult Cond = ParseExpression();
1842 if (!Cond.isUsable()) {
1843 if (!Tok.isOneOf(Ks: tok::r_paren, Ks: tok::r_square, Ks: tok::r_brace))
1844 SkipUntil(T: tok::semi);
1845 Cond = Actions.CreateRecoveryExpr(
1846 Begin: Start, End: Start == Tok.getLocation() ? Start : PrevTokLocation, SubExprs: {},
1847 T: Actions.getASTContext().BoolTy);
1848 }
1849 T.consumeClose();
1850 DoScope.Exit();
1851
1852 if (Cond.isInvalid() || Body.isInvalid())
1853 return StmtError();
1854
1855 return Actions.ActOnDoStmt(DoLoc, Body: Body.get(), WhileLoc, CondLParen: T.getOpenLocation(),
1856 Cond: Cond.get(), CondRParen: T.getCloseLocation());
1857}
1858
1859bool Parser::isForRangeIdentifier() {
1860 assert(Tok.is(tok::identifier));
1861
1862 const Token &Next = NextToken();
1863 if (Next.is(K: tok::colon))
1864 return true;
1865
1866 if (Next.isOneOf(Ks: tok::l_square, Ks: tok::kw_alignas)) {
1867 TentativeParsingAction PA(*this);
1868 ConsumeToken();
1869 SkipCXX11Attributes();
1870 bool Result = Tok.is(K: tok::colon);
1871 PA.Revert();
1872 return Result;
1873 }
1874
1875 return false;
1876}
1877
1878StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1879 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1880 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1881
1882 SourceLocation CoawaitLoc;
1883 if (Tok.is(K: tok::kw_co_await))
1884 CoawaitLoc = ConsumeToken();
1885
1886 if (Tok.isNot(K: tok::l_paren)) {
1887 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "for";
1888 SkipUntil(T: tok::semi);
1889 return StmtError();
1890 }
1891
1892 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1893 getLangOpts().ObjC;
1894
1895 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1896 // the case for C90. Start the loop scope.
1897 //
1898 // C++ 6.4p3:
1899 // A name introduced by a declaration in a condition is in scope from its
1900 // point of declaration until the end of the substatements controlled by the
1901 // condition.
1902 // C++ 3.3.2p4:
1903 // Names declared in the for-init-statement, and in the condition of if,
1904 // while, for, and switch statements are local to the if, while, for, or
1905 // switch statement (including the controlled statement).
1906 // C++ 6.5.3p1:
1907 // Names declared in the for-init-statement are in the same declarative-region
1908 // as those declared in the condition.
1909 //
1910 unsigned ScopeFlags = 0;
1911 if (C99orCXXorObjC)
1912 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1913
1914 ParseScope ForScope(this, ScopeFlags);
1915
1916 BalancedDelimiterTracker T(*this, tok::l_paren);
1917 T.consumeOpen();
1918
1919 ExprResult Value;
1920
1921 bool ForEach = false;
1922 StmtResult FirstPart;
1923 Sema::ConditionResult SecondPart;
1924 ExprResult Collection;
1925 ForRangeInfo ForRangeInfo;
1926 FullExprArg ThirdPart(Actions);
1927
1928 if (Tok.is(K: tok::code_completion)) {
1929 cutOffParsing();
1930 Actions.CodeCompletion().CodeCompleteOrdinaryName(
1931 S: getCurScope(), CompletionContext: C99orCXXorObjC ? SemaCodeCompletion::PCC_ForInit
1932 : SemaCodeCompletion::PCC_Expression);
1933 return StmtError();
1934 }
1935
1936 ParsedAttributes attrs(AttrFactory);
1937 MaybeParseCXX11Attributes(Attrs&: attrs);
1938
1939 SourceLocation EmptyInitStmtSemiLoc;
1940
1941 // Parse the first part of the for specifier.
1942 if (Tok.is(K: tok::semi)) { // for (;
1943 ProhibitAttributes(Attrs&: attrs);
1944 // no first part, eat the ';'.
1945 SourceLocation SemiLoc = Tok.getLocation();
1946 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
1947 EmptyInitStmtSemiLoc = SemiLoc;
1948 ConsumeToken();
1949 } else if (getLangOpts().CPlusPlus && Tok.is(K: tok::identifier) &&
1950 isForRangeIdentifier()) {
1951 ProhibitAttributes(Attrs&: attrs);
1952 IdentifierInfo *Name = Tok.getIdentifierInfo();
1953 SourceLocation Loc = ConsumeToken();
1954 MaybeParseCXX11Attributes(Attrs&: attrs);
1955
1956 ForRangeInfo.ColonLoc = ConsumeToken();
1957 if (Tok.is(K: tok::l_brace))
1958 ForRangeInfo.RangeExpr = ParseBraceInitializer();
1959 else
1960 ForRangeInfo.RangeExpr = ParseExpression();
1961
1962 Diag(Loc, DiagID: diag::err_for_range_identifier)
1963 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1964 ? FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "auto &&")
1965 : FixItHint());
1966
1967 ForRangeInfo.LoopVar =
1968 Actions.ActOnCXXForRangeIdentifier(S: getCurScope(), IdentLoc: Loc, Ident: Name, Attrs&: attrs);
1969 } else if (isForInitDeclaration()) { // for (int X = 4;
1970 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1971
1972 // Parse declaration, which eats the ';'.
1973 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
1974 Diag(Tok, DiagID: diag::ext_c99_variable_decl_in_for_loop);
1975 Diag(Tok, DiagID: diag::warn_gcc_variable_decl_in_for_loop);
1976 }
1977 DeclGroupPtrTy DG;
1978 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1979 if (!getLangOpts().CPlusPlus &&
1980 Tok.isOneOf(Ks: tok::kw_static_assert, Ks: tok::kw__Static_assert)) {
1981 ProhibitAttributes(Attrs&: attrs);
1982 Decl *D = ParseStaticAssertDeclaration(DeclEnd);
1983 DG = Actions.ConvertDeclToDeclGroup(Ptr: D);
1984 FirstPart = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: Tok.getLocation());
1985 } else if (Tok.is(K: tok::kw_using)) {
1986 DG = ParseAliasDeclarationInInitStatement(Context: DeclaratorContext::ForInit,
1987 Attrs&: attrs);
1988 FirstPart = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: Tok.getLocation());
1989 } else {
1990 // In C++0x, "for (T NS:a" might not be a typo for ::
1991 bool MightBeForRangeStmt = getLangOpts().CPlusPlus || getLangOpts().ObjC;
1992 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1993 ParsedAttributes DeclSpecAttrs(AttrFactory);
1994 DG = ParseSimpleDeclaration(
1995 Context: DeclaratorContext::ForInit, DeclEnd, DeclAttrs&: attrs, DeclSpecAttrs, RequireSemi: false,
1996 FRI: MightBeForRangeStmt ? &ForRangeInfo : nullptr);
1997 FirstPart = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: Tok.getLocation());
1998 if (ForRangeInfo.ParsedForRangeDecl()) {
1999 Diag(Loc: ForRangeInfo.ColonLoc, DiagID: getLangOpts().CPlusPlus11
2000 ? diag::warn_cxx98_compat_for_range
2001 : diag::ext_for_range);
2002 ForRangeInfo.LoopVar = FirstPart;
2003 FirstPart = StmtResult();
2004 } else if (Tok.is(K: tok::semi)) { // for (int x = 4;
2005 ConsumeToken();
2006 } else if ((ForEach = isTokIdentifier_in())) {
2007 Actions.ActOnForEachDeclStmt(Decl: DG);
2008 // ObjC: for (id x in expr)
2009 ConsumeToken(); // consume 'in'
2010
2011 if (Tok.is(K: tok::code_completion)) {
2012 cutOffParsing();
2013 Actions.CodeCompletion().CodeCompleteObjCForCollection(S: getCurScope(),
2014 IterationVar: DG);
2015 return StmtError();
2016 }
2017 Collection = ParseExpression();
2018 } else {
2019 Diag(Tok, DiagID: diag::err_expected_semi_for);
2020 }
2021 }
2022 } else {
2023 ProhibitAttributes(Attrs&: attrs);
2024 Value = ParseExpression();
2025
2026 ForEach = isTokIdentifier_in();
2027
2028 // Turn the expression into a stmt.
2029 if (!Value.isInvalid()) {
2030 if (ForEach)
2031 FirstPart = Actions.ActOnForEachLValueExpr(E: Value.get());
2032 else {
2033 // We already know this is not an init-statement within a for loop, so
2034 // if we are parsing a C++11 range-based for loop, we should treat this
2035 // expression statement as being a discarded value expression because
2036 // we will err below. This way we do not warn on an unused expression
2037 // that was an error in the first place, like with: for (expr : expr);
2038 bool IsRangeBasedFor =
2039 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(K: tok::colon);
2040 FirstPart = Actions.ActOnExprStmt(Arg: Value, DiscardedValue: !IsRangeBasedFor);
2041 }
2042 }
2043
2044 if (Tok.is(K: tok::semi)) {
2045 ConsumeToken();
2046 } else if (ForEach) {
2047 ConsumeToken(); // consume 'in'
2048
2049 if (Tok.is(K: tok::code_completion)) {
2050 cutOffParsing();
2051 Actions.CodeCompletion().CodeCompleteObjCForCollection(S: getCurScope(),
2052 IterationVar: nullptr);
2053 return StmtError();
2054 }
2055 Collection = ParseExpression();
2056 } else if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::colon) && FirstPart.get()) {
2057 // User tried to write the reasonable, but ill-formed, for-range-statement
2058 // for (expr : expr) { ... }
2059 Diag(Tok, DiagID: diag::err_for_range_expected_decl)
2060 << FirstPart.get()->getSourceRange();
2061 SkipUntil(T: tok::r_paren, Flags: StopBeforeMatch);
2062 SecondPart = Sema::ConditionError();
2063 } else {
2064 if (!Value.isInvalid()) {
2065 Diag(Tok, DiagID: diag::err_expected_semi_for);
2066 } else {
2067 // Skip until semicolon or rparen, don't consume it.
2068 SkipUntil(T: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch);
2069 if (Tok.is(K: tok::semi))
2070 ConsumeToken();
2071 }
2072 }
2073 }
2074
2075 // Parse the second part of the for specifier.
2076 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
2077 !SecondPart.isInvalid()) {
2078 // Parse the second part of the for specifier.
2079 if (Tok.is(K: tok::semi)) { // for (...;;
2080 // no second part.
2081 } else if (Tok.is(K: tok::r_paren)) {
2082 // missing both semicolons.
2083 } else {
2084 if (getLangOpts().CPlusPlus) {
2085 // C++2a: We've parsed an init-statement; we might have a
2086 // for-range-declaration next.
2087 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
2088 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
2089 SourceLocation SecondPartStart = Tok.getLocation();
2090 Sema::ConditionKind CK = Sema::ConditionKind::Boolean;
2091 SecondPart = ParseCXXCondition(
2092 /*InitStmt=*/nullptr, Loc: ForLoc, CK,
2093 // FIXME: recovery if we don't see another semi!
2094 /*MissingOK=*/true, FRI: MightBeForRangeStmt ? &ForRangeInfo : nullptr,
2095 /*EnterForConditionScope=*/true);
2096
2097 if (ForRangeInfo.ParsedForRangeDecl()) {
2098 Diag(Loc: FirstPart.get() ? FirstPart.get()->getBeginLoc()
2099 : ForRangeInfo.ColonLoc,
2100 DiagID: getLangOpts().CPlusPlus20
2101 ? diag::warn_cxx17_compat_for_range_init_stmt
2102 : diag::ext_for_range_init_stmt)
2103 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
2104 : SourceRange());
2105 if (EmptyInitStmtSemiLoc.isValid()) {
2106 Diag(Loc: EmptyInitStmtSemiLoc, DiagID: diag::warn_empty_init_statement)
2107 << /*for-loop*/ 2
2108 << FixItHint::CreateRemoval(RemoveRange: EmptyInitStmtSemiLoc);
2109 }
2110 }
2111
2112 if (SecondPart.isInvalid()) {
2113 ExprResult CondExpr = Actions.CreateRecoveryExpr(
2114 Begin: SecondPartStart,
2115 End: Tok.getLocation() == SecondPartStart ? SecondPartStart
2116 : PrevTokLocation,
2117 SubExprs: {}, T: Actions.PreferredConditionType(K: CK));
2118 if (!CondExpr.isInvalid())
2119 SecondPart = Actions.ActOnCondition(S: getCurScope(), Loc: ForLoc,
2120 SubExpr: CondExpr.get(), CK,
2121 /*MissingOK=*/false);
2122 }
2123
2124 } else {
2125 // We permit 'continue' and 'break' in the condition of a for loop.
2126 getCurScope()->AddFlags(Flags: Scope::BreakScope | Scope::ContinueScope);
2127
2128 ExprResult SecondExpr = ParseExpression();
2129 if (SecondExpr.isInvalid())
2130 SecondPart = Sema::ConditionError();
2131 else
2132 SecondPart = Actions.ActOnCondition(
2133 S: getCurScope(), Loc: ForLoc, SubExpr: SecondExpr.get(),
2134 CK: Sema::ConditionKind::Boolean, /*MissingOK=*/true);
2135 }
2136 }
2137 }
2138
2139 // Enter a break / continue scope, if we didn't already enter one while
2140 // parsing the second part.
2141 if (!getCurScope()->isContinueScope())
2142 getCurScope()->AddFlags(Flags: Scope::BreakScope | Scope::ContinueScope);
2143
2144 // Parse the third part of the for statement.
2145 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
2146 if (Tok.isNot(K: tok::semi)) {
2147 if (!SecondPart.isInvalid())
2148 Diag(Tok, DiagID: diag::err_expected_semi_for);
2149 SkipUntil(T: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch);
2150 }
2151
2152 if (Tok.is(K: tok::semi)) {
2153 ConsumeToken();
2154 }
2155
2156 if (Tok.isNot(K: tok::r_paren)) { // for (...;...;)
2157 ExprResult Third = ParseExpression();
2158 // FIXME: The C++11 standard doesn't actually say that this is a
2159 // discarded-value expression, but it clearly should be.
2160 ThirdPart = Actions.MakeFullDiscardedValueExpr(Arg: Third.get());
2161 }
2162 }
2163 // Match the ')'.
2164 T.consumeClose();
2165
2166 // C++ Coroutines [stmt.iter]:
2167 // 'co_await' can only be used for a range-based for statement.
2168 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
2169 Diag(Loc: CoawaitLoc, DiagID: diag::err_for_co_await_not_range_for);
2170 CoawaitLoc = SourceLocation();
2171 }
2172
2173 if (CoawaitLoc.isValid() && getLangOpts().CPlusPlus20)
2174 Diag(Loc: CoawaitLoc, DiagID: diag::warn_deprecated_for_co_await);
2175
2176 // We need to perform most of the semantic analysis for a C++0x for-range
2177 // statememt before parsing the body, in order to be able to deduce the type
2178 // of an auto-typed loop variable.
2179 StmtResult ForRangeStmt;
2180 StmtResult ForEachStmt;
2181
2182 if (ForRangeInfo.ParsedForRangeDecl()) {
2183 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
2184 S: getCurScope(), ForLoc, CoawaitLoc, InitStmt: FirstPart.get(),
2185 LoopVar: ForRangeInfo.LoopVar.get(), ColonLoc: ForRangeInfo.ColonLoc,
2186 Collection: ForRangeInfo.RangeExpr.get(), RParenLoc: T.getCloseLocation(), Kind: Sema::BFRK_Build,
2187 LifetimeExtendTemps: ForRangeInfo.LifetimeExtendTemps);
2188 } else if (ForEach) {
2189 // Similarly, we need to do the semantic analysis for a for-range
2190 // statement immediately in order to close over temporaries correctly.
2191 ForEachStmt = Actions.ObjC().ActOnObjCForCollectionStmt(
2192 ForColLoc: ForLoc, First: FirstPart.get(), collection: Collection.get(), RParenLoc: T.getCloseLocation());
2193 } else {
2194 // In OpenMP loop region loop control variable must be captured and be
2195 // private. Perform analysis of first part (if any).
2196 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
2197 Actions.OpenMP().ActOnOpenMPLoopInitialization(ForLoc, Init: FirstPart.get());
2198 }
2199 }
2200
2201 // OpenACC Restricts a for-loop inside of certain construct/clause
2202 // combinations, so diagnose that here in OpenACC mode.
2203 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
2204 if (ForRangeInfo.ParsedForRangeDecl())
2205 getActions().OpenACC().ActOnRangeForStmtBegin(ForLoc, RangeFor: ForRangeStmt.get());
2206 else
2207 getActions().OpenACC().ActOnForStmtBegin(
2208 ForLoc, First: FirstPart.get(), Second: SecondPart.get().second, Third: ThirdPart.get());
2209
2210 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2211 // there is no compound stmt. C90 does not have this clause. We only do this
2212 // if the body isn't a compound statement to avoid push/pop in common cases.
2213 //
2214 // C++ 6.5p2:
2215 // The substatement in an iteration-statement implicitly defines a local scope
2216 // which is entered and exited each time through the loop.
2217 //
2218 // See comments in ParseIfStatement for why we create a scope for
2219 // for-init-statement/condition and a new scope for substatement in C++.
2220 //
2221 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
2222 Tok.is(K: tok::l_brace));
2223
2224 // The body of the for loop has the same local mangling number as the
2225 // for-init-statement.
2226 // It will only be incremented if the body contains other things that would
2227 // normally increment the mangling number (like a compound statement).
2228 if (C99orCXXorObjC)
2229 getCurScope()->decrementMSManglingNumber();
2230
2231 MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
2232
2233 // Read the body statement.
2234 StmtResult Body(ParseStatement(TrailingElseLoc));
2235
2236 if (Body.isUsable())
2237 MIChecker.Check();
2238
2239 // Pop the body scope if needed.
2240 InnerScope.Exit();
2241
2242 getActions().OpenACC().ActOnForStmtEnd(ForLoc, Body);
2243
2244 // Leave the for-scope.
2245 ForScope.Exit();
2246
2247 if (Body.isInvalid())
2248 return StmtError();
2249
2250 if (ForEach)
2251 return Actions.ObjC().FinishObjCForCollectionStmt(ForCollection: ForEachStmt.get(),
2252 Body: Body.get());
2253
2254 if (ForRangeInfo.ParsedForRangeDecl())
2255 return Actions.FinishCXXForRangeStmt(ForRange: ForRangeStmt.get(), Body: Body.get());
2256
2257 return Actions.ActOnForStmt(ForLoc, LParenLoc: T.getOpenLocation(), First: FirstPart.get(),
2258 Second: SecondPart, Third: ThirdPart, RParenLoc: T.getCloseLocation(),
2259 Body: Body.get());
2260}
2261
2262StmtResult Parser::ParseGotoStatement() {
2263 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
2264 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
2265
2266 StmtResult Res;
2267 if (Tok.is(K: tok::identifier)) {
2268 LabelDecl *LD = Actions.LookupOrCreateLabel(II: Tok.getIdentifierInfo(),
2269 IdentLoc: Tok.getLocation());
2270 Res = Actions.ActOnGotoStmt(GotoLoc, LabelLoc: Tok.getLocation(), TheDecl: LD);
2271 ConsumeToken();
2272 } else if (Tok.is(K: tok::star)) {
2273 // GNU indirect goto extension.
2274 Diag(Tok, DiagID: diag::ext_gnu_indirect_goto);
2275 SourceLocation StarLoc = ConsumeToken();
2276 ExprResult R(ParseExpression());
2277 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
2278 SkipUntil(T: tok::semi, Flags: StopBeforeMatch);
2279 return StmtError();
2280 }
2281 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, DestExp: R.get());
2282 } else {
2283 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
2284 return StmtError();
2285 }
2286
2287 return Res;
2288}
2289
2290StmtResult Parser::ParseContinueStatement() {
2291 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
2292 return Actions.ActOnContinueStmt(ContinueLoc, CurScope: getCurScope());
2293}
2294
2295StmtResult Parser::ParseBreakStatement() {
2296 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
2297 return Actions.ActOnBreakStmt(BreakLoc, CurScope: getCurScope());
2298}
2299
2300StmtResult Parser::ParseReturnStatement() {
2301 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
2302 "Not a return stmt!");
2303 bool IsCoreturn = Tok.is(K: tok::kw_co_return);
2304 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
2305
2306 ExprResult R;
2307 if (Tok.isNot(K: tok::semi)) {
2308 if (!IsCoreturn)
2309 PreferredType.enterReturn(S&: Actions, Tok: Tok.getLocation());
2310 // FIXME: Code completion for co_return.
2311 if (Tok.is(K: tok::code_completion) && !IsCoreturn) {
2312 cutOffParsing();
2313 Actions.CodeCompletion().CodeCompleteExpression(
2314 S: getCurScope(), PreferredType: PreferredType.get(Tok: Tok.getLocation()));
2315 return StmtError();
2316 }
2317
2318 if (Tok.is(K: tok::l_brace) && getLangOpts().CPlusPlus) {
2319 R = ParseInitializer();
2320 if (R.isUsable())
2321 Diag(Loc: R.get()->getBeginLoc(),
2322 DiagID: getLangOpts().CPlusPlus11
2323 ? diag::warn_cxx98_compat_generalized_initializer_lists
2324 : diag::ext_generalized_initializer_lists)
2325 << R.get()->getSourceRange();
2326 } else
2327 R = ParseExpression();
2328 if (R.isInvalid()) {
2329 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
2330 return StmtError();
2331 }
2332 }
2333 if (IsCoreturn)
2334 return Actions.ActOnCoreturnStmt(S: getCurScope(), KwLoc: ReturnLoc, E: R.get());
2335 return Actions.ActOnReturnStmt(ReturnLoc, RetValExp: R.get(), CurScope: getCurScope());
2336}
2337
2338StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2339 ParsedStmtContext StmtCtx,
2340 SourceLocation *TrailingElseLoc,
2341 ParsedAttributes &Attrs) {
2342 // Create temporary attribute list.
2343 ParsedAttributes TempAttrs(AttrFactory);
2344
2345 SourceLocation StartLoc = Tok.getLocation();
2346
2347 // Get loop hints and consume annotated token.
2348 while (Tok.is(K: tok::annot_pragma_loop_hint)) {
2349 LoopHint Hint;
2350 if (!HandlePragmaLoopHint(Hint))
2351 continue;
2352
2353 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2354 ArgsUnion(Hint.ValueExpr)};
2355 TempAttrs.addNew(attrName: Hint.PragmaNameLoc->getIdentifierInfo(), attrRange: Hint.Range,
2356 scope: AttributeScopeInfo(), args: ArgHints, /*numArgs=*/4,
2357 form: ParsedAttr::Form::Pragma());
2358 }
2359
2360 // Get the next statement.
2361 MaybeParseCXX11Attributes(Attrs);
2362
2363 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2364 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2365 Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs&: Attrs, GNUAttrs&: EmptyDeclSpecAttrs);
2366
2367 Attrs.takeAllFrom(Other&: TempAttrs);
2368
2369 // Start of attribute range may already be set for some invalid input.
2370 // See PR46336.
2371 if (Attrs.Range.getBegin().isInvalid())
2372 Attrs.Range.setBegin(StartLoc);
2373
2374 return S;
2375}
2376
2377Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2378 assert(Tok.is(tok::l_brace));
2379 SourceLocation LBraceLoc = Tok.getLocation();
2380
2381 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2382 "parsing function body");
2383
2384 // Save and reset current vtordisp stack if we have entered a C++ method body.
2385 bool IsCXXMethod =
2386 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Val: Decl);
2387 Sema::PragmaStackSentinelRAII
2388 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2389
2390 // Do not enter a scope for the brace, as the arguments are in the same scope
2391 // (the function body) as the body itself. Instead, just read the statement
2392 // list and put it into a CompoundStmt for safe keeping.
2393 StmtResult FnBody(ParseCompoundStatementBody());
2394
2395 // If the function body could not be parsed, make a bogus compoundstmt.
2396 if (FnBody.isInvalid()) {
2397 Sema::CompoundScopeRAII CompoundScope(Actions);
2398 FnBody = Actions.ActOnCompoundStmt(L: LBraceLoc, R: LBraceLoc, Elts: {}, isStmtExpr: false);
2399 }
2400
2401 BodyScope.Exit();
2402 return Actions.ActOnFinishFunctionBody(Decl, Body: FnBody.get());
2403}
2404
2405Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2406 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2407 SourceLocation TryLoc = ConsumeToken();
2408
2409 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2410 "parsing function try block");
2411
2412 // Constructor initializer list?
2413 if (Tok.is(K: tok::colon))
2414 ParseConstructorInitializer(ConstructorDecl: Decl);
2415 else
2416 Actions.ActOnDefaultCtorInitializers(CDtorDecl: Decl);
2417
2418 // Save and reset current vtordisp stack if we have entered a C++ method body.
2419 bool IsCXXMethod =
2420 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Val: Decl);
2421 Sema::PragmaStackSentinelRAII
2422 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2423
2424 SourceLocation LBraceLoc = Tok.getLocation();
2425 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2426 // If we failed to parse the try-catch, we just give the function an empty
2427 // compound statement as the body.
2428 if (FnBody.isInvalid()) {
2429 Sema::CompoundScopeRAII CompoundScope(Actions);
2430 FnBody = Actions.ActOnCompoundStmt(L: LBraceLoc, R: LBraceLoc, Elts: {}, isStmtExpr: false);
2431 }
2432
2433 BodyScope.Exit();
2434 return Actions.ActOnFinishFunctionBody(Decl, Body: FnBody.get());
2435}
2436
2437bool Parser::trySkippingFunctionBody() {
2438 assert(SkipFunctionBodies &&
2439 "Should only be called when SkipFunctionBodies is enabled");
2440 if (!PP.isCodeCompletionEnabled()) {
2441 SkipFunctionBody();
2442 return true;
2443 }
2444
2445 // We're in code-completion mode. Skip parsing for all function bodies unless
2446 // the body contains the code-completion point.
2447 TentativeParsingAction PA(*this);
2448 bool IsTryCatch = Tok.is(K: tok::kw_try);
2449 CachedTokens Toks;
2450 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2451 if (llvm::any_of(Range&: Toks, P: [](const Token &Tok) {
2452 return Tok.is(K: tok::code_completion);
2453 })) {
2454 PA.Revert();
2455 return false;
2456 }
2457 if (ErrorInPrologue) {
2458 PA.Commit();
2459 SkipMalformedDecl();
2460 return true;
2461 }
2462 if (!SkipUntil(T: tok::r_brace, Flags: StopAtCodeCompletion)) {
2463 PA.Revert();
2464 return false;
2465 }
2466 while (IsTryCatch && Tok.is(K: tok::kw_catch)) {
2467 if (!SkipUntil(T: tok::l_brace, Flags: StopAtCodeCompletion) ||
2468 !SkipUntil(T: tok::r_brace, Flags: StopAtCodeCompletion)) {
2469 PA.Revert();
2470 return false;
2471 }
2472 }
2473 PA.Commit();
2474 return true;
2475}
2476
2477StmtResult Parser::ParseCXXTryBlock() {
2478 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2479
2480 SourceLocation TryLoc = ConsumeToken();
2481 return ParseCXXTryBlockCommon(TryLoc);
2482}
2483
2484StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2485 if (Tok.isNot(K: tok::l_brace))
2486 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
2487
2488 StmtResult TryBlock(ParseCompoundStatement(
2489 /*isStmtExpr=*/false, ScopeFlags: Scope::DeclScope | Scope::TryScope |
2490 Scope::CompoundStmtScope |
2491 (FnTry ? Scope::FnTryCatchScope : 0)));
2492 if (TryBlock.isInvalid())
2493 return TryBlock;
2494
2495 // Borland allows SEH-handlers with 'try'
2496
2497 if ((Tok.is(K: tok::identifier) &&
2498 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2499 Tok.is(K: tok::kw___finally)) {
2500 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2501 StmtResult Handler;
2502 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2503 SourceLocation Loc = ConsumeToken();
2504 Handler = ParseSEHExceptBlock(ExceptLoc: Loc);
2505 }
2506 else {
2507 SourceLocation Loc = ConsumeToken();
2508 Handler = ParseSEHFinallyBlock(FinallyLoc: Loc);
2509 }
2510 if(Handler.isInvalid())
2511 return Handler;
2512
2513 return Actions.ActOnSEHTryBlock(IsCXXTry: true /* IsCXXTry */,
2514 TryLoc,
2515 TryBlock: TryBlock.get(),
2516 Handler: Handler.get());
2517 }
2518 else {
2519 StmtVector Handlers;
2520
2521 // C++11 attributes can't appear here, despite this context seeming
2522 // statement-like.
2523 DiagnoseAndSkipCXX11Attributes();
2524
2525 if (Tok.isNot(K: tok::kw_catch))
2526 return StmtError(Diag(Tok, DiagID: diag::err_expected_catch));
2527 while (Tok.is(K: tok::kw_catch)) {
2528 StmtResult Handler(ParseCXXCatchBlock(FnCatch: FnTry));
2529 if (!Handler.isInvalid())
2530 Handlers.push_back(Elt: Handler.get());
2531 }
2532 // Don't bother creating the full statement if we don't have any usable
2533 // handlers.
2534 if (Handlers.empty())
2535 return StmtError();
2536
2537 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock: TryBlock.get(), Handlers);
2538 }
2539}
2540
2541StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2542 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2543
2544 SourceLocation CatchLoc = ConsumeToken();
2545
2546 BalancedDelimiterTracker T(*this, tok::l_paren);
2547 if (T.expectAndConsume())
2548 return StmtError();
2549
2550 // C++ 3.3.2p3:
2551 // The name in a catch exception-declaration is local to the handler and
2552 // shall not be redeclared in the outermost block of the handler.
2553 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2554 Scope::CatchScope |
2555 (FnCatch ? Scope::FnTryCatchScope : 0));
2556
2557 // exception-declaration is equivalent to '...' or a parameter-declaration
2558 // without default arguments.
2559 Decl *ExceptionDecl = nullptr;
2560 if (Tok.isNot(K: tok::ellipsis)) {
2561 ParsedAttributes Attributes(AttrFactory);
2562 MaybeParseCXX11Attributes(Attrs&: Attributes);
2563
2564 DeclSpec DS(AttrFactory);
2565
2566 if (ParseCXXTypeSpecifierSeq(DS))
2567 return StmtError();
2568
2569 Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);
2570 ParseDeclarator(D&: ExDecl);
2571 ExceptionDecl = Actions.ActOnExceptionDeclarator(S: getCurScope(), D&: ExDecl);
2572 } else
2573 ConsumeToken();
2574
2575 T.consumeClose();
2576 if (T.getCloseLocation().isInvalid())
2577 return StmtError();
2578
2579 if (Tok.isNot(K: tok::l_brace))
2580 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
2581
2582 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2583 StmtResult Block(ParseCompoundStatement());
2584 if (Block.isInvalid())
2585 return Block;
2586
2587 return Actions.ActOnCXXCatchBlock(CatchLoc, ExDecl: ExceptionDecl, HandlerBlock: Block.get());
2588}
2589
2590void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2591 IfExistsCondition Result;
2592 if (ParseMicrosoftIfExistsCondition(Result))
2593 return;
2594
2595 // Handle dependent statements by parsing the braces as a compound statement.
2596 // This is not the same behavior as Visual C++, which don't treat this as a
2597 // compound statement, but for Clang's type checking we can't have anything
2598 // inside these braces escaping to the surrounding code.
2599 if (Result.Behavior == IfExistsBehavior::Dependent) {
2600 if (!Tok.is(K: tok::l_brace)) {
2601 Diag(Tok, DiagID: diag::err_expected) << tok::l_brace;
2602 return;
2603 }
2604
2605 StmtResult Compound = ParseCompoundStatement();
2606 if (Compound.isInvalid())
2607 return;
2608
2609 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(KeywordLoc: Result.KeywordLoc,
2610 IsIfExists: Result.IsIfExists,
2611 SS&: Result.SS,
2612 Name&: Result.Name,
2613 Nested: Compound.get());
2614 if (DepResult.isUsable())
2615 Stmts.push_back(Elt: DepResult.get());
2616 return;
2617 }
2618
2619 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2620 if (Braces.consumeOpen()) {
2621 Diag(Tok, DiagID: diag::err_expected) << tok::l_brace;
2622 return;
2623 }
2624
2625 switch (Result.Behavior) {
2626 case IfExistsBehavior::Parse:
2627 // Parse the statements below.
2628 break;
2629
2630 case IfExistsBehavior::Dependent:
2631 llvm_unreachable("Dependent case handled above");
2632
2633 case IfExistsBehavior::Skip:
2634 Braces.skipToEnd();
2635 return;
2636 }
2637
2638 // Condition is true, parse the statements.
2639 while (Tok.isNot(K: tok::r_brace)) {
2640 StmtResult R =
2641 ParseStatementOrDeclaration(Stmts, StmtCtx: ParsedStmtContext::Compound);
2642 if (R.isUsable())
2643 Stmts.push_back(Elt: R.get());
2644 }
2645 Braces.consumeClose();
2646}
2647

source code of clang/lib/Parse/ParseStmt.cpp