Parser.cpp 76 KB

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