ParseTentative.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180
  1. //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the tentative parsing portions of the Parser
  10. // interfaces, for ambiguity resolution.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/Parser.h"
  14. #include "clang/Parse/ParseDiagnostic.h"
  15. #include "clang/Sema/ParsedTemplate.h"
  16. using namespace clang;
  17. /// isCXXDeclarationStatement - C++-specialized function that disambiguates
  18. /// between a declaration or an expression statement, when parsing function
  19. /// bodies. Returns true for declaration, false for expression.
  20. ///
  21. /// declaration-statement:
  22. /// block-declaration
  23. ///
  24. /// block-declaration:
  25. /// simple-declaration
  26. /// asm-definition
  27. /// namespace-alias-definition
  28. /// using-declaration
  29. /// using-directive
  30. /// [C++0x] static_assert-declaration
  31. ///
  32. /// asm-definition:
  33. /// 'asm' '(' string-literal ')' ';'
  34. ///
  35. /// namespace-alias-definition:
  36. /// 'namespace' identifier = qualified-namespace-specifier ';'
  37. ///
  38. /// using-declaration:
  39. /// 'using' typename[opt] '::'[opt] nested-name-specifier
  40. /// unqualified-id ';'
  41. /// 'using' '::' unqualified-id ;
  42. ///
  43. /// using-directive:
  44. /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
  45. /// namespace-name ';'
  46. ///
  47. bool Parser::isCXXDeclarationStatement() {
  48. switch (Tok.getKind()) {
  49. // asm-definition
  50. case tok::kw_asm:
  51. // namespace-alias-definition
  52. case tok::kw_namespace:
  53. // using-declaration
  54. // using-directive
  55. case tok::kw_using:
  56. // static_assert-declaration
  57. case tok::kw_static_assert:
  58. case tok::kw__Static_assert:
  59. return true;
  60. // simple-declaration
  61. default:
  62. return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
  63. }
  64. }
  65. /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
  66. /// between a simple-declaration or an expression-statement.
  67. /// If during the disambiguation process a parsing error is encountered,
  68. /// the function returns true to let the declaration parsing code handle it.
  69. /// Returns false if the statement is disambiguated as expression.
  70. ///
  71. /// simple-declaration:
  72. /// decl-specifier-seq init-declarator-list[opt] ';'
  73. /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
  74. /// brace-or-equal-initializer ';' [C++17]
  75. ///
  76. /// (if AllowForRangeDecl specified)
  77. /// for ( for-range-declaration : for-range-initializer ) statement
  78. ///
  79. /// for-range-declaration:
  80. /// decl-specifier-seq declarator
  81. /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
  82. ///
  83. /// In any of the above cases there can be a preceding attribute-specifier-seq,
  84. /// but the caller is expected to handle that.
  85. bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
  86. // C++ 6.8p1:
  87. // There is an ambiguity in the grammar involving expression-statements and
  88. // declarations: An expression-statement with a function-style explicit type
  89. // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
  90. // from a declaration where the first declarator starts with a '('. In those
  91. // cases the statement is a declaration. [Note: To disambiguate, the whole
  92. // statement might have to be examined to determine if it is an
  93. // expression-statement or a declaration].
  94. // C++ 6.8p3:
  95. // The disambiguation is purely syntactic; that is, the meaning of the names
  96. // occurring in such a statement, beyond whether they are type-names or not,
  97. // is not generally used in or changed by the disambiguation. Class
  98. // templates are instantiated as necessary to determine if a qualified name
  99. // is a type-name. Disambiguation precedes parsing, and a statement
  100. // disambiguated as a declaration may be an ill-formed declaration.
  101. // We don't have to parse all of the decl-specifier-seq part. There's only
  102. // an ambiguity if the first decl-specifier is
  103. // simple-type-specifier/typename-specifier followed by a '(', which may
  104. // indicate a function-style cast expression.
  105. // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
  106. // a case.
  107. bool InvalidAsDeclaration = false;
  108. TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
  109. &InvalidAsDeclaration);
  110. if (TPR != TPResult::Ambiguous)
  111. return TPR != TPResult::False; // Returns true for TPResult::True or
  112. // TPResult::Error.
  113. // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
  114. // and so gets some cases wrong. We can't carry on if we've already seen
  115. // something which makes this statement invalid as a declaration in this case,
  116. // since it can cause us to misparse valid code. Revisit this once
  117. // TryParseInitDeclaratorList is fixed.
  118. if (InvalidAsDeclaration)
  119. return false;
  120. // FIXME: Add statistics about the number of ambiguous statements encountered
  121. // and how they were resolved (number of declarations+number of expressions).
  122. // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
  123. // or an identifier which doesn't resolve as anything. We need tentative
  124. // parsing...
  125. {
  126. RevertingTentativeParsingAction PA(*this);
  127. TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
  128. }
  129. // In case of an error, let the declaration parsing code handle it.
  130. if (TPR == TPResult::Error)
  131. return true;
  132. // Declarations take precedence over expressions.
  133. if (TPR == TPResult::Ambiguous)
  134. TPR = TPResult::True;
  135. assert(TPR == TPResult::True || TPR == TPResult::False);
  136. return TPR == TPResult::True;
  137. }
  138. /// Try to consume a token sequence that we've already identified as
  139. /// (potentially) starting a decl-specifier.
  140. Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
  141. switch (Tok.getKind()) {
  142. case tok::kw__Atomic:
  143. if (NextToken().isNot(tok::l_paren)) {
  144. ConsumeToken();
  145. break;
  146. }
  147. LLVM_FALLTHROUGH;
  148. case tok::kw_typeof:
  149. case tok::kw___attribute:
  150. case tok::kw___underlying_type: {
  151. ConsumeToken();
  152. if (Tok.isNot(tok::l_paren))
  153. return TPResult::Error;
  154. ConsumeParen();
  155. if (!SkipUntil(tok::r_paren))
  156. return TPResult::Error;
  157. break;
  158. }
  159. case tok::kw_class:
  160. case tok::kw_struct:
  161. case tok::kw_union:
  162. case tok::kw___interface:
  163. case tok::kw_enum:
  164. // elaborated-type-specifier:
  165. // class-key attribute-specifier-seq[opt]
  166. // nested-name-specifier[opt] identifier
  167. // class-key nested-name-specifier[opt] template[opt] simple-template-id
  168. // enum nested-name-specifier[opt] identifier
  169. //
  170. // FIXME: We don't support class-specifiers nor enum-specifiers here.
  171. ConsumeToken();
  172. // Skip attributes.
  173. if (!TrySkipAttributes())
  174. return TPResult::Error;
  175. if (TryAnnotateOptionalCXXScopeToken())
  176. return TPResult::Error;
  177. if (Tok.is(tok::annot_cxxscope))
  178. ConsumeAnnotationToken();
  179. if (Tok.is(tok::identifier))
  180. ConsumeToken();
  181. else if (Tok.is(tok::annot_template_id))
  182. ConsumeAnnotationToken();
  183. else
  184. return TPResult::Error;
  185. break;
  186. case tok::annot_cxxscope:
  187. ConsumeAnnotationToken();
  188. LLVM_FALLTHROUGH;
  189. default:
  190. ConsumeAnyToken();
  191. if (getLangOpts().ObjC && Tok.is(tok::less))
  192. return TryParseProtocolQualifiers();
  193. break;
  194. }
  195. return TPResult::Ambiguous;
  196. }
  197. /// simple-declaration:
  198. /// decl-specifier-seq init-declarator-list[opt] ';'
  199. ///
  200. /// (if AllowForRangeDecl specified)
  201. /// for ( for-range-declaration : for-range-initializer ) statement
  202. /// for-range-declaration:
  203. /// attribute-specifier-seqopt type-specifier-seq declarator
  204. ///
  205. Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
  206. if (TryConsumeDeclarationSpecifier() == TPResult::Error)
  207. return TPResult::Error;
  208. // Two decl-specifiers in a row conclusively disambiguate this as being a
  209. // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
  210. // overwhelmingly common case that the next token is a '('.
  211. if (Tok.isNot(tok::l_paren)) {
  212. TPResult TPR = isCXXDeclarationSpecifier();
  213. if (TPR == TPResult::Ambiguous)
  214. return TPResult::True;
  215. if (TPR == TPResult::True || TPR == TPResult::Error)
  216. return TPR;
  217. assert(TPR == TPResult::False);
  218. }
  219. TPResult TPR = TryParseInitDeclaratorList();
  220. if (TPR != TPResult::Ambiguous)
  221. return TPR;
  222. if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
  223. return TPResult::False;
  224. return TPResult::Ambiguous;
  225. }
  226. /// Tentatively parse an init-declarator-list in order to disambiguate it from
  227. /// an expression.
  228. ///
  229. /// init-declarator-list:
  230. /// init-declarator
  231. /// init-declarator-list ',' init-declarator
  232. ///
  233. /// init-declarator:
  234. /// declarator initializer[opt]
  235. /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
  236. ///
  237. /// initializer:
  238. /// brace-or-equal-initializer
  239. /// '(' expression-list ')'
  240. ///
  241. /// brace-or-equal-initializer:
  242. /// '=' initializer-clause
  243. /// [C++11] braced-init-list
  244. ///
  245. /// initializer-clause:
  246. /// assignment-expression
  247. /// braced-init-list
  248. ///
  249. /// braced-init-list:
  250. /// '{' initializer-list ','[opt] '}'
  251. /// '{' '}'
  252. ///
  253. Parser::TPResult Parser::TryParseInitDeclaratorList() {
  254. while (true) {
  255. // declarator
  256. TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
  257. if (TPR != TPResult::Ambiguous)
  258. return TPR;
  259. // [GNU] simple-asm-expr[opt] attributes[opt]
  260. if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
  261. return TPResult::True;
  262. // initializer[opt]
  263. if (Tok.is(tok::l_paren)) {
  264. // Parse through the parens.
  265. ConsumeParen();
  266. if (!SkipUntil(tok::r_paren, StopAtSemi))
  267. return TPResult::Error;
  268. } else if (Tok.is(tok::l_brace)) {
  269. // A left-brace here is sufficient to disambiguate the parse; an
  270. // expression can never be followed directly by a braced-init-list.
  271. return TPResult::True;
  272. } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
  273. // MSVC and g++ won't examine the rest of declarators if '=' is
  274. // encountered; they just conclude that we have a declaration.
  275. // EDG parses the initializer completely, which is the proper behavior
  276. // for this case.
  277. //
  278. // At present, Clang follows MSVC and g++, since the parser does not have
  279. // the ability to parse an expression fully without recording the
  280. // results of that parse.
  281. // FIXME: Handle this case correctly.
  282. //
  283. // Also allow 'in' after an Objective-C declaration as in:
  284. // for (int (^b)(void) in array). Ideally this should be done in the
  285. // context of parsing for-init-statement of a foreach statement only. But,
  286. // in any other context 'in' is invalid after a declaration and parser
  287. // issues the error regardless of outcome of this decision.
  288. // FIXME: Change if above assumption does not hold.
  289. return TPResult::True;
  290. }
  291. if (!TryConsumeToken(tok::comma))
  292. break;
  293. }
  294. return TPResult::Ambiguous;
  295. }
  296. struct Parser::ConditionDeclarationOrInitStatementState {
  297. Parser &P;
  298. bool CanBeExpression = true;
  299. bool CanBeCondition = true;
  300. bool CanBeInitStatement;
  301. bool CanBeForRangeDecl;
  302. ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement,
  303. bool CanBeForRangeDecl)
  304. : P(P), CanBeInitStatement(CanBeInitStatement),
  305. CanBeForRangeDecl(CanBeForRangeDecl) {}
  306. bool resolved() {
  307. return CanBeExpression + CanBeCondition + CanBeInitStatement +
  308. CanBeForRangeDecl < 2;
  309. }
  310. void markNotExpression() {
  311. CanBeExpression = false;
  312. if (!resolved()) {
  313. // FIXME: Unify the parsing codepaths for condition variables and
  314. // simple-declarations so that we don't need to eagerly figure out which
  315. // kind we have here. (Just parse init-declarators until we reach a
  316. // semicolon or right paren.)
  317. RevertingTentativeParsingAction PA(P);
  318. if (CanBeForRangeDecl) {
  319. // Skip until we hit a ')', ';', or a ':' with no matching '?'.
  320. // The final case is a for range declaration, the rest are not.
  321. unsigned QuestionColonDepth = 0;
  322. while (true) {
  323. P.SkipUntil({tok::r_paren, tok::semi, tok::question, tok::colon},
  324. StopBeforeMatch);
  325. if (P.Tok.is(tok::question))
  326. ++QuestionColonDepth;
  327. else if (P.Tok.is(tok::colon)) {
  328. if (QuestionColonDepth)
  329. --QuestionColonDepth;
  330. else {
  331. CanBeCondition = CanBeInitStatement = false;
  332. return;
  333. }
  334. } else {
  335. CanBeForRangeDecl = false;
  336. break;
  337. }
  338. P.ConsumeToken();
  339. }
  340. } else {
  341. // Just skip until we hit a ')' or ';'.
  342. P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
  343. }
  344. if (P.Tok.isNot(tok::r_paren))
  345. CanBeCondition = CanBeForRangeDecl = false;
  346. if (P.Tok.isNot(tok::semi))
  347. CanBeInitStatement = false;
  348. }
  349. }
  350. bool markNotCondition() {
  351. CanBeCondition = false;
  352. return resolved();
  353. }
  354. bool markNotForRangeDecl() {
  355. CanBeForRangeDecl = false;
  356. return resolved();
  357. }
  358. bool update(TPResult IsDecl) {
  359. switch (IsDecl) {
  360. case TPResult::True:
  361. markNotExpression();
  362. assert(resolved() && "can't continue after tentative parsing bails out");
  363. break;
  364. case TPResult::False:
  365. CanBeCondition = CanBeInitStatement = CanBeForRangeDecl = false;
  366. break;
  367. case TPResult::Ambiguous:
  368. break;
  369. case TPResult::Error:
  370. CanBeExpression = CanBeCondition = CanBeInitStatement =
  371. CanBeForRangeDecl = false;
  372. break;
  373. }
  374. return resolved();
  375. }
  376. ConditionOrInitStatement result() const {
  377. assert(CanBeExpression + CanBeCondition + CanBeInitStatement +
  378. CanBeForRangeDecl < 2 &&
  379. "result called but not yet resolved");
  380. if (CanBeExpression)
  381. return ConditionOrInitStatement::Expression;
  382. if (CanBeCondition)
  383. return ConditionOrInitStatement::ConditionDecl;
  384. if (CanBeInitStatement)
  385. return ConditionOrInitStatement::InitStmtDecl;
  386. if (CanBeForRangeDecl)
  387. return ConditionOrInitStatement::ForRangeDecl;
  388. return ConditionOrInitStatement::Error;
  389. }
  390. };
  391. bool Parser::isEnumBase(bool AllowSemi) {
  392. assert(Tok.is(tok::colon) && "should be looking at the ':'");
  393. RevertingTentativeParsingAction PA(*this);
  394. // ':'
  395. ConsumeToken();
  396. // type-specifier-seq
  397. bool InvalidAsDeclSpec = false;
  398. // FIXME: We could disallow non-type decl-specifiers here, but it makes no
  399. // difference: those specifiers are ill-formed regardless of the
  400. // interpretation.
  401. TPResult R = isCXXDeclarationSpecifier(/*BracedCastResult*/ TPResult::True,
  402. &InvalidAsDeclSpec);
  403. if (R == TPResult::Ambiguous) {
  404. // We either have a decl-specifier followed by '(' or an undeclared
  405. // identifier.
  406. if (TryConsumeDeclarationSpecifier() == TPResult::Error)
  407. return true;
  408. // If we get to the end of the enum-base, we hit either a '{' or a ';'.
  409. // Don't bother checking the enumerator-list.
  410. if (Tok.is(tok::l_brace) || (AllowSemi && Tok.is(tok::semi)))
  411. return true;
  412. // A second decl-specifier unambiguously indicatges an enum-base.
  413. R = isCXXDeclarationSpecifier(TPResult::True, &InvalidAsDeclSpec);
  414. }
  415. return R != TPResult::False;
  416. }
  417. /// Disambiguates between a declaration in a condition, a
  418. /// simple-declaration in an init-statement, and an expression for
  419. /// a condition of a if/switch statement.
  420. ///
  421. /// condition:
  422. /// expression
  423. /// type-specifier-seq declarator '=' assignment-expression
  424. /// [C++11] type-specifier-seq declarator '=' initializer-clause
  425. /// [C++11] type-specifier-seq declarator braced-init-list
  426. /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
  427. /// '=' assignment-expression
  428. /// simple-declaration:
  429. /// decl-specifier-seq init-declarator-list[opt] ';'
  430. ///
  431. /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
  432. /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
  433. /// 'int(x);' (a simple-declaration in an init-statement).
  434. Parser::ConditionOrInitStatement
  435. Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement,
  436. bool CanBeForRangeDecl) {
  437. ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement,
  438. CanBeForRangeDecl);
  439. if (CanBeInitStatement && Tok.is(tok::kw_using))
  440. return ConditionOrInitStatement::InitStmtDecl;
  441. if (State.update(isCXXDeclarationSpecifier()))
  442. return State.result();
  443. // It might be a declaration; we need tentative parsing.
  444. RevertingTentativeParsingAction PA(*this);
  445. // FIXME: A tag definition unambiguously tells us this is an init-statement.
  446. if (State.update(TryConsumeDeclarationSpecifier()))
  447. return State.result();
  448. assert(Tok.is(tok::l_paren) && "Expected '('");
  449. while (true) {
  450. // Consume a declarator.
  451. if (State.update(TryParseDeclarator(false/*mayBeAbstract*/)))
  452. return State.result();
  453. // Attributes, asm label, or an initializer imply this is not an expression.
  454. // FIXME: Disambiguate properly after an = instead of assuming that it's a
  455. // valid declaration.
  456. if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) ||
  457. (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) {
  458. State.markNotExpression();
  459. return State.result();
  460. }
  461. // A colon here identifies a for-range declaration.
  462. if (State.CanBeForRangeDecl && Tok.is(tok::colon))
  463. return ConditionOrInitStatement::ForRangeDecl;
  464. // At this point, it can't be a condition any more, because a condition
  465. // must have a brace-or-equal-initializer.
  466. if (State.markNotCondition())
  467. return State.result();
  468. // Likewise, it can't be a for-range declaration any more.
  469. if (State.markNotForRangeDecl())
  470. return State.result();
  471. // A parenthesized initializer could be part of an expression or a
  472. // simple-declaration.
  473. if (Tok.is(tok::l_paren)) {
  474. ConsumeParen();
  475. SkipUntil(tok::r_paren, StopAtSemi);
  476. }
  477. if (!TryConsumeToken(tok::comma))
  478. break;
  479. }
  480. // We reached the end. If it can now be some kind of decl, then it is.
  481. if (State.CanBeCondition && Tok.is(tok::r_paren))
  482. return ConditionOrInitStatement::ConditionDecl;
  483. else if (State.CanBeInitStatement && Tok.is(tok::semi))
  484. return ConditionOrInitStatement::InitStmtDecl;
  485. else
  486. return ConditionOrInitStatement::Expression;
  487. }
  488. /// Determine whether the next set of tokens contains a type-id.
  489. ///
  490. /// The context parameter states what context we're parsing right
  491. /// now, which affects how this routine copes with the token
  492. /// following the type-id. If the context is TypeIdInParens, we have
  493. /// already parsed the '(' and we will cease lookahead when we hit
  494. /// the corresponding ')'. If the context is
  495. /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
  496. /// before this template argument, and will cease lookahead when we
  497. /// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
  498. /// preceding such. Returns true for a type-id and false for an expression.
  499. /// If during the disambiguation process a parsing error is encountered,
  500. /// the function returns true to let the declaration parsing code handle it.
  501. ///
  502. /// type-id:
  503. /// type-specifier-seq abstract-declarator[opt]
  504. ///
  505. bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
  506. isAmbiguous = false;
  507. // C++ 8.2p2:
  508. // The ambiguity arising from the similarity between a function-style cast and
  509. // a type-id can occur in different contexts. The ambiguity appears as a
  510. // choice between a function-style cast expression and a declaration of a
  511. // type. The resolution is that any construct that could possibly be a type-id
  512. // in its syntactic context shall be considered a type-id.
  513. TPResult TPR = isCXXDeclarationSpecifier();
  514. if (TPR != TPResult::Ambiguous)
  515. return TPR != TPResult::False; // Returns true for TPResult::True or
  516. // TPResult::Error.
  517. // FIXME: Add statistics about the number of ambiguous statements encountered
  518. // and how they were resolved (number of declarations+number of expressions).
  519. // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
  520. // We need tentative parsing...
  521. RevertingTentativeParsingAction PA(*this);
  522. // type-specifier-seq
  523. TryConsumeDeclarationSpecifier();
  524. assert(Tok.is(tok::l_paren) && "Expected '('");
  525. // declarator
  526. TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
  527. // In case of an error, let the declaration parsing code handle it.
  528. if (TPR == TPResult::Error)
  529. TPR = TPResult::True;
  530. if (TPR == TPResult::Ambiguous) {
  531. // We are supposed to be inside parens, so if after the abstract declarator
  532. // we encounter a ')' this is a type-id, otherwise it's an expression.
  533. if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
  534. TPR = TPResult::True;
  535. isAmbiguous = true;
  536. // We are supposed to be inside a template argument, so if after
  537. // the abstract declarator we encounter a '>', '>>' (in C++0x), or
  538. // ','; or, in C++0x, an ellipsis immediately preceding such, this
  539. // is a type-id. Otherwise, it's an expression.
  540. } else if (Context == TypeIdAsTemplateArgument &&
  541. (Tok.isOneOf(tok::greater, tok::comma) ||
  542. (getLangOpts().CPlusPlus11 &&
  543. (Tok.isOneOf(tok::greatergreater,
  544. tok::greatergreatergreater) ||
  545. (Tok.is(tok::ellipsis) &&
  546. NextToken().isOneOf(tok::greater, tok::greatergreater,
  547. tok::greatergreatergreater,
  548. tok::comma)))))) {
  549. TPR = TPResult::True;
  550. isAmbiguous = true;
  551. } else
  552. TPR = TPResult::False;
  553. }
  554. assert(TPR == TPResult::True || TPR == TPResult::False);
  555. return TPR == TPResult::True;
  556. }
  557. /// Returns true if this is a C++11 attribute-specifier. Per
  558. /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
  559. /// always introduce an attribute. In Objective-C++11, this rule does not
  560. /// apply if either '[' begins a message-send.
  561. ///
  562. /// If Disambiguate is true, we try harder to determine whether a '[[' starts
  563. /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
  564. ///
  565. /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
  566. /// Obj-C message send or the start of an attribute. Otherwise, we assume it
  567. /// is not an Obj-C message send.
  568. ///
  569. /// C++11 [dcl.attr.grammar]:
  570. ///
  571. /// attribute-specifier:
  572. /// '[' '[' attribute-list ']' ']'
  573. /// alignment-specifier
  574. ///
  575. /// attribute-list:
  576. /// attribute[opt]
  577. /// attribute-list ',' attribute[opt]
  578. /// attribute '...'
  579. /// attribute-list ',' attribute '...'
  580. ///
  581. /// attribute:
  582. /// attribute-token attribute-argument-clause[opt]
  583. ///
  584. /// attribute-token:
  585. /// identifier
  586. /// identifier '::' identifier
  587. ///
  588. /// attribute-argument-clause:
  589. /// '(' balanced-token-seq ')'
  590. Parser::CXX11AttributeKind
  591. Parser::isCXX11AttributeSpecifier(bool Disambiguate,
  592. bool OuterMightBeMessageSend) {
  593. if (Tok.is(tok::kw_alignas))
  594. return CAK_AttributeSpecifier;
  595. if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
  596. return CAK_NotAttributeSpecifier;
  597. // No tentative parsing if we don't need to look for ']]' or a lambda.
  598. if (!Disambiguate && !getLangOpts().ObjC)
  599. return CAK_AttributeSpecifier;
  600. // '[[using ns: ...]]' is an attribute.
  601. if (GetLookAheadToken(2).is(tok::kw_using))
  602. return CAK_AttributeSpecifier;
  603. RevertingTentativeParsingAction PA(*this);
  604. // Opening brackets were checked for above.
  605. ConsumeBracket();
  606. if (!getLangOpts().ObjC) {
  607. ConsumeBracket();
  608. bool IsAttribute = SkipUntil(tok::r_square);
  609. IsAttribute &= Tok.is(tok::r_square);
  610. return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
  611. }
  612. // In Obj-C++11, we need to distinguish four situations:
  613. // 1a) int x[[attr]]; C++11 attribute.
  614. // 1b) [[attr]]; C++11 statement attribute.
  615. // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
  616. // 3a) int x[[obj get]]; Message send in array size/index.
  617. // 3b) [[Class alloc] init]; Message send in message send.
  618. // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
  619. // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
  620. // Check to see if this is a lambda-expression.
  621. // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
  622. // into the tentative attribute parse below.
  623. {
  624. RevertingTentativeParsingAction LambdaTPA(*this);
  625. LambdaIntroducer Intro;
  626. LambdaIntroducerTentativeParse Tentative;
  627. if (ParseLambdaIntroducer(Intro, &Tentative)) {
  628. // We hit a hard error after deciding this was not an attribute.
  629. // FIXME: Don't parse and annotate expressions when disambiguating
  630. // against an attribute.
  631. return CAK_NotAttributeSpecifier;
  632. }
  633. switch (Tentative) {
  634. case LambdaIntroducerTentativeParse::MessageSend:
  635. // Case 3: The inner construct is definitely a message send, so the
  636. // outer construct is definitely not an attribute.
  637. return CAK_NotAttributeSpecifier;
  638. case LambdaIntroducerTentativeParse::Success:
  639. case LambdaIntroducerTentativeParse::Incomplete:
  640. // This is a lambda-introducer or attribute-specifier.
  641. if (Tok.is(tok::r_square))
  642. // Case 1: C++11 attribute.
  643. return CAK_AttributeSpecifier;
  644. if (OuterMightBeMessageSend)
  645. // Case 4: Lambda in message send.
  646. return CAK_NotAttributeSpecifier;
  647. // Case 2: Lambda in array size / index.
  648. return CAK_InvalidAttributeSpecifier;
  649. case LambdaIntroducerTentativeParse::Invalid:
  650. // No idea what this is; we couldn't parse it as a lambda-introducer.
  651. // Might still be an attribute-specifier or a message send.
  652. break;
  653. }
  654. }
  655. ConsumeBracket();
  656. // If we don't have a lambda-introducer, then we have an attribute or a
  657. // message-send.
  658. bool IsAttribute = true;
  659. while (Tok.isNot(tok::r_square)) {
  660. if (Tok.is(tok::comma)) {
  661. // Case 1: Stray commas can only occur in attributes.
  662. return CAK_AttributeSpecifier;
  663. }
  664. // Parse the attribute-token, if present.
  665. // C++11 [dcl.attr.grammar]:
  666. // If a keyword or an alternative token that satisfies the syntactic
  667. // requirements of an identifier is contained in an attribute-token,
  668. // it is considered an identifier.
  669. SourceLocation Loc;
  670. if (!TryParseCXX11AttributeIdentifier(Loc)) {
  671. IsAttribute = false;
  672. break;
  673. }
  674. if (Tok.is(tok::coloncolon)) {
  675. ConsumeToken();
  676. if (!TryParseCXX11AttributeIdentifier(Loc)) {
  677. IsAttribute = false;
  678. break;
  679. }
  680. }
  681. // Parse the attribute-argument-clause, if present.
  682. if (Tok.is(tok::l_paren)) {
  683. ConsumeParen();
  684. if (!SkipUntil(tok::r_paren)) {
  685. IsAttribute = false;
  686. break;
  687. }
  688. }
  689. TryConsumeToken(tok::ellipsis);
  690. if (!TryConsumeToken(tok::comma))
  691. break;
  692. }
  693. // An attribute must end ']]'.
  694. if (IsAttribute) {
  695. if (Tok.is(tok::r_square)) {
  696. ConsumeBracket();
  697. IsAttribute = Tok.is(tok::r_square);
  698. } else {
  699. IsAttribute = false;
  700. }
  701. }
  702. if (IsAttribute)
  703. // Case 1: C++11 statement attribute.
  704. return CAK_AttributeSpecifier;
  705. // Case 3: Message send.
  706. return CAK_NotAttributeSpecifier;
  707. }
  708. bool Parser::TrySkipAttributes() {
  709. while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
  710. tok::kw_alignas)) {
  711. if (Tok.is(tok::l_square)) {
  712. ConsumeBracket();
  713. if (Tok.isNot(tok::l_square))
  714. return false;
  715. ConsumeBracket();
  716. if (!SkipUntil(tok::r_square) || Tok.isNot(tok::r_square))
  717. return false;
  718. // Note that explicitly checking for `[[` and `]]` allows to fail as
  719. // expected in the case of the Objective-C message send syntax.
  720. ConsumeBracket();
  721. } else {
  722. ConsumeToken();
  723. if (Tok.isNot(tok::l_paren))
  724. return false;
  725. ConsumeParen();
  726. if (!SkipUntil(tok::r_paren))
  727. return false;
  728. }
  729. }
  730. return true;
  731. }
  732. Parser::TPResult Parser::TryParsePtrOperatorSeq() {
  733. while (true) {
  734. if (TryAnnotateOptionalCXXScopeToken(true))
  735. return TPResult::Error;
  736. if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
  737. (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
  738. // ptr-operator
  739. ConsumeAnyToken();
  740. // Skip attributes.
  741. if (!TrySkipAttributes())
  742. return TPResult::Error;
  743. while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
  744. tok::kw__Nonnull, tok::kw__Nullable,
  745. tok::kw__Nullable_result, tok::kw__Null_unspecified,
  746. tok::kw__Atomic))
  747. ConsumeToken();
  748. } else {
  749. return TPResult::True;
  750. }
  751. }
  752. }
  753. /// operator-function-id:
  754. /// 'operator' operator
  755. ///
  756. /// operator: one of
  757. /// new delete new[] delete[] + - * / % ^ [...]
  758. ///
  759. /// conversion-function-id:
  760. /// 'operator' conversion-type-id
  761. ///
  762. /// conversion-type-id:
  763. /// type-specifier-seq conversion-declarator[opt]
  764. ///
  765. /// conversion-declarator:
  766. /// ptr-operator conversion-declarator[opt]
  767. ///
  768. /// literal-operator-id:
  769. /// 'operator' string-literal identifier
  770. /// 'operator' user-defined-string-literal
  771. Parser::TPResult Parser::TryParseOperatorId() {
  772. assert(Tok.is(tok::kw_operator));
  773. ConsumeToken();
  774. // Maybe this is an operator-function-id.
  775. switch (Tok.getKind()) {
  776. case tok::kw_new: case tok::kw_delete:
  777. ConsumeToken();
  778. if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
  779. ConsumeBracket();
  780. ConsumeBracket();
  781. }
  782. return TPResult::True;
  783. #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
  784. case tok::Token:
  785. #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
  786. #include "clang/Basic/OperatorKinds.def"
  787. ConsumeToken();
  788. return TPResult::True;
  789. case tok::l_square:
  790. if (NextToken().is(tok::r_square)) {
  791. ConsumeBracket();
  792. ConsumeBracket();
  793. return TPResult::True;
  794. }
  795. break;
  796. case tok::l_paren:
  797. if (NextToken().is(tok::r_paren)) {
  798. ConsumeParen();
  799. ConsumeParen();
  800. return TPResult::True;
  801. }
  802. break;
  803. default:
  804. break;
  805. }
  806. // Maybe this is a literal-operator-id.
  807. if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
  808. bool FoundUDSuffix = false;
  809. do {
  810. FoundUDSuffix |= Tok.hasUDSuffix();
  811. ConsumeStringToken();
  812. } while (isTokenStringLiteral());
  813. if (!FoundUDSuffix) {
  814. if (Tok.is(tok::identifier))
  815. ConsumeToken();
  816. else
  817. return TPResult::Error;
  818. }
  819. return TPResult::True;
  820. }
  821. // Maybe this is a conversion-function-id.
  822. bool AnyDeclSpecifiers = false;
  823. while (true) {
  824. TPResult TPR = isCXXDeclarationSpecifier();
  825. if (TPR == TPResult::Error)
  826. return TPR;
  827. if (TPR == TPResult::False) {
  828. if (!AnyDeclSpecifiers)
  829. return TPResult::Error;
  830. break;
  831. }
  832. if (TryConsumeDeclarationSpecifier() == TPResult::Error)
  833. return TPResult::Error;
  834. AnyDeclSpecifiers = true;
  835. }
  836. return TryParsePtrOperatorSeq();
  837. }
  838. /// declarator:
  839. /// direct-declarator
  840. /// ptr-operator declarator
  841. ///
  842. /// direct-declarator:
  843. /// declarator-id
  844. /// direct-declarator '(' parameter-declaration-clause ')'
  845. /// cv-qualifier-seq[opt] exception-specification[opt]
  846. /// direct-declarator '[' constant-expression[opt] ']'
  847. /// '(' declarator ')'
  848. /// [GNU] '(' attributes declarator ')'
  849. ///
  850. /// abstract-declarator:
  851. /// ptr-operator abstract-declarator[opt]
  852. /// direct-abstract-declarator
  853. ///
  854. /// direct-abstract-declarator:
  855. /// direct-abstract-declarator[opt]
  856. /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  857. /// exception-specification[opt]
  858. /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
  859. /// '(' abstract-declarator ')'
  860. /// [C++0x] ...
  861. ///
  862. /// ptr-operator:
  863. /// '*' cv-qualifier-seq[opt]
  864. /// '&'
  865. /// [C++0x] '&&' [TODO]
  866. /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
  867. ///
  868. /// cv-qualifier-seq:
  869. /// cv-qualifier cv-qualifier-seq[opt]
  870. ///
  871. /// cv-qualifier:
  872. /// 'const'
  873. /// 'volatile'
  874. ///
  875. /// declarator-id:
  876. /// '...'[opt] id-expression
  877. ///
  878. /// id-expression:
  879. /// unqualified-id
  880. /// qualified-id [TODO]
  881. ///
  882. /// unqualified-id:
  883. /// identifier
  884. /// operator-function-id
  885. /// conversion-function-id
  886. /// literal-operator-id
  887. /// '~' class-name [TODO]
  888. /// '~' decltype-specifier [TODO]
  889. /// template-id [TODO]
  890. ///
  891. Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
  892. bool mayHaveIdentifier,
  893. bool mayHaveDirectInit) {
  894. // declarator:
  895. // direct-declarator
  896. // ptr-operator declarator
  897. if (TryParsePtrOperatorSeq() == TPResult::Error)
  898. return TPResult::Error;
  899. // direct-declarator:
  900. // direct-abstract-declarator:
  901. if (Tok.is(tok::ellipsis))
  902. ConsumeToken();
  903. if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
  904. (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
  905. NextToken().is(tok::kw_operator)))) &&
  906. mayHaveIdentifier) {
  907. // declarator-id
  908. if (Tok.is(tok::annot_cxxscope)) {
  909. CXXScopeSpec SS;
  910. Actions.RestoreNestedNameSpecifierAnnotation(
  911. Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
  912. if (SS.isInvalid())
  913. return TPResult::Error;
  914. ConsumeAnnotationToken();
  915. } else if (Tok.is(tok::identifier)) {
  916. TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
  917. }
  918. if (Tok.is(tok::kw_operator)) {
  919. if (TryParseOperatorId() == TPResult::Error)
  920. return TPResult::Error;
  921. } else
  922. ConsumeToken();
  923. } else if (Tok.is(tok::l_paren)) {
  924. ConsumeParen();
  925. if (mayBeAbstract &&
  926. (Tok.is(tok::r_paren) || // 'int()' is a function.
  927. // 'int(...)' is a function.
  928. (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
  929. isDeclarationSpecifier())) { // 'int(int)' is a function.
  930. // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  931. // exception-specification[opt]
  932. TPResult TPR = TryParseFunctionDeclarator();
  933. if (TPR != TPResult::Ambiguous)
  934. return TPR;
  935. } else {
  936. // '(' declarator ')'
  937. // '(' attributes declarator ')'
  938. // '(' abstract-declarator ')'
  939. if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
  940. tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
  941. tok::kw___regcall, tok::kw___vectorcall))
  942. return TPResult::True; // attributes indicate declaration
  943. TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
  944. if (TPR != TPResult::Ambiguous)
  945. return TPR;
  946. if (Tok.isNot(tok::r_paren))
  947. return TPResult::False;
  948. ConsumeParen();
  949. }
  950. } else if (!mayBeAbstract) {
  951. return TPResult::False;
  952. }
  953. if (mayHaveDirectInit)
  954. return TPResult::Ambiguous;
  955. while (true) {
  956. TPResult TPR(TPResult::Ambiguous);
  957. if (Tok.is(tok::l_paren)) {
  958. // Check whether we have a function declarator or a possible ctor-style
  959. // initializer that follows the declarator. Note that ctor-style
  960. // initializers are not possible in contexts where abstract declarators
  961. // are allowed.
  962. if (!mayBeAbstract && !isCXXFunctionDeclarator())
  963. break;
  964. // direct-declarator '(' parameter-declaration-clause ')'
  965. // cv-qualifier-seq[opt] exception-specification[opt]
  966. ConsumeParen();
  967. TPR = TryParseFunctionDeclarator();
  968. } else if (Tok.is(tok::l_square)) {
  969. // direct-declarator '[' constant-expression[opt] ']'
  970. // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
  971. TPR = TryParseBracketDeclarator();
  972. } else if (Tok.is(tok::kw_requires)) {
  973. // declarator requires-clause
  974. // A requires clause indicates a function declaration.
  975. TPR = TPResult::True;
  976. } else {
  977. break;
  978. }
  979. if (TPR != TPResult::Ambiguous)
  980. return TPR;
  981. }
  982. return TPResult::Ambiguous;
  983. }
  984. bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
  985. return llvm::is_contained(TentativelyDeclaredIdentifiers, II);
  986. }
  987. namespace {
  988. class TentativeParseCCC final : public CorrectionCandidateCallback {
  989. public:
  990. TentativeParseCCC(const Token &Next) {
  991. WantRemainingKeywords = false;
  992. WantTypeSpecifiers =
  993. Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater, tok::l_brace,
  994. tok::identifier, tok::comma);
  995. }
  996. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  997. // Reject any candidate that only resolves to instance members since they
  998. // aren't viable as standalone identifiers instead of member references.
  999. if (Candidate.isResolved() && !Candidate.isKeyword() &&
  1000. llvm::all_of(Candidate,
  1001. [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
  1002. return false;
  1003. return CorrectionCandidateCallback::ValidateCandidate(Candidate);
  1004. }
  1005. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  1006. return std::make_unique<TentativeParseCCC>(*this);
  1007. }
  1008. };
  1009. }
  1010. /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
  1011. /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
  1012. /// be either a decl-specifier or a function-style cast, and TPResult::Error
  1013. /// if a parsing error was found and reported.
  1014. ///
  1015. /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
  1016. /// declaration specifiers but possibly valid as some other kind of construct
  1017. /// return TPResult::Ambiguous instead of TPResult::False. When this happens,
  1018. /// the intent is to keep trying to disambiguate, on the basis that we might
  1019. /// find a better reason to treat this construct as a declaration later on.
  1020. /// When this happens and the name could possibly be valid in some other
  1021. /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
  1022. /// that trigger this are:
  1023. ///
  1024. /// * When parsing X::Y (with no 'typename') where X is dependent
  1025. /// * When parsing X<Y> where X is undeclared
  1026. ///
  1027. /// decl-specifier:
  1028. /// storage-class-specifier
  1029. /// type-specifier
  1030. /// function-specifier
  1031. /// 'friend'
  1032. /// 'typedef'
  1033. /// [C++11] 'constexpr'
  1034. /// [C++20] 'consteval'
  1035. /// [GNU] attributes declaration-specifiers[opt]
  1036. ///
  1037. /// storage-class-specifier:
  1038. /// 'register'
  1039. /// 'static'
  1040. /// 'extern'
  1041. /// 'mutable'
  1042. /// 'auto'
  1043. /// [GNU] '__thread'
  1044. /// [C++11] 'thread_local'
  1045. /// [C11] '_Thread_local'
  1046. ///
  1047. /// function-specifier:
  1048. /// 'inline'
  1049. /// 'virtual'
  1050. /// 'explicit'
  1051. ///
  1052. /// typedef-name:
  1053. /// identifier
  1054. ///
  1055. /// type-specifier:
  1056. /// simple-type-specifier
  1057. /// class-specifier
  1058. /// enum-specifier
  1059. /// elaborated-type-specifier
  1060. /// typename-specifier
  1061. /// cv-qualifier
  1062. ///
  1063. /// simple-type-specifier:
  1064. /// '::'[opt] nested-name-specifier[opt] type-name
  1065. /// '::'[opt] nested-name-specifier 'template'
  1066. /// simple-template-id [TODO]
  1067. /// 'char'
  1068. /// 'wchar_t'
  1069. /// 'bool'
  1070. /// 'short'
  1071. /// 'int'
  1072. /// 'long'
  1073. /// 'signed'
  1074. /// 'unsigned'
  1075. /// 'float'
  1076. /// 'double'
  1077. /// 'void'
  1078. /// [GNU] typeof-specifier
  1079. /// [GNU] '_Complex'
  1080. /// [C++11] 'auto'
  1081. /// [GNU] '__auto_type'
  1082. /// [C++11] 'decltype' ( expression )
  1083. /// [C++1y] 'decltype' ( 'auto' )
  1084. ///
  1085. /// type-name:
  1086. /// class-name
  1087. /// enum-name
  1088. /// typedef-name
  1089. ///
  1090. /// elaborated-type-specifier:
  1091. /// class-key '::'[opt] nested-name-specifier[opt] identifier
  1092. /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
  1093. /// simple-template-id
  1094. /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
  1095. ///
  1096. /// enum-name:
  1097. /// identifier
  1098. ///
  1099. /// enum-specifier:
  1100. /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
  1101. /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
  1102. ///
  1103. /// class-specifier:
  1104. /// class-head '{' member-specification[opt] '}'
  1105. ///
  1106. /// class-head:
  1107. /// class-key identifier[opt] base-clause[opt]
  1108. /// class-key nested-name-specifier identifier base-clause[opt]
  1109. /// class-key nested-name-specifier[opt] simple-template-id
  1110. /// base-clause[opt]
  1111. ///
  1112. /// class-key:
  1113. /// 'class'
  1114. /// 'struct'
  1115. /// 'union'
  1116. ///
  1117. /// cv-qualifier:
  1118. /// 'const'
  1119. /// 'volatile'
  1120. /// [GNU] restrict
  1121. ///
  1122. Parser::TPResult
  1123. Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
  1124. bool *InvalidAsDeclSpec) {
  1125. auto IsPlaceholderSpecifier = [&] (TemplateIdAnnotation *TemplateId,
  1126. int Lookahead) {
  1127. // We have a placeholder-constraint (we check for 'auto' or 'decltype' to
  1128. // distinguish 'C<int>;' from 'C<int> auto c = 1;')
  1129. return TemplateId->Kind == TNK_Concept_template &&
  1130. GetLookAheadToken(Lookahead + 1).isOneOf(tok::kw_auto, tok::kw_decltype,
  1131. // If we have an identifier here, the user probably forgot the
  1132. // 'auto' in the placeholder constraint, e.g. 'C<int> x = 2;'
  1133. // This will be diagnosed nicely later, so disambiguate as a
  1134. // declaration.
  1135. tok::identifier);
  1136. };
  1137. switch (Tok.getKind()) {
  1138. case tok::identifier: {
  1139. // Check for need to substitute AltiVec __vector keyword
  1140. // for "vector" identifier.
  1141. if (TryAltiVecVectorToken())
  1142. return TPResult::True;
  1143. const Token &Next = NextToken();
  1144. // In 'foo bar', 'foo' is always a type name outside of Objective-C.
  1145. if (!getLangOpts().ObjC && Next.is(tok::identifier))
  1146. return TPResult::True;
  1147. if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
  1148. // Determine whether this is a valid expression. If not, we will hit
  1149. // a parse error one way or another. In that case, tell the caller that
  1150. // this is ambiguous. Typo-correct to type and expression keywords and
  1151. // to types and identifiers, in order to try to recover from errors.
  1152. TentativeParseCCC CCC(Next);
  1153. switch (TryAnnotateName(&CCC)) {
  1154. case ANK_Error:
  1155. return TPResult::Error;
  1156. case ANK_TentativeDecl:
  1157. return TPResult::False;
  1158. case ANK_TemplateName:
  1159. // In C++17, this could be a type template for class template argument
  1160. // deduction. Try to form a type annotation for it. If we're in a
  1161. // template template argument, we'll undo this when checking the
  1162. // validity of the argument.
  1163. if (getLangOpts().CPlusPlus17) {
  1164. if (TryAnnotateTypeOrScopeToken())
  1165. return TPResult::Error;
  1166. if (Tok.isNot(tok::identifier))
  1167. break;
  1168. }
  1169. // A bare type template-name which can't be a template template
  1170. // argument is an error, and was probably intended to be a type.
  1171. return GreaterThanIsOperator ? TPResult::True : TPResult::False;
  1172. case ANK_Unresolved:
  1173. return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
  1174. case ANK_Success:
  1175. break;
  1176. }
  1177. assert(Tok.isNot(tok::identifier) &&
  1178. "TryAnnotateName succeeded without producing an annotation");
  1179. } else {
  1180. // This might possibly be a type with a dependent scope specifier and
  1181. // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
  1182. // since it will annotate as a primary expression, and we want to use the
  1183. // "missing 'typename'" logic.
  1184. if (TryAnnotateTypeOrScopeToken())
  1185. return TPResult::Error;
  1186. // If annotation failed, assume it's a non-type.
  1187. // FIXME: If this happens due to an undeclared identifier, treat it as
  1188. // ambiguous.
  1189. if (Tok.is(tok::identifier))
  1190. return TPResult::False;
  1191. }
  1192. // We annotated this token as something. Recurse to handle whatever we got.
  1193. return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
  1194. }
  1195. case tok::kw_typename: // typename T::type
  1196. // Annotate typenames and C++ scope specifiers. If we get one, just
  1197. // recurse to handle whatever we get.
  1198. if (TryAnnotateTypeOrScopeToken())
  1199. return TPResult::Error;
  1200. return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
  1201. case tok::coloncolon: { // ::foo::bar
  1202. const Token &Next = NextToken();
  1203. if (Next.isOneOf(tok::kw_new, // ::new
  1204. tok::kw_delete)) // ::delete
  1205. return TPResult::False;
  1206. LLVM_FALLTHROUGH;
  1207. }
  1208. case tok::kw___super:
  1209. case tok::kw_decltype:
  1210. // Annotate typenames and C++ scope specifiers. If we get one, just
  1211. // recurse to handle whatever we get.
  1212. if (TryAnnotateTypeOrScopeToken())
  1213. return TPResult::Error;
  1214. return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
  1215. // decl-specifier:
  1216. // storage-class-specifier
  1217. // type-specifier
  1218. // function-specifier
  1219. // 'friend'
  1220. // 'typedef'
  1221. // 'constexpr'
  1222. case tok::kw_friend:
  1223. case tok::kw_typedef:
  1224. case tok::kw_constexpr:
  1225. case tok::kw_consteval:
  1226. case tok::kw_constinit:
  1227. // storage-class-specifier
  1228. case tok::kw_register:
  1229. case tok::kw_static:
  1230. case tok::kw_extern:
  1231. case tok::kw_mutable:
  1232. case tok::kw_auto:
  1233. case tok::kw___thread:
  1234. case tok::kw_thread_local:
  1235. case tok::kw__Thread_local:
  1236. // function-specifier
  1237. case tok::kw_inline:
  1238. case tok::kw_virtual:
  1239. case tok::kw_explicit:
  1240. // Modules
  1241. case tok::kw___module_private__:
  1242. // Debugger support
  1243. case tok::kw___unknown_anytype:
  1244. // type-specifier:
  1245. // simple-type-specifier
  1246. // class-specifier
  1247. // enum-specifier
  1248. // elaborated-type-specifier
  1249. // typename-specifier
  1250. // cv-qualifier
  1251. // class-specifier
  1252. // elaborated-type-specifier
  1253. case tok::kw_class:
  1254. case tok::kw_struct:
  1255. case tok::kw_union:
  1256. case tok::kw___interface:
  1257. // enum-specifier
  1258. case tok::kw_enum:
  1259. // cv-qualifier
  1260. case tok::kw_const:
  1261. case tok::kw_volatile:
  1262. return TPResult::True;
  1263. // OpenCL address space qualifiers
  1264. case tok::kw_private:
  1265. if (!getLangOpts().OpenCL)
  1266. return TPResult::False;
  1267. LLVM_FALLTHROUGH;
  1268. case tok::kw___private:
  1269. case tok::kw___local:
  1270. case tok::kw___global:
  1271. case tok::kw___constant:
  1272. case tok::kw___generic:
  1273. // OpenCL access qualifiers
  1274. case tok::kw___read_only:
  1275. case tok::kw___write_only:
  1276. case tok::kw___read_write:
  1277. // OpenCL pipe
  1278. case tok::kw_pipe:
  1279. // GNU
  1280. case tok::kw_restrict:
  1281. case tok::kw__Complex:
  1282. case tok::kw___attribute:
  1283. case tok::kw___auto_type:
  1284. return TPResult::True;
  1285. // Microsoft
  1286. case tok::kw___declspec:
  1287. case tok::kw___cdecl:
  1288. case tok::kw___stdcall:
  1289. case tok::kw___fastcall:
  1290. case tok::kw___thiscall:
  1291. case tok::kw___regcall:
  1292. case tok::kw___vectorcall:
  1293. case tok::kw___w64:
  1294. case tok::kw___sptr:
  1295. case tok::kw___uptr:
  1296. case tok::kw___ptr64:
  1297. case tok::kw___ptr32:
  1298. case tok::kw___forceinline:
  1299. case tok::kw___unaligned:
  1300. case tok::kw__Nonnull:
  1301. case tok::kw__Nullable:
  1302. case tok::kw__Nullable_result:
  1303. case tok::kw__Null_unspecified:
  1304. case tok::kw___kindof:
  1305. return TPResult::True;
  1306. // Borland
  1307. case tok::kw___pascal:
  1308. return TPResult::True;
  1309. // AltiVec
  1310. case tok::kw___vector:
  1311. return TPResult::True;
  1312. case tok::annot_template_id: {
  1313. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1314. // If lookup for the template-name found nothing, don't assume we have a
  1315. // definitive disambiguation result yet.
  1316. if ((TemplateId->hasInvalidName() ||
  1317. TemplateId->Kind == TNK_Undeclared_template) &&
  1318. InvalidAsDeclSpec) {
  1319. // 'template-id(' can be a valid expression but not a valid decl spec if
  1320. // the template-name is not declared, but we don't consider this to be a
  1321. // definitive disambiguation. In any other context, it's an error either
  1322. // way.
  1323. *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
  1324. return TPResult::Ambiguous;
  1325. }
  1326. if (TemplateId->hasInvalidName())
  1327. return TPResult::Error;
  1328. if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/0))
  1329. return TPResult::True;
  1330. if (TemplateId->Kind != TNK_Type_template)
  1331. return TPResult::False;
  1332. CXXScopeSpec SS;
  1333. AnnotateTemplateIdTokenAsType(SS);
  1334. assert(Tok.is(tok::annot_typename));
  1335. goto case_typename;
  1336. }
  1337. case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
  1338. // We've already annotated a scope; try to annotate a type.
  1339. if (TryAnnotateTypeOrScopeToken())
  1340. return TPResult::Error;
  1341. if (!Tok.is(tok::annot_typename)) {
  1342. if (Tok.is(tok::annot_cxxscope) &&
  1343. NextToken().is(tok::annot_template_id)) {
  1344. TemplateIdAnnotation *TemplateId =
  1345. takeTemplateIdAnnotation(NextToken());
  1346. if (TemplateId->hasInvalidName()) {
  1347. if (InvalidAsDeclSpec) {
  1348. *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
  1349. return TPResult::Ambiguous;
  1350. }
  1351. return TPResult::Error;
  1352. }
  1353. if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/1))
  1354. return TPResult::True;
  1355. }
  1356. // If the next token is an identifier or a type qualifier, then this
  1357. // can't possibly be a valid expression either.
  1358. if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
  1359. CXXScopeSpec SS;
  1360. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  1361. Tok.getAnnotationRange(),
  1362. SS);
  1363. if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
  1364. RevertingTentativeParsingAction PA(*this);
  1365. ConsumeAnnotationToken();
  1366. ConsumeToken();
  1367. bool isIdentifier = Tok.is(tok::identifier);
  1368. TPResult TPR = TPResult::False;
  1369. if (!isIdentifier)
  1370. TPR = isCXXDeclarationSpecifier(BracedCastResult,
  1371. InvalidAsDeclSpec);
  1372. if (isIdentifier ||
  1373. TPR == TPResult::True || TPR == TPResult::Error)
  1374. return TPResult::Error;
  1375. if (InvalidAsDeclSpec) {
  1376. // We can't tell whether this is a missing 'typename' or a valid
  1377. // expression.
  1378. *InvalidAsDeclSpec = true;
  1379. return TPResult::Ambiguous;
  1380. } else {
  1381. // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens
  1382. // are or the form *) or &) *> or &> &&>, this can't be an expression.
  1383. // The typename must be missing.
  1384. if (getLangOpts().MSVCCompat) {
  1385. if (((Tok.is(tok::amp) || Tok.is(tok::star)) &&
  1386. (NextToken().is(tok::r_paren) ||
  1387. NextToken().is(tok::greater))) ||
  1388. (Tok.is(tok::ampamp) && NextToken().is(tok::greater)))
  1389. return TPResult::True;
  1390. }
  1391. }
  1392. } else {
  1393. // Try to resolve the name. If it doesn't exist, assume it was
  1394. // intended to name a type and keep disambiguating.
  1395. switch (TryAnnotateName()) {
  1396. case ANK_Error:
  1397. return TPResult::Error;
  1398. case ANK_TentativeDecl:
  1399. return TPResult::False;
  1400. case ANK_TemplateName:
  1401. // In C++17, this could be a type template for class template
  1402. // argument deduction.
  1403. if (getLangOpts().CPlusPlus17) {
  1404. if (TryAnnotateTypeOrScopeToken())
  1405. return TPResult::Error;
  1406. if (Tok.isNot(tok::identifier))
  1407. break;
  1408. }
  1409. // A bare type template-name which can't be a template template
  1410. // argument is an error, and was probably intended to be a type.
  1411. // In C++17, this could be class template argument deduction.
  1412. return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
  1413. ? TPResult::True
  1414. : TPResult::False;
  1415. case ANK_Unresolved:
  1416. return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
  1417. case ANK_Success:
  1418. break;
  1419. }
  1420. // Annotated it, check again.
  1421. assert(Tok.isNot(tok::annot_cxxscope) ||
  1422. NextToken().isNot(tok::identifier));
  1423. return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
  1424. }
  1425. }
  1426. return TPResult::False;
  1427. }
  1428. // If that succeeded, fallthrough into the generic simple-type-id case.
  1429. LLVM_FALLTHROUGH;
  1430. // The ambiguity resides in a simple-type-specifier/typename-specifier
  1431. // followed by a '('. The '(' could either be the start of:
  1432. //
  1433. // direct-declarator:
  1434. // '(' declarator ')'
  1435. //
  1436. // direct-abstract-declarator:
  1437. // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  1438. // exception-specification[opt]
  1439. // '(' abstract-declarator ')'
  1440. //
  1441. // or part of a function-style cast expression:
  1442. //
  1443. // simple-type-specifier '(' expression-list[opt] ')'
  1444. //
  1445. // simple-type-specifier:
  1446. case tok::annot_typename:
  1447. case_typename:
  1448. // In Objective-C, we might have a protocol-qualified type.
  1449. if (getLangOpts().ObjC && NextToken().is(tok::less)) {
  1450. // Tentatively parse the protocol qualifiers.
  1451. RevertingTentativeParsingAction PA(*this);
  1452. ConsumeAnyToken(); // The type token
  1453. TPResult TPR = TryParseProtocolQualifiers();
  1454. bool isFollowedByParen = Tok.is(tok::l_paren);
  1455. bool isFollowedByBrace = Tok.is(tok::l_brace);
  1456. if (TPR == TPResult::Error)
  1457. return TPResult::Error;
  1458. if (isFollowedByParen)
  1459. return TPResult::Ambiguous;
  1460. if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
  1461. return BracedCastResult;
  1462. return TPResult::True;
  1463. }
  1464. LLVM_FALLTHROUGH;
  1465. case tok::kw_char:
  1466. case tok::kw_wchar_t:
  1467. case tok::kw_char8_t:
  1468. case tok::kw_char16_t:
  1469. case tok::kw_char32_t:
  1470. case tok::kw_bool:
  1471. case tok::kw_short:
  1472. case tok::kw_int:
  1473. case tok::kw_long:
  1474. case tok::kw___int64:
  1475. case tok::kw___int128:
  1476. case tok::kw_signed:
  1477. case tok::kw_unsigned:
  1478. case tok::kw_half:
  1479. case tok::kw_float:
  1480. case tok::kw_double:
  1481. case tok::kw___bf16:
  1482. case tok::kw__Float16:
  1483. case tok::kw___float128:
  1484. case tok::kw___ibm128:
  1485. case tok::kw_void:
  1486. case tok::annot_decltype:
  1487. #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
  1488. #include "clang/Basic/OpenCLImageTypes.def"
  1489. if (NextToken().is(tok::l_paren))
  1490. return TPResult::Ambiguous;
  1491. // This is a function-style cast in all cases we disambiguate other than
  1492. // one:
  1493. // struct S {
  1494. // enum E : int { a = 4 }; // enum
  1495. // enum E : int { 4 }; // bit-field
  1496. // };
  1497. if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
  1498. return BracedCastResult;
  1499. if (isStartOfObjCClassMessageMissingOpenBracket())
  1500. return TPResult::False;
  1501. return TPResult::True;
  1502. // GNU typeof support.
  1503. case tok::kw_typeof: {
  1504. if (NextToken().isNot(tok::l_paren))
  1505. return TPResult::True;
  1506. RevertingTentativeParsingAction PA(*this);
  1507. TPResult TPR = TryParseTypeofSpecifier();
  1508. bool isFollowedByParen = Tok.is(tok::l_paren);
  1509. bool isFollowedByBrace = Tok.is(tok::l_brace);
  1510. if (TPR == TPResult::Error)
  1511. return TPResult::Error;
  1512. if (isFollowedByParen)
  1513. return TPResult::Ambiguous;
  1514. if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
  1515. return BracedCastResult;
  1516. return TPResult::True;
  1517. }
  1518. // C++0x type traits support
  1519. case tok::kw___underlying_type:
  1520. return TPResult::True;
  1521. // C11 _Atomic
  1522. case tok::kw__Atomic:
  1523. return TPResult::True;
  1524. case tok::kw__BitInt:
  1525. case tok::kw__ExtInt: {
  1526. if (NextToken().isNot(tok::l_paren))
  1527. return TPResult::Error;
  1528. RevertingTentativeParsingAction PA(*this);
  1529. ConsumeToken();
  1530. ConsumeParen();
  1531. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1532. return TPResult::Error;
  1533. if (Tok.is(tok::l_paren))
  1534. return TPResult::Ambiguous;
  1535. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
  1536. return BracedCastResult;
  1537. return TPResult::True;
  1538. }
  1539. default:
  1540. return TPResult::False;
  1541. }
  1542. }
  1543. bool Parser::isCXXDeclarationSpecifierAType() {
  1544. switch (Tok.getKind()) {
  1545. // typename-specifier
  1546. case tok::annot_decltype:
  1547. case tok::annot_template_id:
  1548. case tok::annot_typename:
  1549. case tok::kw_typeof:
  1550. case tok::kw___underlying_type:
  1551. return true;
  1552. // elaborated-type-specifier
  1553. case tok::kw_class:
  1554. case tok::kw_struct:
  1555. case tok::kw_union:
  1556. case tok::kw___interface:
  1557. case tok::kw_enum:
  1558. return true;
  1559. // simple-type-specifier
  1560. case tok::kw_char:
  1561. case tok::kw_wchar_t:
  1562. case tok::kw_char8_t:
  1563. case tok::kw_char16_t:
  1564. case tok::kw_char32_t:
  1565. case tok::kw_bool:
  1566. case tok::kw_short:
  1567. case tok::kw_int:
  1568. case tok::kw__ExtInt:
  1569. case tok::kw__BitInt:
  1570. case tok::kw_long:
  1571. case tok::kw___int64:
  1572. case tok::kw___int128:
  1573. case tok::kw_signed:
  1574. case tok::kw_unsigned:
  1575. case tok::kw_half:
  1576. case tok::kw_float:
  1577. case tok::kw_double:
  1578. case tok::kw___bf16:
  1579. case tok::kw__Float16:
  1580. case tok::kw___float128:
  1581. case tok::kw___ibm128:
  1582. case tok::kw_void:
  1583. case tok::kw___unknown_anytype:
  1584. case tok::kw___auto_type:
  1585. #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
  1586. #include "clang/Basic/OpenCLImageTypes.def"
  1587. return true;
  1588. case tok::kw_auto:
  1589. return getLangOpts().CPlusPlus11;
  1590. case tok::kw__Atomic:
  1591. // "_Atomic foo"
  1592. return NextToken().is(tok::l_paren);
  1593. default:
  1594. return false;
  1595. }
  1596. }
  1597. /// [GNU] typeof-specifier:
  1598. /// 'typeof' '(' expressions ')'
  1599. /// 'typeof' '(' type-name ')'
  1600. ///
  1601. Parser::TPResult Parser::TryParseTypeofSpecifier() {
  1602. assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
  1603. ConsumeToken();
  1604. assert(Tok.is(tok::l_paren) && "Expected '('");
  1605. // Parse through the parens after 'typeof'.
  1606. ConsumeParen();
  1607. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1608. return TPResult::Error;
  1609. return TPResult::Ambiguous;
  1610. }
  1611. /// [ObjC] protocol-qualifiers:
  1612. //// '<' identifier-list '>'
  1613. Parser::TPResult Parser::TryParseProtocolQualifiers() {
  1614. assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
  1615. ConsumeToken();
  1616. do {
  1617. if (Tok.isNot(tok::identifier))
  1618. return TPResult::Error;
  1619. ConsumeToken();
  1620. if (Tok.is(tok::comma)) {
  1621. ConsumeToken();
  1622. continue;
  1623. }
  1624. if (Tok.is(tok::greater)) {
  1625. ConsumeToken();
  1626. return TPResult::Ambiguous;
  1627. }
  1628. } while (false);
  1629. return TPResult::Error;
  1630. }
  1631. /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
  1632. /// a constructor-style initializer, when parsing declaration statements.
  1633. /// Returns true for function declarator and false for constructor-style
  1634. /// initializer.
  1635. /// If during the disambiguation process a parsing error is encountered,
  1636. /// the function returns true to let the declaration parsing code handle it.
  1637. ///
  1638. /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  1639. /// exception-specification[opt]
  1640. ///
  1641. bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
  1642. // C++ 8.2p1:
  1643. // The ambiguity arising from the similarity between a function-style cast and
  1644. // a declaration mentioned in 6.8 can also occur in the context of a
  1645. // declaration. In that context, the choice is between a function declaration
  1646. // with a redundant set of parentheses around a parameter name and an object
  1647. // declaration with a function-style cast as the initializer. Just as for the
  1648. // ambiguities mentioned in 6.8, the resolution is to consider any construct
  1649. // that could possibly be a declaration a declaration.
  1650. RevertingTentativeParsingAction PA(*this);
  1651. ConsumeParen();
  1652. bool InvalidAsDeclaration = false;
  1653. TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
  1654. if (TPR == TPResult::Ambiguous) {
  1655. if (Tok.isNot(tok::r_paren))
  1656. TPR = TPResult::False;
  1657. else {
  1658. const Token &Next = NextToken();
  1659. if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
  1660. tok::kw_throw, tok::kw_noexcept, tok::l_square,
  1661. tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
  1662. isCXX11VirtSpecifier(Next))
  1663. // The next token cannot appear after a constructor-style initializer,
  1664. // and can appear next in a function definition. This must be a function
  1665. // declarator.
  1666. TPR = TPResult::True;
  1667. else if (InvalidAsDeclaration)
  1668. // Use the absence of 'typename' as a tie-breaker.
  1669. TPR = TPResult::False;
  1670. }
  1671. }
  1672. if (IsAmbiguous && TPR == TPResult::Ambiguous)
  1673. *IsAmbiguous = true;
  1674. // In case of an error, let the declaration parsing code handle it.
  1675. return TPR != TPResult::False;
  1676. }
  1677. /// parameter-declaration-clause:
  1678. /// parameter-declaration-list[opt] '...'[opt]
  1679. /// parameter-declaration-list ',' '...'
  1680. ///
  1681. /// parameter-declaration-list:
  1682. /// parameter-declaration
  1683. /// parameter-declaration-list ',' parameter-declaration
  1684. ///
  1685. /// parameter-declaration:
  1686. /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
  1687. /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
  1688. /// '=' assignment-expression
  1689. /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
  1690. /// attributes[opt]
  1691. /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
  1692. /// attributes[opt] '=' assignment-expression
  1693. ///
  1694. Parser::TPResult
  1695. Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
  1696. bool VersusTemplateArgument) {
  1697. if (Tok.is(tok::r_paren))
  1698. return TPResult::Ambiguous;
  1699. // parameter-declaration-list[opt] '...'[opt]
  1700. // parameter-declaration-list ',' '...'
  1701. //
  1702. // parameter-declaration-list:
  1703. // parameter-declaration
  1704. // parameter-declaration-list ',' parameter-declaration
  1705. //
  1706. while (true) {
  1707. // '...'[opt]
  1708. if (Tok.is(tok::ellipsis)) {
  1709. ConsumeToken();
  1710. if (Tok.is(tok::r_paren))
  1711. return TPResult::True; // '...)' is a sign of a function declarator.
  1712. else
  1713. return TPResult::False;
  1714. }
  1715. // An attribute-specifier-seq here is a sign of a function declarator.
  1716. if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
  1717. /*OuterMightBeMessageSend*/true))
  1718. return TPResult::True;
  1719. ParsedAttributes attrs(AttrFactory);
  1720. MaybeParseMicrosoftAttributes(attrs);
  1721. // decl-specifier-seq
  1722. // A parameter-declaration's initializer must be preceded by an '=', so
  1723. // decl-specifier-seq '{' is not a parameter in C++11.
  1724. TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
  1725. InvalidAsDeclaration);
  1726. // A declaration-specifier (not followed by '(' or '{') means this can't be
  1727. // an expression, but it could still be a template argument.
  1728. if (TPR != TPResult::Ambiguous &&
  1729. !(VersusTemplateArgument && TPR == TPResult::True))
  1730. return TPR;
  1731. bool SeenType = false;
  1732. do {
  1733. SeenType |= isCXXDeclarationSpecifierAType();
  1734. if (TryConsumeDeclarationSpecifier() == TPResult::Error)
  1735. return TPResult::Error;
  1736. // If we see a parameter name, this can't be a template argument.
  1737. if (SeenType && Tok.is(tok::identifier))
  1738. return TPResult::True;
  1739. TPR = isCXXDeclarationSpecifier(TPResult::False,
  1740. InvalidAsDeclaration);
  1741. if (TPR == TPResult::Error)
  1742. return TPR;
  1743. // Two declaration-specifiers means this can't be an expression.
  1744. if (TPR == TPResult::True && !VersusTemplateArgument)
  1745. return TPR;
  1746. } while (TPR != TPResult::False);
  1747. // declarator
  1748. // abstract-declarator[opt]
  1749. TPR = TryParseDeclarator(true/*mayBeAbstract*/);
  1750. if (TPR != TPResult::Ambiguous)
  1751. return TPR;
  1752. // [GNU] attributes[opt]
  1753. if (Tok.is(tok::kw___attribute))
  1754. return TPResult::True;
  1755. // If we're disambiguating a template argument in a default argument in
  1756. // a class definition versus a parameter declaration, an '=' here
  1757. // disambiguates the parse one way or the other.
  1758. // If this is a parameter, it must have a default argument because
  1759. // (a) the previous parameter did, and
  1760. // (b) this must be the first declaration of the function, so we can't
  1761. // inherit any default arguments from elsewhere.
  1762. // FIXME: If we reach a ')' without consuming any '>'s, then this must
  1763. // also be a function parameter (that's missing its default argument).
  1764. if (VersusTemplateArgument)
  1765. return Tok.is(tok::equal) ? TPResult::True : TPResult::False;
  1766. if (Tok.is(tok::equal)) {
  1767. // '=' assignment-expression
  1768. // Parse through assignment-expression.
  1769. if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
  1770. return TPResult::Error;
  1771. }
  1772. if (Tok.is(tok::ellipsis)) {
  1773. ConsumeToken();
  1774. if (Tok.is(tok::r_paren))
  1775. return TPResult::True; // '...)' is a sign of a function declarator.
  1776. else
  1777. return TPResult::False;
  1778. }
  1779. if (!TryConsumeToken(tok::comma))
  1780. break;
  1781. }
  1782. return TPResult::Ambiguous;
  1783. }
  1784. /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
  1785. /// parsing as a function declarator.
  1786. /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
  1787. /// return TPResult::Ambiguous, otherwise it will return either False() or
  1788. /// Error().
  1789. ///
  1790. /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  1791. /// exception-specification[opt]
  1792. ///
  1793. /// exception-specification:
  1794. /// 'throw' '(' type-id-list[opt] ')'
  1795. ///
  1796. Parser::TPResult Parser::TryParseFunctionDeclarator() {
  1797. // The '(' is already parsed.
  1798. TPResult TPR = TryParseParameterDeclarationClause();
  1799. if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
  1800. TPR = TPResult::False;
  1801. if (TPR == TPResult::False || TPR == TPResult::Error)
  1802. return TPR;
  1803. // Parse through the parens.
  1804. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1805. return TPResult::Error;
  1806. // cv-qualifier-seq
  1807. while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
  1808. tok::kw_restrict))
  1809. ConsumeToken();
  1810. // ref-qualifier[opt]
  1811. if (Tok.isOneOf(tok::amp, tok::ampamp))
  1812. ConsumeToken();
  1813. // exception-specification
  1814. if (Tok.is(tok::kw_throw)) {
  1815. ConsumeToken();
  1816. if (Tok.isNot(tok::l_paren))
  1817. return TPResult::Error;
  1818. // Parse through the parens after 'throw'.
  1819. ConsumeParen();
  1820. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1821. return TPResult::Error;
  1822. }
  1823. if (Tok.is(tok::kw_noexcept)) {
  1824. ConsumeToken();
  1825. // Possibly an expression as well.
  1826. if (Tok.is(tok::l_paren)) {
  1827. // Find the matching rparen.
  1828. ConsumeParen();
  1829. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1830. return TPResult::Error;
  1831. }
  1832. }
  1833. return TPResult::Ambiguous;
  1834. }
  1835. /// '[' constant-expression[opt] ']'
  1836. ///
  1837. Parser::TPResult Parser::TryParseBracketDeclarator() {
  1838. ConsumeBracket();
  1839. // A constant-expression cannot begin with a '{', but the
  1840. // expr-or-braced-init-list of a postfix-expression can.
  1841. if (Tok.is(tok::l_brace))
  1842. return TPResult::False;
  1843. if (!SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch))
  1844. return TPResult::Error;
  1845. // If we hit a comma before the ']', this is not a constant-expression,
  1846. // but might still be the expr-or-braced-init-list of a postfix-expression.
  1847. if (Tok.isNot(tok::r_square))
  1848. return TPResult::False;
  1849. ConsumeBracket();
  1850. return TPResult::Ambiguous;
  1851. }
  1852. /// Determine whether we might be looking at the '<' template-argument-list '>'
  1853. /// of a template-id or simple-template-id, rather than a less-than comparison.
  1854. /// This will often fail and produce an ambiguity, but should never be wrong
  1855. /// if it returns True or False.
  1856. Parser::TPResult Parser::isTemplateArgumentList(unsigned TokensToSkip) {
  1857. if (!TokensToSkip) {
  1858. if (Tok.isNot(tok::less))
  1859. return TPResult::False;
  1860. if (NextToken().is(tok::greater))
  1861. return TPResult::True;
  1862. }
  1863. RevertingTentativeParsingAction PA(*this);
  1864. while (TokensToSkip) {
  1865. ConsumeAnyToken();
  1866. --TokensToSkip;
  1867. }
  1868. if (!TryConsumeToken(tok::less))
  1869. return TPResult::False;
  1870. // We can't do much to tell an expression apart from a template-argument,
  1871. // but one good distinguishing factor is that a "decl-specifier" not
  1872. // followed by '(' or '{' can't appear in an expression.
  1873. bool InvalidAsTemplateArgumentList = false;
  1874. if (isCXXDeclarationSpecifier(TPResult::False,
  1875. &InvalidAsTemplateArgumentList) ==
  1876. TPResult::True)
  1877. return TPResult::True;
  1878. if (InvalidAsTemplateArgumentList)
  1879. return TPResult::False;
  1880. // FIXME: In many contexts, X<thing1, Type> can only be a
  1881. // template-argument-list. But that's not true in general:
  1882. //
  1883. // using b = int;
  1884. // void f() {
  1885. // int a = A<B, b, c = C>D; // OK, declares b, not a template-id.
  1886. //
  1887. // X<Y<0, int> // ', int>' might be end of X's template argument list
  1888. //
  1889. // We might be able to disambiguate a few more cases if we're careful.
  1890. // A template-argument-list must be terminated by a '>'.
  1891. if (SkipUntil({tok::greater, tok::greatergreater, tok::greatergreatergreater},
  1892. StopAtSemi | StopBeforeMatch))
  1893. return TPResult::Ambiguous;
  1894. return TPResult::False;
  1895. }
  1896. /// Determine whether we might be looking at the '(' of a C++20 explicit(bool)
  1897. /// in an earlier language mode.
  1898. Parser::TPResult Parser::isExplicitBool() {
  1899. assert(Tok.is(tok::l_paren) && "expected to be looking at a '(' token");
  1900. RevertingTentativeParsingAction PA(*this);
  1901. ConsumeParen();
  1902. // We can only have 'explicit' on a constructor, conversion function, or
  1903. // deduction guide. The declarator of a deduction guide cannot be
  1904. // parenthesized, so we know this isn't a deduction guide. So the only
  1905. // thing we need to check for is some number of parens followed by either
  1906. // the current class name or 'operator'.
  1907. while (Tok.is(tok::l_paren))
  1908. ConsumeParen();
  1909. if (TryAnnotateOptionalCXXScopeToken())
  1910. return TPResult::Error;
  1911. // Class-scope constructor and conversion function names can't really be
  1912. // qualified, but we get better diagnostics if we assume they can be.
  1913. CXXScopeSpec SS;
  1914. if (Tok.is(tok::annot_cxxscope)) {
  1915. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  1916. Tok.getAnnotationRange(),
  1917. SS);
  1918. ConsumeAnnotationToken();
  1919. }
  1920. // 'explicit(operator' might be explicit(bool) or the declaration of a
  1921. // conversion function, but it's probably a conversion function.
  1922. if (Tok.is(tok::kw_operator))
  1923. return TPResult::Ambiguous;
  1924. // If this can't be a constructor name, it can only be explicit(bool).
  1925. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
  1926. return TPResult::True;
  1927. if (!Actions.isCurrentClassName(Tok.is(tok::identifier)
  1928. ? *Tok.getIdentifierInfo()
  1929. : *takeTemplateIdAnnotation(Tok)->Name,
  1930. getCurScope(), &SS))
  1931. return TPResult::True;
  1932. // Formally, we must have a right-paren after the constructor name to match
  1933. // the grammar for a constructor. But clang permits a parenthesized
  1934. // constructor declarator, so also allow a constructor declarator to follow
  1935. // with no ')' token after the constructor name.
  1936. if (!NextToken().is(tok::r_paren) &&
  1937. !isConstructorDeclarator(/*Unqualified=*/SS.isEmpty(),
  1938. /*DeductionGuide=*/false))
  1939. return TPResult::True;
  1940. // Might be explicit(bool) or a parenthesized constructor name.
  1941. return TPResult::Ambiguous;
  1942. }