]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseInit.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / lib / Parse / ParseInit.cpp
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
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/ParseDiagnostic.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/Sema/Designator.h"
18 #include "clang/Sema/Scope.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace clang;
22
23
24 /// MayBeDesignationStart - Return true if this token might be the start of a
25 /// designator.  If we can tell it is impossible that it is a designator, return
26 /// false.
27 static bool MayBeDesignationStart(tok::TokenKind K, Preprocessor &PP) {
28   switch (K) {
29   default: return false;
30   case tok::period:      // designator: '.' identifier
31   case tok::l_square:    // designator: array-designator
32       return true;
33   case tok::identifier:  // designation: identifier ':'
34     return PP.LookAhead(0).is(tok::colon);
35   }
36 }
37
38 static void CheckArrayDesignatorSyntax(Parser &P, SourceLocation Loc,
39                                        Designation &Desig) {
40   // If we have exactly one array designator, this used the GNU
41   // 'designation: array-designator' extension, otherwise there should be no
42   // designators at all!
43   if (Desig.getNumDesignators() == 1 &&
44       (Desig.getDesignator(0).isArrayDesignator() ||
45        Desig.getDesignator(0).isArrayRangeDesignator()))
46     P.Diag(Loc, diag::ext_gnu_missing_equal_designator);
47   else if (Desig.getNumDesignators() > 0)
48     P.Diag(Loc, diag::err_expected_equal_designator);
49 }
50
51 /// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production
52 /// checking to see if the token stream starts with a designator.
53 ///
54 ///       designation:
55 ///         designator-list '='
56 /// [GNU]   array-designator
57 /// [GNU]   identifier ':'
58 ///
59 ///       designator-list:
60 ///         designator
61 ///         designator-list designator
62 ///
63 ///       designator:
64 ///         array-designator
65 ///         '.' identifier
66 ///
67 ///       array-designator:
68 ///         '[' constant-expression ']'
69 /// [GNU]   '[' constant-expression '...' constant-expression ']'
70 ///
71 /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
72 /// initializer (because it is an expression).  We need to consider this case
73 /// when parsing array designators.
74 ///
75 ExprResult Parser::ParseInitializerWithPotentialDesignator() {
76
77   // If this is the old-style GNU extension:
78   //   designation ::= identifier ':'
79   // Handle it as a field designator.  Otherwise, this must be the start of a
80   // normal expression.
81   if (Tok.is(tok::identifier)) {
82     const IdentifierInfo *FieldName = Tok.getIdentifierInfo();
83
84     llvm::SmallString<256> NewSyntax;
85     llvm::raw_svector_ostream(NewSyntax) << '.' << FieldName->getName()
86                                          << " = ";
87
88     SourceLocation NameLoc = ConsumeToken(); // Eat the identifier.
89
90     assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!");
91     SourceLocation ColonLoc = ConsumeToken();
92
93     Diag(NameLoc, diag::ext_gnu_old_style_field_designator)
94       << FixItHint::CreateReplacement(SourceRange(NameLoc, ColonLoc),
95                                       NewSyntax.str());
96
97     Designation D;
98     D.AddDesignator(Designator::getField(FieldName, SourceLocation(), NameLoc));
99     return Actions.ActOnDesignatedInitializer(D, ColonLoc, true,
100                                               ParseInitializer());
101   }
102
103   // Desig - This is initialized when we see our first designator.  We may have
104   // an objc message send with no designator, so we don't want to create this
105   // eagerly.
106   Designation Desig;
107
108   // Parse each designator in the designator list until we find an initializer.
109   while (Tok.is(tok::period) || Tok.is(tok::l_square)) {
110     if (Tok.is(tok::period)) {
111       // designator: '.' identifier
112       SourceLocation DotLoc = ConsumeToken();
113
114       if (Tok.isNot(tok::identifier)) {
115         Diag(Tok.getLocation(), diag::err_expected_field_designator);
116         return ExprError();
117       }
118
119       Desig.AddDesignator(Designator::getField(Tok.getIdentifierInfo(), DotLoc,
120                                                Tok.getLocation()));
121       ConsumeToken(); // Eat the identifier.
122       continue;
123     }
124
125     // We must have either an array designator now or an objc message send.
126     assert(Tok.is(tok::l_square) && "Unexpected token!");
127
128     // Handle the two forms of array designator:
129     //   array-designator: '[' constant-expression ']'
130     //   array-designator: '[' constant-expression '...' constant-expression ']'
131     //
132     // Also, we have to handle the case where the expression after the
133     // designator an an objc message send: '[' objc-message-expr ']'.
134     // Interesting cases are:
135     //   [foo bar]         -> objc message send
136     //   [foo]             -> array designator
137     //   [foo ... bar]     -> array designator
138     //   [4][foo bar]      -> obsolete GNU designation with objc message send.
139     //
140     InMessageExpressionRAIIObject InMessage(*this, true);
141     
142     BalancedDelimiterTracker T(*this, tok::l_square);
143     T.consumeOpen();
144     SourceLocation StartLoc = T.getOpenLocation();
145
146     ExprResult Idx;
147
148     // If Objective-C is enabled and this is a typename (class message
149     // send) or send to 'super', parse this as a message send
150     // expression.  We handle C++ and C separately, since C++ requires
151     // much more complicated parsing.
152     if  (getLang().ObjC1 && getLang().CPlusPlus) {
153       // Send to 'super'.
154       if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
155           NextToken().isNot(tok::period) && 
156           getCurScope()->isInObjcMethodScope()) {
157         CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
158         return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
159                                                            ConsumeToken(),
160                                                            ParsedType(), 
161                                                            0);
162       }
163
164       // Parse the receiver, which is either a type or an expression.
165       bool IsExpr;
166       void *TypeOrExpr;
167       if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
168         SkipUntil(tok::r_square);
169         return ExprError();
170       }
171       
172       // If the receiver was a type, we have a class message; parse
173       // the rest of it.
174       if (!IsExpr) {
175         CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
176         return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 
177                                                            SourceLocation(), 
178                                    ParsedType::getFromOpaquePtr(TypeOrExpr),
179                                                            0);
180       }
181
182       // If the receiver was an expression, we still don't know
183       // whether we have a message send or an array designator; just
184       // adopt the expression for further analysis below.
185       // FIXME: potentially-potentially evaluated expression above?
186       Idx = ExprResult(static_cast<Expr*>(TypeOrExpr));
187     } else if (getLang().ObjC1 && Tok.is(tok::identifier)) {
188       IdentifierInfo *II = Tok.getIdentifierInfo();
189       SourceLocation IILoc = Tok.getLocation();
190       ParsedType ReceiverType;
191       // Three cases. This is a message send to a type: [type foo]
192       // This is a message send to super:  [super foo]
193       // This is a message sent to an expr:  [super.bar foo]
194       switch (Sema::ObjCMessageKind Kind
195                 = Actions.getObjCMessageKind(getCurScope(), II, IILoc, 
196                                              II == Ident_super,
197                                              NextToken().is(tok::period),
198                                              ReceiverType)) {
199       case Sema::ObjCSuperMessage:
200       case Sema::ObjCClassMessage:
201         CheckArrayDesignatorSyntax(*this, StartLoc, Desig);
202         if (Kind == Sema::ObjCSuperMessage)
203           return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
204                                                              ConsumeToken(),
205                                                              ParsedType(),
206                                                              0);
207         ConsumeToken(); // the identifier
208         if (!ReceiverType) {
209           SkipUntil(tok::r_square);
210           return ExprError();
211         }
212
213         return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, 
214                                                            SourceLocation(), 
215                                                            ReceiverType, 
216                                                            0);
217
218       case Sema::ObjCInstanceMessage:
219         // Fall through; we'll just parse the expression and
220         // (possibly) treat this like an Objective-C message send
221         // later.
222         break;
223       }
224     }
225
226     // Parse the index expression, if we haven't already gotten one
227     // above (which can only happen in Objective-C++).
228     // Note that we parse this as an assignment expression, not a constant
229     // expression (allowing *=, =, etc) to handle the objc case.  Sema needs
230     // to validate that the expression is a constant.
231     // FIXME: We also need to tell Sema that we're in a
232     // potentially-potentially evaluated context.
233     if (!Idx.get()) {
234       Idx = ParseAssignmentExpression();
235       if (Idx.isInvalid()) {
236         SkipUntil(tok::r_square);
237         return move(Idx);
238       }
239     }
240
241     // Given an expression, we could either have a designator (if the next
242     // tokens are '...' or ']' or an objc message send.  If this is an objc
243     // message send, handle it now.  An objc-message send is the start of
244     // an assignment-expression production.
245     if (getLang().ObjC1 && Tok.isNot(tok::ellipsis) &&
246         Tok.isNot(tok::r_square)) {
247       CheckArrayDesignatorSyntax(*this, Tok.getLocation(), Desig);
248       return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
249                                                          SourceLocation(),
250                                                          ParsedType(),
251                                                          Idx.take());
252     }
253
254     // If this is a normal array designator, remember it.
255     if (Tok.isNot(tok::ellipsis)) {
256       Desig.AddDesignator(Designator::getArray(Idx.release(), StartLoc));
257     } else {
258       // Handle the gnu array range extension.
259       Diag(Tok, diag::ext_gnu_array_range);
260       SourceLocation EllipsisLoc = ConsumeToken();
261
262       ExprResult RHS(ParseConstantExpression());
263       if (RHS.isInvalid()) {
264         SkipUntil(tok::r_square);
265         return move(RHS);
266       }
267       Desig.AddDesignator(Designator::getArrayRange(Idx.release(),
268                                                     RHS.release(),
269                                                     StartLoc, EllipsisLoc));
270     }
271
272     T.consumeClose();
273     Desig.getDesignator(Desig.getNumDesignators() - 1).setRBracketLoc(
274                                                         T.getCloseLocation());
275   }
276
277   // Okay, we're done with the designator sequence.  We know that there must be
278   // at least one designator, because the only case we can get into this method
279   // without a designator is when we have an objc message send.  That case is
280   // handled and returned from above.
281   assert(!Desig.empty() && "Designator is empty?");
282
283   // Handle a normal designator sequence end, which is an equal.
284   if (Tok.is(tok::equal)) {
285     SourceLocation EqualLoc = ConsumeToken();
286     return Actions.ActOnDesignatedInitializer(Desig, EqualLoc, false,
287                                               ParseInitializer());
288   }
289
290   // We read some number of designators and found something that isn't an = or
291   // an initializer.  If we have exactly one array designator, this
292   // is the GNU 'designation: array-designator' extension.  Otherwise, it is a
293   // parse error.
294   if (Desig.getNumDesignators() == 1 &&
295       (Desig.getDesignator(0).isArrayDesignator() ||
296        Desig.getDesignator(0).isArrayRangeDesignator())) {
297     Diag(Tok, diag::ext_gnu_missing_equal_designator)
298       << FixItHint::CreateInsertion(Tok.getLocation(), "= ");
299     return Actions.ActOnDesignatedInitializer(Desig, Tok.getLocation(),
300                                               true, ParseInitializer());
301   }
302
303   Diag(Tok, diag::err_expected_equal_designator);
304   return ExprError();
305 }
306
307
308 /// ParseBraceInitializer - Called when parsing an initializer that has a
309 /// leading open brace.
310 ///
311 ///       initializer: [C99 6.7.8]
312 ///         '{' initializer-list '}'
313 ///         '{' initializer-list ',' '}'
314 /// [GNU]   '{' '}'
315 ///
316 ///       initializer-list:
317 ///         designation[opt] initializer ...[opt]
318 ///         initializer-list ',' designation[opt] initializer ...[opt]
319 ///
320 ExprResult Parser::ParseBraceInitializer() {
321   InMessageExpressionRAIIObject InMessage(*this, false);
322   
323   BalancedDelimiterTracker T(*this, tok::l_brace);
324   T.consumeOpen();
325   SourceLocation LBraceLoc = T.getOpenLocation();
326
327   /// InitExprs - This is the actual list of expressions contained in the
328   /// initializer.
329   ExprVector InitExprs(Actions);
330
331   if (Tok.is(tok::r_brace)) {
332     // Empty initializers are a C++ feature and a GNU extension to C.
333     if (!getLang().CPlusPlus)
334       Diag(LBraceLoc, diag::ext_gnu_empty_initializer);
335     // Match the '}'.
336     return Actions.ActOnInitList(LBraceLoc, MultiExprArg(Actions),
337                                  ConsumeBrace());
338   }
339
340   bool InitExprsOk = true;
341
342   while (1) {
343     // Parse: designation[opt] initializer
344
345     // If we know that this cannot be a designation, just parse the nested
346     // initializer directly.
347     ExprResult SubElt;
348     if (MayBeDesignationStart(Tok.getKind(), PP))
349       SubElt = ParseInitializerWithPotentialDesignator();
350     else
351       SubElt = ParseInitializer();
352
353     if (Tok.is(tok::ellipsis))
354       SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken());
355     
356     // If we couldn't parse the subelement, bail out.
357     if (!SubElt.isInvalid()) {
358       InitExprs.push_back(SubElt.release());
359     } else {
360       InitExprsOk = false;
361
362       // We have two ways to try to recover from this error: if the code looks
363       // grammatically ok (i.e. we have a comma coming up) try to continue
364       // parsing the rest of the initializer.  This allows us to emit
365       // diagnostics for later elements that we find.  If we don't see a comma,
366       // assume there is a parse error, and just skip to recover.
367       // FIXME: This comment doesn't sound right. If there is a r_brace
368       // immediately, it can't be an error, since there is no other way of
369       // leaving this loop except through this if.
370       if (Tok.isNot(tok::comma)) {
371         SkipUntil(tok::r_brace, false, true);
372         break;
373       }
374     }
375
376     // If we don't have a comma continued list, we're done.
377     if (Tok.isNot(tok::comma)) break;
378
379     // TODO: save comma locations if some client cares.
380     ConsumeToken();
381
382     // Handle trailing comma.
383     if (Tok.is(tok::r_brace)) break;
384   }
385
386   bool closed = !T.consumeClose();
387
388   if (InitExprsOk && closed)
389     return Actions.ActOnInitList(LBraceLoc, move_arg(InitExprs),
390                                  T.getCloseLocation());
391
392   return ExprError(); // an error occurred.
393 }
394