Parser.cpp 79 KB

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