Parser.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672
  1. //===--- Parser.cpp - C Language Family 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 Parser interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/Parser.h"
  14. #include "clang/Parse/ParseDiagnostic.h"
  15. #include "clang/Sema/DeclSpec.h"
  16. #include "clang/Sema/Scope.h"
  17. #include "clang/Sema/ParsedTemplate.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. #include "RAIIObjectsForParser.h"
  20. #include "ParsePragma.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/ASTConsumer.h"
  23. using namespace clang;
  24. IdentifierInfo *Parser::getSEHExceptKeyword() {
  25. // __except is accepted as a (contextual) keyword
  26. if (!Ident__except && (getLang().MicrosoftExt || getLang().Borland))
  27. Ident__except = PP.getIdentifierInfo("__except");
  28. return Ident__except;
  29. }
  30. Parser::Parser(Preprocessor &pp, Sema &actions)
  31. : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
  32. GreaterThanIsOperator(true), ColonIsSacred(false),
  33. InMessageExpression(false), TemplateParameterDepth(0) {
  34. Tok.setKind(tok::eof);
  35. Actions.CurScope = 0;
  36. NumCachedScopes = 0;
  37. ParenCount = BracketCount = BraceCount = 0;
  38. ObjCImpDecl = 0;
  39. // Add #pragma handlers. These are removed and destroyed in the
  40. // destructor.
  41. AlignHandler.reset(new PragmaAlignHandler(actions));
  42. PP.AddPragmaHandler(AlignHandler.get());
  43. GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler(actions));
  44. PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
  45. OptionsHandler.reset(new PragmaOptionsHandler(actions));
  46. PP.AddPragmaHandler(OptionsHandler.get());
  47. PackHandler.reset(new PragmaPackHandler(actions));
  48. PP.AddPragmaHandler(PackHandler.get());
  49. MSStructHandler.reset(new PragmaMSStructHandler(actions));
  50. PP.AddPragmaHandler(MSStructHandler.get());
  51. UnusedHandler.reset(new PragmaUnusedHandler(actions, *this));
  52. PP.AddPragmaHandler(UnusedHandler.get());
  53. WeakHandler.reset(new PragmaWeakHandler(actions));
  54. PP.AddPragmaHandler(WeakHandler.get());
  55. FPContractHandler.reset(new PragmaFPContractHandler(actions, *this));
  56. PP.AddPragmaHandler("STDC", FPContractHandler.get());
  57. if (getLang().OpenCL) {
  58. OpenCLExtensionHandler.reset(
  59. new PragmaOpenCLExtensionHandler(actions, *this));
  60. PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
  61. PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
  62. }
  63. PP.setCodeCompletionHandler(*this);
  64. }
  65. /// If a crash happens while the parser is active, print out a line indicating
  66. /// what the current token is.
  67. void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
  68. const Token &Tok = P.getCurToken();
  69. if (Tok.is(tok::eof)) {
  70. OS << "<eof> parser at end of file\n";
  71. return;
  72. }
  73. if (Tok.getLocation().isInvalid()) {
  74. OS << "<unknown> parser at unknown location\n";
  75. return;
  76. }
  77. const Preprocessor &PP = P.getPreprocessor();
  78. Tok.getLocation().print(OS, PP.getSourceManager());
  79. if (Tok.isAnnotation())
  80. OS << ": at annotation token \n";
  81. else
  82. OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
  83. }
  84. DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
  85. return Diags.Report(Loc, DiagID);
  86. }
  87. DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
  88. return Diag(Tok.getLocation(), DiagID);
  89. }
  90. /// \brief Emits a diagnostic suggesting parentheses surrounding a
  91. /// given range.
  92. ///
  93. /// \param Loc The location where we'll emit the diagnostic.
  94. /// \param Loc The kind of diagnostic to emit.
  95. /// \param ParenRange Source range enclosing code that should be parenthesized.
  96. void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
  97. SourceRange ParenRange) {
  98. SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
  99. if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
  100. // We can't display the parentheses, so just dig the
  101. // warning/error and return.
  102. Diag(Loc, DK);
  103. return;
  104. }
  105. Diag(Loc, DK)
  106. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  107. << FixItHint::CreateInsertion(EndLoc, ")");
  108. }
  109. static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
  110. switch (ExpectedTok) {
  111. case tok::semi: return Tok.is(tok::colon); // : for ;
  112. default: return false;
  113. }
  114. }
  115. /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
  116. /// input. If so, it is consumed and false is returned.
  117. ///
  118. /// If the input is malformed, this emits the specified diagnostic. Next, if
  119. /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
  120. /// returned.
  121. bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
  122. const char *Msg, tok::TokenKind SkipToTok) {
  123. if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
  124. ConsumeAnyToken();
  125. return false;
  126. }
  127. // Detect common single-character typos and resume.
  128. if (IsCommonTypo(ExpectedTok, Tok)) {
  129. SourceLocation Loc = Tok.getLocation();
  130. Diag(Loc, DiagID)
  131. << Msg
  132. << FixItHint::CreateReplacement(SourceRange(Loc),
  133. getTokenSimpleSpelling(ExpectedTok));
  134. ConsumeAnyToken();
  135. // Pretend there wasn't a problem.
  136. return false;
  137. }
  138. const char *Spelling = 0;
  139. SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
  140. if (EndLoc.isValid() &&
  141. (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
  142. // Show what code to insert to fix this problem.
  143. Diag(EndLoc, DiagID)
  144. << Msg
  145. << FixItHint::CreateInsertion(EndLoc, Spelling);
  146. } else
  147. Diag(Tok, DiagID) << Msg;
  148. if (SkipToTok != tok::unknown)
  149. SkipUntil(SkipToTok);
  150. return true;
  151. }
  152. bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
  153. if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
  154. ConsumeAnyToken();
  155. return false;
  156. }
  157. if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
  158. NextToken().is(tok::semi)) {
  159. Diag(Tok, diag::err_extraneous_token_before_semi)
  160. << PP.getSpelling(Tok)
  161. << FixItHint::CreateRemoval(Tok.getLocation());
  162. ConsumeAnyToken(); // The ')' or ']'.
  163. ConsumeToken(); // The ';'.
  164. return false;
  165. }
  166. return ExpectAndConsume(tok::semi, DiagID);
  167. }
  168. //===----------------------------------------------------------------------===//
  169. // Error recovery.
  170. //===----------------------------------------------------------------------===//
  171. /// SkipUntil - Read tokens until we get to the specified token, then consume
  172. /// it (unless DontConsume is true). Because we cannot guarantee that the
  173. /// token will ever occur, this skips to the next token, or to some likely
  174. /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
  175. /// character.
  176. ///
  177. /// If SkipUntil finds the specified token, it returns true, otherwise it
  178. /// returns false.
  179. bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
  180. bool StopAtSemi, bool DontConsume,
  181. bool StopAtCodeCompletion) {
  182. // We always want this function to skip at least one token if the first token
  183. // isn't T and if not at EOF.
  184. bool isFirstTokenSkipped = true;
  185. while (1) {
  186. // If we found one of the tokens, stop and return true.
  187. for (unsigned i = 0; i != NumToks; ++i) {
  188. if (Tok.is(Toks[i])) {
  189. if (DontConsume) {
  190. // Noop, don't consume the token.
  191. } else {
  192. ConsumeAnyToken();
  193. }
  194. return true;
  195. }
  196. }
  197. switch (Tok.getKind()) {
  198. case tok::eof:
  199. // Ran out of tokens.
  200. return false;
  201. case tok::code_completion:
  202. if (!StopAtCodeCompletion)
  203. ConsumeToken();
  204. return false;
  205. case tok::l_paren:
  206. // Recursively skip properly-nested parens.
  207. ConsumeParen();
  208. SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
  209. break;
  210. case tok::l_square:
  211. // Recursively skip properly-nested square brackets.
  212. ConsumeBracket();
  213. SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
  214. break;
  215. case tok::l_brace:
  216. // Recursively skip properly-nested braces.
  217. ConsumeBrace();
  218. SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
  219. break;
  220. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  221. // Since the user wasn't looking for this token (if they were, it would
  222. // already be handled), this isn't balanced. If there is a LHS token at a
  223. // higher level, we will assume that this matches the unbalanced token
  224. // and return it. Otherwise, this is a spurious RHS token, which we skip.
  225. case tok::r_paren:
  226. if (ParenCount && !isFirstTokenSkipped)
  227. return false; // Matches something.
  228. ConsumeParen();
  229. break;
  230. case tok::r_square:
  231. if (BracketCount && !isFirstTokenSkipped)
  232. return false; // Matches something.
  233. ConsumeBracket();
  234. break;
  235. case tok::r_brace:
  236. if (BraceCount && !isFirstTokenSkipped)
  237. return false; // Matches something.
  238. ConsumeBrace();
  239. break;
  240. case tok::string_literal:
  241. case tok::wide_string_literal:
  242. case tok::utf8_string_literal:
  243. case tok::utf16_string_literal:
  244. case tok::utf32_string_literal:
  245. ConsumeStringToken();
  246. break;
  247. case tok::semi:
  248. if (StopAtSemi)
  249. return false;
  250. // FALL THROUGH.
  251. default:
  252. // Skip this token.
  253. ConsumeToken();
  254. break;
  255. }
  256. isFirstTokenSkipped = false;
  257. }
  258. }
  259. //===----------------------------------------------------------------------===//
  260. // Scope manipulation
  261. //===----------------------------------------------------------------------===//
  262. /// EnterScope - Start a new scope.
  263. void Parser::EnterScope(unsigned ScopeFlags) {
  264. if (NumCachedScopes) {
  265. Scope *N = ScopeCache[--NumCachedScopes];
  266. N->Init(getCurScope(), ScopeFlags);
  267. Actions.CurScope = N;
  268. } else {
  269. Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
  270. }
  271. }
  272. /// ExitScope - Pop a scope off the scope stack.
  273. void Parser::ExitScope() {
  274. assert(getCurScope() && "Scope imbalance!");
  275. // Inform the actions module that this scope is going away if there are any
  276. // decls in it.
  277. if (!getCurScope()->decl_empty())
  278. Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
  279. Scope *OldScope = getCurScope();
  280. Actions.CurScope = OldScope->getParent();
  281. if (NumCachedScopes == ScopeCacheSize)
  282. delete OldScope;
  283. else
  284. ScopeCache[NumCachedScopes++] = OldScope;
  285. }
  286. /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
  287. /// this object does nothing.
  288. Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
  289. bool ManageFlags)
  290. : CurScope(ManageFlags ? Self->getCurScope() : 0) {
  291. if (CurScope) {
  292. OldFlags = CurScope->getFlags();
  293. CurScope->setFlags(ScopeFlags);
  294. }
  295. }
  296. /// Restore the flags for the current scope to what they were before this
  297. /// object overrode them.
  298. Parser::ParseScopeFlags::~ParseScopeFlags() {
  299. if (CurScope)
  300. CurScope->setFlags(OldFlags);
  301. }
  302. //===----------------------------------------------------------------------===//
  303. // C99 6.9: External Definitions.
  304. //===----------------------------------------------------------------------===//
  305. Parser::~Parser() {
  306. // If we still have scopes active, delete the scope tree.
  307. delete getCurScope();
  308. Actions.CurScope = 0;
  309. // Free the scope cache.
  310. for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
  311. delete ScopeCache[i];
  312. // Free LateParsedTemplatedFunction nodes.
  313. for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
  314. it != LateParsedTemplateMap.end(); ++it)
  315. delete it->second;
  316. clearLateParsedObjCMethods();
  317. // Remove the pragma handlers we installed.
  318. PP.RemovePragmaHandler(AlignHandler.get());
  319. AlignHandler.reset();
  320. PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
  321. GCCVisibilityHandler.reset();
  322. PP.RemovePragmaHandler(OptionsHandler.get());
  323. OptionsHandler.reset();
  324. PP.RemovePragmaHandler(PackHandler.get());
  325. PackHandler.reset();
  326. PP.RemovePragmaHandler(MSStructHandler.get());
  327. MSStructHandler.reset();
  328. PP.RemovePragmaHandler(UnusedHandler.get());
  329. UnusedHandler.reset();
  330. PP.RemovePragmaHandler(WeakHandler.get());
  331. WeakHandler.reset();
  332. if (getLang().OpenCL) {
  333. PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
  334. OpenCLExtensionHandler.reset();
  335. PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
  336. }
  337. PP.RemovePragmaHandler("STDC", FPContractHandler.get());
  338. FPContractHandler.reset();
  339. PP.clearCodeCompletionHandler();
  340. }
  341. /// Initialize - Warm up the parser.
  342. ///
  343. void Parser::Initialize() {
  344. // Create the translation unit scope. Install it as the current scope.
  345. assert(getCurScope() == 0 && "A scope is already active?");
  346. EnterScope(Scope::DeclScope);
  347. Actions.ActOnTranslationUnitScope(getCurScope());
  348. // Prime the lexer look-ahead.
  349. ConsumeToken();
  350. if (Tok.is(tok::eof) &&
  351. !getLang().CPlusPlus) // Empty source file is an extension in C
  352. Diag(Tok, diag::ext_empty_source_file);
  353. // Initialization for Objective-C context sensitive keywords recognition.
  354. // Referenced in Parser::ParseObjCTypeQualifierList.
  355. if (getLang().ObjC1) {
  356. ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
  357. ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
  358. ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
  359. ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
  360. ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
  361. ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
  362. }
  363. Ident_instancetype = 0;
  364. Ident_final = 0;
  365. Ident_override = 0;
  366. Ident_super = &PP.getIdentifierTable().get("super");
  367. if (getLang().AltiVec) {
  368. Ident_vector = &PP.getIdentifierTable().get("vector");
  369. Ident_pixel = &PP.getIdentifierTable().get("pixel");
  370. }
  371. Ident_introduced = 0;
  372. Ident_deprecated = 0;
  373. Ident_obsoleted = 0;
  374. Ident_unavailable = 0;
  375. Ident__except = 0;
  376. Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
  377. Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
  378. Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
  379. if(getLang().Borland) {
  380. Ident__exception_info = PP.getIdentifierInfo("_exception_info");
  381. Ident___exception_info = PP.getIdentifierInfo("__exception_info");
  382. Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
  383. Ident__exception_code = PP.getIdentifierInfo("_exception_code");
  384. Ident___exception_code = PP.getIdentifierInfo("__exception_code");
  385. Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
  386. Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
  387. Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
  388. Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
  389. PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
  390. PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
  391. PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
  392. PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
  393. PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
  394. PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
  395. PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
  396. PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
  397. PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
  398. }
  399. }
  400. /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
  401. /// action tells us to. This returns true if the EOF was encountered.
  402. bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
  403. DelayedCleanupPoint CleanupRAII(TopLevelDeclCleanupPool);
  404. while (Tok.is(tok::annot_pragma_unused))
  405. HandlePragmaUnused();
  406. Result = DeclGroupPtrTy();
  407. if (Tok.is(tok::eof)) {
  408. // Late template parsing can begin.
  409. if (getLang().DelayedTemplateParsing)
  410. Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
  411. Actions.ActOnEndOfTranslationUnit();
  412. return true;
  413. }
  414. ParsedAttributesWithRange attrs(AttrFactory);
  415. MaybeParseCXX0XAttributes(attrs);
  416. MaybeParseMicrosoftAttributes(attrs);
  417. Result = ParseExternalDeclaration(attrs);
  418. return false;
  419. }
  420. /// ParseTranslationUnit:
  421. /// translation-unit: [C99 6.9]
  422. /// external-declaration
  423. /// translation-unit external-declaration
  424. void Parser::ParseTranslationUnit() {
  425. Initialize();
  426. DeclGroupPtrTy Res;
  427. while (!ParseTopLevelDecl(Res))
  428. /*parse them all*/;
  429. ExitScope();
  430. assert(getCurScope() == 0 && "Scope imbalance!");
  431. }
  432. /// ParseExternalDeclaration:
  433. ///
  434. /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
  435. /// function-definition
  436. /// declaration
  437. /// [C++0x] empty-declaration
  438. /// [GNU] asm-definition
  439. /// [GNU] __extension__ external-declaration
  440. /// [OBJC] objc-class-definition
  441. /// [OBJC] objc-class-declaration
  442. /// [OBJC] objc-alias-declaration
  443. /// [OBJC] objc-protocol-definition
  444. /// [OBJC] objc-method-definition
  445. /// [OBJC] @end
  446. /// [C++] linkage-specification
  447. /// [GNU] asm-definition:
  448. /// simple-asm-expr ';'
  449. ///
  450. /// [C++0x] empty-declaration:
  451. /// ';'
  452. ///
  453. /// [C++0x/GNU] 'extern' 'template' declaration
  454. Parser::DeclGroupPtrTy
  455. Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
  456. ParsingDeclSpec *DS) {
  457. DelayedCleanupPoint CleanupRAII(TopLevelDeclCleanupPool);
  458. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  459. if (PP.isCodeCompletionReached()) {
  460. cutOffParsing();
  461. return DeclGroupPtrTy();
  462. }
  463. Decl *SingleDecl = 0;
  464. switch (Tok.getKind()) {
  465. case tok::semi:
  466. Diag(Tok, getLang().CPlusPlus0x ?
  467. diag::warn_cxx98_compat_top_level_semi : diag::ext_top_level_semi)
  468. << FixItHint::CreateRemoval(Tok.getLocation());
  469. ConsumeToken();
  470. // TODO: Invoke action for top-level semicolon.
  471. return DeclGroupPtrTy();
  472. case tok::r_brace:
  473. Diag(Tok, diag::err_expected_external_declaration);
  474. ConsumeBrace();
  475. return DeclGroupPtrTy();
  476. case tok::eof:
  477. Diag(Tok, diag::err_expected_external_declaration);
  478. return DeclGroupPtrTy();
  479. case tok::kw___extension__: {
  480. // __extension__ silences extension warnings in the subexpression.
  481. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  482. ConsumeToken();
  483. return ParseExternalDeclaration(attrs);
  484. }
  485. case tok::kw_asm: {
  486. ProhibitAttributes(attrs);
  487. SourceLocation StartLoc = Tok.getLocation();
  488. SourceLocation EndLoc;
  489. ExprResult Result(ParseSimpleAsm(&EndLoc));
  490. ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
  491. "top-level asm block");
  492. if (Result.isInvalid())
  493. return DeclGroupPtrTy();
  494. SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
  495. break;
  496. }
  497. case tok::at:
  498. return ParseObjCAtDirectives();
  499. break;
  500. case tok::minus:
  501. case tok::plus:
  502. if (!getLang().ObjC1) {
  503. Diag(Tok, diag::err_expected_external_declaration);
  504. ConsumeToken();
  505. return DeclGroupPtrTy();
  506. }
  507. SingleDecl = ParseObjCMethodDefinition();
  508. break;
  509. case tok::code_completion:
  510. Actions.CodeCompleteOrdinaryName(getCurScope(),
  511. ObjCImpDecl? Sema::PCC_ObjCImplementation
  512. : Sema::PCC_Namespace);
  513. cutOffParsing();
  514. return DeclGroupPtrTy();
  515. case tok::kw_using:
  516. case tok::kw_namespace:
  517. case tok::kw_typedef:
  518. case tok::kw_template:
  519. case tok::kw_export: // As in 'export template'
  520. case tok::kw_static_assert:
  521. case tok::kw__Static_assert:
  522. // A function definition cannot start with a these keywords.
  523. {
  524. SourceLocation DeclEnd;
  525. StmtVector Stmts(Actions);
  526. return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
  527. }
  528. case tok::kw_static:
  529. // Parse (then ignore) 'static' prior to a template instantiation. This is
  530. // a GCC extension that we intentionally do not support.
  531. if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
  532. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  533. << 0;
  534. SourceLocation DeclEnd;
  535. StmtVector Stmts(Actions);
  536. return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
  537. }
  538. goto dont_know;
  539. case tok::kw_inline:
  540. if (getLang().CPlusPlus) {
  541. tok::TokenKind NextKind = NextToken().getKind();
  542. // Inline namespaces. Allowed as an extension even in C++03.
  543. if (NextKind == tok::kw_namespace) {
  544. SourceLocation DeclEnd;
  545. StmtVector Stmts(Actions);
  546. return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
  547. }
  548. // Parse (then ignore) 'inline' prior to a template instantiation. This is
  549. // a GCC extension that we intentionally do not support.
  550. if (NextKind == tok::kw_template) {
  551. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  552. << 1;
  553. SourceLocation DeclEnd;
  554. StmtVector Stmts(Actions);
  555. return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
  556. }
  557. }
  558. goto dont_know;
  559. case tok::kw_extern:
  560. if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
  561. // Extern templates
  562. SourceLocation ExternLoc = ConsumeToken();
  563. SourceLocation TemplateLoc = ConsumeToken();
  564. Diag(ExternLoc, getLang().CPlusPlus0x ?
  565. diag::warn_cxx98_compat_extern_template :
  566. diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
  567. SourceLocation DeclEnd;
  568. return Actions.ConvertDeclToDeclGroup(
  569. ParseExplicitInstantiation(Declarator::FileContext,
  570. ExternLoc, TemplateLoc, DeclEnd));
  571. }
  572. // FIXME: Detect C++ linkage specifications here?
  573. goto dont_know;
  574. case tok::kw___if_exists:
  575. case tok::kw___if_not_exists:
  576. ParseMicrosoftIfExistsExternalDeclaration();
  577. return DeclGroupPtrTy();
  578. case tok::kw___import_module__:
  579. return ParseModuleImport();
  580. default:
  581. dont_know:
  582. // We can't tell whether this is a function-definition or declaration yet.
  583. if (DS) {
  584. DS->takeAttributesFrom(attrs);
  585. return ParseDeclarationOrFunctionDefinition(*DS);
  586. } else {
  587. return ParseDeclarationOrFunctionDefinition(attrs);
  588. }
  589. }
  590. // This routine returns a DeclGroup, if the thing we parsed only contains a
  591. // single decl, convert it now.
  592. return Actions.ConvertDeclToDeclGroup(SingleDecl);
  593. }
  594. /// \brief Determine whether the current token, if it occurs after a
  595. /// declarator, continues a declaration or declaration list.
  596. bool Parser::isDeclarationAfterDeclarator() {
  597. // Check for '= delete' or '= default'
  598. if (getLang().CPlusPlus && Tok.is(tok::equal)) {
  599. const Token &KW = NextToken();
  600. if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
  601. return false;
  602. }
  603. return Tok.is(tok::equal) || // int X()= -> not a function def
  604. Tok.is(tok::comma) || // int X(), -> not a function def
  605. Tok.is(tok::semi) || // int X(); -> not a function def
  606. Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
  607. Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
  608. (getLang().CPlusPlus &&
  609. Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
  610. }
  611. /// \brief Determine whether the current token, if it occurs after a
  612. /// declarator, indicates the start of a function definition.
  613. bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
  614. assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
  615. if (Tok.is(tok::l_brace)) // int X() {}
  616. return true;
  617. // Handle K&R C argument lists: int X(f) int f; {}
  618. if (!getLang().CPlusPlus &&
  619. Declarator.getFunctionTypeInfo().isKNRPrototype())
  620. return isDeclarationSpecifier();
  621. if (getLang().CPlusPlus && Tok.is(tok::equal)) {
  622. const Token &KW = NextToken();
  623. return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
  624. }
  625. return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
  626. Tok.is(tok::kw_try); // X() try { ... }
  627. }
  628. /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
  629. /// a declaration. We can't tell which we have until we read up to the
  630. /// compound-statement in function-definition. TemplateParams, if
  631. /// non-NULL, provides the template parameters when we're parsing a
  632. /// C++ template-declaration.
  633. ///
  634. /// function-definition: [C99 6.9.1]
  635. /// decl-specs declarator declaration-list[opt] compound-statement
  636. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  637. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  638. ///
  639. /// declaration: [C99 6.7]
  640. /// declaration-specifiers init-declarator-list[opt] ';'
  641. /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
  642. /// [OMP] threadprivate-directive [TODO]
  643. ///
  644. Parser::DeclGroupPtrTy
  645. Parser::ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
  646. AccessSpecifier AS) {
  647. // Parse the common declaration-specifiers piece.
  648. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
  649. // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
  650. // declaration-specifiers init-declarator-list[opt] ';'
  651. if (Tok.is(tok::semi)) {
  652. ConsumeToken();
  653. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
  654. DS.complete(TheDecl);
  655. return Actions.ConvertDeclToDeclGroup(TheDecl);
  656. }
  657. // ObjC2 allows prefix attributes on class interfaces and protocols.
  658. // FIXME: This still needs better diagnostics. We should only accept
  659. // attributes here, no types, etc.
  660. if (getLang().ObjC2 && Tok.is(tok::at)) {
  661. SourceLocation AtLoc = ConsumeToken(); // the "@"
  662. if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
  663. !Tok.isObjCAtKeyword(tok::objc_protocol)) {
  664. Diag(Tok, diag::err_objc_unexpected_attr);
  665. SkipUntil(tok::semi); // FIXME: better skip?
  666. return DeclGroupPtrTy();
  667. }
  668. DS.abort();
  669. const char *PrevSpec = 0;
  670. unsigned DiagID;
  671. if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
  672. Diag(AtLoc, DiagID) << PrevSpec;
  673. Decl *TheDecl = 0;
  674. if (Tok.isObjCAtKeyword(tok::objc_protocol))
  675. TheDecl = ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
  676. else
  677. TheDecl = ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
  678. return Actions.ConvertDeclToDeclGroup(TheDecl);
  679. }
  680. // If the declspec consisted only of 'extern' and we have a string
  681. // literal following it, this must be a C++ linkage specifier like
  682. // 'extern "C"'.
  683. if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
  684. DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
  685. DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
  686. Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
  687. return Actions.ConvertDeclToDeclGroup(TheDecl);
  688. }
  689. return ParseDeclGroup(DS, Declarator::FileContext, true);
  690. }
  691. Parser::DeclGroupPtrTy
  692. Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs,
  693. AccessSpecifier AS) {
  694. ParsingDeclSpec DS(*this);
  695. DS.takeAttributesFrom(attrs);
  696. // Must temporarily exit the objective-c container scope for
  697. // parsing c constructs and re-enter objc container scope
  698. // afterwards.
  699. ObjCDeclContextSwitch ObjCDC(*this);
  700. return ParseDeclarationOrFunctionDefinition(DS, AS);
  701. }
  702. /// ParseFunctionDefinition - We parsed and verified that the specified
  703. /// Declarator is well formed. If this is a K&R-style function, read the
  704. /// parameters declaration-list, then start the compound-statement.
  705. ///
  706. /// function-definition: [C99 6.9.1]
  707. /// decl-specs declarator declaration-list[opt] compound-statement
  708. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  709. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  710. /// [C++] function-definition: [C++ 8.4]
  711. /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
  712. /// function-body
  713. /// [C++] function-definition: [C++ 8.4]
  714. /// decl-specifier-seq[opt] declarator function-try-block
  715. ///
  716. Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
  717. const ParsedTemplateInfo &TemplateInfo) {
  718. // Poison the SEH identifiers so they are flagged as illegal in function bodies
  719. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  720. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  721. // If this is C90 and the declspecs were completely missing, fudge in an
  722. // implicit int. We do this here because this is the only place where
  723. // declaration-specifiers are completely optional in the grammar.
  724. if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) {
  725. const char *PrevSpec;
  726. unsigned DiagID;
  727. D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
  728. D.getIdentifierLoc(),
  729. PrevSpec, DiagID);
  730. D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
  731. }
  732. // If this declaration was formed with a K&R-style identifier list for the
  733. // arguments, parse declarations for all of the args next.
  734. // int foo(a,b) int a; float b; {}
  735. if (FTI.isKNRPrototype())
  736. ParseKNRParamDeclarations(D);
  737. // We should have either an opening brace or, in a C++ constructor,
  738. // we may have a colon.
  739. if (Tok.isNot(tok::l_brace) &&
  740. (!getLang().CPlusPlus ||
  741. (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
  742. Tok.isNot(tok::equal)))) {
  743. Diag(Tok, diag::err_expected_fn_body);
  744. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  745. SkipUntil(tok::l_brace, true, true);
  746. // If we didn't find the '{', bail out.
  747. if (Tok.isNot(tok::l_brace))
  748. return 0;
  749. }
  750. // In delayed template parsing mode, for function template we consume the
  751. // tokens and store them for late parsing at the end of the translation unit.
  752. if (getLang().DelayedTemplateParsing &&
  753. TemplateInfo.Kind == ParsedTemplateInfo::Template) {
  754. MultiTemplateParamsArg TemplateParameterLists(Actions,
  755. TemplateInfo.TemplateParams->data(),
  756. TemplateInfo.TemplateParams->size());
  757. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  758. Scope *ParentScope = getCurScope()->getParent();
  759. D.setFunctionDefinitionKind(FDK_Definition);
  760. Decl *DP = Actions.HandleDeclarator(ParentScope, D,
  761. move(TemplateParameterLists));
  762. D.complete(DP);
  763. D.getMutableDeclSpec().abort();
  764. if (DP) {
  765. LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
  766. FunctionDecl *FnD = 0;
  767. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
  768. FnD = FunTmpl->getTemplatedDecl();
  769. else
  770. FnD = cast<FunctionDecl>(DP);
  771. Actions.CheckForFunctionRedefinition(FnD);
  772. LateParsedTemplateMap[FnD] = LPT;
  773. Actions.MarkAsLateParsedTemplate(FnD);
  774. LexTemplateFunctionForLateParsing(LPT->Toks);
  775. } else {
  776. CachedTokens Toks;
  777. LexTemplateFunctionForLateParsing(Toks);
  778. }
  779. return DP;
  780. }
  781. // Enter a scope for the function body.
  782. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  783. // Tell the actions module that we have entered a function definition with the
  784. // specified Declarator for the function.
  785. Decl *Res = TemplateInfo.TemplateParams?
  786. Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
  787. MultiTemplateParamsArg(Actions,
  788. TemplateInfo.TemplateParams->data(),
  789. TemplateInfo.TemplateParams->size()),
  790. D)
  791. : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
  792. // Break out of the ParsingDeclarator context before we parse the body.
  793. D.complete(Res);
  794. // Break out of the ParsingDeclSpec context, too. This const_cast is
  795. // safe because we're always the sole owner.
  796. D.getMutableDeclSpec().abort();
  797. if (Tok.is(tok::equal)) {
  798. assert(getLang().CPlusPlus && "Only C++ function definitions have '='");
  799. ConsumeToken();
  800. Actions.ActOnFinishFunctionBody(Res, 0, false);
  801. bool Delete = false;
  802. SourceLocation KWLoc;
  803. if (Tok.is(tok::kw_delete)) {
  804. Diag(Tok, getLang().CPlusPlus0x ?
  805. diag::warn_cxx98_compat_deleted_function :
  806. diag::ext_deleted_function);
  807. KWLoc = ConsumeToken();
  808. Actions.SetDeclDeleted(Res, KWLoc);
  809. Delete = true;
  810. } else if (Tok.is(tok::kw_default)) {
  811. Diag(Tok, getLang().CPlusPlus0x ?
  812. diag::warn_cxx98_compat_defaulted_function :
  813. diag::ext_defaulted_function);
  814. KWLoc = ConsumeToken();
  815. Actions.SetDeclDefaulted(Res, KWLoc);
  816. } else {
  817. llvm_unreachable("function definition after = not 'delete' or 'default'");
  818. }
  819. if (Tok.is(tok::comma)) {
  820. Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
  821. << Delete;
  822. SkipUntil(tok::semi);
  823. } else {
  824. ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
  825. Delete ? "delete" : "default", tok::semi);
  826. }
  827. return Res;
  828. }
  829. if (Tok.is(tok::kw_try))
  830. return ParseFunctionTryBlock(Res, BodyScope);
  831. // If we have a colon, then we're probably parsing a C++
  832. // ctor-initializer.
  833. if (Tok.is(tok::colon)) {
  834. ParseConstructorInitializer(Res);
  835. // Recover from error.
  836. if (!Tok.is(tok::l_brace)) {
  837. BodyScope.Exit();
  838. Actions.ActOnFinishFunctionBody(Res, 0);
  839. return Res;
  840. }
  841. } else
  842. Actions.ActOnDefaultCtorInitializers(Res);
  843. return ParseFunctionStatementBody(Res, BodyScope);
  844. }
  845. /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
  846. /// types for a function with a K&R-style identifier list for arguments.
  847. void Parser::ParseKNRParamDeclarations(Declarator &D) {
  848. // We know that the top-level of this declarator is a function.
  849. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  850. // Enter function-declaration scope, limiting any declarators to the
  851. // function prototype scope, including parameter declarators.
  852. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
  853. // Read all the argument declarations.
  854. while (isDeclarationSpecifier()) {
  855. SourceLocation DSStart = Tok.getLocation();
  856. // Parse the common declaration-specifiers piece.
  857. DeclSpec DS(AttrFactory);
  858. ParseDeclarationSpecifiers(DS);
  859. // C99 6.9.1p6: 'each declaration in the declaration list shall have at
  860. // least one declarator'.
  861. // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
  862. // the declarations though. It's trivial to ignore them, really hard to do
  863. // anything else with them.
  864. if (Tok.is(tok::semi)) {
  865. Diag(DSStart, diag::err_declaration_does_not_declare_param);
  866. ConsumeToken();
  867. continue;
  868. }
  869. // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
  870. // than register.
  871. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  872. DS.getStorageClassSpec() != DeclSpec::SCS_register) {
  873. Diag(DS.getStorageClassSpecLoc(),
  874. diag::err_invalid_storage_class_in_func_decl);
  875. DS.ClearStorageClassSpecs();
  876. }
  877. if (DS.isThreadSpecified()) {
  878. Diag(DS.getThreadSpecLoc(),
  879. diag::err_invalid_storage_class_in_func_decl);
  880. DS.ClearStorageClassSpecs();
  881. }
  882. // Parse the first declarator attached to this declspec.
  883. Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
  884. ParseDeclarator(ParmDeclarator);
  885. // Handle the full declarator list.
  886. while (1) {
  887. // If attributes are present, parse them.
  888. MaybeParseGNUAttributes(ParmDeclarator);
  889. // Ask the actions module to compute the type for this declarator.
  890. Decl *Param =
  891. Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
  892. if (Param &&
  893. // A missing identifier has already been diagnosed.
  894. ParmDeclarator.getIdentifier()) {
  895. // Scan the argument list looking for the correct param to apply this
  896. // type.
  897. for (unsigned i = 0; ; ++i) {
  898. // C99 6.9.1p6: those declarators shall declare only identifiers from
  899. // the identifier list.
  900. if (i == FTI.NumArgs) {
  901. Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
  902. << ParmDeclarator.getIdentifier();
  903. break;
  904. }
  905. if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
  906. // Reject redefinitions of parameters.
  907. if (FTI.ArgInfo[i].Param) {
  908. Diag(ParmDeclarator.getIdentifierLoc(),
  909. diag::err_param_redefinition)
  910. << ParmDeclarator.getIdentifier();
  911. } else {
  912. FTI.ArgInfo[i].Param = Param;
  913. }
  914. break;
  915. }
  916. }
  917. }
  918. // If we don't have a comma, it is either the end of the list (a ';') or
  919. // an error, bail out.
  920. if (Tok.isNot(tok::comma))
  921. break;
  922. // Consume the comma.
  923. ConsumeToken();
  924. // Parse the next declarator.
  925. ParmDeclarator.clear();
  926. ParseDeclarator(ParmDeclarator);
  927. }
  928. if (Tok.is(tok::semi)) {
  929. ConsumeToken();
  930. } else {
  931. Diag(Tok, diag::err_parse_error);
  932. // Skip to end of block or statement
  933. SkipUntil(tok::semi, true);
  934. if (Tok.is(tok::semi))
  935. ConsumeToken();
  936. }
  937. }
  938. // The actions module must verify that all arguments were declared.
  939. Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
  940. }
  941. /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
  942. /// allowed to be a wide string, and is not subject to character translation.
  943. ///
  944. /// [GNU] asm-string-literal:
  945. /// string-literal
  946. ///
  947. Parser::ExprResult Parser::ParseAsmStringLiteral() {
  948. switch (Tok.getKind()) {
  949. case tok::string_literal:
  950. break;
  951. case tok::wide_string_literal: {
  952. SourceLocation L = Tok.getLocation();
  953. Diag(Tok, diag::err_asm_operand_wide_string_literal)
  954. << SourceRange(L, L);
  955. return ExprError();
  956. }
  957. default:
  958. Diag(Tok, diag::err_expected_string_literal);
  959. return ExprError();
  960. }
  961. ExprResult Res(ParseStringLiteralExpression());
  962. if (Res.isInvalid()) return move(Res);
  963. return move(Res);
  964. }
  965. /// ParseSimpleAsm
  966. ///
  967. /// [GNU] simple-asm-expr:
  968. /// 'asm' '(' asm-string-literal ')'
  969. ///
  970. Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
  971. assert(Tok.is(tok::kw_asm) && "Not an asm!");
  972. SourceLocation Loc = ConsumeToken();
  973. if (Tok.is(tok::kw_volatile)) {
  974. // Remove from the end of 'asm' to the end of 'volatile'.
  975. SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
  976. PP.getLocForEndOfToken(Tok.getLocation()));
  977. Diag(Tok, diag::warn_file_asm_volatile)
  978. << FixItHint::CreateRemoval(RemovalRange);
  979. ConsumeToken();
  980. }
  981. BalancedDelimiterTracker T(*this, tok::l_paren);
  982. if (T.consumeOpen()) {
  983. Diag(Tok, diag::err_expected_lparen_after) << "asm";
  984. return ExprError();
  985. }
  986. ExprResult Result(ParseAsmStringLiteral());
  987. if (Result.isInvalid()) {
  988. SkipUntil(tok::r_paren, true, true);
  989. if (EndLoc)
  990. *EndLoc = Tok.getLocation();
  991. ConsumeAnyToken();
  992. } else {
  993. // Close the paren and get the location of the end bracket
  994. T.consumeClose();
  995. if (EndLoc)
  996. *EndLoc = T.getCloseLocation();
  997. }
  998. return move(Result);
  999. }
  1000. /// \brief Get the TemplateIdAnnotation from the token and put it in the
  1001. /// cleanup pool so that it gets destroyed when parsing the current top level
  1002. /// declaration is finished.
  1003. TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
  1004. assert(tok.is(tok::annot_template_id) && "Expected template-id token");
  1005. TemplateIdAnnotation *
  1006. Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
  1007. TopLevelDeclCleanupPool.delayMemberFunc< TemplateIdAnnotation,
  1008. &TemplateIdAnnotation::Destroy>(Id);
  1009. return Id;
  1010. }
  1011. /// TryAnnotateTypeOrScopeToken - If the current token position is on a
  1012. /// typename (possibly qualified in C++) or a C++ scope specifier not followed
  1013. /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
  1014. /// with a single annotation token representing the typename or C++ scope
  1015. /// respectively.
  1016. /// This simplifies handling of C++ scope specifiers and allows efficient
  1017. /// backtracking without the need to re-parse and resolve nested-names and
  1018. /// typenames.
  1019. /// It will mainly be called when we expect to treat identifiers as typenames
  1020. /// (if they are typenames). For example, in C we do not expect identifiers
  1021. /// inside expressions to be treated as typenames so it will not be called
  1022. /// for expressions in C.
  1023. /// The benefit for C/ObjC is that a typename will be annotated and
  1024. /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
  1025. /// will not be called twice, once to check whether we have a declaration
  1026. /// specifier, and another one to get the actual type inside
  1027. /// ParseDeclarationSpecifiers).
  1028. ///
  1029. /// This returns true if an error occurred.
  1030. ///
  1031. /// Note that this routine emits an error if you call it with ::new or ::delete
  1032. /// as the current tokens, so only call it in contexts where these are invalid.
  1033. bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
  1034. assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
  1035. || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
  1036. || Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
  1037. if (Tok.is(tok::kw_typename)) {
  1038. // Parse a C++ typename-specifier, e.g., "typename T::type".
  1039. //
  1040. // typename-specifier:
  1041. // 'typename' '::' [opt] nested-name-specifier identifier
  1042. // 'typename' '::' [opt] nested-name-specifier template [opt]
  1043. // simple-template-id
  1044. SourceLocation TypenameLoc = ConsumeToken();
  1045. CXXScopeSpec SS;
  1046. if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
  1047. /*EnteringContext=*/false,
  1048. 0, /*IsTypename*/true))
  1049. return true;
  1050. if (!SS.isSet()) {
  1051. if (getLang().MicrosoftExt)
  1052. Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
  1053. else
  1054. Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
  1055. return true;
  1056. }
  1057. TypeResult Ty;
  1058. if (Tok.is(tok::identifier)) {
  1059. // FIXME: check whether the next token is '<', first!
  1060. Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
  1061. *Tok.getIdentifierInfo(),
  1062. Tok.getLocation());
  1063. } else if (Tok.is(tok::annot_template_id)) {
  1064. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1065. if (TemplateId->Kind == TNK_Function_template) {
  1066. Diag(Tok, diag::err_typename_refers_to_non_type_template)
  1067. << Tok.getAnnotationRange();
  1068. return true;
  1069. }
  1070. ASTTemplateArgsPtr TemplateArgsPtr(Actions,
  1071. TemplateId->getTemplateArgs(),
  1072. TemplateId->NumArgs);
  1073. Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
  1074. /*FIXME:*/SourceLocation(),
  1075. TemplateId->Template,
  1076. TemplateId->TemplateNameLoc,
  1077. TemplateId->LAngleLoc,
  1078. TemplateArgsPtr,
  1079. TemplateId->RAngleLoc);
  1080. } else {
  1081. Diag(Tok, diag::err_expected_type_name_after_typename)
  1082. << SS.getRange();
  1083. return true;
  1084. }
  1085. SourceLocation EndLoc = Tok.getLastLoc();
  1086. Tok.setKind(tok::annot_typename);
  1087. setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
  1088. Tok.setAnnotationEndLoc(EndLoc);
  1089. Tok.setLocation(TypenameLoc);
  1090. PP.AnnotateCachedTokens(Tok);
  1091. return false;
  1092. }
  1093. // Remembers whether the token was originally a scope annotation.
  1094. bool wasScopeAnnotation = Tok.is(tok::annot_cxxscope);
  1095. CXXScopeSpec SS;
  1096. if (getLang().CPlusPlus)
  1097. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  1098. return true;
  1099. if (Tok.is(tok::identifier)) {
  1100. IdentifierInfo *CorrectedII = 0;
  1101. // Determine whether the identifier is a type name.
  1102. if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
  1103. Tok.getLocation(), getCurScope(),
  1104. &SS, false,
  1105. NextToken().is(tok::period),
  1106. ParsedType(),
  1107. /*NonTrivialTypeSourceInfo*/true,
  1108. NeedType ? &CorrectedII : NULL)) {
  1109. // A FixIt was applied as a result of typo correction
  1110. if (CorrectedII)
  1111. Tok.setIdentifierInfo(CorrectedII);
  1112. // This is a typename. Replace the current token in-place with an
  1113. // annotation type token.
  1114. Tok.setKind(tok::annot_typename);
  1115. setTypeAnnotation(Tok, Ty);
  1116. Tok.setAnnotationEndLoc(Tok.getLocation());
  1117. if (SS.isNotEmpty()) // it was a C++ qualified type name.
  1118. Tok.setLocation(SS.getBeginLoc());
  1119. // In case the tokens were cached, have Preprocessor replace
  1120. // them with the annotation token.
  1121. PP.AnnotateCachedTokens(Tok);
  1122. return false;
  1123. }
  1124. if (!getLang().CPlusPlus) {
  1125. // If we're in C, we can't have :: tokens at all (the lexer won't return
  1126. // them). If the identifier is not a type, then it can't be scope either,
  1127. // just early exit.
  1128. return false;
  1129. }
  1130. // If this is a template-id, annotate with a template-id or type token.
  1131. if (NextToken().is(tok::less)) {
  1132. TemplateTy Template;
  1133. UnqualifiedId TemplateName;
  1134. TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1135. bool MemberOfUnknownSpecialization;
  1136. if (TemplateNameKind TNK
  1137. = Actions.isTemplateName(getCurScope(), SS,
  1138. /*hasTemplateKeyword=*/false, TemplateName,
  1139. /*ObjectType=*/ ParsedType(),
  1140. EnteringContext,
  1141. Template, MemberOfUnknownSpecialization)) {
  1142. // Consume the identifier.
  1143. ConsumeToken();
  1144. if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName)) {
  1145. // If an unrecoverable error occurred, we need to return true here,
  1146. // because the token stream is in a damaged state. We may not return
  1147. // a valid identifier.
  1148. return true;
  1149. }
  1150. }
  1151. }
  1152. // The current token, which is either an identifier or a
  1153. // template-id, is not part of the annotation. Fall through to
  1154. // push that token back into the stream and complete the C++ scope
  1155. // specifier annotation.
  1156. }
  1157. if (Tok.is(tok::annot_template_id)) {
  1158. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1159. if (TemplateId->Kind == TNK_Type_template) {
  1160. // A template-id that refers to a type was parsed into a
  1161. // template-id annotation in a context where we weren't allowed
  1162. // to produce a type annotation token. Update the template-id
  1163. // annotation token to a type annotation token now.
  1164. AnnotateTemplateIdTokenAsType();
  1165. return false;
  1166. }
  1167. }
  1168. if (SS.isEmpty())
  1169. return false;
  1170. // A C++ scope specifier that isn't followed by a typename.
  1171. // Push the current token back into the token stream (or revert it if it is
  1172. // cached) and use an annotation scope token for current token.
  1173. if (PP.isBacktrackEnabled())
  1174. PP.RevertCachedTokens(1);
  1175. else
  1176. PP.EnterToken(Tok);
  1177. Tok.setKind(tok::annot_cxxscope);
  1178. Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
  1179. Tok.setAnnotationRange(SS.getRange());
  1180. // In case the tokens were cached, have Preprocessor replace them
  1181. // with the annotation token. We don't need to do this if we've
  1182. // just reverted back to the state we were in before being called.
  1183. if (!wasScopeAnnotation)
  1184. PP.AnnotateCachedTokens(Tok);
  1185. return false;
  1186. }
  1187. /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
  1188. /// annotates C++ scope specifiers and template-ids. This returns
  1189. /// true if the token was annotated or there was an error that could not be
  1190. /// recovered from.
  1191. ///
  1192. /// Note that this routine emits an error if you call it with ::new or ::delete
  1193. /// as the current tokens, so only call it in contexts where these are invalid.
  1194. bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
  1195. assert(getLang().CPlusPlus &&
  1196. "Call sites of this function should be guarded by checking for C++");
  1197. assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
  1198. (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
  1199. Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
  1200. CXXScopeSpec SS;
  1201. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  1202. return true;
  1203. if (SS.isEmpty())
  1204. return false;
  1205. // Push the current token back into the token stream (or revert it if it is
  1206. // cached) and use an annotation scope token for current token.
  1207. if (PP.isBacktrackEnabled())
  1208. PP.RevertCachedTokens(1);
  1209. else
  1210. PP.EnterToken(Tok);
  1211. Tok.setKind(tok::annot_cxxscope);
  1212. Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
  1213. Tok.setAnnotationRange(SS.getRange());
  1214. // In case the tokens were cached, have Preprocessor replace them with the
  1215. // annotation token.
  1216. PP.AnnotateCachedTokens(Tok);
  1217. return false;
  1218. }
  1219. bool Parser::isTokenEqualOrMistypedEqualEqual(unsigned DiagID) {
  1220. if (Tok.is(tok::equalequal)) {
  1221. // We have '==' in a context that we would expect a '='.
  1222. // The user probably made a typo, intending to type '='. Emit diagnostic,
  1223. // fixit hint to turn '==' -> '=' and continue as if the user typed '='.
  1224. Diag(Tok, DiagID)
  1225. << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
  1226. getTokenSimpleSpelling(tok::equal));
  1227. return true;
  1228. }
  1229. return Tok.is(tok::equal);
  1230. }
  1231. SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
  1232. assert(Tok.is(tok::code_completion));
  1233. PrevTokLocation = Tok.getLocation();
  1234. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1235. if (S->getFlags() & Scope::FnScope) {
  1236. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
  1237. cutOffParsing();
  1238. return PrevTokLocation;
  1239. }
  1240. if (S->getFlags() & Scope::ClassScope) {
  1241. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
  1242. cutOffParsing();
  1243. return PrevTokLocation;
  1244. }
  1245. }
  1246. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
  1247. cutOffParsing();
  1248. return PrevTokLocation;
  1249. }
  1250. // Anchor the Parser::FieldCallback vtable to this translation unit.
  1251. // We use a spurious method instead of the destructor because
  1252. // destroying FieldCallbacks can actually be slightly
  1253. // performance-sensitive.
  1254. void Parser::FieldCallback::_anchor() {
  1255. }
  1256. // Code-completion pass-through functions
  1257. void Parser::CodeCompleteDirective(bool InConditional) {
  1258. Actions.CodeCompletePreprocessorDirective(InConditional);
  1259. }
  1260. void Parser::CodeCompleteInConditionalExclusion() {
  1261. Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
  1262. }
  1263. void Parser::CodeCompleteMacroName(bool IsDefinition) {
  1264. Actions.CodeCompletePreprocessorMacroName(IsDefinition);
  1265. }
  1266. void Parser::CodeCompletePreprocessorExpression() {
  1267. Actions.CodeCompletePreprocessorExpression();
  1268. }
  1269. void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
  1270. MacroInfo *MacroInfo,
  1271. unsigned ArgumentIndex) {
  1272. Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
  1273. ArgumentIndex);
  1274. }
  1275. void Parser::CodeCompleteNaturalLanguage() {
  1276. Actions.CodeCompleteNaturalLanguage();
  1277. }
  1278. bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
  1279. assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
  1280. "Expected '__if_exists' or '__if_not_exists'");
  1281. Result.IsIfExists = Tok.is(tok::kw___if_exists);
  1282. Result.KeywordLoc = ConsumeToken();
  1283. BalancedDelimiterTracker T(*this, tok::l_paren);
  1284. if (T.consumeOpen()) {
  1285. Diag(Tok, diag::err_expected_lparen_after)
  1286. << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
  1287. return true;
  1288. }
  1289. // Parse nested-name-specifier.
  1290. ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
  1291. /*EnteringContext=*/false);
  1292. // Check nested-name specifier.
  1293. if (Result.SS.isInvalid()) {
  1294. T.skipToEnd();
  1295. return true;
  1296. }
  1297. // Parse the unqualified-id.
  1298. if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
  1299. Result.Name)) {
  1300. T.skipToEnd();
  1301. return true;
  1302. }
  1303. if (T.consumeClose())
  1304. return true;
  1305. // Check if the symbol exists.
  1306. switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
  1307. Result.IsIfExists, Result.SS,
  1308. Result.Name)) {
  1309. case Sema::IER_Exists:
  1310. Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1311. break;
  1312. case Sema::IER_DoesNotExist:
  1313. Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1314. break;
  1315. case Sema::IER_Dependent:
  1316. Result.Behavior = IEB_Dependent;
  1317. break;
  1318. case Sema::IER_Error:
  1319. return true;
  1320. }
  1321. return false;
  1322. }
  1323. void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
  1324. IfExistsCondition Result;
  1325. if (ParseMicrosoftIfExistsCondition(Result))
  1326. return;
  1327. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  1328. if (Braces.consumeOpen()) {
  1329. Diag(Tok, diag::err_expected_lbrace);
  1330. return;
  1331. }
  1332. switch (Result.Behavior) {
  1333. case IEB_Parse:
  1334. // Parse declarations below.
  1335. break;
  1336. case IEB_Dependent:
  1337. llvm_unreachable("Cannot have a dependent external declaration");
  1338. case IEB_Skip:
  1339. Braces.skipToEnd();
  1340. return;
  1341. }
  1342. // Parse the declarations.
  1343. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  1344. ParsedAttributesWithRange attrs(AttrFactory);
  1345. MaybeParseCXX0XAttributes(attrs);
  1346. MaybeParseMicrosoftAttributes(attrs);
  1347. DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
  1348. if (Result && !getCurScope()->getParent())
  1349. Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
  1350. }
  1351. Braces.consumeClose();
  1352. }
  1353. Parser::DeclGroupPtrTy Parser::ParseModuleImport() {
  1354. assert(Tok.is(tok::kw___import_module__) &&
  1355. "Improper start to module import");
  1356. SourceLocation ImportLoc = ConsumeToken();
  1357. llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1358. // Parse the module path.
  1359. do {
  1360. if (!Tok.is(tok::identifier)) {
  1361. Diag(Tok, diag::err_module_expected_ident);
  1362. SkipUntil(tok::semi);
  1363. return DeclGroupPtrTy();
  1364. }
  1365. // Record this part of the module path.
  1366. Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
  1367. ConsumeToken();
  1368. if (Tok.is(tok::period)) {
  1369. ConsumeToken();
  1370. continue;
  1371. }
  1372. break;
  1373. } while (true);
  1374. DeclResult Import = Actions.ActOnModuleImport(ImportLoc, Path);
  1375. ExpectAndConsumeSemi(diag::err_module_expected_semi);
  1376. if (Import.isInvalid())
  1377. return DeclGroupPtrTy();
  1378. return Actions.ConvertDeclToDeclGroup(Import.get());
  1379. }
  1380. bool Parser::BalancedDelimiterTracker::consumeOpen() {
  1381. // Try to consume the token we are holding
  1382. if (P.Tok.is(Kind)) {
  1383. P.QuantityTracker.push(Kind);
  1384. Cleanup = true;
  1385. if (P.QuantityTracker.getDepth(Kind) < MaxDepth) {
  1386. LOpen = P.ConsumeAnyToken();
  1387. return false;
  1388. } else {
  1389. P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
  1390. P.SkipUntil(tok::eof);
  1391. }
  1392. }
  1393. return true;
  1394. }
  1395. bool Parser::BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
  1396. const char *Msg,
  1397. tok::TokenKind SkipToToc ) {
  1398. LOpen = P.Tok.getLocation();
  1399. if (!P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc)) {
  1400. P.QuantityTracker.push(Kind);
  1401. Cleanup = true;
  1402. if (P.QuantityTracker.getDepth(Kind) < MaxDepth) {
  1403. return false;
  1404. } else {
  1405. P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
  1406. P.SkipUntil(tok::eof);
  1407. }
  1408. }
  1409. return true;
  1410. }
  1411. bool Parser::BalancedDelimiterTracker::consumeClose() {
  1412. if (P.Tok.is(Close)) {
  1413. LClose = P.ConsumeAnyToken();
  1414. if (Cleanup)
  1415. P.QuantityTracker.pop(Kind);
  1416. Cleanup = false;
  1417. return false;
  1418. } else {
  1419. const char *LHSName = "unknown";
  1420. diag::kind DID = diag::err_parse_error;
  1421. switch (Close) {
  1422. default: break;
  1423. case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
  1424. case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
  1425. case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
  1426. case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break;
  1427. case tok::greatergreatergreater:
  1428. LHSName = "<<<"; DID = diag::err_expected_ggg; break;
  1429. }
  1430. P.Diag(P.Tok, DID);
  1431. P.Diag(LOpen, diag::note_matching) << LHSName;
  1432. if (P.SkipUntil(Close))
  1433. LClose = P.Tok.getLocation();
  1434. }
  1435. return true;
  1436. }
  1437. void Parser::BalancedDelimiterTracker::skipToEnd() {
  1438. P.SkipUntil(Close, false);
  1439. Cleanup = false;
  1440. }