Parser.cpp 88 KB

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