Parser.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082
  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. // HLSL Change Ends
  676. case tok::kw_using:
  677. case tok::kw_namespace:
  678. case tok::kw_typedef:
  679. case tok::kw_template:
  680. case tok::kw_export: // As in 'export template'
  681. case tok::kw_static_assert:
  682. case tok::kw__Static_assert:
  683. // A function definition cannot start with any of these keywords.
  684. {
  685. SourceLocation DeclEnd;
  686. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  687. }
  688. case tok::kw_static:
  689. // Parse (then ignore) 'static' prior to a template instantiation. This is
  690. // a GCC extension that we intentionally do not support.
  691. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
  692. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  693. << 0;
  694. SourceLocation DeclEnd;
  695. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  696. }
  697. goto dont_know;
  698. case tok::kw_inline:
  699. if (getLangOpts().CPlusPlus) {
  700. tok::TokenKind NextKind = NextToken().getKind();
  701. // Inline namespaces. Allowed as an extension even in C++03.
  702. if (NextKind == tok::kw_namespace) {
  703. SourceLocation DeclEnd;
  704. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  705. }
  706. // Parse (then ignore) 'inline' prior to a template instantiation. This is
  707. // a GCC extension that we intentionally do not support.
  708. if (NextKind == tok::kw_template) {
  709. Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
  710. << 1;
  711. SourceLocation DeclEnd;
  712. return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
  713. }
  714. }
  715. goto dont_know;
  716. case tok::kw_extern:
  717. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template) && !getLangOpts().HLSL) { // HLSL Change
  718. // Extern templates
  719. SourceLocation ExternLoc = ConsumeToken();
  720. SourceLocation TemplateLoc = ConsumeToken();
  721. Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
  722. diag::warn_cxx98_compat_extern_template :
  723. diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
  724. SourceLocation DeclEnd;
  725. return Actions.ConvertDeclToDeclGroup(
  726. ParseExplicitInstantiation(Declarator::FileContext,
  727. ExternLoc, TemplateLoc, DeclEnd));
  728. }
  729. goto dont_know;
  730. case tok::kw___if_exists:
  731. case tok::kw___if_not_exists:
  732. if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing
  733. ParseMicrosoftIfExistsExternalDeclaration();
  734. return DeclGroupPtrTy();
  735. default:
  736. dont_know:
  737. // We can't tell whether this is a function-definition or declaration yet.
  738. return ParseDeclarationOrFunctionDefinition(attrs, DS);
  739. }
  740. // This routine returns a DeclGroup, if the thing we parsed only contains a
  741. // single decl, convert it now.
  742. return Actions.ConvertDeclToDeclGroup(SingleDecl);
  743. }
  744. /// \brief Determine whether the current token, if it occurs after a
  745. /// declarator, continues a declaration or declaration list.
  746. bool Parser::isDeclarationAfterDeclarator() {
  747. // Check for '= delete' or '= default'
  748. if (!getLangOpts().HLSL && (getLangOpts().CPlusPlus && Tok.is(tok::equal))) { // HLSL Change - remove support
  749. const Token &KW = NextToken();
  750. if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
  751. return false;
  752. }
  753. return Tok.is(tok::equal) || // int X()= -> not a function def
  754. Tok.is(tok::comma) || // int X(), -> not a function def
  755. Tok.is(tok::semi) || // int X(); -> not a function def
  756. Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
  757. Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
  758. (getLangOpts().CPlusPlus &&
  759. Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
  760. }
  761. /// \brief Determine whether the current token, if it occurs after a
  762. /// declarator, indicates the start of a function definition.
  763. bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
  764. assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
  765. if (Tok.is(tok::l_brace)) // int X() {}
  766. return true;
  767. // Handle K&R C argument lists: int X(f) int f; {}
  768. if (!getLangOpts().CPlusPlus &&
  769. Declarator.getFunctionTypeInfo().isKNRPrototype())
  770. return isDeclarationSpecifier();
  771. if (!getLangOpts().HLSL && getLangOpts().CPlusPlus && Tok.is(tok::equal)) { // HLSL Change - remove support
  772. const Token &KW = NextToken();
  773. return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
  774. }
  775. return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
  776. Tok.is(tok::kw_try); // X() try { ... }
  777. }
  778. /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
  779. /// a declaration. We can't tell which we have until we read up to the
  780. /// compound-statement in function-definition. TemplateParams, if
  781. /// non-NULL, provides the template parameters when we're parsing a
  782. /// C++ template-declaration.
  783. ///
  784. /// function-definition: [C99 6.9.1]
  785. /// decl-specs declarator declaration-list[opt] compound-statement
  786. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  787. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  788. ///
  789. /// declaration: [C99 6.7]
  790. /// declaration-specifiers init-declarator-list[opt] ';'
  791. /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
  792. /// [OMP] threadprivate-directive [TODO]
  793. ///
  794. Parser::DeclGroupPtrTy
  795. Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
  796. ParsingDeclSpec &DS,
  797. AccessSpecifier AS) {
  798. // Parse the common declaration-specifiers piece.
  799. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
  800. // If we had a free-standing type definition with a missing semicolon, we
  801. // may get this far before the problem becomes obvious.
  802. if (DS.hasTagDefinition() &&
  803. DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
  804. return DeclGroupPtrTy();
  805. // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
  806. // declaration-specifiers init-declarator-list[opt] ';'
  807. if (Tok.is(tok::semi)) {
  808. ProhibitAttributes(attrs);
  809. ConsumeToken();
  810. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
  811. DS.complete(TheDecl);
  812. return Actions.ConvertDeclToDeclGroup(TheDecl);
  813. }
  814. DS.takeAttributesFrom(attrs);
  815. // ObjC2 allows prefix attributes on class interfaces and protocols.
  816. // FIXME: This still needs better diagnostics. We should only accept
  817. // attributes here, no types, etc.
  818. if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
  819. SourceLocation AtLoc = ConsumeToken(); // the "@"
  820. if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
  821. !Tok.isObjCAtKeyword(tok::objc_protocol)) {
  822. Diag(Tok, diag::err_objc_unexpected_attr);
  823. SkipUntil(tok::semi); // FIXME: better skip?
  824. return DeclGroupPtrTy();
  825. }
  826. DS.abort();
  827. const char *PrevSpec = nullptr;
  828. unsigned DiagID;
  829. if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
  830. Actions.getASTContext().getPrintingPolicy()))
  831. Diag(AtLoc, DiagID) << PrevSpec;
  832. if (Tok.isObjCAtKeyword(tok::objc_protocol))
  833. return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
  834. return Actions.ConvertDeclToDeclGroup(
  835. ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
  836. }
  837. // If the declspec consisted only of 'extern' and we have a string
  838. // literal following it, this must be a C++ linkage specifier like
  839. // 'extern "C"'.
  840. if (!getLangOpts().HLSL && getLangOpts().CPlusPlus && isTokenStringLiteral() && // HLSL Change - disallow extern "C"
  841. DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
  842. DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
  843. Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
  844. return Actions.ConvertDeclToDeclGroup(TheDecl);
  845. }
  846. return ParseDeclGroup(DS, Declarator::FileContext);
  847. }
  848. Parser::DeclGroupPtrTy
  849. Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
  850. ParsingDeclSpec *DS,
  851. AccessSpecifier AS) {
  852. if (DS) {
  853. return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
  854. } else {
  855. ParsingDeclSpec PDS(*this);
  856. // Must temporarily exit the objective-c container scope for
  857. // parsing c constructs and re-enter objc container scope
  858. // afterwards.
  859. ObjCDeclContextSwitch ObjCDC(*this);
  860. return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
  861. }
  862. }
  863. /// ParseFunctionDefinition - We parsed and verified that the specified
  864. /// Declarator is well formed. If this is a K&R-style function, read the
  865. /// parameters declaration-list, then start the compound-statement.
  866. ///
  867. /// function-definition: [C99 6.9.1]
  868. /// decl-specs declarator declaration-list[opt] compound-statement
  869. /// [C90] function-definition: [C99 6.7.1] - implicit int result
  870. /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
  871. /// [C++] function-definition: [C++ 8.4]
  872. /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
  873. /// function-body
  874. /// [C++] function-definition: [C++ 8.4]
  875. /// decl-specifier-seq[opt] declarator function-try-block
  876. ///
  877. Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
  878. const ParsedTemplateInfo &TemplateInfo,
  879. LateParsedAttrList *LateParsedAttrs) {
  880. // Poison SEH identifiers so they are flagged as illegal in function bodies.
  881. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  882. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  883. // If this is C90 and the declspecs were completely missing, fudge in an
  884. // implicit int. We do this here because this is the only place where
  885. // declaration-specifiers are completely optional in the grammar.
  886. if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
  887. const char *PrevSpec;
  888. unsigned DiagID;
  889. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  890. D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
  891. D.getIdentifierLoc(),
  892. PrevSpec, DiagID,
  893. Policy);
  894. D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
  895. }
  896. // If this declaration was formed with a K&R-style identifier list for the
  897. // arguments, parse declarations for all of the args next.
  898. // int foo(a,b) int a; float b; {}
  899. if (!getLangOpts().HLSL && FTI.isKNRPrototype()) // HLSL Change - there is no support for K&R-style functions
  900. ParseKNRParamDeclarations(D);
  901. // We should have either an opening brace or, in a C++ constructor,
  902. // we may have a colon.
  903. if (Tok.isNot(tok::l_brace) &&
  904. ((getLangOpts().HLSL && Tok.isNot(tok::colon)) || // HLSL Change - for HLSL, only allow ':', not try or =
  905. (!getLangOpts().CPlusPlus ||
  906. (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
  907. Tok.isNot(tok::equal))))) {
  908. Diag(Tok, diag::err_expected_fn_body);
  909. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  910. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  911. // If we didn't find the '{', bail out.
  912. if (Tok.isNot(tok::l_brace))
  913. return nullptr;
  914. }
  915. // Check to make sure that any normal attributes are allowed to be on
  916. // a definition. Late parsed attributes are checked at the end.
  917. if (Tok.isNot(tok::equal)) {
  918. AttributeList *DtorAttrs = D.getAttributes();
  919. while (DtorAttrs) {
  920. if (DtorAttrs->isKnownToGCC() &&
  921. !DtorAttrs->isCXX11Attribute()) {
  922. Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
  923. << DtorAttrs->getName();
  924. }
  925. DtorAttrs = DtorAttrs->getNext();
  926. }
  927. }
  928. // In delayed template parsing mode, for function template we consume the
  929. // tokens and store them for late parsing at the end of the translation unit.
  930. if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
  931. TemplateInfo.Kind == ParsedTemplateInfo::Template &&
  932. Actions.canDelayFunctionBody(D)) {
  933. MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
  934. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  935. Scope *ParentScope = getCurScope()->getParent();
  936. D.setFunctionDefinitionKind(FDK_Definition);
  937. Decl *DP = Actions.HandleDeclarator(ParentScope, D,
  938. TemplateParameterLists);
  939. D.complete(DP);
  940. D.getMutableDeclSpec().abort();
  941. CachedTokens Toks;
  942. LexTemplateFunctionForLateParsing(Toks);
  943. if (DP) {
  944. FunctionDecl *FnD = DP->getAsFunction();
  945. Actions.CheckForFunctionRedefinition(FnD);
  946. Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
  947. }
  948. return DP;
  949. }
  950. else if (CurParsedObjCImpl && !getLangOpts().HLSL && // HLSL Change - remove support for Obj-C parsing
  951. !TemplateInfo.TemplateParams &&
  952. (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
  953. Tok.is(tok::colon)) &&
  954. Actions.CurContext->isTranslationUnit()) {
  955. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  956. Scope *ParentScope = getCurScope()->getParent();
  957. D.setFunctionDefinitionKind(FDK_Definition);
  958. Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
  959. MultiTemplateParamsArg());
  960. D.complete(FuncDecl);
  961. D.getMutableDeclSpec().abort();
  962. if (FuncDecl) {
  963. // Consume the tokens and store them for later parsing.
  964. StashAwayMethodOrFunctionBodyTokens(FuncDecl);
  965. CurParsedObjCImpl->HasCFunction = true;
  966. return FuncDecl;
  967. }
  968. // FIXME: Should we really fall through here?
  969. }
  970. // Enter a scope for the function body.
  971. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
  972. // Tell the actions module that we have entered a function definition with the
  973. // specified Declarator for the function.
  974. Decl *Res = TemplateInfo.TemplateParams?
  975. Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
  976. *TemplateInfo.TemplateParams, D)
  977. : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
  978. // Break out of the ParsingDeclarator context before we parse the body.
  979. D.complete(Res);
  980. // Break out of the ParsingDeclSpec context, too. This const_cast is
  981. // safe because we're always the sole owner.
  982. D.getMutableDeclSpec().abort();
  983. if (!getLangOpts().HLSL && TryConsumeToken(tok::equal)) { // HLSL Change: this has already been rejected in this function
  984. assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
  985. bool Delete = false;
  986. SourceLocation KWLoc;
  987. if (TryConsumeToken(tok::kw_delete, KWLoc)) {
  988. Diag(KWLoc, getLangOpts().CPlusPlus11
  989. ? diag::warn_cxx98_compat_deleted_function
  990. : diag::ext_deleted_function);
  991. Actions.SetDeclDeleted(Res, KWLoc);
  992. Delete = true;
  993. } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
  994. Diag(KWLoc, getLangOpts().CPlusPlus11
  995. ? diag::warn_cxx98_compat_defaulted_function
  996. : diag::ext_defaulted_function);
  997. Actions.SetDeclDefaulted(Res, KWLoc);
  998. } else {
  999. llvm_unreachable("function definition after = not 'delete' or 'default'");
  1000. }
  1001. if (Tok.is(tok::comma)) {
  1002. Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
  1003. << Delete;
  1004. SkipUntil(tok::semi);
  1005. } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  1006. Delete ? "delete" : "default")) {
  1007. SkipUntil(tok::semi);
  1008. }
  1009. Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
  1010. Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
  1011. return Res;
  1012. }
  1013. if (Tok.is(tok::kw_try) && !getLangOpts().HLSL) // HLSL Change: this has already been rejected in this function
  1014. return ParseFunctionTryBlock(Res, BodyScope);
  1015. // If we have a colon, then we're probably parsing a C++
  1016. // ctor-initializer.
  1017. if (Tok.is(tok::colon)) {
  1018. ParseConstructorInitializer(Res);
  1019. // Recover from error.
  1020. if (!Tok.is(tok::l_brace)) {
  1021. BodyScope.Exit();
  1022. Actions.ActOnFinishFunctionBody(Res, nullptr);
  1023. return Res;
  1024. }
  1025. } else
  1026. Actions.ActOnDefaultCtorInitializers(Res);
  1027. // Late attributes are parsed in the same scope as the function body.
  1028. if (LateParsedAttrs)
  1029. ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
  1030. return ParseFunctionStatementBody(Res, BodyScope);
  1031. }
  1032. /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
  1033. /// types for a function with a K&R-style identifier list for arguments.
  1034. void Parser::ParseKNRParamDeclarations(Declarator &D) {
  1035. // We know that the top-level of this declarator is a function.
  1036. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  1037. // Enter function-declaration scope, limiting any declarators to the
  1038. // function prototype scope, including parameter declarators.
  1039. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
  1040. Scope::FunctionDeclarationScope | Scope::DeclScope);
  1041. // Read all the argument declarations.
  1042. while (isDeclarationSpecifier()) {
  1043. SourceLocation DSStart = Tok.getLocation();
  1044. // Parse the common declaration-specifiers piece.
  1045. DeclSpec DS(AttrFactory);
  1046. ParseDeclarationSpecifiers(DS);
  1047. // C99 6.9.1p6: 'each declaration in the declaration list shall have at
  1048. // least one declarator'.
  1049. // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
  1050. // the declarations though. It's trivial to ignore them, really hard to do
  1051. // anything else with them.
  1052. if (TryConsumeToken(tok::semi)) {
  1053. Diag(DSStart, diag::err_declaration_does_not_declare_param);
  1054. continue;
  1055. }
  1056. // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
  1057. // than register.
  1058. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  1059. DS.getStorageClassSpec() != DeclSpec::SCS_register) {
  1060. Diag(DS.getStorageClassSpecLoc(),
  1061. diag::err_invalid_storage_class_in_func_decl);
  1062. DS.ClearStorageClassSpecs();
  1063. }
  1064. if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
  1065. Diag(DS.getThreadStorageClassSpecLoc(),
  1066. diag::err_invalid_storage_class_in_func_decl);
  1067. DS.ClearStorageClassSpecs();
  1068. }
  1069. // Parse the first declarator attached to this declspec.
  1070. Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
  1071. ParseDeclarator(ParmDeclarator);
  1072. // Handle the full declarator list.
  1073. while (1) {
  1074. // If attributes are present, parse them.
  1075. MaybeParseGNUAttributes(ParmDeclarator);
  1076. // Ask the actions module to compute the type for this declarator.
  1077. Decl *Param =
  1078. Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
  1079. if (Param &&
  1080. // A missing identifier has already been diagnosed.
  1081. ParmDeclarator.getIdentifier()) {
  1082. // Scan the argument list looking for the correct param to apply this
  1083. // type.
  1084. for (unsigned i = 0; ; ++i) {
  1085. // C99 6.9.1p6: those declarators shall declare only identifiers from
  1086. // the identifier list.
  1087. if (i == FTI.NumParams) {
  1088. Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
  1089. << ParmDeclarator.getIdentifier();
  1090. break;
  1091. }
  1092. if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
  1093. // Reject redefinitions of parameters.
  1094. if (FTI.Params[i].Param) {
  1095. Diag(ParmDeclarator.getIdentifierLoc(),
  1096. diag::err_param_redefinition)
  1097. << ParmDeclarator.getIdentifier();
  1098. } else {
  1099. FTI.Params[i].Param = Param;
  1100. }
  1101. break;
  1102. }
  1103. }
  1104. }
  1105. // If we don't have a comma, it is either the end of the list (a ';') or
  1106. // an error, bail out.
  1107. if (Tok.isNot(tok::comma))
  1108. break;
  1109. ParmDeclarator.clear();
  1110. // Consume the comma.
  1111. ParmDeclarator.setCommaLoc(ConsumeToken());
  1112. // Parse the next declarator.
  1113. ParseDeclarator(ParmDeclarator);
  1114. }
  1115. // Consume ';' and continue parsing.
  1116. if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
  1117. continue;
  1118. // Otherwise recover by skipping to next semi or mandatory function body.
  1119. if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
  1120. break;
  1121. TryConsumeToken(tok::semi);
  1122. }
  1123. // The actions module must verify that all arguments were declared.
  1124. Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
  1125. }
  1126. /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
  1127. /// allowed to be a wide string, and is not subject to character translation.
  1128. ///
  1129. /// [GNU] asm-string-literal:
  1130. /// string-literal
  1131. ///
  1132. ExprResult Parser::ParseAsmStringLiteral() {
  1133. assert(!getLangOpts().HLSL); // HLSL Change - this point should be unreachable
  1134. if (!isTokenStringLiteral()) {
  1135. Diag(Tok, diag::err_expected_string_literal)
  1136. << /*Source='in...'*/0 << "'asm'";
  1137. return ExprError();
  1138. }
  1139. ExprResult AsmString(ParseStringLiteralExpression());
  1140. if (!AsmString.isInvalid()) {
  1141. const auto *SL = cast<StringLiteral>(AsmString.get());
  1142. if (!SL->isAscii()) {
  1143. Diag(Tok, diag::err_asm_operand_wide_string_literal)
  1144. << SL->isWide()
  1145. << SL->getSourceRange();
  1146. return ExprError();
  1147. }
  1148. }
  1149. return AsmString;
  1150. }
  1151. /// ParseSimpleAsm
  1152. ///
  1153. /// [GNU] simple-asm-expr:
  1154. /// 'asm' '(' asm-string-literal ')'
  1155. ///
  1156. ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
  1157. assert(!getLangOpts().HLSL); // HLSL Change - this point should be unreachable
  1158. assert(Tok.is(tok::kw_asm) && "Not an asm!");
  1159. SourceLocation Loc = ConsumeToken();
  1160. if (Tok.is(tok::kw_volatile)) {
  1161. // Remove from the end of 'asm' to the end of 'volatile'.
  1162. SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
  1163. PP.getLocForEndOfToken(Tok.getLocation()));
  1164. Diag(Tok, diag::warn_file_asm_volatile)
  1165. << FixItHint::CreateRemoval(RemovalRange);
  1166. ConsumeToken();
  1167. }
  1168. BalancedDelimiterTracker T(*this, tok::l_paren);
  1169. if (T.consumeOpen()) {
  1170. Diag(Tok, diag::err_expected_lparen_after) << "asm";
  1171. return ExprError();
  1172. }
  1173. ExprResult Result(ParseAsmStringLiteral());
  1174. if (!Result.isInvalid()) {
  1175. // Close the paren and get the location of the end bracket
  1176. T.consumeClose();
  1177. if (EndLoc)
  1178. *EndLoc = T.getCloseLocation();
  1179. } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
  1180. if (EndLoc)
  1181. *EndLoc = Tok.getLocation();
  1182. ConsumeParen();
  1183. }
  1184. return Result;
  1185. }
  1186. /// \brief Get the TemplateIdAnnotation from the token and put it in the
  1187. /// cleanup pool so that it gets destroyed when parsing the current top level
  1188. /// declaration is finished.
  1189. TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
  1190. assert(tok.is(tok::annot_template_id) && "Expected template-id token");
  1191. TemplateIdAnnotation *
  1192. Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
  1193. return Id;
  1194. }
  1195. void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
  1196. // Push the current token back into the token stream (or revert it if it is
  1197. // cached) and use an annotation scope token for current token.
  1198. if (PP.isBacktrackEnabled())
  1199. PP.RevertCachedTokens(1);
  1200. else
  1201. PP.EnterToken(Tok);
  1202. Tok.setKind(tok::annot_cxxscope);
  1203. Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
  1204. Tok.setAnnotationRange(SS.getRange());
  1205. // In case the tokens were cached, have Preprocessor replace them
  1206. // with the annotation token. We don't need to do this if we've
  1207. // just reverted back to a prior state.
  1208. if (IsNewAnnotation)
  1209. PP.AnnotateCachedTokens(Tok);
  1210. }
  1211. /// \brief Attempt to classify the name at the current token position. This may
  1212. /// form a type, scope or primary expression annotation, or replace the token
  1213. /// with a typo-corrected keyword. This is only appropriate when the current
  1214. /// name must refer to an entity which has already been declared.
  1215. ///
  1216. /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
  1217. /// and might possibly have a dependent nested name specifier.
  1218. /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
  1219. /// no typo correction will be performed.
  1220. Parser::AnnotatedNameKind
  1221. Parser::TryAnnotateName(bool IsAddressOfOperand,
  1222. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  1223. assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
  1224. const bool EnteringContext = false;
  1225. const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
  1226. CXXScopeSpec SS;
  1227. if (getLangOpts().CPlusPlus &&
  1228. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  1229. return ANK_Error;
  1230. if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
  1231. if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
  1232. !WasScopeAnnotation))
  1233. return ANK_Error;
  1234. // HLSL Change Starts - allow implicitly annotated templates
  1235. return (Tok.isNot(tok::annot_typename) || SS.isInvalid()) ? ANK_Unresolved : ANK_Success;
  1236. // HLSL Change End
  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. /*NextIsLess*/ true)) { // HLSL Change - additional flag
  1537. // Consume the identifier.
  1538. ConsumeToken();
  1539. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  1540. TemplateName)) {
  1541. // If an unrecoverable error occurred, we need to return true here,
  1542. // because the token stream is in a damaged state. We may not return
  1543. // a valid identifier.
  1544. return true;
  1545. }
  1546. }
  1547. }
  1548. // The current token, which is either an identifier or a
  1549. // template-id, is not part of the annotation. Fall through to
  1550. // push that token back into the stream and complete the C++ scope
  1551. // specifier annotation.
  1552. }
  1553. if (Tok.is(tok::annot_template_id)) {
  1554. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1555. if (TemplateId->Kind == TNK_Type_template) {
  1556. // A template-id that refers to a type was parsed into a
  1557. // template-id annotation in a context where we weren't allowed
  1558. // to produce a type annotation token. Update the template-id
  1559. // annotation token to a type annotation token now.
  1560. AnnotateTemplateIdTokenAsType();
  1561. return false;
  1562. }
  1563. }
  1564. if (SS.isEmpty())
  1565. return false;
  1566. // A C++ scope specifier that isn't followed by a typename.
  1567. AnnotateScopeToken(SS, IsNewScope);
  1568. return false;
  1569. }
  1570. /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
  1571. /// annotates C++ scope specifiers and template-ids. This returns
  1572. /// true if there was an error that could not be recovered from.
  1573. ///
  1574. /// Note that this routine emits an error if you call it with ::new or ::delete
  1575. /// as the current tokens, so only call it in contexts where these are invalid.
  1576. bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
  1577. assert(getLangOpts().CPlusPlus &&
  1578. "Call sites of this function should be guarded by checking for C++");
  1579. assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
  1580. (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
  1581. Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
  1582. "Cannot be a type or scope token!");
  1583. CXXScopeSpec SS;
  1584. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  1585. return true;
  1586. if (SS.isEmpty())
  1587. return false;
  1588. AnnotateScopeToken(SS, true);
  1589. return false;
  1590. }
  1591. bool Parser::isTokenEqualOrEqualTypo() {
  1592. tok::TokenKind Kind = Tok.getKind();
  1593. switch (Kind) {
  1594. default:
  1595. return false;
  1596. case tok::ampequal: // &=
  1597. case tok::starequal: // *=
  1598. case tok::plusequal: // +=
  1599. case tok::minusequal: // -=
  1600. case tok::exclaimequal: // !=
  1601. case tok::slashequal: // /=
  1602. case tok::percentequal: // %=
  1603. case tok::lessequal: // <=
  1604. case tok::lesslessequal: // <<=
  1605. case tok::greaterequal: // >=
  1606. case tok::greatergreaterequal: // >>=
  1607. case tok::caretequal: // ^=
  1608. case tok::pipeequal: // |=
  1609. case tok::equalequal: // ==
  1610. Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
  1611. << Kind
  1612. << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
  1613. case tok::equal:
  1614. return true;
  1615. }
  1616. }
  1617. SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
  1618. assert(Tok.is(tok::code_completion));
  1619. PrevTokLocation = Tok.getLocation();
  1620. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1621. if (S->getFlags() & Scope::FnScope) {
  1622. Actions.CodeCompleteOrdinaryName(getCurScope(),
  1623. Sema::PCC_RecoveryInFunction);
  1624. cutOffParsing();
  1625. return PrevTokLocation;
  1626. }
  1627. if (S->getFlags() & Scope::ClassScope) {
  1628. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
  1629. cutOffParsing();
  1630. return PrevTokLocation;
  1631. }
  1632. }
  1633. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
  1634. cutOffParsing();
  1635. return PrevTokLocation;
  1636. }
  1637. // Code-completion pass-through functions
  1638. void Parser::CodeCompleteDirective(bool InConditional) {
  1639. Actions.CodeCompletePreprocessorDirective(InConditional);
  1640. }
  1641. void Parser::CodeCompleteInConditionalExclusion() {
  1642. Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
  1643. }
  1644. void Parser::CodeCompleteMacroName(bool IsDefinition) {
  1645. Actions.CodeCompletePreprocessorMacroName(IsDefinition);
  1646. }
  1647. void Parser::CodeCompletePreprocessorExpression() {
  1648. Actions.CodeCompletePreprocessorExpression();
  1649. }
  1650. void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
  1651. MacroInfo *MacroInfo,
  1652. unsigned ArgumentIndex) {
  1653. Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
  1654. ArgumentIndex);
  1655. }
  1656. void Parser::CodeCompleteNaturalLanguage() {
  1657. Actions.CodeCompleteNaturalLanguage();
  1658. }
  1659. bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
  1660. assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
  1661. "Expected '__if_exists' or '__if_not_exists'");
  1662. Result.IsIfExists = Tok.is(tok::kw___if_exists);
  1663. Result.KeywordLoc = ConsumeToken();
  1664. BalancedDelimiterTracker T(*this, tok::l_paren);
  1665. if (T.consumeOpen()) {
  1666. Diag(Tok, diag::err_expected_lparen_after)
  1667. << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
  1668. return true;
  1669. }
  1670. // Parse nested-name-specifier.
  1671. if (getLangOpts().CPlusPlus)
  1672. ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
  1673. /*EnteringContext=*/false);
  1674. // Check nested-name specifier.
  1675. if (Result.SS.isInvalid()) {
  1676. T.skipToEnd();
  1677. return true;
  1678. }
  1679. // Parse the unqualified-id.
  1680. SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
  1681. if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
  1682. TemplateKWLoc, Result.Name)) {
  1683. T.skipToEnd();
  1684. return true;
  1685. }
  1686. if (T.consumeClose())
  1687. return true;
  1688. // Check if the symbol exists.
  1689. switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
  1690. Result.IsIfExists, Result.SS,
  1691. Result.Name)) {
  1692. case Sema::IER_Exists:
  1693. Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1694. break;
  1695. case Sema::IER_DoesNotExist:
  1696. Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
  1697. break;
  1698. case Sema::IER_Dependent:
  1699. Result.Behavior = IEB_Dependent;
  1700. break;
  1701. case Sema::IER_Error:
  1702. return true;
  1703. }
  1704. return false;
  1705. }
  1706. void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
  1707. IfExistsCondition Result;
  1708. if (ParseMicrosoftIfExistsCondition(Result))
  1709. return;
  1710. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  1711. if (Braces.consumeOpen()) {
  1712. Diag(Tok, diag::err_expected) << tok::l_brace;
  1713. return;
  1714. }
  1715. switch (Result.Behavior) {
  1716. case IEB_Parse:
  1717. // Parse declarations below.
  1718. break;
  1719. case IEB_Dependent:
  1720. llvm_unreachable("Cannot have a dependent external declaration");
  1721. case IEB_Skip:
  1722. Braces.skipToEnd();
  1723. return;
  1724. }
  1725. // Parse the declarations.
  1726. // FIXME: Support module import within __if_exists?
  1727. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  1728. ParsedAttributesWithRange attrs(AttrFactory);
  1729. MaybeParseCXX11Attributes(attrs);
  1730. assert(!getLangOpts().HLSL); // HLSL Change: in lieu of MaybeParseHLSLAttributes - if-exists not allowed
  1731. MaybeParseMicrosoftAttributes(attrs);
  1732. DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
  1733. if (Result && !getCurScope()->getParent())
  1734. Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
  1735. }
  1736. Braces.consumeClose();
  1737. }
  1738. Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
  1739. assert(Tok.isObjCAtKeyword(tok::objc_import) &&
  1740. "Improper start to module import");
  1741. SourceLocation ImportLoc = ConsumeToken();
  1742. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1743. // Parse the module path.
  1744. do {
  1745. if (!Tok.is(tok::identifier)) {
  1746. if (Tok.is(tok::code_completion)) {
  1747. Actions.CodeCompleteModuleImport(ImportLoc, Path);
  1748. cutOffParsing();
  1749. return DeclGroupPtrTy();
  1750. }
  1751. Diag(Tok, diag::err_module_expected_ident);
  1752. SkipUntil(tok::semi);
  1753. return DeclGroupPtrTy();
  1754. }
  1755. // Record this part of the module path.
  1756. Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
  1757. ConsumeToken();
  1758. if (Tok.is(tok::period)) {
  1759. ConsumeToken();
  1760. continue;
  1761. }
  1762. break;
  1763. } while (true);
  1764. if (PP.hadModuleLoaderFatalFailure()) {
  1765. // With a fatal failure in the module loader, we abort parsing.
  1766. cutOffParsing();
  1767. return DeclGroupPtrTy();
  1768. }
  1769. DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
  1770. ExpectAndConsumeSemi(diag::err_module_expected_semi);
  1771. if (Import.isInvalid())
  1772. return DeclGroupPtrTy();
  1773. return Actions.ConvertDeclToDeclGroup(Import.get());
  1774. }
  1775. bool BalancedDelimiterTracker::diagnoseOverflow() {
  1776. P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
  1777. << P.getLangOpts().BracketDepth;
  1778. P.Diag(P.Tok, diag::note_bracket_depth);
  1779. P.cutOffParsing();
  1780. return true;
  1781. }
  1782. bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
  1783. const char *Msg,
  1784. tok::TokenKind SkipToTok) {
  1785. LOpen = P.Tok.getLocation();
  1786. if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
  1787. if (SkipToTok != tok::unknown)
  1788. P.SkipUntil(SkipToTok, Parser::StopAtSemi);
  1789. return true;
  1790. }
  1791. if (getDepth() < MaxDepth)
  1792. return false;
  1793. return diagnoseOverflow();
  1794. }
  1795. bool BalancedDelimiterTracker::diagnoseMissingClose() {
  1796. assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
  1797. P.Diag(P.Tok, diag::err_expected) << Close;
  1798. P.Diag(LOpen, diag::note_matching) << Kind;
  1799. // If we're not already at some kind of closing bracket, skip to our closing
  1800. // token.
  1801. if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
  1802. P.Tok.isNot(tok::r_square) &&
  1803. P.SkipUntil(Close, FinalToken,
  1804. Parser::StopAtSemi | Parser::StopBeforeMatch) &&
  1805. P.Tok.is(Close))
  1806. LClose = P.ConsumeAnyToken();
  1807. return true;
  1808. }
  1809. void BalancedDelimiterTracker::skipToEnd() {
  1810. P.SkipUntil(Close, Parser::StopBeforeMatch);
  1811. consumeClose();
  1812. }