ParseInit.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. //===--- ParseInit.cpp - Initializer 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 initializer parsing as specified by C99 6.7.8.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/Parser.h"
  14. #include "RAIIObjectsForParser.h"
  15. #include "clang/Parse/ParseDiagnostic.h"
  16. #include "clang/Sema/Designator.h"
  17. #include "clang/Sema/Scope.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. using namespace clang;
  21. /// MayBeDesignationStart - Return true if the current token might be the start
  22. /// of a designator. If we can tell it is impossible that it is a designator,
  23. /// return false.
  24. bool Parser::MayBeDesignationStart() {
  25. switch (Tok.getKind()) {
  26. default:
  27. return false;
  28. case tok::period: // designator: '.' identifier
  29. return true;
  30. case tok::l_square: { // designator: array-designator
  31. if (!PP.getLangOpts().CPlusPlus11)
  32. return true;
  33. // C++11 lambda expressions and C99 designators can be ambiguous all the
  34. // way through the closing ']' and to the next character. Handle the easy
  35. // cases here, and fall back to tentative parsing if those fail.
  36. switch (PP.LookAhead(0).getKind()) {
  37. case tok::equal:
  38. case tok::r_square:
  39. // Definitely starts a lambda expression.
  40. return false;
  41. case tok::amp:
  42. case tok::kw_this:
  43. case tok::identifier:
  44. // We have to do additional analysis, because these could be the
  45. // start of a constant expression or a lambda capture list.
  46. break;
  47. default:
  48. // Anything not mentioned above cannot occur following a '[' in a
  49. // lambda expression.
  50. return true;
  51. }
  52. // Handle the complicated case below.
  53. break;
  54. }
  55. case tok::identifier: // designation: identifier ':'
  56. return PP.LookAhead(0).is(tok::colon);
  57. }
  58. // Parse up to (at most) the token after the closing ']' to determine
  59. // whether this is a C99 designator or a lambda.
  60. TentativeParsingAction Tentative(*this);
  61. LambdaIntroducer Intro;
  62. bool SkippedInits = false;
  63. Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
  64. if (DiagID) {
  65. // If this can't be a lambda capture list, it's a designator.
  66. Tentative.Revert();
  67. return true;
  68. }
  69. // Once we hit the closing square bracket, we look at the next
  70. // token. If it's an '=', this is a designator. Otherwise, it's a
  71. // lambda expression. This decision favors lambdas over the older
  72. // GNU designator syntax, which allows one to omit the '=', but is
  73. // consistent with GCC.
  74. tok::TokenKind Kind = Tok.getKind();
  75. // FIXME: If we didn't skip any inits, parse the lambda from here
  76. // rather than throwing away then reparsing the LambdaIntroducer.
  77. Tentative.Revert();
  78. return Kind == tok::equal;
  79. }
  80. static void CheckArrayDesignatorSyntax(Parser &P, SourceLocation Loc,
  81. Designation &Desig) {
  82. // If we have exactly one array designator, this used the GNU
  83. // 'designation: array-designator' extension, otherwise there should be no
  84. // designators at all!
  85. if (Desig.getNumDesignators() == 1 &&
  86. (Desig.getDesignator(0).isArrayDesignator() ||
  87. Desig.getDesignator(0).isArrayRangeDesignator()))
  88. P.Diag(Loc, diag::ext_gnu_missing_equal_designator);
  89. else if (Desig.getNumDesignators() > 0)
  90. P.Diag(Loc, diag::err_expected_equal_designator);
  91. }
  92. /// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production
  93. /// checking to see if the token stream starts with a designator.
  94. ///
  95. /// designation:
  96. /// designator-list '='
  97. /// [GNU] array-designator
  98. /// [GNU] identifier ':'
  99. ///
  100. /// designator-list:
  101. /// designator
  102. /// designator-list designator
  103. ///
  104. /// designator:
  105. /// array-designator
  106. /// '.' identifier
  107. ///
  108. /// array-designator:
  109. /// '[' constant-expression ']'
  110. /// [GNU] '[' constant-expression '...' constant-expression ']'
  111. ///
  112. /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
  113. /// initializer (because it is an expression). We need to consider this case
  114. /// when parsing array designators.
  115. ///
  116. ExprResult Parser::ParseInitializerWithPotentialDesignator() {
  117. // If this is the old-style GNU extension:
  118. // designation ::= identifier ':'
  119. // Handle it as a field designator. Otherwise, this must be the start of a
  120. // normal expression.
  121. if (Tok.is(tok::identifier)) {
  122. const IdentifierInfo *FieldName = Tok.getIdentifierInfo();
  123. SmallString<256> NewSyntax;
  124. llvm::raw_svector_ostream(NewSyntax) << '.' << FieldName->getName()
  125. << " = ";
  126. SourceLocation NameLoc = ConsumeToken(); // Eat the identifier.
  127. assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!");
  128. SourceLocation ColonLoc = ConsumeToken();
  129. Diag(NameLoc, diag::ext_gnu_old_style_field_designator)
  130. << FixItHint::CreateReplacement(SourceRange(NameLoc, ColonLoc),
  131. NewSyntax);
  132. Designation D;
  133. D.AddDesignator(Designator::getField(FieldName, SourceLocation(), NameLoc));
  134. return Actions.ActOnDesignatedInitializer(D, ColonLoc, true,
  135. ParseInitializer());
  136. }
  137. // Desig - This is initialized when we see our first designator. We may have
  138. // an objc message send with no designator, so we don't want to create this
  139. // eagerly.
  140. Designation Desig;
  141. // Parse each designator in the designator list until we find an initializer.
  142. while (Tok.is(tok::period) || Tok.is(tok::l_square)) {
  143. if (Tok.is(tok::period)) {
  144. // designator: '.' identifier
  145. SourceLocation DotLoc = ConsumeToken();
  146. if (Tok.isNot(tok::identifier)) {
  147. Diag(Tok.getLocation(), diag::err_expected_field_designator);
  148. return ExprError();
  149. }
  150. Desig.AddDesignator(Designator::getField(Tok.getIdentifierInfo(), DotLoc,
  151. Tok.getLocation()));
  152. ConsumeToken(); // Eat the identifier.
  153. continue;
  154. }
  155. // We must have either an array designator now or an objc message send.
  156. assert(Tok.is(tok::l_square) && "Unexpected token!");
  157. // Handle the two forms of array designator:
  158. // array-designator: '[' constant-expression ']'
  159. // array-designator: '[' constant-expression '...' constant-expression ']'
  160. //
  161. // Also, we have to handle the case where the expression after the
  162. // designator an an objc message send: '[' objc-message-expr ']'.
  163. // Interesting cases are:
  164. // [foo bar] -> objc message send
  165. // [foo] -> array designator
  166. // [foo ... bar] -> array designator
  167. // [4][foo bar] -> obsolete GNU designation with objc message send.
  168. //
  169. // We do not need to check for an expression starting with [[ here. If it
  170. // contains an Objective-C message send, then it is not an ill-formed
  171. // attribute. If it is a lambda-expression within an array-designator, then
  172. // it will be rejected because a constant-expression cannot begin with a
  173. // lambda-expression.
  174. InMessageExpressionRAIIObject InMessage(*this, true);
  175. BalancedDelimiterTracker T(*this, tok::l_square);
  176. T.consumeOpen();
  177. SourceLocation StartLoc = T.getOpenLocation();
  178. ExprResult Idx;
  179. // If Objective-C is enabled and this is a typename (class message
  180. // send) or send to 'super', parse this as a message send
  181. // expression. We handle C++ and C separately, since C++ requires
  182. // much more complicated parsing.
  183. if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus) {
  184. // Send to 'super'.
  185. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
  186. NextToken().isNot(tok::period) &&
  187. getCurScope()->isInObjcMethodScope()) {
  188. CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
  189. return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
  190. ConsumeToken(),
  191. ParsedType(),
  192. nullptr);
  193. }
  194. // Parse the receiver, which is either a type or an expression.
  195. bool IsExpr;
  196. void *TypeOrExpr;
  197. if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
  198. SkipUntil(tok::r_square, StopAtSemi);
  199. return ExprError();
  200. }
  201. // If the receiver was a type, we have a class message; parse
  202. // the rest of it.
  203. if (!IsExpr) {
  204. CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
  205. return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
  206. SourceLocation(),
  207. ParsedType::getFromOpaquePtr(TypeOrExpr),
  208. nullptr);
  209. }
  210. // If the receiver was an expression, we still don't know
  211. // whether we have a message send or an array designator; just
  212. // adopt the expression for further analysis below.
  213. // FIXME: potentially-potentially evaluated expression above?
  214. Idx = ExprResult(static_cast<Expr*>(TypeOrExpr));
  215. } else if (getLangOpts().ObjC1 && Tok.is(tok::identifier)) {
  216. IdentifierInfo *II = Tok.getIdentifierInfo();
  217. SourceLocation IILoc = Tok.getLocation();
  218. ParsedType ReceiverType;
  219. // Three cases. This is a message send to a type: [type foo]
  220. // This is a message send to super: [super foo]
  221. // This is a message sent to an expr: [super.bar foo]
  222. switch (Actions.getObjCMessageKind(
  223. getCurScope(), II, IILoc, II == Ident_super,
  224. NextToken().is(tok::period), ReceiverType)) {
  225. case Sema::ObjCSuperMessage:
  226. CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
  227. return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
  228. ConsumeToken(),
  229. ParsedType(),
  230. nullptr);
  231. case Sema::ObjCClassMessage:
  232. CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
  233. ConsumeToken(); // the identifier
  234. if (!ReceiverType) {
  235. SkipUntil(tok::r_square, StopAtSemi);
  236. return ExprError();
  237. }
  238. // Parse type arguments and protocol qualifiers.
  239. if (Tok.is(tok::less)) {
  240. SourceLocation NewEndLoc;
  241. TypeResult NewReceiverType
  242. = parseObjCTypeArgsAndProtocolQualifiers(IILoc, ReceiverType,
  243. /*consumeLastToken=*/true,
  244. NewEndLoc);
  245. if (!NewReceiverType.isUsable()) {
  246. SkipUntil(tok::r_square, StopAtSemi);
  247. return ExprError();
  248. }
  249. ReceiverType = NewReceiverType.get();
  250. }
  251. return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
  252. SourceLocation(),
  253. ReceiverType,
  254. nullptr);
  255. case Sema::ObjCInstanceMessage:
  256. // Fall through; we'll just parse the expression and
  257. // (possibly) treat this like an Objective-C message send
  258. // later.
  259. break;
  260. }
  261. }
  262. // Parse the index expression, if we haven't already gotten one
  263. // above (which can only happen in Objective-C++).
  264. // Note that we parse this as an assignment expression, not a constant
  265. // expression (allowing *=, =, etc) to handle the objc case. Sema needs
  266. // to validate that the expression is a constant.
  267. // FIXME: We also need to tell Sema that we're in a
  268. // potentially-potentially evaluated context.
  269. if (!Idx.get()) {
  270. Idx = ParseAssignmentExpression();
  271. if (Idx.isInvalid()) {
  272. SkipUntil(tok::r_square, StopAtSemi);
  273. return Idx;
  274. }
  275. }
  276. // Given an expression, we could either have a designator (if the next
  277. // tokens are '...' or ']' or an objc message send. If this is an objc
  278. // message send, handle it now. An objc-message send is the start of
  279. // an assignment-expression production.
  280. if (getLangOpts().ObjC1 && Tok.isNot(tok::ellipsis) &&
  281. Tok.isNot(tok::r_square)) {
  282. CheckArrayDesignatorSyntax(*this, Tok.getLocation(), Desig);
  283. return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
  284. SourceLocation(),
  285. ParsedType(),
  286. Idx.get());
  287. }
  288. // If this is a normal array designator, remember it.
  289. if (Tok.isNot(tok::ellipsis)) {
  290. Desig.AddDesignator(Designator::getArray(Idx.get(), StartLoc));
  291. } else {
  292. // Handle the gnu array range extension.
  293. Diag(Tok, diag::ext_gnu_array_range);
  294. SourceLocation EllipsisLoc = ConsumeToken();
  295. ExprResult RHS(ParseConstantExpression());
  296. if (RHS.isInvalid()) {
  297. SkipUntil(tok::r_square, StopAtSemi);
  298. return RHS;
  299. }
  300. Desig.AddDesignator(Designator::getArrayRange(Idx.get(),
  301. RHS.get(),
  302. StartLoc, EllipsisLoc));
  303. }
  304. T.consumeClose();
  305. Desig.getDesignator(Desig.getNumDesignators() - 1).setRBracketLoc(
  306. T.getCloseLocation());
  307. }
  308. // Okay, we're done with the designator sequence. We know that there must be
  309. // at least one designator, because the only case we can get into this method
  310. // without a designator is when we have an objc message send. That case is
  311. // handled and returned from above.
  312. assert(!Desig.empty() && "Designator is empty?");
  313. // Handle a normal designator sequence end, which is an equal.
  314. if (Tok.is(tok::equal)) {
  315. SourceLocation EqualLoc = ConsumeToken();
  316. return Actions.ActOnDesignatedInitializer(Desig, EqualLoc, false,
  317. ParseInitializer());
  318. }
  319. // We read some number of designators and found something that isn't an = or
  320. // an initializer. If we have exactly one array designator, this
  321. // is the GNU 'designation: array-designator' extension. Otherwise, it is a
  322. // parse error.
  323. if (Desig.getNumDesignators() == 1 &&
  324. (Desig.getDesignator(0).isArrayDesignator() ||
  325. Desig.getDesignator(0).isArrayRangeDesignator())) {
  326. Diag(Tok, diag::ext_gnu_missing_equal_designator)
  327. << FixItHint::CreateInsertion(Tok.getLocation(), "= ");
  328. return Actions.ActOnDesignatedInitializer(Desig, Tok.getLocation(),
  329. true, ParseInitializer());
  330. }
  331. Diag(Tok, diag::err_expected_equal_designator);
  332. return ExprError();
  333. }
  334. /// ParseBraceInitializer - Called when parsing an initializer that has a
  335. /// leading open brace.
  336. ///
  337. /// initializer: [C99 6.7.8]
  338. /// '{' initializer-list '}'
  339. /// '{' initializer-list ',' '}'
  340. /// [GNU] '{' '}'
  341. ///
  342. /// initializer-list:
  343. /// designation[opt] initializer ...[opt]
  344. /// initializer-list ',' designation[opt] initializer ...[opt]
  345. ///
  346. ExprResult Parser::ParseBraceInitializer() {
  347. // HLSL Note - this is used for float f[] = { 1, 2, 3 };
  348. InMessageExpressionRAIIObject InMessage(*this, false);
  349. BalancedDelimiterTracker T(*this, tok::l_brace);
  350. T.consumeOpen();
  351. SourceLocation LBraceLoc = T.getOpenLocation();
  352. /// InitExprs - This is the actual list of expressions contained in the
  353. /// initializer.
  354. ExprVector InitExprs;
  355. if (Tok.is(tok::r_brace)) {
  356. // Empty initializers are a C++ feature and a GNU extension to C.
  357. if (!getLangOpts().CPlusPlus)
  358. Diag(LBraceLoc, diag::ext_gnu_empty_initializer);
  359. // Match the '}'.
  360. return Actions.ActOnInitList(LBraceLoc, None, ConsumeBrace());
  361. }
  362. bool InitExprsOk = true;
  363. while (1) {
  364. // Handle Microsoft __if_exists/if_not_exists if necessary.
  365. if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
  366. Tok.is(tok::kw___if_not_exists))) {
  367. if (ParseMicrosoftIfExistsBraceInitializer(InitExprs, InitExprsOk)) {
  368. if (Tok.isNot(tok::comma)) break;
  369. ConsumeToken();
  370. }
  371. if (Tok.is(tok::r_brace)) break;
  372. continue;
  373. }
  374. // Parse: designation[opt] initializer
  375. // If we know that this cannot be a designation, just parse the nested
  376. // initializer directly.
  377. ExprResult SubElt;
  378. if (MayBeDesignationStart())
  379. SubElt = ParseInitializerWithPotentialDesignator();
  380. else
  381. SubElt = ParseInitializer();
  382. if (Tok.is(tok::ellipsis)) {
  383. // HLSL Change Starts
  384. if (getLangOpts().HLSL) {
  385. Diag(Tok, diag::err_hlsl_unsupported_construct) << "expansion";
  386. InitExprsOk = false;
  387. SkipUntil(tok::r_brace, StopBeforeMatch);
  388. break;
  389. }
  390. // HLSL Change Ends
  391. SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken());
  392. }
  393. SubElt = Actions.CorrectDelayedTyposInExpr(SubElt.get());
  394. // If we couldn't parse the subelement, bail out.
  395. if (SubElt.isUsable()) {
  396. InitExprs.push_back(SubElt.get());
  397. } else {
  398. InitExprsOk = false;
  399. // We have two ways to try to recover from this error: if the code looks
  400. // grammatically ok (i.e. we have a comma coming up) try to continue
  401. // parsing the rest of the initializer. This allows us to emit
  402. // diagnostics for later elements that we find. If we don't see a comma,
  403. // assume there is a parse error, and just skip to recover.
  404. // FIXME: This comment doesn't sound right. If there is a r_brace
  405. // immediately, it can't be an error, since there is no other way of
  406. // leaving this loop except through this if.
  407. if (Tok.isNot(tok::comma)) {
  408. SkipUntil(tok::r_brace, StopBeforeMatch);
  409. break;
  410. }
  411. }
  412. // If we don't have a comma continued list, we're done.
  413. if (Tok.isNot(tok::comma)) break;
  414. // TODO: save comma locations if some client cares.
  415. ConsumeToken();
  416. // Handle trailing comma.
  417. if (Tok.is(tok::r_brace)) break;
  418. }
  419. bool closed = !T.consumeClose();
  420. if (InitExprsOk && closed)
  421. return Actions.ActOnInitList(LBraceLoc, InitExprs,
  422. T.getCloseLocation());
  423. return ExprError(); // an error occurred.
  424. }
  425. // Return true if a comma (or closing brace) is necessary after the
  426. // __if_exists/if_not_exists statement.
  427. bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
  428. bool &InitExprsOk) {
  429. assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change
  430. bool trailingComma = false;
  431. IfExistsCondition Result;
  432. if (ParseMicrosoftIfExistsCondition(Result))
  433. return false;
  434. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  435. if (Braces.consumeOpen()) {
  436. Diag(Tok, diag::err_expected) << tok::l_brace;
  437. return false;
  438. }
  439. switch (Result.Behavior) {
  440. case IEB_Parse:
  441. // Parse the declarations below.
  442. break;
  443. case IEB_Dependent:
  444. Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
  445. << Result.IsIfExists;
  446. // Fall through to skip.
  447. case IEB_Skip:
  448. Braces.skipToEnd();
  449. return false;
  450. }
  451. while (!isEofOrEom()) {
  452. trailingComma = false;
  453. // If we know that this cannot be a designation, just parse the nested
  454. // initializer directly.
  455. ExprResult SubElt;
  456. if (MayBeDesignationStart())
  457. SubElt = ParseInitializerWithPotentialDesignator();
  458. else
  459. SubElt = ParseInitializer();
  460. if (Tok.is(tok::ellipsis))
  461. SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken());
  462. // If we couldn't parse the subelement, bail out.
  463. if (!SubElt.isInvalid())
  464. InitExprs.push_back(SubElt.get());
  465. else
  466. InitExprsOk = false;
  467. if (Tok.is(tok::comma)) {
  468. ConsumeToken();
  469. trailingComma = true;
  470. }
  471. if (Tok.is(tok::r_brace))
  472. break;
  473. }
  474. Braces.consumeClose();
  475. return !trailingComma;
  476. }