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/Parse/DeclSpec.h"
17 #include "clang/Parse/Scope.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "ExtensionRAIIObject.h"
20 #include "ParsePragma.h"
21 using namespace clang;
22 
23 /// \brief A comment handler that passes comments found by the preprocessor
24 /// to the parser action.
25 class ActionCommentHandler : public CommentHandler {
26   Action &Actions;
27 
28 public:
29   explicit ActionCommentHandler(Action &Actions) : Actions(Actions) { }
30 
31   virtual void HandleComment(Preprocessor &PP, SourceRange Comment) {
32     Actions.ActOnComment(Comment);
33   }
34 };
35 
36 Parser::Parser(Preprocessor &pp, Action &actions)
37   : CrashInfo(*this), PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
38     GreaterThanIsOperator(true) {
39   Tok.setKind(tok::eof);
40   CurScope = 0;
41   NumCachedScopes = 0;
42   ParenCount = BracketCount = BraceCount = 0;
43   ObjCImpDecl = DeclPtrTy();
44 
45   // Add #pragma handlers. These are removed and destroyed in the
46   // destructor.
47   PackHandler.reset(new
48           PragmaPackHandler(&PP.getIdentifierTable().get("pack"), actions));
49   PP.AddPragmaHandler(0, PackHandler.get());
50 
51   UnusedHandler.reset(new
52           PragmaUnusedHandler(&PP.getIdentifierTable().get("unused"), actions,
53                               *this));
54   PP.AddPragmaHandler(0, UnusedHandler.get());
55 
56   WeakHandler.reset(new
57           PragmaWeakHandler(&PP.getIdentifierTable().get("weak"), actions));
58   PP.AddPragmaHandler(0, WeakHandler.get());
59 
60   CommentHandler.reset(new ActionCommentHandler(actions));
61   PP.AddCommentHandler(CommentHandler.get());
62 }
63 
64 /// If a crash happens while the parser is active, print out a line indicating
65 /// what the current token is.
66 void PrettyStackTraceParserEntry::print(llvm::raw_ostream &OS) const {
67   const Token &Tok = P.getCurToken();
68   if (Tok.is(tok::eof)) {
69     OS << "<eof> parser at end of file\n";
70     return;
71   }
72 
73   if (Tok.getLocation().isInvalid()) {
74     OS << "<unknown> parser at unknown location\n";
75     return;
76   }
77 
78   const Preprocessor &PP = P.getPreprocessor();
79   Tok.getLocation().print(OS, PP.getSourceManager());
80   OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
81 }
82 
83 
84 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
85   return Diags.Report(FullSourceLoc(Loc, PP.getSourceManager()), DiagID);
86 }
87 
88 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
89   return Diag(Tok.getLocation(), DiagID);
90 }
91 
92 /// \brief Emits a diagnostic suggesting parentheses surrounding a
93 /// given range.
94 ///
95 /// \param Loc The location where we'll emit the diagnostic.
96 /// \param Loc The kind of diagnostic to emit.
97 /// \param ParenRange Source range enclosing code that should be parenthesized.
98 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
99                                 SourceRange ParenRange) {
100   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
101   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
102     // We can't display the parentheses, so just dig the
103     // warning/error and return.
104     Diag(Loc, DK);
105     return;
106   }
107 
108   Diag(Loc, DK)
109     << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
110     << CodeModificationHint::CreateInsertion(EndLoc, ")");
111 }
112 
113 /// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
114 /// this helper function matches and consumes the specified RHS token if
115 /// present.  If not present, it emits the specified diagnostic indicating
116 /// that the parser failed to match the RHS of the token at LHSLoc.  LHSName
117 /// should be the name of the unmatched LHS token.
118 SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
119                                            SourceLocation LHSLoc) {
120 
121   if (Tok.is(RHSTok))
122     return ConsumeAnyToken();
123 
124   SourceLocation R = Tok.getLocation();
125   const char *LHSName = "unknown";
126   diag::kind DID = diag::err_parse_error;
127   switch (RHSTok) {
128   default: break;
129   case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
130   case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
131   case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
132   case tok::greater:  LHSName = "<"; DID = diag::err_expected_greater; break;
133   }
134   Diag(Tok, DID);
135   Diag(LHSLoc, diag::note_matching) << LHSName;
136   SkipUntil(RHSTok);
137   return R;
138 }
139 
140 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
141 /// input.  If so, it is consumed and false is returned.
142 ///
143 /// If the input is malformed, this emits the specified diagnostic.  Next, if
144 /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
145 /// returned.
146 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
147                               const char *Msg, tok::TokenKind SkipToTok) {
148   if (Tok.is(ExpectedTok)) {
149     ConsumeAnyToken();
150     return false;
151   }
152 
153   const char *Spelling = 0;
154   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
155   if (EndLoc.isValid() &&
156       (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
157     // Show what code to insert to fix this problem.
158     Diag(EndLoc, DiagID)
159       << Msg
160       << CodeModificationHint::CreateInsertion(EndLoc, Spelling);
161   } else
162     Diag(Tok, DiagID) << Msg;
163 
164   if (SkipToTok != tok::unknown)
165     SkipUntil(SkipToTok);
166   return true;
167 }
168 
169 //===----------------------------------------------------------------------===//
170 // Error recovery.
171 //===----------------------------------------------------------------------===//
172 
173 /// SkipUntil - Read tokens until we get to the specified token, then consume
174 /// it (unless DontConsume is true).  Because we cannot guarantee that the
175 /// token will ever occur, this skips to the next token, or to some likely
176 /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
177 /// character.
178 ///
179 /// If SkipUntil finds the specified token, it returns true, otherwise it
180 /// returns false.
181 bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
182                        bool StopAtSemi, bool DontConsume) {
183   // We always want this function to skip at least one token if the first token
184   // isn't T and if not at EOF.
185   bool isFirstTokenSkipped = true;
186   while (1) {
187     // If we found one of the tokens, stop and return true.
188     for (unsigned i = 0; i != NumToks; ++i) {
189       if (Tok.is(Toks[i])) {
190         if (DontConsume) {
191           // Noop, don't consume the token.
192         } else {
193           ConsumeAnyToken();
194         }
195         return true;
196       }
197     }
198 
199     switch (Tok.getKind()) {
200     case tok::eof:
201       // Ran out of tokens.
202       return false;
203 
204     case tok::l_paren:
205       // Recursively skip properly-nested parens.
206       ConsumeParen();
207       SkipUntil(tok::r_paren, false);
208       break;
209     case tok::l_square:
210       // Recursively skip properly-nested square brackets.
211       ConsumeBracket();
212       SkipUntil(tok::r_square, false);
213       break;
214     case tok::l_brace:
215       // Recursively skip properly-nested braces.
216       ConsumeBrace();
217       SkipUntil(tok::r_brace, false);
218       break;
219 
220     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
221     // Since the user wasn't looking for this token (if they were, it would
222     // already be handled), this isn't balanced.  If there is a LHS token at a
223     // higher level, we will assume that this matches the unbalanced token
224     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
225     case tok::r_paren:
226       if (ParenCount && !isFirstTokenSkipped)
227         return false;  // Matches something.
228       ConsumeParen();
229       break;
230     case tok::r_square:
231       if (BracketCount && !isFirstTokenSkipped)
232         return false;  // Matches something.
233       ConsumeBracket();
234       break;
235     case tok::r_brace:
236       if (BraceCount && !isFirstTokenSkipped)
237         return false;  // Matches something.
238       ConsumeBrace();
239       break;
240 
241     case tok::string_literal:
242     case tok::wide_string_literal:
243       ConsumeStringToken();
244       break;
245     case tok::semi:
246       if (StopAtSemi)
247         return false;
248       // FALL THROUGH.
249     default:
250       // Skip this token.
251       ConsumeToken();
252       break;
253     }
254     isFirstTokenSkipped = false;
255   }
256 }
257 
258 //===----------------------------------------------------------------------===//
259 // Scope manipulation
260 //===----------------------------------------------------------------------===//
261 
262 /// EnterScope - Start a new scope.
263 void Parser::EnterScope(unsigned ScopeFlags) {
264   if (NumCachedScopes) {
265     Scope *N = ScopeCache[--NumCachedScopes];
266     N->Init(CurScope, ScopeFlags);
267     CurScope = N;
268   } else {
269     CurScope = new Scope(CurScope, ScopeFlags);
270   }
271 }
272 
273 /// ExitScope - Pop a scope off the scope stack.
274 void Parser::ExitScope() {
275   assert(CurScope && "Scope imbalance!");
276 
277   // Inform the actions module that this scope is going away if there are any
278   // decls in it.
279   if (!CurScope->decl_empty())
280     Actions.ActOnPopScope(Tok.getLocation(), CurScope);
281 
282   Scope *OldScope = CurScope;
283   CurScope = OldScope->getParent();
284 
285   if (NumCachedScopes == ScopeCacheSize)
286     delete OldScope;
287   else
288     ScopeCache[NumCachedScopes++] = OldScope;
289 }
290 
291 
292 
293 
294 //===----------------------------------------------------------------------===//
295 // C99 6.9: External Definitions.
296 //===----------------------------------------------------------------------===//
297 
298 Parser::~Parser() {
299   // If we still have scopes active, delete the scope tree.
300   delete CurScope;
301 
302   // Free the scope cache.
303   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
304     delete ScopeCache[i];
305 
306   // Remove the pragma handlers we installed.
307   PP.RemovePragmaHandler(0, PackHandler.get());
308   PackHandler.reset();
309   PP.RemovePragmaHandler(0, UnusedHandler.get());
310   UnusedHandler.reset();
311   PP.RemovePragmaHandler(0, WeakHandler.get());
312   WeakHandler.reset();
313   PP.RemoveCommentHandler(CommentHandler.get());
314 }
315 
316 /// Initialize - Warm up the parser.
317 ///
318 void Parser::Initialize() {
319   // Prime the lexer look-ahead.
320   ConsumeToken();
321 
322   // Create the translation unit scope.  Install it as the current scope.
323   assert(CurScope == 0 && "A scope is already active?");
324   EnterScope(Scope::DeclScope);
325   Actions.ActOnTranslationUnitScope(Tok.getLocation(), CurScope);
326 
327   if (Tok.is(tok::eof) &&
328       !getLang().CPlusPlus)  // Empty source file is an extension in C
329     Diag(Tok, diag::ext_empty_source_file);
330 
331   // Initialization for Objective-C context sensitive keywords recognition.
332   // Referenced in Parser::ParseObjCTypeQualifierList.
333   if (getLang().ObjC1) {
334     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
335     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
336     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
337     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
338     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
339     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
340   }
341 
342   Ident_super = &PP.getIdentifierTable().get("super");
343 }
344 
345 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
346 /// action tells us to.  This returns true if the EOF was encountered.
347 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
348   Result = DeclGroupPtrTy();
349   if (Tok.is(tok::eof)) {
350     Actions.ActOnEndOfTranslationUnit();
351     return true;
352   }
353 
354   Result = ParseExternalDeclaration();
355   return false;
356 }
357 
358 /// ParseTranslationUnit:
359 ///       translation-unit: [C99 6.9]
360 ///         external-declaration
361 ///         translation-unit external-declaration
362 void Parser::ParseTranslationUnit() {
363   Initialize();
364 
365   DeclGroupPtrTy Res;
366   while (!ParseTopLevelDecl(Res))
367     /*parse them all*/;
368 
369   ExitScope();
370   assert(CurScope == 0 && "Scope imbalance!");
371 }
372 
373 /// ParseExternalDeclaration:
374 ///
375 ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
376 ///         function-definition
377 ///         declaration
378 /// [EXT]   ';'
379 /// [GNU]   asm-definition
380 /// [GNU]   __extension__ external-declaration
381 /// [OBJC]  objc-class-definition
382 /// [OBJC]  objc-class-declaration
383 /// [OBJC]  objc-alias-declaration
384 /// [OBJC]  objc-protocol-definition
385 /// [OBJC]  objc-method-definition
386 /// [OBJC]  @end
387 /// [C++]   linkage-specification
388 /// [GNU] asm-definition:
389 ///         simple-asm-expr ';'
390 ///
391 Parser::DeclGroupPtrTy Parser::ParseExternalDeclaration() {
392   DeclPtrTy SingleDecl;
393   switch (Tok.getKind()) {
394   case tok::semi:
395     Diag(Tok, diag::ext_top_level_semi)
396       << CodeModificationHint::CreateRemoval(SourceRange(Tok.getLocation()));
397     ConsumeToken();
398     // TODO: Invoke action for top-level semicolon.
399     return DeclGroupPtrTy();
400   case tok::r_brace:
401     Diag(Tok, diag::err_expected_external_declaration);
402     ConsumeBrace();
403     return DeclGroupPtrTy();
404   case tok::eof:
405     Diag(Tok, diag::err_expected_external_declaration);
406     return DeclGroupPtrTy();
407   case tok::kw___extension__: {
408     // __extension__ silences extension warnings in the subexpression.
409     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
410     ConsumeToken();
411     return ParseExternalDeclaration();
412   }
413   case tok::kw_asm: {
414     OwningExprResult Result(ParseSimpleAsm());
415 
416     ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
417                      "top-level asm block");
418 
419     if (Result.isInvalid())
420       return DeclGroupPtrTy();
421     SingleDecl = Actions.ActOnFileScopeAsmDecl(Tok.getLocation(), move(Result));
422     break;
423   }
424   case tok::at:
425     // @ is not a legal token unless objc is enabled, no need to check for ObjC.
426     /// FIXME: ParseObjCAtDirectives should return a DeclGroup for things like
427     /// @class foo, bar;
428     SingleDecl = ParseObjCAtDirectives();
429     break;
430   case tok::minus:
431   case tok::plus:
432     if (!getLang().ObjC1) {
433       Diag(Tok, diag::err_expected_external_declaration);
434       ConsumeToken();
435       return DeclGroupPtrTy();
436     }
437     SingleDecl = ParseObjCMethodDefinition();
438     break;
439   case tok::kw_using:
440   case tok::kw_namespace:
441   case tok::kw_typedef:
442   case tok::kw_template:
443   case tok::kw_export:    // As in 'export template'
444   case tok::kw_static_assert:
445     // A function definition cannot start with a these keywords.
446     {
447       SourceLocation DeclEnd;
448       return ParseDeclaration(Declarator::FileContext, DeclEnd);
449     }
450   default:
451     // We can't tell whether this is a function-definition or declaration yet.
452     return ParseDeclarationOrFunctionDefinition();
453   }
454 
455   // This routine returns a DeclGroup, if the thing we parsed only contains a
456   // single decl, convert it now.
457   return Actions.ConvertDeclToDeclGroup(SingleDecl);
458 }
459 
460 /// \brief Determine whether the current token, if it occurs after a
461 /// declarator, continues a declaration or declaration list.
462 bool Parser::isDeclarationAfterDeclarator() {
463   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
464     Tok.is(tok::comma) ||           // int X(),  -> not a function def
465     Tok.is(tok::semi)  ||           // int X();  -> not a function def
466     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
467     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
468     (getLang().CPlusPlus &&
469      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
470 }
471 
472 /// \brief Determine whether the current token, if it occurs after a
473 /// declarator, indicates the start of a function definition.
474 bool Parser::isStartOfFunctionDefinition() {
475   return Tok.is(tok::l_brace) ||    // int X() {}
476     (!getLang().CPlusPlus &&
477      isDeclarationSpecifier()) ||   // int X(f) int f; {}
478     (getLang().CPlusPlus &&
479      (Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
480       Tok.is(tok::kw_try)));        // X() try { ... }
481 }
482 
483 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
484 /// a declaration.  We can't tell which we have until we read up to the
485 /// compound-statement in function-definition. TemplateParams, if
486 /// non-NULL, provides the template parameters when we're parsing a
487 /// C++ template-declaration.
488 ///
489 ///       function-definition: [C99 6.9.1]
490 ///         decl-specs      declarator declaration-list[opt] compound-statement
491 /// [C90] function-definition: [C99 6.7.1] - implicit int result
492 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
493 ///
494 ///       declaration: [C99 6.7]
495 ///         declaration-specifiers init-declarator-list[opt] ';'
496 /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
497 /// [OMP]   threadprivate-directive                              [TODO]
498 ///
499 Parser::DeclGroupPtrTy
500 Parser::ParseDeclarationOrFunctionDefinition(AccessSpecifier AS) {
501   // Parse the common declaration-specifiers piece.
502   DeclSpec DS;
503   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS);
504 
505   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
506   // declaration-specifiers init-declarator-list[opt] ';'
507   if (Tok.is(tok::semi)) {
508     ConsumeToken();
509     DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
510     return Actions.ConvertDeclToDeclGroup(TheDecl);
511   }
512 
513   // ObjC2 allows prefix attributes on class interfaces and protocols.
514   // FIXME: This still needs better diagnostics. We should only accept
515   // attributes here, no types, etc.
516   if (getLang().ObjC2 && Tok.is(tok::at)) {
517     SourceLocation AtLoc = ConsumeToken(); // the "@"
518     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
519         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
520       Diag(Tok, diag::err_objc_unexpected_attr);
521       SkipUntil(tok::semi); // FIXME: better skip?
522       return DeclGroupPtrTy();
523     }
524     const char *PrevSpec = 0;
525     unsigned DiagID;
526     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
527       Diag(AtLoc, DiagID) << PrevSpec;
528 
529     DeclPtrTy TheDecl;
530     if (Tok.isObjCAtKeyword(tok::objc_protocol))
531       TheDecl = ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
532     else
533       TheDecl = ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
534     return Actions.ConvertDeclToDeclGroup(TheDecl);
535   }
536 
537   // If the declspec consisted only of 'extern' and we have a string
538   // literal following it, this must be a C++ linkage specifier like
539   // 'extern "C"'.
540   if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
541       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
542       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
543     DeclPtrTy TheDecl = ParseLinkage(Declarator::FileContext);
544     return Actions.ConvertDeclToDeclGroup(TheDecl);
545   }
546 
547   // Parse the first declarator.
548   Declarator DeclaratorInfo(DS, Declarator::FileContext);
549   ParseDeclarator(DeclaratorInfo);
550   // Error parsing the declarator?
551   if (!DeclaratorInfo.hasName()) {
552     // If so, skip until the semi-colon or a }.
553     SkipUntil(tok::r_brace, true, true);
554     if (Tok.is(tok::semi))
555       ConsumeToken();
556     return DeclGroupPtrTy();
557   }
558 
559   // If we have a declaration or declarator list, handle it.
560   if (isDeclarationAfterDeclarator()) {
561     // Parse the init-declarator-list for a normal declaration.
562     DeclGroupPtrTy DG =
563       ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
564     // Eat the semi colon after the declaration.
565     ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
566     return DG;
567   }
568 
569   if (DeclaratorInfo.isFunctionDeclarator() &&
570       isStartOfFunctionDefinition()) {
571     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
572       Diag(Tok, diag::err_function_declared_typedef);
573 
574       if (Tok.is(tok::l_brace)) {
575         // This recovery skips the entire function body. It would be nice
576         // to simply call ParseFunctionDefinition() below, however Sema
577         // assumes the declarator represents a function, not a typedef.
578         ConsumeBrace();
579         SkipUntil(tok::r_brace, true);
580       } else {
581         SkipUntil(tok::semi);
582       }
583       return DeclGroupPtrTy();
584     }
585     DeclPtrTy TheDecl = ParseFunctionDefinition(DeclaratorInfo);
586     return Actions.ConvertDeclToDeclGroup(TheDecl);
587   }
588 
589   if (DeclaratorInfo.isFunctionDeclarator())
590     Diag(Tok, diag::err_expected_fn_body);
591   else
592     Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
593   SkipUntil(tok::semi);
594   return DeclGroupPtrTy();
595 }
596 
597 /// ParseFunctionDefinition - We parsed and verified that the specified
598 /// Declarator is well formed.  If this is a K&R-style function, read the
599 /// parameters declaration-list, then start the compound-statement.
600 ///
601 ///       function-definition: [C99 6.9.1]
602 ///         decl-specs      declarator declaration-list[opt] compound-statement
603 /// [C90] function-definition: [C99 6.7.1] - implicit int result
604 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
605 /// [C++] function-definition: [C++ 8.4]
606 ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
607 ///         function-body
608 /// [C++] function-definition: [C++ 8.4]
609 ///         decl-specifier-seq[opt] declarator function-try-block
610 ///
611 Parser::DeclPtrTy Parser::ParseFunctionDefinition(Declarator &D,
612                                      const ParsedTemplateInfo &TemplateInfo) {
613   const DeclaratorChunk &FnTypeInfo = D.getTypeObject(0);
614   assert(FnTypeInfo.Kind == DeclaratorChunk::Function &&
615          "This isn't a function declarator!");
616   const DeclaratorChunk::FunctionTypeInfo &FTI = FnTypeInfo.Fun;
617 
618   // If this is C90 and the declspecs were completely missing, fudge in an
619   // implicit int.  We do this here because this is the only place where
620   // declaration-specifiers are completely optional in the grammar.
621   if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) {
622     const char *PrevSpec;
623     unsigned DiagID;
624     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
625                                            D.getIdentifierLoc(),
626                                            PrevSpec, DiagID);
627     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
628   }
629 
630   // If this declaration was formed with a K&R-style identifier list for the
631   // arguments, parse declarations for all of the args next.
632   // int foo(a,b) int a; float b; {}
633   if (!FTI.hasPrototype && FTI.NumArgs != 0)
634     ParseKNRParamDeclarations(D);
635 
636   // We should have either an opening brace or, in a C++ constructor,
637   // we may have a colon.
638   if (Tok.isNot(tok::l_brace) && Tok.isNot(tok::colon) &&
639       Tok.isNot(tok::kw_try)) {
640     Diag(Tok, diag::err_expected_fn_body);
641 
642     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
643     SkipUntil(tok::l_brace, true, true);
644 
645     // If we didn't find the '{', bail out.
646     if (Tok.isNot(tok::l_brace))
647       return DeclPtrTy();
648   }
649 
650   // Enter a scope for the function body.
651   ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
652 
653   // Tell the actions module that we have entered a function definition with the
654   // specified Declarator for the function.
655   DeclPtrTy Res = TemplateInfo.TemplateParams?
656       Actions.ActOnStartOfFunctionTemplateDef(CurScope,
657                               Action::MultiTemplateParamsArg(Actions,
658                                           TemplateInfo.TemplateParams->data(),
659                                          TemplateInfo.TemplateParams->size()),
660                                               D)
661     : Actions.ActOnStartOfFunctionDef(CurScope, D);
662 
663   if (Tok.is(tok::kw_try))
664     return ParseFunctionTryBlock(Res);
665 
666   // If we have a colon, then we're probably parsing a C++
667   // ctor-initializer.
668   if (Tok.is(tok::colon))
669     ParseConstructorInitializer(Res);
670   else
671     Actions.ActOnDefaultCtorInitializers(Res);
672 
673   return ParseFunctionStatementBody(Res);
674 }
675 
676 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
677 /// types for a function with a K&R-style identifier list for arguments.
678 void Parser::ParseKNRParamDeclarations(Declarator &D) {
679   // We know that the top-level of this declarator is a function.
680   DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
681 
682   // Enter function-declaration scope, limiting any declarators to the
683   // function prototype scope, including parameter declarators.
684   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
685 
686   // Read all the argument declarations.
687   while (isDeclarationSpecifier()) {
688     SourceLocation DSStart = Tok.getLocation();
689 
690     // Parse the common declaration-specifiers piece.
691     DeclSpec DS;
692     ParseDeclarationSpecifiers(DS);
693 
694     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
695     // least one declarator'.
696     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
697     // the declarations though.  It's trivial to ignore them, really hard to do
698     // anything else with them.
699     if (Tok.is(tok::semi)) {
700       Diag(DSStart, diag::err_declaration_does_not_declare_param);
701       ConsumeToken();
702       continue;
703     }
704 
705     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
706     // than register.
707     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
708         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
709       Diag(DS.getStorageClassSpecLoc(),
710            diag::err_invalid_storage_class_in_func_decl);
711       DS.ClearStorageClassSpecs();
712     }
713     if (DS.isThreadSpecified()) {
714       Diag(DS.getThreadSpecLoc(),
715            diag::err_invalid_storage_class_in_func_decl);
716       DS.ClearStorageClassSpecs();
717     }
718 
719     // Parse the first declarator attached to this declspec.
720     Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
721     ParseDeclarator(ParmDeclarator);
722 
723     // Handle the full declarator list.
724     while (1) {
725       Action::AttrTy *AttrList;
726       // If attributes are present, parse them.
727       if (Tok.is(tok::kw___attribute))
728         // FIXME: attach attributes too.
729         AttrList = ParseAttributes();
730 
731       // Ask the actions module to compute the type for this declarator.
732       Action::DeclPtrTy Param =
733         Actions.ActOnParamDeclarator(CurScope, ParmDeclarator);
734 
735       if (Param &&
736           // A missing identifier has already been diagnosed.
737           ParmDeclarator.getIdentifier()) {
738 
739         // Scan the argument list looking for the correct param to apply this
740         // type.
741         for (unsigned i = 0; ; ++i) {
742           // C99 6.9.1p6: those declarators shall declare only identifiers from
743           // the identifier list.
744           if (i == FTI.NumArgs) {
745             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
746               << ParmDeclarator.getIdentifier();
747             break;
748           }
749 
750           if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
751             // Reject redefinitions of parameters.
752             if (FTI.ArgInfo[i].Param) {
753               Diag(ParmDeclarator.getIdentifierLoc(),
754                    diag::err_param_redefinition)
755                  << ParmDeclarator.getIdentifier();
756             } else {
757               FTI.ArgInfo[i].Param = Param;
758             }
759             break;
760           }
761         }
762       }
763 
764       // If we don't have a comma, it is either the end of the list (a ';') or
765       // an error, bail out.
766       if (Tok.isNot(tok::comma))
767         break;
768 
769       // Consume the comma.
770       ConsumeToken();
771 
772       // Parse the next declarator.
773       ParmDeclarator.clear();
774       ParseDeclarator(ParmDeclarator);
775     }
776 
777     if (Tok.is(tok::semi)) {
778       ConsumeToken();
779     } else {
780       Diag(Tok, diag::err_parse_error);
781       // Skip to end of block or statement
782       SkipUntil(tok::semi, true);
783       if (Tok.is(tok::semi))
784         ConsumeToken();
785     }
786   }
787 
788   // The actions module must verify that all arguments were declared.
789   Actions.ActOnFinishKNRParamDeclarations(CurScope, D, Tok.getLocation());
790 }
791 
792 
793 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
794 /// allowed to be a wide string, and is not subject to character translation.
795 ///
796 /// [GNU] asm-string-literal:
797 ///         string-literal
798 ///
799 Parser::OwningExprResult Parser::ParseAsmStringLiteral() {
800   if (!isTokenStringLiteral()) {
801     Diag(Tok, diag::err_expected_string_literal);
802     return ExprError();
803   }
804 
805   OwningExprResult Res(ParseStringLiteralExpression());
806   if (Res.isInvalid()) return move(Res);
807 
808   // TODO: Diagnose: wide string literal in 'asm'
809 
810   return move(Res);
811 }
812 
813 /// ParseSimpleAsm
814 ///
815 /// [GNU] simple-asm-expr:
816 ///         'asm' '(' asm-string-literal ')'
817 ///
818 Parser::OwningExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
819   assert(Tok.is(tok::kw_asm) && "Not an asm!");
820   SourceLocation Loc = ConsumeToken();
821 
822   if (Tok.isNot(tok::l_paren)) {
823     Diag(Tok, diag::err_expected_lparen_after) << "asm";
824     return ExprError();
825   }
826 
827   Loc = ConsumeParen();
828 
829   OwningExprResult Result(ParseAsmStringLiteral());
830 
831   if (Result.isInvalid()) {
832     SkipUntil(tok::r_paren, true, true);
833     if (EndLoc)
834       *EndLoc = Tok.getLocation();
835     ConsumeAnyToken();
836   } else {
837     Loc = MatchRHSPunctuation(tok::r_paren, Loc);
838     if (EndLoc)
839       *EndLoc = Loc;
840   }
841 
842   return move(Result);
843 }
844 
845 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
846 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
847 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
848 /// with a single annotation token representing the typename or C++ scope
849 /// respectively.
850 /// This simplifies handling of C++ scope specifiers and allows efficient
851 /// backtracking without the need to re-parse and resolve nested-names and
852 /// typenames.
853 /// It will mainly be called when we expect to treat identifiers as typenames
854 /// (if they are typenames). For example, in C we do not expect identifiers
855 /// inside expressions to be treated as typenames so it will not be called
856 /// for expressions in C.
857 /// The benefit for C/ObjC is that a typename will be annotated and
858 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
859 /// will not be called twice, once to check whether we have a declaration
860 /// specifier, and another one to get the actual type inside
861 /// ParseDeclarationSpecifiers).
862 ///
863 /// This returns true if the token was annotated or an unrecoverable error
864 /// occurs.
865 ///
866 /// Note that this routine emits an error if you call it with ::new or ::delete
867 /// as the current tokens, so only call it in contexts where these are invalid.
868 bool Parser::TryAnnotateTypeOrScopeToken() {
869   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
870           || Tok.is(tok::kw_typename)) &&
871          "Cannot be a type or scope token!");
872 
873   if (Tok.is(tok::kw_typename)) {
874     // Parse a C++ typename-specifier, e.g., "typename T::type".
875     //
876     //   typename-specifier:
877     //     'typename' '::' [opt] nested-name-specifier identifier
878     //     'typename' '::' [opt] nested-name-specifier template [opt]
879     //            simple-template-id
880     SourceLocation TypenameLoc = ConsumeToken();
881     CXXScopeSpec SS;
882     bool HadNestedNameSpecifier = ParseOptionalCXXScopeSpecifier(SS);
883     if (!HadNestedNameSpecifier) {
884       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
885       return false;
886     }
887 
888     TypeResult Ty;
889     if (Tok.is(tok::identifier)) {
890       // FIXME: check whether the next token is '<', first!
891       Ty = Actions.ActOnTypenameType(TypenameLoc, SS, *Tok.getIdentifierInfo(),
892                                      Tok.getLocation());
893     } else if (Tok.is(tok::annot_template_id)) {
894       TemplateIdAnnotation *TemplateId
895         = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
896       if (TemplateId->Kind == TNK_Function_template) {
897         Diag(Tok, diag::err_typename_refers_to_non_type_template)
898           << Tok.getAnnotationRange();
899         return false;
900       }
901 
902       AnnotateTemplateIdTokenAsType(0);
903       assert(Tok.is(tok::annot_typename) &&
904              "AnnotateTemplateIdTokenAsType isn't working properly");
905       if (Tok.getAnnotationValue())
906         Ty = Actions.ActOnTypenameType(TypenameLoc, SS, SourceLocation(),
907                                        Tok.getAnnotationValue());
908       else
909         Ty = true;
910     } else {
911       Diag(Tok, diag::err_expected_type_name_after_typename)
912         << SS.getRange();
913       return false;
914     }
915 
916     Tok.setKind(tok::annot_typename);
917     Tok.setAnnotationValue(Ty.isInvalid()? 0 : Ty.get());
918     Tok.setAnnotationEndLoc(Tok.getLocation());
919     Tok.setLocation(TypenameLoc);
920     PP.AnnotateCachedTokens(Tok);
921     return true;
922   }
923 
924   CXXScopeSpec SS;
925   if (getLang().CPlusPlus)
926     ParseOptionalCXXScopeSpecifier(SS);
927 
928   if (Tok.is(tok::identifier)) {
929     // Determine whether the identifier is a type name.
930     if (TypeTy *Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
931                                          Tok.getLocation(), CurScope, &SS)) {
932       // This is a typename. Replace the current token in-place with an
933       // annotation type token.
934       Tok.setKind(tok::annot_typename);
935       Tok.setAnnotationValue(Ty);
936       Tok.setAnnotationEndLoc(Tok.getLocation());
937       if (SS.isNotEmpty()) // it was a C++ qualified type name.
938         Tok.setLocation(SS.getBeginLoc());
939 
940       // In case the tokens were cached, have Preprocessor replace
941       // them with the annotation token.
942       PP.AnnotateCachedTokens(Tok);
943       return true;
944     }
945 
946     if (!getLang().CPlusPlus) {
947       // If we're in C, we can't have :: tokens at all (the lexer won't return
948       // them).  If the identifier is not a type, then it can't be scope either,
949       // just early exit.
950       return false;
951     }
952 
953     // If this is a template-id, annotate with a template-id or type token.
954     if (NextToken().is(tok::less)) {
955       TemplateTy Template;
956       if (TemplateNameKind TNK
957             = Actions.isTemplateName(*Tok.getIdentifierInfo(),
958                                      CurScope, Template, &SS))
959         if (AnnotateTemplateIdToken(Template, TNK, &SS)) {
960           // If an unrecoverable error occurred, we need to return true here,
961           // because the token stream is in a damaged state.  We may not return
962           // a valid identifier.
963           return Tok.isNot(tok::identifier);
964         }
965     }
966 
967     // The current token, which is either an identifier or a
968     // template-id, is not part of the annotation. Fall through to
969     // push that token back into the stream and complete the C++ scope
970     // specifier annotation.
971   }
972 
973   if (Tok.is(tok::annot_template_id)) {
974     TemplateIdAnnotation *TemplateId
975       = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
976     if (TemplateId->Kind == TNK_Type_template) {
977       // A template-id that refers to a type was parsed into a
978       // template-id annotation in a context where we weren't allowed
979       // to produce a type annotation token. Update the template-id
980       // annotation token to a type annotation token now.
981       AnnotateTemplateIdTokenAsType(&SS);
982       return true;
983     }
984   }
985 
986   if (SS.isEmpty())
987     return Tok.isNot(tok::identifier) && Tok.isNot(tok::coloncolon);
988 
989   // A C++ scope specifier that isn't followed by a typename.
990   // Push the current token back into the token stream (or revert it if it is
991   // cached) and use an annotation scope token for current token.
992   if (PP.isBacktrackEnabled())
993     PP.RevertCachedTokens(1);
994   else
995     PP.EnterToken(Tok);
996   Tok.setKind(tok::annot_cxxscope);
997   Tok.setAnnotationValue(SS.getScopeRep());
998   Tok.setAnnotationRange(SS.getRange());
999 
1000   // In case the tokens were cached, have Preprocessor replace them with the
1001   // annotation token.
1002   PP.AnnotateCachedTokens(Tok);
1003   return true;
1004 }
1005 
1006 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1007 /// annotates C++ scope specifiers and template-ids.  This returns
1008 /// true if the token was annotated or there was an error that could not be
1009 /// recovered from.
1010 ///
1011 /// Note that this routine emits an error if you call it with ::new or ::delete
1012 /// as the current tokens, so only call it in contexts where these are invalid.
1013 bool Parser::TryAnnotateCXXScopeToken() {
1014   assert(getLang().CPlusPlus &&
1015          "Call sites of this function should be guarded by checking for C++");
1016   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
1017          "Cannot be a type or scope token!");
1018 
1019   CXXScopeSpec SS;
1020   if (!ParseOptionalCXXScopeSpecifier(SS))
1021     return Tok.is(tok::annot_template_id);
1022 
1023   // Push the current token back into the token stream (or revert it if it is
1024   // cached) and use an annotation scope token for current token.
1025   if (PP.isBacktrackEnabled())
1026     PP.RevertCachedTokens(1);
1027   else
1028     PP.EnterToken(Tok);
1029   Tok.setKind(tok::annot_cxxscope);
1030   Tok.setAnnotationValue(SS.getScopeRep());
1031   Tok.setAnnotationRange(SS.getRange());
1032 
1033   // In case the tokens were cached, have Preprocessor replace them with the
1034   // annotation token.
1035   PP.AnnotateCachedTokens(Tok);
1036   return true;
1037 }
1038