ParseStmt.cpp 81 KB

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