ParseStmt.cpp 78 KB

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