ParseStmt.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Statement and Block portions of the Parser
  11. // interface.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Parse/Parser.h"
  15. #include "RAIIObjectsForParser.h"
  16. #include "clang/Sema/DeclSpec.h"
  17. #include "clang/Sema/PrettyDeclStackTrace.h"
  18. #include "clang/Sema/Scope.h"
  19. #include "clang/Basic/Diagnostic.h"
  20. #include "clang/Basic/PrettyStackTrace.h"
  21. #include "clang/Basic/SourceManager.h"
  22. using namespace clang;
  23. //===----------------------------------------------------------------------===//
  24. // C99 6.8: Statements and Blocks.
  25. //===----------------------------------------------------------------------===//
  26. /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
  27. /// StatementOrDeclaration:
  28. /// statement
  29. /// declaration
  30. ///
  31. /// statement:
  32. /// labeled-statement
  33. /// compound-statement
  34. /// expression-statement
  35. /// selection-statement
  36. /// iteration-statement
  37. /// jump-statement
  38. /// [C++] declaration-statement
  39. /// [C++] try-block
  40. /// [MS] seh-try-block
  41. /// [OBC] objc-throw-statement
  42. /// [OBC] objc-try-catch-statement
  43. /// [OBC] objc-synchronized-statement
  44. /// [GNU] asm-statement
  45. /// [OMP] openmp-construct [TODO]
  46. ///
  47. /// labeled-statement:
  48. /// identifier ':' statement
  49. /// 'case' constant-expression ':' statement
  50. /// 'default' ':' statement
  51. ///
  52. /// selection-statement:
  53. /// if-statement
  54. /// switch-statement
  55. ///
  56. /// iteration-statement:
  57. /// while-statement
  58. /// do-statement
  59. /// for-statement
  60. ///
  61. /// expression-statement:
  62. /// expression[opt] ';'
  63. ///
  64. /// jump-statement:
  65. /// 'goto' identifier ';'
  66. /// 'continue' ';'
  67. /// 'break' ';'
  68. /// 'return' expression[opt] ';'
  69. /// [GNU] 'goto' '*' expression ';'
  70. ///
  71. /// [OBC] objc-throw-statement:
  72. /// [OBC] '@' 'throw' expression ';'
  73. /// [OBC] '@' 'throw' ';'
  74. ///
  75. StmtResult
  76. Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
  77. SourceLocation *TrailingElseLoc) {
  78. const char *SemiError = 0;
  79. StmtResult Res;
  80. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  81. ParsedAttributesWithRange attrs(AttrFactory);
  82. MaybeParseCXX0XAttributes(attrs);
  83. // Cases in this switch statement should fall through if the parser expects
  84. // the token to end in a semicolon (in which case SemiError should be set),
  85. // or they directly 'return;' if not.
  86. Retry:
  87. tok::TokenKind Kind = Tok.getKind();
  88. SourceLocation AtLoc;
  89. switch (Kind) {
  90. case tok::at: // May be a @try or @throw statement
  91. {
  92. AtLoc = ConsumeToken(); // consume @
  93. return ParseObjCAtStatement(AtLoc);
  94. }
  95. case tok::code_completion:
  96. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
  97. cutOffParsing();
  98. return StmtError();
  99. case tok::identifier: {
  100. Token Next = NextToken();
  101. if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
  102. // identifier ':' statement
  103. return ParseLabeledStatement(attrs);
  104. }
  105. if (Next.isNot(tok::coloncolon)) {
  106. CXXScopeSpec SS;
  107. IdentifierInfo *Name = Tok.getIdentifierInfo();
  108. SourceLocation NameLoc = Tok.getLocation();
  109. if (getLangOpts().CPlusPlus)
  110. CheckForTemplateAndDigraph(Next, ParsedType(),
  111. /*EnteringContext=*/false, *Name, SS);
  112. Sema::NameClassification Classification
  113. = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next);
  114. switch (Classification.getKind()) {
  115. case Sema::NC_Keyword:
  116. // The identifier was corrected to a keyword. Update the token
  117. // to this keyword, and try again.
  118. if (Name->getTokenID() != tok::identifier) {
  119. Tok.setIdentifierInfo(Name);
  120. Tok.setKind(Name->getTokenID());
  121. goto Retry;
  122. }
  123. // Fall through via the normal error path.
  124. // FIXME: This seems like it could only happen for context-sensitive
  125. // keywords.
  126. case Sema::NC_Error:
  127. // Handle errors here by skipping up to the next semicolon or '}', and
  128. // eat the semicolon if that's what stopped us.
  129. SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
  130. if (Tok.is(tok::semi))
  131. ConsumeToken();
  132. return StmtError();
  133. case Sema::NC_Unknown:
  134. // Either we don't know anything about this identifier, or we know that
  135. // we're in a syntactic context we haven't handled yet.
  136. break;
  137. case Sema::NC_Type:
  138. Tok.setKind(tok::annot_typename);
  139. setTypeAnnotation(Tok, Classification.getType());
  140. Tok.setAnnotationEndLoc(NameLoc);
  141. PP.AnnotateCachedTokens(Tok);
  142. break;
  143. case Sema::NC_Expression:
  144. Tok.setKind(tok::annot_primary_expr);
  145. setExprAnnotation(Tok, Classification.getExpression());
  146. Tok.setAnnotationEndLoc(NameLoc);
  147. PP.AnnotateCachedTokens(Tok);
  148. break;
  149. case Sema::NC_TypeTemplate:
  150. case Sema::NC_FunctionTemplate: {
  151. ConsumeToken(); // the identifier
  152. UnqualifiedId Id;
  153. Id.setIdentifier(Name, NameLoc);
  154. if (AnnotateTemplateIdToken(
  155. TemplateTy::make(Classification.getTemplateName()),
  156. Classification.getTemplateNameKind(),
  157. SS, SourceLocation(), Id,
  158. /*AllowTypeAnnotation=*/false)) {
  159. // Handle errors here by skipping up to the next semicolon or '}', and
  160. // eat the semicolon if that's what stopped us.
  161. SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
  162. if (Tok.is(tok::semi))
  163. ConsumeToken();
  164. return StmtError();
  165. }
  166. // If the next token is '::', jump right into parsing a
  167. // nested-name-specifier. We don't want to leave the template-id
  168. // hanging.
  169. if (NextToken().is(tok::coloncolon) && TryAnnotateCXXScopeToken(false)){
  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=*/true, /*DontConsume=*/true);
  173. if (Tok.is(tok::semi))
  174. ConsumeToken();
  175. return StmtError();
  176. }
  177. // We've annotated a template-id, so try again now.
  178. goto Retry;
  179. }
  180. case Sema::NC_NestedNameSpecifier:
  181. // FIXME: Implement this!
  182. break;
  183. }
  184. }
  185. // Fall through
  186. }
  187. default: {
  188. if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
  189. SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
  190. DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
  191. DeclEnd, attrs);
  192. return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
  193. }
  194. if (Tok.is(tok::r_brace)) {
  195. Diag(Tok, diag::err_expected_statement);
  196. return StmtError();
  197. }
  198. return ParseExprStatement(attrs);
  199. }
  200. case tok::kw_case: // C99 6.8.1: labeled-statement
  201. return ParseCaseStatement(attrs);
  202. case tok::kw_default: // C99 6.8.1: labeled-statement
  203. return ParseDefaultStatement(attrs);
  204. case tok::l_brace: // C99 6.8.2: compound-statement
  205. return ParseCompoundStatement(attrs);
  206. case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
  207. bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
  208. return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
  209. }
  210. case tok::kw_if: // C99 6.8.4.1: if-statement
  211. return ParseIfStatement(attrs, TrailingElseLoc);
  212. case tok::kw_switch: // C99 6.8.4.2: switch-statement
  213. return ParseSwitchStatement(attrs, TrailingElseLoc);
  214. case tok::kw_while: // C99 6.8.5.1: while-statement
  215. return ParseWhileStatement(attrs, TrailingElseLoc);
  216. case tok::kw_do: // C99 6.8.5.2: do-statement
  217. Res = ParseDoStatement(attrs);
  218. SemiError = "do/while";
  219. break;
  220. case tok::kw_for: // C99 6.8.5.3: for-statement
  221. return ParseForStatement(attrs, TrailingElseLoc);
  222. case tok::kw_goto: // C99 6.8.6.1: goto-statement
  223. Res = ParseGotoStatement(attrs);
  224. SemiError = "goto";
  225. break;
  226. case tok::kw_continue: // C99 6.8.6.2: continue-statement
  227. Res = ParseContinueStatement(attrs);
  228. SemiError = "continue";
  229. break;
  230. case tok::kw_break: // C99 6.8.6.3: break-statement
  231. Res = ParseBreakStatement(attrs);
  232. SemiError = "break";
  233. break;
  234. case tok::kw_return: // C99 6.8.6.4: return-statement
  235. Res = ParseReturnStatement(attrs);
  236. SemiError = "return";
  237. break;
  238. case tok::kw_asm: {
  239. ProhibitAttributes(attrs);
  240. bool msAsm = false;
  241. Res = ParseAsmStatement(msAsm);
  242. Res = Actions.ActOnFinishFullStmt(Res.get());
  243. if (msAsm) return move(Res);
  244. SemiError = "asm";
  245. break;
  246. }
  247. case tok::kw_try: // C++ 15: try-block
  248. return ParseCXXTryBlock(attrs);
  249. case tok::kw___try:
  250. return ParseSEHTryBlock(attrs);
  251. case tok::annot_pragma_vis:
  252. HandlePragmaVisibility();
  253. return StmtEmpty();
  254. case tok::annot_pragma_pack:
  255. HandlePragmaPack();
  256. return StmtEmpty();
  257. }
  258. // If we reached this code, the statement must end in a semicolon.
  259. if (Tok.is(tok::semi)) {
  260. ConsumeToken();
  261. } else if (!Res.isInvalid()) {
  262. // If the result was valid, then we do want to diagnose this. Use
  263. // ExpectAndConsume to emit the diagnostic, even though we know it won't
  264. // succeed.
  265. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
  266. // Skip until we see a } or ;, but don't eat it.
  267. SkipUntil(tok::r_brace, true, true);
  268. }
  269. return move(Res);
  270. }
  271. /// \brief Parse an expression statement.
  272. StmtResult Parser::ParseExprStatement(ParsedAttributes &Attrs) {
  273. // If a case keyword is missing, this is where it should be inserted.
  274. Token OldToken = Tok;
  275. // FIXME: Use the attributes
  276. // expression[opt] ';'
  277. ExprResult Expr(ParseExpression());
  278. if (Expr.isInvalid()) {
  279. // If the expression is invalid, skip ahead to the next semicolon or '}'.
  280. // Not doing this opens us up to the possibility of infinite loops if
  281. // ParseExpression does not consume any tokens.
  282. SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
  283. if (Tok.is(tok::semi))
  284. ConsumeToken();
  285. return StmtError();
  286. }
  287. if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
  288. Actions.CheckCaseExpression(Expr.get())) {
  289. // If a constant expression is followed by a colon inside a switch block,
  290. // suggest a missing case keyword.
  291. Diag(OldToken, diag::err_expected_case_before_expression)
  292. << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
  293. // Recover parsing as a case statement.
  294. return ParseCaseStatement(Attrs, /*MissingCase=*/true, Expr);
  295. }
  296. // Otherwise, eat the semicolon.
  297. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
  298. return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
  299. }
  300. StmtResult Parser::ParseSEHTryBlock(ParsedAttributes & Attrs) {
  301. assert(Tok.is(tok::kw___try) && "Expected '__try'");
  302. SourceLocation Loc = ConsumeToken();
  303. return ParseSEHTryBlockCommon(Loc);
  304. }
  305. /// ParseSEHTryBlockCommon
  306. ///
  307. /// seh-try-block:
  308. /// '__try' compound-statement seh-handler
  309. ///
  310. /// seh-handler:
  311. /// seh-except-block
  312. /// seh-finally-block
  313. ///
  314. StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
  315. if(Tok.isNot(tok::l_brace))
  316. return StmtError(Diag(Tok,diag::err_expected_lbrace));
  317. ParsedAttributesWithRange attrs(AttrFactory);
  318. StmtResult TryBlock(ParseCompoundStatement(attrs));
  319. if(TryBlock.isInvalid())
  320. return move(TryBlock);
  321. StmtResult Handler;
  322. if (Tok.is(tok::identifier) &&
  323. Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
  324. SourceLocation Loc = ConsumeToken();
  325. Handler = ParseSEHExceptBlock(Loc);
  326. } else if (Tok.is(tok::kw___finally)) {
  327. SourceLocation Loc = ConsumeToken();
  328. Handler = ParseSEHFinallyBlock(Loc);
  329. } else {
  330. return StmtError(Diag(Tok,diag::err_seh_expected_handler));
  331. }
  332. if(Handler.isInvalid())
  333. return move(Handler);
  334. return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
  335. TryLoc,
  336. TryBlock.take(),
  337. Handler.take());
  338. }
  339. /// ParseSEHExceptBlock - Handle __except
  340. ///
  341. /// seh-except-block:
  342. /// '__except' '(' seh-filter-expression ')' compound-statement
  343. ///
  344. StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
  345. PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
  346. raii2(Ident___exception_code, false),
  347. raii3(Ident_GetExceptionCode, false);
  348. if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
  349. return StmtError();
  350. ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
  351. if (getLangOpts().Borland) {
  352. Ident__exception_info->setIsPoisoned(false);
  353. Ident___exception_info->setIsPoisoned(false);
  354. Ident_GetExceptionInfo->setIsPoisoned(false);
  355. }
  356. ExprResult FilterExpr(ParseExpression());
  357. if (getLangOpts().Borland) {
  358. Ident__exception_info->setIsPoisoned(true);
  359. Ident___exception_info->setIsPoisoned(true);
  360. Ident_GetExceptionInfo->setIsPoisoned(true);
  361. }
  362. if(FilterExpr.isInvalid())
  363. return StmtError();
  364. if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
  365. return StmtError();
  366. ParsedAttributesWithRange attrs(AttrFactory);
  367. StmtResult Block(ParseCompoundStatement(attrs));
  368. if(Block.isInvalid())
  369. return move(Block);
  370. return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
  371. }
  372. /// ParseSEHFinallyBlock - Handle __finally
  373. ///
  374. /// seh-finally-block:
  375. /// '__finally' compound-statement
  376. ///
  377. StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
  378. PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
  379. raii2(Ident___abnormal_termination, false),
  380. raii3(Ident_AbnormalTermination, false);
  381. ParsedAttributesWithRange attrs(AttrFactory);
  382. StmtResult Block(ParseCompoundStatement(attrs));
  383. if(Block.isInvalid())
  384. return move(Block);
  385. return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
  386. }
  387. /// ParseLabeledStatement - We have an identifier and a ':' after it.
  388. ///
  389. /// labeled-statement:
  390. /// identifier ':' statement
  391. /// [GNU] identifier ':' attributes[opt] statement
  392. ///
  393. StmtResult Parser::ParseLabeledStatement(ParsedAttributes &attrs) {
  394. assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
  395. "Not an identifier!");
  396. Token IdentTok = Tok; // Save the whole token.
  397. ConsumeToken(); // eat the identifier.
  398. assert(Tok.is(tok::colon) && "Not a label!");
  399. // identifier ':' statement
  400. SourceLocation ColonLoc = ConsumeToken();
  401. // Read label attributes, if present.
  402. MaybeParseGNUAttributes(attrs);
  403. StmtResult SubStmt(ParseStatement());
  404. // Broken substmt shouldn't prevent the label from being added to the AST.
  405. if (SubStmt.isInvalid())
  406. SubStmt = Actions.ActOnNullStmt(ColonLoc);
  407. LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
  408. IdentTok.getLocation());
  409. if (AttributeList *Attrs = attrs.getList())
  410. Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
  411. return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
  412. SubStmt.get());
  413. }
  414. /// ParseCaseStatement
  415. /// labeled-statement:
  416. /// 'case' constant-expression ':' statement
  417. /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
  418. ///
  419. StmtResult Parser::ParseCaseStatement(ParsedAttributes &attrs, bool MissingCase,
  420. ExprResult Expr) {
  421. assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
  422. // FIXME: Use attributes?
  423. // It is very very common for code to contain many case statements recursively
  424. // nested, as in (but usually without indentation):
  425. // case 1:
  426. // case 2:
  427. // case 3:
  428. // case 4:
  429. // case 5: etc.
  430. //
  431. // Parsing this naively works, but is both inefficient and can cause us to run
  432. // out of stack space in our recursive descent parser. As a special case,
  433. // flatten this recursion into an iterative loop. This is complex and gross,
  434. // but all the grossness is constrained to ParseCaseStatement (and some
  435. // wierdness in the actions), so this is just local grossness :).
  436. // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
  437. // example above.
  438. StmtResult TopLevelCase(true);
  439. // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
  440. // gets updated each time a new case is parsed, and whose body is unset so
  441. // far. When parsing 'case 4', this is the 'case 3' node.
  442. Stmt *DeepestParsedCaseStmt = 0;
  443. // While we have case statements, eat and stack them.
  444. SourceLocation ColonLoc;
  445. do {
  446. SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
  447. ConsumeToken(); // eat the 'case'.
  448. if (Tok.is(tok::code_completion)) {
  449. Actions.CodeCompleteCase(getCurScope());
  450. cutOffParsing();
  451. return StmtError();
  452. }
  453. /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
  454. /// Disable this form of error recovery while we're parsing the case
  455. /// expression.
  456. ColonProtectionRAIIObject ColonProtection(*this);
  457. ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
  458. MissingCase = false;
  459. if (LHS.isInvalid()) {
  460. SkipUntil(tok::colon);
  461. return StmtError();
  462. }
  463. // GNU case range extension.
  464. SourceLocation DotDotDotLoc;
  465. ExprResult RHS;
  466. if (Tok.is(tok::ellipsis)) {
  467. Diag(Tok, diag::ext_gnu_case_range);
  468. DotDotDotLoc = ConsumeToken();
  469. RHS = ParseConstantExpression();
  470. if (RHS.isInvalid()) {
  471. SkipUntil(tok::colon);
  472. return StmtError();
  473. }
  474. }
  475. ColonProtection.restore();
  476. if (Tok.is(tok::colon)) {
  477. ColonLoc = ConsumeToken();
  478. // Treat "case blah;" as a typo for "case blah:".
  479. } else if (Tok.is(tok::semi)) {
  480. ColonLoc = ConsumeToken();
  481. Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
  482. << FixItHint::CreateReplacement(ColonLoc, ":");
  483. } else {
  484. SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
  485. Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
  486. << FixItHint::CreateInsertion(ExpectedLoc, ":");
  487. ColonLoc = ExpectedLoc;
  488. }
  489. StmtResult Case =
  490. Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
  491. RHS.get(), ColonLoc);
  492. // If we had a sema error parsing this case, then just ignore it and
  493. // continue parsing the sub-stmt.
  494. if (Case.isInvalid()) {
  495. if (TopLevelCase.isInvalid()) // No parsed case stmts.
  496. return ParseStatement();
  497. // Otherwise, just don't add it as a nested case.
  498. } else {
  499. // If this is the first case statement we parsed, it becomes TopLevelCase.
  500. // Otherwise we link it into the current chain.
  501. Stmt *NextDeepest = Case.get();
  502. if (TopLevelCase.isInvalid())
  503. TopLevelCase = move(Case);
  504. else
  505. Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
  506. DeepestParsedCaseStmt = NextDeepest;
  507. }
  508. // Handle all case statements.
  509. } while (Tok.is(tok::kw_case));
  510. assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
  511. // If we found a non-case statement, start by parsing it.
  512. StmtResult SubStmt;
  513. if (Tok.isNot(tok::r_brace)) {
  514. SubStmt = ParseStatement();
  515. } else {
  516. // Nicely diagnose the common error "switch (X) { case 4: }", which is
  517. // not valid.
  518. SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
  519. Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
  520. << FixItHint::CreateInsertion(AfterColonLoc, " ;");
  521. SubStmt = true;
  522. }
  523. // Broken sub-stmt shouldn't prevent forming the case statement properly.
  524. if (SubStmt.isInvalid())
  525. SubStmt = Actions.ActOnNullStmt(SourceLocation());
  526. // Install the body into the most deeply-nested case.
  527. Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
  528. // Return the top level parsed statement tree.
  529. return move(TopLevelCase);
  530. }
  531. /// ParseDefaultStatement
  532. /// labeled-statement:
  533. /// 'default' ':' statement
  534. /// Note that this does not parse the 'statement' at the end.
  535. ///
  536. StmtResult Parser::ParseDefaultStatement(ParsedAttributes &attrs) {
  537. //FIXME: Use attributes?
  538. assert(Tok.is(tok::kw_default) && "Not a default stmt!");
  539. SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
  540. SourceLocation ColonLoc;
  541. if (Tok.is(tok::colon)) {
  542. ColonLoc = ConsumeToken();
  543. // Treat "default;" as a typo for "default:".
  544. } else if (Tok.is(tok::semi)) {
  545. ColonLoc = ConsumeToken();
  546. Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
  547. << FixItHint::CreateReplacement(ColonLoc, ":");
  548. } else {
  549. SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
  550. Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
  551. << FixItHint::CreateInsertion(ExpectedLoc, ":");
  552. ColonLoc = ExpectedLoc;
  553. }
  554. StmtResult SubStmt;
  555. if (Tok.isNot(tok::r_brace)) {
  556. SubStmt = ParseStatement();
  557. } else {
  558. // Diagnose the common error "switch (X) {... default: }", which is
  559. // not valid.
  560. SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
  561. Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
  562. << FixItHint::CreateInsertion(AfterColonLoc, " ;");
  563. SubStmt = true;
  564. }
  565. // Broken sub-stmt shouldn't prevent forming the case statement properly.
  566. if (SubStmt.isInvalid())
  567. SubStmt = Actions.ActOnNullStmt(ColonLoc);
  568. return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
  569. SubStmt.get(), getCurScope());
  570. }
  571. StmtResult Parser::ParseCompoundStatement(ParsedAttributes &Attr,
  572. bool isStmtExpr) {
  573. return ParseCompoundStatement(Attr, isStmtExpr, Scope::DeclScope);
  574. }
  575. /// ParseCompoundStatement - Parse a "{}" block.
  576. ///
  577. /// compound-statement: [C99 6.8.2]
  578. /// { block-item-list[opt] }
  579. /// [GNU] { label-declarations block-item-list } [TODO]
  580. ///
  581. /// block-item-list:
  582. /// block-item
  583. /// block-item-list block-item
  584. ///
  585. /// block-item:
  586. /// declaration
  587. /// [GNU] '__extension__' declaration
  588. /// statement
  589. /// [OMP] openmp-directive [TODO]
  590. ///
  591. /// [GNU] label-declarations:
  592. /// [GNU] label-declaration
  593. /// [GNU] label-declarations label-declaration
  594. ///
  595. /// [GNU] label-declaration:
  596. /// [GNU] '__label__' identifier-list ';'
  597. ///
  598. /// [OMP] openmp-directive: [TODO]
  599. /// [OMP] barrier-directive
  600. /// [OMP] flush-directive
  601. ///
  602. StmtResult Parser::ParseCompoundStatement(ParsedAttributes &attrs,
  603. bool isStmtExpr,
  604. unsigned ScopeFlags) {
  605. //FIXME: Use attributes?
  606. assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
  607. // Enter a scope to hold everything within the compound stmt. Compound
  608. // statements can always hold declarations.
  609. ParseScope CompoundScope(this, ScopeFlags);
  610. // Parse the statements in the body.
  611. return ParseCompoundStatementBody(isStmtExpr);
  612. }
  613. /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
  614. /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
  615. /// consume the '}' at the end of the block. It does not manipulate the scope
  616. /// stack.
  617. StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
  618. PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
  619. Tok.getLocation(),
  620. "in compound statement ('{}')");
  621. InMessageExpressionRAIIObject InMessage(*this, false);
  622. BalancedDelimiterTracker T(*this, tok::l_brace);
  623. if (T.consumeOpen())
  624. return StmtError();
  625. Sema::CompoundScopeRAII CompoundScope(Actions);
  626. StmtVector Stmts(Actions);
  627. // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
  628. // only allowed at the start of a compound stmt regardless of the language.
  629. while (Tok.is(tok::kw___label__)) {
  630. SourceLocation LabelLoc = ConsumeToken();
  631. Diag(LabelLoc, diag::ext_gnu_local_label);
  632. SmallVector<Decl *, 8> DeclsInGroup;
  633. while (1) {
  634. if (Tok.isNot(tok::identifier)) {
  635. Diag(Tok, diag::err_expected_ident);
  636. break;
  637. }
  638. IdentifierInfo *II = Tok.getIdentifierInfo();
  639. SourceLocation IdLoc = ConsumeToken();
  640. DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
  641. if (!Tok.is(tok::comma))
  642. break;
  643. ConsumeToken();
  644. }
  645. DeclSpec DS(AttrFactory);
  646. DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
  647. DeclsInGroup.data(), DeclsInGroup.size());
  648. StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
  649. ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
  650. if (R.isUsable())
  651. Stmts.push_back(R.release());
  652. }
  653. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  654. if (Tok.is(tok::annot_pragma_unused)) {
  655. HandlePragmaUnused();
  656. continue;
  657. }
  658. if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
  659. Tok.is(tok::kw___if_not_exists))) {
  660. ParseMicrosoftIfExistsStatement(Stmts);
  661. continue;
  662. }
  663. StmtResult R;
  664. if (Tok.isNot(tok::kw___extension__)) {
  665. R = ParseStatementOrDeclaration(Stmts, false);
  666. } else {
  667. // __extension__ can start declarations and it can also be a unary
  668. // operator for expressions. Consume multiple __extension__ markers here
  669. // until we can determine which is which.
  670. // FIXME: This loses extension expressions in the AST!
  671. SourceLocation ExtLoc = ConsumeToken();
  672. while (Tok.is(tok::kw___extension__))
  673. ConsumeToken();
  674. ParsedAttributesWithRange attrs(AttrFactory);
  675. MaybeParseCXX0XAttributes(attrs);
  676. // If this is the start of a declaration, parse it as such.
  677. if (isDeclarationStatement()) {
  678. // __extension__ silences extension warnings in the subdeclaration.
  679. // FIXME: Save the __extension__ on the decl as a node somehow?
  680. ExtensionRAIIObject O(Diags);
  681. SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
  682. DeclGroupPtrTy Res = ParseDeclaration(Stmts,
  683. Declarator::BlockContext, DeclEnd,
  684. attrs);
  685. R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
  686. } else {
  687. // Otherwise this was a unary __extension__ marker.
  688. ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
  689. if (Res.isInvalid()) {
  690. SkipUntil(tok::semi);
  691. continue;
  692. }
  693. // FIXME: Use attributes?
  694. // Eat the semicolon at the end of stmt and convert the expr into a
  695. // statement.
  696. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
  697. R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
  698. }
  699. }
  700. if (R.isUsable())
  701. Stmts.push_back(R.release());
  702. }
  703. // We broke out of the while loop because we found a '}' or EOF.
  704. if (Tok.isNot(tok::r_brace)) {
  705. Diag(Tok, diag::err_expected_rbrace);
  706. Diag(T.getOpenLocation(), diag::note_matching) << "{";
  707. return StmtError();
  708. }
  709. if (T.consumeClose())
  710. return StmtError();
  711. return Actions.ActOnCompoundStmt(T.getOpenLocation(), T.getCloseLocation(),
  712. move_arg(Stmts), isStmtExpr);
  713. }
  714. /// ParseParenExprOrCondition:
  715. /// [C ] '(' expression ')'
  716. /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
  717. ///
  718. /// This function parses and performs error recovery on the specified condition
  719. /// or expression (depending on whether we're in C++ or C mode). This function
  720. /// goes out of its way to recover well. It returns true if there was a parser
  721. /// error (the right paren couldn't be found), which indicates that the caller
  722. /// should try to recover harder. It returns false if the condition is
  723. /// successfully parsed. Note that a successful parse can still have semantic
  724. /// errors in the condition.
  725. bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
  726. Decl *&DeclResult,
  727. SourceLocation Loc,
  728. bool ConvertToBoolean) {
  729. BalancedDelimiterTracker T(*this, tok::l_paren);
  730. T.consumeOpen();
  731. if (getLangOpts().CPlusPlus)
  732. ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
  733. else {
  734. ExprResult = ParseExpression();
  735. DeclResult = 0;
  736. // If required, convert to a boolean value.
  737. if (!ExprResult.isInvalid() && ConvertToBoolean)
  738. ExprResult
  739. = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
  740. }
  741. // If the parser was confused by the condition and we don't have a ')', try to
  742. // recover by skipping ahead to a semi and bailing out. If condexp is
  743. // semantically invalid but we have well formed code, keep going.
  744. if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
  745. SkipUntil(tok::semi);
  746. // Skipping may have stopped if it found the containing ')'. If so, we can
  747. // continue parsing the if statement.
  748. if (Tok.isNot(tok::r_paren))
  749. return true;
  750. }
  751. // Otherwise the condition is valid or the rparen is present.
  752. T.consumeClose();
  753. return false;
  754. }
  755. /// ParseIfStatement
  756. /// if-statement: [C99 6.8.4.1]
  757. /// 'if' '(' expression ')' statement
  758. /// 'if' '(' expression ')' statement 'else' statement
  759. /// [C++] 'if' '(' condition ')' statement
  760. /// [C++] 'if' '(' condition ')' statement 'else' statement
  761. ///
  762. StmtResult Parser::ParseIfStatement(ParsedAttributes &attrs,
  763. SourceLocation *TrailingElseLoc) {
  764. // FIXME: Use attributes?
  765. assert(Tok.is(tok::kw_if) && "Not an if stmt!");
  766. SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
  767. if (Tok.isNot(tok::l_paren)) {
  768. Diag(Tok, diag::err_expected_lparen_after) << "if";
  769. SkipUntil(tok::semi);
  770. return StmtError();
  771. }
  772. bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
  773. // C99 6.8.4p3 - In C99, the if statement is a block. This is not
  774. // the case for C90.
  775. //
  776. // C++ 6.4p3:
  777. // A name introduced by a declaration in a condition is in scope from its
  778. // point of declaration until the end of the substatements controlled by the
  779. // condition.
  780. // C++ 3.3.2p4:
  781. // Names declared in the for-init-statement, and in the condition of if,
  782. // while, for, and switch statements are local to the if, while, for, or
  783. // switch statement (including the controlled statement).
  784. //
  785. ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
  786. // Parse the condition.
  787. ExprResult CondExp;
  788. Decl *CondVar = 0;
  789. if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
  790. return StmtError();
  791. FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
  792. // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
  793. // there is no compound stmt. C90 does not have this clause. We only do this
  794. // if the body isn't a compound statement to avoid push/pop in common cases.
  795. //
  796. // C++ 6.4p1:
  797. // The substatement in a selection-statement (each substatement, in the else
  798. // form of the if statement) implicitly defines a local scope.
  799. //
  800. // For C++ we create a scope for the condition and a new scope for
  801. // substatements because:
  802. // -When the 'then' scope exits, we want the condition declaration to still be
  803. // active for the 'else' scope too.
  804. // -Sema will detect name clashes by considering declarations of a
  805. // 'ControlScope' as part of its direct subscope.
  806. // -If we wanted the condition and substatement to be in the same scope, we
  807. // would have to notify ParseStatement not to create a new scope. It's
  808. // simpler to let it create a new scope.
  809. //
  810. ParseScope InnerScope(this, Scope::DeclScope,
  811. C99orCXX && Tok.isNot(tok::l_brace));
  812. // Read the 'then' stmt.
  813. SourceLocation ThenStmtLoc = Tok.getLocation();
  814. SourceLocation InnerStatementTrailingElseLoc;
  815. StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
  816. // Pop the 'if' scope if needed.
  817. InnerScope.Exit();
  818. // If it has an else, parse it.
  819. SourceLocation ElseLoc;
  820. SourceLocation ElseStmtLoc;
  821. StmtResult ElseStmt;
  822. if (Tok.is(tok::kw_else)) {
  823. if (TrailingElseLoc)
  824. *TrailingElseLoc = Tok.getLocation();
  825. ElseLoc = ConsumeToken();
  826. ElseStmtLoc = Tok.getLocation();
  827. // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
  828. // there is no compound stmt. C90 does not have this clause. We only do
  829. // this if the body isn't a compound statement to avoid push/pop in common
  830. // cases.
  831. //
  832. // C++ 6.4p1:
  833. // The substatement in a selection-statement (each substatement, in the else
  834. // form of the if statement) implicitly defines a local scope.
  835. //
  836. ParseScope InnerScope(this, Scope::DeclScope,
  837. C99orCXX && Tok.isNot(tok::l_brace));
  838. ElseStmt = ParseStatement();
  839. // Pop the 'else' scope if needed.
  840. InnerScope.Exit();
  841. } else if (Tok.is(tok::code_completion)) {
  842. Actions.CodeCompleteAfterIf(getCurScope());
  843. cutOffParsing();
  844. return StmtError();
  845. } else if (InnerStatementTrailingElseLoc.isValid()) {
  846. Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
  847. }
  848. IfScope.Exit();
  849. // If the condition was invalid, discard the if statement. We could recover
  850. // better by replacing it with a valid expr, but don't do that yet.
  851. if (CondExp.isInvalid() && !CondVar)
  852. return StmtError();
  853. // If the then or else stmt is invalid and the other is valid (and present),
  854. // make turn the invalid one into a null stmt to avoid dropping the other
  855. // part. If both are invalid, return error.
  856. if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
  857. (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
  858. (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
  859. // Both invalid, or one is invalid and other is non-present: return error.
  860. return StmtError();
  861. }
  862. // Now if either are invalid, replace with a ';'.
  863. if (ThenStmt.isInvalid())
  864. ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
  865. if (ElseStmt.isInvalid())
  866. ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
  867. return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
  868. ElseLoc, ElseStmt.get());
  869. }
  870. /// ParseSwitchStatement
  871. /// switch-statement:
  872. /// 'switch' '(' expression ')' statement
  873. /// [C++] 'switch' '(' condition ')' statement
  874. StmtResult Parser::ParseSwitchStatement(ParsedAttributes &attrs,
  875. SourceLocation *TrailingElseLoc) {
  876. // FIXME: Use attributes?
  877. assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
  878. SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
  879. if (Tok.isNot(tok::l_paren)) {
  880. Diag(Tok, diag::err_expected_lparen_after) << "switch";
  881. SkipUntil(tok::semi);
  882. return StmtError();
  883. }
  884. bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
  885. // C99 6.8.4p3 - In C99, the switch statement is a block. This is
  886. // not the case for C90. Start the switch scope.
  887. //
  888. // C++ 6.4p3:
  889. // A name introduced by a declaration in a condition is in scope from its
  890. // point of declaration until the end of the substatements controlled by the
  891. // condition.
  892. // C++ 3.3.2p4:
  893. // Names declared in the for-init-statement, and in the condition of if,
  894. // while, for, and switch statements are local to the if, while, for, or
  895. // switch statement (including the controlled statement).
  896. //
  897. unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
  898. if (C99orCXX)
  899. ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
  900. ParseScope SwitchScope(this, ScopeFlags);
  901. // Parse the condition.
  902. ExprResult Cond;
  903. Decl *CondVar = 0;
  904. if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
  905. return StmtError();
  906. StmtResult Switch
  907. = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
  908. if (Switch.isInvalid()) {
  909. // Skip the switch body.
  910. // FIXME: This is not optimal recovery, but parsing the body is more
  911. // dangerous due to the presence of case and default statements, which
  912. // will have no place to connect back with the switch.
  913. if (Tok.is(tok::l_brace)) {
  914. ConsumeBrace();
  915. SkipUntil(tok::r_brace, false, false);
  916. } else
  917. SkipUntil(tok::semi);
  918. return move(Switch);
  919. }
  920. // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
  921. // there is no compound stmt. C90 does not have this clause. We only do this
  922. // if the body isn't a compound statement to avoid push/pop in common cases.
  923. //
  924. // C++ 6.4p1:
  925. // The substatement in a selection-statement (each substatement, in the else
  926. // form of the if statement) implicitly defines a local scope.
  927. //
  928. // See comments in ParseIfStatement for why we create a scope for the
  929. // condition and a new scope for substatement in C++.
  930. //
  931. ParseScope InnerScope(this, Scope::DeclScope,
  932. C99orCXX && Tok.isNot(tok::l_brace));
  933. // Read the body statement.
  934. StmtResult Body(ParseStatement(TrailingElseLoc));
  935. // Pop the scopes.
  936. InnerScope.Exit();
  937. SwitchScope.Exit();
  938. if (Body.isInvalid()) {
  939. // FIXME: Remove the case statement list from the Switch statement.
  940. // Put the synthesized null statement on the same line as the end of switch
  941. // condition.
  942. SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
  943. Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
  944. }
  945. return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
  946. }
  947. /// ParseWhileStatement
  948. /// while-statement: [C99 6.8.5.1]
  949. /// 'while' '(' expression ')' statement
  950. /// [C++] 'while' '(' condition ')' statement
  951. StmtResult Parser::ParseWhileStatement(ParsedAttributes &attrs,
  952. SourceLocation *TrailingElseLoc) {
  953. // FIXME: Use attributes?
  954. assert(Tok.is(tok::kw_while) && "Not a while stmt!");
  955. SourceLocation WhileLoc = Tok.getLocation();
  956. ConsumeToken(); // eat the 'while'.
  957. if (Tok.isNot(tok::l_paren)) {
  958. Diag(Tok, diag::err_expected_lparen_after) << "while";
  959. SkipUntil(tok::semi);
  960. return StmtError();
  961. }
  962. bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
  963. // C99 6.8.5p5 - In C99, the while statement is a block. This is not
  964. // the case for C90. Start the loop scope.
  965. //
  966. // C++ 6.4p3:
  967. // A name introduced by a declaration in a condition is in scope from its
  968. // point of declaration until the end of the substatements controlled by the
  969. // condition.
  970. // C++ 3.3.2p4:
  971. // Names declared in the for-init-statement, and in the condition of if,
  972. // while, for, and switch statements are local to the if, while, for, or
  973. // switch statement (including the controlled statement).
  974. //
  975. unsigned ScopeFlags;
  976. if (C99orCXX)
  977. ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
  978. Scope::DeclScope | Scope::ControlScope;
  979. else
  980. ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
  981. ParseScope WhileScope(this, ScopeFlags);
  982. // Parse the condition.
  983. ExprResult Cond;
  984. Decl *CondVar = 0;
  985. if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
  986. return StmtError();
  987. FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
  988. // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
  989. // there is no compound stmt. C90 does not have this clause. We only do this
  990. // if the body isn't a compound statement to avoid push/pop in common cases.
  991. //
  992. // C++ 6.5p2:
  993. // The substatement in an iteration-statement implicitly defines a local scope
  994. // which is entered and exited each time through the loop.
  995. //
  996. // See comments in ParseIfStatement for why we create a scope for the
  997. // condition and a new scope for substatement in C++.
  998. //
  999. ParseScope InnerScope(this, Scope::DeclScope,
  1000. C99orCXX && Tok.isNot(tok::l_brace));
  1001. // Read the body statement.
  1002. StmtResult Body(ParseStatement(TrailingElseLoc));
  1003. // Pop the body scope if needed.
  1004. InnerScope.Exit();
  1005. WhileScope.Exit();
  1006. if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
  1007. return StmtError();
  1008. return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
  1009. }
  1010. /// ParseDoStatement
  1011. /// do-statement: [C99 6.8.5.2]
  1012. /// 'do' statement 'while' '(' expression ')' ';'
  1013. /// Note: this lets the caller parse the end ';'.
  1014. StmtResult Parser::ParseDoStatement(ParsedAttributes &attrs) {
  1015. // FIXME: Use attributes?
  1016. assert(Tok.is(tok::kw_do) && "Not a do stmt!");
  1017. SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
  1018. // C99 6.8.5p5 - In C99, the do statement is a block. This is not
  1019. // the case for C90. Start the loop scope.
  1020. unsigned ScopeFlags;
  1021. if (getLangOpts().C99)
  1022. ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
  1023. else
  1024. ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
  1025. ParseScope DoScope(this, ScopeFlags);
  1026. // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
  1027. // there is no compound stmt. C90 does not have this clause. We only do this
  1028. // if the body isn't a compound statement to avoid push/pop in common cases.
  1029. //
  1030. // C++ 6.5p2:
  1031. // The substatement in an iteration-statement implicitly defines a local scope
  1032. // which is entered and exited each time through the loop.
  1033. //
  1034. ParseScope InnerScope(this, Scope::DeclScope,
  1035. (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
  1036. Tok.isNot(tok::l_brace));
  1037. // Read the body statement.
  1038. StmtResult Body(ParseStatement());
  1039. // Pop the body scope if needed.
  1040. InnerScope.Exit();
  1041. if (Tok.isNot(tok::kw_while)) {
  1042. if (!Body.isInvalid()) {
  1043. Diag(Tok, diag::err_expected_while);
  1044. Diag(DoLoc, diag::note_matching) << "do";
  1045. SkipUntil(tok::semi, false, true);
  1046. }
  1047. return StmtError();
  1048. }
  1049. SourceLocation WhileLoc = ConsumeToken();
  1050. if (Tok.isNot(tok::l_paren)) {
  1051. Diag(Tok, diag::err_expected_lparen_after) << "do/while";
  1052. SkipUntil(tok::semi, false, true);
  1053. return StmtError();
  1054. }
  1055. // Parse the parenthesized condition.
  1056. BalancedDelimiterTracker T(*this, tok::l_paren);
  1057. T.consumeOpen();
  1058. ExprResult Cond = ParseExpression();
  1059. T.consumeClose();
  1060. DoScope.Exit();
  1061. if (Cond.isInvalid() || Body.isInvalid())
  1062. return StmtError();
  1063. return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
  1064. Cond.get(), T.getCloseLocation());
  1065. }
  1066. /// ParseForStatement
  1067. /// for-statement: [C99 6.8.5.3]
  1068. /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
  1069. /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
  1070. /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
  1071. /// [C++] statement
  1072. /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
  1073. /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
  1074. /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
  1075. ///
  1076. /// [C++] for-init-statement:
  1077. /// [C++] expression-statement
  1078. /// [C++] simple-declaration
  1079. ///
  1080. /// [C++0x] for-range-declaration:
  1081. /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
  1082. /// [C++0x] for-range-initializer:
  1083. /// [C++0x] expression
  1084. /// [C++0x] braced-init-list [TODO]
  1085. StmtResult Parser::ParseForStatement(ParsedAttributes &attrs,
  1086. SourceLocation *TrailingElseLoc) {
  1087. // FIXME: Use attributes?
  1088. assert(Tok.is(tok::kw_for) && "Not a for stmt!");
  1089. SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
  1090. if (Tok.isNot(tok::l_paren)) {
  1091. Diag(Tok, diag::err_expected_lparen_after) << "for";
  1092. SkipUntil(tok::semi);
  1093. return StmtError();
  1094. }
  1095. bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || getLangOpts().ObjC1;
  1096. // C99 6.8.5p5 - In C99, the for statement is a block. This is not
  1097. // the case for C90. Start the loop scope.
  1098. //
  1099. // C++ 6.4p3:
  1100. // A name introduced by a declaration in a condition is in scope from its
  1101. // point of declaration until the end of the substatements controlled by the
  1102. // condition.
  1103. // C++ 3.3.2p4:
  1104. // Names declared in the for-init-statement, and in the condition of if,
  1105. // while, for, and switch statements are local to the if, while, for, or
  1106. // switch statement (including the controlled statement).
  1107. // C++ 6.5.3p1:
  1108. // Names declared in the for-init-statement are in the same declarative-region
  1109. // as those declared in the condition.
  1110. //
  1111. unsigned ScopeFlags;
  1112. if (C99orCXXorObjC)
  1113. ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
  1114. Scope::DeclScope | Scope::ControlScope;
  1115. else
  1116. ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
  1117. ParseScope ForScope(this, ScopeFlags);
  1118. BalancedDelimiterTracker T(*this, tok::l_paren);
  1119. T.consumeOpen();
  1120. ExprResult Value;
  1121. bool ForEach = false, ForRange = false;
  1122. StmtResult FirstPart;
  1123. bool SecondPartIsInvalid = false;
  1124. FullExprArg SecondPart(Actions);
  1125. ExprResult Collection;
  1126. ForRangeInit ForRangeInit;
  1127. FullExprArg ThirdPart(Actions);
  1128. Decl *SecondVar = 0;
  1129. if (Tok.is(tok::code_completion)) {
  1130. Actions.CodeCompleteOrdinaryName(getCurScope(),
  1131. C99orCXXorObjC? Sema::PCC_ForInit
  1132. : Sema::PCC_Expression);
  1133. cutOffParsing();
  1134. return StmtError();
  1135. }
  1136. // Parse the first part of the for specifier.
  1137. if (Tok.is(tok::semi)) { // for (;
  1138. // no first part, eat the ';'.
  1139. ConsumeToken();
  1140. } else if (isForInitDeclaration()) { // for (int X = 4;
  1141. // Parse declaration, which eats the ';'.
  1142. if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
  1143. Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
  1144. ParsedAttributesWithRange attrs(AttrFactory);
  1145. MaybeParseCXX0XAttributes(attrs);
  1146. // In C++0x, "for (T NS:a" might not be a typo for ::
  1147. bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
  1148. ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
  1149. SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
  1150. StmtVector Stmts(Actions);
  1151. DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
  1152. DeclEnd, attrs, false,
  1153. MightBeForRangeStmt ?
  1154. &ForRangeInit : 0);
  1155. FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
  1156. if (ForRangeInit.ParsedForRangeDecl()) {
  1157. Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
  1158. diag::warn_cxx98_compat_for_range : diag::ext_for_range);
  1159. ForRange = true;
  1160. } else if (Tok.is(tok::semi)) { // for (int x = 4;
  1161. ConsumeToken();
  1162. } else if ((ForEach = isTokIdentifier_in())) {
  1163. Actions.ActOnForEachDeclStmt(DG);
  1164. // ObjC: for (id x in expr)
  1165. ConsumeToken(); // consume 'in'
  1166. if (Tok.is(tok::code_completion)) {
  1167. Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
  1168. cutOffParsing();
  1169. return StmtError();
  1170. }
  1171. Collection = ParseExpression();
  1172. } else {
  1173. Diag(Tok, diag::err_expected_semi_for);
  1174. }
  1175. } else {
  1176. Value = ParseExpression();
  1177. ForEach = isTokIdentifier_in();
  1178. // Turn the expression into a stmt.
  1179. if (!Value.isInvalid()) {
  1180. if (ForEach)
  1181. FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
  1182. else
  1183. FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
  1184. }
  1185. if (Tok.is(tok::semi)) {
  1186. ConsumeToken();
  1187. } else if (ForEach) {
  1188. ConsumeToken(); // consume 'in'
  1189. if (Tok.is(tok::code_completion)) {
  1190. Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
  1191. cutOffParsing();
  1192. return StmtError();
  1193. }
  1194. Collection = ParseExpression();
  1195. } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPart.get()) {
  1196. // User tried to write the reasonable, but ill-formed, for-range-statement
  1197. // for (expr : expr) { ... }
  1198. Diag(Tok, diag::err_for_range_expected_decl)
  1199. << FirstPart.get()->getSourceRange();
  1200. SkipUntil(tok::r_paren, false, true);
  1201. SecondPartIsInvalid = true;
  1202. } else {
  1203. if (!Value.isInvalid()) {
  1204. Diag(Tok, diag::err_expected_semi_for);
  1205. } else {
  1206. // Skip until semicolon or rparen, don't consume it.
  1207. SkipUntil(tok::r_paren, true, true);
  1208. if (Tok.is(tok::semi))
  1209. ConsumeToken();
  1210. }
  1211. }
  1212. }
  1213. if (!ForEach && !ForRange) {
  1214. assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
  1215. // Parse the second part of the for specifier.
  1216. if (Tok.is(tok::semi)) { // for (...;;
  1217. // no second part.
  1218. } else if (Tok.is(tok::r_paren)) {
  1219. // missing both semicolons.
  1220. } else {
  1221. ExprResult Second;
  1222. if (getLangOpts().CPlusPlus)
  1223. ParseCXXCondition(Second, SecondVar, ForLoc, true);
  1224. else {
  1225. Second = ParseExpression();
  1226. if (!Second.isInvalid())
  1227. Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
  1228. Second.get());
  1229. }
  1230. SecondPartIsInvalid = Second.isInvalid();
  1231. SecondPart = Actions.MakeFullExpr(Second.get());
  1232. }
  1233. if (Tok.isNot(tok::semi)) {
  1234. if (!SecondPartIsInvalid || SecondVar)
  1235. Diag(Tok, diag::err_expected_semi_for);
  1236. else
  1237. // Skip until semicolon or rparen, don't consume it.
  1238. SkipUntil(tok::r_paren, true, true);
  1239. }
  1240. if (Tok.is(tok::semi)) {
  1241. ConsumeToken();
  1242. }
  1243. // Parse the third part of the for specifier.
  1244. if (Tok.isNot(tok::r_paren)) { // for (...;...;)
  1245. ExprResult Third = ParseExpression();
  1246. ThirdPart = Actions.MakeFullExpr(Third.take());
  1247. }
  1248. }
  1249. // Match the ')'.
  1250. T.consumeClose();
  1251. // We need to perform most of the semantic analysis for a C++0x for-range
  1252. // statememt before parsing the body, in order to be able to deduce the type
  1253. // of an auto-typed loop variable.
  1254. StmtResult ForRangeStmt;
  1255. if (ForRange) {
  1256. ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, T.getOpenLocation(),
  1257. FirstPart.take(),
  1258. ForRangeInit.ColonLoc,
  1259. ForRangeInit.RangeExpr.get(),
  1260. T.getCloseLocation());
  1261. // Similarly, we need to do the semantic analysis for a for-range
  1262. // statement immediately in order to close over temporaries correctly.
  1263. } else if (ForEach) {
  1264. if (!Collection.isInvalid())
  1265. Collection =
  1266. Actions.ActOnObjCForCollectionOperand(ForLoc, Collection.take());
  1267. }
  1268. // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
  1269. // there is no compound stmt. C90 does not have this clause. We only do this
  1270. // if the body isn't a compound statement to avoid push/pop in common cases.
  1271. //
  1272. // C++ 6.5p2:
  1273. // The substatement in an iteration-statement implicitly defines a local scope
  1274. // which is entered and exited each time through the loop.
  1275. //
  1276. // See comments in ParseIfStatement for why we create a scope for
  1277. // for-init-statement/condition and a new scope for substatement in C++.
  1278. //
  1279. ParseScope InnerScope(this, Scope::DeclScope,
  1280. C99orCXXorObjC && Tok.isNot(tok::l_brace));
  1281. // Read the body statement.
  1282. StmtResult Body(ParseStatement(TrailingElseLoc));
  1283. // Pop the body scope if needed.
  1284. InnerScope.Exit();
  1285. // Leave the for-scope.
  1286. ForScope.Exit();
  1287. if (Body.isInvalid())
  1288. return StmtError();
  1289. if (ForEach)
  1290. return Actions.ActOnObjCForCollectionStmt(ForLoc, T.getOpenLocation(),
  1291. FirstPart.take(),
  1292. Collection.take(),
  1293. T.getCloseLocation(),
  1294. Body.take());
  1295. if (ForRange)
  1296. return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
  1297. return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
  1298. SecondPart, SecondVar, ThirdPart,
  1299. T.getCloseLocation(), Body.take());
  1300. }
  1301. /// ParseGotoStatement
  1302. /// jump-statement:
  1303. /// 'goto' identifier ';'
  1304. /// [GNU] 'goto' '*' expression ';'
  1305. ///
  1306. /// Note: this lets the caller parse the end ';'.
  1307. ///
  1308. StmtResult Parser::ParseGotoStatement(ParsedAttributes &attrs) {
  1309. // FIXME: Use attributes?
  1310. assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
  1311. SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
  1312. StmtResult Res;
  1313. if (Tok.is(tok::identifier)) {
  1314. LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
  1315. Tok.getLocation());
  1316. Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
  1317. ConsumeToken();
  1318. } else if (Tok.is(tok::star)) {
  1319. // GNU indirect goto extension.
  1320. Diag(Tok, diag::ext_gnu_indirect_goto);
  1321. SourceLocation StarLoc = ConsumeToken();
  1322. ExprResult R(ParseExpression());
  1323. if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
  1324. SkipUntil(tok::semi, false, true);
  1325. return StmtError();
  1326. }
  1327. Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
  1328. } else {
  1329. Diag(Tok, diag::err_expected_ident);
  1330. return StmtError();
  1331. }
  1332. return move(Res);
  1333. }
  1334. /// ParseContinueStatement
  1335. /// jump-statement:
  1336. /// 'continue' ';'
  1337. ///
  1338. /// Note: this lets the caller parse the end ';'.
  1339. ///
  1340. StmtResult Parser::ParseContinueStatement(ParsedAttributes &attrs) {
  1341. // FIXME: Use attributes?
  1342. SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
  1343. return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
  1344. }
  1345. /// ParseBreakStatement
  1346. /// jump-statement:
  1347. /// 'break' ';'
  1348. ///
  1349. /// Note: this lets the caller parse the end ';'.
  1350. ///
  1351. StmtResult Parser::ParseBreakStatement(ParsedAttributes &attrs) {
  1352. // FIXME: Use attributes?
  1353. SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
  1354. return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
  1355. }
  1356. /// ParseReturnStatement
  1357. /// jump-statement:
  1358. /// 'return' expression[opt] ';'
  1359. StmtResult Parser::ParseReturnStatement(ParsedAttributes &attrs) {
  1360. // FIXME: Use attributes?
  1361. assert(Tok.is(tok::kw_return) && "Not a return stmt!");
  1362. SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
  1363. ExprResult R;
  1364. if (Tok.isNot(tok::semi)) {
  1365. if (Tok.is(tok::code_completion)) {
  1366. Actions.CodeCompleteReturn(getCurScope());
  1367. cutOffParsing();
  1368. return StmtError();
  1369. }
  1370. if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
  1371. R = ParseInitializer();
  1372. if (R.isUsable())
  1373. Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
  1374. diag::warn_cxx98_compat_generalized_initializer_lists :
  1375. diag::ext_generalized_initializer_lists)
  1376. << R.get()->getSourceRange();
  1377. } else
  1378. R = ParseExpression();
  1379. if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
  1380. SkipUntil(tok::semi, false, true);
  1381. return StmtError();
  1382. }
  1383. }
  1384. return Actions.ActOnReturnStmt(ReturnLoc, R.take());
  1385. }
  1386. /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
  1387. /// this routine is called to collect the tokens for an MS asm statement.
  1388. StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
  1389. SourceManager &SrcMgr = PP.getSourceManager();
  1390. SourceLocation EndLoc = AsmLoc;
  1391. do {
  1392. bool InBraces = false;
  1393. unsigned short savedBraceCount = 0;
  1394. bool InAsmComment = false;
  1395. FileID FID;
  1396. unsigned LineNo = 0;
  1397. unsigned NumTokensRead = 0;
  1398. SourceLocation LBraceLoc;
  1399. if (Tok.is(tok::l_brace)) {
  1400. // Braced inline asm: consume the opening brace.
  1401. InBraces = true;
  1402. savedBraceCount = BraceCount;
  1403. EndLoc = LBraceLoc = ConsumeBrace();
  1404. ++NumTokensRead;
  1405. } else {
  1406. // Single-line inline asm; compute which line it is on.
  1407. std::pair<FileID, unsigned> ExpAsmLoc =
  1408. SrcMgr.getDecomposedExpansionLoc(EndLoc);
  1409. FID = ExpAsmLoc.first;
  1410. LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
  1411. }
  1412. SourceLocation TokLoc = Tok.getLocation();
  1413. do {
  1414. // If we hit EOF, we're done, period.
  1415. if (Tok.is(tok::eof))
  1416. break;
  1417. // When we consume the closing brace, we're done.
  1418. if (InBraces && BraceCount == savedBraceCount)
  1419. break;
  1420. if (!InAsmComment && Tok.is(tok::semi)) {
  1421. // A semicolon in an asm is the start of a comment.
  1422. InAsmComment = true;
  1423. if (InBraces) {
  1424. // Compute which line the comment is on.
  1425. std::pair<FileID, unsigned> ExpSemiLoc =
  1426. SrcMgr.getDecomposedExpansionLoc(TokLoc);
  1427. FID = ExpSemiLoc.first;
  1428. LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
  1429. }
  1430. } else if (!InBraces || InAsmComment) {
  1431. // If end-of-line is significant, check whether this token is on a
  1432. // new line.
  1433. std::pair<FileID, unsigned> ExpLoc =
  1434. SrcMgr.getDecomposedExpansionLoc(TokLoc);
  1435. if (ExpLoc.first != FID ||
  1436. SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
  1437. // If this is a single-line __asm, we're done.
  1438. if (!InBraces)
  1439. break;
  1440. // We're no longer in a comment.
  1441. InAsmComment = false;
  1442. } else if (!InAsmComment && Tok.is(tok::r_brace)) {
  1443. // Single-line asm always ends when a closing brace is seen.
  1444. // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
  1445. // does MSVC do here?
  1446. break;
  1447. }
  1448. }
  1449. // Consume the next token; make sure we don't modify the brace count etc.
  1450. // if we are in a comment.
  1451. EndLoc = TokLoc;
  1452. if (InAsmComment)
  1453. PP.Lex(Tok);
  1454. else
  1455. ConsumeAnyToken();
  1456. TokLoc = Tok.getLocation();
  1457. ++NumTokensRead;
  1458. } while (1);
  1459. if (InBraces && BraceCount != savedBraceCount) {
  1460. // __asm without closing brace (this can happen at EOF).
  1461. Diag(Tok, diag::err_expected_rbrace);
  1462. Diag(LBraceLoc, diag::note_matching) << "{";
  1463. return StmtError();
  1464. } else if (NumTokensRead == 0) {
  1465. // Empty __asm.
  1466. Diag(Tok, diag::err_expected_lbrace);
  1467. return StmtError();
  1468. }
  1469. // Multiple adjacent asm's form together into a single asm statement
  1470. // in the AST.
  1471. if (!Tok.is(tok::kw_asm))
  1472. break;
  1473. EndLoc = ConsumeToken();
  1474. } while (1);
  1475. // FIXME: Need to actually grab the data and pass it on to Sema. Ideally,
  1476. // what Sema wants is a string of the entire inline asm, with one instruction
  1477. // per line and all the __asm keywords stripped out, and a way of mapping
  1478. // from any character of that string to its location in the original source
  1479. // code. I'm not entirely sure how to go about that, though.
  1480. Token t;
  1481. t.setKind(tok::string_literal);
  1482. t.setLiteralData("\"/*FIXME: not done*/\"");
  1483. t.clearFlag(Token::NeedsCleaning);
  1484. t.setLength(21);
  1485. ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
  1486. ExprVector Constraints(Actions);
  1487. ExprVector Exprs(Actions);
  1488. ExprVector Clobbers(Actions);
  1489. return Actions.ActOnAsmStmt(AsmLoc, true, true, 0, 0, 0,
  1490. move_arg(Constraints), move_arg(Exprs),
  1491. AsmString.take(), move_arg(Clobbers),
  1492. EndLoc, true);
  1493. }
  1494. /// ParseAsmStatement - Parse a GNU extended asm statement.
  1495. /// asm-statement:
  1496. /// gnu-asm-statement
  1497. /// ms-asm-statement
  1498. ///
  1499. /// [GNU] gnu-asm-statement:
  1500. /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
  1501. ///
  1502. /// [GNU] asm-argument:
  1503. /// asm-string-literal
  1504. /// asm-string-literal ':' asm-operands[opt]
  1505. /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
  1506. /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
  1507. /// ':' asm-clobbers
  1508. ///
  1509. /// [GNU] asm-clobbers:
  1510. /// asm-string-literal
  1511. /// asm-clobbers ',' asm-string-literal
  1512. ///
  1513. /// [MS] ms-asm-statement:
  1514. /// ms-asm-block
  1515. /// ms-asm-block ms-asm-statement
  1516. ///
  1517. /// [MS] ms-asm-block:
  1518. /// '__asm' ms-asm-line '\n'
  1519. /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
  1520. ///
  1521. /// [MS] ms-asm-instruction-block
  1522. /// ms-asm-line
  1523. /// ms-asm-line '\n' ms-asm-instruction-block
  1524. ///
  1525. StmtResult Parser::ParseAsmStatement(bool &msAsm) {
  1526. assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
  1527. SourceLocation AsmLoc = ConsumeToken();
  1528. if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
  1529. msAsm = true;
  1530. return ParseMicrosoftAsmStatement(AsmLoc);
  1531. }
  1532. DeclSpec DS(AttrFactory);
  1533. SourceLocation Loc = Tok.getLocation();
  1534. ParseTypeQualifierListOpt(DS, true, false);
  1535. // GNU asms accept, but warn, about type-qualifiers other than volatile.
  1536. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  1537. Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
  1538. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  1539. Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
  1540. // Remember if this was a volatile asm.
  1541. bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
  1542. if (Tok.isNot(tok::l_paren)) {
  1543. Diag(Tok, diag::err_expected_lparen_after) << "asm";
  1544. SkipUntil(tok::r_paren);
  1545. return StmtError();
  1546. }
  1547. BalancedDelimiterTracker T(*this, tok::l_paren);
  1548. T.consumeOpen();
  1549. ExprResult AsmString(ParseAsmStringLiteral());
  1550. if (AsmString.isInvalid()) {
  1551. // Consume up to and including the closing paren.
  1552. T.skipToEnd();
  1553. return StmtError();
  1554. }
  1555. SmallVector<IdentifierInfo *, 4> Names;
  1556. ExprVector Constraints(Actions);
  1557. ExprVector Exprs(Actions);
  1558. ExprVector Clobbers(Actions);
  1559. if (Tok.is(tok::r_paren)) {
  1560. // We have a simple asm expression like 'asm("foo")'.
  1561. T.consumeClose();
  1562. return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
  1563. /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
  1564. move_arg(Constraints), move_arg(Exprs),
  1565. AsmString.take(), move_arg(Clobbers),
  1566. T.getCloseLocation());
  1567. }
  1568. // Parse Outputs, if present.
  1569. bool AteExtraColon = false;
  1570. if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
  1571. // In C++ mode, parse "::" like ": :".
  1572. AteExtraColon = Tok.is(tok::coloncolon);
  1573. ConsumeToken();
  1574. if (!AteExtraColon &&
  1575. ParseAsmOperandsOpt(Names, Constraints, Exprs))
  1576. return StmtError();
  1577. }
  1578. unsigned NumOutputs = Names.size();
  1579. // Parse Inputs, if present.
  1580. if (AteExtraColon ||
  1581. Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
  1582. // In C++ mode, parse "::" like ": :".
  1583. if (AteExtraColon)
  1584. AteExtraColon = false;
  1585. else {
  1586. AteExtraColon = Tok.is(tok::coloncolon);
  1587. ConsumeToken();
  1588. }
  1589. if (!AteExtraColon &&
  1590. ParseAsmOperandsOpt(Names, Constraints, Exprs))
  1591. return StmtError();
  1592. }
  1593. assert(Names.size() == Constraints.size() &&
  1594. Constraints.size() == Exprs.size() &&
  1595. "Input operand size mismatch!");
  1596. unsigned NumInputs = Names.size() - NumOutputs;
  1597. // Parse the clobbers, if present.
  1598. if (AteExtraColon || Tok.is(tok::colon)) {
  1599. if (!AteExtraColon)
  1600. ConsumeToken();
  1601. // Parse the asm-string list for clobbers if present.
  1602. if (Tok.isNot(tok::r_paren)) {
  1603. while (1) {
  1604. ExprResult Clobber(ParseAsmStringLiteral());
  1605. if (Clobber.isInvalid())
  1606. break;
  1607. Clobbers.push_back(Clobber.release());
  1608. if (Tok.isNot(tok::comma)) break;
  1609. ConsumeToken();
  1610. }
  1611. }
  1612. }
  1613. T.consumeClose();
  1614. return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
  1615. NumOutputs, NumInputs, Names.data(),
  1616. move_arg(Constraints), move_arg(Exprs),
  1617. AsmString.take(), move_arg(Clobbers),
  1618. T.getCloseLocation());
  1619. }
  1620. /// ParseAsmOperands - Parse the asm-operands production as used by
  1621. /// asm-statement, assuming the leading ':' token was eaten.
  1622. ///
  1623. /// [GNU] asm-operands:
  1624. /// asm-operand
  1625. /// asm-operands ',' asm-operand
  1626. ///
  1627. /// [GNU] asm-operand:
  1628. /// asm-string-literal '(' expression ')'
  1629. /// '[' identifier ']' asm-string-literal '(' expression ')'
  1630. ///
  1631. //
  1632. // FIXME: Avoid unnecessary std::string trashing.
  1633. bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
  1634. SmallVectorImpl<Expr *> &Constraints,
  1635. SmallVectorImpl<Expr *> &Exprs) {
  1636. // 'asm-operands' isn't present?
  1637. if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
  1638. return false;
  1639. while (1) {
  1640. // Read the [id] if present.
  1641. if (Tok.is(tok::l_square)) {
  1642. BalancedDelimiterTracker T(*this, tok::l_square);
  1643. T.consumeOpen();
  1644. if (Tok.isNot(tok::identifier)) {
  1645. Diag(Tok, diag::err_expected_ident);
  1646. SkipUntil(tok::r_paren);
  1647. return true;
  1648. }
  1649. IdentifierInfo *II = Tok.getIdentifierInfo();
  1650. ConsumeToken();
  1651. Names.push_back(II);
  1652. T.consumeClose();
  1653. } else
  1654. Names.push_back(0);
  1655. ExprResult Constraint(ParseAsmStringLiteral());
  1656. if (Constraint.isInvalid()) {
  1657. SkipUntil(tok::r_paren);
  1658. return true;
  1659. }
  1660. Constraints.push_back(Constraint.release());
  1661. if (Tok.isNot(tok::l_paren)) {
  1662. Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
  1663. SkipUntil(tok::r_paren);
  1664. return true;
  1665. }
  1666. // Read the parenthesized expression.
  1667. BalancedDelimiterTracker T(*this, tok::l_paren);
  1668. T.consumeOpen();
  1669. ExprResult Res(ParseExpression());
  1670. T.consumeClose();
  1671. if (Res.isInvalid()) {
  1672. SkipUntil(tok::r_paren);
  1673. return true;
  1674. }
  1675. Exprs.push_back(Res.release());
  1676. // Eat the comma and continue parsing if it exists.
  1677. if (Tok.isNot(tok::comma)) return false;
  1678. ConsumeToken();
  1679. }
  1680. }
  1681. Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
  1682. assert(Tok.is(tok::l_brace));
  1683. SourceLocation LBraceLoc = Tok.getLocation();
  1684. if (PP.isCodeCompletionEnabled()) {
  1685. if (trySkippingFunctionBodyForCodeCompletion()) {
  1686. BodyScope.Exit();
  1687. return Actions.ActOnFinishFunctionBody(Decl, 0);
  1688. }
  1689. }
  1690. PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
  1691. "parsing function body");
  1692. // Do not enter a scope for the brace, as the arguments are in the same scope
  1693. // (the function body) as the body itself. Instead, just read the statement
  1694. // list and put it into a CompoundStmt for safe keeping.
  1695. StmtResult FnBody(ParseCompoundStatementBody());
  1696. // If the function body could not be parsed, make a bogus compoundstmt.
  1697. if (FnBody.isInvalid()) {
  1698. Sema::CompoundScopeRAII CompoundScope(Actions);
  1699. FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
  1700. MultiStmtArg(Actions), false);
  1701. }
  1702. BodyScope.Exit();
  1703. return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
  1704. }
  1705. /// ParseFunctionTryBlock - Parse a C++ function-try-block.
  1706. ///
  1707. /// function-try-block:
  1708. /// 'try' ctor-initializer[opt] compound-statement handler-seq
  1709. ///
  1710. Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
  1711. assert(Tok.is(tok::kw_try) && "Expected 'try'");
  1712. SourceLocation TryLoc = ConsumeToken();
  1713. PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
  1714. "parsing function try block");
  1715. // Constructor initializer list?
  1716. if (Tok.is(tok::colon))
  1717. ParseConstructorInitializer(Decl);
  1718. else
  1719. Actions.ActOnDefaultCtorInitializers(Decl);
  1720. if (PP.isCodeCompletionEnabled()) {
  1721. if (trySkippingFunctionBodyForCodeCompletion()) {
  1722. BodyScope.Exit();
  1723. return Actions.ActOnFinishFunctionBody(Decl, 0);
  1724. }
  1725. }
  1726. SourceLocation LBraceLoc = Tok.getLocation();
  1727. StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
  1728. // If we failed to parse the try-catch, we just give the function an empty
  1729. // compound statement as the body.
  1730. if (FnBody.isInvalid()) {
  1731. Sema::CompoundScopeRAII CompoundScope(Actions);
  1732. FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
  1733. MultiStmtArg(Actions), false);
  1734. }
  1735. BodyScope.Exit();
  1736. return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
  1737. }
  1738. bool Parser::trySkippingFunctionBodyForCodeCompletion() {
  1739. assert(Tok.is(tok::l_brace));
  1740. assert(PP.isCodeCompletionEnabled() &&
  1741. "Should only be called when in code-completion mode");
  1742. // We're in code-completion mode. Skip parsing for all function bodies unless
  1743. // the body contains the code-completion point.
  1744. TentativeParsingAction PA(*this);
  1745. ConsumeBrace();
  1746. if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
  1747. /*StopAtCodeCompletion=*/true)) {
  1748. PA.Commit();
  1749. return true;
  1750. }
  1751. PA.Revert();
  1752. return false;
  1753. }
  1754. /// ParseCXXTryBlock - Parse a C++ try-block.
  1755. ///
  1756. /// try-block:
  1757. /// 'try' compound-statement handler-seq
  1758. ///
  1759. StmtResult Parser::ParseCXXTryBlock(ParsedAttributes &attrs) {
  1760. // FIXME: Add attributes?
  1761. assert(Tok.is(tok::kw_try) && "Expected 'try'");
  1762. SourceLocation TryLoc = ConsumeToken();
  1763. return ParseCXXTryBlockCommon(TryLoc);
  1764. }
  1765. /// ParseCXXTryBlockCommon - Parse the common part of try-block and
  1766. /// function-try-block.
  1767. ///
  1768. /// try-block:
  1769. /// 'try' compound-statement handler-seq
  1770. ///
  1771. /// function-try-block:
  1772. /// 'try' ctor-initializer[opt] compound-statement handler-seq
  1773. ///
  1774. /// handler-seq:
  1775. /// handler handler-seq[opt]
  1776. ///
  1777. /// [Borland] try-block:
  1778. /// 'try' compound-statement seh-except-block
  1779. /// 'try' compound-statment seh-finally-block
  1780. ///
  1781. StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
  1782. if (Tok.isNot(tok::l_brace))
  1783. return StmtError(Diag(Tok, diag::err_expected_lbrace));
  1784. // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
  1785. ParsedAttributesWithRange attrs(AttrFactory);
  1786. StmtResult TryBlock(ParseCompoundStatement(attrs, /*isStmtExpr=*/false,
  1787. Scope::DeclScope|Scope::TryScope));
  1788. if (TryBlock.isInvalid())
  1789. return move(TryBlock);
  1790. // Borland allows SEH-handlers with 'try'
  1791. if((Tok.is(tok::identifier) &&
  1792. Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
  1793. Tok.is(tok::kw___finally)) {
  1794. // TODO: Factor into common return ParseSEHHandlerCommon(...)
  1795. StmtResult Handler;
  1796. if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
  1797. SourceLocation Loc = ConsumeToken();
  1798. Handler = ParseSEHExceptBlock(Loc);
  1799. }
  1800. else {
  1801. SourceLocation Loc = ConsumeToken();
  1802. Handler = ParseSEHFinallyBlock(Loc);
  1803. }
  1804. if(Handler.isInvalid())
  1805. return move(Handler);
  1806. return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
  1807. TryLoc,
  1808. TryBlock.take(),
  1809. Handler.take());
  1810. }
  1811. else {
  1812. StmtVector Handlers(Actions);
  1813. MaybeParseCXX0XAttributes(attrs);
  1814. ProhibitAttributes(attrs);
  1815. if (Tok.isNot(tok::kw_catch))
  1816. return StmtError(Diag(Tok, diag::err_expected_catch));
  1817. while (Tok.is(tok::kw_catch)) {
  1818. StmtResult Handler(ParseCXXCatchBlock());
  1819. if (!Handler.isInvalid())
  1820. Handlers.push_back(Handler.release());
  1821. }
  1822. // Don't bother creating the full statement if we don't have any usable
  1823. // handlers.
  1824. if (Handlers.empty())
  1825. return StmtError();
  1826. return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
  1827. }
  1828. }
  1829. /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
  1830. ///
  1831. /// handler:
  1832. /// 'catch' '(' exception-declaration ')' compound-statement
  1833. ///
  1834. /// exception-declaration:
  1835. /// type-specifier-seq declarator
  1836. /// type-specifier-seq abstract-declarator
  1837. /// type-specifier-seq
  1838. /// '...'
  1839. ///
  1840. StmtResult Parser::ParseCXXCatchBlock() {
  1841. assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
  1842. SourceLocation CatchLoc = ConsumeToken();
  1843. BalancedDelimiterTracker T(*this, tok::l_paren);
  1844. if (T.expectAndConsume(diag::err_expected_lparen))
  1845. return StmtError();
  1846. // C++ 3.3.2p3:
  1847. // The name in a catch exception-declaration is local to the handler and
  1848. // shall not be redeclared in the outermost block of the handler.
  1849. ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
  1850. // exception-declaration is equivalent to '...' or a parameter-declaration
  1851. // without default arguments.
  1852. Decl *ExceptionDecl = 0;
  1853. if (Tok.isNot(tok::ellipsis)) {
  1854. DeclSpec DS(AttrFactory);
  1855. if (ParseCXXTypeSpecifierSeq(DS))
  1856. return StmtError();
  1857. Declarator ExDecl(DS, Declarator::CXXCatchContext);
  1858. ParseDeclarator(ExDecl);
  1859. ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
  1860. } else
  1861. ConsumeToken();
  1862. T.consumeClose();
  1863. if (T.getCloseLocation().isInvalid())
  1864. return StmtError();
  1865. if (Tok.isNot(tok::l_brace))
  1866. return StmtError(Diag(Tok, diag::err_expected_lbrace));
  1867. // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
  1868. ParsedAttributes attrs(AttrFactory);
  1869. StmtResult Block(ParseCompoundStatement(attrs));
  1870. if (Block.isInvalid())
  1871. return move(Block);
  1872. return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
  1873. }
  1874. void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
  1875. IfExistsCondition Result;
  1876. if (ParseMicrosoftIfExistsCondition(Result))
  1877. return;
  1878. // Handle dependent statements by parsing the braces as a compound statement.
  1879. // This is not the same behavior as Visual C++, which don't treat this as a
  1880. // compound statement, but for Clang's type checking we can't have anything
  1881. // inside these braces escaping to the surrounding code.
  1882. if (Result.Behavior == IEB_Dependent) {
  1883. if (!Tok.is(tok::l_brace)) {
  1884. Diag(Tok, diag::err_expected_lbrace);
  1885. return;
  1886. }
  1887. ParsedAttributes Attrs(AttrFactory);
  1888. StmtResult Compound = ParseCompoundStatement(Attrs);
  1889. if (Compound.isInvalid())
  1890. return;
  1891. StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
  1892. Result.IsIfExists,
  1893. Result.SS,
  1894. Result.Name,
  1895. Compound.get());
  1896. if (DepResult.isUsable())
  1897. Stmts.push_back(DepResult.get());
  1898. return;
  1899. }
  1900. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  1901. if (Braces.consumeOpen()) {
  1902. Diag(Tok, diag::err_expected_lbrace);
  1903. return;
  1904. }
  1905. switch (Result.Behavior) {
  1906. case IEB_Parse:
  1907. // Parse the statements below.
  1908. break;
  1909. case IEB_Dependent:
  1910. llvm_unreachable("Dependent case handled above");
  1911. case IEB_Skip:
  1912. Braces.skipToEnd();
  1913. return;
  1914. }
  1915. // Condition is true, parse the statements.
  1916. while (Tok.isNot(tok::r_brace)) {
  1917. StmtResult R = ParseStatementOrDeclaration(Stmts, false);
  1918. if (R.isUsable())
  1919. Stmts.push_back(R.release());
  1920. }
  1921. Braces.consumeClose();
  1922. }