ParseStmt.cpp 77 KB

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