ParseTentative.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. ///
  75. /// (if AllowForRangeDecl specified)
  76. /// for ( for-range-declaration : for-range-initializer ) statement
  77. /// for-range-declaration:
  78. /// attribute-specifier-seqopt type-specifier-seq declarator
  79. bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
  80. // C++ 6.8p1:
  81. // There is an ambiguity in the grammar involving expression-statements and
  82. // declarations: An expression-statement with a function-style explicit type
  83. // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
  84. // from a declaration where the first declarator starts with a '('. In those
  85. // cases the statement is a declaration. [Note: To disambiguate, the whole
  86. // statement might have to be examined to determine if it is an
  87. // expression-statement or a declaration].
  88. // C++ 6.8p3:
  89. // The disambiguation is purely syntactic; that is, the meaning of the names
  90. // occurring in such a statement, beyond whether they are type-names or not,
  91. // is not generally used in or changed by the disambiguation. Class
  92. // templates are instantiated as necessary to determine if a qualified name
  93. // is a type-name. Disambiguation precedes parsing, and a statement
  94. // disambiguated as a declaration may be an ill-formed declaration.
  95. // We don't have to parse all of the decl-specifier-seq part. There's only
  96. // an ambiguity if the first decl-specifier is
  97. // simple-type-specifier/typename-specifier followed by a '(', which may
  98. // indicate a function-style cast expression.
  99. // isCXXDeclarationSpecifier will return TPResult::Ambiguous() only in such
  100. // a case.
  101. bool InvalidAsDeclaration = false;
  102. TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
  103. &InvalidAsDeclaration);
  104. if (TPR != TPResult::Ambiguous())
  105. return TPR != TPResult::False(); // Returns true for TPResult::True() or
  106. // TPResult::Error().
  107. // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
  108. // and so gets some cases wrong. We can't carry on if we've already seen
  109. // something which makes this statement invalid as a declaration in this case,
  110. // since it can cause us to misparse valid code. Revisit this once
  111. // TryParseInitDeclaratorList is fixed.
  112. if (InvalidAsDeclaration)
  113. return false;
  114. // FIXME: Add statistics about the number of ambiguous statements encountered
  115. // and how they were resolved (number of declarations+number of expressions).
  116. // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
  117. // or an identifier which doesn't resolve as anything. We need tentative
  118. // parsing...
  119. TentativeParsingAction PA(*this);
  120. TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
  121. PA.Revert();
  122. // In case of an error, let the declaration parsing code handle it.
  123. if (TPR == TPResult::Error())
  124. return true;
  125. // Declarations take precedence over expressions.
  126. if (TPR == TPResult::Ambiguous())
  127. TPR = TPResult::True();
  128. assert(TPR == TPResult::True() || TPR == TPResult::False());
  129. return TPR == TPResult::True();
  130. }
  131. /// simple-declaration:
  132. /// decl-specifier-seq init-declarator-list[opt] ';'
  133. ///
  134. /// (if AllowForRangeDecl specified)
  135. /// for ( for-range-declaration : for-range-initializer ) statement
  136. /// for-range-declaration:
  137. /// attribute-specifier-seqopt type-specifier-seq declarator
  138. ///
  139. Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
  140. if (Tok.is(tok::kw_typeof))
  141. TryParseTypeofSpecifier();
  142. else {
  143. if (Tok.is(tok::annot_cxxscope))
  144. ConsumeToken();
  145. ConsumeToken();
  146. if (getLangOpts().ObjC1 && Tok.is(tok::less))
  147. TryParseProtocolQualifiers();
  148. }
  149. // Two decl-specifiers in a row conclusively disambiguate this as being a
  150. // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
  151. // overwhelmingly common case that the next token is a '('.
  152. if (Tok.isNot(tok::l_paren)) {
  153. TPResult TPR = isCXXDeclarationSpecifier();
  154. if (TPR == TPResult::Ambiguous())
  155. return TPResult::True();
  156. if (TPR == TPResult::True() || TPR == TPResult::Error())
  157. return TPR;
  158. assert(TPR == TPResult::False());
  159. }
  160. TPResult TPR = TryParseInitDeclaratorList();
  161. if (TPR != TPResult::Ambiguous())
  162. return TPR;
  163. if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
  164. return TPResult::False();
  165. return TPResult::Ambiguous();
  166. }
  167. /// init-declarator-list:
  168. /// init-declarator
  169. /// init-declarator-list ',' init-declarator
  170. ///
  171. /// init-declarator:
  172. /// declarator initializer[opt]
  173. /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
  174. ///
  175. /// initializer:
  176. /// '=' initializer-clause
  177. /// '(' expression-list ')'
  178. ///
  179. /// initializer-clause:
  180. /// assignment-expression
  181. /// '{' initializer-list ','[opt] '}'
  182. /// '{' '}'
  183. ///
  184. Parser::TPResult Parser::TryParseInitDeclaratorList() {
  185. while (1) {
  186. // declarator
  187. TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
  188. if (TPR != TPResult::Ambiguous())
  189. return TPR;
  190. // [GNU] simple-asm-expr[opt] attributes[opt]
  191. if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
  192. return TPResult::True();
  193. // initializer[opt]
  194. if (Tok.is(tok::l_paren)) {
  195. // Parse through the parens.
  196. ConsumeParen();
  197. if (!SkipUntil(tok::r_paren))
  198. return TPResult::Error();
  199. } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
  200. // MSVC and g++ won't examine the rest of declarators if '=' is
  201. // encountered; they just conclude that we have a declaration.
  202. // EDG parses the initializer completely, which is the proper behavior
  203. // for this case.
  204. //
  205. // At present, Clang follows MSVC and g++, since the parser does not have
  206. // the ability to parse an expression fully without recording the
  207. // results of that parse.
  208. // Also allow 'in' after on objective-c declaration as in:
  209. // for (int (^b)(void) in array). Ideally this should be done in the
  210. // context of parsing for-init-statement of a foreach statement only. But,
  211. // in any other context 'in' is invalid after a declaration and parser
  212. // issues the error regardless of outcome of this decision.
  213. // FIXME. Change if above assumption does not hold.
  214. return TPResult::True();
  215. }
  216. if (Tok.isNot(tok::comma))
  217. break;
  218. ConsumeToken(); // the comma.
  219. }
  220. return TPResult::Ambiguous();
  221. }
  222. /// isCXXConditionDeclaration - Disambiguates between a declaration or an
  223. /// expression for a condition of a if/switch/while/for statement.
  224. /// If during the disambiguation process a parsing error is encountered,
  225. /// the function returns true to let the declaration parsing code handle it.
  226. ///
  227. /// condition:
  228. /// expression
  229. /// type-specifier-seq declarator '=' assignment-expression
  230. /// [C++11] type-specifier-seq declarator '=' initializer-clause
  231. /// [C++11] type-specifier-seq declarator braced-init-list
  232. /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
  233. /// '=' assignment-expression
  234. ///
  235. bool Parser::isCXXConditionDeclaration() {
  236. TPResult TPR = isCXXDeclarationSpecifier();
  237. if (TPR != TPResult::Ambiguous())
  238. return TPR != TPResult::False(); // Returns true for TPResult::True() or
  239. // TPResult::Error().
  240. // FIXME: Add statistics about the number of ambiguous statements encountered
  241. // and how they were resolved (number of declarations+number of expressions).
  242. // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
  243. // We need tentative parsing...
  244. TentativeParsingAction PA(*this);
  245. // type-specifier-seq
  246. if (Tok.is(tok::kw_typeof))
  247. TryParseTypeofSpecifier();
  248. else {
  249. ConsumeToken();
  250. if (getLangOpts().ObjC1 && Tok.is(tok::less))
  251. TryParseProtocolQualifiers();
  252. }
  253. assert(Tok.is(tok::l_paren) && "Expected '('");
  254. // declarator
  255. TPR = TryParseDeclarator(false/*mayBeAbstract*/);
  256. // In case of an error, let the declaration parsing code handle it.
  257. if (TPR == TPResult::Error())
  258. TPR = TPResult::True();
  259. if (TPR == TPResult::Ambiguous()) {
  260. // '='
  261. // [GNU] simple-asm-expr[opt] attributes[opt]
  262. if (Tok.is(tok::equal) ||
  263. Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
  264. TPR = TPResult::True();
  265. else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
  266. TPR = TPResult::True();
  267. else
  268. TPR = TPResult::False();
  269. }
  270. PA.Revert();
  271. assert(TPR == TPResult::True() || TPR == TPResult::False());
  272. return TPR == TPResult::True();
  273. }
  274. /// \brief Determine whether the next set of tokens contains a type-id.
  275. ///
  276. /// The context parameter states what context we're parsing right
  277. /// now, which affects how this routine copes with the token
  278. /// following the type-id. If the context is TypeIdInParens, we have
  279. /// already parsed the '(' and we will cease lookahead when we hit
  280. /// the corresponding ')'. If the context is
  281. /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
  282. /// before this template argument, and will cease lookahead when we
  283. /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
  284. /// and false for an expression. If during the disambiguation
  285. /// process a parsing error is encountered, the function returns
  286. /// true to let the declaration parsing code handle it.
  287. ///
  288. /// type-id:
  289. /// type-specifier-seq abstract-declarator[opt]
  290. ///
  291. bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
  292. isAmbiguous = false;
  293. // C++ 8.2p2:
  294. // The ambiguity arising from the similarity between a function-style cast and
  295. // a type-id can occur in different contexts. The ambiguity appears as a
  296. // choice between a function-style cast expression and a declaration of a
  297. // type. The resolution is that any construct that could possibly be a type-id
  298. // in its syntactic context shall be considered a type-id.
  299. TPResult TPR = isCXXDeclarationSpecifier();
  300. if (TPR != TPResult::Ambiguous())
  301. return TPR != TPResult::False(); // Returns true for TPResult::True() or
  302. // TPResult::Error().
  303. // FIXME: Add statistics about the number of ambiguous statements encountered
  304. // and how they were resolved (number of declarations+number of expressions).
  305. // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
  306. // We need tentative parsing...
  307. TentativeParsingAction PA(*this);
  308. // type-specifier-seq
  309. if (Tok.is(tok::kw_typeof))
  310. TryParseTypeofSpecifier();
  311. else {
  312. ConsumeToken();
  313. if (getLangOpts().ObjC1 && Tok.is(tok::less))
  314. TryParseProtocolQualifiers();
  315. }
  316. assert(Tok.is(tok::l_paren) && "Expected '('");
  317. // declarator
  318. TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
  319. // In case of an error, let the declaration parsing code handle it.
  320. if (TPR == TPResult::Error())
  321. TPR = TPResult::True();
  322. if (TPR == TPResult::Ambiguous()) {
  323. // We are supposed to be inside parens, so if after the abstract declarator
  324. // we encounter a ')' this is a type-id, otherwise it's an expression.
  325. if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
  326. TPR = TPResult::True();
  327. isAmbiguous = true;
  328. // We are supposed to be inside a template argument, so if after
  329. // the abstract declarator we encounter a '>', '>>' (in C++0x), or
  330. // ',', this is a type-id. Otherwise, it's an expression.
  331. } else if (Context == TypeIdAsTemplateArgument &&
  332. (Tok.is(tok::greater) || Tok.is(tok::comma) ||
  333. (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
  334. TPR = TPResult::True();
  335. isAmbiguous = true;
  336. } else
  337. TPR = TPResult::False();
  338. }
  339. PA.Revert();
  340. assert(TPR == TPResult::True() || TPR == TPResult::False());
  341. return TPR == TPResult::True();
  342. }
  343. /// \brief Returns true if this is a C++11 attribute-specifier. Per
  344. /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
  345. /// always introduce an attribute. In Objective-C++11, this rule does not
  346. /// apply if either '[' begins a message-send.
  347. ///
  348. /// If Disambiguate is true, we try harder to determine whether a '[[' starts
  349. /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
  350. ///
  351. /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
  352. /// Obj-C message send or the start of an attribute. Otherwise, we assume it
  353. /// is not an Obj-C message send.
  354. ///
  355. /// C++11 [dcl.attr.grammar]:
  356. ///
  357. /// attribute-specifier:
  358. /// '[' '[' attribute-list ']' ']'
  359. /// alignment-specifier
  360. ///
  361. /// attribute-list:
  362. /// attribute[opt]
  363. /// attribute-list ',' attribute[opt]
  364. /// attribute '...'
  365. /// attribute-list ',' attribute '...'
  366. ///
  367. /// attribute:
  368. /// attribute-token attribute-argument-clause[opt]
  369. ///
  370. /// attribute-token:
  371. /// identifier
  372. /// identifier '::' identifier
  373. ///
  374. /// attribute-argument-clause:
  375. /// '(' balanced-token-seq ')'
  376. Parser::CXX11AttributeKind
  377. Parser::isCXX11AttributeSpecifier(bool Disambiguate,
  378. bool OuterMightBeMessageSend) {
  379. if (Tok.is(tok::kw_alignas))
  380. return CAK_AttributeSpecifier;
  381. if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
  382. return CAK_NotAttributeSpecifier;
  383. // No tentative parsing if we don't need to look for ']]' or a lambda.
  384. if (!Disambiguate && !getLangOpts().ObjC1)
  385. return CAK_AttributeSpecifier;
  386. TentativeParsingAction PA(*this);
  387. // Opening brackets were checked for above.
  388. ConsumeBracket();
  389. // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
  390. if (!getLangOpts().ObjC1) {
  391. ConsumeBracket();
  392. bool IsAttribute = SkipUntil(tok::r_square, false);
  393. IsAttribute &= Tok.is(tok::r_square);
  394. PA.Revert();
  395. return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
  396. }
  397. // In Obj-C++11, we need to distinguish four situations:
  398. // 1a) int x[[attr]]; C++11 attribute.
  399. // 1b) [[attr]]; C++11 statement attribute.
  400. // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
  401. // 3a) int x[[obj get]]; Message send in array size/index.
  402. // 3b) [[Class alloc] init]; Message send in message send.
  403. // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
  404. // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
  405. // If we have a lambda-introducer, then this is definitely not a message send.
  406. // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
  407. // into the tentative attribute parse below.
  408. LambdaIntroducer Intro;
  409. if (!TryParseLambdaIntroducer(Intro)) {
  410. // A lambda cannot end with ']]', and an attribute must.
  411. bool IsAttribute = Tok.is(tok::r_square);
  412. PA.Revert();
  413. if (IsAttribute)
  414. // Case 1: C++11 attribute.
  415. return CAK_AttributeSpecifier;
  416. if (OuterMightBeMessageSend)
  417. // Case 4: Lambda in message send.
  418. return CAK_NotAttributeSpecifier;
  419. // Case 2: Lambda in array size / index.
  420. return CAK_InvalidAttributeSpecifier;
  421. }
  422. ConsumeBracket();
  423. // If we don't have a lambda-introducer, then we have an attribute or a
  424. // message-send.
  425. bool IsAttribute = true;
  426. while (Tok.isNot(tok::r_square)) {
  427. if (Tok.is(tok::comma)) {
  428. // Case 1: Stray commas can only occur in attributes.
  429. PA.Revert();
  430. return CAK_AttributeSpecifier;
  431. }
  432. // Parse the attribute-token, if present.
  433. // C++11 [dcl.attr.grammar]:
  434. // If a keyword or an alternative token that satisfies the syntactic
  435. // requirements of an identifier is contained in an attribute-token,
  436. // it is considered an identifier.
  437. SourceLocation Loc;
  438. if (!TryParseCXX11AttributeIdentifier(Loc)) {
  439. IsAttribute = false;
  440. break;
  441. }
  442. if (Tok.is(tok::coloncolon)) {
  443. ConsumeToken();
  444. if (!TryParseCXX11AttributeIdentifier(Loc)) {
  445. IsAttribute = false;
  446. break;
  447. }
  448. }
  449. // Parse the attribute-argument-clause, if present.
  450. if (Tok.is(tok::l_paren)) {
  451. ConsumeParen();
  452. if (!SkipUntil(tok::r_paren, false)) {
  453. IsAttribute = false;
  454. break;
  455. }
  456. }
  457. if (Tok.is(tok::ellipsis))
  458. ConsumeToken();
  459. if (Tok.isNot(tok::comma))
  460. break;
  461. ConsumeToken();
  462. }
  463. // An attribute must end ']]'.
  464. if (IsAttribute) {
  465. if (Tok.is(tok::r_square)) {
  466. ConsumeBracket();
  467. IsAttribute = Tok.is(tok::r_square);
  468. } else {
  469. IsAttribute = false;
  470. }
  471. }
  472. PA.Revert();
  473. if (IsAttribute)
  474. // Case 1: C++11 statement attribute.
  475. return CAK_AttributeSpecifier;
  476. // Case 3: Message send.
  477. return CAK_NotAttributeSpecifier;
  478. }
  479. /// declarator:
  480. /// direct-declarator
  481. /// ptr-operator declarator
  482. ///
  483. /// direct-declarator:
  484. /// declarator-id
  485. /// direct-declarator '(' parameter-declaration-clause ')'
  486. /// cv-qualifier-seq[opt] exception-specification[opt]
  487. /// direct-declarator '[' constant-expression[opt] ']'
  488. /// '(' declarator ')'
  489. /// [GNU] '(' attributes declarator ')'
  490. ///
  491. /// abstract-declarator:
  492. /// ptr-operator abstract-declarator[opt]
  493. /// direct-abstract-declarator
  494. /// ...
  495. ///
  496. /// direct-abstract-declarator:
  497. /// direct-abstract-declarator[opt]
  498. /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  499. /// exception-specification[opt]
  500. /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
  501. /// '(' abstract-declarator ')'
  502. ///
  503. /// ptr-operator:
  504. /// '*' cv-qualifier-seq[opt]
  505. /// '&'
  506. /// [C++0x] '&&' [TODO]
  507. /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
  508. ///
  509. /// cv-qualifier-seq:
  510. /// cv-qualifier cv-qualifier-seq[opt]
  511. ///
  512. /// cv-qualifier:
  513. /// 'const'
  514. /// 'volatile'
  515. ///
  516. /// declarator-id:
  517. /// '...'[opt] id-expression
  518. ///
  519. /// id-expression:
  520. /// unqualified-id
  521. /// qualified-id [TODO]
  522. ///
  523. /// unqualified-id:
  524. /// identifier
  525. /// operator-function-id [TODO]
  526. /// conversion-function-id [TODO]
  527. /// '~' class-name [TODO]
  528. /// template-id [TODO]
  529. ///
  530. Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
  531. bool mayHaveIdentifier) {
  532. // declarator:
  533. // direct-declarator
  534. // ptr-operator declarator
  535. while (1) {
  536. if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
  537. if (TryAnnotateCXXScopeToken(true))
  538. return TPResult::Error();
  539. if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
  540. Tok.is(tok::ampamp) ||
  541. (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
  542. // ptr-operator
  543. ConsumeToken();
  544. while (Tok.is(tok::kw_const) ||
  545. Tok.is(tok::kw_volatile) ||
  546. Tok.is(tok::kw_restrict))
  547. ConsumeToken();
  548. } else {
  549. break;
  550. }
  551. }
  552. // direct-declarator:
  553. // direct-abstract-declarator:
  554. if (Tok.is(tok::ellipsis))
  555. ConsumeToken();
  556. if ((Tok.is(tok::identifier) ||
  557. (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) &&
  558. mayHaveIdentifier) {
  559. // declarator-id
  560. if (Tok.is(tok::annot_cxxscope))
  561. ConsumeToken();
  562. else
  563. TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
  564. ConsumeToken();
  565. } else if (Tok.is(tok::l_paren)) {
  566. ConsumeParen();
  567. if (mayBeAbstract &&
  568. (Tok.is(tok::r_paren) || // 'int()' is a function.
  569. // 'int(...)' is a function.
  570. (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
  571. isDeclarationSpecifier())) { // 'int(int)' is a function.
  572. // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  573. // exception-specification[opt]
  574. TPResult TPR = TryParseFunctionDeclarator();
  575. if (TPR != TPResult::Ambiguous())
  576. return TPR;
  577. } else {
  578. // '(' declarator ')'
  579. // '(' attributes declarator ')'
  580. // '(' abstract-declarator ')'
  581. if (Tok.is(tok::kw___attribute) ||
  582. Tok.is(tok::kw___declspec) ||
  583. Tok.is(tok::kw___cdecl) ||
  584. Tok.is(tok::kw___stdcall) ||
  585. Tok.is(tok::kw___fastcall) ||
  586. Tok.is(tok::kw___thiscall) ||
  587. Tok.is(tok::kw___unaligned))
  588. return TPResult::True(); // attributes indicate declaration
  589. TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
  590. if (TPR != TPResult::Ambiguous())
  591. return TPR;
  592. if (Tok.isNot(tok::r_paren))
  593. return TPResult::False();
  594. ConsumeParen();
  595. }
  596. } else if (!mayBeAbstract) {
  597. return TPResult::False();
  598. }
  599. while (1) {
  600. TPResult TPR(TPResult::Ambiguous());
  601. // abstract-declarator: ...
  602. if (Tok.is(tok::ellipsis))
  603. ConsumeToken();
  604. if (Tok.is(tok::l_paren)) {
  605. // Check whether we have a function declarator or a possible ctor-style
  606. // initializer that follows the declarator. Note that ctor-style
  607. // initializers are not possible in contexts where abstract declarators
  608. // are allowed.
  609. if (!mayBeAbstract && !isCXXFunctionDeclarator())
  610. break;
  611. // direct-declarator '(' parameter-declaration-clause ')'
  612. // cv-qualifier-seq[opt] exception-specification[opt]
  613. ConsumeParen();
  614. TPR = TryParseFunctionDeclarator();
  615. } else if (Tok.is(tok::l_square)) {
  616. // direct-declarator '[' constant-expression[opt] ']'
  617. // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
  618. TPR = TryParseBracketDeclarator();
  619. } else {
  620. break;
  621. }
  622. if (TPR != TPResult::Ambiguous())
  623. return TPR;
  624. }
  625. return TPResult::Ambiguous();
  626. }
  627. Parser::TPResult
  628. Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
  629. switch (Kind) {
  630. // Obviously starts an expression.
  631. case tok::numeric_constant:
  632. case tok::char_constant:
  633. case tok::wide_char_constant:
  634. case tok::utf16_char_constant:
  635. case tok::utf32_char_constant:
  636. case tok::string_literal:
  637. case tok::wide_string_literal:
  638. case tok::utf8_string_literal:
  639. case tok::utf16_string_literal:
  640. case tok::utf32_string_literal:
  641. case tok::l_square:
  642. case tok::l_paren:
  643. case tok::amp:
  644. case tok::ampamp:
  645. case tok::star:
  646. case tok::plus:
  647. case tok::plusplus:
  648. case tok::minus:
  649. case tok::minusminus:
  650. case tok::tilde:
  651. case tok::exclaim:
  652. case tok::kw_sizeof:
  653. case tok::kw___func__:
  654. case tok::kw_const_cast:
  655. case tok::kw_delete:
  656. case tok::kw_dynamic_cast:
  657. case tok::kw_false:
  658. case tok::kw_new:
  659. case tok::kw_operator:
  660. case tok::kw_reinterpret_cast:
  661. case tok::kw_static_cast:
  662. case tok::kw_this:
  663. case tok::kw_throw:
  664. case tok::kw_true:
  665. case tok::kw_typeid:
  666. case tok::kw_alignof:
  667. case tok::kw_noexcept:
  668. case tok::kw_nullptr:
  669. case tok::kw__Alignof:
  670. case tok::kw___null:
  671. case tok::kw___alignof:
  672. case tok::kw___builtin_choose_expr:
  673. case tok::kw___builtin_offsetof:
  674. case tok::kw___builtin_types_compatible_p:
  675. case tok::kw___builtin_va_arg:
  676. case tok::kw___imag:
  677. case tok::kw___real:
  678. case tok::kw___FUNCTION__:
  679. case tok::kw_L__FUNCTION__:
  680. case tok::kw___PRETTY_FUNCTION__:
  681. case tok::kw___has_nothrow_assign:
  682. case tok::kw___has_nothrow_copy:
  683. case tok::kw___has_nothrow_constructor:
  684. case tok::kw___has_trivial_assign:
  685. case tok::kw___has_trivial_copy:
  686. case tok::kw___has_trivial_constructor:
  687. case tok::kw___has_trivial_destructor:
  688. case tok::kw___has_virtual_destructor:
  689. case tok::kw___is_abstract:
  690. case tok::kw___is_base_of:
  691. case tok::kw___is_class:
  692. case tok::kw___is_convertible_to:
  693. case tok::kw___is_empty:
  694. case tok::kw___is_enum:
  695. case tok::kw___is_interface_class:
  696. case tok::kw___is_final:
  697. case tok::kw___is_literal:
  698. case tok::kw___is_literal_type:
  699. case tok::kw___is_pod:
  700. case tok::kw___is_polymorphic:
  701. case tok::kw___is_trivial:
  702. case tok::kw___is_trivially_assignable:
  703. case tok::kw___is_trivially_constructible:
  704. case tok::kw___is_trivially_copyable:
  705. case tok::kw___is_union:
  706. case tok::kw___uuidof:
  707. return TPResult::True();
  708. // Obviously starts a type-specifier-seq:
  709. case tok::kw_char:
  710. case tok::kw_const:
  711. case tok::kw_double:
  712. case tok::kw_enum:
  713. case tok::kw_half:
  714. case tok::kw_float:
  715. case tok::kw_int:
  716. case tok::kw_long:
  717. case tok::kw___int64:
  718. case tok::kw___int128:
  719. case tok::kw_restrict:
  720. case tok::kw_short:
  721. case tok::kw_signed:
  722. case tok::kw_struct:
  723. case tok::kw_union:
  724. case tok::kw_unsigned:
  725. case tok::kw_void:
  726. case tok::kw_volatile:
  727. case tok::kw__Bool:
  728. case tok::kw__Complex:
  729. case tok::kw_class:
  730. case tok::kw_typename:
  731. case tok::kw_wchar_t:
  732. case tok::kw_char16_t:
  733. case tok::kw_char32_t:
  734. case tok::kw___underlying_type:
  735. case tok::kw_thread_local:
  736. case tok::kw__Decimal32:
  737. case tok::kw__Decimal64:
  738. case tok::kw__Decimal128:
  739. case tok::kw___thread:
  740. case tok::kw_typeof:
  741. case tok::kw___cdecl:
  742. case tok::kw___stdcall:
  743. case tok::kw___fastcall:
  744. case tok::kw___thiscall:
  745. case tok::kw___unaligned:
  746. case tok::kw___vector:
  747. case tok::kw___pixel:
  748. case tok::kw__Atomic:
  749. case tok::kw_image1d_t:
  750. case tok::kw_image1d_array_t:
  751. case tok::kw_image1d_buffer_t:
  752. case tok::kw_image2d_t:
  753. case tok::kw_image2d_array_t:
  754. case tok::kw_image3d_t:
  755. case tok::kw_sampler_t:
  756. case tok::kw_event_t:
  757. case tok::kw___unknown_anytype:
  758. return TPResult::False();
  759. default:
  760. break;
  761. }
  762. return TPResult::Ambiguous();
  763. }
  764. bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
  765. return std::find(TentativelyDeclaredIdentifiers.begin(),
  766. TentativelyDeclaredIdentifiers.end(), II)
  767. != TentativelyDeclaredIdentifiers.end();
  768. }
  769. /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
  770. /// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
  771. /// be either a decl-specifier or a function-style cast, and TPResult::Error()
  772. /// if a parsing error was found and reported.
  773. ///
  774. /// If HasMissingTypename is provided, a name with a dependent scope specifier
  775. /// will be treated as ambiguous if the 'typename' keyword is missing. If this
  776. /// happens, *HasMissingTypename will be set to 'true'. This will also be used
  777. /// as an indicator that undeclared identifiers (which will trigger a later
  778. /// parse error) should be treated as types. Returns TPResult::Ambiguous() in
  779. /// such cases.
  780. ///
  781. /// decl-specifier:
  782. /// storage-class-specifier
  783. /// type-specifier
  784. /// function-specifier
  785. /// 'friend'
  786. /// 'typedef'
  787. /// [C++0x] 'constexpr'
  788. /// [GNU] attributes declaration-specifiers[opt]
  789. ///
  790. /// storage-class-specifier:
  791. /// 'register'
  792. /// 'static'
  793. /// 'extern'
  794. /// 'mutable'
  795. /// 'auto'
  796. /// [GNU] '__thread'
  797. ///
  798. /// function-specifier:
  799. /// 'inline'
  800. /// 'virtual'
  801. /// 'explicit'
  802. ///
  803. /// typedef-name:
  804. /// identifier
  805. ///
  806. /// type-specifier:
  807. /// simple-type-specifier
  808. /// class-specifier
  809. /// enum-specifier
  810. /// elaborated-type-specifier
  811. /// typename-specifier
  812. /// cv-qualifier
  813. ///
  814. /// simple-type-specifier:
  815. /// '::'[opt] nested-name-specifier[opt] type-name
  816. /// '::'[opt] nested-name-specifier 'template'
  817. /// simple-template-id [TODO]
  818. /// 'char'
  819. /// 'wchar_t'
  820. /// 'bool'
  821. /// 'short'
  822. /// 'int'
  823. /// 'long'
  824. /// 'signed'
  825. /// 'unsigned'
  826. /// 'float'
  827. /// 'double'
  828. /// 'void'
  829. /// [GNU] typeof-specifier
  830. /// [GNU] '_Complex'
  831. /// [C++0x] 'auto' [TODO]
  832. /// [C++0x] 'decltype' ( expression )
  833. ///
  834. /// type-name:
  835. /// class-name
  836. /// enum-name
  837. /// typedef-name
  838. ///
  839. /// elaborated-type-specifier:
  840. /// class-key '::'[opt] nested-name-specifier[opt] identifier
  841. /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
  842. /// simple-template-id
  843. /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
  844. ///
  845. /// enum-name:
  846. /// identifier
  847. ///
  848. /// enum-specifier:
  849. /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
  850. /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
  851. ///
  852. /// class-specifier:
  853. /// class-head '{' member-specification[opt] '}'
  854. ///
  855. /// class-head:
  856. /// class-key identifier[opt] base-clause[opt]
  857. /// class-key nested-name-specifier identifier base-clause[opt]
  858. /// class-key nested-name-specifier[opt] simple-template-id
  859. /// base-clause[opt]
  860. ///
  861. /// class-key:
  862. /// 'class'
  863. /// 'struct'
  864. /// 'union'
  865. ///
  866. /// cv-qualifier:
  867. /// 'const'
  868. /// 'volatile'
  869. /// [GNU] restrict
  870. ///
  871. Parser::TPResult
  872. Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
  873. bool *HasMissingTypename) {
  874. switch (Tok.getKind()) {
  875. case tok::identifier: {
  876. // Check for need to substitute AltiVec __vector keyword
  877. // for "vector" identifier.
  878. if (TryAltiVecVectorToken())
  879. return TPResult::True();
  880. const Token &Next = NextToken();
  881. // In 'foo bar', 'foo' is always a type name outside of Objective-C.
  882. if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
  883. return TPResult::True();
  884. if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
  885. // Determine whether this is a valid expression. If not, we will hit
  886. // a parse error one way or another. In that case, tell the caller that
  887. // this is ambiguous. Typo-correct to type and expression keywords and
  888. // to types and identifiers, in order to try to recover from errors.
  889. CorrectionCandidateCallback TypoCorrection;
  890. TypoCorrection.WantRemainingKeywords = false;
  891. switch (TryAnnotateName(false /* no nested name specifier */,
  892. &TypoCorrection)) {
  893. case ANK_Error:
  894. return TPResult::Error();
  895. case ANK_TentativeDecl:
  896. return TPResult::False();
  897. case ANK_TemplateName:
  898. // A bare type template-name which can't be a template template
  899. // argument is an error, and was probably intended to be a type.
  900. return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
  901. case ANK_Unresolved:
  902. return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False();
  903. case ANK_Success:
  904. break;
  905. }
  906. assert(Tok.isNot(tok::identifier) &&
  907. "TryAnnotateName succeeded without producing an annotation");
  908. } else {
  909. // This might possibly be a type with a dependent scope specifier and
  910. // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
  911. // since it will annotate as a primary expression, and we want to use the
  912. // "missing 'typename'" logic.
  913. if (TryAnnotateTypeOrScopeToken())
  914. return TPResult::Error();
  915. // If annotation failed, assume it's a non-type.
  916. // FIXME: If this happens due to an undeclared identifier, treat it as
  917. // ambiguous.
  918. if (Tok.is(tok::identifier))
  919. return TPResult::False();
  920. }
  921. // We annotated this token as something. Recurse to handle whatever we got.
  922. return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
  923. }
  924. case tok::kw_typename: // typename T::type
  925. // Annotate typenames and C++ scope specifiers. If we get one, just
  926. // recurse to handle whatever we get.
  927. if (TryAnnotateTypeOrScopeToken())
  928. return TPResult::Error();
  929. return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
  930. case tok::coloncolon: { // ::foo::bar
  931. const Token &Next = NextToken();
  932. if (Next.is(tok::kw_new) || // ::new
  933. Next.is(tok::kw_delete)) // ::delete
  934. return TPResult::False();
  935. }
  936. // Fall through.
  937. case tok::kw_decltype:
  938. // Annotate typenames and C++ scope specifiers. If we get one, just
  939. // recurse to handle whatever we get.
  940. if (TryAnnotateTypeOrScopeToken())
  941. return TPResult::Error();
  942. return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
  943. // decl-specifier:
  944. // storage-class-specifier
  945. // type-specifier
  946. // function-specifier
  947. // 'friend'
  948. // 'typedef'
  949. // 'constexpr'
  950. case tok::kw_friend:
  951. case tok::kw_typedef:
  952. case tok::kw_constexpr:
  953. // storage-class-specifier
  954. case tok::kw_register:
  955. case tok::kw_static:
  956. case tok::kw_extern:
  957. case tok::kw_mutable:
  958. case tok::kw_auto:
  959. case tok::kw___thread:
  960. // function-specifier
  961. case tok::kw_inline:
  962. case tok::kw_virtual:
  963. case tok::kw_explicit:
  964. // Modules
  965. case tok::kw___module_private__:
  966. // Debugger support
  967. case tok::kw___unknown_anytype:
  968. // type-specifier:
  969. // simple-type-specifier
  970. // class-specifier
  971. // enum-specifier
  972. // elaborated-type-specifier
  973. // typename-specifier
  974. // cv-qualifier
  975. // class-specifier
  976. // elaborated-type-specifier
  977. case tok::kw_class:
  978. case tok::kw_struct:
  979. case tok::kw_union:
  980. // enum-specifier
  981. case tok::kw_enum:
  982. // cv-qualifier
  983. case tok::kw_const:
  984. case tok::kw_volatile:
  985. // GNU
  986. case tok::kw_restrict:
  987. case tok::kw__Complex:
  988. case tok::kw___attribute:
  989. return TPResult::True();
  990. // Microsoft
  991. case tok::kw___declspec:
  992. case tok::kw___cdecl:
  993. case tok::kw___stdcall:
  994. case tok::kw___fastcall:
  995. case tok::kw___thiscall:
  996. case tok::kw___w64:
  997. case tok::kw___ptr64:
  998. case tok::kw___ptr32:
  999. case tok::kw___forceinline:
  1000. case tok::kw___unaligned:
  1001. return TPResult::True();
  1002. // Borland
  1003. case tok::kw___pascal:
  1004. return TPResult::True();
  1005. // AltiVec
  1006. case tok::kw___vector:
  1007. return TPResult::True();
  1008. case tok::annot_template_id: {
  1009. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1010. if (TemplateId->Kind != TNK_Type_template)
  1011. return TPResult::False();
  1012. CXXScopeSpec SS;
  1013. AnnotateTemplateIdTokenAsType();
  1014. assert(Tok.is(tok::annot_typename));
  1015. goto case_typename;
  1016. }
  1017. case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
  1018. // We've already annotated a scope; try to annotate a type.
  1019. if (TryAnnotateTypeOrScopeToken())
  1020. return TPResult::Error();
  1021. if (!Tok.is(tok::annot_typename)) {
  1022. // If the next token is an identifier or a type qualifier, then this
  1023. // can't possibly be a valid expression either.
  1024. if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
  1025. CXXScopeSpec SS;
  1026. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  1027. Tok.getAnnotationRange(),
  1028. SS);
  1029. if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
  1030. TentativeParsingAction PA(*this);
  1031. ConsumeToken();
  1032. ConsumeToken();
  1033. bool isIdentifier = Tok.is(tok::identifier);
  1034. TPResult TPR = TPResult::False();
  1035. if (!isIdentifier)
  1036. TPR = isCXXDeclarationSpecifier(BracedCastResult,
  1037. HasMissingTypename);
  1038. PA.Revert();
  1039. if (isIdentifier ||
  1040. TPR == TPResult::True() || TPR == TPResult::Error())
  1041. return TPResult::Error();
  1042. if (HasMissingTypename) {
  1043. // We can't tell whether this is a missing 'typename' or a valid
  1044. // expression.
  1045. *HasMissingTypename = true;
  1046. return TPResult::Ambiguous();
  1047. }
  1048. } else {
  1049. // Try to resolve the name. If it doesn't exist, assume it was
  1050. // intended to name a type and keep disambiguating.
  1051. switch (TryAnnotateName(false /* SS is not dependent */)) {
  1052. case ANK_Error:
  1053. return TPResult::Error();
  1054. case ANK_TentativeDecl:
  1055. return TPResult::False();
  1056. case ANK_TemplateName:
  1057. // A bare type template-name which can't be a template template
  1058. // argument is an error, and was probably intended to be a type.
  1059. return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
  1060. case ANK_Unresolved:
  1061. return HasMissingTypename ? TPResult::Ambiguous()
  1062. : TPResult::False();
  1063. case ANK_Success:
  1064. // Annotated it, check again.
  1065. assert(Tok.isNot(tok::annot_cxxscope) ||
  1066. NextToken().isNot(tok::identifier));
  1067. return isCXXDeclarationSpecifier(BracedCastResult,
  1068. HasMissingTypename);
  1069. }
  1070. }
  1071. }
  1072. return TPResult::False();
  1073. }
  1074. // If that succeeded, fallthrough into the generic simple-type-id case.
  1075. // The ambiguity resides in a simple-type-specifier/typename-specifier
  1076. // followed by a '('. The '(' could either be the start of:
  1077. //
  1078. // direct-declarator:
  1079. // '(' declarator ')'
  1080. //
  1081. // direct-abstract-declarator:
  1082. // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  1083. // exception-specification[opt]
  1084. // '(' abstract-declarator ')'
  1085. //
  1086. // or part of a function-style cast expression:
  1087. //
  1088. // simple-type-specifier '(' expression-list[opt] ')'
  1089. //
  1090. // simple-type-specifier:
  1091. case tok::annot_typename:
  1092. case_typename:
  1093. // In Objective-C, we might have a protocol-qualified type.
  1094. if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
  1095. // Tentatively parse the
  1096. TentativeParsingAction PA(*this);
  1097. ConsumeToken(); // The type token
  1098. TPResult TPR = TryParseProtocolQualifiers();
  1099. bool isFollowedByParen = Tok.is(tok::l_paren);
  1100. bool isFollowedByBrace = Tok.is(tok::l_brace);
  1101. PA.Revert();
  1102. if (TPR == TPResult::Error())
  1103. return TPResult::Error();
  1104. if (isFollowedByParen)
  1105. return TPResult::Ambiguous();
  1106. if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
  1107. return BracedCastResult;
  1108. return TPResult::True();
  1109. }
  1110. case tok::kw_char:
  1111. case tok::kw_wchar_t:
  1112. case tok::kw_char16_t:
  1113. case tok::kw_char32_t:
  1114. case tok::kw_bool:
  1115. case tok::kw_short:
  1116. case tok::kw_int:
  1117. case tok::kw_long:
  1118. case tok::kw___int64:
  1119. case tok::kw___int128:
  1120. case tok::kw_signed:
  1121. case tok::kw_unsigned:
  1122. case tok::kw_half:
  1123. case tok::kw_float:
  1124. case tok::kw_double:
  1125. case tok::kw_void:
  1126. case tok::annot_decltype:
  1127. if (NextToken().is(tok::l_paren))
  1128. return TPResult::Ambiguous();
  1129. // This is a function-style cast in all cases we disambiguate other than
  1130. // one:
  1131. // struct S {
  1132. // enum E : int { a = 4 }; // enum
  1133. // enum E : int { 4 }; // bit-field
  1134. // };
  1135. if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
  1136. return BracedCastResult;
  1137. if (isStartOfObjCClassMessageMissingOpenBracket())
  1138. return TPResult::False();
  1139. return TPResult::True();
  1140. // GNU typeof support.
  1141. case tok::kw_typeof: {
  1142. if (NextToken().isNot(tok::l_paren))
  1143. return TPResult::True();
  1144. TentativeParsingAction PA(*this);
  1145. TPResult TPR = TryParseTypeofSpecifier();
  1146. bool isFollowedByParen = Tok.is(tok::l_paren);
  1147. bool isFollowedByBrace = Tok.is(tok::l_brace);
  1148. PA.Revert();
  1149. if (TPR == TPResult::Error())
  1150. return TPResult::Error();
  1151. if (isFollowedByParen)
  1152. return TPResult::Ambiguous();
  1153. if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
  1154. return BracedCastResult;
  1155. return TPResult::True();
  1156. }
  1157. // C++0x type traits support
  1158. case tok::kw___underlying_type:
  1159. return TPResult::True();
  1160. // C11 _Atomic
  1161. case tok::kw__Atomic:
  1162. return TPResult::True();
  1163. default:
  1164. return TPResult::False();
  1165. }
  1166. }
  1167. /// [GNU] typeof-specifier:
  1168. /// 'typeof' '(' expressions ')'
  1169. /// 'typeof' '(' type-name ')'
  1170. ///
  1171. Parser::TPResult Parser::TryParseTypeofSpecifier() {
  1172. assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
  1173. ConsumeToken();
  1174. assert(Tok.is(tok::l_paren) && "Expected '('");
  1175. // Parse through the parens after 'typeof'.
  1176. ConsumeParen();
  1177. if (!SkipUntil(tok::r_paren))
  1178. return TPResult::Error();
  1179. return TPResult::Ambiguous();
  1180. }
  1181. /// [ObjC] protocol-qualifiers:
  1182. //// '<' identifier-list '>'
  1183. Parser::TPResult Parser::TryParseProtocolQualifiers() {
  1184. assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
  1185. ConsumeToken();
  1186. do {
  1187. if (Tok.isNot(tok::identifier))
  1188. return TPResult::Error();
  1189. ConsumeToken();
  1190. if (Tok.is(tok::comma)) {
  1191. ConsumeToken();
  1192. continue;
  1193. }
  1194. if (Tok.is(tok::greater)) {
  1195. ConsumeToken();
  1196. return TPResult::Ambiguous();
  1197. }
  1198. } while (false);
  1199. return TPResult::Error();
  1200. }
  1201. Parser::TPResult
  1202. Parser::TryParseDeclarationSpecifier(bool *HasMissingTypename) {
  1203. TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
  1204. HasMissingTypename);
  1205. if (TPR != TPResult::Ambiguous())
  1206. return TPR;
  1207. if (Tok.is(tok::kw_typeof))
  1208. TryParseTypeofSpecifier();
  1209. else {
  1210. if (Tok.is(tok::annot_cxxscope))
  1211. ConsumeToken();
  1212. ConsumeToken();
  1213. if (getLangOpts().ObjC1 && Tok.is(tok::less))
  1214. TryParseProtocolQualifiers();
  1215. }
  1216. return TPResult::Ambiguous();
  1217. }
  1218. /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
  1219. /// a constructor-style initializer, when parsing declaration statements.
  1220. /// Returns true for function declarator and false for constructor-style
  1221. /// initializer.
  1222. /// If during the disambiguation process a parsing error is encountered,
  1223. /// the function returns true to let the declaration parsing code handle it.
  1224. ///
  1225. /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  1226. /// exception-specification[opt]
  1227. ///
  1228. bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
  1229. // C++ 8.2p1:
  1230. // The ambiguity arising from the similarity between a function-style cast and
  1231. // a declaration mentioned in 6.8 can also occur in the context of a
  1232. // declaration. In that context, the choice is between a function declaration
  1233. // with a redundant set of parentheses around a parameter name and an object
  1234. // declaration with a function-style cast as the initializer. Just as for the
  1235. // ambiguities mentioned in 6.8, the resolution is to consider any construct
  1236. // that could possibly be a declaration a declaration.
  1237. TentativeParsingAction PA(*this);
  1238. ConsumeParen();
  1239. bool InvalidAsDeclaration = false;
  1240. TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
  1241. if (TPR == TPResult::Ambiguous()) {
  1242. if (Tok.isNot(tok::r_paren))
  1243. TPR = TPResult::False();
  1244. else {
  1245. const Token &Next = NextToken();
  1246. if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
  1247. Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
  1248. Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
  1249. Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
  1250. Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
  1251. Next.is(tok::equal) || Next.is(tok::arrow))
  1252. // The next token cannot appear after a constructor-style initializer,
  1253. // and can appear next in a function definition. This must be a function
  1254. // declarator.
  1255. TPR = TPResult::True();
  1256. else if (InvalidAsDeclaration)
  1257. // Use the absence of 'typename' as a tie-breaker.
  1258. TPR = TPResult::False();
  1259. }
  1260. }
  1261. PA.Revert();
  1262. if (IsAmbiguous && TPR == TPResult::Ambiguous())
  1263. *IsAmbiguous = true;
  1264. // In case of an error, let the declaration parsing code handle it.
  1265. return TPR != TPResult::False();
  1266. }
  1267. /// parameter-declaration-clause:
  1268. /// parameter-declaration-list[opt] '...'[opt]
  1269. /// parameter-declaration-list ',' '...'
  1270. ///
  1271. /// parameter-declaration-list:
  1272. /// parameter-declaration
  1273. /// parameter-declaration-list ',' parameter-declaration
  1274. ///
  1275. /// parameter-declaration:
  1276. /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
  1277. /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
  1278. /// '=' assignment-expression
  1279. /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
  1280. /// attributes[opt]
  1281. /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
  1282. /// attributes[opt] '=' assignment-expression
  1283. ///
  1284. Parser::TPResult
  1285. Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration) {
  1286. if (Tok.is(tok::r_paren))
  1287. return TPResult::Ambiguous();
  1288. // parameter-declaration-list[opt] '...'[opt]
  1289. // parameter-declaration-list ',' '...'
  1290. //
  1291. // parameter-declaration-list:
  1292. // parameter-declaration
  1293. // parameter-declaration-list ',' parameter-declaration
  1294. //
  1295. while (1) {
  1296. // '...'[opt]
  1297. if (Tok.is(tok::ellipsis)) {
  1298. ConsumeToken();
  1299. if (Tok.is(tok::r_paren))
  1300. return TPResult::True(); // '...)' is a sign of a function declarator.
  1301. else
  1302. return TPResult::False();
  1303. }
  1304. // An attribute-specifier-seq here is a sign of a function declarator.
  1305. if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
  1306. /*OuterMightBeMessageSend*/true))
  1307. return TPResult::True();
  1308. ParsedAttributes attrs(AttrFactory);
  1309. MaybeParseMicrosoftAttributes(attrs);
  1310. // decl-specifier-seq
  1311. // A parameter-declaration's initializer must be preceded by an '=', so
  1312. // decl-specifier-seq '{' is not a parameter in C++11.
  1313. TPResult TPR = TryParseDeclarationSpecifier(InvalidAsDeclaration);
  1314. if (TPR != TPResult::Ambiguous())
  1315. return TPR;
  1316. // declarator
  1317. // abstract-declarator[opt]
  1318. TPR = TryParseDeclarator(true/*mayBeAbstract*/);
  1319. if (TPR != TPResult::Ambiguous())
  1320. return TPR;
  1321. // [GNU] attributes[opt]
  1322. if (Tok.is(tok::kw___attribute))
  1323. return TPResult::True();
  1324. if (Tok.is(tok::equal)) {
  1325. // '=' assignment-expression
  1326. // Parse through assignment-expression.
  1327. if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/,
  1328. true/*DontConsume*/))
  1329. return TPResult::Error();
  1330. }
  1331. if (Tok.is(tok::ellipsis)) {
  1332. ConsumeToken();
  1333. if (Tok.is(tok::r_paren))
  1334. return TPResult::True(); // '...)' is a sign of a function declarator.
  1335. else
  1336. return TPResult::False();
  1337. }
  1338. if (Tok.isNot(tok::comma))
  1339. break;
  1340. ConsumeToken(); // the comma.
  1341. }
  1342. return TPResult::Ambiguous();
  1343. }
  1344. /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
  1345. /// parsing as a function declarator.
  1346. /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
  1347. /// return TPResult::Ambiguous(), otherwise it will return either False() or
  1348. /// Error().
  1349. ///
  1350. /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
  1351. /// exception-specification[opt]
  1352. ///
  1353. /// exception-specification:
  1354. /// 'throw' '(' type-id-list[opt] ')'
  1355. ///
  1356. Parser::TPResult Parser::TryParseFunctionDeclarator() {
  1357. // The '(' is already parsed.
  1358. TPResult TPR = TryParseParameterDeclarationClause();
  1359. if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
  1360. TPR = TPResult::False();
  1361. if (TPR == TPResult::False() || TPR == TPResult::Error())
  1362. return TPR;
  1363. // Parse through the parens.
  1364. if (!SkipUntil(tok::r_paren))
  1365. return TPResult::Error();
  1366. // cv-qualifier-seq
  1367. while (Tok.is(tok::kw_const) ||
  1368. Tok.is(tok::kw_volatile) ||
  1369. Tok.is(tok::kw_restrict) )
  1370. ConsumeToken();
  1371. // ref-qualifier[opt]
  1372. if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
  1373. ConsumeToken();
  1374. // exception-specification
  1375. if (Tok.is(tok::kw_throw)) {
  1376. ConsumeToken();
  1377. if (Tok.isNot(tok::l_paren))
  1378. return TPResult::Error();
  1379. // Parse through the parens after 'throw'.
  1380. ConsumeParen();
  1381. if (!SkipUntil(tok::r_paren))
  1382. return TPResult::Error();
  1383. }
  1384. if (Tok.is(tok::kw_noexcept)) {
  1385. ConsumeToken();
  1386. // Possibly an expression as well.
  1387. if (Tok.is(tok::l_paren)) {
  1388. // Find the matching rparen.
  1389. ConsumeParen();
  1390. if (!SkipUntil(tok::r_paren))
  1391. return TPResult::Error();
  1392. }
  1393. }
  1394. return TPResult::Ambiguous();
  1395. }
  1396. /// '[' constant-expression[opt] ']'
  1397. ///
  1398. Parser::TPResult Parser::TryParseBracketDeclarator() {
  1399. ConsumeBracket();
  1400. if (!SkipUntil(tok::r_square))
  1401. return TPResult::Error();
  1402. return TPResult::Ambiguous();
  1403. }