ParseTentative.cpp 62 KB

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