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