blob: 9fe5ab4847bea408791914cfb0a5b81e91b49c82 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
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 top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
Eric Christopher1f84f8d2010-06-24 02:02:00 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000021#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf29c5232010-08-24 22:20:20 +000022#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor295a2a62010-10-30 00:23:06 +000023#include "clang/Lex/ExternalPreprocessorSource.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000024#include "llvm/ADT/StringSwitch.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000026#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000027#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000028using namespace clang;
29
Douglas Gregor295a2a62010-10-30 00:23:06 +000030MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
31 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
32
33 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
34 = Macros.find(II);
35 if (Pos == Macros.end()) {
36 // Load this macro from the external source.
37 getExternalSource()->LoadMacroDefinition(II);
38 Pos = Macros.find(II);
39 }
40 assert(Pos != Macros.end() && "Identifier macro info is missing!");
41 return Pos->second;
42}
43
Chris Lattnera3b605e2008-03-09 03:13:06 +000044/// setMacroInfo - Specify a macro for this identifier.
45///
46void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000047 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000048 Macros[II] = MI;
49 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000050 } else if (II->hasMacroDefinition()) {
51 Macros.erase(II);
52 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000053 }
54}
55
56/// RegisterBuiltinMacro - Register the specified identifier in the identifier
57/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000058static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000059 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000060 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattnera3b605e2008-03-09 03:13:06 +000062 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000063 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000064 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000065 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000066 return Id;
67}
68
69
70/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
71/// identifier table.
72void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000073 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
74 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
75 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
76 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
77 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
78 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattnera3b605e2008-03-09 03:13:06 +000080 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000081 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
82 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
83 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000084
Chris Lattner148772a2009-06-13 07:13:28 +000085 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000086 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
87 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000088 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000089 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
90 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall1ef8a2e2010-08-28 22:34:47 +000091
92 // Microsoft Extensions.
93 if (Features.Microsoft)
94 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
95 else
96 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +000097}
98
99/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
100/// in its expansion, currently expands to that token literally.
101static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
102 const IdentifierInfo *MacroIdent,
103 Preprocessor &PP) {
104 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
105
106 // If the token isn't an identifier, it's always literally expanded.
107 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattnera3b605e2008-03-09 03:13:06 +0000109 // If the identifier is a macro, and if that macro is enabled, it may be
110 // expanded so it's not a trivial expansion.
111 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
112 // Fast expanding "#define X X" is ok, because X would be disabled.
113 II != MacroIdent)
114 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Chris Lattnera3b605e2008-03-09 03:13:06 +0000116 // If this is an object-like macro invocation, it is safe to trivially expand
117 // it.
118 if (MI->isObjectLike()) return true;
119
120 // If this is a function-like macro invocation, it's safe to trivially expand
121 // as long as the identifier is not a macro argument.
122 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
123 I != E; ++I)
124 if (*I == II)
125 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Chris Lattnera3b605e2008-03-09 03:13:06 +0000127 return true;
128}
129
130
131/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
132/// lexed is a '('. If so, consume the token and return true, if not, this
133/// method should have no observable side-effect on the lexed tokens.
134bool Preprocessor::isNextPPTokenLParen() {
135 // Do some quick tests for rejection cases.
136 unsigned Val;
137 if (CurLexer)
138 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000139 else if (CurPTHLexer)
140 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000141 else
142 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Chris Lattnera3b605e2008-03-09 03:13:06 +0000144 if (Val == 2) {
145 // We have run off the end. If it's a source file we don't
146 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
147 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000148 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000149 return false;
150 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
151 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
152 if (Entry.TheLexer)
153 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000154 else if (Entry.ThePTHLexer)
155 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000156 else
157 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Chris Lattnera3b605e2008-03-09 03:13:06 +0000159 if (Val != 2)
160 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Chris Lattnera3b605e2008-03-09 03:13:06 +0000162 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000163 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000164 return false;
165 }
166 }
167
168 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
169 // have found something that isn't a '(' or we found the end of the
170 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000171 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000172}
173
174/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
175/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000176bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000177 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000178 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Douglas Gregor13678972010-01-26 19:43:43 +0000180 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000181 // then the macro could expand to different things in other contexts, we need
182 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000183 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattnera3b605e2008-03-09 03:13:06 +0000185 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
186 if (MI->isBuiltinMacro()) {
187 ExpandBuiltinMacro(Identifier);
188 return false;
189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnera3b605e2008-03-09 03:13:06 +0000191 /// Args - If this is a function-like macro expansion, this contains,
192 /// for each macro argument, the list of tokens that were provided to the
193 /// invocation.
194 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattnere7fb4842009-02-15 20:52:18 +0000196 // Remember where the end of the instantiation occurred. For an object-like
197 // macro, this is the identifier. For a function-like macro, this is the ')'.
198 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattnera3b605e2008-03-09 03:13:06 +0000200 // If this is a function-like macro, read the arguments.
201 if (MI->isFunctionLike()) {
202 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000203 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000204 if (!isNextPPTokenLParen())
205 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnera3b605e2008-03-09 03:13:06 +0000207 // Remember that we are now parsing the arguments to a macro invocation.
208 // Preprocessor directives used inside macro arguments are not portable, and
209 // this enables the warning.
210 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000211 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattnera3b605e2008-03-09 03:13:06 +0000213 // Finished parsing args.
214 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattnera3b605e2008-03-09 03:13:06 +0000216 // If there was an error parsing the arguments, bail out.
217 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Chris Lattnera3b605e2008-03-09 03:13:06 +0000219 ++NumFnMacroExpanded;
220 } else {
221 ++NumMacroExpanded;
222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Chris Lattnera3b605e2008-03-09 03:13:06 +0000224 // Notice that this macro has been used.
225 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattnera3b605e2008-03-09 03:13:06 +0000227 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnera3b605e2008-03-09 03:13:06 +0000229 // If this macro expands to no tokens, don't bother to push it onto the
230 // expansion stack, only to take it right back off.
231 if (MI->getNumTokens() == 0) {
232 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000233 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattnera3b605e2008-03-09 03:13:06 +0000235 // Ignore this macro use, just return the next token in the current
236 // buffer.
237 bool HadLeadingSpace = Identifier.hasLeadingSpace();
238 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattnera3b605e2008-03-09 03:13:06 +0000240 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnera3b605e2008-03-09 03:13:06 +0000242 // If the identifier isn't on some OTHER line, inherit the leading
243 // whitespace/first-on-a-line property of this token. This handles
244 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
245 // empty.
246 if (!Identifier.isAtStartOfLine()) {
247 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
248 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
249 }
250 ++NumFastMacroExpanded;
251 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattnera3b605e2008-03-09 03:13:06 +0000253 } else if (MI->getNumTokens() == 1 &&
254 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000255 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000256 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000257 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000258 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000259
260 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000261 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000262
Chris Lattnera3b605e2008-03-09 03:13:06 +0000263 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
264 // identifier to the expanded token.
265 bool isAtStartOfLine = Identifier.isAtStartOfLine();
266 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattnera3b605e2008-03-09 03:13:06 +0000268 // Remember where the token is instantiated.
269 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Chris Lattnera3b605e2008-03-09 03:13:06 +0000271 // Replace the result token.
272 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnera3b605e2008-03-09 03:13:06 +0000274 // Restore the StartOfLine/LeadingSpace markers.
275 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
276 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000278 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000279 // locations.
280 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000281 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000282 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000283 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattner8ff66de2010-03-26 17:49:16 +0000285 // If this is a disabled macro or #define X X, we must mark the result as
286 // unexpandable.
287 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
288 if (MacroInfo *NewMI = getMacroInfo(NewII))
289 if (!NewMI->isEnabled() || NewMI == MI)
290 Identifier.setFlag(Token::DisableExpand);
291 }
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattnera3b605e2008-03-09 03:13:06 +0000293 // Since this is not an identifier token, it can't be macro expanded, so
294 // we're done.
295 ++NumFastMacroExpanded;
296 return false;
297 }
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattnera3b605e2008-03-09 03:13:06 +0000299 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000300 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Chris Lattnera3b605e2008-03-09 03:13:06 +0000302 // Now that the macro is at the top of the include stack, ask the
303 // preprocessor to read the next token from it.
304 Lex(Identifier);
305 return false;
306}
307
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000308/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
309/// token is the '(' of the macro, this method is invoked to read all of the
310/// actual arguments specified for the macro invocation. This returns null on
311/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000312MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000313 MacroInfo *MI,
314 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000315 // The number of fixed arguments to parse.
316 unsigned NumFixedArgsLeft = MI->getNumArgs();
317 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattnera3b605e2008-03-09 03:13:06 +0000319 // Outer loop, while there are more arguments, keep reading them.
320 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000322 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
323 // an argument value in a macro could expand to ',' or '(' or ')'.
324 LexUnexpandedToken(Tok);
325 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Chris Lattnera3b605e2008-03-09 03:13:06 +0000327 // ArgTokens - Build up a list of tokens that make up each argument. Each
328 // argument is separated by an EOF token. Use a SmallVector so we can avoid
329 // heap allocations in the common case.
330 llvm::SmallVector<Token, 64> ArgTokens;
331
332 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000333 while (Tok.isNot(tok::r_paren)) {
334 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
335 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000337 unsigned ArgTokenStart = ArgTokens.size();
338 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattnera3b605e2008-03-09 03:13:06 +0000340 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
341 // that we already consumed the first one.
342 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Chris Lattnera3b605e2008-03-09 03:13:06 +0000344 while (1) {
345 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
346 // an argument value in a macro could expand to ',' or '(' or ')'.
347 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregorf29c5232010-08-24 22:20:20 +0000349 if (Tok.is(tok::code_completion)) {
350 if (CodeComplete)
351 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
352 MI, NumActuals);
353 LexUnexpandedToken(Tok);
354 }
355
Chris Lattnera3b605e2008-03-09 03:13:06 +0000356 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
357 Diag(MacroName, diag::err_unterm_macro_invoc);
358 // Do not lose the EOF/EOM. Return it to the client.
359 MacroName = Tok;
360 return 0;
361 } else if (Tok.is(tok::r_paren)) {
362 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000363 if (NumParens-- == 0) {
364 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000365 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000366 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000367 } else if (Tok.is(tok::l_paren)) {
368 ++NumParens;
369 } else if (Tok.is(tok::comma) && NumParens == 0) {
370 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000371 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000372 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000373 if (!isVariadic) break;
374 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000375 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000376 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
377 // If this is a comment token in the argument list and we're just in
378 // -C mode (not -CC mode), discard the comment.
379 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000380 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000381 // Reading macro arguments can cause macros that we are currently
382 // expanding from to be popped off the expansion stack. Doing so causes
383 // them to be reenabled for expansion. Here we record whether any
384 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000385 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000386 // C99 6.10.3.4p2.
387 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
388 if (!MI->isEnabled())
389 Tok.setFlag(Token::DisableExpand);
390 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000391 ArgTokens.push_back(Tok);
392 }
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000394 // If this was an empty argument list foo(), don't add this as an empty
395 // argument.
396 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
397 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000398
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000399 // If this is not a variadic macro, and too many args were specified, emit
400 // an error.
401 if (!isVariadic && NumFixedArgsLeft == 0) {
402 if (ArgTokens.size() != ArgTokenStart)
403 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000405 // Emit the diagnostic at the macro name in case there is a missing ).
406 // Emitting it at the , could be far away from the macro name.
407 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
408 return 0;
409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattnera3b605e2008-03-09 03:13:06 +0000411 // Empty arguments are standard in C99 and supported as an extension in
412 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000413 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000414 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattnera3b605e2008-03-09 03:13:06 +0000416 // Add a marker EOF token to the end of the token list for this argument.
417 Token EOFTok;
418 EOFTok.startToken();
419 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000420 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000421 EOFTok.setLength(0);
422 ArgTokens.push_back(EOFTok);
423 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000424 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000425 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattnera3b605e2008-03-09 03:13:06 +0000428 // Okay, we either found the r_paren. Check to see if we parsed too few
429 // arguments.
430 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Chris Lattnera3b605e2008-03-09 03:13:06 +0000432 // See MacroArgs instance var for description of this.
433 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattnera3b605e2008-03-09 03:13:06 +0000435 if (NumActuals < MinArgsExpected) {
436 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000437 if (NumActuals == 0 && MinArgsExpected == 1) {
438 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner97e2de12009-04-20 21:08:10 +0000440 // If there is exactly one argument, and that argument is missing,
441 // then we have an empty "()" argument empty list. This is fine, even if
442 // the macro expects one argument (the argument is just empty).
443 isVarargsElided = MI->isVariadic();
444 } else if (MI->isVariadic() &&
445 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
446 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000447 // Varargs where the named vararg parameter is missing: ok as extension.
448 // #define A(x, ...)
449 // A("blah")
450 Diag(Tok, diag::ext_missing_varargs_arg);
451
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000452 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000453 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000454 // #define A(x, foo...) blah(a, ## foo)
455 // #define B(x, ...) blah(a, ## __VA_ARGS__)
456 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000457 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000458 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000459 } else {
460 // Otherwise, emit the error.
461 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
462 return 0;
463 }
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattnera3b605e2008-03-09 03:13:06 +0000465 // Add a marker EOF token to the end of the token list for this argument.
466 SourceLocation EndLoc = Tok.getLocation();
467 Tok.startToken();
468 Tok.setKind(tok::eof);
469 Tok.setLocation(EndLoc);
470 Tok.setLength(0);
471 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000472
473 // If we expect two arguments, add both as empty.
474 if (NumActuals == 0 && MinArgsExpected == 2)
475 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000477 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
478 // Emit the diagnostic at the macro name in case there is a missing ).
479 // Emitting it at the , could be far away from the macro name.
480 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
481 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Jay Foadbeaaccd2009-05-21 09:52:38 +0000484 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000485 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000486}
487
488/// ComputeDATE_TIME - Compute the current time, enter it into the specified
489/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
490/// the identifier tokens inserted.
491static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
492 Preprocessor &PP) {
493 time_t TT = time(0);
494 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattnera3b605e2008-03-09 03:13:06 +0000496 static const char * const Months[] = {
497 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
498 };
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000500 char TmpBuffer[32];
501 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000502 TM->tm_year+1900);
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattner47246be2009-01-26 19:29:26 +0000504 Token TmpTok;
505 TmpTok.startToken();
506 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
507 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000508
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000509 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner47246be2009-01-26 19:29:26 +0000510 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
511 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000512}
513
Chris Lattner148772a2009-06-13 07:13:28 +0000514
515/// HasFeature - Return true if we recognize and implement the specified feature
516/// specified by the identifier.
517static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
518 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Benjamin Kramer32592e82010-01-09 18:53:11 +0000520 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000521 .Case("attribute_analyzer_noreturn", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000522 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000523 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000524 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000525 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000526 .Case("attribute_ns_returns_not_retained", true)
527 .Case("attribute_ns_returns_retained", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000528 .Case("attribute_objc_ivar_unused", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000529 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000530 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000531 .Case("blocks", LangOpts.Blocks)
532 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
533 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
534 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Anders Carlsson37bf9d22010-09-24 21:25:25 +0000535 .Case("cxx_deleted_functions", true) // Accepted as an extension.
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000536 .Case("cxx_exceptions", LangOpts.Exceptions)
537 .Case("cxx_rtti", LangOpts.RTTI)
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000538 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000539 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
Douglas Gregordab60ad2010-10-01 18:44:50 +0000540 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
John McCall48209082010-11-08 19:48:17 +0000541 .Case("enumerator_attributes", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000542 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000543 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000544 .Case("ownership_holds", true)
545 .Case("ownership_returns", true)
546 .Case("ownership_takes", true)
Sebastian Redlf6c09772010-08-31 23:28:47 +0000547 .Case("cxx_inline_namespaces", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000548 //.Case("cxx_concepts", false)
549 //.Case("cxx_lambdas", false)
550 //.Case("cxx_nullptr", false)
551 //.Case("cxx_rvalue_references", false)
552 //.Case("cxx_variadic_templates", false)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000553 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000554 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000555}
556
Anders Carlssoncae50952010-10-20 02:31:43 +0000557/// HasAttribute - Return true if we recognize and implement the attribute
558/// specified by the given identifier.
559static bool HasAttribute(const IdentifierInfo *II) {
560 return llvm::StringSwitch<bool>(II->getName())
561#include "clang/Lex/AttrSpellings.inc"
562 .Default(false);
563}
564
John Thompson92bd8c72009-11-02 22:28:12 +0000565/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
566/// or '__has_include_next("path")' expression.
567/// Returns true if successful.
568static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
569 IdentifierInfo *II, Preprocessor &PP,
570 const DirectoryLookup *LookupFrom) {
571 SourceLocation LParenLoc;
572
573 // Get '('.
574 PP.LexNonComment(Tok);
575
576 // Ensure we have a '('.
577 if (Tok.isNot(tok::l_paren)) {
578 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
579 return false;
580 }
581
582 // Save '(' location for possible missing ')' message.
583 LParenLoc = Tok.getLocation();
584
585 // Get the file name.
586 PP.getCurrentLexer()->LexIncludeFilename(Tok);
587
588 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000589 llvm::SmallString<128> FilenameBuffer;
590 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000591 SourceLocation EndLoc;
592
John Thompson92bd8c72009-11-02 22:28:12 +0000593 switch (Tok.getKind()) {
594 case tok::eom:
595 // If the token kind is EOM, the error has already been diagnosed.
596 return false;
597
598 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000599 case tok::string_literal: {
600 bool Invalid = false;
601 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
602 if (Invalid)
603 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000604 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000605 }
John Thompson92bd8c72009-11-02 22:28:12 +0000606
607 case tok::less:
608 // This could be a <foo/bar.h> file coming from a macro expansion. In this
609 // case, glue the tokens together into FilenameBuffer and interpret those.
610 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000611 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
John Thompson92bd8c72009-11-02 22:28:12 +0000612 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000613 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000614 break;
615 default:
616 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
617 return false;
618 }
619
Chris Lattnera1394812010-01-10 01:35:12 +0000620 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000621 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
622 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000623 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000624 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000625
626 // Search include directories.
627 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +0000628 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000629
630 // Get the result value. Result = true means the file exists.
631 Result = File != 0;
632
633 // Get ')'.
634 PP.LexNonComment(Tok);
635
636 // Ensure we have a trailing ).
637 if (Tok.isNot(tok::r_paren)) {
638 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
639 PP.Diag(LParenLoc, diag::note_matching) << "(";
640 return false;
641 }
642
643 return true;
644}
645
646/// EvaluateHasInclude - Process a '__has_include("path")' expression.
647/// Returns true if successful.
648static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
649 Preprocessor &PP) {
650 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
651}
652
653/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
654/// Returns true if successful.
655static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
656 IdentifierInfo *II, Preprocessor &PP) {
657 // __has_include_next is like __has_include, except that we start
658 // searching after the current found directory. If we can't do this,
659 // issue a diagnostic.
660 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
661 if (PP.isInPrimaryFile()) {
662 Lookup = 0;
663 PP.Diag(Tok, diag::pp_include_next_in_primary);
664 } else if (Lookup == 0) {
665 PP.Diag(Tok, diag::pp_include_next_absolute_path);
666 } else {
667 // Start looking up in the next directory.
668 ++Lookup;
669 }
670
671 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
672}
Chris Lattner148772a2009-06-13 07:13:28 +0000673
Chris Lattnera3b605e2008-03-09 03:13:06 +0000674/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
675/// as a builtin macro, handle it and return the next token as 'Tok'.
676void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
677 // Figure out which token this is.
678 IdentifierInfo *II = Tok.getIdentifierInfo();
679 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000680
John McCall1ef8a2e2010-08-28 22:34:47 +0000681 // If this is an _Pragma or Microsoft __pragma directive, expand it,
682 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000683 if (II == Ident_Pragma)
684 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000685 else if (II == Ident__pragma) // in non-MS mode this is null
686 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Chris Lattnera3b605e2008-03-09 03:13:06 +0000688 ++NumBuiltinMacroExpanded;
689
Benjamin Kramerb1765912010-01-27 16:38:22 +0000690 llvm::SmallString<128> TmpBuffer;
691 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000692
693 // Set up the return result.
694 Tok.setIdentifierInfo(0);
695 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattnera3b605e2008-03-09 03:13:06 +0000697 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000698 // C99 6.10.8: "__LINE__: The presumed line number (within the current
699 // source file) of the current source line (an integer constant)". This can
700 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000701 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerdff070f2009-04-18 22:29:33 +0000703 // Advance to the location of the first _, this might not be the first byte
704 // of the token if it starts with an escaped newline.
705 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattner081927b2009-02-15 21:06:39 +0000707 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
708 // a macro instantiation. This doesn't matter for object-like macros, but
709 // can matter for a function-like macro that expands to contain __LINE__.
710 // Skip down through instantiation points until we find a file loc for the
711 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000712 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000713 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattner1fa49532009-03-08 08:08:45 +0000715 // __LINE__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000716 OS << PLoc.getLine();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000717 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000718 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000719 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
720 // character string literal)". This can be affected by #line.
721 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
722
723 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
724 // #include stack instead of the current file.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000725 if (II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000726 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000727 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000728 PLoc = SourceMgr.getPresumedLoc(NextLoc);
729 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000730 }
731 }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattnera3b605e2008-03-09 03:13:06 +0000733 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000734 llvm::SmallString<128> FN;
735 FN += PLoc.getFilename();
736 Lexer::Stringify(FN);
737 OS << '"' << FN.str() << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000738 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000739 } else if (II == Ident__DATE__) {
740 if (!DATELoc.isValid())
741 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
742 Tok.setKind(tok::string_literal);
743 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000744 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000745 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000746 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000747 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000748 } else if (II == Ident__TIME__) {
749 if (!TIMELoc.isValid())
750 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
751 Tok.setKind(tok::string_literal);
752 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000753 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000754 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000755 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000756 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000757 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000758 // Compute the presumed include depth of this token. This can be affected
759 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000760 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000762 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
763 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
764 for (; PLoc.isValid(); ++Depth)
765 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattner1fa49532009-03-08 08:08:45 +0000767 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000768 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000769 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000770 } else if (II == Ident__TIMESTAMP__) {
771 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
772 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000773
774 // Get the file that we are lexing out of. If we're currently lexing from
775 // a macro, dig into the include stack.
776 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000777 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattnera3b605e2008-03-09 03:13:06 +0000779 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000780 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Chris Lattnera3b605e2008-03-09 03:13:06 +0000782 const char *Result;
783 if (CurFile) {
784 time_t TT = CurFile->getModificationTime();
785 struct tm *TM = localtime(&TT);
786 Result = asctime(TM);
787 } else {
788 Result = "??? ??? ?? ??:??:?? ????\n";
789 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000790 // Surround the string with " and strip the trailing newline.
791 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000792 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000793 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000794 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000795 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000796 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000797 } else if (II == Ident__has_feature ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000798 II == Ident__has_builtin ||
799 II == Ident__has_attribute) {
Chris Lattner148772a2009-06-13 07:13:28 +0000800 // The argument to these two builtins should be a parenthesized identifier.
801 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattner148772a2009-06-13 07:13:28 +0000803 bool IsValid = false;
804 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Chris Lattner148772a2009-06-13 07:13:28 +0000806 // Read the '('.
807 Lex(Tok);
808 if (Tok.is(tok::l_paren)) {
809 // Read the identifier
810 Lex(Tok);
811 if (Tok.is(tok::identifier)) {
812 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner148772a2009-06-13 07:13:28 +0000814 // Read the ')'.
815 Lex(Tok);
816 if (Tok.is(tok::r_paren))
817 IsValid = true;
818 }
819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattner148772a2009-06-13 07:13:28 +0000821 bool Value = false;
822 if (!IsValid)
823 Diag(StartLoc, diag::err_feature_check_malformed);
824 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000825 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000826 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +0000827 } else if (II == Ident__has_attribute)
828 Value = HasAttribute(FeatureII);
829 else {
Chris Lattner148772a2009-06-13 07:13:28 +0000830 assert(II == Ident__has_feature && "Must be feature check");
831 Value = HasFeature(*this, FeatureII);
832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Benjamin Kramerb1765912010-01-27 16:38:22 +0000834 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000835 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000836 } else if (II == Ident__has_include ||
837 II == Ident__has_include_next) {
838 // The argument to these two builtins should be a parenthesized
839 // file name string literal using angle brackets (<>) or
840 // double-quotes ("").
841 bool Value = false;
842 bool IsValid;
843 if (II == Ident__has_include)
844 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
845 else
846 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000847 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000848 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000849 } else {
850 assert(0 && "Unknown identifier!");
851 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000852 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000853}