xref: /llvm-project/clang/lib/Parse/ParseObjc.cpp (revision f4ffdf357c98e30fd8a67d41ab51e55932f8d2d4)
1 //===--- ParseObjC.cpp - Objective C 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 Objective-C portions of the Parser interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Parse/ParseDiagnostic.h"
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/PrettyDeclStackTrace.h"
19 #include "clang/Sema/Scope.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 using namespace clang;
23 
24 
25 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
26 ///       external-declaration: [C99 6.9]
27 /// [OBJC]  objc-class-definition
28 /// [OBJC]  objc-class-declaration
29 /// [OBJC]  objc-alias-declaration
30 /// [OBJC]  objc-protocol-definition
31 /// [OBJC]  objc-method-definition
32 /// [OBJC]  '@' 'end'
33 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() {
34   SourceLocation AtLoc = ConsumeToken(); // the "@"
35 
36   if (Tok.is(tok::code_completion)) {
37     Actions.CodeCompleteObjCAtDirective(getCurScope());
38     cutOffParsing();
39     return DeclGroupPtrTy();
40   }
41 
42   Decl *SingleDecl = 0;
43   switch (Tok.getObjCKeywordID()) {
44   case tok::objc_class:
45     return ParseObjCAtClassDeclaration(AtLoc);
46   case tok::objc_interface: {
47     ParsedAttributes attrs(AttrFactory);
48     SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
49     break;
50   }
51   case tok::objc_protocol: {
52     ParsedAttributes attrs(AttrFactory);
53     return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
54   }
55   case tok::objc_implementation:
56     return ParseObjCAtImplementationDeclaration(AtLoc);
57   case tok::objc_end:
58     return ParseObjCAtEndDeclaration(AtLoc);
59   case tok::objc_compatibility_alias:
60     SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
61     break;
62   case tok::objc_synthesize:
63     SingleDecl = ParseObjCPropertySynthesize(AtLoc);
64     break;
65   case tok::objc_dynamic:
66     SingleDecl = ParseObjCPropertyDynamic(AtLoc);
67     break;
68   case tok::objc___experimental_modules_import:
69     if (getLangOpts().Modules)
70       return ParseModuleImport(AtLoc);
71 
72     // Fall through
73 
74   default:
75     Diag(AtLoc, diag::err_unexpected_at);
76     SkipUntil(tok::semi);
77     SingleDecl = 0;
78     break;
79   }
80   return Actions.ConvertDeclToDeclGroup(SingleDecl);
81 }
82 
83 ///
84 /// objc-class-declaration:
85 ///    '@' 'class' identifier-list ';'
86 ///
87 Parser::DeclGroupPtrTy
88 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
89   ConsumeToken(); // the identifier "class"
90   SmallVector<IdentifierInfo *, 8> ClassNames;
91   SmallVector<SourceLocation, 8> ClassLocs;
92 
93 
94   while (1) {
95     if (Tok.isNot(tok::identifier)) {
96       Diag(Tok, diag::err_expected_ident);
97       SkipUntil(tok::semi);
98       return Actions.ConvertDeclToDeclGroup(0);
99     }
100     ClassNames.push_back(Tok.getIdentifierInfo());
101     ClassLocs.push_back(Tok.getLocation());
102     ConsumeToken();
103 
104     if (Tok.isNot(tok::comma))
105       break;
106 
107     ConsumeToken();
108   }
109 
110   // Consume the ';'.
111   if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
112     return Actions.ConvertDeclToDeclGroup(0);
113 
114   return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
115                                               ClassLocs.data(),
116                                               ClassNames.size());
117 }
118 
119 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
120 {
121   Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
122   if (ock == Sema::OCK_None)
123     return;
124 
125   Decl *Decl = Actions.getObjCDeclContext();
126   if (CurParsedObjCImpl) {
127     CurParsedObjCImpl->finish(AtLoc);
128   } else {
129     Actions.ActOnAtEnd(getCurScope(), AtLoc);
130   }
131   Diag(AtLoc, diag::err_objc_missing_end)
132       << FixItHint::CreateInsertion(AtLoc, "@end\n");
133   if (Decl)
134     Diag(Decl->getLocStart(), diag::note_objc_container_start)
135         << (int) ock;
136 }
137 
138 ///
139 ///   objc-interface:
140 ///     objc-class-interface-attributes[opt] objc-class-interface
141 ///     objc-category-interface
142 ///
143 ///   objc-class-interface:
144 ///     '@' 'interface' identifier objc-superclass[opt]
145 ///       objc-protocol-refs[opt]
146 ///       objc-class-instance-variables[opt]
147 ///       objc-interface-decl-list
148 ///     @end
149 ///
150 ///   objc-category-interface:
151 ///     '@' 'interface' identifier '(' identifier[opt] ')'
152 ///       objc-protocol-refs[opt]
153 ///       objc-interface-decl-list
154 ///     @end
155 ///
156 ///   objc-superclass:
157 ///     ':' identifier
158 ///
159 ///   objc-class-interface-attributes:
160 ///     __attribute__((visibility("default")))
161 ///     __attribute__((visibility("hidden")))
162 ///     __attribute__((deprecated))
163 ///     __attribute__((unavailable))
164 ///     __attribute__((objc_exception)) - used by NSException on 64-bit
165 ///     __attribute__((objc_root_class))
166 ///
167 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
168                                               ParsedAttributes &attrs) {
169   assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
170          "ParseObjCAtInterfaceDeclaration(): Expected @interface");
171   CheckNestedObjCContexts(AtLoc);
172   ConsumeToken(); // the "interface" identifier
173 
174   // Code completion after '@interface'.
175   if (Tok.is(tok::code_completion)) {
176     Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
177     cutOffParsing();
178     return 0;
179   }
180 
181   if (Tok.isNot(tok::identifier)) {
182     Diag(Tok, diag::err_expected_ident); // missing class or category name.
183     return 0;
184   }
185 
186   // We have a class or category name - consume it.
187   IdentifierInfo *nameId = Tok.getIdentifierInfo();
188   SourceLocation nameLoc = ConsumeToken();
189   if (Tok.is(tok::l_paren) &&
190       !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
191 
192     BalancedDelimiterTracker T(*this, tok::l_paren);
193     T.consumeOpen();
194 
195     SourceLocation categoryLoc;
196     IdentifierInfo *categoryId = 0;
197     if (Tok.is(tok::code_completion)) {
198       Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
199       cutOffParsing();
200       return 0;
201     }
202 
203     // For ObjC2, the category name is optional (not an error).
204     if (Tok.is(tok::identifier)) {
205       categoryId = Tok.getIdentifierInfo();
206       categoryLoc = ConsumeToken();
207     }
208     else if (!getLangOpts().ObjC2) {
209       Diag(Tok, diag::err_expected_ident); // missing category name.
210       return 0;
211     }
212 
213     T.consumeClose();
214     if (T.getCloseLocation().isInvalid())
215       return 0;
216 
217     if (!attrs.empty()) { // categories don't support attributes.
218       Diag(nameLoc, diag::err_objc_no_attributes_on_category);
219       attrs.clear();
220     }
221 
222     // Next, we need to check for any protocol references.
223     SourceLocation LAngleLoc, EndProtoLoc;
224     SmallVector<Decl *, 8> ProtocolRefs;
225     SmallVector<SourceLocation, 8> ProtocolLocs;
226     if (Tok.is(tok::less) &&
227         ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
228                                     LAngleLoc, EndProtoLoc))
229       return 0;
230 
231     Decl *CategoryType =
232     Actions.ActOnStartCategoryInterface(AtLoc,
233                                         nameId, nameLoc,
234                                         categoryId, categoryLoc,
235                                         ProtocolRefs.data(),
236                                         ProtocolRefs.size(),
237                                         ProtocolLocs.data(),
238                                         EndProtoLoc);
239 
240     if (Tok.is(tok::l_brace))
241       ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
242 
243     ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
244     return CategoryType;
245   }
246   // Parse a class interface.
247   IdentifierInfo *superClassId = 0;
248   SourceLocation superClassLoc;
249 
250   if (Tok.is(tok::colon)) { // a super class is specified.
251     ConsumeToken();
252 
253     // Code completion of superclass names.
254     if (Tok.is(tok::code_completion)) {
255       Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
256       cutOffParsing();
257       return 0;
258     }
259 
260     if (Tok.isNot(tok::identifier)) {
261       Diag(Tok, diag::err_expected_ident); // missing super class name.
262       return 0;
263     }
264     superClassId = Tok.getIdentifierInfo();
265     superClassLoc = ConsumeToken();
266   }
267   // Next, we need to check for any protocol references.
268   SmallVector<Decl *, 8> ProtocolRefs;
269   SmallVector<SourceLocation, 8> ProtocolLocs;
270   SourceLocation LAngleLoc, EndProtoLoc;
271   if (Tok.is(tok::less) &&
272       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
273                                   LAngleLoc, EndProtoLoc))
274     return 0;
275 
276   Decl *ClsType =
277     Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
278                                      superClassId, superClassLoc,
279                                      ProtocolRefs.data(), ProtocolRefs.size(),
280                                      ProtocolLocs.data(),
281                                      EndProtoLoc, attrs.getList());
282 
283   if (Tok.is(tok::l_brace))
284     ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
285 
286   ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
287   return ClsType;
288 }
289 
290 /// The Objective-C property callback.  This should be defined where
291 /// it's used, but instead it's been lifted to here to support VS2005.
292 struct Parser::ObjCPropertyCallback : FieldCallback {
293 private:
294   virtual void anchor();
295 public:
296   Parser &P;
297   SmallVectorImpl<Decl *> &Props;
298   ObjCDeclSpec &OCDS;
299   SourceLocation AtLoc;
300   SourceLocation LParenLoc;
301   tok::ObjCKeywordKind MethodImplKind;
302 
303   ObjCPropertyCallback(Parser &P,
304                        SmallVectorImpl<Decl *> &Props,
305                        ObjCDeclSpec &OCDS, SourceLocation AtLoc,
306                        SourceLocation LParenLoc,
307                        tok::ObjCKeywordKind MethodImplKind) :
308     P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
309     MethodImplKind(MethodImplKind) {
310   }
311 
312   void invoke(ParsingFieldDeclarator &FD) {
313     if (FD.D.getIdentifier() == 0) {
314       P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
315         << FD.D.getSourceRange();
316       return;
317     }
318     if (FD.BitfieldSize) {
319       P.Diag(AtLoc, diag::err_objc_property_bitfield)
320         << FD.D.getSourceRange();
321       return;
322     }
323 
324     // Install the property declarator into interfaceDecl.
325     IdentifierInfo *SelName =
326       OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
327 
328     Selector GetterSel =
329       P.PP.getSelectorTable().getNullarySelector(SelName);
330     IdentifierInfo *SetterName = OCDS.getSetterName();
331     Selector SetterSel;
332     if (SetterName)
333       SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
334     else
335       SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(),
336                                                      P.PP.getSelectorTable(),
337                                                      FD.D.getIdentifier());
338     bool isOverridingProperty = false;
339     Decl *Property =
340       P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
341                               FD, OCDS,
342                               GetterSel, SetterSel,
343                               &isOverridingProperty,
344                               MethodImplKind);
345     if (!isOverridingProperty)
346       Props.push_back(Property);
347 
348     FD.complete(Property);
349   }
350 };
351 
352 void Parser::ObjCPropertyCallback::anchor() {
353 }
354 
355 ///   objc-interface-decl-list:
356 ///     empty
357 ///     objc-interface-decl-list objc-property-decl [OBJC2]
358 ///     objc-interface-decl-list objc-method-requirement [OBJC2]
359 ///     objc-interface-decl-list objc-method-proto ';'
360 ///     objc-interface-decl-list declaration
361 ///     objc-interface-decl-list ';'
362 ///
363 ///   objc-method-requirement: [OBJC2]
364 ///     @required
365 ///     @optional
366 ///
367 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
368                                         Decl *CDecl) {
369   SmallVector<Decl *, 32> allMethods;
370   SmallVector<Decl *, 16> allProperties;
371   SmallVector<DeclGroupPtrTy, 8> allTUVariables;
372   tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
373 
374   SourceRange AtEnd;
375 
376   while (1) {
377     // If this is a method prototype, parse it.
378     if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
379       if (Decl *methodPrototype =
380           ParseObjCMethodPrototype(MethodImplKind, false))
381         allMethods.push_back(methodPrototype);
382       // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
383       // method definitions.
384       if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
385         // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
386         SkipUntil(tok::at, /*StopAtSemi=*/true, /*DontConsume=*/true);
387         if (Tok.is(tok::semi))
388           ConsumeToken();
389       }
390       continue;
391     }
392     if (Tok.is(tok::l_paren)) {
393       Diag(Tok, diag::err_expected_minus_or_plus);
394       ParseObjCMethodDecl(Tok.getLocation(),
395                           tok::minus,
396                           MethodImplKind, false);
397       continue;
398     }
399     // Ignore excess semicolons.
400     if (Tok.is(tok::semi)) {
401       ConsumeToken();
402       continue;
403     }
404 
405     // If we got to the end of the file, exit the loop.
406     if (Tok.is(tok::eof))
407       break;
408 
409     // Code completion within an Objective-C interface.
410     if (Tok.is(tok::code_completion)) {
411       Actions.CodeCompleteOrdinaryName(getCurScope(),
412                             CurParsedObjCImpl? Sema::PCC_ObjCImplementation
413                                              : Sema::PCC_ObjCInterface);
414       return cutOffParsing();
415     }
416 
417     // If we don't have an @ directive, parse it as a function definition.
418     if (Tok.isNot(tok::at)) {
419       // The code below does not consume '}'s because it is afraid of eating the
420       // end of a namespace.  Because of the way this code is structured, an
421       // erroneous r_brace would cause an infinite loop if not handled here.
422       if (Tok.is(tok::r_brace))
423         break;
424       ParsedAttributesWithRange attrs(AttrFactory);
425       allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
426       continue;
427     }
428 
429     // Otherwise, we have an @ directive, eat the @.
430     SourceLocation AtLoc = ConsumeToken(); // the "@"
431     if (Tok.is(tok::code_completion)) {
432       Actions.CodeCompleteObjCAtDirective(getCurScope());
433       return cutOffParsing();
434     }
435 
436     tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
437 
438     if (DirectiveKind == tok::objc_end) { // @end -> terminate list
439       AtEnd.setBegin(AtLoc);
440       AtEnd.setEnd(Tok.getLocation());
441       break;
442     } else if (DirectiveKind == tok::objc_not_keyword) {
443       Diag(Tok, diag::err_objc_unknown_at);
444       SkipUntil(tok::semi);
445       continue;
446     }
447 
448     // Eat the identifier.
449     ConsumeToken();
450 
451     switch (DirectiveKind) {
452     default:
453       // FIXME: If someone forgets an @end on a protocol, this loop will
454       // continue to eat up tons of stuff and spew lots of nonsense errors.  It
455       // would probably be better to bail out if we saw an @class or @interface
456       // or something like that.
457       Diag(AtLoc, diag::err_objc_illegal_interface_qual);
458       // Skip until we see an '@' or '}' or ';'.
459       SkipUntil(tok::r_brace, tok::at);
460       break;
461 
462     case tok::objc_implementation:
463     case tok::objc_interface:
464       Diag(AtLoc, diag::err_objc_missing_end)
465           << FixItHint::CreateInsertion(AtLoc, "@end\n");
466       Diag(CDecl->getLocStart(), diag::note_objc_container_start)
467           << (int) Actions.getObjCContainerKind();
468       ConsumeToken();
469       break;
470 
471     case tok::objc_required:
472     case tok::objc_optional:
473       // This is only valid on protocols.
474       // FIXME: Should this check for ObjC2 being enabled?
475       if (contextKey != tok::objc_protocol)
476         Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
477       else
478         MethodImplKind = DirectiveKind;
479       break;
480 
481     case tok::objc_property:
482       if (!getLangOpts().ObjC2)
483         Diag(AtLoc, diag::err_objc_properties_require_objc2);
484 
485       ObjCDeclSpec OCDS;
486       SourceLocation LParenLoc;
487       // Parse property attribute list, if any.
488       if (Tok.is(tok::l_paren)) {
489         LParenLoc = Tok.getLocation();
490         ParseObjCPropertyAttribute(OCDS);
491       }
492 
493       ObjCPropertyCallback Callback(*this, allProperties,
494                                     OCDS, AtLoc, LParenLoc, MethodImplKind);
495 
496       // Parse all the comma separated declarators.
497       ParsingDeclSpec DS(*this);
498       ParseStructDeclaration(DS, Callback);
499 
500       ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
501       break;
502     }
503   }
504 
505   // We break out of the big loop in two cases: when we see @end or when we see
506   // EOF.  In the former case, eat the @end.  In the later case, emit an error.
507   if (Tok.is(tok::code_completion)) {
508     Actions.CodeCompleteObjCAtDirective(getCurScope());
509     return cutOffParsing();
510   } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
511     ConsumeToken(); // the "end" identifier
512   } else {
513     Diag(Tok, diag::err_objc_missing_end)
514         << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
515     Diag(CDecl->getLocStart(), diag::note_objc_container_start)
516         << (int) Actions.getObjCContainerKind();
517     AtEnd.setBegin(Tok.getLocation());
518     AtEnd.setEnd(Tok.getLocation());
519   }
520 
521   // Insert collected methods declarations into the @interface object.
522   // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
523   Actions.ActOnAtEnd(getCurScope(), AtEnd,
524                      allMethods.data(), allMethods.size(),
525                      allProperties.data(), allProperties.size(),
526                      allTUVariables.data(), allTUVariables.size());
527 }
528 
529 ///   Parse property attribute declarations.
530 ///
531 ///   property-attr-decl: '(' property-attrlist ')'
532 ///   property-attrlist:
533 ///     property-attribute
534 ///     property-attrlist ',' property-attribute
535 ///   property-attribute:
536 ///     getter '=' identifier
537 ///     setter '=' identifier ':'
538 ///     readonly
539 ///     readwrite
540 ///     assign
541 ///     retain
542 ///     copy
543 ///     nonatomic
544 ///     atomic
545 ///     strong
546 ///     weak
547 ///     unsafe_unretained
548 ///
549 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
550   assert(Tok.getKind() == tok::l_paren);
551   BalancedDelimiterTracker T(*this, tok::l_paren);
552   T.consumeOpen();
553 
554   while (1) {
555     if (Tok.is(tok::code_completion)) {
556       Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
557       return cutOffParsing();
558     }
559     const IdentifierInfo *II = Tok.getIdentifierInfo();
560 
561     // If this is not an identifier at all, bail out early.
562     if (II == 0) {
563       T.consumeClose();
564       return;
565     }
566 
567     SourceLocation AttrName = ConsumeToken(); // consume last attribute name
568 
569     if (II->isStr("readonly"))
570       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
571     else if (II->isStr("assign"))
572       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
573     else if (II->isStr("unsafe_unretained"))
574       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
575     else if (II->isStr("readwrite"))
576       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
577     else if (II->isStr("retain"))
578       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
579     else if (II->isStr("strong"))
580       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
581     else if (II->isStr("copy"))
582       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
583     else if (II->isStr("nonatomic"))
584       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
585     else if (II->isStr("atomic"))
586       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
587     else if (II->isStr("weak"))
588       DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
589     else if (II->isStr("getter") || II->isStr("setter")) {
590       bool IsSetter = II->getNameStart()[0] == 's';
591 
592       // getter/setter require extra treatment.
593       unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
594         diag::err_objc_expected_equal_for_getter;
595 
596       if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
597         return;
598 
599       if (Tok.is(tok::code_completion)) {
600         if (IsSetter)
601           Actions.CodeCompleteObjCPropertySetter(getCurScope());
602         else
603           Actions.CodeCompleteObjCPropertyGetter(getCurScope());
604         return cutOffParsing();
605       }
606 
607 
608       SourceLocation SelLoc;
609       IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
610 
611       if (!SelIdent) {
612         Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
613           << IsSetter;
614         SkipUntil(tok::r_paren);
615         return;
616       }
617 
618       if (IsSetter) {
619         DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
620         DS.setSetterName(SelIdent);
621 
622         if (ExpectAndConsume(tok::colon,
623                              diag::err_expected_colon_after_setter_name, "",
624                              tok::r_paren))
625           return;
626       } else {
627         DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
628         DS.setGetterName(SelIdent);
629       }
630     } else {
631       Diag(AttrName, diag::err_objc_expected_property_attr) << II;
632       SkipUntil(tok::r_paren);
633       return;
634     }
635 
636     if (Tok.isNot(tok::comma))
637       break;
638 
639     ConsumeToken();
640   }
641 
642   T.consumeClose();
643 }
644 
645 ///   objc-method-proto:
646 ///     objc-instance-method objc-method-decl objc-method-attributes[opt]
647 ///     objc-class-method objc-method-decl objc-method-attributes[opt]
648 ///
649 ///   objc-instance-method: '-'
650 ///   objc-class-method: '+'
651 ///
652 ///   objc-method-attributes:         [OBJC2]
653 ///     __attribute__((deprecated))
654 ///
655 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
656                                        bool MethodDefinition) {
657   assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
658 
659   tok::TokenKind methodType = Tok.getKind();
660   SourceLocation mLoc = ConsumeToken();
661   Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
662                                     MethodDefinition);
663   // Since this rule is used for both method declarations and definitions,
664   // the caller is (optionally) responsible for consuming the ';'.
665   return MDecl;
666 }
667 
668 ///   objc-selector:
669 ///     identifier
670 ///     one of
671 ///       enum struct union if else while do for switch case default
672 ///       break continue return goto asm sizeof typeof __alignof
673 ///       unsigned long const short volatile signed restrict _Complex
674 ///       in out inout bycopy byref oneway int char float double void _Bool
675 ///
676 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
677 
678   switch (Tok.getKind()) {
679   default:
680     return 0;
681   case tok::ampamp:
682   case tok::ampequal:
683   case tok::amp:
684   case tok::pipe:
685   case tok::tilde:
686   case tok::exclaim:
687   case tok::exclaimequal:
688   case tok::pipepipe:
689   case tok::pipeequal:
690   case tok::caret:
691   case tok::caretequal: {
692     std::string ThisTok(PP.getSpelling(Tok));
693     if (isalpha(ThisTok[0])) {
694       IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
695       Tok.setKind(tok::identifier);
696       SelectorLoc = ConsumeToken();
697       return II;
698     }
699     return 0;
700   }
701 
702   case tok::identifier:
703   case tok::kw_asm:
704   case tok::kw_auto:
705   case tok::kw_bool:
706   case tok::kw_break:
707   case tok::kw_case:
708   case tok::kw_catch:
709   case tok::kw_char:
710   case tok::kw_class:
711   case tok::kw_const:
712   case tok::kw_const_cast:
713   case tok::kw_continue:
714   case tok::kw_default:
715   case tok::kw_delete:
716   case tok::kw_do:
717   case tok::kw_double:
718   case tok::kw_dynamic_cast:
719   case tok::kw_else:
720   case tok::kw_enum:
721   case tok::kw_explicit:
722   case tok::kw_export:
723   case tok::kw_extern:
724   case tok::kw_false:
725   case tok::kw_float:
726   case tok::kw_for:
727   case tok::kw_friend:
728   case tok::kw_goto:
729   case tok::kw_if:
730   case tok::kw_inline:
731   case tok::kw_int:
732   case tok::kw_long:
733   case tok::kw_mutable:
734   case tok::kw_namespace:
735   case tok::kw_new:
736   case tok::kw_operator:
737   case tok::kw_private:
738   case tok::kw_protected:
739   case tok::kw_public:
740   case tok::kw_register:
741   case tok::kw_reinterpret_cast:
742   case tok::kw_restrict:
743   case tok::kw_return:
744   case tok::kw_short:
745   case tok::kw_signed:
746   case tok::kw_sizeof:
747   case tok::kw_static:
748   case tok::kw_static_cast:
749   case tok::kw_struct:
750   case tok::kw_switch:
751   case tok::kw_template:
752   case tok::kw_this:
753   case tok::kw_throw:
754   case tok::kw_true:
755   case tok::kw_try:
756   case tok::kw_typedef:
757   case tok::kw_typeid:
758   case tok::kw_typename:
759   case tok::kw_typeof:
760   case tok::kw_union:
761   case tok::kw_unsigned:
762   case tok::kw_using:
763   case tok::kw_virtual:
764   case tok::kw_void:
765   case tok::kw_volatile:
766   case tok::kw_wchar_t:
767   case tok::kw_while:
768   case tok::kw__Bool:
769   case tok::kw__Complex:
770   case tok::kw___alignof:
771     IdentifierInfo *II = Tok.getIdentifierInfo();
772     SelectorLoc = ConsumeToken();
773     return II;
774   }
775 }
776 
777 ///  objc-for-collection-in: 'in'
778 ///
779 bool Parser::isTokIdentifier_in() const {
780   // FIXME: May have to do additional look-ahead to only allow for
781   // valid tokens following an 'in'; such as an identifier, unary operators,
782   // '[' etc.
783   return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
784           Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
785 }
786 
787 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
788 /// qualifier list and builds their bitmask representation in the input
789 /// argument.
790 ///
791 ///   objc-type-qualifiers:
792 ///     objc-type-qualifier
793 ///     objc-type-qualifiers objc-type-qualifier
794 ///
795 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
796                                         Declarator::TheContext Context) {
797   assert(Context == Declarator::ObjCParameterContext ||
798          Context == Declarator::ObjCResultContext);
799 
800   while (1) {
801     if (Tok.is(tok::code_completion)) {
802       Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
803                           Context == Declarator::ObjCParameterContext);
804       return cutOffParsing();
805     }
806 
807     if (Tok.isNot(tok::identifier))
808       return;
809 
810     const IdentifierInfo *II = Tok.getIdentifierInfo();
811     for (unsigned i = 0; i != objc_NumQuals; ++i) {
812       if (II != ObjCTypeQuals[i])
813         continue;
814 
815       ObjCDeclSpec::ObjCDeclQualifier Qual;
816       switch (i) {
817       default: llvm_unreachable("Unknown decl qualifier");
818       case objc_in:     Qual = ObjCDeclSpec::DQ_In; break;
819       case objc_out:    Qual = ObjCDeclSpec::DQ_Out; break;
820       case objc_inout:  Qual = ObjCDeclSpec::DQ_Inout; break;
821       case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
822       case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
823       case objc_byref:  Qual = ObjCDeclSpec::DQ_Byref; break;
824       }
825       DS.setObjCDeclQualifier(Qual);
826       ConsumeToken();
827       II = 0;
828       break;
829     }
830 
831     // If this wasn't a recognized qualifier, bail out.
832     if (II) return;
833   }
834 }
835 
836 /// Take all the decl attributes out of the given list and add
837 /// them to the given attribute set.
838 static void takeDeclAttributes(ParsedAttributes &attrs,
839                                AttributeList *list) {
840   while (list) {
841     AttributeList *cur = list;
842     list = cur->getNext();
843 
844     if (!cur->isUsedAsTypeAttr()) {
845       // Clear out the next pointer.  We're really completely
846       // destroying the internal invariants of the declarator here,
847       // but it doesn't matter because we're done with it.
848       cur->setNext(0);
849       attrs.add(cur);
850     }
851   }
852 }
853 
854 /// takeDeclAttributes - Take all the decl attributes from the given
855 /// declarator and add them to the given list.
856 static void takeDeclAttributes(ParsedAttributes &attrs,
857                                Declarator &D) {
858   // First, take ownership of all attributes.
859   attrs.getPool().takeAllFrom(D.getAttributePool());
860   attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
861 
862   // Now actually move the attributes over.
863   takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
864   takeDeclAttributes(attrs, D.getAttributes());
865   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
866     takeDeclAttributes(attrs,
867                   const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
868 }
869 
870 ///   objc-type-name:
871 ///     '(' objc-type-qualifiers[opt] type-name ')'
872 ///     '(' objc-type-qualifiers[opt] ')'
873 ///
874 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
875                                      Declarator::TheContext context,
876                                      ParsedAttributes *paramAttrs) {
877   assert(context == Declarator::ObjCParameterContext ||
878          context == Declarator::ObjCResultContext);
879   assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext));
880 
881   assert(Tok.is(tok::l_paren) && "expected (");
882 
883   BalancedDelimiterTracker T(*this, tok::l_paren);
884   T.consumeOpen();
885 
886   SourceLocation TypeStartLoc = Tok.getLocation();
887   ObjCDeclContextSwitch ObjCDC(*this);
888 
889   // Parse type qualifiers, in, inout, etc.
890   ParseObjCTypeQualifierList(DS, context);
891 
892   ParsedType Ty;
893   if (isTypeSpecifierQualifier()) {
894     // Parse an abstract declarator.
895     DeclSpec declSpec(AttrFactory);
896     declSpec.setObjCQualifiers(&DS);
897     ParseSpecifierQualifierList(declSpec);
898     declSpec.SetRangeEnd(Tok.getLocation());
899     Declarator declarator(declSpec, context);
900     ParseDeclarator(declarator);
901 
902     // If that's not invalid, extract a type.
903     if (!declarator.isInvalidType()) {
904       TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
905       if (!type.isInvalid())
906         Ty = type.get();
907 
908       // If we're parsing a parameter, steal all the decl attributes
909       // and add them to the decl spec.
910       if (context == Declarator::ObjCParameterContext)
911         takeDeclAttributes(*paramAttrs, declarator);
912     }
913   } else if (context == Declarator::ObjCResultContext &&
914              Tok.is(tok::identifier)) {
915     if (!Ident_instancetype)
916       Ident_instancetype = PP.getIdentifierInfo("instancetype");
917 
918     if (Tok.getIdentifierInfo() == Ident_instancetype) {
919       Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
920       ConsumeToken();
921     }
922   }
923 
924   if (Tok.is(tok::r_paren))
925     T.consumeClose();
926   else if (Tok.getLocation() == TypeStartLoc) {
927     // If we didn't eat any tokens, then this isn't a type.
928     Diag(Tok, diag::err_expected_type);
929     SkipUntil(tok::r_paren);
930   } else {
931     // Otherwise, we found *something*, but didn't get a ')' in the right
932     // place.  Emit an error then return what we have as the type.
933     T.consumeClose();
934   }
935   return Ty;
936 }
937 
938 ///   objc-method-decl:
939 ///     objc-selector
940 ///     objc-keyword-selector objc-parmlist[opt]
941 ///     objc-type-name objc-selector
942 ///     objc-type-name objc-keyword-selector objc-parmlist[opt]
943 ///
944 ///   objc-keyword-selector:
945 ///     objc-keyword-decl
946 ///     objc-keyword-selector objc-keyword-decl
947 ///
948 ///   objc-keyword-decl:
949 ///     objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
950 ///     objc-selector ':' objc-keyword-attributes[opt] identifier
951 ///     ':' objc-type-name objc-keyword-attributes[opt] identifier
952 ///     ':' objc-keyword-attributes[opt] identifier
953 ///
954 ///   objc-parmlist:
955 ///     objc-parms objc-ellipsis[opt]
956 ///
957 ///   objc-parms:
958 ///     objc-parms , parameter-declaration
959 ///
960 ///   objc-ellipsis:
961 ///     , ...
962 ///
963 ///   objc-keyword-attributes:         [OBJC2]
964 ///     __attribute__((unused))
965 ///
966 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
967                                   tok::TokenKind mType,
968                                   tok::ObjCKeywordKind MethodImplKind,
969                                   bool MethodDefinition) {
970   ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
971 
972   if (Tok.is(tok::code_completion)) {
973     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
974                                        /*ReturnType=*/ ParsedType());
975     cutOffParsing();
976     return 0;
977   }
978 
979   // Parse the return type if present.
980   ParsedType ReturnType;
981   ObjCDeclSpec DSRet;
982   if (Tok.is(tok::l_paren))
983     ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0);
984 
985   // If attributes exist before the method, parse them.
986   ParsedAttributes methodAttrs(AttrFactory);
987   if (getLangOpts().ObjC2)
988     MaybeParseGNUAttributes(methodAttrs);
989 
990   if (Tok.is(tok::code_completion)) {
991     Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
992                                        ReturnType);
993     cutOffParsing();
994     return 0;
995   }
996 
997   // Now parse the selector.
998   SourceLocation selLoc;
999   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1000 
1001   // An unnamed colon is valid.
1002   if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1003     Diag(Tok, diag::err_expected_selector_for_method)
1004       << SourceRange(mLoc, Tok.getLocation());
1005     // Skip until we get a ; or @.
1006     SkipUntil(tok::at, true /*StopAtSemi*/, true /*don't consume*/);
1007     return 0;
1008   }
1009 
1010   SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1011   if (Tok.isNot(tok::colon)) {
1012     // If attributes exist after the method, parse them.
1013     if (getLangOpts().ObjC2)
1014       MaybeParseGNUAttributes(methodAttrs);
1015 
1016     Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1017     Decl *Result
1018          = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1019                                           mType, DSRet, ReturnType,
1020                                           selLoc, Sel, 0,
1021                                           CParamInfo.data(), CParamInfo.size(),
1022                                           methodAttrs.getList(), MethodImplKind,
1023                                           false, MethodDefinition);
1024     PD.complete(Result);
1025     return Result;
1026   }
1027 
1028   SmallVector<IdentifierInfo *, 12> KeyIdents;
1029   SmallVector<SourceLocation, 12> KeyLocs;
1030   SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1031   ParseScope PrototypeScope(this,
1032                             Scope::FunctionPrototypeScope|Scope::DeclScope);
1033 
1034   AttributePool allParamAttrs(AttrFactory);
1035   bool warnSelectorName = false;
1036   while (1) {
1037     ParsedAttributes paramAttrs(AttrFactory);
1038     Sema::ObjCArgInfo ArgInfo;
1039 
1040     // Each iteration parses a single keyword argument.
1041     if (Tok.isNot(tok::colon)) {
1042       Diag(Tok, diag::err_expected_colon);
1043       break;
1044     }
1045     ConsumeToken(); // Eat the ':'.
1046 
1047     ArgInfo.Type = ParsedType();
1048     if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1049       ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1050                                        Declarator::ObjCParameterContext,
1051                                        &paramAttrs);
1052 
1053     // If attributes exist before the argument name, parse them.
1054     // Regardless, collect all the attributes we've parsed so far.
1055     ArgInfo.ArgAttrs = 0;
1056     if (getLangOpts().ObjC2) {
1057       MaybeParseGNUAttributes(paramAttrs);
1058       ArgInfo.ArgAttrs = paramAttrs.getList();
1059     }
1060 
1061     // Code completion for the next piece of the selector.
1062     if (Tok.is(tok::code_completion)) {
1063       KeyIdents.push_back(SelIdent);
1064       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1065                                                  mType == tok::minus,
1066                                                  /*AtParameterName=*/true,
1067                                                  ReturnType,
1068                                                  KeyIdents.data(),
1069                                                  KeyIdents.size());
1070       cutOffParsing();
1071       return 0;
1072     }
1073 
1074     if (Tok.isNot(tok::identifier)) {
1075       Diag(Tok, diag::err_expected_ident); // missing argument name.
1076       break;
1077     }
1078 
1079     ArgInfo.Name = Tok.getIdentifierInfo();
1080     ArgInfo.NameLoc = Tok.getLocation();
1081     ConsumeToken(); // Eat the identifier.
1082 
1083     ArgInfos.push_back(ArgInfo);
1084     KeyIdents.push_back(SelIdent);
1085     KeyLocs.push_back(selLoc);
1086 
1087     // Make sure the attributes persist.
1088     allParamAttrs.takeAllFrom(paramAttrs.getPool());
1089 
1090     // Code completion for the next piece of the selector.
1091     if (Tok.is(tok::code_completion)) {
1092       Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1093                                                  mType == tok::minus,
1094                                                  /*AtParameterName=*/false,
1095                                                  ReturnType,
1096                                                  KeyIdents.data(),
1097                                                  KeyIdents.size());
1098       cutOffParsing();
1099       return 0;
1100     }
1101 
1102     // Check for another keyword selector.
1103     SelIdent = ParseObjCSelectorPiece(selLoc);
1104     if (!SelIdent && Tok.isNot(tok::colon))
1105       break;
1106     if (MethodDefinition && !SelIdent) {
1107       SourceLocation ColonLoc = Tok.getLocation();
1108       if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1109         warnSelectorName = true;
1110         Diag(ArgInfo.NameLoc, diag::missing_selector_name);
1111       }
1112     }
1113     // We have a selector or a colon, continue parsing.
1114   }
1115 
1116   bool isVariadic = false;
1117   bool cStyleParamWarned = false;
1118   // Parse the (optional) parameter list.
1119   while (Tok.is(tok::comma)) {
1120     ConsumeToken();
1121     if (Tok.is(tok::ellipsis)) {
1122       isVariadic = true;
1123       ConsumeToken();
1124       break;
1125     }
1126     if (!cStyleParamWarned) {
1127       Diag(Tok, diag::warn_cstyle_param);
1128       cStyleParamWarned = true;
1129     }
1130     DeclSpec DS(AttrFactory);
1131     ParseDeclarationSpecifiers(DS);
1132     // Parse the declarator.
1133     Declarator ParmDecl(DS, Declarator::PrototypeContext);
1134     ParseDeclarator(ParmDecl);
1135     IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1136     Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1137     CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1138                                                     ParmDecl.getIdentifierLoc(),
1139                                                     Param,
1140                                                    0));
1141   }
1142 
1143   // FIXME: Add support for optional parameter list...
1144   // If attributes exist after the method, parse them.
1145   if (getLangOpts().ObjC2)
1146     MaybeParseGNUAttributes(methodAttrs);
1147 
1148   if (KeyIdents.size() == 0)
1149     return 0;
1150 
1151   Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1152                                                    &KeyIdents[0]);
1153   if (warnSelectorName) {
1154     SmallVector<IdentifierInfo *, 12> DiagKeyIdents;
1155     for (unsigned i = 0, size = KeyIdents.size(); i < size; i++)
1156       if (KeyIdents[i])
1157         DiagKeyIdents.push_back(KeyIdents[i]);
1158       else {
1159         std::string name = "Name";
1160         name += llvm::utostr(i+1);
1161         IdentifierInfo *NamedMissingId = &PP.getIdentifierTable().get(name);
1162         DiagKeyIdents.push_back(NamedMissingId);
1163       }
1164       Selector NewSel =
1165         PP.getSelectorTable().getSelector(DiagKeyIdents.size(), &DiagKeyIdents[0]);
1166       Diag(mLoc, diag::note_missing_argument_name)
1167         << NewSel.getAsString() << Sel.getAsString();
1168   }
1169   Decl *Result
1170        = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1171                                         mType, DSRet, ReturnType,
1172                                         KeyLocs, Sel, &ArgInfos[0],
1173                                         CParamInfo.data(), CParamInfo.size(),
1174                                         methodAttrs.getList(),
1175                                         MethodImplKind, isVariadic, MethodDefinition);
1176 
1177   PD.complete(Result);
1178   return Result;
1179 }
1180 
1181 ///   objc-protocol-refs:
1182 ///     '<' identifier-list '>'
1183 ///
1184 bool Parser::
1185 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1186                             SmallVectorImpl<SourceLocation> &ProtocolLocs,
1187                             bool WarnOnDeclarations,
1188                             SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1189   assert(Tok.is(tok::less) && "expected <");
1190 
1191   LAngleLoc = ConsumeToken(); // the "<"
1192 
1193   SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1194 
1195   while (1) {
1196     if (Tok.is(tok::code_completion)) {
1197       Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1198                                                  ProtocolIdents.size());
1199       cutOffParsing();
1200       return true;
1201     }
1202 
1203     if (Tok.isNot(tok::identifier)) {
1204       Diag(Tok, diag::err_expected_ident);
1205       SkipUntil(tok::greater);
1206       return true;
1207     }
1208     ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1209                                        Tok.getLocation()));
1210     ProtocolLocs.push_back(Tok.getLocation());
1211     ConsumeToken();
1212 
1213     if (Tok.isNot(tok::comma))
1214       break;
1215     ConsumeToken();
1216   }
1217 
1218   // Consume the '>'.
1219   if (Tok.isNot(tok::greater)) {
1220     Diag(Tok, diag::err_expected_greater);
1221     return true;
1222   }
1223 
1224   EndLoc = ConsumeToken();
1225 
1226   // Convert the list of protocols identifiers into a list of protocol decls.
1227   Actions.FindProtocolDeclaration(WarnOnDeclarations,
1228                                   &ProtocolIdents[0], ProtocolIdents.size(),
1229                                   Protocols);
1230   return false;
1231 }
1232 
1233 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1234 /// in a decl-specifier-seq, starting at the '<'.
1235 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1236   assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1237   assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1238   SourceLocation LAngleLoc, EndProtoLoc;
1239   SmallVector<Decl *, 8> ProtocolDecl;
1240   SmallVector<SourceLocation, 8> ProtocolLocs;
1241   bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1242                                             LAngleLoc, EndProtoLoc);
1243   DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1244                            ProtocolLocs.data(), LAngleLoc);
1245   if (EndProtoLoc.isValid())
1246     DS.SetRangeEnd(EndProtoLoc);
1247   return Result;
1248 }
1249 
1250 
1251 ///   objc-class-instance-variables:
1252 ///     '{' objc-instance-variable-decl-list[opt] '}'
1253 ///
1254 ///   objc-instance-variable-decl-list:
1255 ///     objc-visibility-spec
1256 ///     objc-instance-variable-decl ';'
1257 ///     ';'
1258 ///     objc-instance-variable-decl-list objc-visibility-spec
1259 ///     objc-instance-variable-decl-list objc-instance-variable-decl ';'
1260 ///     objc-instance-variable-decl-list ';'
1261 ///
1262 ///   objc-visibility-spec:
1263 ///     @private
1264 ///     @protected
1265 ///     @public
1266 ///     @package [OBJC2]
1267 ///
1268 ///   objc-instance-variable-decl:
1269 ///     struct-declaration
1270 ///
1271 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1272                                              tok::ObjCKeywordKind visibility,
1273                                              SourceLocation atLoc) {
1274   assert(Tok.is(tok::l_brace) && "expected {");
1275   SmallVector<Decl *, 32> AllIvarDecls;
1276 
1277   ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1278   ObjCDeclContextSwitch ObjCDC(*this);
1279 
1280   BalancedDelimiterTracker T(*this, tok::l_brace);
1281   T.consumeOpen();
1282 
1283   // While we still have something to read, read the instance variables.
1284   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1285     // Each iteration of this loop reads one objc-instance-variable-decl.
1286 
1287     // Check for extraneous top-level semicolon.
1288     if (Tok.is(tok::semi)) {
1289       ConsumeExtraSemi(InstanceVariableList);
1290       continue;
1291     }
1292 
1293     // Set the default visibility to private.
1294     if (Tok.is(tok::at)) { // parse objc-visibility-spec
1295       ConsumeToken(); // eat the @ sign
1296 
1297       if (Tok.is(tok::code_completion)) {
1298         Actions.CodeCompleteObjCAtVisibility(getCurScope());
1299         return cutOffParsing();
1300       }
1301 
1302       switch (Tok.getObjCKeywordID()) {
1303       case tok::objc_private:
1304       case tok::objc_public:
1305       case tok::objc_protected:
1306       case tok::objc_package:
1307         visibility = Tok.getObjCKeywordID();
1308         ConsumeToken();
1309         continue;
1310       default:
1311         Diag(Tok, diag::err_objc_illegal_visibility_spec);
1312         continue;
1313       }
1314     }
1315 
1316     if (Tok.is(tok::code_completion)) {
1317       Actions.CodeCompleteOrdinaryName(getCurScope(),
1318                                        Sema::PCC_ObjCInstanceVariableList);
1319       return cutOffParsing();
1320     }
1321 
1322     struct ObjCIvarCallback : FieldCallback {
1323       Parser &P;
1324       Decl *IDecl;
1325       tok::ObjCKeywordKind visibility;
1326       SmallVectorImpl<Decl *> &AllIvarDecls;
1327 
1328       ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1329                        SmallVectorImpl<Decl *> &AllIvarDecls) :
1330         P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1331       }
1332 
1333       void invoke(ParsingFieldDeclarator &FD) {
1334         P.Actions.ActOnObjCContainerStartDefinition(IDecl);
1335         // Install the declarator into the interface decl.
1336         Decl *Field
1337           = P.Actions.ActOnIvar(P.getCurScope(),
1338                                 FD.D.getDeclSpec().getSourceRange().getBegin(),
1339                                 FD.D, FD.BitfieldSize, visibility);
1340         P.Actions.ActOnObjCContainerFinishDefinition();
1341         if (Field)
1342           AllIvarDecls.push_back(Field);
1343         FD.complete(Field);
1344       }
1345     } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1346 
1347     // Parse all the comma separated declarators.
1348     ParsingDeclSpec DS(*this);
1349     ParseStructDeclaration(DS, Callback);
1350 
1351     if (Tok.is(tok::semi)) {
1352       ConsumeToken();
1353     } else {
1354       Diag(Tok, diag::err_expected_semi_decl_list);
1355       // Skip to end of block or statement
1356       SkipUntil(tok::r_brace, true, true);
1357     }
1358   }
1359   T.consumeClose();
1360 
1361   Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1362   Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1363   Actions.ActOnObjCContainerFinishDefinition();
1364   // Call ActOnFields() even if we don't have any decls. This is useful
1365   // for code rewriting tools that need to be aware of the empty list.
1366   Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1367                       AllIvarDecls,
1368                       T.getOpenLocation(), T.getCloseLocation(), 0);
1369   return;
1370 }
1371 
1372 ///   objc-protocol-declaration:
1373 ///     objc-protocol-definition
1374 ///     objc-protocol-forward-reference
1375 ///
1376 ///   objc-protocol-definition:
1377 ///     \@protocol identifier
1378 ///       objc-protocol-refs[opt]
1379 ///       objc-interface-decl-list
1380 ///     \@end
1381 ///
1382 ///   objc-protocol-forward-reference:
1383 ///     \@protocol identifier-list ';'
1384 ///
1385 ///   "\@protocol identifier ;" should be resolved as "\@protocol
1386 ///   identifier-list ;": objc-interface-decl-list may not start with a
1387 ///   semicolon in the first alternative if objc-protocol-refs are omitted.
1388 Parser::DeclGroupPtrTy
1389 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1390                                        ParsedAttributes &attrs) {
1391   assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1392          "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1393   ConsumeToken(); // the "protocol" identifier
1394 
1395   if (Tok.is(tok::code_completion)) {
1396     Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1397     cutOffParsing();
1398     return DeclGroupPtrTy();
1399   }
1400 
1401   if (Tok.isNot(tok::identifier)) {
1402     Diag(Tok, diag::err_expected_ident); // missing protocol name.
1403     return DeclGroupPtrTy();
1404   }
1405   // Save the protocol name, then consume it.
1406   IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1407   SourceLocation nameLoc = ConsumeToken();
1408 
1409   if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1410     IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1411     ConsumeToken();
1412     return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1413                                                    attrs.getList());
1414   }
1415 
1416   CheckNestedObjCContexts(AtLoc);
1417 
1418   if (Tok.is(tok::comma)) { // list of forward declarations.
1419     SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1420     ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1421 
1422     // Parse the list of forward declarations.
1423     while (1) {
1424       ConsumeToken(); // the ','
1425       if (Tok.isNot(tok::identifier)) {
1426         Diag(Tok, diag::err_expected_ident);
1427         SkipUntil(tok::semi);
1428         return DeclGroupPtrTy();
1429       }
1430       ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1431                                                Tok.getLocation()));
1432       ConsumeToken(); // the identifier
1433 
1434       if (Tok.isNot(tok::comma))
1435         break;
1436     }
1437     // Consume the ';'.
1438     if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1439       return DeclGroupPtrTy();
1440 
1441     return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1442                                                    &ProtocolRefs[0],
1443                                                    ProtocolRefs.size(),
1444                                                    attrs.getList());
1445   }
1446 
1447   // Last, and definitely not least, parse a protocol declaration.
1448   SourceLocation LAngleLoc, EndProtoLoc;
1449 
1450   SmallVector<Decl *, 8> ProtocolRefs;
1451   SmallVector<SourceLocation, 8> ProtocolLocs;
1452   if (Tok.is(tok::less) &&
1453       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1454                                   LAngleLoc, EndProtoLoc))
1455     return DeclGroupPtrTy();
1456 
1457   Decl *ProtoType =
1458     Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1459                                         ProtocolRefs.data(),
1460                                         ProtocolRefs.size(),
1461                                         ProtocolLocs.data(),
1462                                         EndProtoLoc, attrs.getList());
1463 
1464   ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1465   return Actions.ConvertDeclToDeclGroup(ProtoType);
1466 }
1467 
1468 ///   objc-implementation:
1469 ///     objc-class-implementation-prologue
1470 ///     objc-category-implementation-prologue
1471 ///
1472 ///   objc-class-implementation-prologue:
1473 ///     @implementation identifier objc-superclass[opt]
1474 ///       objc-class-instance-variables[opt]
1475 ///
1476 ///   objc-category-implementation-prologue:
1477 ///     @implementation identifier ( identifier )
1478 Parser::DeclGroupPtrTy
1479 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
1480   assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1481          "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1482   CheckNestedObjCContexts(AtLoc);
1483   ConsumeToken(); // the "implementation" identifier
1484 
1485   // Code completion after '@implementation'.
1486   if (Tok.is(tok::code_completion)) {
1487     Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1488     cutOffParsing();
1489     return DeclGroupPtrTy();
1490   }
1491 
1492   if (Tok.isNot(tok::identifier)) {
1493     Diag(Tok, diag::err_expected_ident); // missing class or category name.
1494     return DeclGroupPtrTy();
1495   }
1496   // We have a class or category name - consume it.
1497   IdentifierInfo *nameId = Tok.getIdentifierInfo();
1498   SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1499   Decl *ObjCImpDecl = 0;
1500 
1501   if (Tok.is(tok::l_paren)) {
1502     // we have a category implementation.
1503     ConsumeParen();
1504     SourceLocation categoryLoc, rparenLoc;
1505     IdentifierInfo *categoryId = 0;
1506 
1507     if (Tok.is(tok::code_completion)) {
1508       Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1509       cutOffParsing();
1510       return DeclGroupPtrTy();
1511     }
1512 
1513     if (Tok.is(tok::identifier)) {
1514       categoryId = Tok.getIdentifierInfo();
1515       categoryLoc = ConsumeToken();
1516     } else {
1517       Diag(Tok, diag::err_expected_ident); // missing category name.
1518       return DeclGroupPtrTy();
1519     }
1520     if (Tok.isNot(tok::r_paren)) {
1521       Diag(Tok, diag::err_expected_rparen);
1522       SkipUntil(tok::r_paren, false); // don't stop at ';'
1523       return DeclGroupPtrTy();
1524     }
1525     rparenLoc = ConsumeParen();
1526     ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
1527                                     AtLoc, nameId, nameLoc, categoryId,
1528                                     categoryLoc);
1529 
1530   } else {
1531     // We have a class implementation
1532     SourceLocation superClassLoc;
1533     IdentifierInfo *superClassId = 0;
1534     if (Tok.is(tok::colon)) {
1535       // We have a super class
1536       ConsumeToken();
1537       if (Tok.isNot(tok::identifier)) {
1538         Diag(Tok, diag::err_expected_ident); // missing super class name.
1539         return DeclGroupPtrTy();
1540       }
1541       superClassId = Tok.getIdentifierInfo();
1542       superClassLoc = ConsumeToken(); // Consume super class name
1543     }
1544     ObjCImpDecl = Actions.ActOnStartClassImplementation(
1545                                     AtLoc, nameId, nameLoc,
1546                                     superClassId, superClassLoc);
1547 
1548     if (Tok.is(tok::l_brace)) // we have ivars
1549       ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
1550   }
1551   assert(ObjCImpDecl);
1552 
1553   SmallVector<Decl *, 8> DeclsInGroup;
1554 
1555   {
1556     ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1557     while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
1558       ParsedAttributesWithRange attrs(AttrFactory);
1559       MaybeParseCXX0XAttributes(attrs);
1560       MaybeParseMicrosoftAttributes(attrs);
1561       if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1562         DeclGroupRef DG = DGP.get();
1563         DeclsInGroup.append(DG.begin(), DG.end());
1564       }
1565     }
1566   }
1567 
1568   return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1569 }
1570 
1571 Parser::DeclGroupPtrTy
1572 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1573   assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1574          "ParseObjCAtEndDeclaration(): Expected @end");
1575   ConsumeToken(); // the "end" identifier
1576   if (CurParsedObjCImpl)
1577     CurParsedObjCImpl->finish(atEnd);
1578   else
1579     // missing @implementation
1580     Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1581   return DeclGroupPtrTy();
1582 }
1583 
1584 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1585   if (!Finished) {
1586     finish(P.Tok.getLocation());
1587     if (P.Tok.is(tok::eof)) {
1588       P.Diag(P.Tok, diag::err_objc_missing_end)
1589           << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1590       P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1591           << Sema::OCK_Implementation;
1592     }
1593   }
1594   P.CurParsedObjCImpl = 0;
1595   assert(LateParsedObjCMethods.empty());
1596 }
1597 
1598 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1599   assert(!Finished);
1600   P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1601   for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1602     P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1603                                true/*Methods*/);
1604 
1605   P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1606 
1607   if (HasCFunction)
1608     for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1609       P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1610                                  false/*c-functions*/);
1611 
1612   /// \brief Clear and free the cached objc methods.
1613   for (LateParsedObjCMethodContainer::iterator
1614          I = LateParsedObjCMethods.begin(),
1615          E = LateParsedObjCMethods.end(); I != E; ++I)
1616     delete *I;
1617   LateParsedObjCMethods.clear();
1618 
1619   Finished = true;
1620 }
1621 
1622 ///   compatibility-alias-decl:
1623 ///     @compatibility_alias alias-name  class-name ';'
1624 ///
1625 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1626   assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1627          "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1628   ConsumeToken(); // consume compatibility_alias
1629   if (Tok.isNot(tok::identifier)) {
1630     Diag(Tok, diag::err_expected_ident);
1631     return 0;
1632   }
1633   IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1634   SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1635   if (Tok.isNot(tok::identifier)) {
1636     Diag(Tok, diag::err_expected_ident);
1637     return 0;
1638   }
1639   IdentifierInfo *classId = Tok.getIdentifierInfo();
1640   SourceLocation classLoc = ConsumeToken(); // consume class-name;
1641   ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1642                    "@compatibility_alias");
1643   return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1644                                          classId, classLoc);
1645 }
1646 
1647 ///   property-synthesis:
1648 ///     @synthesize property-ivar-list ';'
1649 ///
1650 ///   property-ivar-list:
1651 ///     property-ivar
1652 ///     property-ivar-list ',' property-ivar
1653 ///
1654 ///   property-ivar:
1655 ///     identifier
1656 ///     identifier '=' identifier
1657 ///
1658 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1659   assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1660          "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1661   ConsumeToken(); // consume synthesize
1662 
1663   while (true) {
1664     if (Tok.is(tok::code_completion)) {
1665       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1666       cutOffParsing();
1667       return 0;
1668     }
1669 
1670     if (Tok.isNot(tok::identifier)) {
1671       Diag(Tok, diag::err_synthesized_property_name);
1672       SkipUntil(tok::semi);
1673       return 0;
1674     }
1675 
1676     IdentifierInfo *propertyIvar = 0;
1677     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1678     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1679     SourceLocation propertyIvarLoc;
1680     if (Tok.is(tok::equal)) {
1681       // property '=' ivar-name
1682       ConsumeToken(); // consume '='
1683 
1684       if (Tok.is(tok::code_completion)) {
1685         Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1686         cutOffParsing();
1687         return 0;
1688       }
1689 
1690       if (Tok.isNot(tok::identifier)) {
1691         Diag(Tok, diag::err_expected_ident);
1692         break;
1693       }
1694       propertyIvar = Tok.getIdentifierInfo();
1695       propertyIvarLoc = ConsumeToken(); // consume ivar-name
1696     }
1697     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1698                                   propertyId, propertyIvar, propertyIvarLoc);
1699     if (Tok.isNot(tok::comma))
1700       break;
1701     ConsumeToken(); // consume ','
1702   }
1703   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1704   return 0;
1705 }
1706 
1707 ///   property-dynamic:
1708 ///     @dynamic  property-list
1709 ///
1710 ///   property-list:
1711 ///     identifier
1712 ///     property-list ',' identifier
1713 ///
1714 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1715   assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1716          "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1717   ConsumeToken(); // consume dynamic
1718   while (true) {
1719     if (Tok.is(tok::code_completion)) {
1720       Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1721       cutOffParsing();
1722       return 0;
1723     }
1724 
1725     if (Tok.isNot(tok::identifier)) {
1726       Diag(Tok, diag::err_expected_ident);
1727       SkipUntil(tok::semi);
1728       return 0;
1729     }
1730 
1731     IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1732     SourceLocation propertyLoc = ConsumeToken(); // consume property name
1733     Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1734                                   propertyId, 0, SourceLocation());
1735 
1736     if (Tok.isNot(tok::comma))
1737       break;
1738     ConsumeToken(); // consume ','
1739   }
1740   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1741   return 0;
1742 }
1743 
1744 ///  objc-throw-statement:
1745 ///    throw expression[opt];
1746 ///
1747 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1748   ExprResult Res;
1749   ConsumeToken(); // consume throw
1750   if (Tok.isNot(tok::semi)) {
1751     Res = ParseExpression();
1752     if (Res.isInvalid()) {
1753       SkipUntil(tok::semi);
1754       return StmtError();
1755     }
1756   }
1757   // consume ';'
1758   ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1759   return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1760 }
1761 
1762 /// objc-synchronized-statement:
1763 ///   @synchronized '(' expression ')' compound-statement
1764 ///
1765 StmtResult
1766 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1767   ConsumeToken(); // consume synchronized
1768   if (Tok.isNot(tok::l_paren)) {
1769     Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1770     return StmtError();
1771   }
1772 
1773   // The operand is surrounded with parentheses.
1774   ConsumeParen();  // '('
1775   ExprResult operand(ParseExpression());
1776 
1777   if (Tok.is(tok::r_paren)) {
1778     ConsumeParen();  // ')'
1779   } else {
1780     if (!operand.isInvalid())
1781       Diag(Tok, diag::err_expected_rparen);
1782 
1783     // Skip forward until we see a left brace, but don't consume it.
1784     SkipUntil(tok::l_brace, true, true);
1785   }
1786 
1787   // Require a compound statement.
1788   if (Tok.isNot(tok::l_brace)) {
1789     if (!operand.isInvalid())
1790       Diag(Tok, diag::err_expected_lbrace);
1791     return StmtError();
1792   }
1793 
1794   // Check the @synchronized operand now.
1795   if (!operand.isInvalid())
1796     operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
1797 
1798   // Parse the compound statement within a new scope.
1799   ParseScope bodyScope(this, Scope::DeclScope);
1800   StmtResult body(ParseCompoundStatementBody());
1801   bodyScope.Exit();
1802 
1803   // If there was a semantic or parse error earlier with the
1804   // operand, fail now.
1805   if (operand.isInvalid())
1806     return StmtError();
1807 
1808   if (body.isInvalid())
1809     body = Actions.ActOnNullStmt(Tok.getLocation());
1810 
1811   return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1812 }
1813 
1814 ///  objc-try-catch-statement:
1815 ///    @try compound-statement objc-catch-list[opt]
1816 ///    @try compound-statement objc-catch-list[opt] @finally compound-statement
1817 ///
1818 ///  objc-catch-list:
1819 ///    @catch ( parameter-declaration ) compound-statement
1820 ///    objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1821 ///  catch-parameter-declaration:
1822 ///     parameter-declaration
1823 ///     '...' [OBJC2]
1824 ///
1825 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1826   bool catch_or_finally_seen = false;
1827 
1828   ConsumeToken(); // consume try
1829   if (Tok.isNot(tok::l_brace)) {
1830     Diag(Tok, diag::err_expected_lbrace);
1831     return StmtError();
1832   }
1833   StmtVector CatchStmts;
1834   StmtResult FinallyStmt;
1835   ParseScope TryScope(this, Scope::DeclScope);
1836   StmtResult TryBody(ParseCompoundStatementBody());
1837   TryScope.Exit();
1838   if (TryBody.isInvalid())
1839     TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1840 
1841   while (Tok.is(tok::at)) {
1842     // At this point, we need to lookahead to determine if this @ is the start
1843     // of an @catch or @finally.  We don't want to consume the @ token if this
1844     // is an @try or @encode or something else.
1845     Token AfterAt = GetLookAheadToken(1);
1846     if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1847         !AfterAt.isObjCAtKeyword(tok::objc_finally))
1848       break;
1849 
1850     SourceLocation AtCatchFinallyLoc = ConsumeToken();
1851     if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1852       Decl *FirstPart = 0;
1853       ConsumeToken(); // consume catch
1854       if (Tok.is(tok::l_paren)) {
1855         ConsumeParen();
1856         ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1857         if (Tok.isNot(tok::ellipsis)) {
1858           DeclSpec DS(AttrFactory);
1859           ParseDeclarationSpecifiers(DS);
1860           Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1861           ParseDeclarator(ParmDecl);
1862 
1863           // Inform the actions module about the declarator, so it
1864           // gets added to the current scope.
1865           FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1866         } else
1867           ConsumeToken(); // consume '...'
1868 
1869         SourceLocation RParenLoc;
1870 
1871         if (Tok.is(tok::r_paren))
1872           RParenLoc = ConsumeParen();
1873         else // Skip over garbage, until we get to ')'.  Eat the ')'.
1874           SkipUntil(tok::r_paren, true, false);
1875 
1876         StmtResult CatchBody(true);
1877         if (Tok.is(tok::l_brace))
1878           CatchBody = ParseCompoundStatementBody();
1879         else
1880           Diag(Tok, diag::err_expected_lbrace);
1881         if (CatchBody.isInvalid())
1882           CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1883 
1884         StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1885                                                               RParenLoc,
1886                                                               FirstPart,
1887                                                               CatchBody.take());
1888         if (!Catch.isInvalid())
1889           CatchStmts.push_back(Catch.release());
1890 
1891       } else {
1892         Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1893           << "@catch clause";
1894         return StmtError();
1895       }
1896       catch_or_finally_seen = true;
1897     } else {
1898       assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1899       ConsumeToken(); // consume finally
1900       ParseScope FinallyScope(this, Scope::DeclScope);
1901 
1902       StmtResult FinallyBody(true);
1903       if (Tok.is(tok::l_brace))
1904         FinallyBody = ParseCompoundStatementBody();
1905       else
1906         Diag(Tok, diag::err_expected_lbrace);
1907       if (FinallyBody.isInvalid())
1908         FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1909       FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1910                                                    FinallyBody.take());
1911       catch_or_finally_seen = true;
1912       break;
1913     }
1914   }
1915   if (!catch_or_finally_seen) {
1916     Diag(atLoc, diag::err_missing_catch_finally);
1917     return StmtError();
1918   }
1919 
1920   return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1921                                     CatchStmts,
1922                                     FinallyStmt.take());
1923 }
1924 
1925 /// objc-autoreleasepool-statement:
1926 ///   @autoreleasepool compound-statement
1927 ///
1928 StmtResult
1929 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1930   ConsumeToken(); // consume autoreleasepool
1931   if (Tok.isNot(tok::l_brace)) {
1932     Diag(Tok, diag::err_expected_lbrace);
1933     return StmtError();
1934   }
1935   // Enter a scope to hold everything within the compound stmt.  Compound
1936   // statements can always hold declarations.
1937   ParseScope BodyScope(this, Scope::DeclScope);
1938 
1939   StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1940 
1941   BodyScope.Exit();
1942   if (AutoreleasePoolBody.isInvalid())
1943     AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1944   return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1945                                                 AutoreleasePoolBody.take());
1946 }
1947 
1948 /// StashAwayMethodOrFunctionBodyTokens -  Consume the tokens and store them
1949 /// for later parsing.
1950 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1951   LexedMethod* LM = new LexedMethod(this, MDecl);
1952   CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1953   CachedTokens &Toks = LM->Toks;
1954   // Begin by storing the '{' or 'try' or ':' token.
1955   Toks.push_back(Tok);
1956   if (Tok.is(tok::kw_try)) {
1957     ConsumeToken();
1958     if (Tok.is(tok::colon)) {
1959       Toks.push_back(Tok);
1960       ConsumeToken();
1961       while (Tok.isNot(tok::l_brace)) {
1962         ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1963         ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1964       }
1965     }
1966     Toks.push_back(Tok); // also store '{'
1967   }
1968   else if (Tok.is(tok::colon)) {
1969     ConsumeToken();
1970     while (Tok.isNot(tok::l_brace)) {
1971       ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1972       ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1973     }
1974     Toks.push_back(Tok); // also store '{'
1975   }
1976   ConsumeBrace();
1977   // Consume everything up to (and including) the matching right brace.
1978   ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1979   while (Tok.is(tok::kw_catch)) {
1980     ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1981     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1982   }
1983 }
1984 
1985 ///   objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1986 ///
1987 Decl *Parser::ParseObjCMethodDefinition() {
1988   Decl *MDecl = ParseObjCMethodPrototype();
1989 
1990   PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1991                                       "parsing Objective-C method");
1992 
1993   // parse optional ';'
1994   if (Tok.is(tok::semi)) {
1995     if (CurParsedObjCImpl) {
1996       Diag(Tok, diag::warn_semicolon_before_method_body)
1997         << FixItHint::CreateRemoval(Tok.getLocation());
1998     }
1999     ConsumeToken();
2000   }
2001 
2002   // We should have an opening brace now.
2003   if (Tok.isNot(tok::l_brace)) {
2004     Diag(Tok, diag::err_expected_method_body);
2005 
2006     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
2007     SkipUntil(tok::l_brace, true, true);
2008 
2009     // If we didn't find the '{', bail out.
2010     if (Tok.isNot(tok::l_brace))
2011       return 0;
2012   }
2013 
2014   if (!MDecl) {
2015     ConsumeBrace();
2016     SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
2017     return 0;
2018   }
2019 
2020   // Allow the rest of sema to find private method decl implementations.
2021   Actions.AddAnyMethodToGlobalPool(MDecl);
2022   assert (CurParsedObjCImpl
2023           && "ParseObjCMethodDefinition - Method out of @implementation");
2024   // Consume the tokens and store them for later parsing.
2025   StashAwayMethodOrFunctionBodyTokens(MDecl);
2026   return MDecl;
2027 }
2028 
2029 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2030   if (Tok.is(tok::code_completion)) {
2031     Actions.CodeCompleteObjCAtStatement(getCurScope());
2032     cutOffParsing();
2033     return StmtError();
2034   }
2035 
2036   if (Tok.isObjCAtKeyword(tok::objc_try))
2037     return ParseObjCTryStmt(AtLoc);
2038 
2039   if (Tok.isObjCAtKeyword(tok::objc_throw))
2040     return ParseObjCThrowStmt(AtLoc);
2041 
2042   if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2043     return ParseObjCSynchronizedStmt(AtLoc);
2044 
2045   if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2046     return ParseObjCAutoreleasePoolStmt(AtLoc);
2047 
2048   ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2049   if (Res.isInvalid()) {
2050     // If the expression is invalid, skip ahead to the next semicolon. Not
2051     // doing this opens us up to the possibility of infinite loops if
2052     // ParseExpression does not consume any tokens.
2053     SkipUntil(tok::semi);
2054     return StmtError();
2055   }
2056 
2057   // Otherwise, eat the semicolon.
2058   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2059   return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
2060 }
2061 
2062 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2063   switch (Tok.getKind()) {
2064   case tok::code_completion:
2065     Actions.CodeCompleteObjCAtExpression(getCurScope());
2066     cutOffParsing();
2067     return ExprError();
2068 
2069   case tok::minus:
2070   case tok::plus: {
2071     tok::TokenKind Kind = Tok.getKind();
2072     SourceLocation OpLoc = ConsumeToken();
2073 
2074     if (!Tok.is(tok::numeric_constant)) {
2075       const char *Symbol = 0;
2076       switch (Kind) {
2077       case tok::minus: Symbol = "-"; break;
2078       case tok::plus: Symbol = "+"; break;
2079       default: llvm_unreachable("missing unary operator case");
2080       }
2081       Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2082         << Symbol;
2083       return ExprError();
2084     }
2085 
2086     ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2087     if (Lit.isInvalid()) {
2088       return Lit;
2089     }
2090     ConsumeToken(); // Consume the literal token.
2091 
2092     Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
2093     if (Lit.isInvalid())
2094       return Lit;
2095 
2096     return ParsePostfixExpressionSuffix(
2097              Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2098   }
2099 
2100   case tok::string_literal:    // primary-expression: string-literal
2101   case tok::wide_string_literal:
2102     return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2103 
2104   case tok::char_constant:
2105     return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2106 
2107   case tok::numeric_constant:
2108     return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2109 
2110   case tok::kw_true:  // Objective-C++, etc.
2111   case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2112     return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2113   case tok::kw_false: // Objective-C++, etc.
2114   case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2115     return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2116 
2117   case tok::l_square:
2118     // Objective-C array literal
2119     return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2120 
2121   case tok::l_brace:
2122     // Objective-C dictionary literal
2123     return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2124 
2125   case tok::l_paren:
2126     // Objective-C boxed expression
2127     return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2128 
2129   default:
2130     if (Tok.getIdentifierInfo() == 0)
2131       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2132 
2133     switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2134     case tok::objc_encode:
2135       return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2136     case tok::objc_protocol:
2137       return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2138     case tok::objc_selector:
2139       return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2140       default: {
2141         const char *str = 0;
2142         if (GetLookAheadToken(1).is(tok::l_brace)) {
2143           char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2144           str =
2145             ch == 't' ? "try"
2146                       : (ch == 'f' ? "finally"
2147                                    : (ch == 'a' ? "autoreleasepool" : 0));
2148         }
2149         if (str) {
2150           SourceLocation kwLoc = Tok.getLocation();
2151           return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2152                              FixItHint::CreateReplacement(kwLoc, str));
2153         }
2154         else
2155           return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2156       }
2157     }
2158   }
2159 }
2160 
2161 /// \brief Parse the receiver of an Objective-C++ message send.
2162 ///
2163 /// This routine parses the receiver of a message send in
2164 /// Objective-C++ either as a type or as an expression. Note that this
2165 /// routine must not be called to parse a send to 'super', since it
2166 /// has no way to return such a result.
2167 ///
2168 /// \param IsExpr Whether the receiver was parsed as an expression.
2169 ///
2170 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2171 /// IsExpr is true), the parsed expression. If the receiver was parsed
2172 /// as a type (\c IsExpr is false), the parsed type.
2173 ///
2174 /// \returns True if an error occurred during parsing or semantic
2175 /// analysis, in which case the arguments do not have valid
2176 /// values. Otherwise, returns false for a successful parse.
2177 ///
2178 ///   objc-receiver: [C++]
2179 ///     'super' [not parsed here]
2180 ///     expression
2181 ///     simple-type-specifier
2182 ///     typename-specifier
2183 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2184   InMessageExpressionRAIIObject InMessage(*this, true);
2185 
2186   if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2187       Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2188     TryAnnotateTypeOrScopeToken();
2189 
2190   if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2191     //   objc-receiver:
2192     //     expression
2193     ExprResult Receiver = ParseExpression();
2194     if (Receiver.isInvalid())
2195       return true;
2196 
2197     IsExpr = true;
2198     TypeOrExpr = Receiver.take();
2199     return false;
2200   }
2201 
2202   // objc-receiver:
2203   //   typename-specifier
2204   //   simple-type-specifier
2205   //   expression (that starts with one of the above)
2206   DeclSpec DS(AttrFactory);
2207   ParseCXXSimpleTypeSpecifier(DS);
2208 
2209   if (Tok.is(tok::l_paren)) {
2210     // If we see an opening parentheses at this point, we are
2211     // actually parsing an expression that starts with a
2212     // function-style cast, e.g.,
2213     //
2214     //   postfix-expression:
2215     //     simple-type-specifier ( expression-list [opt] )
2216     //     typename-specifier ( expression-list [opt] )
2217     //
2218     // Parse the remainder of this case, then the (optional)
2219     // postfix-expression suffix, followed by the (optional)
2220     // right-hand side of the binary expression. We have an
2221     // instance method.
2222     ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2223     if (!Receiver.isInvalid())
2224       Receiver = ParsePostfixExpressionSuffix(Receiver.take());
2225     if (!Receiver.isInvalid())
2226       Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
2227     if (Receiver.isInvalid())
2228       return true;
2229 
2230     IsExpr = true;
2231     TypeOrExpr = Receiver.take();
2232     return false;
2233   }
2234 
2235   // We have a class message. Turn the simple-type-specifier or
2236   // typename-specifier we parsed into a type and parse the
2237   // remainder of the class message.
2238   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2239   TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2240   if (Type.isInvalid())
2241     return true;
2242 
2243   IsExpr = false;
2244   TypeOrExpr = Type.get().getAsOpaquePtr();
2245   return false;
2246 }
2247 
2248 /// \brief Determine whether the parser is currently referring to a an
2249 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2250 ///
2251 /// This routine will only return true for a subset of valid message-send
2252 /// expressions.
2253 bool Parser::isSimpleObjCMessageExpression() {
2254   assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2255          "Incorrect start for isSimpleObjCMessageExpression");
2256   return GetLookAheadToken(1).is(tok::identifier) &&
2257          GetLookAheadToken(2).is(tok::identifier);
2258 }
2259 
2260 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2261   if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2262       InMessageExpression)
2263     return false;
2264 
2265 
2266   ParsedType Type;
2267 
2268   if (Tok.is(tok::annot_typename))
2269     Type = getTypeAnnotation(Tok);
2270   else if (Tok.is(tok::identifier))
2271     Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2272                                getCurScope());
2273   else
2274     return false;
2275 
2276   if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2277     const Token &AfterNext = GetLookAheadToken(2);
2278     if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2279       if (Tok.is(tok::identifier))
2280         TryAnnotateTypeOrScopeToken();
2281 
2282       return Tok.is(tok::annot_typename);
2283     }
2284   }
2285 
2286   return false;
2287 }
2288 
2289 ///   objc-message-expr:
2290 ///     '[' objc-receiver objc-message-args ']'
2291 ///
2292 ///   objc-receiver: [C]
2293 ///     'super'
2294 ///     expression
2295 ///     class-name
2296 ///     type-name
2297 ///
2298 ExprResult Parser::ParseObjCMessageExpression() {
2299   assert(Tok.is(tok::l_square) && "'[' expected");
2300   SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2301 
2302   if (Tok.is(tok::code_completion)) {
2303     Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2304     cutOffParsing();
2305     return ExprError();
2306   }
2307 
2308   InMessageExpressionRAIIObject InMessage(*this, true);
2309 
2310   if (getLangOpts().CPlusPlus) {
2311     // We completely separate the C and C++ cases because C++ requires
2312     // more complicated (read: slower) parsing.
2313 
2314     // Handle send to super.
2315     // FIXME: This doesn't benefit from the same typo-correction we
2316     // get in Objective-C.
2317     if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2318         NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2319       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2320                                             ParsedType(), 0);
2321 
2322     // Parse the receiver, which is either a type or an expression.
2323     bool IsExpr;
2324     void *TypeOrExpr = NULL;
2325     if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2326       SkipUntil(tok::r_square);
2327       return ExprError();
2328     }
2329 
2330     if (IsExpr)
2331       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2332                                             ParsedType(),
2333                                             static_cast<Expr*>(TypeOrExpr));
2334 
2335     return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2336                               ParsedType::getFromOpaquePtr(TypeOrExpr),
2337                                           0);
2338   }
2339 
2340   if (Tok.is(tok::identifier)) {
2341     IdentifierInfo *Name = Tok.getIdentifierInfo();
2342     SourceLocation NameLoc = Tok.getLocation();
2343     ParsedType ReceiverType;
2344     switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2345                                        Name == Ident_super,
2346                                        NextToken().is(tok::period),
2347                                        ReceiverType)) {
2348     case Sema::ObjCSuperMessage:
2349       return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2350                                             ParsedType(), 0);
2351 
2352     case Sema::ObjCClassMessage:
2353       if (!ReceiverType) {
2354         SkipUntil(tok::r_square);
2355         return ExprError();
2356       }
2357 
2358       ConsumeToken(); // the type name
2359 
2360       return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2361                                             ReceiverType, 0);
2362 
2363     case Sema::ObjCInstanceMessage:
2364       // Fall through to parse an expression.
2365       break;
2366     }
2367   }
2368 
2369   // Otherwise, an arbitrary expression can be the receiver of a send.
2370   ExprResult Res(ParseExpression());
2371   if (Res.isInvalid()) {
2372     SkipUntil(tok::r_square);
2373     return Res;
2374   }
2375 
2376   return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2377                                         ParsedType(), Res.take());
2378 }
2379 
2380 /// \brief Parse the remainder of an Objective-C message following the
2381 /// '[' objc-receiver.
2382 ///
2383 /// This routine handles sends to super, class messages (sent to a
2384 /// class name), and instance messages (sent to an object), and the
2385 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2386 /// ReceiverExpr, respectively. Only one of these parameters may have
2387 /// a valid value.
2388 ///
2389 /// \param LBracLoc The location of the opening '['.
2390 ///
2391 /// \param SuperLoc If this is a send to 'super', the location of the
2392 /// 'super' keyword that indicates a send to the superclass.
2393 ///
2394 /// \param ReceiverType If this is a class message, the type of the
2395 /// class we are sending a message to.
2396 ///
2397 /// \param ReceiverExpr If this is an instance message, the expression
2398 /// used to compute the receiver object.
2399 ///
2400 ///   objc-message-args:
2401 ///     objc-selector
2402 ///     objc-keywordarg-list
2403 ///
2404 ///   objc-keywordarg-list:
2405 ///     objc-keywordarg
2406 ///     objc-keywordarg-list objc-keywordarg
2407 ///
2408 ///   objc-keywordarg:
2409 ///     selector-name[opt] ':' objc-keywordexpr
2410 ///
2411 ///   objc-keywordexpr:
2412 ///     nonempty-expr-list
2413 ///
2414 ///   nonempty-expr-list:
2415 ///     assignment-expression
2416 ///     nonempty-expr-list , assignment-expression
2417 ///
2418 ExprResult
2419 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2420                                        SourceLocation SuperLoc,
2421                                        ParsedType ReceiverType,
2422                                        ExprArg ReceiverExpr) {
2423   InMessageExpressionRAIIObject InMessage(*this, true);
2424 
2425   if (Tok.is(tok::code_completion)) {
2426     if (SuperLoc.isValid())
2427       Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2428                                            false);
2429     else if (ReceiverType)
2430       Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2431                                            false);
2432     else
2433       Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2434                                               0, 0, false);
2435     cutOffParsing();
2436     return ExprError();
2437   }
2438 
2439   // Parse objc-selector
2440   SourceLocation Loc;
2441   IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2442 
2443   SmallVector<IdentifierInfo *, 12> KeyIdents;
2444   SmallVector<SourceLocation, 12> KeyLocs;
2445   ExprVector KeyExprs;
2446 
2447   if (Tok.is(tok::colon)) {
2448     while (1) {
2449       // Each iteration parses a single keyword argument.
2450       KeyIdents.push_back(selIdent);
2451       KeyLocs.push_back(Loc);
2452 
2453       if (Tok.isNot(tok::colon)) {
2454         Diag(Tok, diag::err_expected_colon);
2455         // We must manually skip to a ']', otherwise the expression skipper will
2456         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2457         // the enclosing expression.
2458         SkipUntil(tok::r_square);
2459         return ExprError();
2460       }
2461 
2462       ConsumeToken(); // Eat the ':'.
2463       ///  Parse the expression after ':'
2464 
2465       if (Tok.is(tok::code_completion)) {
2466         if (SuperLoc.isValid())
2467           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2468                                                KeyIdents.data(),
2469                                                KeyIdents.size(),
2470                                                /*AtArgumentEpression=*/true);
2471         else if (ReceiverType)
2472           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2473                                                KeyIdents.data(),
2474                                                KeyIdents.size(),
2475                                                /*AtArgumentEpression=*/true);
2476         else
2477           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2478                                                   KeyIdents.data(),
2479                                                   KeyIdents.size(),
2480                                                   /*AtArgumentEpression=*/true);
2481 
2482         cutOffParsing();
2483         return ExprError();
2484       }
2485 
2486       ExprResult Res(ParseAssignmentExpression());
2487       if (Res.isInvalid()) {
2488         // We must manually skip to a ']', otherwise the expression skipper will
2489         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2490         // the enclosing expression.
2491         SkipUntil(tok::r_square);
2492         return Res;
2493       }
2494 
2495       // We have a valid expression.
2496       KeyExprs.push_back(Res.release());
2497 
2498       // Code completion after each argument.
2499       if (Tok.is(tok::code_completion)) {
2500         if (SuperLoc.isValid())
2501           Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2502                                                KeyIdents.data(),
2503                                                KeyIdents.size(),
2504                                                /*AtArgumentEpression=*/false);
2505         else if (ReceiverType)
2506           Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2507                                                KeyIdents.data(),
2508                                                KeyIdents.size(),
2509                                                /*AtArgumentEpression=*/false);
2510         else
2511           Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2512                                                   KeyIdents.data(),
2513                                                   KeyIdents.size(),
2514                                                 /*AtArgumentEpression=*/false);
2515         cutOffParsing();
2516         return ExprError();
2517       }
2518 
2519       // Check for another keyword selector.
2520       selIdent = ParseObjCSelectorPiece(Loc);
2521       if (!selIdent && Tok.isNot(tok::colon))
2522         break;
2523       // We have a selector or a colon, continue parsing.
2524     }
2525     // Parse the, optional, argument list, comma separated.
2526     while (Tok.is(tok::comma)) {
2527       SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2528       ///  Parse the expression after ','
2529       ExprResult Res(ParseAssignmentExpression());
2530       if (Res.isInvalid()) {
2531         if (Tok.is(tok::colon)) {
2532           Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2533             FixItHint::CreateRemoval(commaLoc);
2534         }
2535         // We must manually skip to a ']', otherwise the expression skipper will
2536         // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2537         // the enclosing expression.
2538         SkipUntil(tok::r_square);
2539         return Res;
2540       }
2541 
2542       // We have a valid expression.
2543       KeyExprs.push_back(Res.release());
2544     }
2545   } else if (!selIdent) {
2546     Diag(Tok, diag::err_expected_ident); // missing selector name.
2547 
2548     // We must manually skip to a ']', otherwise the expression skipper will
2549     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2550     // the enclosing expression.
2551     SkipUntil(tok::r_square);
2552     return ExprError();
2553   }
2554 
2555   if (Tok.isNot(tok::r_square)) {
2556     if (Tok.is(tok::identifier))
2557       Diag(Tok, diag::err_expected_colon);
2558     else
2559       Diag(Tok, diag::err_expected_rsquare);
2560     // We must manually skip to a ']', otherwise the expression skipper will
2561     // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2562     // the enclosing expression.
2563     SkipUntil(tok::r_square);
2564     return ExprError();
2565   }
2566 
2567   SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2568 
2569   unsigned nKeys = KeyIdents.size();
2570   if (nKeys == 0) {
2571     KeyIdents.push_back(selIdent);
2572     KeyLocs.push_back(Loc);
2573   }
2574   Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2575 
2576   if (SuperLoc.isValid())
2577     return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2578                                      LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2579   else if (ReceiverType)
2580     return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2581                                      LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2582   return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2583                                       LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2584 }
2585 
2586 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2587   ExprResult Res(ParseStringLiteralExpression());
2588   if (Res.isInvalid()) return Res;
2589 
2590   // @"foo" @"bar" is a valid concatenated string.  Eat any subsequent string
2591   // expressions.  At this point, we know that the only valid thing that starts
2592   // with '@' is an @"".
2593   SmallVector<SourceLocation, 4> AtLocs;
2594   ExprVector AtStrings;
2595   AtLocs.push_back(AtLoc);
2596   AtStrings.push_back(Res.release());
2597 
2598   while (Tok.is(tok::at)) {
2599     AtLocs.push_back(ConsumeToken()); // eat the @.
2600 
2601     // Invalid unless there is a string literal.
2602     if (!isTokenStringLiteral())
2603       return ExprError(Diag(Tok, diag::err_objc_concat_string));
2604 
2605     ExprResult Lit(ParseStringLiteralExpression());
2606     if (Lit.isInvalid())
2607       return Lit;
2608 
2609     AtStrings.push_back(Lit.release());
2610   }
2611 
2612   return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(),
2613                                               AtStrings.size()));
2614 }
2615 
2616 /// ParseObjCBooleanLiteral -
2617 /// objc-scalar-literal : '@' boolean-keyword
2618 ///                        ;
2619 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2620 ///                        ;
2621 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2622                                            bool ArgValue) {
2623   SourceLocation EndLoc = ConsumeToken();             // consume the keyword.
2624   return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2625 }
2626 
2627 /// ParseObjCCharacterLiteral -
2628 /// objc-scalar-literal : '@' character-literal
2629 ///                        ;
2630 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2631   ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2632   if (Lit.isInvalid()) {
2633     return Lit;
2634   }
2635   ConsumeToken(); // Consume the literal token.
2636   return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2637 }
2638 
2639 /// ParseObjCNumericLiteral -
2640 /// objc-scalar-literal : '@' scalar-literal
2641 ///                        ;
2642 /// scalar-literal : | numeric-constant			/* any numeric constant. */
2643 ///                    ;
2644 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2645   ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2646   if (Lit.isInvalid()) {
2647     return Lit;
2648   }
2649   ConsumeToken(); // Consume the literal token.
2650   return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2651 }
2652 
2653 /// ParseObjCBoxedExpr -
2654 /// objc-box-expression:
2655 ///       @( assignment-expression )
2656 ExprResult
2657 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2658   if (Tok.isNot(tok::l_paren))
2659     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2660 
2661   BalancedDelimiterTracker T(*this, tok::l_paren);
2662   T.consumeOpen();
2663   ExprResult ValueExpr(ParseAssignmentExpression());
2664   if (T.consumeClose())
2665     return ExprError();
2666 
2667   if (ValueExpr.isInvalid())
2668     return ExprError();
2669 
2670   // Wrap the sub-expression in a parenthesized expression, to distinguish
2671   // a boxed expression from a literal.
2672   SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2673   ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take());
2674   return Owned(Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2675                                           ValueExpr.take()));
2676 }
2677 
2678 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2679   ExprVector ElementExprs;                   // array elements.
2680   ConsumeBracket(); // consume the l_square.
2681 
2682   while (Tok.isNot(tok::r_square)) {
2683     // Parse list of array element expressions (all must be id types).
2684     ExprResult Res(ParseAssignmentExpression());
2685     if (Res.isInvalid()) {
2686       // We must manually skip to a ']', otherwise the expression skipper will
2687       // stop at the ']' when it skips to the ';'.  We want it to skip beyond
2688       // the enclosing expression.
2689       SkipUntil(tok::r_square);
2690       return Res;
2691     }
2692 
2693     // Parse the ellipsis that indicates a pack expansion.
2694     if (Tok.is(tok::ellipsis))
2695       Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2696     if (Res.isInvalid())
2697       return true;
2698 
2699     ElementExprs.push_back(Res.release());
2700 
2701     if (Tok.is(tok::comma))
2702       ConsumeToken(); // Eat the ','.
2703     else if (Tok.isNot(tok::r_square))
2704      return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
2705   }
2706   SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2707   MultiExprArg Args(ElementExprs);
2708   return Owned(Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args));
2709 }
2710 
2711 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2712   SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2713   ConsumeBrace(); // consume the l_square.
2714   while (Tok.isNot(tok::r_brace)) {
2715     // Parse the comma separated key : value expressions.
2716     ExprResult KeyExpr;
2717     {
2718       ColonProtectionRAIIObject X(*this);
2719       KeyExpr = ParseAssignmentExpression();
2720       if (KeyExpr.isInvalid()) {
2721         // We must manually skip to a '}', otherwise the expression skipper will
2722         // stop at the '}' when it skips to the ';'.  We want it to skip beyond
2723         // the enclosing expression.
2724         SkipUntil(tok::r_brace);
2725         return KeyExpr;
2726       }
2727     }
2728 
2729     if (Tok.is(tok::colon)) {
2730       ConsumeToken();
2731     } else {
2732       return ExprError(Diag(Tok, diag::err_expected_colon));
2733     }
2734 
2735     ExprResult ValueExpr(ParseAssignmentExpression());
2736     if (ValueExpr.isInvalid()) {
2737       // We must manually skip to a '}', otherwise the expression skipper will
2738       // stop at the '}' when it skips to the ';'.  We want it to skip beyond
2739       // the enclosing expression.
2740       SkipUntil(tok::r_brace);
2741       return ValueExpr;
2742     }
2743 
2744     // Parse the ellipsis that designates this as a pack expansion.
2745     SourceLocation EllipsisLoc;
2746     if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
2747       EllipsisLoc = ConsumeToken();
2748 
2749     // We have a valid expression. Collect it in a vector so we can
2750     // build the argument list.
2751     ObjCDictionaryElement Element = {
2752       KeyExpr.get(), ValueExpr.get(), EllipsisLoc, llvm::Optional<unsigned>()
2753     };
2754     Elements.push_back(Element);
2755 
2756     if (Tok.is(tok::comma))
2757       ConsumeToken(); // Eat the ','.
2758     else if (Tok.isNot(tok::r_brace))
2759       return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
2760   }
2761   SourceLocation EndLoc = ConsumeBrace();
2762 
2763   // Create the ObjCDictionaryLiteral.
2764   return Owned(Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2765                                                   Elements.data(),
2766                                                   Elements.size()));
2767 }
2768 
2769 ///    objc-encode-expression:
2770 ///      \@encode ( type-name )
2771 ExprResult
2772 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2773   assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2774 
2775   SourceLocation EncLoc = ConsumeToken();
2776 
2777   if (Tok.isNot(tok::l_paren))
2778     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2779 
2780   BalancedDelimiterTracker T(*this, tok::l_paren);
2781   T.consumeOpen();
2782 
2783   TypeResult Ty = ParseTypeName();
2784 
2785   T.consumeClose();
2786 
2787   if (Ty.isInvalid())
2788     return ExprError();
2789 
2790   return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc,
2791                                                  T.getOpenLocation(), Ty.get(),
2792                                                  T.getCloseLocation()));
2793 }
2794 
2795 ///     objc-protocol-expression
2796 ///       \@protocol ( protocol-name )
2797 ExprResult
2798 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2799   SourceLocation ProtoLoc = ConsumeToken();
2800 
2801   if (Tok.isNot(tok::l_paren))
2802     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2803 
2804   BalancedDelimiterTracker T(*this, tok::l_paren);
2805   T.consumeOpen();
2806 
2807   if (Tok.isNot(tok::identifier))
2808     return ExprError(Diag(Tok, diag::err_expected_ident));
2809 
2810   IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2811   SourceLocation ProtoIdLoc = ConsumeToken();
2812 
2813   T.consumeClose();
2814 
2815   return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2816                                                    T.getOpenLocation(),
2817                                                    ProtoIdLoc,
2818                                                    T.getCloseLocation()));
2819 }
2820 
2821 ///     objc-selector-expression
2822 ///       @selector '(' objc-keyword-selector ')'
2823 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2824   SourceLocation SelectorLoc = ConsumeToken();
2825 
2826   if (Tok.isNot(tok::l_paren))
2827     return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2828 
2829   SmallVector<IdentifierInfo *, 12> KeyIdents;
2830   SourceLocation sLoc;
2831 
2832   BalancedDelimiterTracker T(*this, tok::l_paren);
2833   T.consumeOpen();
2834 
2835   if (Tok.is(tok::code_completion)) {
2836     Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2837                                      KeyIdents.size());
2838     cutOffParsing();
2839     return ExprError();
2840   }
2841 
2842   IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2843   if (!SelIdent &&  // missing selector name.
2844       Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2845     return ExprError(Diag(Tok, diag::err_expected_ident));
2846 
2847   KeyIdents.push_back(SelIdent);
2848   unsigned nColons = 0;
2849   if (Tok.isNot(tok::r_paren)) {
2850     while (1) {
2851       if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2852         ++nColons;
2853         KeyIdents.push_back(0);
2854       } else if (Tok.isNot(tok::colon))
2855         return ExprError(Diag(Tok, diag::err_expected_colon));
2856 
2857       ++nColons;
2858       ConsumeToken(); // Eat the ':' or '::'.
2859       if (Tok.is(tok::r_paren))
2860         break;
2861 
2862       if (Tok.is(tok::code_completion)) {
2863         Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2864                                          KeyIdents.size());
2865         cutOffParsing();
2866         return ExprError();
2867       }
2868 
2869       // Check for another keyword selector.
2870       SourceLocation Loc;
2871       SelIdent = ParseObjCSelectorPiece(Loc);
2872       KeyIdents.push_back(SelIdent);
2873       if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2874         break;
2875     }
2876   }
2877   T.consumeClose();
2878   Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2879   return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2880                                                    T.getOpenLocation(),
2881                                                    T.getCloseLocation()));
2882  }
2883 
2884 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2885   // MCDecl might be null due to error in method or c-function  prototype, etc.
2886   Decl *MCDecl = LM.D;
2887   bool skip = MCDecl &&
2888               ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2889               (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2890   if (skip)
2891     return;
2892 
2893   // Save the current token position.
2894   SourceLocation OrigLoc = Tok.getLocation();
2895 
2896   assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2897   // Append the current token at the end of the new token stream so that it
2898   // doesn't get lost.
2899   LM.Toks.push_back(Tok);
2900   PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2901 
2902   // Consume the previously pushed token.
2903   ConsumeAnyToken();
2904 
2905   assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2906           Tok.is(tok::colon)) &&
2907           "Inline objective-c method not starting with '{' or 'try' or ':'");
2908   // Enter a scope for the method or c-fucntion body.
2909   ParseScope BodyScope(this,
2910                        parseMethod
2911                        ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2912                        : Scope::FnScope|Scope::DeclScope);
2913 
2914   // Tell the actions module that we have entered a method or c-function definition
2915   // with the specified Declarator for the method/function.
2916   if (parseMethod)
2917     Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2918   else
2919     Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2920   if (Tok.is(tok::kw_try))
2921     MCDecl = ParseFunctionTryBlock(MCDecl, BodyScope);
2922   else {
2923     if (Tok.is(tok::colon))
2924       ParseConstructorInitializer(MCDecl);
2925     MCDecl = ParseFunctionStatementBody(MCDecl, BodyScope);
2926   }
2927 
2928   if (Tok.getLocation() != OrigLoc) {
2929     // Due to parsing error, we either went over the cached tokens or
2930     // there are still cached tokens left. If it's the latter case skip the
2931     // leftover tokens.
2932     // Since this is an uncommon situation that should be avoided, use the
2933     // expensive isBeforeInTranslationUnit call.
2934     if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2935                                                      OrigLoc))
2936       while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
2937         ConsumeAnyToken();
2938   }
2939 
2940   return;
2941 }
2942