]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/Parse/Parser.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / clang / lib / Parse / Parser.cpp
1 //===--- Parser.cpp - C Language Family Parser ----------------------------===//
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 Parser interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Parse/Parser.h"
15 #include "ParsePragma.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
25
26
27 namespace {
28 /// \brief A comment handler that passes comments found by the preprocessor
29 /// to the parser action.
30 class ActionCommentHandler : public CommentHandler {
31   Sema &S;
32
33 public:
34   explicit ActionCommentHandler(Sema &S) : S(S) { }
35
36   virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
37     S.ActOnComment(Comment);
38     return false;
39   }
40 };
41 } // end anonymous namespace
42
43 IdentifierInfo *Parser::getSEHExceptKeyword() {
44   // __except is accepted as a (contextual) keyword 
45   if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
46     Ident__except = PP.getIdentifierInfo("__except");
47
48   return Ident__except;
49 }
50
51 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52   : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
53     GreaterThanIsOperator(true), ColonIsSacred(false), 
54     InMessageExpression(false), TemplateParameterDepth(0),
55     ParsingInObjCContainer(false) {
56   SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
57   Tok.startToken();
58   Tok.setKind(tok::eof);
59   Actions.CurScope = 0;
60   NumCachedScopes = 0;
61   ParenCount = BracketCount = BraceCount = 0;
62   CurParsedObjCImpl = 0;
63
64   // Add #pragma handlers. These are removed and destroyed in the
65   // destructor.
66   AlignHandler.reset(new PragmaAlignHandler());
67   PP.AddPragmaHandler(AlignHandler.get());
68
69   GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
70   PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
71
72   OptionsHandler.reset(new PragmaOptionsHandler());
73   PP.AddPragmaHandler(OptionsHandler.get());
74
75   PackHandler.reset(new PragmaPackHandler());
76   PP.AddPragmaHandler(PackHandler.get());
77     
78   MSStructHandler.reset(new PragmaMSStructHandler());
79   PP.AddPragmaHandler(MSStructHandler.get());
80
81   UnusedHandler.reset(new PragmaUnusedHandler());
82   PP.AddPragmaHandler(UnusedHandler.get());
83
84   WeakHandler.reset(new PragmaWeakHandler());
85   PP.AddPragmaHandler(WeakHandler.get());
86
87   RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
88   PP.AddPragmaHandler(RedefineExtnameHandler.get());
89
90   FPContractHandler.reset(new PragmaFPContractHandler());
91   PP.AddPragmaHandler("STDC", FPContractHandler.get());
92
93   if (getLangOpts().OpenCL) {
94     OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
95     PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
96
97     PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
98   }
99   if (getLangOpts().OpenMP)
100     OpenMPHandler.reset(new PragmaOpenMPHandler());
101   else
102     OpenMPHandler.reset(new PragmaNoOpenMPHandler());
103   PP.AddPragmaHandler(OpenMPHandler.get());
104
105   if (getLangOpts().MicrosoftExt) {
106     MSCommentHandler.reset(new PragmaCommentHandler());
107     PP.AddPragmaHandler(MSCommentHandler.get());
108   }
109
110   CommentSemaHandler.reset(new ActionCommentHandler(actions));
111   PP.addCommentHandler(CommentSemaHandler.get());
112
113   PP.setCodeCompletionHandler(*this);
114 }
115
116 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
117   return Diags.Report(Loc, DiagID);
118 }
119
120 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
121   return Diag(Tok.getLocation(), DiagID);
122 }
123
124 /// \brief Emits a diagnostic suggesting parentheses surrounding a
125 /// given range.
126 ///
127 /// \param Loc The location where we'll emit the diagnostic.
128 /// \param DK The kind of diagnostic to emit.
129 /// \param ParenRange Source range enclosing code that should be parenthesized.
130 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
131                                 SourceRange ParenRange) {
132   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
133   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
134     // We can't display the parentheses, so just dig the
135     // warning/error and return.
136     Diag(Loc, DK);
137     return;
138   }
139
140   Diag(Loc, DK)
141     << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
142     << FixItHint::CreateInsertion(EndLoc, ")");
143 }
144
145 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
146   switch (ExpectedTok) {
147   case tok::semi:
148     return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
149   default: return false;
150   }
151 }
152
153 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
154 /// input.  If so, it is consumed and false is returned.
155 ///
156 /// If the input is malformed, this emits the specified diagnostic.  Next, if
157 /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
158 /// returned.
159 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
160                               const char *Msg, tok::TokenKind SkipToTok) {
161   if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
162     ConsumeAnyToken();
163     return false;
164   }
165
166   // Detect common single-character typos and resume.
167   if (IsCommonTypo(ExpectedTok, Tok)) {
168     SourceLocation Loc = Tok.getLocation();
169     Diag(Loc, DiagID)
170       << Msg
171       << FixItHint::CreateReplacement(SourceRange(Loc),
172                                       getTokenSimpleSpelling(ExpectedTok));
173     ConsumeAnyToken();
174
175     // Pretend there wasn't a problem.
176     return false;
177   }
178
179   const char *Spelling = 0;
180   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
181   if (EndLoc.isValid() &&
182       (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
183     // Show what code to insert to fix this problem.
184     Diag(EndLoc, DiagID)
185       << Msg
186       << FixItHint::CreateInsertion(EndLoc, Spelling);
187   } else
188     Diag(Tok, DiagID) << Msg;
189
190   if (SkipToTok != tok::unknown)
191     SkipUntil(SkipToTok);
192   return true;
193 }
194
195 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
196   if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
197     ConsumeToken();
198     return false;
199   }
200   
201   if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && 
202       NextToken().is(tok::semi)) {
203     Diag(Tok, diag::err_extraneous_token_before_semi)
204       << PP.getSpelling(Tok)
205       << FixItHint::CreateRemoval(Tok.getLocation());
206     ConsumeAnyToken(); // The ')' or ']'.
207     ConsumeToken(); // The ';'.
208     return false;
209   }
210   
211   return ExpectAndConsume(tok::semi, DiagID);
212 }
213
214 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
215   if (!Tok.is(tok::semi)) return;
216
217   bool HadMultipleSemis = false;
218   SourceLocation StartLoc = Tok.getLocation();
219   SourceLocation EndLoc = Tok.getLocation();
220   ConsumeToken();
221
222   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
223     HadMultipleSemis = true;
224     EndLoc = Tok.getLocation();
225     ConsumeToken();
226   }
227
228   // C++11 allows extra semicolons at namespace scope, but not in any of the
229   // other contexts.
230   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
231     if (getLangOpts().CPlusPlus11)
232       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
233           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
234     else
235       Diag(StartLoc, diag::ext_extra_semi_cxx11)
236           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
237     return;
238   }
239
240   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
241     Diag(StartLoc, diag::ext_extra_semi)
242         << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
243         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
244   else
245     // A single semicolon is valid after a member function definition.
246     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
247       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
248 }
249
250 //===----------------------------------------------------------------------===//
251 // Error recovery.
252 //===----------------------------------------------------------------------===//
253
254 /// SkipUntil - Read tokens until we get to the specified token, then consume
255 /// it (unless DontConsume is true).  Because we cannot guarantee that the
256 /// token will ever occur, this skips to the next token, or to some likely
257 /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
258 /// character.
259 ///
260 /// If SkipUntil finds the specified token, it returns true, otherwise it
261 /// returns false.
262 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
263                        bool DontConsume, bool StopAtCodeCompletion) {
264   // We always want this function to skip at least one token if the first token
265   // isn't T and if not at EOF.
266   bool isFirstTokenSkipped = true;
267   while (1) {
268     // If we found one of the tokens, stop and return true.
269     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
270       if (Tok.is(Toks[i])) {
271         if (DontConsume) {
272           // Noop, don't consume the token.
273         } else {
274           ConsumeAnyToken();
275         }
276         return true;
277       }
278     }
279
280     switch (Tok.getKind()) {
281     case tok::eof:
282       // Ran out of tokens.
283       return false;
284         
285     case tok::code_completion:
286       if (!StopAtCodeCompletion)
287         ConsumeToken();
288       return false;
289         
290     case tok::l_paren:
291       // Recursively skip properly-nested parens.
292       ConsumeParen();
293       SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
294       break;
295     case tok::l_square:
296       // Recursively skip properly-nested square brackets.
297       ConsumeBracket();
298       SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
299       break;
300     case tok::l_brace:
301       // Recursively skip properly-nested braces.
302       ConsumeBrace();
303       SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
304       break;
305
306     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
307     // Since the user wasn't looking for this token (if they were, it would
308     // already be handled), this isn't balanced.  If there is a LHS token at a
309     // higher level, we will assume that this matches the unbalanced token
310     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
311     case tok::r_paren:
312       if (ParenCount && !isFirstTokenSkipped)
313         return false;  // Matches something.
314       ConsumeParen();
315       break;
316     case tok::r_square:
317       if (BracketCount && !isFirstTokenSkipped)
318         return false;  // Matches something.
319       ConsumeBracket();
320       break;
321     case tok::r_brace:
322       if (BraceCount && !isFirstTokenSkipped)
323         return false;  // Matches something.
324       ConsumeBrace();
325       break;
326
327     case tok::string_literal:
328     case tok::wide_string_literal:
329     case tok::utf8_string_literal:
330     case tok::utf16_string_literal:
331     case tok::utf32_string_literal:
332       ConsumeStringToken();
333       break;
334         
335     case tok::semi:
336       if (StopAtSemi)
337         return false;
338       // FALL THROUGH.
339     default:
340       // Skip this token.
341       ConsumeToken();
342       break;
343     }
344     isFirstTokenSkipped = false;
345   }
346 }
347
348 //===----------------------------------------------------------------------===//
349 // Scope manipulation
350 //===----------------------------------------------------------------------===//
351
352 /// EnterScope - Start a new scope.
353 void Parser::EnterScope(unsigned ScopeFlags) {
354   if (NumCachedScopes) {
355     Scope *N = ScopeCache[--NumCachedScopes];
356     N->Init(getCurScope(), ScopeFlags);
357     Actions.CurScope = N;
358   } else {
359     Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
360   }
361 }
362
363 /// ExitScope - Pop a scope off the scope stack.
364 void Parser::ExitScope() {
365   assert(getCurScope() && "Scope imbalance!");
366
367   // Inform the actions module that this scope is going away if there are any
368   // decls in it.
369   if (!getCurScope()->decl_empty())
370     Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
371
372   Scope *OldScope = getCurScope();
373   Actions.CurScope = OldScope->getParent();
374
375   if (NumCachedScopes == ScopeCacheSize)
376     delete OldScope;
377   else
378     ScopeCache[NumCachedScopes++] = OldScope;
379 }
380
381 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
382 /// this object does nothing.
383 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
384                                  bool ManageFlags)
385   : CurScope(ManageFlags ? Self->getCurScope() : 0) {
386   if (CurScope) {
387     OldFlags = CurScope->getFlags();
388     CurScope->setFlags(ScopeFlags);
389   }
390 }
391
392 /// Restore the flags for the current scope to what they were before this
393 /// object overrode them.
394 Parser::ParseScopeFlags::~ParseScopeFlags() {
395   if (CurScope)
396     CurScope->setFlags(OldFlags);
397 }
398
399
400 //===----------------------------------------------------------------------===//
401 // C99 6.9: External Definitions.
402 //===----------------------------------------------------------------------===//
403
404 Parser::~Parser() {
405   // If we still have scopes active, delete the scope tree.
406   delete getCurScope();
407   Actions.CurScope = 0;
408   
409   // Free the scope cache.
410   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
411     delete ScopeCache[i];
412
413   // Free LateParsedTemplatedFunction nodes.
414   for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
415       it != LateParsedTemplateMap.end(); ++it)
416     delete it->second;
417
418   // Remove the pragma handlers we installed.
419   PP.RemovePragmaHandler(AlignHandler.get());
420   AlignHandler.reset();
421   PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
422   GCCVisibilityHandler.reset();
423   PP.RemovePragmaHandler(OptionsHandler.get());
424   OptionsHandler.reset();
425   PP.RemovePragmaHandler(PackHandler.get());
426   PackHandler.reset();
427   PP.RemovePragmaHandler(MSStructHandler.get());
428   MSStructHandler.reset();
429   PP.RemovePragmaHandler(UnusedHandler.get());
430   UnusedHandler.reset();
431   PP.RemovePragmaHandler(WeakHandler.get());
432   WeakHandler.reset();
433   PP.RemovePragmaHandler(RedefineExtnameHandler.get());
434   RedefineExtnameHandler.reset();
435
436   if (getLangOpts().OpenCL) {
437     PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
438     OpenCLExtensionHandler.reset();
439     PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
440   }
441   PP.RemovePragmaHandler(OpenMPHandler.get());
442   OpenMPHandler.reset();
443
444   if (getLangOpts().MicrosoftExt) {
445     PP.RemovePragmaHandler(MSCommentHandler.get());
446     MSCommentHandler.reset();
447   }
448
449   PP.RemovePragmaHandler("STDC", FPContractHandler.get());
450   FPContractHandler.reset();
451
452   PP.removeCommentHandler(CommentSemaHandler.get());
453
454   PP.clearCodeCompletionHandler();
455
456   assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
457 }
458
459 /// Initialize - Warm up the parser.
460 ///
461 void Parser::Initialize() {
462   // Create the translation unit scope.  Install it as the current scope.
463   assert(getCurScope() == 0 && "A scope is already active?");
464   EnterScope(Scope::DeclScope);
465   Actions.ActOnTranslationUnitScope(getCurScope());
466
467   // Initialization for Objective-C context sensitive keywords recognition.
468   // Referenced in Parser::ParseObjCTypeQualifierList.
469   if (getLangOpts().ObjC1) {
470     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
471     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
472     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
473     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
474     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
475     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
476   }
477
478   Ident_instancetype = 0;
479   Ident_final = 0;
480   Ident_override = 0;
481
482   Ident_super = &PP.getIdentifierTable().get("super");
483
484   if (getLangOpts().AltiVec) {
485     Ident_vector = &PP.getIdentifierTable().get("vector");
486     Ident_pixel = &PP.getIdentifierTable().get("pixel");
487   }
488
489   Ident_introduced = 0;
490   Ident_deprecated = 0;
491   Ident_obsoleted = 0;
492   Ident_unavailable = 0;
493
494   Ident__except = 0;
495   
496   Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
497   Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
498   Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
499
500   if(getLangOpts().Borland) {
501     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
502     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
503     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
504     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
505     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
506     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
507     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
508     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
509     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
510
511     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
512     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
513     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
514     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
515     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
516     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
517     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
518     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
519     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
520   }
521
522   Actions.Initialize();
523
524   // Prime the lexer look-ahead.
525   ConsumeToken();
526 }
527
528 namespace {
529   /// \brief RAIIObject to destroy the contents of a SmallVector of
530   /// TemplateIdAnnotation pointers and clear the vector.
531   class DestroyTemplateIdAnnotationsRAIIObj {
532     SmallVectorImpl<TemplateIdAnnotation *> &Container;
533   public:
534     DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
535                                        &Container)
536       : Container(Container) {}
537
538     ~DestroyTemplateIdAnnotationsRAIIObj() {
539       for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
540            Container.begin(), E = Container.end();
541            I != E; ++I)
542         (*I)->Destroy();
543       Container.clear();
544     }
545   };
546 }
547
548 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
549 /// action tells us to.  This returns true if the EOF was encountered.
550 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
551   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
552
553   // Skip over the EOF token, flagging end of previous input for incremental 
554   // processing
555   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
556     ConsumeToken();
557
558   while (Tok.is(tok::annot_pragma_unused))
559     HandlePragmaUnused();
560
561   Result = DeclGroupPtrTy();
562   if (Tok.is(tok::eof)) {
563     // Late template parsing can begin.
564     if (getLangOpts().DelayedTemplateParsing)
565       Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
566     if (!PP.isIncrementalProcessingEnabled())
567       Actions.ActOnEndOfTranslationUnit();
568     //else don't tell Sema that we ended parsing: more input might come.
569
570     return true;
571   }
572
573   ParsedAttributesWithRange attrs(AttrFactory);
574   MaybeParseCXX11Attributes(attrs);
575   MaybeParseMicrosoftAttributes(attrs);
576
577   Result = ParseExternalDeclaration(attrs);
578   return false;
579 }
580
581 /// ParseExternalDeclaration:
582 ///
583 ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
584 ///         function-definition
585 ///         declaration
586 /// [GNU]   asm-definition
587 /// [GNU]   __extension__ external-declaration
588 /// [OBJC]  objc-class-definition
589 /// [OBJC]  objc-class-declaration
590 /// [OBJC]  objc-alias-declaration
591 /// [OBJC]  objc-protocol-definition
592 /// [OBJC]  objc-method-definition
593 /// [OBJC]  @end
594 /// [C++]   linkage-specification
595 /// [GNU] asm-definition:
596 ///         simple-asm-expr ';'
597 /// [C++11] empty-declaration
598 /// [C++11] attribute-declaration
599 ///
600 /// [C++11] empty-declaration:
601 ///           ';'
602 ///
603 /// [C++0x/GNU] 'extern' 'template' declaration
604 Parser::DeclGroupPtrTy
605 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
606                                  ParsingDeclSpec *DS) {
607   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
608   ParenBraceBracketBalancer BalancerRAIIObj(*this);
609
610   if (PP.isCodeCompletionReached()) {
611     cutOffParsing();
612     return DeclGroupPtrTy();
613   }
614
615   Decl *SingleDecl = 0;
616   switch (Tok.getKind()) {
617   case tok::annot_pragma_vis:
618     HandlePragmaVisibility();
619     return DeclGroupPtrTy();
620   case tok::annot_pragma_pack:
621     HandlePragmaPack();
622     return DeclGroupPtrTy();
623   case tok::annot_pragma_msstruct:
624     HandlePragmaMSStruct();
625     return DeclGroupPtrTy();
626   case tok::annot_pragma_align:
627     HandlePragmaAlign();
628     return DeclGroupPtrTy();
629   case tok::annot_pragma_weak:
630     HandlePragmaWeak();
631     return DeclGroupPtrTy();
632   case tok::annot_pragma_weakalias:
633     HandlePragmaWeakAlias();
634     return DeclGroupPtrTy();
635   case tok::annot_pragma_redefine_extname:
636     HandlePragmaRedefineExtname();
637     return DeclGroupPtrTy();
638   case tok::annot_pragma_fp_contract:
639     HandlePragmaFPContract();
640     return DeclGroupPtrTy();
641   case tok::annot_pragma_opencl_extension:
642     HandlePragmaOpenCLExtension();
643     return DeclGroupPtrTy();
644   case tok::annot_pragma_openmp:
645     ParseOpenMPDeclarativeDirective();
646     return DeclGroupPtrTy();
647   case tok::semi:
648     // Either a C++11 empty-declaration or attribute-declaration.
649     SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
650                                                attrs.getList(),
651                                                Tok.getLocation());
652     ConsumeExtraSemi(OutsideFunction);
653     break;
654   case tok::r_brace:
655     Diag(Tok, diag::err_extraneous_closing_brace);
656     ConsumeBrace();
657     return DeclGroupPtrTy();
658   case tok::eof:
659     Diag(Tok, diag::err_expected_external_declaration);
660     return DeclGroupPtrTy();
661   case tok::kw___extension__: {
662     // __extension__ silences extension warnings in the subexpression.
663     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
664     ConsumeToken();
665     return ParseExternalDeclaration(attrs);
666   }
667   case tok::kw_asm: {
668     ProhibitAttributes(attrs);
669
670     SourceLocation StartLoc = Tok.getLocation();
671     SourceLocation EndLoc;
672     ExprResult Result(ParseSimpleAsm(&EndLoc));
673
674     ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
675                      "top-level asm block");
676
677     if (Result.isInvalid())
678       return DeclGroupPtrTy();
679     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
680     break;
681   }
682   case tok::at:
683     return ParseObjCAtDirectives();
684   case tok::minus:
685   case tok::plus:
686     if (!getLangOpts().ObjC1) {
687       Diag(Tok, diag::err_expected_external_declaration);
688       ConsumeToken();
689       return DeclGroupPtrTy();
690     }
691     SingleDecl = ParseObjCMethodDefinition();
692     break;
693   case tok::code_completion:
694       Actions.CodeCompleteOrdinaryName(getCurScope(), 
695                              CurParsedObjCImpl? Sema::PCC_ObjCImplementation
696                                               : Sema::PCC_Namespace);
697     cutOffParsing();
698     return DeclGroupPtrTy();
699   case tok::kw_using:
700   case tok::kw_namespace:
701   case tok::kw_typedef:
702   case tok::kw_template:
703   case tok::kw_export:    // As in 'export template'
704   case tok::kw_static_assert:
705   case tok::kw__Static_assert:
706     // A function definition cannot start with any of these keywords.
707     {
708       SourceLocation DeclEnd;
709       StmtVector Stmts;
710       return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
711     }
712
713   case tok::kw_static:
714     // Parse (then ignore) 'static' prior to a template instantiation. This is
715     // a GCC extension that we intentionally do not support.
716     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
717       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
718         << 0;
719       SourceLocation DeclEnd;
720       StmtVector Stmts;
721       return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);  
722     }
723     goto dont_know;
724       
725   case tok::kw_inline:
726     if (getLangOpts().CPlusPlus) {
727       tok::TokenKind NextKind = NextToken().getKind();
728       
729       // Inline namespaces. Allowed as an extension even in C++03.
730       if (NextKind == tok::kw_namespace) {
731         SourceLocation DeclEnd;
732         StmtVector Stmts;
733         return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
734       }
735       
736       // Parse (then ignore) 'inline' prior to a template instantiation. This is
737       // a GCC extension that we intentionally do not support.
738       if (NextKind == tok::kw_template) {
739         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
740           << 1;
741         SourceLocation DeclEnd;
742         StmtVector Stmts;
743         return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);  
744       }
745     }
746     goto dont_know;
747
748   case tok::kw_extern:
749     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
750       // Extern templates
751       SourceLocation ExternLoc = ConsumeToken();
752       SourceLocation TemplateLoc = ConsumeToken();
753       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
754              diag::warn_cxx98_compat_extern_template :
755              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
756       SourceLocation DeclEnd;
757       return Actions.ConvertDeclToDeclGroup(
758                   ParseExplicitInstantiation(Declarator::FileContext,
759                                              ExternLoc, TemplateLoc, DeclEnd));
760     }
761     // FIXME: Detect C++ linkage specifications here?
762     goto dont_know;
763
764   case tok::kw___if_exists:
765   case tok::kw___if_not_exists:
766     ParseMicrosoftIfExistsExternalDeclaration();
767     return DeclGroupPtrTy();
768       
769   default:
770   dont_know:
771     // We can't tell whether this is a function-definition or declaration yet.
772     return ParseDeclarationOrFunctionDefinition(attrs, DS);
773   }
774
775   // This routine returns a DeclGroup, if the thing we parsed only contains a
776   // single decl, convert it now.
777   return Actions.ConvertDeclToDeclGroup(SingleDecl);
778 }
779
780 /// \brief Determine whether the current token, if it occurs after a
781 /// declarator, continues a declaration or declaration list.
782 bool Parser::isDeclarationAfterDeclarator() {
783   // Check for '= delete' or '= default'
784   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
785     const Token &KW = NextToken();
786     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
787       return false;
788   }
789   
790   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
791     Tok.is(tok::comma) ||           // int X(),  -> not a function def
792     Tok.is(tok::semi)  ||           // int X();  -> not a function def
793     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
794     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
795     (getLangOpts().CPlusPlus &&
796      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
797 }
798
799 /// \brief Determine whether the current token, if it occurs after a
800 /// declarator, indicates the start of a function definition.
801 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
802   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
803   if (Tok.is(tok::l_brace))   // int X() {}
804     return true;
805   
806   // Handle K&R C argument lists: int X(f) int f; {}
807   if (!getLangOpts().CPlusPlus &&
808       Declarator.getFunctionTypeInfo().isKNRPrototype()) 
809     return isDeclarationSpecifier();
810
811   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
812     const Token &KW = NextToken();
813     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
814   }
815   
816   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
817          Tok.is(tok::kw_try);          // X() try { ... }
818 }
819
820 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
821 /// a declaration.  We can't tell which we have until we read up to the
822 /// compound-statement in function-definition. TemplateParams, if
823 /// non-NULL, provides the template parameters when we're parsing a
824 /// C++ template-declaration.
825 ///
826 ///       function-definition: [C99 6.9.1]
827 ///         decl-specs      declarator declaration-list[opt] compound-statement
828 /// [C90] function-definition: [C99 6.7.1] - implicit int result
829 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
830 ///
831 ///       declaration: [C99 6.7]
832 ///         declaration-specifiers init-declarator-list[opt] ';'
833 /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
834 /// [OMP]   threadprivate-directive                              [TODO]
835 ///
836 Parser::DeclGroupPtrTy
837 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
838                                        ParsingDeclSpec &DS,
839                                        AccessSpecifier AS) {
840   // Parse the common declaration-specifiers piece.
841   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
842
843   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
844   // declaration-specifiers init-declarator-list[opt] ';'
845   if (Tok.is(tok::semi)) {
846     ProhibitAttributes(attrs);
847     ConsumeToken();
848     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
849     DS.complete(TheDecl);
850     return Actions.ConvertDeclToDeclGroup(TheDecl);
851   }
852
853   DS.takeAttributesFrom(attrs);
854
855   // ObjC2 allows prefix attributes on class interfaces and protocols.
856   // FIXME: This still needs better diagnostics. We should only accept
857   // attributes here, no types, etc.
858   if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
859     SourceLocation AtLoc = ConsumeToken(); // the "@"
860     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
861         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
862       Diag(Tok, diag::err_objc_unexpected_attr);
863       SkipUntil(tok::semi); // FIXME: better skip?
864       return DeclGroupPtrTy();
865     }
866
867     DS.abort();
868
869     const char *PrevSpec = 0;
870     unsigned DiagID;
871     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
872       Diag(AtLoc, DiagID) << PrevSpec;
873
874     if (Tok.isObjCAtKeyword(tok::objc_protocol))
875       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
876
877     return Actions.ConvertDeclToDeclGroup(
878             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
879   }
880
881   // If the declspec consisted only of 'extern' and we have a string
882   // literal following it, this must be a C++ linkage specifier like
883   // 'extern "C"'.
884   if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
885       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
886       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
887     Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
888     return Actions.ConvertDeclToDeclGroup(TheDecl);
889   }
890
891   return ParseDeclGroup(DS, Declarator::FileContext, true);
892 }
893
894 Parser::DeclGroupPtrTy
895 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
896                                              ParsingDeclSpec *DS,
897                                              AccessSpecifier AS) {
898   if (DS) {
899     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
900   } else {
901     ParsingDeclSpec PDS(*this);
902     // Must temporarily exit the objective-c container scope for
903     // parsing c constructs and re-enter objc container scope
904     // afterwards.
905     ObjCDeclContextSwitch ObjCDC(*this);
906       
907     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
908   }
909 }
910
911 /// ParseFunctionDefinition - We parsed and verified that the specified
912 /// Declarator is well formed.  If this is a K&R-style function, read the
913 /// parameters declaration-list, then start the compound-statement.
914 ///
915 ///       function-definition: [C99 6.9.1]
916 ///         decl-specs      declarator declaration-list[opt] compound-statement
917 /// [C90] function-definition: [C99 6.7.1] - implicit int result
918 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
919 /// [C++] function-definition: [C++ 8.4]
920 ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
921 ///         function-body
922 /// [C++] function-definition: [C++ 8.4]
923 ///         decl-specifier-seq[opt] declarator function-try-block
924 ///
925 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
926                                       const ParsedTemplateInfo &TemplateInfo,
927                                       LateParsedAttrList *LateParsedAttrs) {
928   // Poison the SEH identifiers so they are flagged as illegal in function bodies
929   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
930   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
931
932   // If this is C90 and the declspecs were completely missing, fudge in an
933   // implicit int.  We do this here because this is the only place where
934   // declaration-specifiers are completely optional in the grammar.
935   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
936     const char *PrevSpec;
937     unsigned DiagID;
938     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
939                                            D.getIdentifierLoc(),
940                                            PrevSpec, DiagID);
941     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
942   }
943
944   // If this declaration was formed with a K&R-style identifier list for the
945   // arguments, parse declarations for all of the args next.
946   // int foo(a,b) int a; float b; {}
947   if (FTI.isKNRPrototype())
948     ParseKNRParamDeclarations(D);
949
950   // We should have either an opening brace or, in a C++ constructor,
951   // we may have a colon.
952   if (Tok.isNot(tok::l_brace) && 
953       (!getLangOpts().CPlusPlus ||
954        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
955         Tok.isNot(tok::equal)))) {
956     Diag(Tok, diag::err_expected_fn_body);
957
958     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
959     SkipUntil(tok::l_brace, true, true);
960
961     // If we didn't find the '{', bail out.
962     if (Tok.isNot(tok::l_brace))
963       return 0;
964   }
965
966   // Check to make sure that any normal attributes are allowed to be on
967   // a definition.  Late parsed attributes are checked at the end.
968   if (Tok.isNot(tok::equal)) {
969     AttributeList *DtorAttrs = D.getAttributes();
970     while (DtorAttrs) {
971       if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName()) &&
972           !DtorAttrs->isCXX11Attribute()) {
973         Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
974           << DtorAttrs->getName()->getName();
975       }
976       DtorAttrs = DtorAttrs->getNext();
977     }
978   }
979
980   // In delayed template parsing mode, for function template we consume the
981   // tokens and store them for late parsing at the end of the translation unit.
982   if (getLangOpts().DelayedTemplateParsing &&
983       Tok.isNot(tok::equal) &&
984       TemplateInfo.Kind == ParsedTemplateInfo::Template) {
985     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
986     
987     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
988     Scope *ParentScope = getCurScope()->getParent();
989
990     D.setFunctionDefinitionKind(FDK_Definition);
991     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
992                                         TemplateParameterLists);
993     D.complete(DP);
994     D.getMutableDeclSpec().abort();
995
996     if (DP) {
997       LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
998
999       FunctionDecl *FnD = 0;
1000       if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
1001         FnD = FunTmpl->getTemplatedDecl();
1002       else
1003         FnD = cast<FunctionDecl>(DP);
1004       Actions.CheckForFunctionRedefinition(FnD);
1005
1006       LateParsedTemplateMap[FnD] = LPT;
1007       Actions.MarkAsLateParsedTemplate(FnD);
1008       LexTemplateFunctionForLateParsing(LPT->Toks);
1009     } else {
1010       CachedTokens Toks;
1011       LexTemplateFunctionForLateParsing(Toks);
1012     }
1013     return DP;
1014   }
1015   else if (CurParsedObjCImpl && 
1016            !TemplateInfo.TemplateParams &&
1017            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1018             Tok.is(tok::colon)) && 
1019       Actions.CurContext->isTranslationUnit()) {
1020     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1021     Scope *ParentScope = getCurScope()->getParent();
1022     
1023     D.setFunctionDefinitionKind(FDK_Definition);
1024     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1025                                               MultiTemplateParamsArg());
1026     D.complete(FuncDecl);
1027     D.getMutableDeclSpec().abort();
1028     if (FuncDecl) {
1029       // Consume the tokens and store them for later parsing.
1030       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1031       CurParsedObjCImpl->HasCFunction = true;
1032       return FuncDecl;
1033     }
1034   }
1035       
1036   // Enter a scope for the function body.
1037   ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1038
1039   // Tell the actions module that we have entered a function definition with the
1040   // specified Declarator for the function.
1041   Decl *Res = TemplateInfo.TemplateParams?
1042       Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
1043                                               *TemplateInfo.TemplateParams, D)
1044     : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
1045
1046   // Break out of the ParsingDeclarator context before we parse the body.
1047   D.complete(Res);
1048   
1049   // Break out of the ParsingDeclSpec context, too.  This const_cast is
1050   // safe because we're always the sole owner.
1051   D.getMutableDeclSpec().abort();
1052
1053   if (Tok.is(tok::equal)) {
1054     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1055     ConsumeToken();
1056
1057     Actions.ActOnFinishFunctionBody(Res, 0, false);
1058  
1059     bool Delete = false;
1060     SourceLocation KWLoc;
1061     if (Tok.is(tok::kw_delete)) {
1062       Diag(Tok, getLangOpts().CPlusPlus11 ?
1063            diag::warn_cxx98_compat_deleted_function :
1064            diag::ext_deleted_function);
1065
1066       KWLoc = ConsumeToken();
1067       Actions.SetDeclDeleted(Res, KWLoc);
1068       Delete = true;
1069     } else if (Tok.is(tok::kw_default)) {
1070       Diag(Tok, getLangOpts().CPlusPlus11 ?
1071            diag::warn_cxx98_compat_defaulted_function :
1072            diag::ext_defaulted_function);
1073
1074       KWLoc = ConsumeToken();
1075       Actions.SetDeclDefaulted(Res, KWLoc);
1076     } else {
1077       llvm_unreachable("function definition after = not 'delete' or 'default'");
1078     }
1079
1080     if (Tok.is(tok::comma)) {
1081       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1082         << Delete;
1083       SkipUntil(tok::semi);
1084     } else {
1085       ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1086                        Delete ? "delete" : "default", tok::semi);
1087     }
1088
1089     return Res;
1090   }
1091
1092   if (Tok.is(tok::kw_try))
1093     return ParseFunctionTryBlock(Res, BodyScope);
1094
1095   // If we have a colon, then we're probably parsing a C++
1096   // ctor-initializer.
1097   if (Tok.is(tok::colon)) {
1098     ParseConstructorInitializer(Res);
1099
1100     // Recover from error.
1101     if (!Tok.is(tok::l_brace)) {
1102       BodyScope.Exit();
1103       Actions.ActOnFinishFunctionBody(Res, 0);
1104       return Res;
1105     }
1106   } else
1107     Actions.ActOnDefaultCtorInitializers(Res);
1108
1109   // Late attributes are parsed in the same scope as the function body.
1110   if (LateParsedAttrs)
1111     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1112
1113   return ParseFunctionStatementBody(Res, BodyScope);
1114 }
1115
1116 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1117 /// types for a function with a K&R-style identifier list for arguments.
1118 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1119   // We know that the top-level of this declarator is a function.
1120   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1121
1122   // Enter function-declaration scope, limiting any declarators to the
1123   // function prototype scope, including parameter declarators.
1124   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1125                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1126
1127   // Read all the argument declarations.
1128   while (isDeclarationSpecifier()) {
1129     SourceLocation DSStart = Tok.getLocation();
1130
1131     // Parse the common declaration-specifiers piece.
1132     DeclSpec DS(AttrFactory);
1133     ParseDeclarationSpecifiers(DS);
1134
1135     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1136     // least one declarator'.
1137     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1138     // the declarations though.  It's trivial to ignore them, really hard to do
1139     // anything else with them.
1140     if (Tok.is(tok::semi)) {
1141       Diag(DSStart, diag::err_declaration_does_not_declare_param);
1142       ConsumeToken();
1143       continue;
1144     }
1145
1146     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1147     // than register.
1148     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1149         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1150       Diag(DS.getStorageClassSpecLoc(),
1151            diag::err_invalid_storage_class_in_func_decl);
1152       DS.ClearStorageClassSpecs();
1153     }
1154     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1155       Diag(DS.getThreadStorageClassSpecLoc(),
1156            diag::err_invalid_storage_class_in_func_decl);
1157       DS.ClearStorageClassSpecs();
1158     }
1159
1160     // Parse the first declarator attached to this declspec.
1161     Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1162     ParseDeclarator(ParmDeclarator);
1163
1164     // Handle the full declarator list.
1165     while (1) {
1166       // If attributes are present, parse them.
1167       MaybeParseGNUAttributes(ParmDeclarator);
1168
1169       // Ask the actions module to compute the type for this declarator.
1170       Decl *Param =
1171         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1172
1173       if (Param &&
1174           // A missing identifier has already been diagnosed.
1175           ParmDeclarator.getIdentifier()) {
1176
1177         // Scan the argument list looking for the correct param to apply this
1178         // type.
1179         for (unsigned i = 0; ; ++i) {
1180           // C99 6.9.1p6: those declarators shall declare only identifiers from
1181           // the identifier list.
1182           if (i == FTI.NumArgs) {
1183             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1184               << ParmDeclarator.getIdentifier();
1185             break;
1186           }
1187
1188           if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1189             // Reject redefinitions of parameters.
1190             if (FTI.ArgInfo[i].Param) {
1191               Diag(ParmDeclarator.getIdentifierLoc(),
1192                    diag::err_param_redefinition)
1193                  << ParmDeclarator.getIdentifier();
1194             } else {
1195               FTI.ArgInfo[i].Param = Param;
1196             }
1197             break;
1198           }
1199         }
1200       }
1201
1202       // If we don't have a comma, it is either the end of the list (a ';') or
1203       // an error, bail out.
1204       if (Tok.isNot(tok::comma))
1205         break;
1206
1207       ParmDeclarator.clear();
1208
1209       // Consume the comma.
1210       ParmDeclarator.setCommaLoc(ConsumeToken());
1211
1212       // Parse the next declarator.
1213       ParseDeclarator(ParmDeclarator);
1214     }
1215
1216     if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
1217       // Skip to end of block or statement
1218       SkipUntil(tok::semi, true);
1219       if (Tok.is(tok::semi))
1220         ConsumeToken();
1221     }
1222   }
1223
1224   // The actions module must verify that all arguments were declared.
1225   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1226 }
1227
1228
1229 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1230 /// allowed to be a wide string, and is not subject to character translation.
1231 ///
1232 /// [GNU] asm-string-literal:
1233 ///         string-literal
1234 ///
1235 Parser::ExprResult Parser::ParseAsmStringLiteral() {
1236   switch (Tok.getKind()) {
1237     case tok::string_literal:
1238       break;
1239     case tok::utf8_string_literal:
1240     case tok::utf16_string_literal:
1241     case tok::utf32_string_literal:
1242     case tok::wide_string_literal: {
1243       SourceLocation L = Tok.getLocation();
1244       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1245         << (Tok.getKind() == tok::wide_string_literal)
1246         << SourceRange(L, L);
1247       return ExprError();
1248     }
1249     default:
1250       Diag(Tok, diag::err_expected_string_literal)
1251         << /*Source='in...'*/0 << "'asm'";
1252       return ExprError();
1253   }
1254
1255   return ParseStringLiteralExpression();
1256 }
1257
1258 /// ParseSimpleAsm
1259 ///
1260 /// [GNU] simple-asm-expr:
1261 ///         'asm' '(' asm-string-literal ')'
1262 ///
1263 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1264   assert(Tok.is(tok::kw_asm) && "Not an asm!");
1265   SourceLocation Loc = ConsumeToken();
1266
1267   if (Tok.is(tok::kw_volatile)) {
1268     // Remove from the end of 'asm' to the end of 'volatile'.
1269     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1270                              PP.getLocForEndOfToken(Tok.getLocation()));
1271
1272     Diag(Tok, diag::warn_file_asm_volatile)
1273       << FixItHint::CreateRemoval(RemovalRange);
1274     ConsumeToken();
1275   }
1276
1277   BalancedDelimiterTracker T(*this, tok::l_paren);
1278   if (T.consumeOpen()) {
1279     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1280     return ExprError();
1281   }
1282
1283   ExprResult Result(ParseAsmStringLiteral());
1284
1285   if (Result.isInvalid()) {
1286     SkipUntil(tok::r_paren, true, true);
1287     if (EndLoc)
1288       *EndLoc = Tok.getLocation();
1289     ConsumeAnyToken();
1290   } else {
1291     // Close the paren and get the location of the end bracket
1292     T.consumeClose();
1293     if (EndLoc)
1294       *EndLoc = T.getCloseLocation();
1295   }
1296
1297   return Result;
1298 }
1299
1300 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1301 /// cleanup pool so that it gets destroyed when parsing the current top level
1302 /// declaration is finished.
1303 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1304   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1305   TemplateIdAnnotation *
1306       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1307   return Id;
1308 }
1309
1310 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1311   // Push the current token back into the token stream (or revert it if it is
1312   // cached) and use an annotation scope token for current token.
1313   if (PP.isBacktrackEnabled())
1314     PP.RevertCachedTokens(1);
1315   else
1316     PP.EnterToken(Tok);
1317   Tok.setKind(tok::annot_cxxscope);
1318   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1319   Tok.setAnnotationRange(SS.getRange());
1320
1321   // In case the tokens were cached, have Preprocessor replace them
1322   // with the annotation token.  We don't need to do this if we've
1323   // just reverted back to a prior state.
1324   if (IsNewAnnotation)
1325     PP.AnnotateCachedTokens(Tok);
1326 }
1327
1328 /// \brief Attempt to classify the name at the current token position. This may
1329 /// form a type, scope or primary expression annotation, or replace the token
1330 /// with a typo-corrected keyword. This is only appropriate when the current
1331 /// name must refer to an entity which has already been declared.
1332 ///
1333 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1334 ///        and might possibly have a dependent nested name specifier.
1335 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1336 ///        no typo correction will be performed.
1337 Parser::AnnotatedNameKind
1338 Parser::TryAnnotateName(bool IsAddressOfOperand,
1339                         CorrectionCandidateCallback *CCC) {
1340   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1341
1342   const bool EnteringContext = false;
1343   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1344
1345   CXXScopeSpec SS;
1346   if (getLangOpts().CPlusPlus &&
1347       ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1348     return ANK_Error;
1349
1350   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1351     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1352                                                   !WasScopeAnnotation))
1353       return ANK_Error;
1354     return ANK_Unresolved;
1355   }
1356
1357   IdentifierInfo *Name = Tok.getIdentifierInfo();
1358   SourceLocation NameLoc = Tok.getLocation();
1359
1360   // FIXME: Move the tentative declaration logic into ClassifyName so we can
1361   // typo-correct to tentatively-declared identifiers.
1362   if (isTentativelyDeclared(Name)) {
1363     // Identifier has been tentatively declared, and thus cannot be resolved as
1364     // an expression. Fall back to annotating it as a type.
1365     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1366                                                   !WasScopeAnnotation))
1367       return ANK_Error;
1368     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1369   }
1370
1371   Token Next = NextToken();
1372
1373   // Look up and classify the identifier. We don't perform any typo-correction
1374   // after a scope specifier, because in general we can't recover from typos
1375   // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1376   // back into scope specifier parsing).
1377   Sema::NameClassification Classification
1378     = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1379                            IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1380
1381   switch (Classification.getKind()) {
1382   case Sema::NC_Error:
1383     return ANK_Error;
1384
1385   case Sema::NC_Keyword:
1386     // The identifier was typo-corrected to a keyword.
1387     Tok.setIdentifierInfo(Name);
1388     Tok.setKind(Name->getTokenID());
1389     PP.TypoCorrectToken(Tok);
1390     if (SS.isNotEmpty())
1391       AnnotateScopeToken(SS, !WasScopeAnnotation);
1392     // We've "annotated" this as a keyword.
1393     return ANK_Success;
1394
1395   case Sema::NC_Unknown:
1396     // It's not something we know about. Leave it unannotated.
1397     break;
1398
1399   case Sema::NC_Type:
1400     Tok.setKind(tok::annot_typename);
1401     setTypeAnnotation(Tok, Classification.getType());
1402     Tok.setAnnotationEndLoc(NameLoc);
1403     if (SS.isNotEmpty())
1404       Tok.setLocation(SS.getBeginLoc());
1405     PP.AnnotateCachedTokens(Tok);
1406     return ANK_Success;
1407
1408   case Sema::NC_Expression:
1409     Tok.setKind(tok::annot_primary_expr);
1410     setExprAnnotation(Tok, Classification.getExpression());
1411     Tok.setAnnotationEndLoc(NameLoc);
1412     if (SS.isNotEmpty())
1413       Tok.setLocation(SS.getBeginLoc());
1414     PP.AnnotateCachedTokens(Tok);
1415     return ANK_Success;
1416
1417   case Sema::NC_TypeTemplate:
1418     if (Next.isNot(tok::less)) {
1419       // This may be a type template being used as a template template argument.
1420       if (SS.isNotEmpty())
1421         AnnotateScopeToken(SS, !WasScopeAnnotation);
1422       return ANK_TemplateName;
1423     }
1424     // Fall through.
1425   case Sema::NC_FunctionTemplate: {
1426     // We have a type or function template followed by '<'.
1427     ConsumeToken();
1428     UnqualifiedId Id;
1429     Id.setIdentifier(Name, NameLoc);
1430     if (AnnotateTemplateIdToken(
1431             TemplateTy::make(Classification.getTemplateName()),
1432             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1433       return ANK_Error;
1434     return ANK_Success;
1435   }
1436
1437   case Sema::NC_NestedNameSpecifier:
1438     llvm_unreachable("already parsed nested name specifier");
1439   }
1440
1441   // Unable to classify the name, but maybe we can annotate a scope specifier.
1442   if (SS.isNotEmpty())
1443     AnnotateScopeToken(SS, !WasScopeAnnotation);
1444   return ANK_Unresolved;
1445 }
1446
1447 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1448 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1449 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1450 /// with a single annotation token representing the typename or C++ scope
1451 /// respectively.
1452 /// This simplifies handling of C++ scope specifiers and allows efficient
1453 /// backtracking without the need to re-parse and resolve nested-names and
1454 /// typenames.
1455 /// It will mainly be called when we expect to treat identifiers as typenames
1456 /// (if they are typenames). For example, in C we do not expect identifiers
1457 /// inside expressions to be treated as typenames so it will not be called
1458 /// for expressions in C.
1459 /// The benefit for C/ObjC is that a typename will be annotated and
1460 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1461 /// will not be called twice, once to check whether we have a declaration
1462 /// specifier, and another one to get the actual type inside
1463 /// ParseDeclarationSpecifiers).
1464 ///
1465 /// This returns true if an error occurred.
1466 ///
1467 /// Note that this routine emits an error if you call it with ::new or ::delete
1468 /// as the current tokens, so only call it in contexts where these are invalid.
1469 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1470   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1471           || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
1472           || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1473           && "Cannot be a type or scope token!");
1474
1475   if (Tok.is(tok::kw_typename)) {
1476     // Parse a C++ typename-specifier, e.g., "typename T::type".
1477     //
1478     //   typename-specifier:
1479     //     'typename' '::' [opt] nested-name-specifier identifier
1480     //     'typename' '::' [opt] nested-name-specifier template [opt]
1481     //            simple-template-id
1482     SourceLocation TypenameLoc = ConsumeToken();
1483     CXXScopeSpec SS;
1484     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), 
1485                                        /*EnteringContext=*/false,
1486                                        0, /*IsTypename*/true))
1487       return true;
1488     if (!SS.isSet()) {
1489       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1490           Tok.is(tok::annot_decltype)) {
1491         // Attempt to recover by skipping the invalid 'typename'
1492         if (Tok.is(tok::annot_decltype) ||
1493             (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1494             Tok.isAnnotation())) {
1495           unsigned DiagID = diag::err_expected_qualified_after_typename;
1496           // MS compatibility: MSVC permits using known types with typename.
1497           // e.g. "typedef typename T* pointer_type"
1498           if (getLangOpts().MicrosoftExt)
1499             DiagID = diag::warn_expected_qualified_after_typename;
1500           Diag(Tok.getLocation(), DiagID);
1501           return false;
1502         }
1503       }
1504
1505       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1506       return true;
1507     }
1508
1509     TypeResult Ty;
1510     if (Tok.is(tok::identifier)) {
1511       // FIXME: check whether the next token is '<', first!
1512       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 
1513                                      *Tok.getIdentifierInfo(),
1514                                      Tok.getLocation());
1515     } else if (Tok.is(tok::annot_template_id)) {
1516       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1517       if (TemplateId->Kind == TNK_Function_template) {
1518         Diag(Tok, diag::err_typename_refers_to_non_type_template)
1519           << Tok.getAnnotationRange();
1520         return true;
1521       }
1522
1523       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1524                                          TemplateId->NumArgs);
1525
1526       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1527                                      TemplateId->TemplateKWLoc,
1528                                      TemplateId->Template,
1529                                      TemplateId->TemplateNameLoc,
1530                                      TemplateId->LAngleLoc,
1531                                      TemplateArgsPtr,
1532                                      TemplateId->RAngleLoc);
1533     } else {
1534       Diag(Tok, diag::err_expected_type_name_after_typename)
1535         << SS.getRange();
1536       return true;
1537     }
1538
1539     SourceLocation EndLoc = Tok.getLastLoc();
1540     Tok.setKind(tok::annot_typename);
1541     setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1542     Tok.setAnnotationEndLoc(EndLoc);
1543     Tok.setLocation(TypenameLoc);
1544     PP.AnnotateCachedTokens(Tok);
1545     return false;
1546   }
1547
1548   // Remembers whether the token was originally a scope annotation.
1549   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1550
1551   CXXScopeSpec SS;
1552   if (getLangOpts().CPlusPlus)
1553     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1554       return true;
1555
1556   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1557                                                    SS, !WasScopeAnnotation);
1558 }
1559
1560 /// \brief Try to annotate a type or scope token, having already parsed an
1561 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1562 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1563 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1564                                                        bool NeedType,
1565                                                        CXXScopeSpec &SS,
1566                                                        bool IsNewScope) {
1567   if (Tok.is(tok::identifier)) {
1568     IdentifierInfo *CorrectedII = 0;
1569     // Determine whether the identifier is a type name.
1570     if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1571                                             Tok.getLocation(), getCurScope(),
1572                                             &SS, false, 
1573                                             NextToken().is(tok::period),
1574                                             ParsedType(),
1575                                             /*IsCtorOrDtorName=*/false,
1576                                             /*NonTrivialTypeSourceInfo*/true,
1577                                             NeedType ? &CorrectedII : NULL)) {
1578       // A FixIt was applied as a result of typo correction
1579       if (CorrectedII)
1580         Tok.setIdentifierInfo(CorrectedII);
1581       // This is a typename. Replace the current token in-place with an
1582       // annotation type token.
1583       Tok.setKind(tok::annot_typename);
1584       setTypeAnnotation(Tok, Ty);
1585       Tok.setAnnotationEndLoc(Tok.getLocation());
1586       if (SS.isNotEmpty()) // it was a C++ qualified type name.
1587         Tok.setLocation(SS.getBeginLoc());
1588
1589       // In case the tokens were cached, have Preprocessor replace
1590       // them with the annotation token.
1591       PP.AnnotateCachedTokens(Tok);
1592       return false;
1593     }
1594
1595     if (!getLangOpts().CPlusPlus) {
1596       // If we're in C, we can't have :: tokens at all (the lexer won't return
1597       // them).  If the identifier is not a type, then it can't be scope either,
1598       // just early exit.
1599       return false;
1600     }
1601
1602     // If this is a template-id, annotate with a template-id or type token.
1603     if (NextToken().is(tok::less)) {
1604       TemplateTy Template;
1605       UnqualifiedId TemplateName;
1606       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1607       bool MemberOfUnknownSpecialization;
1608       if (TemplateNameKind TNK
1609           = Actions.isTemplateName(getCurScope(), SS,
1610                                    /*hasTemplateKeyword=*/false, TemplateName,
1611                                    /*ObjectType=*/ ParsedType(),
1612                                    EnteringContext,
1613                                    Template, MemberOfUnknownSpecialization)) {
1614         // Consume the identifier.
1615         ConsumeToken();
1616         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1617                                     TemplateName)) {
1618           // If an unrecoverable error occurred, we need to return true here,
1619           // because the token stream is in a damaged state.  We may not return
1620           // a valid identifier.
1621           return true;
1622         }
1623       }
1624     }
1625
1626     // The current token, which is either an identifier or a
1627     // template-id, is not part of the annotation. Fall through to
1628     // push that token back into the stream and complete the C++ scope
1629     // specifier annotation.
1630   }
1631
1632   if (Tok.is(tok::annot_template_id)) {
1633     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1634     if (TemplateId->Kind == TNK_Type_template) {
1635       // A template-id that refers to a type was parsed into a
1636       // template-id annotation in a context where we weren't allowed
1637       // to produce a type annotation token. Update the template-id
1638       // annotation token to a type annotation token now.
1639       AnnotateTemplateIdTokenAsType();
1640       return false;
1641     }
1642   }
1643
1644   if (SS.isEmpty())
1645     return false;
1646
1647   // A C++ scope specifier that isn't followed by a typename.
1648   AnnotateScopeToken(SS, IsNewScope);
1649   return false;
1650 }
1651
1652 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1653 /// annotates C++ scope specifiers and template-ids.  This returns
1654 /// true if there was an error that could not be recovered from.
1655 ///
1656 /// Note that this routine emits an error if you call it with ::new or ::delete
1657 /// as the current tokens, so only call it in contexts where these are invalid.
1658 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1659   assert(getLangOpts().CPlusPlus &&
1660          "Call sites of this function should be guarded by checking for C++");
1661   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1662           (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1663          Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
1664
1665   CXXScopeSpec SS;
1666   if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1667     return true;
1668   if (SS.isEmpty())
1669     return false;
1670
1671   AnnotateScopeToken(SS, true);
1672   return false;
1673 }
1674
1675 bool Parser::isTokenEqualOrEqualTypo() {
1676   tok::TokenKind Kind = Tok.getKind();
1677   switch (Kind) {
1678   default:
1679     return false;
1680   case tok::ampequal:            // &=
1681   case tok::starequal:           // *=
1682   case tok::plusequal:           // +=
1683   case tok::minusequal:          // -=
1684   case tok::exclaimequal:        // !=
1685   case tok::slashequal:          // /=
1686   case tok::percentequal:        // %=
1687   case tok::lessequal:           // <=
1688   case tok::lesslessequal:       // <<=
1689   case tok::greaterequal:        // >=
1690   case tok::greatergreaterequal: // >>=
1691   case tok::caretequal:          // ^=
1692   case tok::pipeequal:           // |=
1693   case tok::equalequal:          // ==
1694     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1695       << getTokenSimpleSpelling(Kind)
1696       << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1697   case tok::equal:
1698     return true;
1699   }
1700 }
1701
1702 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1703   assert(Tok.is(tok::code_completion));
1704   PrevTokLocation = Tok.getLocation();
1705
1706   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1707     if (S->getFlags() & Scope::FnScope) {
1708       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1709       cutOffParsing();
1710       return PrevTokLocation;
1711     }
1712     
1713     if (S->getFlags() & Scope::ClassScope) {
1714       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1715       cutOffParsing();
1716       return PrevTokLocation;
1717     }
1718   }
1719   
1720   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1721   cutOffParsing();
1722   return PrevTokLocation;
1723 }
1724
1725 // Anchor the Parser::FieldCallback vtable to this translation unit.
1726 // We use a spurious method instead of the destructor because
1727 // destroying FieldCallbacks can actually be slightly
1728 // performance-sensitive.
1729 void Parser::FieldCallback::_anchor() {
1730 }
1731
1732 // Code-completion pass-through functions
1733
1734 void Parser::CodeCompleteDirective(bool InConditional) {
1735   Actions.CodeCompletePreprocessorDirective(InConditional);
1736 }
1737
1738 void Parser::CodeCompleteInConditionalExclusion() {
1739   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1740 }
1741
1742 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1743   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1744 }
1745
1746 void Parser::CodeCompletePreprocessorExpression() { 
1747   Actions.CodeCompletePreprocessorExpression();
1748 }
1749
1750 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1751                                        MacroInfo *MacroInfo,
1752                                        unsigned ArgumentIndex) {
1753   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 
1754                                                 ArgumentIndex);
1755 }
1756
1757 void Parser::CodeCompleteNaturalLanguage() {
1758   Actions.CodeCompleteNaturalLanguage();
1759 }
1760
1761 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1762   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1763          "Expected '__if_exists' or '__if_not_exists'");
1764   Result.IsIfExists = Tok.is(tok::kw___if_exists);
1765   Result.KeywordLoc = ConsumeToken();
1766
1767   BalancedDelimiterTracker T(*this, tok::l_paren);
1768   if (T.consumeOpen()) {
1769     Diag(Tok, diag::err_expected_lparen_after) 
1770       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1771     return true;
1772   }
1773   
1774   // Parse nested-name-specifier.
1775   ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(), 
1776                                  /*EnteringContext=*/false);
1777
1778   // Check nested-name specifier.
1779   if (Result.SS.isInvalid()) {
1780     T.skipToEnd();
1781     return true;
1782   }
1783
1784   // Parse the unqualified-id.
1785   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1786   if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1787                          TemplateKWLoc, Result.Name)) {
1788     T.skipToEnd();
1789     return true;
1790   }
1791
1792   if (T.consumeClose())
1793     return true;
1794   
1795   // Check if the symbol exists.
1796   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1797                                                Result.IsIfExists, Result.SS, 
1798                                                Result.Name)) {
1799   case Sema::IER_Exists:
1800     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1801     break;
1802
1803   case Sema::IER_DoesNotExist:
1804     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1805     break;
1806
1807   case Sema::IER_Dependent:
1808     Result.Behavior = IEB_Dependent;
1809     break;
1810       
1811   case Sema::IER_Error:
1812     return true;
1813   }
1814
1815   return false;
1816 }
1817
1818 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1819   IfExistsCondition Result;
1820   if (ParseMicrosoftIfExistsCondition(Result))
1821     return;
1822   
1823   BalancedDelimiterTracker Braces(*this, tok::l_brace);
1824   if (Braces.consumeOpen()) {
1825     Diag(Tok, diag::err_expected_lbrace);
1826     return;
1827   }
1828
1829   switch (Result.Behavior) {
1830   case IEB_Parse:
1831     // Parse declarations below.
1832     break;
1833       
1834   case IEB_Dependent:
1835     llvm_unreachable("Cannot have a dependent external declaration");
1836       
1837   case IEB_Skip:
1838     Braces.skipToEnd();
1839     return;
1840   }
1841
1842   // Parse the declarations.
1843   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1844     ParsedAttributesWithRange attrs(AttrFactory);
1845     MaybeParseCXX11Attributes(attrs);
1846     MaybeParseMicrosoftAttributes(attrs);
1847     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1848     if (Result && !getCurScope()->getParent())
1849       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1850   }     
1851   Braces.consumeClose();
1852 }
1853
1854 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1855   assert(Tok.isObjCAtKeyword(tok::objc_import) && 
1856          "Improper start to module import");
1857   SourceLocation ImportLoc = ConsumeToken();
1858   
1859   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1860   
1861   // Parse the module path.
1862   do {
1863     if (!Tok.is(tok::identifier)) {
1864       if (Tok.is(tok::code_completion)) {
1865         Actions.CodeCompleteModuleImport(ImportLoc, Path);
1866         ConsumeCodeCompletionToken();
1867         SkipUntil(tok::semi);
1868         return DeclGroupPtrTy();
1869       }
1870       
1871       Diag(Tok, diag::err_module_expected_ident);
1872       SkipUntil(tok::semi);
1873       return DeclGroupPtrTy();
1874     }
1875     
1876     // Record this part of the module path.
1877     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1878     ConsumeToken();
1879     
1880     if (Tok.is(tok::period)) {
1881       ConsumeToken();
1882       continue;
1883     }
1884     
1885     break;
1886   } while (true);
1887   
1888   DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
1889   ExpectAndConsumeSemi(diag::err_module_expected_semi);
1890   if (Import.isInvalid())
1891     return DeclGroupPtrTy();
1892   
1893   return Actions.ConvertDeclToDeclGroup(Import.get());
1894 }
1895
1896 bool BalancedDelimiterTracker::diagnoseOverflow() {
1897   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
1898     << P.getLangOpts().BracketDepth;
1899   P.Diag(P.Tok, diag::note_bracket_depth);
1900   P.SkipUntil(tok::eof);
1901   return true;  
1902 }
1903
1904 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1905                                             const char *Msg,
1906                                             tok::TokenKind SkipToToc ) {
1907   LOpen = P.Tok.getLocation();
1908   if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1909     return true;
1910   
1911   if (getDepth() < MaxDepth)
1912     return false;
1913     
1914   return diagnoseOverflow();
1915 }
1916
1917 bool BalancedDelimiterTracker::diagnoseMissingClose() {
1918   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1919   
1920   const char *LHSName = "unknown";
1921   diag::kind DID;
1922   switch (Close) {
1923   default: llvm_unreachable("Unexpected balanced token");
1924   case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1925   case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1926   case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
1927   }
1928   P.Diag(P.Tok, DID);
1929   P.Diag(LOpen, diag::note_matching) << LHSName;
1930   if (P.SkipUntil(Close, /*StopAtSemi*/ true, /*DontConsume*/ true))
1931     LClose = P.ConsumeAnyToken();
1932   return true;
1933 }
1934
1935 void BalancedDelimiterTracker::skipToEnd() {
1936   P.SkipUntil(Close, false);
1937 }