Parser.cpp 99 KB

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