Parser.cpp revision effa8d1c97b00a3f53e972b0e61d9aade5ea1c57
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/Basic/Diagnostic.h"
16#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
18#include "ExtensionRAIIObject.h"
19#include "ParsePragma.h"
20using namespace clang;
21
22Parser::Parser(Preprocessor &pp, Action &actions)
23  : PP(pp), Actions(actions), Diags(PP.getDiagnostics()) {
24  Tok.setKind(tok::eof);
25  CurScope = 0;
26  NumCachedScopes = 0;
27  ParenCount = BracketCount = BraceCount = 0;
28  ObjCImpDecl = 0;
29
30  // Add #pragma handlers. These are removed and destroyed in the
31  // destructor.
32  PackHandler =
33    new PragmaPackHandler(&PP.getIdentifierTable().get("pack"), actions);
34  PP.AddPragmaHandler(0, PackHandler);
35
36  // Instantiate a LexedMethodsForTopClass for all the non-nested classes.
37  PushTopClassStack();
38}
39
40///  Out-of-line virtual destructor to provide home for Action class.
41ActionBase::~ActionBase() {}
42
43///  Out-of-line virtual destructor to provide home for Action class.
44Action::~Action() {}
45
46
47DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
48  return Diags.Report(FullSourceLoc(Loc,PP.getSourceManager()), DiagID);
49}
50
51DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
52  return Diag(Tok.getLocation(), DiagID);
53}
54
55/// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
56/// this helper function matches and consumes the specified RHS token if
57/// present.  If not present, it emits the specified diagnostic indicating
58/// that the parser failed to match the RHS of the token at LHSLoc.  LHSName
59/// should be the name of the unmatched LHS token.
60SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
61                                           SourceLocation LHSLoc) {
62
63  if (Tok.is(RHSTok))
64    return ConsumeAnyToken();
65
66  SourceLocation R = Tok.getLocation();
67  const char *LHSName = "unknown";
68  diag::kind DID = diag::err_parse_error;
69  switch (RHSTok) {
70  default: break;
71  case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
72  case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
73  case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
74  case tok::greater:  LHSName = "<"; DID = diag::err_expected_greater; break;
75  }
76  Diag(Tok, DID);
77  Diag(LHSLoc, diag::note_matching) << LHSName;
78  SkipUntil(RHSTok);
79  return R;
80}
81
82/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
83/// input.  If so, it is consumed and false is returned.
84///
85/// If the input is malformed, this emits the specified diagnostic.  Next, if
86/// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
87/// returned.
88bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
89                              const char *Msg, tok::TokenKind SkipToTok) {
90  if (Tok.is(ExpectedTok)) {
91    ConsumeAnyToken();
92    return false;
93  }
94
95  Diag(Tok, DiagID) << Msg;
96  if (SkipToTok != tok::unknown)
97    SkipUntil(SkipToTok);
98  return true;
99}
100
101//===----------------------------------------------------------------------===//
102// Error recovery.
103//===----------------------------------------------------------------------===//
104
105/// SkipUntil - Read tokens until we get to the specified token, then consume
106/// it (unless DontConsume is true).  Because we cannot guarantee that the
107/// token will ever occur, this skips to the next token, or to some likely
108/// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
109/// character.
110///
111/// If SkipUntil finds the specified token, it returns true, otherwise it
112/// returns false.
113bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
114                       bool StopAtSemi, bool DontConsume) {
115  // We always want this function to skip at least one token if the first token
116  // isn't T and if not at EOF.
117  bool isFirstTokenSkipped = true;
118  while (1) {
119    // If we found one of the tokens, stop and return true.
120    for (unsigned i = 0; i != NumToks; ++i) {
121      if (Tok.is(Toks[i])) {
122        if (DontConsume) {
123          // Noop, don't consume the token.
124        } else {
125          ConsumeAnyToken();
126        }
127        return true;
128      }
129    }
130
131    switch (Tok.getKind()) {
132    case tok::eof:
133      // Ran out of tokens.
134      return false;
135
136    case tok::l_paren:
137      // Recursively skip properly-nested parens.
138      ConsumeParen();
139      SkipUntil(tok::r_paren, false);
140      break;
141    case tok::l_square:
142      // Recursively skip properly-nested square brackets.
143      ConsumeBracket();
144      SkipUntil(tok::r_square, false);
145      break;
146    case tok::l_brace:
147      // Recursively skip properly-nested braces.
148      ConsumeBrace();
149      SkipUntil(tok::r_brace, false);
150      break;
151
152    // Okay, we found a ']' or '}' or ')', which we think should be balanced.
153    // Since the user wasn't looking for this token (if they were, it would
154    // already be handled), this isn't balanced.  If there is a LHS token at a
155    // higher level, we will assume that this matches the unbalanced token
156    // and return it.  Otherwise, this is a spurious RHS token, which we skip.
157    case tok::r_paren:
158      if (ParenCount && !isFirstTokenSkipped)
159        return false;  // Matches something.
160      ConsumeParen();
161      break;
162    case tok::r_square:
163      if (BracketCount && !isFirstTokenSkipped)
164        return false;  // Matches something.
165      ConsumeBracket();
166      break;
167    case tok::r_brace:
168      if (BraceCount && !isFirstTokenSkipped)
169        return false;  // Matches something.
170      ConsumeBrace();
171      break;
172
173    case tok::string_literal:
174    case tok::wide_string_literal:
175      ConsumeStringToken();
176      break;
177    case tok::semi:
178      if (StopAtSemi)
179        return false;
180      // FALL THROUGH.
181    default:
182      // Skip this token.
183      ConsumeToken();
184      break;
185    }
186    isFirstTokenSkipped = false;
187  }
188}
189
190//===----------------------------------------------------------------------===//
191// Scope manipulation
192//===----------------------------------------------------------------------===//
193
194/// EnterScope - Start a new scope.
195void Parser::EnterScope(unsigned ScopeFlags) {
196  if (NumCachedScopes) {
197    Scope *N = ScopeCache[--NumCachedScopes];
198    N->Init(CurScope, ScopeFlags);
199    CurScope = N;
200  } else {
201    CurScope = new Scope(CurScope, ScopeFlags);
202  }
203}
204
205/// ExitScope - Pop a scope off the scope stack.
206void Parser::ExitScope() {
207  assert(CurScope && "Scope imbalance!");
208
209  // Inform the actions module that this scope is going away if there are any
210  // decls in it.
211  if (!CurScope->decl_empty())
212    Actions.ActOnPopScope(Tok.getLocation(), CurScope);
213
214  Scope *OldScope = CurScope;
215  CurScope = OldScope->getParent();
216
217  if (NumCachedScopes == ScopeCacheSize)
218    delete OldScope;
219  else
220    ScopeCache[NumCachedScopes++] = OldScope;
221}
222
223
224
225
226//===----------------------------------------------------------------------===//
227// C99 6.9: External Definitions.
228//===----------------------------------------------------------------------===//
229
230Parser::~Parser() {
231  // If we still have scopes active, delete the scope tree.
232  delete CurScope;
233
234  // Free the scope cache.
235  for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
236    delete ScopeCache[i];
237
238  // Remove the pragma handlers we installed.
239  PP.RemovePragmaHandler(0, PackHandler);
240  delete PackHandler;
241}
242
243/// Initialize - Warm up the parser.
244///
245void Parser::Initialize() {
246  // Prime the lexer look-ahead.
247  ConsumeToken();
248
249  // Create the translation unit scope.  Install it as the current scope.
250  assert(CurScope == 0 && "A scope is already active?");
251  EnterScope(Scope::DeclScope);
252  Actions.ActOnTranslationUnitScope(Tok.getLocation(), CurScope);
253
254  if (Tok.is(tok::eof) &&
255      !getLang().CPlusPlus)  // Empty source file is an extension in C
256    Diag(Tok, diag::ext_empty_source_file);
257
258  // Initialization for Objective-C context sensitive keywords recognition.
259  // Referenced in Parser::ParseObjCTypeQualifierList.
260  if (getLang().ObjC1) {
261    ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
262    ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
263    ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
264    ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
265    ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
266    ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
267  }
268
269  Ident_super = &PP.getIdentifierTable().get("super");
270}
271
272/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
273/// action tells us to.  This returns true if the EOF was encountered.
274bool Parser::ParseTopLevelDecl(DeclTy*& Result) {
275  Result = 0;
276  if (Tok.is(tok::eof)) {
277    Actions.ActOnEndOfTranslationUnit();
278    return true;
279  }
280
281  Result = ParseExternalDeclaration();
282  return false;
283}
284
285/// ParseTranslationUnit:
286///       translation-unit: [C99 6.9]
287///         external-declaration
288///         translation-unit external-declaration
289void Parser::ParseTranslationUnit() {
290  Initialize();  // pushes a scope.
291
292  DeclTy *Res;
293  while (!ParseTopLevelDecl(Res))
294    /*parse them all*/;
295
296  ExitScope();
297  assert(CurScope == 0 && "Scope imbalance!");
298}
299
300/// ParseExternalDeclaration:
301///
302///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
303///         function-definition
304///         declaration
305/// [EXT]   ';'
306/// [GNU]   asm-definition
307/// [GNU]   __extension__ external-declaration
308/// [OBJC]  objc-class-definition
309/// [OBJC]  objc-class-declaration
310/// [OBJC]  objc-alias-declaration
311/// [OBJC]  objc-protocol-definition
312/// [OBJC]  objc-method-definition
313/// [OBJC]  @end
314/// [C++]   linkage-specification
315/// [GNU] asm-definition:
316///         simple-asm-expr ';'
317///
318Parser::DeclTy *Parser::ParseExternalDeclaration() {
319  switch (Tok.getKind()) {
320  case tok::semi:
321    Diag(Tok, diag::ext_top_level_semi);
322    ConsumeToken();
323    // TODO: Invoke action for top-level semicolon.
324    return 0;
325  case tok::r_brace:
326    Diag(Tok, diag::err_expected_external_declaration);
327    ConsumeBrace();
328    return 0;
329  case tok::eof:
330    Diag(Tok, diag::err_expected_external_declaration);
331    return 0;
332  case tok::kw___extension__: {
333    // __extension__ silences extension warnings in the subexpression.
334    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
335    ConsumeToken();
336    return ParseExternalDeclaration();
337  }
338  case tok::kw_asm: {
339    OwningExprResult Result(ParseSimpleAsm());
340
341    ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
342                     "top-level asm block");
343
344    if (!Result.isInvalid())
345      return Actions.ActOnFileScopeAsmDecl(Tok.getLocation(), Result.release());
346    return 0;
347  }
348  case tok::at:
349    // @ is not a legal token unless objc is enabled, no need to check.
350    return ParseObjCAtDirectives();
351  case tok::minus:
352  case tok::plus:
353    if (getLang().ObjC1)
354      return ParseObjCMethodDefinition();
355    else {
356      Diag(Tok, diag::err_expected_external_declaration);
357      ConsumeToken();
358    }
359    return 0;
360  case tok::kw_namespace:
361  case tok::kw_typedef:
362  case tok::kw_template:
363  case tok::kw_export:    // As in 'export template'
364    // A function definition cannot start with a these keywords.
365    return ParseDeclaration(Declarator::FileContext);
366
367  default:
368    // We can't tell whether this is a function-definition or declaration yet.
369    return ParseDeclarationOrFunctionDefinition();
370  }
371}
372
373/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
374/// a declaration.  We can't tell which we have until we read up to the
375/// compound-statement in function-definition.
376///
377///       function-definition: [C99 6.9.1]
378///         decl-specs      declarator declaration-list[opt] compound-statement
379/// [C90] function-definition: [C99 6.7.1] - implicit int result
380/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
381///
382///       declaration: [C99 6.7]
383///         declaration-specifiers init-declarator-list[opt] ';'
384/// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
385/// [OMP]   threadprivate-directive                              [TODO]
386///
387Parser::DeclTy *Parser::ParseDeclarationOrFunctionDefinition() {
388  // Parse the common declaration-specifiers piece.
389  DeclSpec DS;
390  ParseDeclarationSpecifiers(DS);
391
392  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
393  // declaration-specifiers init-declarator-list[opt] ';'
394  if (Tok.is(tok::semi)) {
395    ConsumeToken();
396    return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
397  }
398
399  // ObjC2 allows prefix attributes on class interfaces and protocols.
400  // FIXME: This still needs better diagnostics. We should only accept
401  // attributes here, no types, etc.
402  if (getLang().ObjC2 && Tok.is(tok::at)) {
403    SourceLocation AtLoc = ConsumeToken(); // the "@"
404    if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
405        !Tok.isObjCAtKeyword(tok::objc_protocol)) {
406      Diag(Tok, diag::err_objc_unexpected_attr);
407      SkipUntil(tok::semi); // FIXME: better skip?
408      return 0;
409    }
410    const char *PrevSpec = 0;
411    if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec))
412      Diag(AtLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
413    if (Tok.isObjCAtKeyword(tok::objc_protocol))
414      return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
415    return ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
416  }
417
418  // If the declspec consisted only of 'extern' and we have a string
419  // literal following it, this must be a C++ linkage specifier like
420  // 'extern "C"'.
421  if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
422      DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
423      DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier)
424    return ParseLinkage(Declarator::FileContext);
425
426  // Parse the first declarator.
427  Declarator DeclaratorInfo(DS, Declarator::FileContext);
428  ParseDeclarator(DeclaratorInfo);
429  // Error parsing the declarator?
430  if (!DeclaratorInfo.hasName()) {
431    // If so, skip until the semi-colon or a }.
432    SkipUntil(tok::r_brace, true, true);
433    if (Tok.is(tok::semi))
434      ConsumeToken();
435    return 0;
436  }
437
438  // If the declarator is the start of a function definition, handle it.
439  if (Tok.is(tok::equal) ||           // int X()=  -> not a function def
440      Tok.is(tok::comma) ||           // int X(),  -> not a function def
441      Tok.is(tok::semi)  ||           // int X();  -> not a function def
442      Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
443      Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
444      (getLang().CPlusPlus &&
445       Tok.is(tok::l_paren)) ) {      // int X(0) -> not a function def [C++]
446    // FALL THROUGH.
447  } else if (DeclaratorInfo.isFunctionDeclarator() &&
448             (Tok.is(tok::l_brace) ||             // int X() {}
449              ( !getLang().CPlusPlus &&
450                isDeclarationSpecifier() ))) {    // int X(f) int f; {}
451    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
452      Diag(Tok, diag::err_function_declared_typedef);
453
454      if (Tok.is(tok::l_brace)) {
455        // This recovery skips the entire function body. It would be nice
456        // to simply call ParseFunctionDefinition() below, however Sema
457        // assumes the declarator represents a function, not a typedef.
458        ConsumeBrace();
459        SkipUntil(tok::r_brace, true);
460      } else {
461        SkipUntil(tok::semi);
462      }
463      return 0;
464    }
465    return ParseFunctionDefinition(DeclaratorInfo);
466  } else {
467    if (DeclaratorInfo.isFunctionDeclarator())
468      Diag(Tok, diag::err_expected_fn_body);
469    else
470      Diag(Tok, diag::err_expected_after_declarator);
471    SkipUntil(tok::semi);
472    return 0;
473  }
474
475  // Parse the init-declarator-list for a normal declaration.
476  return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
477}
478
479/// ParseFunctionDefinition - We parsed and verified that the specified
480/// Declarator is well formed.  If this is a K&R-style function, read the
481/// parameters declaration-list, then start the compound-statement.
482///
483///       function-definition: [C99 6.9.1]
484///         decl-specs      declarator declaration-list[opt] compound-statement
485/// [C90] function-definition: [C99 6.7.1] - implicit int result
486/// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
487/// [C++] function-definition: [C++ 8.4]
488///         decl-specifier-seq[opt] declarator ctor-initializer[opt] function-body
489/// [C++] function-definition: [C++ 8.4]
490///         decl-specifier-seq[opt] declarator function-try-block [TODO]
491///
492Parser::DeclTy *Parser::ParseFunctionDefinition(Declarator &D) {
493  const DeclaratorChunk &FnTypeInfo = D.getTypeObject(0);
494  assert(FnTypeInfo.Kind == DeclaratorChunk::Function &&
495         "This isn't a function declarator!");
496  const DeclaratorChunk::FunctionTypeInfo &FTI = FnTypeInfo.Fun;
497
498  // If this is C90 and the declspecs were completely missing, fudge in an
499  // implicit int.  We do this here because this is the only place where
500  // declaration-specifiers are completely optional in the grammar.
501  if (getLang().ImplicitInt && D.getDeclSpec().getParsedSpecifiers() == 0) {
502    const char *PrevSpec;
503    D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
504                                           D.getIdentifierLoc(),
505                                           PrevSpec);
506  }
507
508  // If this declaration was formed with a K&R-style identifier list for the
509  // arguments, parse declarations for all of the args next.
510  // int foo(a,b) int a; float b; {}
511  if (!FTI.hasPrototype && FTI.NumArgs != 0)
512    ParseKNRParamDeclarations(D);
513
514  // We should have either an opening brace or, in a C++ constructor,
515  // we may have a colon.
516  // FIXME: In C++, we might also find the 'try' keyword.
517  if (Tok.isNot(tok::l_brace) && Tok.isNot(tok::colon)) {
518    Diag(Tok, diag::err_expected_fn_body);
519
520    // Skip over garbage, until we get to '{'.  Don't eat the '{'.
521    SkipUntil(tok::l_brace, true, true);
522
523    // If we didn't find the '{', bail out.
524    if (Tok.isNot(tok::l_brace))
525      return 0;
526  }
527
528  // Enter a scope for the function body.
529  EnterScope(Scope::FnScope|Scope::DeclScope);
530
531  // Tell the actions module that we have entered a function definition with the
532  // specified Declarator for the function.
533  DeclTy *Res = Actions.ActOnStartOfFunctionDef(CurScope, D);
534
535  // If we have a colon, then we're probably parsing a C++
536  // ctor-initializer.
537  if (Tok.is(tok::colon))
538    ParseConstructorInitializer(Res);
539
540  SourceLocation BraceLoc = Tok.getLocation();
541  return ParseFunctionStatementBody(Res, BraceLoc, BraceLoc);
542}
543
544/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
545/// types for a function with a K&R-style identifier list for arguments.
546void Parser::ParseKNRParamDeclarations(Declarator &D) {
547  // We know that the top-level of this declarator is a function.
548  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
549
550  // Enter function-declaration scope, limiting any declarators to the
551  // function prototype scope, including parameter declarators.
552  EnterScope(Scope::FnScope|Scope::DeclScope);
553
554  // Read all the argument declarations.
555  while (isDeclarationSpecifier()) {
556    SourceLocation DSStart = Tok.getLocation();
557
558    // Parse the common declaration-specifiers piece.
559    DeclSpec DS;
560    ParseDeclarationSpecifiers(DS);
561
562    // C99 6.9.1p6: 'each declaration in the declaration list shall have at
563    // least one declarator'.
564    // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
565    // the declarations though.  It's trivial to ignore them, really hard to do
566    // anything else with them.
567    if (Tok.is(tok::semi)) {
568      Diag(DSStart, diag::err_declaration_does_not_declare_param);
569      ConsumeToken();
570      continue;
571    }
572
573    // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
574    // than register.
575    if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
576        DS.getStorageClassSpec() != DeclSpec::SCS_register) {
577      Diag(DS.getStorageClassSpecLoc(),
578           diag::err_invalid_storage_class_in_func_decl);
579      DS.ClearStorageClassSpecs();
580    }
581    if (DS.isThreadSpecified()) {
582      Diag(DS.getThreadSpecLoc(),
583           diag::err_invalid_storage_class_in_func_decl);
584      DS.ClearStorageClassSpecs();
585    }
586
587    // Parse the first declarator attached to this declspec.
588    Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
589    ParseDeclarator(ParmDeclarator);
590
591    // Handle the full declarator list.
592    while (1) {
593      DeclTy *AttrList;
594      // If attributes are present, parse them.
595      if (Tok.is(tok::kw___attribute))
596        // FIXME: attach attributes too.
597        AttrList = ParseAttributes();
598
599      // Ask the actions module to compute the type for this declarator.
600      Action::DeclTy *Param =
601        Actions.ActOnParamDeclarator(CurScope, ParmDeclarator);
602
603      if (Param &&
604          // A missing identifier has already been diagnosed.
605          ParmDeclarator.getIdentifier()) {
606
607        // Scan the argument list looking for the correct param to apply this
608        // type.
609        for (unsigned i = 0; ; ++i) {
610          // C99 6.9.1p6: those declarators shall declare only identifiers from
611          // the identifier list.
612          if (i == FTI.NumArgs) {
613            Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
614              << ParmDeclarator.getIdentifier();
615            break;
616          }
617
618          if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
619            // Reject redefinitions of parameters.
620            if (FTI.ArgInfo[i].Param) {
621              Diag(ParmDeclarator.getIdentifierLoc(),
622                   diag::err_param_redefinition)
623                 << ParmDeclarator.getIdentifier();
624            } else {
625              FTI.ArgInfo[i].Param = Param;
626            }
627            break;
628          }
629        }
630      }
631
632      // If we don't have a comma, it is either the end of the list (a ';') or
633      // an error, bail out.
634      if (Tok.isNot(tok::comma))
635        break;
636
637      // Consume the comma.
638      ConsumeToken();
639
640      // Parse the next declarator.
641      ParmDeclarator.clear();
642      ParseDeclarator(ParmDeclarator);
643    }
644
645    if (Tok.is(tok::semi)) {
646      ConsumeToken();
647    } else {
648      Diag(Tok, diag::err_parse_error);
649      // Skip to end of block or statement
650      SkipUntil(tok::semi, true);
651      if (Tok.is(tok::semi))
652        ConsumeToken();
653    }
654  }
655
656  // Leave prototype scope.
657  ExitScope();
658
659  // The actions module must verify that all arguments were declared.
660}
661
662
663/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
664/// allowed to be a wide string, and is not subject to character translation.
665///
666/// [GNU] asm-string-literal:
667///         string-literal
668///
669Parser::OwningExprResult Parser::ParseAsmStringLiteral() {
670  if (!isTokenStringLiteral()) {
671    Diag(Tok, diag::err_expected_string_literal);
672    return OwningExprResult(true);
673  }
674
675  OwningExprResult Res(Actions, ParseStringLiteralExpression());
676  if (Res.isInvalid()) return move(Res);
677
678  // TODO: Diagnose: wide string literal in 'asm'
679
680  return move(Res);
681}
682
683/// ParseSimpleAsm
684///
685/// [GNU] simple-asm-expr:
686///         'asm' '(' asm-string-literal ')'
687///
688Parser::OwningExprResult Parser::ParseSimpleAsm() {
689  assert(Tok.is(tok::kw_asm) && "Not an asm!");
690  SourceLocation Loc = ConsumeToken();
691
692  if (Tok.isNot(tok::l_paren)) {
693    Diag(Tok, diag::err_expected_lparen_after) << "asm";
694    return OwningExprResult(true);
695  }
696
697  ConsumeParen();
698
699  OwningExprResult Result(ParseAsmStringLiteral());
700
701  if (Result.isInvalid())
702    SkipUntil(tok::r_paren);
703  else
704    MatchRHSPunctuation(tok::r_paren, Loc);
705
706  return move(Result);
707}
708
709/// TryAnnotateTypeOrScopeToken - If the current token position is on a
710/// typename (possibly qualified in C++) or a C++ scope specifier not followed
711/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
712/// with a single annotation token representing the typename or C++ scope
713/// respectively.
714/// This simplifies handling of C++ scope specifiers and allows efficient
715/// backtracking without the need to re-parse and resolve nested-names and
716/// typenames.
717/// It will mainly be called when we expect to treat identifiers as typenames
718/// (if they are typenames). For example, in C we do not expect identifiers
719/// inside expressions to be treated as typenames so it will not be called
720/// for expressions in C.
721/// The benefit for C/ObjC is that a typename will be annotated and
722/// Actions.isTypeName will not be needed to be called again (e.g. isTypeName
723/// will not be called twice, once to check whether we have a declaration
724/// specifier, and another one to get the actual type inside
725/// ParseDeclarationSpecifiers).
726void Parser::TryAnnotateTypeOrScopeToken() {
727  if (Tok.is(tok::annot_qualtypename) || Tok.is(tok::annot_cxxscope))
728    return;
729
730  CXXScopeSpec SS;
731  if (getLang().CPlusPlus)
732    MaybeParseCXXScopeSpecifier(SS);
733
734  if (Tok.is(tok::identifier)) {
735    TypeTy *Ty = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope, &SS);
736    if (Ty) {
737      // This is a typename. Replace the current token in-place with an
738      // annotation type token.
739      Tok.setKind(tok::annot_qualtypename);
740      Tok.setAnnotationValue(Ty);
741      Tok.setAnnotationEndLoc(Tok.getLocation());
742      if (SS.isNotEmpty()) // it was a C++ qualified type name.
743        Tok.setLocation(SS.getBeginLoc());
744
745      // In case the tokens were cached, have Preprocessor replace them with the
746      // annotation token.
747      PP.AnnotateCachedTokens(Tok);
748      return;
749    }
750  }
751
752  if (SS.isNotEmpty()) {
753    // A C++ scope specifier that isn't followed by a typename.
754    // Push the current token back into the token stream (or revert it if it is
755    // cached) and use an annotation scope token for current token.
756    if (PP.isBacktrackEnabled())
757      PP.RevertCachedTokens(1);
758    else
759      PP.EnterToken(Tok);
760    Tok.setKind(tok::annot_cxxscope);
761    Tok.setAnnotationValue(SS.getScopeRep());
762    Tok.setAnnotationRange(SS.getRange());
763
764    // In case the tokens were cached, have Preprocessor replace them with the
765    // annotation token.
766    PP.AnnotateCachedTokens(Tok);
767  }
768}
769
770/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
771/// annotates C++ scope specifiers.
772void Parser::TryAnnotateCXXScopeToken() {
773  assert(getLang().CPlusPlus &&
774         "Call sites of this function should be guarded by checking for C++.");
775
776  if (Tok.is(tok::annot_cxxscope))
777    return;
778
779  CXXScopeSpec SS;
780  if (MaybeParseCXXScopeSpecifier(SS)) {
781
782    // Push the current token back into the token stream (or revert it if it is
783    // cached) and use an annotation scope token for current token.
784    if (PP.isBacktrackEnabled())
785      PP.RevertCachedTokens(1);
786    else
787      PP.EnterToken(Tok);
788    Tok.setKind(tok::annot_cxxscope);
789    Tok.setAnnotationValue(SS.getScopeRep());
790    Tok.setAnnotationRange(SS.getRange());
791
792    // In case the tokens were cached, have Preprocessor replace them with the
793    // annotation token.
794    PP.AnnotateCachedTokens(Tok);
795  }
796}
797