Parser.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  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 "RAIIObjectsForParser.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/Parse/ParseDiagnostic.h"
  19. #include "clang/Sema/DeclSpec.h"
  20. #include "clang/Sema/ParsedTemplate.h"
  21. #include "clang/Sema/Scope.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. namespace {
  25. /// \brief A comment handler that passes comments found by the preprocessor
  26. /// to the parser action.
  27. class ActionCommentHandler : public CommentHandler {
  28. Sema &S;
  29. public:
  30. explicit ActionCommentHandler(Sema &S) : S(S) { }
  31. bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
  32. S.ActOnComment(Comment);
  33. return false;
  34. }
  35. };
  36. } // end anonymous namespace
  37. IdentifierInfo *Parser::getSEHExceptKeyword() {
  38. // __except is accepted as a (contextual) keyword
  39. if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
  40. Ident__except = PP.getIdentifierInfo("__except");
  41. return Ident__except;
  42. }
  43. Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
  44. : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
  45. GreaterThanIsOperator(true), ColonIsSacred(false),
  46. InMessageExpression(false), TemplateParameterDepth(0),
  47. ParsingInObjCContainer(false) {
  48. SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
  49. Tok.startToken();
  50. Tok.setKind(tok::eof);
  51. Actions.CurScope = nullptr;
  52. NumCachedScopes = 0;
  53. ParenCount = BracketCount = BraceCount = 0;
  54. CurParsedObjCImpl = nullptr;
  55. // Add #pragma handlers. These are removed and destroyed in the
  56. // destructor.
  57. initializePragmaHandlers();
  58. CommentSemaHandler.reset(new ActionCommentHandler(actions));
  59. PP.addCommentHandler(CommentSemaHandler.get());
  60. PP.setCodeCompletionHandler(*this);
  61. }
  62. DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
  63. return Diags.Report(Loc, DiagID);
  64. }
  65. DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
  66. return Diag(Tok.getLocation(), DiagID);
  67. }
  68. /// \brief Emits a diagnostic suggesting parentheses surrounding a
  69. /// given range.
  70. ///
  71. /// \param Loc The location where we'll emit the diagnostic.
  72. /// \param DK The kind of diagnostic to emit.
  73. /// \param ParenRange Source range enclosing code that should be parenthesized.
  74. void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
  75. SourceRange ParenRange) {
  76. SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
  77. if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
  78. // We can't display the parentheses, so just dig the
  79. // warning/error and return.
  80. Diag(Loc, DK);
  81. return;
  82. }
  83. Diag(Loc, DK)
  84. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  85. << FixItHint::CreateInsertion(EndLoc, ")");
  86. }
  87. static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
  88. switch (ExpectedTok) {
  89. case tok::semi:
  90. return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
  91. default: return false;
  92. }
  93. }
  94. bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
  95. StringRef Msg) {
  96. if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
  97. ConsumeAnyToken();
  98. return false;
  99. }
  100. // Detect common single-character typos and resume.
  101. if (IsCommonTypo(ExpectedTok, Tok)) {
  102. SourceLocation Loc = Tok.getLocation();
  103. {
  104. DiagnosticBuilder DB = Diag(Loc, DiagID);
  105. DB << FixItHint::CreateReplacement(
  106. SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
  107. if (DiagID == diag::err_expected)
  108. DB << ExpectedTok;
  109. else if (DiagID == diag::err_expected_after)
  110. DB << Msg << ExpectedTok;
  111. else
  112. DB << Msg;
  113. }
  114. // Pretend there wasn't a problem.
  115. ConsumeAnyToken();
  116. return false;
  117. }
  118. SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
  119. const char *Spelling = nullptr;
  120. if (EndLoc.isValid())
  121. Spelling = tok::getPunctuatorSpelling(ExpectedTok);
  122. DiagnosticBuilder DB =
  123. Spelling
  124. ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
  125. : Diag(Tok, DiagID);
  126. if (DiagID == diag::err_expected)
  127. DB << ExpectedTok;
  128. else if (DiagID == diag::err_expected_after)
  129. DB << Msg << ExpectedTok;
  130. else
  131. DB << Msg;
  132. return true;
  133. }
  134. bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
  135. if (TryConsumeToken(tok::semi))
  136. return false;
  137. if (Tok.is(tok::code_completion)) {
  138. handleUnexpectedCodeCompletionToken();
  139. return false;
  140. }
  141. if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
  142. NextToken().is(tok::semi)) {
  143. Diag(Tok, diag::err_extraneous_token_before_semi)
  144. << PP.getSpelling(Tok)
  145. << FixItHint::CreateRemoval(Tok.getLocation());
  146. ConsumeAnyToken(); // The ')' or ']'.
  147. ConsumeToken(); // The ';'.
  148. return false;
  149. }
  150. return ExpectAndConsume(tok::semi, DiagID);
  151. }
  152. void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
  153. if (!Tok.is(tok::semi)) return;
  154. bool HadMultipleSemis = false;
  155. SourceLocation StartLoc = Tok.getLocation();
  156. SourceLocation EndLoc = Tok.getLocation();
  157. ConsumeToken();
  158. while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
  159. HadMultipleSemis = true;
  160. EndLoc = Tok.getLocation();
  161. ConsumeToken();
  162. }
  163. // C++11 allows extra semicolons at namespace scope, but not in any of the
  164. // other contexts.
  165. if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
  166. if (getLangOpts().CPlusPlus11)
  167. Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
  168. << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
  169. else
  170. Diag(StartLoc, diag::ext_extra_semi_cxx11)
  171. << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
  172. return;
  173. }
  174. if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
  175. Diag(StartLoc, diag::ext_extra_semi)
  176. << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST,
  177. Actions.getASTContext().getPrintingPolicy())
  178. << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
  179. else
  180. // A single semicolon is valid after a member function definition.
  181. Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
  182. << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
  183. }
  184. //===----------------------------------------------------------------------===//
  185. // Error recovery.
  186. //===----------------------------------------------------------------------===//
  187. static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
  188. return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
  189. }
  190. /// SkipUntil - Read tokens until we get to the specified token, then consume
  191. /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
  192. /// token will ever occur, this skips to the next token, or to some likely
  193. /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
  194. /// character.
  195. ///
  196. /// If SkipUntil finds the specified token, it returns true, otherwise it
  197. /// returns false.
  198. bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
  199. // We always want this function to skip at least one token if the first token
  200. // isn't T and if not at EOF.
  201. bool isFirstTokenSkipped = true;
  202. while (1) {
  203. // If we found one of the tokens, stop and return true.
  204. for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
  205. if (Tok.is(Toks[i])) {
  206. if (HasFlagsSet(Flags, StopBeforeMatch)) {
  207. // Noop, don't consume the token.
  208. } else {
  209. ConsumeAnyToken();
  210. }
  211. return true;
  212. }
  213. }
  214. // Important special case: The caller has given up and just wants us to
  215. // skip the rest of the file. Do this without recursing, since we can
  216. // get here precisely because the caller detected too much recursion.
  217. if (Toks.size() == 1 && Toks[0] == tok::eof &&
  218. !HasFlagsSet(Flags, StopAtSemi) &&
  219. !HasFlagsSet(Flags, StopAtCodeCompletion)) {
  220. while (Tok.isNot(tok::eof))
  221. ConsumeAnyToken();
  222. return true;
  223. }
  224. switch (Tok.getKind()) {
  225. case tok::eof:
  226. // Ran out of tokens.
  227. return false;
  228. case tok::annot_pragma_openmp_end:
  229. // Stop before an OpenMP pragma boundary.
  230. case tok::annot_module_begin:
  231. case tok::annot_module_end:
  232. case tok::annot_module_include:
  233. // Stop before we change submodules. They generally indicate a "good"
  234. // place to pick up parsing again (except in the special case where
  235. // we're trying to skip to EOF).
  236. return false;
  237. case tok::code_completion:
  238. if (!HasFlagsSet(Flags, StopAtCodeCompletion))
  239. handleUnexpectedCodeCompletionToken();
  240. return false;
  241. case tok::l_paren:
  242. // Recursively skip properly-nested parens.
  243. ConsumeParen();
  244. if (HasFlagsSet(Flags, StopAtCodeCompletion))
  245. SkipUntil(tok::r_paren, StopAtCodeCompletion);
  246. else
  247. SkipUntil(tok::r_paren);
  248. break;
  249. case tok::l_square:
  250. // Recursively skip properly-nested square brackets.
  251. ConsumeBracket();
  252. if (HasFlagsSet(Flags, StopAtCodeCompletion))
  253. SkipUntil(tok::r_square, StopAtCodeCompletion);
  254. else
  255. SkipUntil(tok::r_square);
  256. break;
  257. case tok::l_brace:
  258. // Recursively skip properly-nested braces.
  259. ConsumeBrace();
  260. if (HasFlagsSet(Flags, StopAtCodeCompletion))
  261. SkipUntil(tok::r_brace, StopAtCodeCompletion);
  262. else
  263. SkipUntil(tok::r_brace);
  264. break;
  265. // Okay, we found a ']' or '}' or ')', which we think should be balanced.
  266. // Since the user wasn't looking for this token (if they were, it would
  267. // already be handled), this isn't balanced. If there is a LHS token at a
  268. // higher level, we will assume that this matches the unbalanced token
  269. // and return it. Otherwise, this is a spurious RHS token, which we skip.
  270. case tok::r_paren:
  271. if (ParenCount && !isFirstTokenSkipped)
  272. return false; // Matches something.
  273. ConsumeParen();
  274. break;
  275. case tok::r_square:
  276. if (BracketCount && !isFirstTokenSkipped)
  277. return false; // Matches something.
  278. ConsumeBracket();
  279. break;
  280. case tok::r_brace:
  281. if (BraceCount && !isFirstTokenSkipped)
  282. return false; // Matches something.
  283. ConsumeBrace();
  284. break;
  285. case tok::string_literal:
  286. case tok::wide_string_literal:
  287. case tok::utf8_string_literal:
  288. case tok::utf16_string_literal:
  289. case tok::utf32_string_literal:
  290. ConsumeStringToken();
  291. break;
  292. case tok::semi:
  293. if (HasFlagsSet(Flags, StopAtSemi))
  294. return false;
  295. // FALL THROUGH.
  296. default:
  297. // Skip this token.
  298. ConsumeToken();
  299. break;
  300. }
  301. isFirstTokenSkipped = false;
  302. }
  303. }
  304. //===----------------------------------------------------------------------===//
  305. // Scope manipulation
  306. //===----------------------------------------------------------------------===//
  307. /// EnterScope - Start a new scope.
  308. void Parser::EnterScope(unsigned ScopeFlags) {
  309. if (NumCachedScopes) {
  310. Scope *N = ScopeCache[--NumCachedScopes];
  311. N->Init(getCurScope(), ScopeFlags);
  312. Actions.CurScope = N;
  313. } else {
  314. Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
  315. }
  316. }
  317. /// ExitScope - Pop a scope off the scope stack.
  318. void Parser::ExitScope() {
  319. assert(getCurScope() && "Scope imbalance!");
  320. // Inform the actions module that this scope is going away if there are any
  321. // decls in it.
  322. Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
  323. Scope *OldScope = getCurScope();
  324. Actions.CurScope = OldScope->getParent();
  325. if (NumCachedScopes == ScopeCacheSize)
  326. delete OldScope;
  327. else
  328. ScopeCache[NumCachedScopes++] = OldScope;
  329. }
  330. /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
  331. /// this object does nothing.
  332. Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
  333. bool ManageFlags)
  334. : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
  335. if (CurScope) {
  336. OldFlags = CurScope->getFlags();
  337. CurScope->setFlags(ScopeFlags);
  338. }
  339. }
  340. /// Restore the flags for the current scope to what they were before this
  341. /// object overrode them.
  342. Parser::ParseScopeFlags::~ParseScopeFlags() {
  343. if (CurScope)
  344. CurScope->setFlags(OldFlags);
  345. }
  346. //===----------------------------------------------------------------------===//
  347. // C99 6.9: External Definitions.
  348. //===----------------------------------------------------------------------===//
  349. Parser::~Parser() {
  350. // If we still have scopes active, delete the scope tree.
  351. delete getCurScope();
  352. Actions.CurScope = nullptr;
  353. // Free the scope cache.
  354. for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
  355. delete ScopeCache[i];
  356. resetPragmaHandlers();
  357. PP.removeCommentHandler(CommentSemaHandler.get());
  358. PP.clearCodeCompletionHandler();
  359. assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
  360. }
  361. /// Initialize - Warm up the parser.
  362. ///
  363. void Parser::Initialize() {
  364. // Create the translation unit scope. Install it as the current scope.
  365. assert(getCurScope() == nullptr && "A scope is already active?");
  366. EnterScope(Scope::DeclScope);
  367. Actions.ActOnTranslationUnitScope(getCurScope());
  368. // Initialization for Objective-C context sensitive keywords recognition.
  369. // Referenced in Parser::ParseObjCTypeQualifierList.
  370. if (getLangOpts().ObjC1) {
  371. ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
  372. ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
  373. ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
  374. ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
  375. ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
  376. ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
  377. }
  378. Ident_instancetype = nullptr;
  379. Ident_final = nullptr;
  380. Ident_sealed = nullptr;
  381. Ident_override = nullptr;
  382. Ident_super = &PP.getIdentifierTable().get("super");
  383. if (getLangOpts().AltiVec) {
  384. Ident_vector = &PP.getIdentifierTable().get("vector");
  385. Ident_pixel = &PP.getIdentifierTable().get("pixel");
  386. Ident_bool = &PP.getIdentifierTable().get("bool");
  387. }
  388. Ident_introduced = nullptr;
  389. Ident_deprecated = nullptr;
  390. Ident_obsoleted = nullptr;
  391. Ident_unavailable = nullptr;
  392. Ident__except = nullptr;
  393. Ident__exception_code = Ident__exception_info = nullptr;
  394. Ident__abnormal_termination = Ident___exception_code = nullptr;
  395. Ident___exception_info = Ident___abnormal_termination = nullptr;
  396. Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
  397. Ident_AbnormalTermination = nullptr;
  398. if(getLangOpts().Borland) {
  399. Ident__exception_info = PP.getIdentifierInfo("_exception_info");
  400. Ident___exception_info = PP.getIdentifierInfo("__exception_info");
  401. Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
  402. Ident__exception_code = PP.getIdentifierInfo("_exception_code");
  403. Ident___exception_code = PP.getIdentifierInfo("__exception_code");
  404. Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
  405. Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
  406. Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
  407. Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
  408. PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
  409. PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
  410. PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
  411. PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
  412. PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
  413. PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
  414. PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
  415. PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
  416. PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
  417. }
  418. Actions.Initialize();
  419. // Prime the lexer look-ahead.
  420. ConsumeToken();
  421. }
  422. namespace {
  423. /// \brief RAIIObject to destroy the contents of a SmallVector of
  424. /// TemplateIdAnnotation pointers and clear the vector.
  425. class DestroyTemplateIdAnnotationsRAIIObj {
  426. SmallVectorImpl<TemplateIdAnnotation *> &Container;
  427. public:
  428. DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
  429. &Container)
  430. : Container(Container) {}
  431. ~DestroyTemplateIdAnnotationsRAIIObj() {
  432. for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
  433. Container.begin(), E = Container.end();
  434. I != E; ++I)
  435. (*I)->Destroy();
  436. Container.clear();
  437. }
  438. };
  439. }
  440. void Parser::LateTemplateParserCleanupCallback(void *P) {
  441. // While this RAII helper doesn't bracket any actual work, the destructor will
  442. // clean up annotations that were created during ActOnEndOfTranslationUnit
  443. // when incremental processing is enabled.
  444. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
  445. }
  446. /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
  447. /// action tells us to. This returns true if the EOF was encountered.
  448. bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
  449. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
  450. // Skip over the EOF token, flagging end of previous input for incremental
  451. // processing
  452. if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
  453. ConsumeToken();
  454. Result = DeclGroupPtrTy();
  455. switch (Tok.getKind()) {
  456. case tok::annot_pragma_unused:
  457. HandlePragmaUnused();
  458. return false;
  459. case tok::annot_module_include:
  460. Actions.ActOnModuleInclude(Tok.getLocation(),
  461. reinterpret_cast<Module *>(
  462. Tok.getAnnotationValue()));
  463. ConsumeToken();
  464. return false;
  465. case tok::annot_module_begin:
  466. case tok::annot_module_end:
  467. // FIXME: Update visibility based on the submodule we're in.
  468. ConsumeToken();
  469. return false;
  470. case tok::eof:
  471. // Late template parsing can begin.
  472. if (getLangOpts().DelayedTemplateParsing)
  473. Actions.SetLateTemplateParser(LateTemplateParserCallback,
  474. PP.isIncrementalProcessingEnabled() ?
  475. LateTemplateParserCleanupCallback : nullptr,
  476. this);
  477. if (!PP.isIncrementalProcessingEnabled())
  478. Actions.ActOnEndOfTranslationUnit();
  479. //else don't tell Sema that we ended parsing: more input might come.
  480. return true;
  481. default:
  482. break;
  483. }
  484. ParsedAttributesWithRange attrs(AttrFactory);
  485. MaybeParseCXX11Attributes(attrs);
  486. MaybeParseMicrosoftAttributes(attrs);
  487. Result = ParseExternalDeclaration(attrs);
  488. return false;
  489. }
  490. /// ParseExternalDeclaration:
  491. ///
  492. /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
  493. /// function-definition
  494. /// declaration
  495. /// [GNU] asm-definition
  496. /// [GNU] __extension__ external-declaration
  497. /// [OBJC] objc-class-definition
  498. /// [OBJC] objc-class-declaration
  499. /// [OBJC] objc-alias-declaration
  500. /// [OBJC] objc-protocol-definition
  501. /// [OBJC] objc-method-definition
  502. /// [OBJC] @end
  503. /// [C++] linkage-specification
  504. /// [GNU] asm-definition:
  505. /// simple-asm-expr ';'
  506. /// [C++11] empty-declaration
  507. /// [C++11] attribute-declaration
  508. ///
  509. /// [C++11] empty-declaration:
  510. /// ';'
  511. ///
  512. /// [C++0x/GNU] 'extern' 'template' declaration
  513. Parser::DeclGroupPtrTy
  514. Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
  515. ParsingDeclSpec *DS) {
  516. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
  517. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  518. if (PP.isCodeCompletionReached()) {
  519. cutOffParsing();
  520. return DeclGroupPtrTy();
  521. }
  522. Decl *SingleDecl = nullptr;
  523. switch (Tok.getKind()) {
  524. case tok::annot_pragma_vis:
  525. HandlePragmaVisibility();
  526. return DeclGroupPtrTy();
  527. case tok::annot_pragma_pack:
  528. HandlePragmaPack();
  529. return DeclGroupPtrTy();
  530. case tok::annot_pragma_msstruct:
  531. HandlePragmaMSStruct();
  532. return DeclGroupPtrTy();
  533. case tok::annot_pragma_align:
  534. HandlePragmaAlign();
  535. return DeclGroupPtrTy();
  536. case tok::annot_pragma_weak:
  537. HandlePragmaWeak();
  538. return DeclGroupPtrTy();
  539. case tok::annot_pragma_weakalias:
  540. HandlePragmaWeakAlias();
  541. return DeclGroupPtrTy();
  542. case tok::annot_pragma_redefine_extname:
  543. HandlePragmaRedefineExtname();
  544. return DeclGroupPtrTy();
  545. case tok::annot_pragma_fp_contract:
  546. HandlePragmaFPContract();
  547. return DeclGroupPtrTy();
  548. case tok::annot_pragma_opencl_extension:
  549. HandlePragmaOpenCLExtension();
  550. return DeclGroupPtrTy();
  551. case tok::annot_pragma_openmp:
  552. return ParseOpenMPDeclarativeDirective();
  553. case tok::annot_pragma_ms_pointers_to_members:
  554. HandlePragmaMSPointersToMembers();
  555. return DeclGroupPtrTy();
  556. case tok::annot_pragma_ms_vtordisp:
  557. HandlePragmaMSVtorDisp();
  558. return DeclGroupPtrTy();
  559. case tok::annot_pragma_ms_pragma:
  560. HandlePragmaMSPragma();
  561. return DeclGroupPtrTy();
  562. case tok::semi:
  563. // Either a C++11 empty-declaration or attribute-declaration.
  564. SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
  565. attrs.getList(),
  566. Tok.getLocation());
  567. ConsumeExtraSemi(OutsideFunction);
  568. break;
  569. case tok::r_brace:
  570. Diag(Tok, diag::err_extraneous_closing_brace);
  571. ConsumeBrace();
  572. return DeclGroupPtrTy();
  573. case tok::eof:
  574. Diag(Tok, diag::err_expected_external_declaration);
  575. return DeclGroupPtrTy();
  576. case tok::kw___extension__: {
  577. // __extension__ silences extension warnings in the subexpression.
  578. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  579. ConsumeToken();
  580. return ParseExternalDeclaration(attrs);
  581. }
  582. case tok::kw_asm: {
  583. ProhibitAttributes(attrs);
  584. SourceLocation StartLoc = Tok.getLocation();
  585. SourceLocation EndLoc;
  586. ExprResult Result(ParseSimpleAsm(&EndLoc));
  587. ExpectAndConsume(tok::semi, diag::err_expected_after,
  588. "top-level asm block");
  589. if (Result.isInvalid())
  590. return DeclGroupPtrTy();
  591. SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
  592. break;
  593. }
  594. case tok::at:
  595. return ParseObjCAtDirectives();
  596. case tok::minus:
  597. case tok::plus:
  598. if (!getLangOpts().ObjC1) {
  599. Diag(Tok, diag::err_expected_external_declaration);
  600. ConsumeToken();
  601. return DeclGroupPtrTy();
  602. }
  603. SingleDecl = ParseObjCMethodDefinition();
  604. break;
  605. case tok::code_completion:
  606. Actions.CodeCompleteOrdinaryName(getCurScope(),
  607. CurParsedObjCImpl? Sema::PCC_ObjCImplementation
  608. : Sema::PCC_Namespace);
  609. cutOffParsing();
  610. return DeclGroupPtrTy();
  611. case tok::kw_using:
  612. case tok::kw_namespace:
  613. case tok::kw_typedef:
  614. case tok::kw_template:
  615. case tok::kw_export: // As in 'export template'
  616. case tok::kw_static_assert:
  617. case tok::kw__Static_assert:
  618. // A function definition cannot start with any of these keywords.
  619. {
  620. SourceLocation DeclEnd;
  621. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  622. }
  623. case tok::kw_static:
  624. // Parse (then ignore) 'static' prior to a template instantiation. This is
  625. // a GCC extension that we intentionally do not support.
  626. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
  627. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  628. << 0;
  629. SourceLocation DeclEnd;
  630. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  631. }
  632. goto dont_know;
  633. case tok::kw_inline:
  634. if (getLangOpts().CPlusPlus) {
  635. tok::TokenKind NextKind = NextToken().getKind();
  636. // Inline namespaces. Allowed as an extension even in C++03.
  637. if (NextKind == tok::kw_namespace) {
  638. SourceLocation DeclEnd;
  639. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  640. }
  641. // Parse (then ignore) 'inline' prior to a template instantiation. This is
  642. // a GCC extension that we intentionally do not support.
  643. if (NextKind == tok::kw_template) {
  644. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  645. << 1;
  646. SourceLocation DeclEnd;
  647. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  648. }
  649. }
  650. goto dont_know;
  651. case tok::kw_extern:
  652. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
  653. // Extern templates
  654. SourceLocation ExternLoc = ConsumeToken();
  655. SourceLocation TemplateLoc = ConsumeToken();
  656. Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
  657. diag::warn_cxx98_compat_extern_template :
  658. diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
  659. SourceLocation DeclEnd;
  660. return Actions.ConvertDeclToDeclGroup(
  661. ParseExplicitInstantiation(Declarator::FileContext,
  662. ExternLoc, TemplateLoc, DeclEnd));
  663. }
  664. goto dont_know;
  665. case tok::kw___if_exists:
  666. case tok::kw___if_not_exists:
  667. ParseMicrosoftIfExistsExternalDeclaration();
  668. return DeclGroupPtrTy();
  669. default:
  670. dont_know:
  671. // We can't tell whether this is a function-definition or declaration yet.
  672. return ParseDeclarationOrFunctionDefinition(attrs, DS);
  673. }
  674. // This routine returns a DeclGroup, if the thing we parsed only contains a
  675. // single decl, convert it now.
  676. return Actions.ConvertDeclToDeclGroup(SingleDecl);
  677. }
  678. /// \brief Determine whether the current token, if it occurs after a
  679. /// declarator, continues a declaration or declaration list.
  680. bool Parser::isDeclarationAfterDeclarator() {
  681. // Check for '= delete' or '= default'
  682. if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
  683. const Token &KW = NextToken();
  684. if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
  685. return false;
  686. }
  687. return Tok.is(tok::equal) || // int X()= -> not a function def
  688. Tok.is(tok::comma) || // int X(), -> not a function def
  689. Tok.is(tok::semi) || // int X(); -> not a function def
  690. Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
  691. Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
  692. (getLangOpts().CPlusPlus &&
  693. Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
  694. }
  695. /// \brief Determine whether the current token, if it occurs after a
  696. /// declarator, indicates the start of a function definition.
  697. bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
  698. assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
  699. if (Tok.is(tok::l_brace)) // int X() {}
  700. return true;
  701. // Handle K&R C argument lists: int X(f) int f; {}
  702. if (!getLangOpts().CPlusPlus &&
  703. Declarator.getFunctionTypeInfo().isKNRPrototype())
  704. return isDeclarationSpecifier();
  705. if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
  706. const Token &KW = NextToken();
  707. return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
  708. }
  709. return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
  710. Tok.is(tok::kw_try); // X() try { ... }
  711. }
  712. /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
  713. /// a declaration. We can't tell which we have until we read up to the
  714. /// compound-statement in function-definition. TemplateParams, if
  715. /// non-NULL, provides the template parameters when we're parsing a
  716. /// C++ template-declaration.
  717. ///
  718. /// function-definition: [C99 6.9.1]
  719. /// decl-specs declarator declaration-list[opt] compound-statement
  720. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  721. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  722. ///
  723. /// declaration: [C99 6.7]
  724. /// declaration-specifiers init-declarator-list[opt] ';'
  725. /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
  726. /// [OMP] threadprivate-directive [TODO]
  727. ///
  728. Parser::DeclGroupPtrTy
  729. Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
  730. ParsingDeclSpec &DS,
  731. AccessSpecifier AS) {
  732. // Parse the common declaration-specifiers piece.
  733. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
  734. // If we had a free-standing type definition with a missing semicolon, we
  735. // may get this far before the problem becomes obvious.
  736. if (DS.hasTagDefinition() &&
  737. DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
  738. return DeclGroupPtrTy();
  739. // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
  740. // declaration-specifiers init-declarator-list[opt] ';'
  741. if (Tok.is(tok::semi)) {
  742. ProhibitAttributes(attrs);
  743. ConsumeToken();
  744. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
  745. DS.complete(TheDecl);
  746. return Actions.ConvertDeclToDeclGroup(TheDecl);
  747. }
  748. DS.takeAttributesFrom(attrs);
  749. // ObjC2 allows prefix attributes on class interfaces and protocols.
  750. // FIXME: This still needs better diagnostics. We should only accept
  751. // attributes here, no types, etc.
  752. if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
  753. SourceLocation AtLoc = ConsumeToken(); // the "@"
  754. if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
  755. !Tok.isObjCAtKeyword(tok::objc_protocol)) {
  756. Diag(Tok, diag::err_objc_unexpected_attr);
  757. SkipUntil(tok::semi); // FIXME: better skip?
  758. return DeclGroupPtrTy();
  759. }
  760. DS.abort();
  761. const char *PrevSpec = nullptr;
  762. unsigned DiagID;
  763. if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
  764. Actions.getASTContext().getPrintingPolicy()))
  765. Diag(AtLoc, DiagID) << PrevSpec;
  766. if (Tok.isObjCAtKeyword(tok::objc_protocol))
  767. return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
  768. return Actions.ConvertDeclToDeclGroup(
  769. ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
  770. }
  771. // If the declspec consisted only of 'extern' and we have a string
  772. // literal following it, this must be a C++ linkage specifier like
  773. // 'extern "C"'.
  774. if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
  775. DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
  776. DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
  777. Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
  778. return Actions.ConvertDeclToDeclGroup(TheDecl);
  779. }
  780. return ParseDeclGroup(DS, Declarator::FileContext);
  781. }
  782. Parser::DeclGroupPtrTy
  783. Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
  784. ParsingDeclSpec *DS,
  785. AccessSpecifier AS) {
  786. if (DS) {
  787. return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
  788. } else {
  789. ParsingDeclSpec PDS(*this);
  790. // Must temporarily exit the objective-c container scope for
  791. // parsing c constructs and re-enter objc container scope
  792. // afterwards.
  793. ObjCDeclContextSwitch ObjCDC(*this);
  794. return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
  795. }
  796. }
  797. /// ParseFunctionDefinition - We parsed and verified that the specified
  798. /// Declarator is well formed. If this is a K&R-style function, read the
  799. /// parameters declaration-list, then start the compound-statement.
  800. ///
  801. /// function-definition: [C99 6.9.1]
  802. /// decl-specs declarator declaration-list[opt] compound-statement
  803. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  804. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  805. /// [C++] function-definition: [C++ 8.4]
  806. /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
  807. /// function-body
  808. /// [C++] function-definition: [C++ 8.4]
  809. /// decl-specifier-seq[opt] declarator function-try-block
  810. ///
  811. Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
  812. const ParsedTemplateInfo &TemplateInfo,
  813. LateParsedAttrList *LateParsedAttrs) {
  814. // Poison SEH identifiers so they are flagged as illegal in function bodies.
  815. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  816. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  817. // If this is C90 and the declspecs were completely missing, fudge in an
  818. // implicit int. We do this here because this is the only place where
  819. // declaration-specifiers are completely optional in the grammar.
  820. if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
  821. const char *PrevSpec;
  822. unsigned DiagID;
  823. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  824. D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
  825. D.getIdentifierLoc(),
  826. PrevSpec, DiagID,
  827. Policy);
  828. D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
  829. }
  830. // If this declaration was formed with a K&R-style identifier list for the
  831. // arguments, parse declarations for all of the args next.
  832. // int foo(a,b) int a; float b; {}
  833. if (FTI.isKNRPrototype())
  834. ParseKNRParamDeclarations(D);
  835. // We should have either an opening brace or, in a C++ constructor,
  836. // we may have a colon.
  837. if (Tok.isNot(tok::l_brace) &&
  838. (!getLangOpts().CPlusPlus ||
  839. (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
  840. Tok.isNot(tok::equal)))) {
  841. Diag(Tok, diag::err_expected_fn_body);
  842. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  843. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  844. // If we didn't find the '{', bail out.
  845. if (Tok.isNot(tok::l_brace))
  846. return nullptr;
  847. }
  848. // Check to make sure that any normal attributes are allowed to be on
  849. // a definition. Late parsed attributes are checked at the end.
  850. if (Tok.isNot(tok::equal)) {
  851. AttributeList *DtorAttrs = D.getAttributes();
  852. while (DtorAttrs) {
  853. if (DtorAttrs->isKnownToGCC() &&
  854. !DtorAttrs->isCXX11Attribute()) {
  855. Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
  856. << DtorAttrs->getName();
  857. }
  858. DtorAttrs = DtorAttrs->getNext();
  859. }
  860. }
  861. // In delayed template parsing mode, for function template we consume the
  862. // tokens and store them for late parsing at the end of the translation unit.
  863. if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
  864. TemplateInfo.Kind == ParsedTemplateInfo::Template &&
  865. Actions.canDelayFunctionBody(D)) {
  866. MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
  867. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  868. Scope *ParentScope = getCurScope()->getParent();
  869. D.setFunctionDefinitionKind(FDK_Definition);
  870. Decl *DP = Actions.HandleDeclarator(ParentScope, D,
  871. TemplateParameterLists);
  872. D.complete(DP);
  873. D.getMutableDeclSpec().abort();
  874. CachedTokens Toks;
  875. LexTemplateFunctionForLateParsing(Toks);
  876. if (DP) {
  877. FunctionDecl *FnD = DP->getAsFunction();
  878. Actions.CheckForFunctionRedefinition(FnD);
  879. Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
  880. }
  881. return DP;
  882. }
  883. else if (CurParsedObjCImpl &&
  884. !TemplateInfo.TemplateParams &&
  885. (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
  886. Tok.is(tok::colon)) &&
  887. Actions.CurContext->isTranslationUnit()) {
  888. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  889. Scope *ParentScope = getCurScope()->getParent();
  890. D.setFunctionDefinitionKind(FDK_Definition);
  891. Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
  892. MultiTemplateParamsArg());
  893. D.complete(FuncDecl);
  894. D.getMutableDeclSpec().abort();
  895. if (FuncDecl) {
  896. // Consume the tokens and store them for later parsing.
  897. StashAwayMethodOrFunctionBodyTokens(FuncDecl);
  898. CurParsedObjCImpl->HasCFunction = true;
  899. return FuncDecl;
  900. }
  901. // FIXME: Should we really fall through here?
  902. }
  903. // Enter a scope for the function body.
  904. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  905. // Tell the actions module that we have entered a function definition with the
  906. // specified Declarator for the function.
  907. Decl *Res = TemplateInfo.TemplateParams?
  908. Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
  909. *TemplateInfo.TemplateParams, D)
  910. : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
  911. // Break out of the ParsingDeclarator context before we parse the body.
  912. D.complete(Res);
  913. // Break out of the ParsingDeclSpec context, too. This const_cast is
  914. // safe because we're always the sole owner.
  915. D.getMutableDeclSpec().abort();
  916. if (TryConsumeToken(tok::equal)) {
  917. assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
  918. bool Delete = false;
  919. SourceLocation KWLoc;
  920. if (TryConsumeToken(tok::kw_delete, KWLoc)) {
  921. Diag(KWLoc, getLangOpts().CPlusPlus11
  922. ? diag::warn_cxx98_compat_deleted_function
  923. : diag::ext_deleted_function);
  924. Actions.SetDeclDeleted(Res, KWLoc);
  925. Delete = true;
  926. } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
  927. Diag(KWLoc, getLangOpts().CPlusPlus11
  928. ? diag::warn_cxx98_compat_defaulted_function
  929. : diag::ext_defaulted_function);
  930. Actions.SetDeclDefaulted(Res, KWLoc);
  931. } else {
  932. llvm_unreachable("function definition after = not 'delete' or 'default'");
  933. }
  934. if (Tok.is(tok::comma)) {
  935. Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
  936. << Delete;
  937. SkipUntil(tok::semi);
  938. } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  939. Delete ? "delete" : "default")) {
  940. SkipUntil(tok::semi);
  941. }
  942. Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
  943. Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
  944. return Res;
  945. }
  946. if (Tok.is(tok::kw_try))
  947. return ParseFunctionTryBlock(Res, BodyScope);
  948. // If we have a colon, then we're probably parsing a C++
  949. // ctor-initializer.
  950. if (Tok.is(tok::colon)) {
  951. ParseConstructorInitializer(Res);
  952. // Recover from error.
  953. if (!Tok.is(tok::l_brace)) {
  954. BodyScope.Exit();
  955. Actions.ActOnFinishFunctionBody(Res, nullptr);
  956. return Res;
  957. }
  958. } else
  959. Actions.ActOnDefaultCtorInitializers(Res);
  960. // Late attributes are parsed in the same scope as the function body.
  961. if (LateParsedAttrs)
  962. ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
  963. return ParseFunctionStatementBody(Res, BodyScope);
  964. }
  965. /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
  966. /// types for a function with a K&R-style identifier list for arguments.
  967. void Parser::ParseKNRParamDeclarations(Declarator &D) {
  968. // We know that the top-level of this declarator is a function.
  969. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  970. // Enter function-declaration scope, limiting any declarators to the
  971. // function prototype scope, including parameter declarators.
  972. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
  973. Scope::FunctionDeclarationScope | Scope::DeclScope);
  974. // Read all the argument declarations.
  975. while (isDeclarationSpecifier()) {
  976. SourceLocation DSStart = Tok.getLocation();
  977. // Parse the common declaration-specifiers piece.
  978. DeclSpec DS(AttrFactory);
  979. ParseDeclarationSpecifiers(DS);
  980. // C99 6.9.1p6: 'each declaration in the declaration list shall have at
  981. // least one declarator'.
  982. // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
  983. // the declarations though. It's trivial to ignore them, really hard to do
  984. // anything else with them.
  985. if (TryConsumeToken(tok::semi)) {
  986. Diag(DSStart, diag::err_declaration_does_not_declare_param);
  987. continue;
  988. }
  989. // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
  990. // than register.
  991. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  992. DS.getStorageClassSpec() != DeclSpec::SCS_register) {
  993. Diag(DS.getStorageClassSpecLoc(),
  994. diag::err_invalid_storage_class_in_func_decl);
  995. DS.ClearStorageClassSpecs();
  996. }
  997. if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
  998. Diag(DS.getThreadStorageClassSpecLoc(),
  999. diag::err_invalid_storage_class_in_func_decl);
  1000. DS.ClearStorageClassSpecs();
  1001. }
  1002. // Parse the first declarator attached to this declspec.
  1003. Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
  1004. ParseDeclarator(ParmDeclarator);
  1005. // Handle the full declarator list.
  1006. while (1) {
  1007. // If attributes are present, parse them.
  1008. MaybeParseGNUAttributes(ParmDeclarator);
  1009. // Ask the actions module to compute the type for this declarator.
  1010. Decl *Param =
  1011. Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
  1012. if (Param &&
  1013. // A missing identifier has already been diagnosed.
  1014. ParmDeclarator.getIdentifier()) {
  1015. // Scan the argument list looking for the correct param to apply this
  1016. // type.
  1017. for (unsigned i = 0; ; ++i) {
  1018. // C99 6.9.1p6: those declarators shall declare only identifiers from
  1019. // the identifier list.
  1020. if (i == FTI.NumParams) {
  1021. Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
  1022. << ParmDeclarator.getIdentifier();
  1023. break;
  1024. }
  1025. if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
  1026. // Reject redefinitions of parameters.
  1027. if (FTI.Params[i].Param) {
  1028. Diag(ParmDeclarator.getIdentifierLoc(),
  1029. diag::err_param_redefinition)
  1030. << ParmDeclarator.getIdentifier();
  1031. } else {
  1032. FTI.Params[i].Param = Param;
  1033. }
  1034. break;
  1035. }
  1036. }
  1037. }
  1038. // If we don't have a comma, it is either the end of the list (a ';') or
  1039. // an error, bail out.
  1040. if (Tok.isNot(tok::comma))
  1041. break;
  1042. ParmDeclarator.clear();
  1043. // Consume the comma.
  1044. ParmDeclarator.setCommaLoc(ConsumeToken());
  1045. // Parse the next declarator.
  1046. ParseDeclarator(ParmDeclarator);
  1047. }
  1048. // Consume ';' and continue parsing.
  1049. if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
  1050. continue;
  1051. // Otherwise recover by skipping to next semi or mandatory function body.
  1052. if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
  1053. break;
  1054. TryConsumeToken(tok::semi);
  1055. }
  1056. // The actions module must verify that all arguments were declared.
  1057. Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
  1058. }
  1059. /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
  1060. /// allowed to be a wide string, and is not subject to character translation.
  1061. ///
  1062. /// [GNU] asm-string-literal:
  1063. /// string-literal
  1064. ///
  1065. ExprResult Parser::ParseAsmStringLiteral() {
  1066. if (!isTokenStringLiteral()) {
  1067. Diag(Tok, diag::err_expected_string_literal)
  1068. << /*Source='in...'*/0 << "'asm'";
  1069. return ExprError();
  1070. }
  1071. ExprResult AsmString(ParseStringLiteralExpression());
  1072. if (!AsmString.isInvalid()) {
  1073. const auto *SL = cast<StringLiteral>(AsmString.get());
  1074. if (!SL->isAscii()) {
  1075. Diag(Tok, diag::err_asm_operand_wide_string_literal)
  1076. << SL->isWide()
  1077. << SL->getSourceRange();
  1078. return ExprError();
  1079. }
  1080. }
  1081. return AsmString;
  1082. }
  1083. /// ParseSimpleAsm
  1084. ///
  1085. /// [GNU] simple-asm-expr:
  1086. /// 'asm' '(' asm-string-literal ')'
  1087. ///
  1088. ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
  1089. assert(Tok.is(tok::kw_asm) && "Not an asm!");
  1090. SourceLocation Loc = ConsumeToken();
  1091. if (Tok.is(tok::kw_volatile)) {
  1092. // Remove from the end of 'asm' to the end of 'volatile'.
  1093. SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
  1094. PP.getLocForEndOfToken(Tok.getLocation()));
  1095. Diag(Tok, diag::warn_file_asm_volatile)
  1096. << FixItHint::CreateRemoval(RemovalRange);
  1097. ConsumeToken();
  1098. }
  1099. BalancedDelimiterTracker T(*this, tok::l_paren);
  1100. if (T.consumeOpen()) {
  1101. Diag(Tok, diag::err_expected_lparen_after) << "asm";
  1102. return ExprError();
  1103. }
  1104. ExprResult Result(ParseAsmStringLiteral());
  1105. if (!Result.isInvalid()) {
  1106. // Close the paren and get the location of the end bracket
  1107. T.consumeClose();
  1108. if (EndLoc)
  1109. *EndLoc = T.getCloseLocation();
  1110. } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
  1111. if (EndLoc)
  1112. *EndLoc = Tok.getLocation();
  1113. ConsumeParen();
  1114. }
  1115. return Result;
  1116. }
  1117. /// \brief Get the TemplateIdAnnotation from the token and put it in the
  1118. /// cleanup pool so that it gets destroyed when parsing the current top level
  1119. /// declaration is finished.
  1120. TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
  1121. assert(tok.is(tok::annot_template_id) && "Expected template-id token");
  1122. TemplateIdAnnotation *
  1123. Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
  1124. return Id;
  1125. }
  1126. void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
  1127. // Push the current token back into the token stream (or revert it if it is
  1128. // cached) and use an annotation scope token for current token.
  1129. if (PP.isBacktrackEnabled())
  1130. PP.RevertCachedTokens(1);
  1131. else
  1132. PP.EnterToken(Tok);
  1133. Tok.setKind(tok::annot_cxxscope);
  1134. Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
  1135. Tok.setAnnotationRange(SS.getRange());
  1136. // In case the tokens were cached, have Preprocessor replace them
  1137. // with the annotation token. We don't need to do this if we've
  1138. // just reverted back to a prior state.
  1139. if (IsNewAnnotation)
  1140. PP.AnnotateCachedTokens(Tok);
  1141. }
  1142. /// \brief Attempt to classify the name at the current token position. This may
  1143. /// form a type, scope or primary expression annotation, or replace the token
  1144. /// with a typo-corrected keyword. This is only appropriate when the current
  1145. /// name must refer to an entity which has already been declared.
  1146. ///
  1147. /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
  1148. /// and might possibly have a dependent nested name specifier.
  1149. /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
  1150. /// no typo correction will be performed.
  1151. Parser::AnnotatedNameKind
  1152. Parser::TryAnnotateName(bool IsAddressOfOperand,
  1153. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  1154. assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
  1155. const bool EnteringContext = false;
  1156. const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
  1157. CXXScopeSpec SS;
  1158. if (getLangOpts().CPlusPlus &&
  1159. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  1160. return ANK_Error;
  1161. if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
  1162. if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
  1163. !WasScopeAnnotation))
  1164. return ANK_Error;
  1165. return ANK_Unresolved;
  1166. }
  1167. IdentifierInfo *Name = Tok.getIdentifierInfo();
  1168. SourceLocation NameLoc = Tok.getLocation();
  1169. // FIXME: Move the tentative declaration logic into ClassifyName so we can
  1170. // typo-correct to tentatively-declared identifiers.
  1171. if (isTentativelyDeclared(Name)) {
  1172. // Identifier has been tentatively declared, and thus cannot be resolved as
  1173. // an expression. Fall back to annotating it as a type.
  1174. if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
  1175. !WasScopeAnnotation))
  1176. return ANK_Error;
  1177. return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
  1178. }
  1179. Token Next = NextToken();
  1180. // Look up and classify the identifier. We don't perform any typo-correction
  1181. // after a scope specifier, because in general we can't recover from typos
  1182. // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to
  1183. // jump back into scope specifier parsing).
  1184. Sema::NameClassification Classification = Actions.ClassifyName(
  1185. getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
  1186. SS.isEmpty() ? std::move(CCC) : nullptr);
  1187. switch (Classification.getKind()) {
  1188. case Sema::NC_Error:
  1189. return ANK_Error;
  1190. case Sema::NC_Keyword:
  1191. // The identifier was typo-corrected to a keyword.
  1192. Tok.setIdentifierInfo(Name);
  1193. Tok.setKind(Name->getTokenID());
  1194. PP.TypoCorrectToken(Tok);
  1195. if (SS.isNotEmpty())
  1196. AnnotateScopeToken(SS, !WasScopeAnnotation);
  1197. // We've "annotated" this as a keyword.
  1198. return ANK_Success;
  1199. case Sema::NC_Unknown:
  1200. // It's not something we know about. Leave it unannotated.
  1201. break;
  1202. case Sema::NC_Type:
  1203. Tok.setKind(tok::annot_typename);
  1204. setTypeAnnotation(Tok, Classification.getType());
  1205. Tok.setAnnotationEndLoc(NameLoc);
  1206. if (SS.isNotEmpty())
  1207. Tok.setLocation(SS.getBeginLoc());
  1208. PP.AnnotateCachedTokens(Tok);
  1209. return ANK_Success;
  1210. case Sema::NC_Expression:
  1211. Tok.setKind(tok::annot_primary_expr);
  1212. setExprAnnotation(Tok, Classification.getExpression());
  1213. Tok.setAnnotationEndLoc(NameLoc);
  1214. if (SS.isNotEmpty())
  1215. Tok.setLocation(SS.getBeginLoc());
  1216. PP.AnnotateCachedTokens(Tok);
  1217. return ANK_Success;
  1218. case Sema::NC_TypeTemplate:
  1219. if (Next.isNot(tok::less)) {
  1220. // This may be a type template being used as a template template argument.
  1221. if (SS.isNotEmpty())
  1222. AnnotateScopeToken(SS, !WasScopeAnnotation);
  1223. return ANK_TemplateName;
  1224. }
  1225. // Fall through.
  1226. case Sema::NC_VarTemplate:
  1227. case Sema::NC_FunctionTemplate: {
  1228. // We have a type, variable or function template followed by '<'.
  1229. ConsumeToken();
  1230. UnqualifiedId Id;
  1231. Id.setIdentifier(Name, NameLoc);
  1232. if (AnnotateTemplateIdToken(
  1233. TemplateTy::make(Classification.getTemplateName()),
  1234. Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
  1235. return ANK_Error;
  1236. return ANK_Success;
  1237. }
  1238. case Sema::NC_NestedNameSpecifier:
  1239. llvm_unreachable("already parsed nested name specifier");
  1240. }
  1241. // Unable to classify the name, but maybe we can annotate a scope specifier.
  1242. if (SS.isNotEmpty())
  1243. AnnotateScopeToken(SS, !WasScopeAnnotation);
  1244. return ANK_Unresolved;
  1245. }
  1246. bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
  1247. assert(Tok.isNot(tok::identifier));
  1248. Diag(Tok, diag::ext_keyword_as_ident)
  1249. << PP.getSpelling(Tok)
  1250. << DisableKeyword;
  1251. if (DisableKeyword)
  1252. Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
  1253. Tok.setKind(tok::identifier);
  1254. return true;
  1255. }
  1256. /// TryAnnotateTypeOrScopeToken - If the current token position is on a
  1257. /// typename (possibly qualified in C++) or a C++ scope specifier not followed
  1258. /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
  1259. /// with a single annotation token representing the typename or C++ scope
  1260. /// respectively.
  1261. /// This simplifies handling of C++ scope specifiers and allows efficient
  1262. /// backtracking without the need to re-parse and resolve nested-names and
  1263. /// typenames.
  1264. /// It will mainly be called when we expect to treat identifiers as typenames
  1265. /// (if they are typenames). For example, in C we do not expect identifiers
  1266. /// inside expressions to be treated as typenames so it will not be called
  1267. /// for expressions in C.
  1268. /// The benefit for C/ObjC is that a typename will be annotated and
  1269. /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
  1270. /// will not be called twice, once to check whether we have a declaration
  1271. /// specifier, and another one to get the actual type inside
  1272. /// ParseDeclarationSpecifiers).
  1273. ///
  1274. /// This returns true if an error occurred.
  1275. ///
  1276. /// Note that this routine emits an error if you call it with ::new or ::delete
  1277. /// as the current tokens, so only call it in contexts where these are invalid.
  1278. bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
  1279. assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
  1280. Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
  1281. Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
  1282. Tok.is(tok::kw___super)) &&
  1283. "Cannot be a type or scope token!");
  1284. if (Tok.is(tok::kw_typename)) {
  1285. // MSVC lets you do stuff like:
  1286. // typename typedef T_::D D;
  1287. //
  1288. // We will consume the typedef token here and put it back after we have
  1289. // parsed the first identifier, transforming it into something more like:
  1290. // typename T_::D typedef D;
  1291. if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
  1292. Token TypedefToken;
  1293. PP.Lex(TypedefToken);
  1294. bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType);
  1295. PP.EnterToken(Tok);
  1296. Tok = TypedefToken;
  1297. if (!Result)
  1298. Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
  1299. return Result;
  1300. }
  1301. // Parse a C++ typename-specifier, e.g., "typename T::type".
  1302. //
  1303. // typename-specifier:
  1304. // 'typename' '::' [opt] nested-name-specifier identifier
  1305. // 'typename' '::' [opt] nested-name-specifier template [opt]
  1306. // simple-template-id
  1307. SourceLocation TypenameLoc = ConsumeToken();
  1308. CXXScopeSpec SS;
  1309. if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
  1310. /*EnteringContext=*/false,
  1311. nullptr, /*IsTypename*/ true))
  1312. return true;
  1313. if (!SS.isSet()) {
  1314. if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
  1315. Tok.is(tok::annot_decltype)) {
  1316. // Attempt to recover by skipping the invalid 'typename'
  1317. if (Tok.is(tok::annot_decltype) ||
  1318. (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
  1319. Tok.isAnnotation())) {
  1320. unsigned DiagID = diag::err_expected_qualified_after_typename;
  1321. // MS compatibility: MSVC permits using known types with typename.
  1322. // e.g. "typedef typename T* pointer_type"
  1323. if (getLangOpts().MicrosoftExt)
  1324. DiagID = diag::warn_expected_qualified_after_typename;
  1325. Diag(Tok.getLocation(), DiagID);
  1326. return false;
  1327. }
  1328. }
  1329. Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
  1330. return true;
  1331. }
  1332. TypeResult Ty;
  1333. if (Tok.is(tok::identifier)) {
  1334. // FIXME: check whether the next token is '<', first!
  1335. Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
  1336. *Tok.getIdentifierInfo(),
  1337. Tok.getLocation());
  1338. } else if (Tok.is(tok::annot_template_id)) {
  1339. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1340. if (TemplateId->Kind != TNK_Type_template &&
  1341. TemplateId->Kind != TNK_Dependent_template_name) {
  1342. Diag(Tok, diag::err_typename_refers_to_non_type_template)
  1343. << Tok.getAnnotationRange();
  1344. return true;
  1345. }
  1346. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  1347. TemplateId->NumArgs);
  1348. Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
  1349. TemplateId->TemplateKWLoc,
  1350. TemplateId->Template,
  1351. TemplateId->TemplateNameLoc,
  1352. TemplateId->LAngleLoc,
  1353. TemplateArgsPtr,
  1354. TemplateId->RAngleLoc);
  1355. } else {
  1356. Diag(Tok, diag::err_expected_type_name_after_typename)
  1357. << SS.getRange();
  1358. return true;
  1359. }
  1360. SourceLocation EndLoc = Tok.getLastLoc();
  1361. Tok.setKind(tok::annot_typename);
  1362. setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
  1363. Tok.setAnnotationEndLoc(EndLoc);
  1364. Tok.setLocation(TypenameLoc);
  1365. PP.AnnotateCachedTokens(Tok);
  1366. return false;
  1367. }
  1368. // Remembers whether the token was originally a scope annotation.
  1369. bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
  1370. CXXScopeSpec SS;
  1371. if (getLangOpts().CPlusPlus)
  1372. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  1373. return true;
  1374. return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
  1375. SS, !WasScopeAnnotation);
  1376. }
  1377. /// \brief Try to annotate a type or scope token, having already parsed an
  1378. /// optional scope specifier. \p IsNewScope should be \c true unless the scope
  1379. /// specifier was extracted from an existing tok::annot_cxxscope annotation.
  1380. bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
  1381. bool NeedType,
  1382. CXXScopeSpec &SS,
  1383. bool IsNewScope) {
  1384. if (Tok.is(tok::identifier)) {
  1385. IdentifierInfo *CorrectedII = nullptr;
  1386. // Determine whether the identifier is a type name.
  1387. if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
  1388. Tok.getLocation(), getCurScope(),
  1389. &SS, false,
  1390. NextToken().is(tok::period),
  1391. ParsedType(),
  1392. /*IsCtorOrDtorName=*/false,
  1393. /*NonTrivialTypeSourceInfo*/ true,
  1394. NeedType ? &CorrectedII
  1395. : nullptr)) {
  1396. // A FixIt was applied as a result of typo correction
  1397. if (CorrectedII)
  1398. Tok.setIdentifierInfo(CorrectedII);
  1399. // This is a typename. Replace the current token in-place with an
  1400. // annotation type token.
  1401. Tok.setKind(tok::annot_typename);
  1402. setTypeAnnotation(Tok, Ty);
  1403. Tok.setAnnotationEndLoc(Tok.getLocation());
  1404. if (SS.isNotEmpty()) // it was a C++ qualified type name.
  1405. Tok.setLocation(SS.getBeginLoc());
  1406. // In case the tokens were cached, have Preprocessor replace
  1407. // them with the annotation token.
  1408. PP.AnnotateCachedTokens(Tok);
  1409. return false;
  1410. }
  1411. if (!getLangOpts().CPlusPlus) {
  1412. // If we're in C, we can't have :: tokens at all (the lexer won't return
  1413. // them). If the identifier is not a type, then it can't be scope either,
  1414. // just early exit.
  1415. return false;
  1416. }
  1417. // If this is a template-id, annotate with a template-id or type token.
  1418. if (NextToken().is(tok::less)) {
  1419. TemplateTy Template;
  1420. UnqualifiedId TemplateName;
  1421. TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1422. bool MemberOfUnknownSpecialization;
  1423. if (TemplateNameKind TNK
  1424. = Actions.isTemplateName(getCurScope(), SS,
  1425. /*hasTemplateKeyword=*/false, TemplateName,
  1426. /*ObjectType=*/ ParsedType(),
  1427. EnteringContext,
  1428. Template, MemberOfUnknownSpecialization)) {
  1429. // Consume the identifier.
  1430. ConsumeToken();
  1431. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  1432. TemplateName)) {
  1433. // If an unrecoverable error occurred, we need to return true here,
  1434. // because the token stream is in a damaged state. We may not return
  1435. // a valid identifier.
  1436. return true;
  1437. }
  1438. }
  1439. }
  1440. // The current token, which is either an identifier or a
  1441. // template-id, is not part of the annotation. Fall through to
  1442. // push that token back into the stream and complete the C++ scope
  1443. // specifier annotation.
  1444. }
  1445. if (Tok.is(tok::annot_template_id)) {
  1446. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1447. if (TemplateId->Kind == TNK_Type_template) {
  1448. // A template-id that refers to a type was parsed into a
  1449. // template-id annotation in a context where we weren't allowed
  1450. // to produce a type annotation token. Update the template-id
  1451. // annotation token to a type annotation token now.
  1452. AnnotateTemplateIdTokenAsType();
  1453. return false;
  1454. }
  1455. }
  1456. if (SS.isEmpty())
  1457. return false;
  1458. // A C++ scope specifier that isn't followed by a typename.
  1459. AnnotateScopeToken(SS, IsNewScope);
  1460. return false;
  1461. }
  1462. /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
  1463. /// annotates C++ scope specifiers and template-ids. This returns
  1464. /// true if there was an error that could not be recovered from.
  1465. ///
  1466. /// Note that this routine emits an error if you call it with ::new or ::delete
  1467. /// as the current tokens, so only call it in contexts where these are invalid.
  1468. bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
  1469. assert(getLangOpts().CPlusPlus &&
  1470. "Call sites of this function should be guarded by checking for C++");
  1471. assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
  1472. (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
  1473. Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
  1474. "Cannot be a type or scope token!");
  1475. CXXScopeSpec SS;
  1476. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  1477. return true;
  1478. if (SS.isEmpty())
  1479. return false;
  1480. AnnotateScopeToken(SS, true);
  1481. return false;
  1482. }
  1483. bool Parser::isTokenEqualOrEqualTypo() {
  1484. tok::TokenKind Kind = Tok.getKind();
  1485. switch (Kind) {
  1486. default:
  1487. return false;
  1488. case tok::ampequal: // &=
  1489. case tok::starequal: // *=
  1490. case tok::plusequal: // +=
  1491. case tok::minusequal: // -=
  1492. case tok::exclaimequal: // !=
  1493. case tok::slashequal: // /=
  1494. case tok::percentequal: // %=
  1495. case tok::lessequal: // <=
  1496. case tok::lesslessequal: // <<=
  1497. case tok::greaterequal: // >=
  1498. case tok::greatergreaterequal: // >>=
  1499. case tok::caretequal: // ^=
  1500. case tok::pipeequal: // |=
  1501. case tok::equalequal: // ==
  1502. Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
  1503. << Kind
  1504. << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
  1505. case tok::equal:
  1506. return true;
  1507. }
  1508. }
  1509. SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
  1510. assert(Tok.is(tok::code_completion));
  1511. PrevTokLocation = Tok.getLocation();
  1512. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1513. if (S->getFlags() & Scope::FnScope) {
  1514. Actions.CodeCompleteOrdinaryName(getCurScope(),
  1515. Sema::PCC_RecoveryInFunction);
  1516. cutOffParsing();
  1517. return PrevTokLocation;
  1518. }
  1519. if (S->getFlags() & Scope::ClassScope) {
  1520. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
  1521. cutOffParsing();
  1522. return PrevTokLocation;
  1523. }
  1524. }
  1525. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
  1526. cutOffParsing();
  1527. return PrevTokLocation;
  1528. }
  1529. // Code-completion pass-through functions
  1530. void Parser::CodeCompleteDirective(bool InConditional) {
  1531. Actions.CodeCompletePreprocessorDirective(InConditional);
  1532. }
  1533. void Parser::CodeCompleteInConditionalExclusion() {
  1534. Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
  1535. }
  1536. void Parser::CodeCompleteMacroName(bool IsDefinition) {
  1537. Actions.CodeCompletePreprocessorMacroName(IsDefinition);
  1538. }
  1539. void Parser::CodeCompletePreprocessorExpression() {
  1540. Actions.CodeCompletePreprocessorExpression();
  1541. }
  1542. void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
  1543. MacroInfo *MacroInfo,
  1544. unsigned ArgumentIndex) {
  1545. Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
  1546. ArgumentIndex);
  1547. }
  1548. void Parser::CodeCompleteNaturalLanguage() {
  1549. Actions.CodeCompleteNaturalLanguage();
  1550. }
  1551. bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
  1552. assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
  1553. "Expected '__if_exists' or '__if_not_exists'");
  1554. Result.IsIfExists = Tok.is(tok::kw___if_exists);
  1555. Result.KeywordLoc = ConsumeToken();
  1556. BalancedDelimiterTracker T(*this, tok::l_paren);
  1557. if (T.consumeOpen()) {
  1558. Diag(Tok, diag::err_expected_lparen_after)
  1559. << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
  1560. return true;
  1561. }
  1562. // Parse nested-name-specifier.
  1563. if (getLangOpts().CPlusPlus)
  1564. ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
  1565. /*EnteringContext=*/false);
  1566. // Check nested-name specifier.
  1567. if (Result.SS.isInvalid()) {
  1568. T.skipToEnd();
  1569. return true;
  1570. }
  1571. // Parse the unqualified-id.
  1572. SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
  1573. if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
  1574. TemplateKWLoc, Result.Name)) {
  1575. T.skipToEnd();
  1576. return true;
  1577. }
  1578. if (T.consumeClose())
  1579. return true;
  1580. // Check if the symbol exists.
  1581. switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
  1582. Result.IsIfExists, Result.SS,
  1583. Result.Name)) {
  1584. case Sema::IER_Exists:
  1585. Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1586. break;
  1587. case Sema::IER_DoesNotExist:
  1588. Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1589. break;
  1590. case Sema::IER_Dependent:
  1591. Result.Behavior = IEB_Dependent;
  1592. break;
  1593. case Sema::IER_Error:
  1594. return true;
  1595. }
  1596. return false;
  1597. }
  1598. void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
  1599. IfExistsCondition Result;
  1600. if (ParseMicrosoftIfExistsCondition(Result))
  1601. return;
  1602. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  1603. if (Braces.consumeOpen()) {
  1604. Diag(Tok, diag::err_expected) << tok::l_brace;
  1605. return;
  1606. }
  1607. switch (Result.Behavior) {
  1608. case IEB_Parse:
  1609. // Parse declarations below.
  1610. break;
  1611. case IEB_Dependent:
  1612. llvm_unreachable("Cannot have a dependent external declaration");
  1613. case IEB_Skip:
  1614. Braces.skipToEnd();
  1615. return;
  1616. }
  1617. // Parse the declarations.
  1618. // FIXME: Support module import within __if_exists?
  1619. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  1620. ParsedAttributesWithRange attrs(AttrFactory);
  1621. MaybeParseCXX11Attributes(attrs);
  1622. MaybeParseMicrosoftAttributes(attrs);
  1623. DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
  1624. if (Result && !getCurScope()->getParent())
  1625. Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
  1626. }
  1627. Braces.consumeClose();
  1628. }
  1629. Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
  1630. assert(Tok.isObjCAtKeyword(tok::objc_import) &&
  1631. "Improper start to module import");
  1632. SourceLocation ImportLoc = ConsumeToken();
  1633. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1634. // Parse the module path.
  1635. do {
  1636. if (!Tok.is(tok::identifier)) {
  1637. if (Tok.is(tok::code_completion)) {
  1638. Actions.CodeCompleteModuleImport(ImportLoc, Path);
  1639. cutOffParsing();
  1640. return DeclGroupPtrTy();
  1641. }
  1642. Diag(Tok, diag::err_module_expected_ident);
  1643. SkipUntil(tok::semi);
  1644. return DeclGroupPtrTy();
  1645. }
  1646. // Record this part of the module path.
  1647. Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
  1648. ConsumeToken();
  1649. if (Tok.is(tok::period)) {
  1650. ConsumeToken();
  1651. continue;
  1652. }
  1653. break;
  1654. } while (true);
  1655. if (PP.hadModuleLoaderFatalFailure()) {
  1656. // With a fatal failure in the module loader, we abort parsing.
  1657. cutOffParsing();
  1658. return DeclGroupPtrTy();
  1659. }
  1660. DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
  1661. ExpectAndConsumeSemi(diag::err_module_expected_semi);
  1662. if (Import.isInvalid())
  1663. return DeclGroupPtrTy();
  1664. return Actions.ConvertDeclToDeclGroup(Import.get());
  1665. }
  1666. bool BalancedDelimiterTracker::diagnoseOverflow() {
  1667. P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
  1668. << P.getLangOpts().BracketDepth;
  1669. P.Diag(P.Tok, diag::note_bracket_depth);
  1670. P.cutOffParsing();
  1671. return true;
  1672. }
  1673. bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
  1674. const char *Msg,
  1675. tok::TokenKind SkipToTok) {
  1676. LOpen = P.Tok.getLocation();
  1677. if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
  1678. if (SkipToTok != tok::unknown)
  1679. P.SkipUntil(SkipToTok, Parser::StopAtSemi);
  1680. return true;
  1681. }
  1682. if (getDepth() < MaxDepth)
  1683. return false;
  1684. return diagnoseOverflow();
  1685. }
  1686. bool BalancedDelimiterTracker::diagnoseMissingClose() {
  1687. assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
  1688. P.Diag(P.Tok, diag::err_expected) << Close;
  1689. P.Diag(LOpen, diag::note_matching) << Kind;
  1690. // If we're not already at some kind of closing bracket, skip to our closing
  1691. // token.
  1692. if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
  1693. P.Tok.isNot(tok::r_square) &&
  1694. P.SkipUntil(Close, FinalToken,
  1695. Parser::StopAtSemi | Parser::StopBeforeMatch) &&
  1696. P.Tok.is(Close))
  1697. LClose = P.ConsumeAnyToken();
  1698. return true;
  1699. }
  1700. void BalancedDelimiterTracker::skipToEnd() {
  1701. P.SkipUntil(Close, Parser::StopBeforeMatch);
  1702. consumeClose();
  1703. }