blob: 7b09d2105c2fb23cfdb3aa47831f67294031a56e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Parser.cpp - C Language Family Parser ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner500d3292009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
Chris Lattnerc46d1a12008-10-20 06:45:43 +000018#include "ExtensionRAIIObject.h"
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +000019#include "ParsePragma.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020using namespace clang;
21
22Parser::Parser(Preprocessor &pp, Action &actions)
Douglas Gregor55f6b142009-02-09 18:46:07 +000023 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
24 GreaterThanIsOperator(true) {
Reid Spencer5f016e22007-07-11 17:01:13 +000025 Tok.setKind(tok::eof);
26 CurScope = 0;
Chris Lattner9e344c62007-07-15 00:04:39 +000027 NumCachedScopes = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000028 ParenCount = BracketCount = BraceCount = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000029 ObjCImpDecl = 0;
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +000030
31 // Add #pragma handlers. These are removed and destroyed in the
32 // destructor.
33 PackHandler =
34 new PragmaPackHandler(&PP.getIdentifierTable().get("pack"), actions);
35 PP.AddPragmaHandler(0, PackHandler);
36
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +000037 // Instantiate a LexedMethodsForTopClass for all the non-nested classes.
38 PushTopClassStack();
Reid Spencer5f016e22007-07-11 17:01:13 +000039}
40
41/// Out-of-line virtual destructor to provide home for Action class.
Sebastian Redl7f792fa2008-12-09 19:36:21 +000042ActionBase::~ActionBase() {}
43
44/// Out-of-line virtual destructor to provide home for Action class.
Reid Spencer5f016e22007-07-11 17:01:13 +000045Action::~Action() {}
46
Douglas Gregorf780abc2008-12-30 03:27:21 +000047// Defined out-of-line here because of dependecy on AttributeList
48Action::DeclTy *Action::ActOnUsingDirective(Scope *CurScope,
49 SourceLocation UsingLoc,
50 SourceLocation NamespcLoc,
51 const CXXScopeSpec &SS,
52 SourceLocation IdentLoc,
53 IdentifierInfo *NamespcName,
54 AttributeList *AttrList) {
55
56 // FIXME: Parser seems to assume that Action::ActOn* takes ownership over
57 // passed AttributeList, however other actions don't free it, is it
58 // temporary state or bug?
59 delete AttrList;
60 return 0;
61}
Reid Spencer5f016e22007-07-11 17:01:13 +000062
Chris Lattner3cbfe2c2008-11-22 00:59:29 +000063DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
Chris Lattner1ab3b962008-11-18 07:48:38 +000064 return Diags.Report(FullSourceLoc(Loc,PP.getSourceManager()), DiagID);
65}
66
Chris Lattner3cbfe2c2008-11-22 00:59:29 +000067DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
Chris Lattner1ab3b962008-11-18 07:48:38 +000068 return Diag(Tok.getLocation(), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +000069}
70
71/// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
72/// this helper function matches and consumes the specified RHS token if
73/// present. If not present, it emits the specified diagnostic indicating
74/// that the parser failed to match the RHS of the token at LHSLoc. LHSName
75/// should be the name of the unmatched LHS token.
76SourceLocation Parser::MatchRHSPunctuation(tok::TokenKind RHSTok,
77 SourceLocation LHSLoc) {
Mike Stumpa6f01772008-06-19 19:28:49 +000078
Chris Lattner00073222007-10-09 17:23:58 +000079 if (Tok.is(RHSTok))
Reid Spencer5f016e22007-07-11 17:01:13 +000080 return ConsumeAnyToken();
Mike Stumpa6f01772008-06-19 19:28:49 +000081
Reid Spencer5f016e22007-07-11 17:01:13 +000082 SourceLocation R = Tok.getLocation();
83 const char *LHSName = "unknown";
84 diag::kind DID = diag::err_parse_error;
85 switch (RHSTok) {
86 default: break;
87 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
88 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
89 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
90 case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break;
91 }
92 Diag(Tok, DID);
Chris Lattner28eb7e92008-11-23 23:17:07 +000093 Diag(LHSLoc, diag::note_matching) << LHSName;
Reid Spencer5f016e22007-07-11 17:01:13 +000094 SkipUntil(RHSTok);
95 return R;
96}
97
98/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
99/// input. If so, it is consumed and false is returned.
100///
101/// If the input is malformed, this emits the specified diagnostic. Next, if
102/// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
103/// returned.
104bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
105 const char *Msg, tok::TokenKind SkipToTok) {
Chris Lattner00073222007-10-09 17:23:58 +0000106 if (Tok.is(ExpectedTok)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 ConsumeAnyToken();
108 return false;
109 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000110
Chris Lattner1ab3b962008-11-18 07:48:38 +0000111 Diag(Tok, DiagID) << Msg;
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 if (SkipToTok != tok::unknown)
113 SkipUntil(SkipToTok);
114 return true;
115}
116
117//===----------------------------------------------------------------------===//
118// Error recovery.
119//===----------------------------------------------------------------------===//
120
121/// SkipUntil - Read tokens until we get to the specified token, then consume
Chris Lattner012cf462007-07-24 17:03:04 +0000122/// it (unless DontConsume is true). Because we cannot guarantee that the
Reid Spencer5f016e22007-07-11 17:01:13 +0000123/// token will ever occur, this skips to the next token, or to some likely
124/// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
125/// character.
Mike Stumpa6f01772008-06-19 19:28:49 +0000126///
Reid Spencer5f016e22007-07-11 17:01:13 +0000127/// If SkipUntil finds the specified token, it returns true, otherwise it
Mike Stumpa6f01772008-06-19 19:28:49 +0000128/// returns false.
Reid Spencer5f016e22007-07-11 17:01:13 +0000129bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
130 bool StopAtSemi, bool DontConsume) {
131 // We always want this function to skip at least one token if the first token
132 // isn't T and if not at EOF.
133 bool isFirstTokenSkipped = true;
134 while (1) {
135 // If we found one of the tokens, stop and return true.
136 for (unsigned i = 0; i != NumToks; ++i) {
Chris Lattner00073222007-10-09 17:23:58 +0000137 if (Tok.is(Toks[i])) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 if (DontConsume) {
139 // Noop, don't consume the token.
140 } else {
141 ConsumeAnyToken();
142 }
143 return true;
144 }
145 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000146
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 switch (Tok.getKind()) {
148 case tok::eof:
149 // Ran out of tokens.
150 return false;
Mike Stumpa6f01772008-06-19 19:28:49 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 case tok::l_paren:
153 // Recursively skip properly-nested parens.
154 ConsumeParen();
155 SkipUntil(tok::r_paren, false);
156 break;
157 case tok::l_square:
158 // Recursively skip properly-nested square brackets.
159 ConsumeBracket();
160 SkipUntil(tok::r_square, false);
161 break;
162 case tok::l_brace:
163 // Recursively skip properly-nested braces.
164 ConsumeBrace();
165 SkipUntil(tok::r_brace, false);
166 break;
Mike Stumpa6f01772008-06-19 19:28:49 +0000167
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
169 // Since the user wasn't looking for this token (if they were, it would
170 // already be handled), this isn't balanced. If there is a LHS token at a
171 // higher level, we will assume that this matches the unbalanced token
172 // and return it. Otherwise, this is a spurious RHS token, which we skip.
173 case tok::r_paren:
174 if (ParenCount && !isFirstTokenSkipped)
175 return false; // Matches something.
176 ConsumeParen();
177 break;
178 case tok::r_square:
179 if (BracketCount && !isFirstTokenSkipped)
180 return false; // Matches something.
181 ConsumeBracket();
182 break;
183 case tok::r_brace:
184 if (BraceCount && !isFirstTokenSkipped)
185 return false; // Matches something.
186 ConsumeBrace();
187 break;
Mike Stumpa6f01772008-06-19 19:28:49 +0000188
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 case tok::string_literal:
190 case tok::wide_string_literal:
191 ConsumeStringToken();
192 break;
193 case tok::semi:
194 if (StopAtSemi)
195 return false;
196 // FALL THROUGH.
197 default:
198 // Skip this token.
199 ConsumeToken();
200 break;
201 }
202 isFirstTokenSkipped = false;
Mike Stumpa6f01772008-06-19 19:28:49 +0000203 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
206//===----------------------------------------------------------------------===//
207// Scope manipulation
208//===----------------------------------------------------------------------===//
209
Reid Spencer5f016e22007-07-11 17:01:13 +0000210/// EnterScope - Start a new scope.
211void Parser::EnterScope(unsigned ScopeFlags) {
Chris Lattner9e344c62007-07-15 00:04:39 +0000212 if (NumCachedScopes) {
213 Scope *N = ScopeCache[--NumCachedScopes];
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 N->Init(CurScope, ScopeFlags);
215 CurScope = N;
216 } else {
217 CurScope = new Scope(CurScope, ScopeFlags);
218 }
219}
220
221/// ExitScope - Pop a scope off the scope stack.
222void Parser::ExitScope() {
223 assert(CurScope && "Scope imbalance!");
224
Chris Lattner90ae68a2007-10-09 20:37:18 +0000225 // Inform the actions module that this scope is going away if there are any
226 // decls in it.
227 if (!CurScope->decl_empty())
Steve Naroffb216c882007-10-09 22:01:59 +0000228 Actions.ActOnPopScope(Tok.getLocation(), CurScope);
Mike Stumpa6f01772008-06-19 19:28:49 +0000229
Chris Lattner9e344c62007-07-15 00:04:39 +0000230 Scope *OldScope = CurScope;
231 CurScope = OldScope->getParent();
Mike Stumpa6f01772008-06-19 19:28:49 +0000232
Chris Lattner9e344c62007-07-15 00:04:39 +0000233 if (NumCachedScopes == ScopeCacheSize)
234 delete OldScope;
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 else
Chris Lattner9e344c62007-07-15 00:04:39 +0000236 ScopeCache[NumCachedScopes++] = OldScope;
Reid Spencer5f016e22007-07-11 17:01:13 +0000237}
238
239
240
241
242//===----------------------------------------------------------------------===//
243// C99 6.9: External Definitions.
244//===----------------------------------------------------------------------===//
245
246Parser::~Parser() {
247 // If we still have scopes active, delete the scope tree.
248 delete CurScope;
Mike Stumpa6f01772008-06-19 19:28:49 +0000249
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 // Free the scope cache.
Chris Lattner9e344c62007-07-15 00:04:39 +0000251 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
252 delete ScopeCache[i];
Daniel Dunbarfcdd8fe2008-10-04 19:21:03 +0000253
254 // Remove the pragma handlers we installed.
255 PP.RemovePragmaHandler(0, PackHandler);
256 delete PackHandler;
Reid Spencer5f016e22007-07-11 17:01:13 +0000257}
258
259/// Initialize - Warm up the parser.
260///
261void Parser::Initialize() {
262 // Prime the lexer look-ahead.
263 ConsumeToken();
Mike Stumpa6f01772008-06-19 19:28:49 +0000264
Chris Lattner31e05722007-08-26 06:24:45 +0000265 // Create the translation unit scope. Install it as the current scope.
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 assert(CurScope == 0 && "A scope is already active?");
Chris Lattner31e05722007-08-26 06:24:45 +0000267 EnterScope(Scope::DeclScope);
Steve Naroffb216c882007-10-09 22:01:59 +0000268 Actions.ActOnTranslationUnitScope(Tok.getLocation(), CurScope);
Mike Stumpa6f01772008-06-19 19:28:49 +0000269
Chris Lattner00073222007-10-09 17:23:58 +0000270 if (Tok.is(tok::eof) &&
Chris Lattnerf7261752007-08-25 05:47:03 +0000271 !getLang().CPlusPlus) // Empty source file is an extension in C
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 Diag(Tok, diag::ext_empty_source_file);
Mike Stumpa6f01772008-06-19 19:28:49 +0000273
Chris Lattner34870da2007-08-29 22:54:08 +0000274 // Initialization for Objective-C context sensitive keywords recognition.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000275 // Referenced in Parser::ParseObjCTypeQualifierList.
Chris Lattner34870da2007-08-29 22:54:08 +0000276 if (getLang().ObjC1) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000277 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
278 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
279 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
280 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
281 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
282 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
Chris Lattner34870da2007-08-29 22:54:08 +0000283 }
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000284
285 Ident_super = &PP.getIdentifierTable().get("super");
Reid Spencer5f016e22007-07-11 17:01:13 +0000286}
287
288/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
289/// action tells us to. This returns true if the EOF was encountered.
Steve Naroff89307ff2007-11-29 23:05:20 +0000290bool Parser::ParseTopLevelDecl(DeclTy*& Result) {
291 Result = 0;
Chris Lattner9299f3f2008-08-23 03:19:52 +0000292 if (Tok.is(tok::eof)) {
293 Actions.ActOnEndOfTranslationUnit();
294 return true;
295 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000296
Steve Naroff89307ff2007-11-29 23:05:20 +0000297 Result = ParseExternalDeclaration();
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 return false;
299}
300
Reid Spencer5f016e22007-07-11 17:01:13 +0000301/// ParseTranslationUnit:
302/// translation-unit: [C99 6.9]
Mike Stumpa6f01772008-06-19 19:28:49 +0000303/// external-declaration
304/// translation-unit external-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000305void Parser::ParseTranslationUnit() {
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000306 Initialize();
Mike Stumpa6f01772008-06-19 19:28:49 +0000307
Steve Naroff89307ff2007-11-29 23:05:20 +0000308 DeclTy *Res;
309 while (!ParseTopLevelDecl(Res))
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 /*parse them all*/;
Chris Lattner06f54852008-08-23 02:00:52 +0000311
312 ExitScope();
313 assert(CurScope == 0 && "Scope imbalance!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000314}
315
316/// ParseExternalDeclaration:
Chris Lattner90b93d62008-12-08 21:59:01 +0000317///
Douglas Gregorc19923d2008-11-21 16:10:08 +0000318/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
Chris Lattnerc3018152007-08-10 20:57:02 +0000319/// function-definition
320/// declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000321/// [EXT] ';'
322/// [GNU] asm-definition
Chris Lattnerc3018152007-08-10 20:57:02 +0000323/// [GNU] __extension__ external-declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000324/// [OBJC] objc-class-definition
325/// [OBJC] objc-class-declaration
326/// [OBJC] objc-alias-declaration
327/// [OBJC] objc-protocol-definition
328/// [OBJC] objc-method-definition
329/// [OBJC] @end
Douglas Gregorc19923d2008-11-21 16:10:08 +0000330/// [C++] linkage-specification
Reid Spencer5f016e22007-07-11 17:01:13 +0000331/// [GNU] asm-definition:
332/// simple-asm-expr ';'
333///
334Parser::DeclTy *Parser::ParseExternalDeclaration() {
335 switch (Tok.getKind()) {
336 case tok::semi:
337 Diag(Tok, diag::ext_top_level_semi);
338 ConsumeToken();
339 // TODO: Invoke action for top-level semicolon.
340 return 0;
Chris Lattner90b93d62008-12-08 21:59:01 +0000341 case tok::r_brace:
342 Diag(Tok, diag::err_expected_external_declaration);
343 ConsumeBrace();
344 return 0;
345 case tok::eof:
346 Diag(Tok, diag::err_expected_external_declaration);
347 return 0;
Chris Lattnerc3018152007-08-10 20:57:02 +0000348 case tok::kw___extension__: {
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000349 // __extension__ silences extension warnings in the subexpression.
350 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner39146d62008-10-20 06:51:33 +0000351 ConsumeToken();
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000352 return ParseExternalDeclaration();
Chris Lattnerc3018152007-08-10 20:57:02 +0000353 }
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000354 case tok::kw_asm: {
Sebastian Redleffa8d12008-12-10 00:02:53 +0000355 OwningExprResult Result(ParseSimpleAsm());
Mike Stumpa6f01772008-06-19 19:28:49 +0000356
Anders Carlsson3f9424f2008-02-08 00:23:11 +0000357 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
358 "top-level asm block");
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000359
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000360 if (!Result.isInvalid())
Sebastian Redl76ad2e82009-02-05 15:02:23 +0000361 return Actions.ActOnFileScopeAsmDecl(Tok.getLocation(), move(Result));
Chris Lattneraec3a1e2008-05-27 23:32:43 +0000362 return 0;
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000363 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 case tok::at:
365 // @ is not a legal token unless objc is enabled, no need to check.
Steve Naroff2bd42fa2007-09-10 20:51:04 +0000366 return ParseObjCAtDirectives();
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 case tok::minus:
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 case tok::plus:
Fariborz Jahanian60fbca02007-11-10 16:31:34 +0000369 if (getLang().ObjC1)
Steve Naroff71c0a952007-11-13 23:01:27 +0000370 return ParseObjCMethodDefinition();
Fariborz Jahanian60fbca02007-11-10 16:31:34 +0000371 else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 Diag(Tok, diag::err_expected_external_declaration);
373 ConsumeToken();
374 }
375 return 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +0000376 case tok::kw_using:
Chris Lattner8f08cb72007-08-25 06:57:03 +0000377 case tok::kw_namespace:
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 case tok::kw_typedef:
Douglas Gregoradcac882008-12-01 23:54:00 +0000379 case tok::kw_template:
380 case tok::kw_export: // As in 'export template'
Chris Lattnerbae35112007-08-25 18:15:16 +0000381 // A function definition cannot start with a these keywords.
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 return ParseDeclaration(Declarator::FileContext);
383 default:
384 // We can't tell whether this is a function-definition or declaration yet.
385 return ParseDeclarationOrFunctionDefinition();
386 }
387}
388
389/// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
390/// a declaration. We can't tell which we have until we read up to the
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000391/// compound-statement in function-definition. TemplateParams, if
392/// non-NULL, provides the template parameters when we're parsing a
393/// C++ template-declaration.
Reid Spencer5f016e22007-07-11 17:01:13 +0000394///
395/// function-definition: [C99 6.9.1]
Chris Lattnera798ebc2008-04-05 05:52:15 +0000396/// decl-specs declarator declaration-list[opt] compound-statement
397/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpa6f01772008-06-19 19:28:49 +0000398/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Chris Lattnera798ebc2008-04-05 05:52:15 +0000399///
Reid Spencer5f016e22007-07-11 17:01:13 +0000400/// declaration: [C99 6.7]
Chris Lattner697e15f2007-08-22 06:06:56 +0000401/// declaration-specifiers init-declarator-list[opt] ';'
402/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
Reid Spencer5f016e22007-07-11 17:01:13 +0000403/// [OMP] threadprivate-directive [TODO]
404///
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000405Parser::DeclTy *
406Parser::ParseDeclarationOrFunctionDefinition(
407 TemplateParameterLists *TemplateParams) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // Parse the common declaration-specifiers piece.
409 DeclSpec DS;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000410 ParseDeclarationSpecifiers(DS, TemplateParams);
Mike Stumpa6f01772008-06-19 19:28:49 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
413 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner00073222007-10-09 17:23:58 +0000414 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 ConsumeToken();
416 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
417 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000418
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000419 // ObjC2 allows prefix attributes on class interfaces and protocols.
420 // FIXME: This still needs better diagnostics. We should only accept
421 // attributes here, no types, etc.
Chris Lattner00073222007-10-09 17:23:58 +0000422 if (getLang().ObjC2 && Tok.is(tok::at)) {
Steve Naroffdac269b2007-08-20 21:31:48 +0000423 SourceLocation AtLoc = ConsumeToken(); // the "@"
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000424 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
425 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
426 Diag(Tok, diag::err_objc_unexpected_attr);
Chris Lattnercb53b362007-12-27 19:57:00 +0000427 SkipUntil(tok::semi); // FIXME: better skip?
428 return 0;
429 }
Fariborz Jahanian0de2ae22008-01-02 19:17:38 +0000430 const char *PrevSpec = 0;
431 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec))
Chris Lattner1ab3b962008-11-18 07:48:38 +0000432 Diag(AtLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000433 if (Tok.isObjCAtKeyword(tok::objc_protocol))
434 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
Mike Stumpa6f01772008-06-19 19:28:49 +0000435 return ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
Steve Naroffdac269b2007-08-20 21:31:48 +0000436 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000437
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000438 // If the declspec consisted only of 'extern' and we have a string
439 // literal following it, this must be a C++ linkage specifier like
440 // 'extern "C"'.
Chris Lattner3c6f6a72008-01-12 07:08:43 +0000441 if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000442 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
443 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier)
444 return ParseLinkage(Declarator::FileContext);
445
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // Parse the first declarator.
447 Declarator DeclaratorInfo(DS, Declarator::FileContext);
448 ParseDeclarator(DeclaratorInfo);
449 // Error parsing the declarator?
Douglas Gregor10bd3682008-11-17 22:58:34 +0000450 if (!DeclaratorInfo.hasName()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 // If so, skip until the semi-colon or a }.
Douglas Gregorcb43d992008-12-01 23:03:32 +0000452 SkipUntil(tok::r_brace, true, true);
Chris Lattner00073222007-10-09 17:23:58 +0000453 if (Tok.is(tok::semi))
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 ConsumeToken();
455 return 0;
456 }
457
458 // If the declarator is the start of a function definition, handle it.
Chris Lattner00073222007-10-09 17:23:58 +0000459 if (Tok.is(tok::equal) || // int X()= -> not a function def
460 Tok.is(tok::comma) || // int X(), -> not a function def
461 Tok.is(tok::semi) || // int X(); -> not a function def
462 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000463 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
464 (getLang().CPlusPlus &&
465 Tok.is(tok::l_paren)) ) { // int X(0) -> not a function def [C++]
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 // FALL THROUGH.
467 } else if (DeclaratorInfo.isFunctionDeclarator() &&
Argyrios Kyrtzidiscf28c722008-06-21 10:00:56 +0000468 (Tok.is(tok::l_brace) || // int X() {}
469 ( !getLang().CPlusPlus &&
470 isDeclarationSpecifier() ))) { // int X(f) int f; {}
Steve Naroffe39bfd02008-02-14 02:58:32 +0000471 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
472 Diag(Tok, diag::err_function_declared_typedef);
Mike Stumpa6f01772008-06-19 19:28:49 +0000473
Steve Naroffe39bfd02008-02-14 02:58:32 +0000474 if (Tok.is(tok::l_brace)) {
475 // This recovery skips the entire function body. It would be nice
Douglas Gregor72c3f312008-12-05 18:15:24 +0000476 // to simply call ParseFunctionDefinition() below, however Sema
Steve Naroffe39bfd02008-02-14 02:58:32 +0000477 // assumes the declarator represents a function, not a typedef.
478 ConsumeBrace();
479 SkipUntil(tok::r_brace, true);
480 } else {
481 SkipUntil(tok::semi);
482 }
483 return 0;
484 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 return ParseFunctionDefinition(DeclaratorInfo);
486 } else {
487 if (DeclaratorInfo.isFunctionDeclarator())
488 Diag(Tok, diag::err_expected_fn_body);
489 else
490 Diag(Tok, diag::err_expected_after_declarator);
491 SkipUntil(tok::semi);
492 return 0;
493 }
494
495 // Parse the init-declarator-list for a normal declaration.
496 return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
497}
498
499/// ParseFunctionDefinition - We parsed and verified that the specified
500/// Declarator is well formed. If this is a K&R-style function, read the
501/// parameters declaration-list, then start the compound-statement.
502///
Chris Lattnera798ebc2008-04-05 05:52:15 +0000503/// function-definition: [C99 6.9.1]
504/// decl-specs declarator declaration-list[opt] compound-statement
505/// [C90] function-definition: [C99 6.7.1] - implicit int result
Mike Stumpa6f01772008-06-19 19:28:49 +0000506/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
Douglas Gregor7ad83902008-11-05 04:29:56 +0000507/// [C++] function-definition: [C++ 8.4]
508/// decl-specifier-seq[opt] declarator ctor-initializer[opt] function-body
509/// [C++] function-definition: [C++ 8.4]
510/// decl-specifier-seq[opt] declarator function-try-block [TODO]
Reid Spencer5f016e22007-07-11 17:01:13 +0000511///
512Parser::DeclTy *Parser::ParseFunctionDefinition(Declarator &D) {
513 const DeclaratorChunk &FnTypeInfo = D.getTypeObject(0);
514 assert(FnTypeInfo.Kind == DeclaratorChunk::Function &&
515 "This isn't a function declarator!");
516 const DeclaratorChunk::FunctionTypeInfo &FTI = FnTypeInfo.Fun;
Mike Stumpa6f01772008-06-19 19:28:49 +0000517
Chris Lattnera798ebc2008-04-05 05:52:15 +0000518 // If this is C90 and the declspecs were completely missing, fudge in an
519 // implicit int. We do this here because this is the only place where
520 // declaration-specifiers are completely optional in the grammar.
Chris Lattnerd658b562008-04-05 06:32:51 +0000521 if (getLang().ImplicitInt && D.getDeclSpec().getParsedSpecifiers() == 0) {
Chris Lattnera798ebc2008-04-05 05:52:15 +0000522 const char *PrevSpec;
Chris Lattner31c28682008-10-20 02:01:34 +0000523 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
524 D.getIdentifierLoc(),
525 PrevSpec);
Sebastian Redlab197ba2009-02-09 18:23:29 +0000526 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
Chris Lattnera798ebc2008-04-05 05:52:15 +0000527 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 // If this declaration was formed with a K&R-style identifier list for the
530 // arguments, parse declarations for all of the args next.
531 // int foo(a,b) int a; float b; {}
532 if (!FTI.hasPrototype && FTI.NumArgs != 0)
533 ParseKNRParamDeclarations(D);
534
Douglas Gregor7ad83902008-11-05 04:29:56 +0000535 // We should have either an opening brace or, in a C++ constructor,
536 // we may have a colon.
Sebastian Redl618e5c02008-11-24 21:45:59 +0000537 // FIXME: In C++, we might also find the 'try' keyword.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000538 if (Tok.isNot(tok::l_brace) && Tok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 Diag(Tok, diag::err_expected_fn_body);
540
541 // Skip over garbage, until we get to '{'. Don't eat the '{'.
542 SkipUntil(tok::l_brace, true, true);
Mike Stumpa6f01772008-06-19 19:28:49 +0000543
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 // If we didn't find the '{', bail out.
Chris Lattner00073222007-10-09 17:23:58 +0000545 if (Tok.isNot(tok::l_brace))
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000548
Chris Lattnerb652cea2007-10-09 17:14:05 +0000549 // Enter a scope for the function body.
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000550 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
Mike Stumpa6f01772008-06-19 19:28:49 +0000551
Chris Lattnerb652cea2007-10-09 17:14:05 +0000552 // Tell the actions module that we have entered a function definition with the
553 // specified Declarator for the function.
554 DeclTy *Res = Actions.ActOnStartOfFunctionDef(CurScope, D);
Mike Stumpa6f01772008-06-19 19:28:49 +0000555
Douglas Gregor7ad83902008-11-05 04:29:56 +0000556 // If we have a colon, then we're probably parsing a C++
557 // ctor-initializer.
558 if (Tok.is(tok::colon))
559 ParseConstructorInitializer(Res);
560
561 SourceLocation BraceLoc = Tok.getLocation();
Mike Stumpa6f01772008-06-19 19:28:49 +0000562 return ParseFunctionStatementBody(Res, BraceLoc, BraceLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000563}
564
565/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
566/// types for a function with a K&R-style identifier list for arguments.
567void Parser::ParseKNRParamDeclarations(Declarator &D) {
568 // We know that the top-level of this declarator is a function.
569 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
570
Chris Lattner04421082008-04-08 04:40:51 +0000571 // Enter function-declaration scope, limiting any declarators to the
572 // function prototype scope, including parameter declarators.
Douglas Gregor3218c4b2009-01-09 22:42:13 +0000573 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
Chris Lattner04421082008-04-08 04:40:51 +0000574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 // Read all the argument declarations.
576 while (isDeclarationSpecifier()) {
577 SourceLocation DSStart = Tok.getLocation();
Mike Stumpa6f01772008-06-19 19:28:49 +0000578
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 // Parse the common declaration-specifiers piece.
580 DeclSpec DS;
581 ParseDeclarationSpecifiers(DS);
Mike Stumpa6f01772008-06-19 19:28:49 +0000582
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
584 // least one declarator'.
585 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
586 // the declarations though. It's trivial to ignore them, really hard to do
587 // anything else with them.
Chris Lattner00073222007-10-09 17:23:58 +0000588 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 Diag(DSStart, diag::err_declaration_does_not_declare_param);
590 ConsumeToken();
591 continue;
592 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000593
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
595 // than register.
596 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
597 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
598 Diag(DS.getStorageClassSpecLoc(),
599 diag::err_invalid_storage_class_in_func_decl);
600 DS.ClearStorageClassSpecs();
601 }
602 if (DS.isThreadSpecified()) {
603 Diag(DS.getThreadSpecLoc(),
604 diag::err_invalid_storage_class_in_func_decl);
605 DS.ClearStorageClassSpecs();
606 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000607
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 // Parse the first declarator attached to this declspec.
609 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
610 ParseDeclarator(ParmDeclarator);
611
612 // Handle the full declarator list.
613 while (1) {
614 DeclTy *AttrList;
615 // If attributes are present, parse them.
Chris Lattner00073222007-10-09 17:23:58 +0000616 if (Tok.is(tok::kw___attribute))
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 // FIXME: attach attributes too.
618 AttrList = ParseAttributes();
Mike Stumpa6f01772008-06-19 19:28:49 +0000619
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 // Ask the actions module to compute the type for this declarator.
Mike Stumpa6f01772008-06-19 19:28:49 +0000621 Action::DeclTy *Param =
Chris Lattner04421082008-04-08 04:40:51 +0000622 Actions.ActOnParamDeclarator(CurScope, ParmDeclarator);
Steve Naroff2bd42fa2007-09-10 20:51:04 +0000623
Mike Stumpa6f01772008-06-19 19:28:49 +0000624 if (Param &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 // A missing identifier has already been diagnosed.
626 ParmDeclarator.getIdentifier()) {
627
628 // Scan the argument list looking for the correct param to apply this
629 // type.
630 for (unsigned i = 0; ; ++i) {
631 // C99 6.9.1p6: those declarators shall declare only identifiers from
632 // the identifier list.
633 if (i == FTI.NumArgs) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000634 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
Chris Lattner6898e332008-11-19 07:51:13 +0000635 << ParmDeclarator.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +0000636 break;
637 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000638
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
640 // Reject redefinitions of parameters.
Chris Lattner04421082008-04-08 04:40:51 +0000641 if (FTI.ArgInfo[i].Param) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 Diag(ParmDeclarator.getIdentifierLoc(),
Chris Lattner1ab3b962008-11-18 07:48:38 +0000643 diag::err_param_redefinition)
Chris Lattner6898e332008-11-19 07:51:13 +0000644 << ParmDeclarator.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 } else {
Chris Lattner04421082008-04-08 04:40:51 +0000646 FTI.ArgInfo[i].Param = Param;
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 }
648 break;
649 }
650 }
651 }
652
653 // If we don't have a comma, it is either the end of the list (a ';') or
654 // an error, bail out.
Chris Lattner00073222007-10-09 17:23:58 +0000655 if (Tok.isNot(tok::comma))
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 break;
Mike Stumpa6f01772008-06-19 19:28:49 +0000657
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 // Consume the comma.
659 ConsumeToken();
Mike Stumpa6f01772008-06-19 19:28:49 +0000660
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 // Parse the next declarator.
662 ParmDeclarator.clear();
663 ParseDeclarator(ParmDeclarator);
664 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000665
Chris Lattner00073222007-10-09 17:23:58 +0000666 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 ConsumeToken();
668 } else {
669 Diag(Tok, diag::err_parse_error);
670 // Skip to end of block or statement
671 SkipUntil(tok::semi, true);
Chris Lattner00073222007-10-09 17:23:58 +0000672 if (Tok.is(tok::semi))
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 ConsumeToken();
674 }
675 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000676
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 // The actions module must verify that all arguments were declared.
Douglas Gregorbe109b32009-01-23 16:23:13 +0000678 Actions.ActOnFinishKNRParamDeclarations(CurScope, D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000679}
680
681
682/// ParseAsmStringLiteral - This is just a normal string-literal, but is not
683/// allowed to be a wide string, and is not subject to character translation.
684///
685/// [GNU] asm-string-literal:
686/// string-literal
687///
Sebastian Redleffa8d12008-12-10 00:02:53 +0000688Parser::OwningExprResult Parser::ParseAsmStringLiteral() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 if (!isTokenStringLiteral()) {
690 Diag(Tok, diag::err_expected_string_literal);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000691 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000693
Sebastian Redl20df9b72008-12-11 22:51:44 +0000694 OwningExprResult Res(ParseStringLiteralExpression());
Sebastian Redleffa8d12008-12-10 00:02:53 +0000695 if (Res.isInvalid()) return move(Res);
Mike Stumpa6f01772008-06-19 19:28:49 +0000696
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 // TODO: Diagnose: wide string literal in 'asm'
Mike Stumpa6f01772008-06-19 19:28:49 +0000698
Sebastian Redleffa8d12008-12-10 00:02:53 +0000699 return move(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +0000700}
701
702/// ParseSimpleAsm
703///
704/// [GNU] simple-asm-expr:
705/// 'asm' '(' asm-string-literal ')'
706///
Sebastian Redlab197ba2009-02-09 18:23:29 +0000707Parser::OwningExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
Chris Lattner00073222007-10-09 17:23:58 +0000708 assert(Tok.is(tok::kw_asm) && "Not an asm!");
Anders Carlssondfab6cb2008-02-08 00:33:21 +0000709 SourceLocation Loc = ConsumeToken();
Mike Stumpa6f01772008-06-19 19:28:49 +0000710
Chris Lattner00073222007-10-09 17:23:58 +0000711 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000712 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Sebastian Redl61364dd2008-12-11 19:30:53 +0000713 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000715
Sebastian Redlab197ba2009-02-09 18:23:29 +0000716 Loc = ConsumeParen();
Mike Stumpa6f01772008-06-19 19:28:49 +0000717
Sebastian Redleffa8d12008-12-10 00:02:53 +0000718 OwningExprResult Result(ParseAsmStringLiteral());
Mike Stumpa6f01772008-06-19 19:28:49 +0000719
Sebastian Redlab197ba2009-02-09 18:23:29 +0000720 if (Result.isInvalid()) {
721 SkipUntil(tok::r_paren, true, true);
722 if (EndLoc)
723 *EndLoc = Tok.getLocation();
724 ConsumeAnyToken();
725 } else {
726 Loc = MatchRHSPunctuation(tok::r_paren, Loc);
727 if (EndLoc)
728 *EndLoc = Loc;
729 }
Mike Stumpa6f01772008-06-19 19:28:49 +0000730
Sebastian Redleffa8d12008-12-10 00:02:53 +0000731 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000732}
733
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000734/// TryAnnotateTypeOrScopeToken - If the current token position is on a
735/// typename (possibly qualified in C++) or a C++ scope specifier not followed
736/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
737/// with a single annotation token representing the typename or C++ scope
738/// respectively.
739/// This simplifies handling of C++ scope specifiers and allows efficient
740/// backtracking without the need to re-parse and resolve nested-names and
741/// typenames.
Argyrios Kyrtzidis44802cc2008-11-26 21:51:07 +0000742/// It will mainly be called when we expect to treat identifiers as typenames
743/// (if they are typenames). For example, in C we do not expect identifiers
744/// inside expressions to be treated as typenames so it will not be called
745/// for expressions in C.
746/// The benefit for C/ObjC is that a typename will be annotated and
Steve Naroffb43a50f2009-01-28 19:39:02 +0000747/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
Argyrios Kyrtzidis44802cc2008-11-26 21:51:07 +0000748/// will not be called twice, once to check whether we have a declaration
749/// specifier, and another one to get the actual type inside
750/// ParseDeclarationSpecifiers).
Chris Lattnera7bc7c82009-01-04 23:23:14 +0000751///
752/// This returns true if the token was annotated.
Chris Lattner55a7cef2009-01-05 00:13:00 +0000753///
754/// Note that this routine emits an error if you call it with ::new or ::delete
755/// as the current tokens, so only call it in contexts where these are invalid.
Chris Lattner5b454732009-01-05 03:55:46 +0000756bool Parser::TryAnnotateTypeOrScopeToken() {
Chris Lattner7452c6f2009-01-05 01:24:05 +0000757 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
758 "Cannot be a type or scope token!");
759
760 // FIXME: Implement template-ids
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000761 CXXScopeSpec SS;
Argyrios Kyrtzidis4bdd91c2008-11-26 21:41:52 +0000762 if (getLang().CPlusPlus)
Chris Lattner7a0ab5f2009-01-06 06:59:53 +0000763 ParseOptionalCXXScopeSpecifier(SS);
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000764
765 if (Tok.is(tok::identifier)) {
Chris Lattner608d1fc2009-01-05 01:49:50 +0000766 // Determine whether the identifier is a type name.
Steve Naroffb43a50f2009-01-28 19:39:02 +0000767 if (TypeTy *Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
Douglas Gregorb696ea32009-02-04 17:00:24 +0000768 Tok.getLocation(), CurScope, &SS)) {
Chris Lattner608d1fc2009-01-05 01:49:50 +0000769 // This is a typename. Replace the current token in-place with an
770 // annotation type token.
Chris Lattnerb31757b2009-01-06 05:06:21 +0000771 Tok.setKind(tok::annot_typename);
Chris Lattner608d1fc2009-01-05 01:49:50 +0000772 Tok.setAnnotationValue(Ty);
773 Tok.setAnnotationEndLoc(Tok.getLocation());
774 if (SS.isNotEmpty()) // it was a C++ qualified type name.
775 Tok.setLocation(SS.getBeginLoc());
776
777 // In case the tokens were cached, have Preprocessor replace
778 // them with the annotation token.
779 PP.AnnotateCachedTokens(Tok);
780 return true;
781 } else if (!getLang().CPlusPlus) {
782 // If we're in C, we can't have :: tokens at all (the lexer won't return
783 // them). If the identifier is not a type, then it can't be scope either,
784 // just early exit.
785 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000786 }
Chris Lattner608d1fc2009-01-05 01:49:50 +0000787
788 // If this is a template-id, annotate the template-id token.
Douglas Gregor55f6b142009-02-09 18:46:07 +0000789 if (NextToken().is(tok::less)) {
790 DeclTy *Template;
791 if (TemplateNameKind TNK
792 = Actions.isTemplateName(*Tok.getIdentifierInfo(),
793 CurScope, Template, &SS)) {
794 AnnotateTemplateIdToken(Template, TNK, &SS);
795 return true;
796 }
797 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000798
799 // We either have an identifier that is not a type name or we have
800 // just created a template-id that might be a type name. Both
801 // cases will be handled below.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000802 }
803
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000804 // FIXME: check for a template-id token here, and look it up if it
805 // names a type.
806
Chris Lattner6ec76d42009-01-04 22:32:19 +0000807 if (SS.isEmpty())
Chris Lattnera7bc7c82009-01-04 23:23:14 +0000808 return false;
Chris Lattner6ec76d42009-01-04 22:32:19 +0000809
810 // A C++ scope specifier that isn't followed by a typename.
811 // Push the current token back into the token stream (or revert it if it is
812 // cached) and use an annotation scope token for current token.
813 if (PP.isBacktrackEnabled())
814 PP.RevertCachedTokens(1);
815 else
816 PP.EnterToken(Tok);
817 Tok.setKind(tok::annot_cxxscope);
818 Tok.setAnnotationValue(SS.getScopeRep());
819 Tok.setAnnotationRange(SS.getRange());
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000820
Chris Lattner6ec76d42009-01-04 22:32:19 +0000821 // In case the tokens were cached, have Preprocessor replace them with the
822 // annotation token.
823 PP.AnnotateCachedTokens(Tok);
Chris Lattnera7bc7c82009-01-04 23:23:14 +0000824 return true;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000825}
826
827/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
Chris Lattner5e02c472009-01-05 00:07:25 +0000828/// annotates C++ scope specifiers. This returns true if the token was
829/// annotated.
Chris Lattner55a7cef2009-01-05 00:13:00 +0000830///
831/// Note that this routine emits an error if you call it with ::new or ::delete
832/// as the current tokens, so only call it in contexts where these are invalid.
Chris Lattner5e02c472009-01-05 00:07:25 +0000833bool Parser::TryAnnotateCXXScopeToken() {
Argyrios Kyrtzidis4bdd91c2008-11-26 21:41:52 +0000834 assert(getLang().CPlusPlus &&
Chris Lattner6ec76d42009-01-04 22:32:19 +0000835 "Call sites of this function should be guarded by checking for C++");
Chris Lattner7452c6f2009-01-05 01:24:05 +0000836 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
837 "Cannot be a type or scope token!");
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000838
Argyrios Kyrtzidis4bdd91c2008-11-26 21:41:52 +0000839 CXXScopeSpec SS;
Chris Lattner7a0ab5f2009-01-06 06:59:53 +0000840 if (!ParseOptionalCXXScopeSpecifier(SS))
Chris Lattner5e02c472009-01-05 00:07:25 +0000841 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000842
Chris Lattner6ec76d42009-01-04 22:32:19 +0000843 // Push the current token back into the token stream (or revert it if it is
844 // cached) and use an annotation scope token for current token.
845 if (PP.isBacktrackEnabled())
846 PP.RevertCachedTokens(1);
847 else
848 PP.EnterToken(Tok);
849 Tok.setKind(tok::annot_cxxscope);
850 Tok.setAnnotationValue(SS.getScopeRep());
851 Tok.setAnnotationRange(SS.getRange());
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000852
Chris Lattner6ec76d42009-01-04 22:32:19 +0000853 // In case the tokens were cached, have Preprocessor replace them with the
854 // annotation token.
855 PP.AnnotateCachedTokens(Tok);
Chris Lattner5e02c472009-01-05 00:07:25 +0000856 return true;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000857}