ParseTentative.cpp 76 KB

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