Parser.cpp 86 KB

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