ParseStmt.cpp 94 KB

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