ParseStmt.cpp 91 KB

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