Parser.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  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. }
  448. void Parser::LateTemplateParserCleanupCallback(void *P) {
  449. // While this RAII helper doesn't bracket any actual work, the destructor will
  450. // clean up annotations that were created during ActOnEndOfTranslationUnit
  451. // when incremental processing is enabled.
  452. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
  453. }
  454. bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result) {
  455. Actions.ActOnStartOfTranslationUnit();
  456. // C11 6.9p1 says translation units must have at least one top-level
  457. // declaration. C++ doesn't have this restriction. We also don't want to
  458. // complain if we have a precompiled header, although technically if the PCH
  459. // is empty we should still emit the (pedantic) diagnostic.
  460. bool NoTopLevelDecls = ParseTopLevelDecl(Result);
  461. if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
  462. !getLangOpts().CPlusPlus)
  463. Diag(diag::ext_empty_translation_unit);
  464. return NoTopLevelDecls;
  465. }
  466. /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
  467. /// action tells us to. This returns true if the EOF was encountered.
  468. bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
  469. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
  470. // Skip over the EOF token, flagging end of previous input for incremental
  471. // processing
  472. if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
  473. ConsumeToken();
  474. Result = nullptr;
  475. switch (Tok.getKind()) {
  476. case tok::annot_pragma_unused:
  477. HandlePragmaUnused();
  478. return false;
  479. case tok::kw_export:
  480. if (NextToken().isNot(tok::kw_module))
  481. break;
  482. LLVM_FALLTHROUGH;
  483. case tok::kw_module:
  484. Result = ParseModuleDecl();
  485. return false;
  486. case tok::annot_module_include:
  487. Actions.ActOnModuleInclude(Tok.getLocation(),
  488. reinterpret_cast<Module *>(
  489. Tok.getAnnotationValue()));
  490. ConsumeAnnotationToken();
  491. return false;
  492. case tok::annot_module_begin:
  493. Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
  494. Tok.getAnnotationValue()));
  495. ConsumeAnnotationToken();
  496. return false;
  497. case tok::annot_module_end:
  498. Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
  499. Tok.getAnnotationValue()));
  500. ConsumeAnnotationToken();
  501. return false;
  502. case tok::annot_pragma_attribute:
  503. HandlePragmaAttribute();
  504. return false;
  505. case tok::eof:
  506. // Late template parsing can begin.
  507. if (getLangOpts().DelayedTemplateParsing)
  508. Actions.SetLateTemplateParser(LateTemplateParserCallback,
  509. PP.isIncrementalProcessingEnabled() ?
  510. LateTemplateParserCleanupCallback : nullptr,
  511. this);
  512. if (!PP.isIncrementalProcessingEnabled())
  513. Actions.ActOnEndOfTranslationUnit();
  514. //else don't tell Sema that we ended parsing: more input might come.
  515. return true;
  516. default:
  517. break;
  518. }
  519. ParsedAttributesWithRange attrs(AttrFactory);
  520. MaybeParseCXX11Attributes(attrs);
  521. Result = ParseExternalDeclaration(attrs);
  522. return false;
  523. }
  524. /// ParseExternalDeclaration:
  525. ///
  526. /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
  527. /// function-definition
  528. /// declaration
  529. /// [GNU] asm-definition
  530. /// [GNU] __extension__ external-declaration
  531. /// [OBJC] objc-class-definition
  532. /// [OBJC] objc-class-declaration
  533. /// [OBJC] objc-alias-declaration
  534. /// [OBJC] objc-protocol-definition
  535. /// [OBJC] objc-method-definition
  536. /// [OBJC] @end
  537. /// [C++] linkage-specification
  538. /// [GNU] asm-definition:
  539. /// simple-asm-expr ';'
  540. /// [C++11] empty-declaration
  541. /// [C++11] attribute-declaration
  542. ///
  543. /// [C++11] empty-declaration:
  544. /// ';'
  545. ///
  546. /// [C++0x/GNU] 'extern' 'template' declaration
  547. ///
  548. /// [Modules-TS] module-import-declaration
  549. ///
  550. Parser::DeclGroupPtrTy
  551. Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
  552. ParsingDeclSpec *DS) {
  553. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
  554. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  555. if (PP.isCodeCompletionReached()) {
  556. cutOffParsing();
  557. return nullptr;
  558. }
  559. Decl *SingleDecl = nullptr;
  560. switch (Tok.getKind()) {
  561. case tok::annot_pragma_vis:
  562. HandlePragmaVisibility();
  563. return nullptr;
  564. case tok::annot_pragma_pack:
  565. HandlePragmaPack();
  566. return nullptr;
  567. case tok::annot_pragma_msstruct:
  568. HandlePragmaMSStruct();
  569. return nullptr;
  570. case tok::annot_pragma_align:
  571. HandlePragmaAlign();
  572. return nullptr;
  573. case tok::annot_pragma_weak:
  574. HandlePragmaWeak();
  575. return nullptr;
  576. case tok::annot_pragma_weakalias:
  577. HandlePragmaWeakAlias();
  578. return nullptr;
  579. case tok::annot_pragma_redefine_extname:
  580. HandlePragmaRedefineExtname();
  581. return nullptr;
  582. case tok::annot_pragma_fp_contract:
  583. HandlePragmaFPContract();
  584. return nullptr;
  585. case tok::annot_pragma_fp:
  586. HandlePragmaFP();
  587. break;
  588. case tok::annot_pragma_opencl_extension:
  589. HandlePragmaOpenCLExtension();
  590. return nullptr;
  591. case tok::annot_pragma_openmp: {
  592. AccessSpecifier AS = AS_none;
  593. return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
  594. }
  595. case tok::annot_pragma_ms_pointers_to_members:
  596. HandlePragmaMSPointersToMembers();
  597. return nullptr;
  598. case tok::annot_pragma_ms_vtordisp:
  599. HandlePragmaMSVtorDisp();
  600. return nullptr;
  601. case tok::annot_pragma_ms_pragma:
  602. HandlePragmaMSPragma();
  603. return nullptr;
  604. case tok::annot_pragma_dump:
  605. HandlePragmaDump();
  606. return nullptr;
  607. case tok::semi:
  608. // Either a C++11 empty-declaration or attribute-declaration.
  609. SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
  610. attrs.getList(),
  611. Tok.getLocation());
  612. ConsumeExtraSemi(OutsideFunction);
  613. break;
  614. case tok::r_brace:
  615. Diag(Tok, diag::err_extraneous_closing_brace);
  616. ConsumeBrace();
  617. return nullptr;
  618. case tok::eof:
  619. Diag(Tok, diag::err_expected_external_declaration);
  620. return nullptr;
  621. case tok::kw___extension__: {
  622. // __extension__ silences extension warnings in the subexpression.
  623. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  624. ConsumeToken();
  625. return ParseExternalDeclaration(attrs);
  626. }
  627. case tok::kw_asm: {
  628. ProhibitAttributes(attrs);
  629. SourceLocation StartLoc = Tok.getLocation();
  630. SourceLocation EndLoc;
  631. ExprResult Result(ParseSimpleAsm(&EndLoc));
  632. // Check if GNU-style InlineAsm is disabled.
  633. // Empty asm string is allowed because it will not introduce
  634. // any assembly code.
  635. if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
  636. const auto *SL = cast<StringLiteral>(Result.get());
  637. if (!SL->getString().trim().empty())
  638. Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
  639. }
  640. ExpectAndConsume(tok::semi, diag::err_expected_after,
  641. "top-level asm block");
  642. if (Result.isInvalid())
  643. return nullptr;
  644. SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
  645. break;
  646. }
  647. case tok::at:
  648. return ParseObjCAtDirectives(attrs);
  649. case tok::minus:
  650. case tok::plus:
  651. if (!getLangOpts().ObjC1) {
  652. Diag(Tok, diag::err_expected_external_declaration);
  653. ConsumeToken();
  654. return nullptr;
  655. }
  656. SingleDecl = ParseObjCMethodDefinition();
  657. break;
  658. case tok::code_completion:
  659. if (CurParsedObjCImpl) {
  660. // Code-complete Objective-C methods even without leading '-'/'+' prefix.
  661. Actions.CodeCompleteObjCMethodDecl(getCurScope(),
  662. /*IsInstanceMethod=*/None,
  663. /*ReturnType=*/nullptr);
  664. }
  665. Actions.CodeCompleteOrdinaryName(
  666. getCurScope(),
  667. CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
  668. cutOffParsing();
  669. return nullptr;
  670. case tok::kw_import:
  671. SingleDecl = ParseModuleImport(SourceLocation());
  672. break;
  673. case tok::kw_export:
  674. if (getLangOpts().ModulesTS) {
  675. SingleDecl = ParseExportDeclaration();
  676. break;
  677. }
  678. // This must be 'export template'. Parse it so we can diagnose our lack
  679. // of support.
  680. LLVM_FALLTHROUGH;
  681. case tok::kw_using:
  682. case tok::kw_namespace:
  683. case tok::kw_typedef:
  684. case tok::kw_template:
  685. case tok::kw_static_assert:
  686. case tok::kw__Static_assert:
  687. // A function definition cannot start with any of these keywords.
  688. {
  689. SourceLocation DeclEnd;
  690. return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
  691. }
  692. case tok::kw_static:
  693. // Parse (then ignore) 'static' prior to a template instantiation. This is
  694. // a GCC extension that we intentionally do not support.
  695. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
  696. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  697. << 0;
  698. SourceLocation DeclEnd;
  699. return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
  700. }
  701. goto dont_know;
  702. case tok::kw_inline:
  703. if (getLangOpts().CPlusPlus) {
  704. tok::TokenKind NextKind = NextToken().getKind();
  705. // Inline namespaces. Allowed as an extension even in C++03.
  706. if (NextKind == tok::kw_namespace) {
  707. SourceLocation DeclEnd;
  708. return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
  709. }
  710. // Parse (then ignore) 'inline' prior to a template instantiation. This is
  711. // a GCC extension that we intentionally do not support.
  712. if (NextKind == tok::kw_template) {
  713. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  714. << 1;
  715. SourceLocation DeclEnd;
  716. return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
  717. }
  718. }
  719. goto dont_know;
  720. case tok::kw_extern:
  721. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
  722. // Extern templates
  723. SourceLocation ExternLoc = ConsumeToken();
  724. SourceLocation TemplateLoc = ConsumeToken();
  725. Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
  726. diag::warn_cxx98_compat_extern_template :
  727. diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
  728. SourceLocation DeclEnd;
  729. return Actions.ConvertDeclToDeclGroup(
  730. ParseExplicitInstantiation(DeclaratorContext::FileContext,
  731. ExternLoc, TemplateLoc, DeclEnd));
  732. }
  733. goto dont_know;
  734. case tok::kw___if_exists:
  735. case tok::kw___if_not_exists:
  736. ParseMicrosoftIfExistsExternalDeclaration();
  737. return nullptr;
  738. case tok::kw_module:
  739. Diag(Tok, diag::err_unexpected_module_decl);
  740. SkipUntil(tok::semi);
  741. return nullptr;
  742. default:
  743. dont_know:
  744. if (Tok.isEditorPlaceholder()) {
  745. ConsumeToken();
  746. return nullptr;
  747. }
  748. // We can't tell whether this is a function-definition or declaration yet.
  749. return ParseDeclarationOrFunctionDefinition(attrs, DS);
  750. }
  751. // This routine returns a DeclGroup, if the thing we parsed only contains a
  752. // single decl, convert it now.
  753. return Actions.ConvertDeclToDeclGroup(SingleDecl);
  754. }
  755. /// \brief Determine whether the current token, if it occurs after a
  756. /// declarator, continues a declaration or declaration list.
  757. bool Parser::isDeclarationAfterDeclarator() {
  758. // Check for '= delete' or '= default'
  759. if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
  760. const Token &KW = NextToken();
  761. if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
  762. return false;
  763. }
  764. return Tok.is(tok::equal) || // int X()= -> not a function def
  765. Tok.is(tok::comma) || // int X(), -> not a function def
  766. Tok.is(tok::semi) || // int X(); -> not a function def
  767. Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
  768. Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
  769. (getLangOpts().CPlusPlus &&
  770. Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
  771. }
  772. /// \brief Determine whether the current token, if it occurs after a
  773. /// declarator, indicates the start of a function definition.
  774. bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
  775. assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
  776. if (Tok.is(tok::l_brace)) // int X() {}
  777. return true;
  778. // Handle K&R C argument lists: int X(f) int f; {}
  779. if (!getLangOpts().CPlusPlus &&
  780. Declarator.getFunctionTypeInfo().isKNRPrototype())
  781. return isDeclarationSpecifier();
  782. if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
  783. const Token &KW = NextToken();
  784. return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
  785. }
  786. return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
  787. Tok.is(tok::kw_try); // X() try { ... }
  788. }
  789. /// Parse either a function-definition or a declaration. We can't tell which
  790. /// we have until we read up to the compound-statement in function-definition.
  791. /// TemplateParams, if non-NULL, provides the template parameters when we're
  792. /// parsing a C++ template-declaration.
  793. ///
  794. /// function-definition: [C99 6.9.1]
  795. /// decl-specs declarator declaration-list[opt] compound-statement
  796. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  797. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  798. ///
  799. /// declaration: [C99 6.7]
  800. /// declaration-specifiers init-declarator-list[opt] ';'
  801. /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
  802. /// [OMP] threadprivate-directive [TODO]
  803. ///
  804. Parser::DeclGroupPtrTy
  805. Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
  806. ParsingDeclSpec &DS,
  807. AccessSpecifier AS) {
  808. MaybeParseMicrosoftAttributes(DS.getAttributes());
  809. // Parse the common declaration-specifiers piece.
  810. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
  811. DeclSpecContext::DSC_top_level);
  812. // If we had a free-standing type definition with a missing semicolon, we
  813. // may get this far before the problem becomes obvious.
  814. if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
  815. DS, AS, DeclSpecContext::DSC_top_level))
  816. return nullptr;
  817. // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
  818. // declaration-specifiers init-declarator-list[opt] ';'
  819. if (Tok.is(tok::semi)) {
  820. auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
  821. assert(DeclSpec::isDeclRep(TKind));
  822. switch(TKind) {
  823. case DeclSpec::TST_class:
  824. return 5;
  825. case DeclSpec::TST_struct:
  826. return 6;
  827. case DeclSpec::TST_union:
  828. return 5;
  829. case DeclSpec::TST_enum:
  830. return 4;
  831. case DeclSpec::TST_interface:
  832. return 9;
  833. default:
  834. llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
  835. }
  836. };
  837. // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
  838. SourceLocation CorrectLocationForAttributes =
  839. DeclSpec::isDeclRep(DS.getTypeSpecType())
  840. ? DS.getTypeSpecTypeLoc().getLocWithOffset(
  841. LengthOfTSTToken(DS.getTypeSpecType()))
  842. : SourceLocation();
  843. ProhibitAttributes(attrs, CorrectLocationForAttributes);
  844. ConsumeToken();
  845. RecordDecl *AnonRecord = nullptr;
  846. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
  847. DS, AnonRecord);
  848. DS.complete(TheDecl);
  849. if (getLangOpts().OpenCL)
  850. Actions.setCurrentOpenCLExtensionForDecl(TheDecl);
  851. if (AnonRecord) {
  852. Decl* decls[] = {AnonRecord, TheDecl};
  853. return Actions.BuildDeclaratorGroup(decls);
  854. }
  855. return Actions.ConvertDeclToDeclGroup(TheDecl);
  856. }
  857. DS.takeAttributesFrom(attrs);
  858. // ObjC2 allows prefix attributes on class interfaces and protocols.
  859. // FIXME: This still needs better diagnostics. We should only accept
  860. // attributes here, no types, etc.
  861. if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
  862. SourceLocation AtLoc = ConsumeToken(); // the "@"
  863. if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
  864. !Tok.isObjCAtKeyword(tok::objc_protocol)) {
  865. Diag(Tok, diag::err_objc_unexpected_attr);
  866. SkipUntil(tok::semi); // FIXME: better skip?
  867. return nullptr;
  868. }
  869. DS.abort();
  870. const char *PrevSpec = nullptr;
  871. unsigned DiagID;
  872. if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
  873. Actions.getASTContext().getPrintingPolicy()))
  874. Diag(AtLoc, DiagID) << PrevSpec;
  875. if (Tok.isObjCAtKeyword(tok::objc_protocol))
  876. return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
  877. return Actions.ConvertDeclToDeclGroup(
  878. ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
  879. }
  880. // If the declspec consisted only of 'extern' and we have a string
  881. // literal following it, this must be a C++ linkage specifier like
  882. // 'extern "C"'.
  883. if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
  884. DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
  885. DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
  886. Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::FileContext);
  887. return Actions.ConvertDeclToDeclGroup(TheDecl);
  888. }
  889. return ParseDeclGroup(DS, DeclaratorContext::FileContext);
  890. }
  891. Parser::DeclGroupPtrTy
  892. Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
  893. ParsingDeclSpec *DS,
  894. AccessSpecifier AS) {
  895. if (DS) {
  896. return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
  897. } else {
  898. ParsingDeclSpec PDS(*this);
  899. // Must temporarily exit the objective-c container scope for
  900. // parsing c constructs and re-enter objc container scope
  901. // afterwards.
  902. ObjCDeclContextSwitch ObjCDC(*this);
  903. return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
  904. }
  905. }
  906. /// ParseFunctionDefinition - We parsed and verified that the specified
  907. /// Declarator is well formed. If this is a K&R-style function, read the
  908. /// parameters declaration-list, then start the compound-statement.
  909. ///
  910. /// function-definition: [C99 6.9.1]
  911. /// decl-specs declarator declaration-list[opt] compound-statement
  912. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  913. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  914. /// [C++] function-definition: [C++ 8.4]
  915. /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
  916. /// function-body
  917. /// [C++] function-definition: [C++ 8.4]
  918. /// decl-specifier-seq[opt] declarator function-try-block
  919. ///
  920. Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
  921. const ParsedTemplateInfo &TemplateInfo,
  922. LateParsedAttrList *LateParsedAttrs) {
  923. // Poison SEH identifiers so they are flagged as illegal in function bodies.
  924. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  925. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  926. // If this is C90 and the declspecs were completely missing, fudge in an
  927. // implicit int. We do this here because this is the only place where
  928. // declaration-specifiers are completely optional in the grammar.
  929. if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
  930. const char *PrevSpec;
  931. unsigned DiagID;
  932. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  933. D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
  934. D.getIdentifierLoc(),
  935. PrevSpec, DiagID,
  936. Policy);
  937. D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
  938. }
  939. // If this declaration was formed with a K&R-style identifier list for the
  940. // arguments, parse declarations for all of the args next.
  941. // int foo(a,b) int a; float b; {}
  942. if (FTI.isKNRPrototype())
  943. ParseKNRParamDeclarations(D);
  944. // We should have either an opening brace or, in a C++ constructor,
  945. // we may have a colon.
  946. if (Tok.isNot(tok::l_brace) &&
  947. (!getLangOpts().CPlusPlus ||
  948. (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
  949. Tok.isNot(tok::equal)))) {
  950. Diag(Tok, diag::err_expected_fn_body);
  951. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  952. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  953. // If we didn't find the '{', bail out.
  954. if (Tok.isNot(tok::l_brace))
  955. return nullptr;
  956. }
  957. // Check to make sure that any normal attributes are allowed to be on
  958. // a definition. Late parsed attributes are checked at the end.
  959. if (Tok.isNot(tok::equal)) {
  960. AttributeList *DtorAttrs = D.getAttributes();
  961. while (DtorAttrs) {
  962. if (DtorAttrs->isKnownToGCC() &&
  963. !DtorAttrs->isCXX11Attribute()) {
  964. Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
  965. << DtorAttrs->getName();
  966. }
  967. DtorAttrs = DtorAttrs->getNext();
  968. }
  969. }
  970. // In delayed template parsing mode, for function template we consume the
  971. // tokens and store them for late parsing at the end of the translation unit.
  972. if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
  973. TemplateInfo.Kind == ParsedTemplateInfo::Template &&
  974. Actions.canDelayFunctionBody(D)) {
  975. MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
  976. ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
  977. Scope::CompoundStmtScope);
  978. Scope *ParentScope = getCurScope()->getParent();
  979. D.setFunctionDefinitionKind(FDK_Definition);
  980. Decl *DP = Actions.HandleDeclarator(ParentScope, D,
  981. TemplateParameterLists);
  982. D.complete(DP);
  983. D.getMutableDeclSpec().abort();
  984. if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
  985. trySkippingFunctionBody()) {
  986. BodyScope.Exit();
  987. return Actions.ActOnSkippedFunctionBody(DP);
  988. }
  989. CachedTokens Toks;
  990. LexTemplateFunctionForLateParsing(Toks);
  991. if (DP) {
  992. FunctionDecl *FnD = DP->getAsFunction();
  993. Actions.CheckForFunctionRedefinition(FnD);
  994. Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
  995. }
  996. return DP;
  997. }
  998. else if (CurParsedObjCImpl &&
  999. !TemplateInfo.TemplateParams &&
  1000. (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
  1001. Tok.is(tok::colon)) &&
  1002. Actions.CurContext->isTranslationUnit()) {
  1003. ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
  1004. Scope::CompoundStmtScope);
  1005. Scope *ParentScope = getCurScope()->getParent();
  1006. D.setFunctionDefinitionKind(FDK_Definition);
  1007. Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
  1008. MultiTemplateParamsArg());
  1009. D.complete(FuncDecl);
  1010. D.getMutableDeclSpec().abort();
  1011. if (FuncDecl) {
  1012. // Consume the tokens and store them for later parsing.
  1013. StashAwayMethodOrFunctionBodyTokens(FuncDecl);
  1014. CurParsedObjCImpl->HasCFunction = true;
  1015. return FuncDecl;
  1016. }
  1017. // FIXME: Should we really fall through here?
  1018. }
  1019. // Enter a scope for the function body.
  1020. ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
  1021. Scope::CompoundStmtScope);
  1022. // Tell the actions module that we have entered a function definition with the
  1023. // specified Declarator for the function.
  1024. Sema::SkipBodyInfo SkipBody;
  1025. Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
  1026. TemplateInfo.TemplateParams
  1027. ? *TemplateInfo.TemplateParams
  1028. : MultiTemplateParamsArg(),
  1029. &SkipBody);
  1030. if (SkipBody.ShouldSkip) {
  1031. SkipFunctionBody();
  1032. return Res;
  1033. }
  1034. // Break out of the ParsingDeclarator context before we parse the body.
  1035. D.complete(Res);
  1036. // Break out of the ParsingDeclSpec context, too. This const_cast is
  1037. // safe because we're always the sole owner.
  1038. D.getMutableDeclSpec().abort();
  1039. if (TryConsumeToken(tok::equal)) {
  1040. assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
  1041. bool Delete = false;
  1042. SourceLocation KWLoc;
  1043. if (TryConsumeToken(tok::kw_delete, KWLoc)) {
  1044. Diag(KWLoc, getLangOpts().CPlusPlus11
  1045. ? diag::warn_cxx98_compat_defaulted_deleted_function
  1046. : diag::ext_defaulted_deleted_function)
  1047. << 1 /* deleted */;
  1048. Actions.SetDeclDeleted(Res, KWLoc);
  1049. Delete = true;
  1050. } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
  1051. Diag(KWLoc, getLangOpts().CPlusPlus11
  1052. ? diag::warn_cxx98_compat_defaulted_deleted_function
  1053. : diag::ext_defaulted_deleted_function)
  1054. << 0 /* defaulted */;
  1055. Actions.SetDeclDefaulted(Res, KWLoc);
  1056. } else {
  1057. llvm_unreachable("function definition after = not 'delete' or 'default'");
  1058. }
  1059. if (Tok.is(tok::comma)) {
  1060. Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
  1061. << Delete;
  1062. SkipUntil(tok::semi);
  1063. } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  1064. Delete ? "delete" : "default")) {
  1065. SkipUntil(tok::semi);
  1066. }
  1067. Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
  1068. Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
  1069. return Res;
  1070. }
  1071. if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
  1072. trySkippingFunctionBody()) {
  1073. BodyScope.Exit();
  1074. Actions.ActOnSkippedFunctionBody(Res);
  1075. return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
  1076. }
  1077. if (Tok.is(tok::kw_try))
  1078. return ParseFunctionTryBlock(Res, BodyScope);
  1079. // If we have a colon, then we're probably parsing a C++
  1080. // ctor-initializer.
  1081. if (Tok.is(tok::colon)) {
  1082. ParseConstructorInitializer(Res);
  1083. // Recover from error.
  1084. if (!Tok.is(tok::l_brace)) {
  1085. BodyScope.Exit();
  1086. Actions.ActOnFinishFunctionBody(Res, nullptr);
  1087. return Res;
  1088. }
  1089. } else
  1090. Actions.ActOnDefaultCtorInitializers(Res);
  1091. // Late attributes are parsed in the same scope as the function body.
  1092. if (LateParsedAttrs)
  1093. ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
  1094. return ParseFunctionStatementBody(Res, BodyScope);
  1095. }
  1096. void Parser::SkipFunctionBody() {
  1097. if (Tok.is(tok::equal)) {
  1098. SkipUntil(tok::semi);
  1099. return;
  1100. }
  1101. bool IsFunctionTryBlock = Tok.is(tok::kw_try);
  1102. if (IsFunctionTryBlock)
  1103. ConsumeToken();
  1104. CachedTokens Skipped;
  1105. if (ConsumeAndStoreFunctionPrologue(Skipped))
  1106. SkipMalformedDecl();
  1107. else {
  1108. SkipUntil(tok::r_brace);
  1109. while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
  1110. SkipUntil(tok::l_brace);
  1111. SkipUntil(tok::r_brace);
  1112. }
  1113. }
  1114. }
  1115. /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
  1116. /// types for a function with a K&R-style identifier list for arguments.
  1117. void Parser::ParseKNRParamDeclarations(Declarator &D) {
  1118. // We know that the top-level of this declarator is a function.
  1119. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  1120. // Enter function-declaration scope, limiting any declarators to the
  1121. // function prototype scope, including parameter declarators.
  1122. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
  1123. Scope::FunctionDeclarationScope | Scope::DeclScope);
  1124. // Read all the argument declarations.
  1125. while (isDeclarationSpecifier()) {
  1126. SourceLocation DSStart = Tok.getLocation();
  1127. // Parse the common declaration-specifiers piece.
  1128. DeclSpec DS(AttrFactory);
  1129. ParseDeclarationSpecifiers(DS);
  1130. // C99 6.9.1p6: 'each declaration in the declaration list shall have at
  1131. // least one declarator'.
  1132. // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
  1133. // the declarations though. It's trivial to ignore them, really hard to do
  1134. // anything else with them.
  1135. if (TryConsumeToken(tok::semi)) {
  1136. Diag(DSStart, diag::err_declaration_does_not_declare_param);
  1137. continue;
  1138. }
  1139. // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
  1140. // than register.
  1141. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  1142. DS.getStorageClassSpec() != DeclSpec::SCS_register) {
  1143. Diag(DS.getStorageClassSpecLoc(),
  1144. diag::err_invalid_storage_class_in_func_decl);
  1145. DS.ClearStorageClassSpecs();
  1146. }
  1147. if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
  1148. Diag(DS.getThreadStorageClassSpecLoc(),
  1149. diag::err_invalid_storage_class_in_func_decl);
  1150. DS.ClearStorageClassSpecs();
  1151. }
  1152. // Parse the first declarator attached to this declspec.
  1153. Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeListContext);
  1154. ParseDeclarator(ParmDeclarator);
  1155. // Handle the full declarator list.
  1156. while (1) {
  1157. // If attributes are present, parse them.
  1158. MaybeParseGNUAttributes(ParmDeclarator);
  1159. // Ask the actions module to compute the type for this declarator.
  1160. Decl *Param =
  1161. Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
  1162. if (Param &&
  1163. // A missing identifier has already been diagnosed.
  1164. ParmDeclarator.getIdentifier()) {
  1165. // Scan the argument list looking for the correct param to apply this
  1166. // type.
  1167. for (unsigned i = 0; ; ++i) {
  1168. // C99 6.9.1p6: those declarators shall declare only identifiers from
  1169. // the identifier list.
  1170. if (i == FTI.NumParams) {
  1171. Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
  1172. << ParmDeclarator.getIdentifier();
  1173. break;
  1174. }
  1175. if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
  1176. // Reject redefinitions of parameters.
  1177. if (FTI.Params[i].Param) {
  1178. Diag(ParmDeclarator.getIdentifierLoc(),
  1179. diag::err_param_redefinition)
  1180. << ParmDeclarator.getIdentifier();
  1181. } else {
  1182. FTI.Params[i].Param = Param;
  1183. }
  1184. break;
  1185. }
  1186. }
  1187. }
  1188. // If we don't have a comma, it is either the end of the list (a ';') or
  1189. // an error, bail out.
  1190. if (Tok.isNot(tok::comma))
  1191. break;
  1192. ParmDeclarator.clear();
  1193. // Consume the comma.
  1194. ParmDeclarator.setCommaLoc(ConsumeToken());
  1195. // Parse the next declarator.
  1196. ParseDeclarator(ParmDeclarator);
  1197. }
  1198. // Consume ';' and continue parsing.
  1199. if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
  1200. continue;
  1201. // Otherwise recover by skipping to next semi or mandatory function body.
  1202. if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
  1203. break;
  1204. TryConsumeToken(tok::semi);
  1205. }
  1206. // The actions module must verify that all arguments were declared.
  1207. Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
  1208. }
  1209. /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
  1210. /// allowed to be a wide string, and is not subject to character translation.
  1211. ///
  1212. /// [GNU] asm-string-literal:
  1213. /// string-literal
  1214. ///
  1215. ExprResult Parser::ParseAsmStringLiteral() {
  1216. if (!isTokenStringLiteral()) {
  1217. Diag(Tok, diag::err_expected_string_literal)
  1218. << /*Source='in...'*/0 << "'asm'";
  1219. return ExprError();
  1220. }
  1221. ExprResult AsmString(ParseStringLiteralExpression());
  1222. if (!AsmString.isInvalid()) {
  1223. const auto *SL = cast<StringLiteral>(AsmString.get());
  1224. if (!SL->isAscii()) {
  1225. Diag(Tok, diag::err_asm_operand_wide_string_literal)
  1226. << SL->isWide()
  1227. << SL->getSourceRange();
  1228. return ExprError();
  1229. }
  1230. }
  1231. return AsmString;
  1232. }
  1233. /// ParseSimpleAsm
  1234. ///
  1235. /// [GNU] simple-asm-expr:
  1236. /// 'asm' '(' asm-string-literal ')'
  1237. ///
  1238. ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
  1239. assert(Tok.is(tok::kw_asm) && "Not an asm!");
  1240. SourceLocation Loc = ConsumeToken();
  1241. if (Tok.is(tok::kw_volatile)) {
  1242. // Remove from the end of 'asm' to the end of 'volatile'.
  1243. SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
  1244. PP.getLocForEndOfToken(Tok.getLocation()));
  1245. Diag(Tok, diag::warn_file_asm_volatile)
  1246. << FixItHint::CreateRemoval(RemovalRange);
  1247. ConsumeToken();
  1248. }
  1249. BalancedDelimiterTracker T(*this, tok::l_paren);
  1250. if (T.consumeOpen()) {
  1251. Diag(Tok, diag::err_expected_lparen_after) << "asm";
  1252. return ExprError();
  1253. }
  1254. ExprResult Result(ParseAsmStringLiteral());
  1255. if (!Result.isInvalid()) {
  1256. // Close the paren and get the location of the end bracket
  1257. T.consumeClose();
  1258. if (EndLoc)
  1259. *EndLoc = T.getCloseLocation();
  1260. } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
  1261. if (EndLoc)
  1262. *EndLoc = Tok.getLocation();
  1263. ConsumeParen();
  1264. }
  1265. return Result;
  1266. }
  1267. /// \brief Get the TemplateIdAnnotation from the token and put it in the
  1268. /// cleanup pool so that it gets destroyed when parsing the current top level
  1269. /// declaration is finished.
  1270. TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
  1271. assert(tok.is(tok::annot_template_id) && "Expected template-id token");
  1272. TemplateIdAnnotation *
  1273. Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
  1274. return Id;
  1275. }
  1276. void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
  1277. // Push the current token back into the token stream (or revert it if it is
  1278. // cached) and use an annotation scope token for current token.
  1279. if (PP.isBacktrackEnabled())
  1280. PP.RevertCachedTokens(1);
  1281. else
  1282. PP.EnterToken(Tok);
  1283. Tok.setKind(tok::annot_cxxscope);
  1284. Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
  1285. Tok.setAnnotationRange(SS.getRange());
  1286. // In case the tokens were cached, have Preprocessor replace them
  1287. // with the annotation token. We don't need to do this if we've
  1288. // just reverted back to a prior state.
  1289. if (IsNewAnnotation)
  1290. PP.AnnotateCachedTokens(Tok);
  1291. }
  1292. /// \brief Attempt to classify the name at the current token position. This may
  1293. /// form a type, scope or primary expression annotation, or replace the token
  1294. /// with a typo-corrected keyword. This is only appropriate when the current
  1295. /// name must refer to an entity which has already been declared.
  1296. ///
  1297. /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
  1298. /// and might possibly have a dependent nested name specifier.
  1299. /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
  1300. /// no typo correction will be performed.
  1301. Parser::AnnotatedNameKind
  1302. Parser::TryAnnotateName(bool IsAddressOfOperand,
  1303. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  1304. assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
  1305. const bool EnteringContext = false;
  1306. const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
  1307. CXXScopeSpec SS;
  1308. if (getLangOpts().CPlusPlus &&
  1309. ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
  1310. return ANK_Error;
  1311. if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
  1312. if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
  1313. return ANK_Error;
  1314. return ANK_Unresolved;
  1315. }
  1316. IdentifierInfo *Name = Tok.getIdentifierInfo();
  1317. SourceLocation NameLoc = Tok.getLocation();
  1318. // FIXME: Move the tentative declaration logic into ClassifyName so we can
  1319. // typo-correct to tentatively-declared identifiers.
  1320. if (isTentativelyDeclared(Name)) {
  1321. // Identifier has been tentatively declared, and thus cannot be resolved as
  1322. // an expression. Fall back to annotating it as a type.
  1323. if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
  1324. return ANK_Error;
  1325. return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
  1326. }
  1327. Token Next = NextToken();
  1328. // Look up and classify the identifier. We don't perform any typo-correction
  1329. // after a scope specifier, because in general we can't recover from typos
  1330. // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to
  1331. // jump back into scope specifier parsing).
  1332. Sema::NameClassification Classification = Actions.ClassifyName(
  1333. getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
  1334. SS.isEmpty() ? std::move(CCC) : nullptr);
  1335. switch (Classification.getKind()) {
  1336. case Sema::NC_Error:
  1337. return ANK_Error;
  1338. case Sema::NC_Keyword:
  1339. // The identifier was typo-corrected to a keyword.
  1340. Tok.setIdentifierInfo(Name);
  1341. Tok.setKind(Name->getTokenID());
  1342. PP.TypoCorrectToken(Tok);
  1343. if (SS.isNotEmpty())
  1344. AnnotateScopeToken(SS, !WasScopeAnnotation);
  1345. // We've "annotated" this as a keyword.
  1346. return ANK_Success;
  1347. case Sema::NC_Unknown:
  1348. // It's not something we know about. Leave it unannotated.
  1349. break;
  1350. case Sema::NC_Type: {
  1351. SourceLocation BeginLoc = NameLoc;
  1352. if (SS.isNotEmpty())
  1353. BeginLoc = SS.getBeginLoc();
  1354. /// An Objective-C object type followed by '<' is a specialization of
  1355. /// a parameterized class type or a protocol-qualified type.
  1356. ParsedType Ty = Classification.getType();
  1357. if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
  1358. (Ty.get()->isObjCObjectType() ||
  1359. Ty.get()->isObjCObjectPointerType())) {
  1360. // Consume the name.
  1361. SourceLocation IdentifierLoc = ConsumeToken();
  1362. SourceLocation NewEndLoc;
  1363. TypeResult NewType
  1364. = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
  1365. /*consumeLastToken=*/false,
  1366. NewEndLoc);
  1367. if (NewType.isUsable())
  1368. Ty = NewType.get();
  1369. else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
  1370. return ANK_Error;
  1371. }
  1372. Tok.setKind(tok::annot_typename);
  1373. setTypeAnnotation(Tok, Ty);
  1374. Tok.setAnnotationEndLoc(Tok.getLocation());
  1375. Tok.setLocation(BeginLoc);
  1376. PP.AnnotateCachedTokens(Tok);
  1377. return ANK_Success;
  1378. }
  1379. case Sema::NC_Expression:
  1380. Tok.setKind(tok::annot_primary_expr);
  1381. setExprAnnotation(Tok, Classification.getExpression());
  1382. Tok.setAnnotationEndLoc(NameLoc);
  1383. if (SS.isNotEmpty())
  1384. Tok.setLocation(SS.getBeginLoc());
  1385. PP.AnnotateCachedTokens(Tok);
  1386. return ANK_Success;
  1387. case Sema::NC_TypeTemplate:
  1388. if (Next.isNot(tok::less)) {
  1389. // This may be a type template being used as a template template argument.
  1390. if (SS.isNotEmpty())
  1391. AnnotateScopeToken(SS, !WasScopeAnnotation);
  1392. return ANK_TemplateName;
  1393. }
  1394. // Fall through.
  1395. case Sema::NC_VarTemplate:
  1396. case Sema::NC_FunctionTemplate: {
  1397. // We have a type, variable or function template followed by '<'.
  1398. ConsumeToken();
  1399. UnqualifiedId Id;
  1400. Id.setIdentifier(Name, NameLoc);
  1401. if (AnnotateTemplateIdToken(
  1402. TemplateTy::make(Classification.getTemplateName()),
  1403. Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
  1404. return ANK_Error;
  1405. return ANK_Success;
  1406. }
  1407. case Sema::NC_NestedNameSpecifier:
  1408. llvm_unreachable("already parsed nested name specifier");
  1409. }
  1410. // Unable to classify the name, but maybe we can annotate a scope specifier.
  1411. if (SS.isNotEmpty())
  1412. AnnotateScopeToken(SS, !WasScopeAnnotation);
  1413. return ANK_Unresolved;
  1414. }
  1415. bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
  1416. assert(Tok.isNot(tok::identifier));
  1417. Diag(Tok, diag::ext_keyword_as_ident)
  1418. << PP.getSpelling(Tok)
  1419. << DisableKeyword;
  1420. if (DisableKeyword)
  1421. Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
  1422. Tok.setKind(tok::identifier);
  1423. return true;
  1424. }
  1425. /// TryAnnotateTypeOrScopeToken - If the current token position is on a
  1426. /// typename (possibly qualified in C++) or a C++ scope specifier not followed
  1427. /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
  1428. /// with a single annotation token representing the typename or C++ scope
  1429. /// respectively.
  1430. /// This simplifies handling of C++ scope specifiers and allows efficient
  1431. /// backtracking without the need to re-parse and resolve nested-names and
  1432. /// typenames.
  1433. /// It will mainly be called when we expect to treat identifiers as typenames
  1434. /// (if they are typenames). For example, in C we do not expect identifiers
  1435. /// inside expressions to be treated as typenames so it will not be called
  1436. /// for expressions in C.
  1437. /// The benefit for C/ObjC is that a typename will be annotated and
  1438. /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
  1439. /// will not be called twice, once to check whether we have a declaration
  1440. /// specifier, and another one to get the actual type inside
  1441. /// ParseDeclarationSpecifiers).
  1442. ///
  1443. /// This returns true if an error occurred.
  1444. ///
  1445. /// Note that this routine emits an error if you call it with ::new or ::delete
  1446. /// as the current tokens, so only call it in contexts where these are invalid.
  1447. bool Parser::TryAnnotateTypeOrScopeToken() {
  1448. assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
  1449. Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
  1450. Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
  1451. Tok.is(tok::kw___super)) &&
  1452. "Cannot be a type or scope token!");
  1453. if (Tok.is(tok::kw_typename)) {
  1454. // MSVC lets you do stuff like:
  1455. // typename typedef T_::D D;
  1456. //
  1457. // We will consume the typedef token here and put it back after we have
  1458. // parsed the first identifier, transforming it into something more like:
  1459. // typename T_::D typedef D;
  1460. if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
  1461. Token TypedefToken;
  1462. PP.Lex(TypedefToken);
  1463. bool Result = TryAnnotateTypeOrScopeToken();
  1464. PP.EnterToken(Tok);
  1465. Tok = TypedefToken;
  1466. if (!Result)
  1467. Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
  1468. return Result;
  1469. }
  1470. // Parse a C++ typename-specifier, e.g., "typename T::type".
  1471. //
  1472. // typename-specifier:
  1473. // 'typename' '::' [opt] nested-name-specifier identifier
  1474. // 'typename' '::' [opt] nested-name-specifier template [opt]
  1475. // simple-template-id
  1476. SourceLocation TypenameLoc = ConsumeToken();
  1477. CXXScopeSpec SS;
  1478. if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  1479. /*EnteringContext=*/false, nullptr,
  1480. /*IsTypename*/ true))
  1481. return true;
  1482. if (!SS.isSet()) {
  1483. if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
  1484. Tok.is(tok::annot_decltype)) {
  1485. // Attempt to recover by skipping the invalid 'typename'
  1486. if (Tok.is(tok::annot_decltype) ||
  1487. (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
  1488. unsigned DiagID = diag::err_expected_qualified_after_typename;
  1489. // MS compatibility: MSVC permits using known types with typename.
  1490. // e.g. "typedef typename T* pointer_type"
  1491. if (getLangOpts().MicrosoftExt)
  1492. DiagID = diag::warn_expected_qualified_after_typename;
  1493. Diag(Tok.getLocation(), DiagID);
  1494. return false;
  1495. }
  1496. }
  1497. if (Tok.isEditorPlaceholder())
  1498. return true;
  1499. Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
  1500. return true;
  1501. }
  1502. TypeResult Ty;
  1503. if (Tok.is(tok::identifier)) {
  1504. // FIXME: check whether the next token is '<', first!
  1505. Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
  1506. *Tok.getIdentifierInfo(),
  1507. Tok.getLocation());
  1508. } else if (Tok.is(tok::annot_template_id)) {
  1509. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1510. if (TemplateId->Kind != TNK_Type_template &&
  1511. TemplateId->Kind != TNK_Dependent_template_name) {
  1512. Diag(Tok, diag::err_typename_refers_to_non_type_template)
  1513. << Tok.getAnnotationRange();
  1514. return true;
  1515. }
  1516. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  1517. TemplateId->NumArgs);
  1518. Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
  1519. TemplateId->TemplateKWLoc,
  1520. TemplateId->Template,
  1521. TemplateId->Name,
  1522. TemplateId->TemplateNameLoc,
  1523. TemplateId->LAngleLoc,
  1524. TemplateArgsPtr,
  1525. TemplateId->RAngleLoc);
  1526. } else {
  1527. Diag(Tok, diag::err_expected_type_name_after_typename)
  1528. << SS.getRange();
  1529. return true;
  1530. }
  1531. SourceLocation EndLoc = Tok.getLastLoc();
  1532. Tok.setKind(tok::annot_typename);
  1533. setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get());
  1534. Tok.setAnnotationEndLoc(EndLoc);
  1535. Tok.setLocation(TypenameLoc);
  1536. PP.AnnotateCachedTokens(Tok);
  1537. return false;
  1538. }
  1539. // Remembers whether the token was originally a scope annotation.
  1540. bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
  1541. CXXScopeSpec SS;
  1542. if (getLangOpts().CPlusPlus)
  1543. if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext*/false))
  1544. return true;
  1545. return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
  1546. }
  1547. /// \brief Try to annotate a type or scope token, having already parsed an
  1548. /// optional scope specifier. \p IsNewScope should be \c true unless the scope
  1549. /// specifier was extracted from an existing tok::annot_cxxscope annotation.
  1550. bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
  1551. bool IsNewScope) {
  1552. if (Tok.is(tok::identifier)) {
  1553. // Determine whether the identifier is a type name.
  1554. if (ParsedType Ty = Actions.getTypeName(
  1555. *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
  1556. false, NextToken().is(tok::period), nullptr,
  1557. /*IsCtorOrDtorName=*/false,
  1558. /*NonTrivialTypeSourceInfo*/true,
  1559. /*IsClassTemplateDeductionContext*/true)) {
  1560. SourceLocation BeginLoc = Tok.getLocation();
  1561. if (SS.isNotEmpty()) // it was a C++ qualified type name.
  1562. BeginLoc = SS.getBeginLoc();
  1563. /// An Objective-C object type followed by '<' is a specialization of
  1564. /// a parameterized class type or a protocol-qualified type.
  1565. if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
  1566. (Ty.get()->isObjCObjectType() ||
  1567. Ty.get()->isObjCObjectPointerType())) {
  1568. // Consume the name.
  1569. SourceLocation IdentifierLoc = ConsumeToken();
  1570. SourceLocation NewEndLoc;
  1571. TypeResult NewType
  1572. = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
  1573. /*consumeLastToken=*/false,
  1574. NewEndLoc);
  1575. if (NewType.isUsable())
  1576. Ty = NewType.get();
  1577. else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
  1578. return false;
  1579. }
  1580. // This is a typename. Replace the current token in-place with an
  1581. // annotation type token.
  1582. Tok.setKind(tok::annot_typename);
  1583. setTypeAnnotation(Tok, Ty);
  1584. Tok.setAnnotationEndLoc(Tok.getLocation());
  1585. Tok.setLocation(BeginLoc);
  1586. // In case the tokens were cached, have Preprocessor replace
  1587. // them with the annotation token.
  1588. PP.AnnotateCachedTokens(Tok);
  1589. return false;
  1590. }
  1591. if (!getLangOpts().CPlusPlus) {
  1592. // If we're in C, we can't have :: tokens at all (the lexer won't return
  1593. // them). If the identifier is not a type, then it can't be scope either,
  1594. // just early exit.
  1595. return false;
  1596. }
  1597. // If this is a template-id, annotate with a template-id or type token.
  1598. if (NextToken().is(tok::less)) {
  1599. TemplateTy Template;
  1600. UnqualifiedId TemplateName;
  1601. TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1602. bool MemberOfUnknownSpecialization;
  1603. if (TemplateNameKind TNK = Actions.isTemplateName(
  1604. getCurScope(), SS,
  1605. /*hasTemplateKeyword=*/false, TemplateName,
  1606. /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
  1607. MemberOfUnknownSpecialization)) {
  1608. // Consume the identifier.
  1609. ConsumeToken();
  1610. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  1611. TemplateName)) {
  1612. // If an unrecoverable error occurred, we need to return true here,
  1613. // because the token stream is in a damaged state. We may not return
  1614. // a valid identifier.
  1615. return true;
  1616. }
  1617. }
  1618. }
  1619. // The current token, which is either an identifier or a
  1620. // template-id, is not part of the annotation. Fall through to
  1621. // push that token back into the stream and complete the C++ scope
  1622. // specifier annotation.
  1623. }
  1624. if (Tok.is(tok::annot_template_id)) {
  1625. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1626. if (TemplateId->Kind == TNK_Type_template) {
  1627. // A template-id that refers to a type was parsed into a
  1628. // template-id annotation in a context where we weren't allowed
  1629. // to produce a type annotation token. Update the template-id
  1630. // annotation token to a type annotation token now.
  1631. AnnotateTemplateIdTokenAsType();
  1632. return false;
  1633. }
  1634. }
  1635. if (SS.isEmpty())
  1636. return false;
  1637. // A C++ scope specifier that isn't followed by a typename.
  1638. AnnotateScopeToken(SS, IsNewScope);
  1639. return false;
  1640. }
  1641. /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
  1642. /// annotates C++ scope specifiers and template-ids. This returns
  1643. /// true if there was an error that could not be recovered from.
  1644. ///
  1645. /// Note that this routine emits an error if you call it with ::new or ::delete
  1646. /// as the current tokens, so only call it in contexts where these are invalid.
  1647. bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
  1648. assert(getLangOpts().CPlusPlus &&
  1649. "Call sites of this function should be guarded by checking for C++");
  1650. assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
  1651. (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
  1652. Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
  1653. "Cannot be a type or scope token!");
  1654. CXXScopeSpec SS;
  1655. if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
  1656. return true;
  1657. if (SS.isEmpty())
  1658. return false;
  1659. AnnotateScopeToken(SS, true);
  1660. return false;
  1661. }
  1662. bool Parser::isTokenEqualOrEqualTypo() {
  1663. tok::TokenKind Kind = Tok.getKind();
  1664. switch (Kind) {
  1665. default:
  1666. return false;
  1667. case tok::ampequal: // &=
  1668. case tok::starequal: // *=
  1669. case tok::plusequal: // +=
  1670. case tok::minusequal: // -=
  1671. case tok::exclaimequal: // !=
  1672. case tok::slashequal: // /=
  1673. case tok::percentequal: // %=
  1674. case tok::lessequal: // <=
  1675. case tok::lesslessequal: // <<=
  1676. case tok::greaterequal: // >=
  1677. case tok::greatergreaterequal: // >>=
  1678. case tok::caretequal: // ^=
  1679. case tok::pipeequal: // |=
  1680. case tok::equalequal: // ==
  1681. Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
  1682. << Kind
  1683. << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
  1684. LLVM_FALLTHROUGH;
  1685. case tok::equal:
  1686. return true;
  1687. }
  1688. }
  1689. SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
  1690. assert(Tok.is(tok::code_completion));
  1691. PrevTokLocation = Tok.getLocation();
  1692. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1693. if (S->getFlags() & Scope::FnScope) {
  1694. Actions.CodeCompleteOrdinaryName(getCurScope(),
  1695. Sema::PCC_RecoveryInFunction);
  1696. cutOffParsing();
  1697. return PrevTokLocation;
  1698. }
  1699. if (S->getFlags() & Scope::ClassScope) {
  1700. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
  1701. cutOffParsing();
  1702. return PrevTokLocation;
  1703. }
  1704. }
  1705. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
  1706. cutOffParsing();
  1707. return PrevTokLocation;
  1708. }
  1709. // Code-completion pass-through functions
  1710. void Parser::CodeCompleteDirective(bool InConditional) {
  1711. Actions.CodeCompletePreprocessorDirective(InConditional);
  1712. }
  1713. void Parser::CodeCompleteInConditionalExclusion() {
  1714. Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
  1715. }
  1716. void Parser::CodeCompleteMacroName(bool IsDefinition) {
  1717. Actions.CodeCompletePreprocessorMacroName(IsDefinition);
  1718. }
  1719. void Parser::CodeCompletePreprocessorExpression() {
  1720. Actions.CodeCompletePreprocessorExpression();
  1721. }
  1722. void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
  1723. MacroInfo *MacroInfo,
  1724. unsigned ArgumentIndex) {
  1725. Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
  1726. ArgumentIndex);
  1727. }
  1728. void Parser::CodeCompleteNaturalLanguage() {
  1729. Actions.CodeCompleteNaturalLanguage();
  1730. }
  1731. bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
  1732. assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
  1733. "Expected '__if_exists' or '__if_not_exists'");
  1734. Result.IsIfExists = Tok.is(tok::kw___if_exists);
  1735. Result.KeywordLoc = ConsumeToken();
  1736. BalancedDelimiterTracker T(*this, tok::l_paren);
  1737. if (T.consumeOpen()) {
  1738. Diag(Tok, diag::err_expected_lparen_after)
  1739. << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
  1740. return true;
  1741. }
  1742. // Parse nested-name-specifier.
  1743. if (getLangOpts().CPlusPlus)
  1744. ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
  1745. /*EnteringContext=*/false);
  1746. // Check nested-name specifier.
  1747. if (Result.SS.isInvalid()) {
  1748. T.skipToEnd();
  1749. return true;
  1750. }
  1751. // Parse the unqualified-id.
  1752. SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
  1753. if (ParseUnqualifiedId(
  1754. Result.SS, /*EnteringContext*/false, /*AllowDestructorName*/true,
  1755. /*AllowConstructorName*/true, /*AllowDeductionGuide*/false, nullptr,
  1756. &TemplateKWLoc, Result.Name)) {
  1757. T.skipToEnd();
  1758. return true;
  1759. }
  1760. if (T.consumeClose())
  1761. return true;
  1762. // Check if the symbol exists.
  1763. switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
  1764. Result.IsIfExists, Result.SS,
  1765. Result.Name)) {
  1766. case Sema::IER_Exists:
  1767. Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1768. break;
  1769. case Sema::IER_DoesNotExist:
  1770. Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1771. break;
  1772. case Sema::IER_Dependent:
  1773. Result.Behavior = IEB_Dependent;
  1774. break;
  1775. case Sema::IER_Error:
  1776. return true;
  1777. }
  1778. return false;
  1779. }
  1780. void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
  1781. IfExistsCondition Result;
  1782. if (ParseMicrosoftIfExistsCondition(Result))
  1783. return;
  1784. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  1785. if (Braces.consumeOpen()) {
  1786. Diag(Tok, diag::err_expected) << tok::l_brace;
  1787. return;
  1788. }
  1789. switch (Result.Behavior) {
  1790. case IEB_Parse:
  1791. // Parse declarations below.
  1792. break;
  1793. case IEB_Dependent:
  1794. llvm_unreachable("Cannot have a dependent external declaration");
  1795. case IEB_Skip:
  1796. Braces.skipToEnd();
  1797. return;
  1798. }
  1799. // Parse the declarations.
  1800. // FIXME: Support module import within __if_exists?
  1801. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  1802. ParsedAttributesWithRange attrs(AttrFactory);
  1803. MaybeParseCXX11Attributes(attrs);
  1804. DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
  1805. if (Result && !getCurScope()->getParent())
  1806. Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
  1807. }
  1808. Braces.consumeClose();
  1809. }
  1810. /// Parse a C++ Modules TS module declaration, which appears at the beginning
  1811. /// of a module interface, module partition, or module implementation file.
  1812. ///
  1813. /// module-declaration: [Modules TS + P0273R0 + P0629R0]
  1814. /// 'export'[opt] 'module' 'partition'[opt]
  1815. /// module-name attribute-specifier-seq[opt] ';'
  1816. ///
  1817. /// Note that 'partition' is a context-sensitive keyword.
  1818. Parser::DeclGroupPtrTy Parser::ParseModuleDecl() {
  1819. SourceLocation StartLoc = Tok.getLocation();
  1820. Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
  1821. ? Sema::ModuleDeclKind::Interface
  1822. : Sema::ModuleDeclKind::Implementation;
  1823. assert(Tok.is(tok::kw_module) && "not a module declaration");
  1824. SourceLocation ModuleLoc = ConsumeToken();
  1825. if (Tok.is(tok::identifier) && NextToken().is(tok::identifier) &&
  1826. Tok.getIdentifierInfo()->isStr("partition")) {
  1827. // If 'partition' is present, this must be a module interface unit.
  1828. if (MDK != Sema::ModuleDeclKind::Interface)
  1829. Diag(Tok.getLocation(), diag::err_module_implementation_partition)
  1830. << FixItHint::CreateInsertion(ModuleLoc, "export ");
  1831. MDK = Sema::ModuleDeclKind::Partition;
  1832. ConsumeToken();
  1833. }
  1834. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1835. if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
  1836. return nullptr;
  1837. // We don't support any module attributes yet; just parse them and diagnose.
  1838. ParsedAttributesWithRange Attrs(AttrFactory);
  1839. MaybeParseCXX11Attributes(Attrs);
  1840. ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
  1841. ExpectAndConsumeSemi(diag::err_module_expected_semi);
  1842. return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path);
  1843. }
  1844. /// Parse a module import declaration. This is essentially the same for
  1845. /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
  1846. /// and the trailing optional attributes (in C++).
  1847. ///
  1848. /// [ObjC] @import declaration:
  1849. /// '@' 'import' module-name ';'
  1850. /// [ModTS] module-import-declaration:
  1851. /// 'import' module-name attribute-specifier-seq[opt] ';'
  1852. Decl *Parser::ParseModuleImport(SourceLocation AtLoc) {
  1853. assert((AtLoc.isInvalid() ? Tok.is(tok::kw_import)
  1854. : Tok.isObjCAtKeyword(tok::objc_import)) &&
  1855. "Improper start to module import");
  1856. SourceLocation ImportLoc = ConsumeToken();
  1857. SourceLocation StartLoc = AtLoc.isInvalid() ? ImportLoc : AtLoc;
  1858. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1859. if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
  1860. return nullptr;
  1861. ParsedAttributesWithRange Attrs(AttrFactory);
  1862. MaybeParseCXX11Attributes(Attrs);
  1863. // We don't support any module import attributes yet.
  1864. ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
  1865. if (PP.hadModuleLoaderFatalFailure()) {
  1866. // With a fatal failure in the module loader, we abort parsing.
  1867. cutOffParsing();
  1868. return nullptr;
  1869. }
  1870. DeclResult Import = Actions.ActOnModuleImport(StartLoc, ImportLoc, Path);
  1871. ExpectAndConsumeSemi(diag::err_module_expected_semi);
  1872. if (Import.isInvalid())
  1873. return nullptr;
  1874. return Import.get();
  1875. }
  1876. /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
  1877. /// grammar).
  1878. ///
  1879. /// module-name:
  1880. /// module-name-qualifier[opt] identifier
  1881. /// module-name-qualifier:
  1882. /// module-name-qualifier[opt] identifier '.'
  1883. bool Parser::ParseModuleName(
  1884. SourceLocation UseLoc,
  1885. SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
  1886. bool IsImport) {
  1887. // Parse the module path.
  1888. while (true) {
  1889. if (!Tok.is(tok::identifier)) {
  1890. if (Tok.is(tok::code_completion)) {
  1891. Actions.CodeCompleteModuleImport(UseLoc, Path);
  1892. cutOffParsing();
  1893. return true;
  1894. }
  1895. Diag(Tok, diag::err_module_expected_ident) << IsImport;
  1896. SkipUntil(tok::semi);
  1897. return true;
  1898. }
  1899. // Record this part of the module path.
  1900. Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
  1901. ConsumeToken();
  1902. if (Tok.isNot(tok::period))
  1903. return false;
  1904. ConsumeToken();
  1905. }
  1906. }
  1907. /// \brief Try recover parser when module annotation appears where it must not
  1908. /// be found.
  1909. /// \returns false if the recover was successful and parsing may be continued, or
  1910. /// true if parser must bail out to top level and handle the token there.
  1911. bool Parser::parseMisplacedModuleImport() {
  1912. while (true) {
  1913. switch (Tok.getKind()) {
  1914. case tok::annot_module_end:
  1915. // If we recovered from a misplaced module begin, we expect to hit a
  1916. // misplaced module end too. Stay in the current context when this
  1917. // happens.
  1918. if (MisplacedModuleBeginCount) {
  1919. --MisplacedModuleBeginCount;
  1920. Actions.ActOnModuleEnd(Tok.getLocation(),
  1921. reinterpret_cast<Module *>(
  1922. Tok.getAnnotationValue()));
  1923. ConsumeAnnotationToken();
  1924. continue;
  1925. }
  1926. // Inform caller that recovery failed, the error must be handled at upper
  1927. // level. This will generate the desired "missing '}' at end of module"
  1928. // diagnostics on the way out.
  1929. return true;
  1930. case tok::annot_module_begin:
  1931. // Recover by entering the module (Sema will diagnose).
  1932. Actions.ActOnModuleBegin(Tok.getLocation(),
  1933. reinterpret_cast<Module *>(
  1934. Tok.getAnnotationValue()));
  1935. ConsumeAnnotationToken();
  1936. ++MisplacedModuleBeginCount;
  1937. continue;
  1938. case tok::annot_module_include:
  1939. // Module import found where it should not be, for instance, inside a
  1940. // namespace. Recover by importing the module.
  1941. Actions.ActOnModuleInclude(Tok.getLocation(),
  1942. reinterpret_cast<Module *>(
  1943. Tok.getAnnotationValue()));
  1944. ConsumeAnnotationToken();
  1945. // If there is another module import, process it.
  1946. continue;
  1947. default:
  1948. return false;
  1949. }
  1950. }
  1951. return false;
  1952. }
  1953. bool BalancedDelimiterTracker::diagnoseOverflow() {
  1954. P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
  1955. << P.getLangOpts().BracketDepth;
  1956. P.Diag(P.Tok, diag::note_bracket_depth);
  1957. P.cutOffParsing();
  1958. return true;
  1959. }
  1960. bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
  1961. const char *Msg,
  1962. tok::TokenKind SkipToTok) {
  1963. LOpen = P.Tok.getLocation();
  1964. if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
  1965. if (SkipToTok != tok::unknown)
  1966. P.SkipUntil(SkipToTok, Parser::StopAtSemi);
  1967. return true;
  1968. }
  1969. if (getDepth() < P.getLangOpts().BracketDepth)
  1970. return false;
  1971. return diagnoseOverflow();
  1972. }
  1973. bool BalancedDelimiterTracker::diagnoseMissingClose() {
  1974. assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
  1975. if (P.Tok.is(tok::annot_module_end))
  1976. P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
  1977. else
  1978. P.Diag(P.Tok, diag::err_expected) << Close;
  1979. P.Diag(LOpen, diag::note_matching) << Kind;
  1980. // If we're not already at some kind of closing bracket, skip to our closing
  1981. // token.
  1982. if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
  1983. P.Tok.isNot(tok::r_square) &&
  1984. P.SkipUntil(Close, FinalToken,
  1985. Parser::StopAtSemi | Parser::StopBeforeMatch) &&
  1986. P.Tok.is(Close))
  1987. LClose = P.ConsumeAnyToken();
  1988. return true;
  1989. }
  1990. void BalancedDelimiterTracker::skipToEnd() {
  1991. P.SkipUntil(Close, Parser::StopBeforeMatch);
  1992. consumeClose();
  1993. }