blob: 9015c278fc921e74752b65bf24a032ac89ed49ce [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"
Benjamin Kramer32592e82010-01-09 18:53:11 +000023#include "llvm/ADT/StringSwitch.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000024#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000025#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000026#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000027using namespace clang;
28
29/// setMacroInfo - Specify a macro for this identifier.
30///
31void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000032 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000033 Macros[II] = MI;
34 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000035 } else if (II->hasMacroDefinition()) {
36 Macros.erase(II);
37 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000038 }
39}
40
41/// RegisterBuiltinMacro - Register the specified identifier in the identifier
42/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000043static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000044 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000045 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattnera3b605e2008-03-09 03:13:06 +000047 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000048 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000049 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000050 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000051 return Id;
52}
53
54
55/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
56/// identifier table.
57void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000058 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
59 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
60 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
61 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
62 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
63 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattnera3b605e2008-03-09 03:13:06 +000065 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000066 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
67 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
68 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner148772a2009-06-13 07:13:28 +000070 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000071 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
72 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
73 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
74 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall1ef8a2e2010-08-28 22:34:47 +000075
76 // Microsoft Extensions.
77 if (Features.Microsoft)
78 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
79 else
80 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +000081}
82
83/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
84/// in its expansion, currently expands to that token literally.
85static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
86 const IdentifierInfo *MacroIdent,
87 Preprocessor &PP) {
88 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
89
90 // If the token isn't an identifier, it's always literally expanded.
91 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattnera3b605e2008-03-09 03:13:06 +000093 // If the identifier is a macro, and if that macro is enabled, it may be
94 // expanded so it's not a trivial expansion.
95 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
96 // Fast expanding "#define X X" is ok, because X would be disabled.
97 II != MacroIdent)
98 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattnera3b605e2008-03-09 03:13:06 +0000100 // If this is an object-like macro invocation, it is safe to trivially expand
101 // it.
102 if (MI->isObjectLike()) return true;
103
104 // If this is a function-like macro invocation, it's safe to trivially expand
105 // as long as the identifier is not a macro argument.
106 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
107 I != E; ++I)
108 if (*I == II)
109 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000110
Chris Lattnera3b605e2008-03-09 03:13:06 +0000111 return true;
112}
113
114
115/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
116/// lexed is a '('. If so, consume the token and return true, if not, this
117/// method should have no observable side-effect on the lexed tokens.
118bool Preprocessor::isNextPPTokenLParen() {
119 // Do some quick tests for rejection cases.
120 unsigned Val;
121 if (CurLexer)
122 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000123 else if (CurPTHLexer)
124 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000125 else
126 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Chris Lattnera3b605e2008-03-09 03:13:06 +0000128 if (Val == 2) {
129 // We have run off the end. If it's a source file we don't
130 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
131 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000132 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000133 return false;
134 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
135 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
136 if (Entry.TheLexer)
137 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000138 else if (Entry.ThePTHLexer)
139 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000140 else
141 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattnera3b605e2008-03-09 03:13:06 +0000143 if (Val != 2)
144 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Chris Lattnera3b605e2008-03-09 03:13:06 +0000146 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000147 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000148 return false;
149 }
150 }
151
152 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
153 // have found something that isn't a '(' or we found the end of the
154 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000155 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000156}
157
158/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
159/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000160bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000161 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000162 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Douglas Gregor13678972010-01-26 19:43:43 +0000164 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 // then the macro could expand to different things in other contexts, we need
166 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000167 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Chris Lattnera3b605e2008-03-09 03:13:06 +0000169 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
170 if (MI->isBuiltinMacro()) {
171 ExpandBuiltinMacro(Identifier);
172 return false;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnera3b605e2008-03-09 03:13:06 +0000175 /// Args - If this is a function-like macro expansion, this contains,
176 /// for each macro argument, the list of tokens that were provided to the
177 /// invocation.
178 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattnere7fb4842009-02-15 20:52:18 +0000180 // Remember where the end of the instantiation occurred. For an object-like
181 // macro, this is the identifier. For a function-like macro, this is the ')'.
182 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattnera3b605e2008-03-09 03:13:06 +0000184 // If this is a function-like macro, read the arguments.
185 if (MI->isFunctionLike()) {
186 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000187 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000188 if (!isNextPPTokenLParen())
189 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnera3b605e2008-03-09 03:13:06 +0000191 // Remember that we are now parsing the arguments to a macro invocation.
192 // Preprocessor directives used inside macro arguments are not portable, and
193 // this enables the warning.
194 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000195 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattnera3b605e2008-03-09 03:13:06 +0000197 // Finished parsing args.
198 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattnera3b605e2008-03-09 03:13:06 +0000200 // If there was an error parsing the arguments, bail out.
201 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Chris Lattnera3b605e2008-03-09 03:13:06 +0000203 ++NumFnMacroExpanded;
204 } else {
205 ++NumMacroExpanded;
206 }
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Chris Lattnera3b605e2008-03-09 03:13:06 +0000208 // Notice that this macro has been used.
209 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chris Lattnera3b605e2008-03-09 03:13:06 +0000211 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattnera3b605e2008-03-09 03:13:06 +0000213 // If this macro expands to no tokens, don't bother to push it onto the
214 // expansion stack, only to take it right back off.
215 if (MI->getNumTokens() == 0) {
216 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000217 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Chris Lattnera3b605e2008-03-09 03:13:06 +0000219 // Ignore this macro use, just return the next token in the current
220 // buffer.
221 bool HadLeadingSpace = Identifier.hasLeadingSpace();
222 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Chris Lattnera3b605e2008-03-09 03:13:06 +0000224 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattnera3b605e2008-03-09 03:13:06 +0000226 // If the identifier isn't on some OTHER line, inherit the leading
227 // whitespace/first-on-a-line property of this token. This handles
228 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
229 // empty.
230 if (!Identifier.isAtStartOfLine()) {
231 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
232 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
233 }
234 ++NumFastMacroExpanded;
235 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattnera3b605e2008-03-09 03:13:06 +0000237 } else if (MI->getNumTokens() == 1 &&
238 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000239 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000240 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000241 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000242 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000243
244 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000245 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000246
Chris Lattnera3b605e2008-03-09 03:13:06 +0000247 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
248 // identifier to the expanded token.
249 bool isAtStartOfLine = Identifier.isAtStartOfLine();
250 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattnera3b605e2008-03-09 03:13:06 +0000252 // Remember where the token is instantiated.
253 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattnera3b605e2008-03-09 03:13:06 +0000255 // Replace the result token.
256 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Chris Lattnera3b605e2008-03-09 03:13:06 +0000258 // Restore the StartOfLine/LeadingSpace markers.
259 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
260 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000262 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000263 // locations.
264 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000265 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000266 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000267 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Chris Lattner8ff66de2010-03-26 17:49:16 +0000269 // If this is a disabled macro or #define X X, we must mark the result as
270 // unexpandable.
271 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
272 if (MacroInfo *NewMI = getMacroInfo(NewII))
273 if (!NewMI->isEnabled() || NewMI == MI)
274 Identifier.setFlag(Token::DisableExpand);
275 }
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattnera3b605e2008-03-09 03:13:06 +0000277 // Since this is not an identifier token, it can't be macro expanded, so
278 // we're done.
279 ++NumFastMacroExpanded;
280 return false;
281 }
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnera3b605e2008-03-09 03:13:06 +0000283 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000284 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattnera3b605e2008-03-09 03:13:06 +0000286 // Now that the macro is at the top of the include stack, ask the
287 // preprocessor to read the next token from it.
288 Lex(Identifier);
289 return false;
290}
291
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000292/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
293/// token is the '(' of the macro, this method is invoked to read all of the
294/// actual arguments specified for the macro invocation. This returns null on
295/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000296MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000297 MacroInfo *MI,
298 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000299 // The number of fixed arguments to parse.
300 unsigned NumFixedArgsLeft = MI->getNumArgs();
301 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattnera3b605e2008-03-09 03:13:06 +0000303 // Outer loop, while there are more arguments, keep reading them.
304 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000305
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000306 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
307 // an argument value in a macro could expand to ',' or '(' or ')'.
308 LexUnexpandedToken(Tok);
309 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattnera3b605e2008-03-09 03:13:06 +0000311 // ArgTokens - Build up a list of tokens that make up each argument. Each
312 // argument is separated by an EOF token. Use a SmallVector so we can avoid
313 // heap allocations in the common case.
314 llvm::SmallVector<Token, 64> ArgTokens;
315
316 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000317 while (Tok.isNot(tok::r_paren)) {
318 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
319 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000321 unsigned ArgTokenStart = ArgTokens.size();
322 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattnera3b605e2008-03-09 03:13:06 +0000324 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
325 // that we already consumed the first one.
326 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattnera3b605e2008-03-09 03:13:06 +0000328 while (1) {
329 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
330 // an argument value in a macro could expand to ',' or '(' or ')'.
331 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Douglas Gregorf29c5232010-08-24 22:20:20 +0000333 if (Tok.is(tok::code_completion)) {
334 if (CodeComplete)
335 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
336 MI, NumActuals);
337 LexUnexpandedToken(Tok);
338 }
339
Chris Lattnera3b605e2008-03-09 03:13:06 +0000340 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
341 Diag(MacroName, diag::err_unterm_macro_invoc);
342 // Do not lose the EOF/EOM. Return it to the client.
343 MacroName = Tok;
344 return 0;
345 } else if (Tok.is(tok::r_paren)) {
346 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000347 if (NumParens-- == 0) {
348 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000349 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000350 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000351 } else if (Tok.is(tok::l_paren)) {
352 ++NumParens;
353 } else if (Tok.is(tok::comma) && NumParens == 0) {
354 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000355 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000356 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000357 if (!isVariadic) break;
358 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000359 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000360 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
361 // If this is a comment token in the argument list and we're just in
362 // -C mode (not -CC mode), discard the comment.
363 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000364 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000365 // Reading macro arguments can cause macros that we are currently
366 // expanding from to be popped off the expansion stack. Doing so causes
367 // them to be reenabled for expansion. Here we record whether any
368 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000369 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000370 // C99 6.10.3.4p2.
371 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
372 if (!MI->isEnabled())
373 Tok.setFlag(Token::DisableExpand);
374 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000375 ArgTokens.push_back(Tok);
376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000378 // If this was an empty argument list foo(), don't add this as an empty
379 // argument.
380 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
381 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000382
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000383 // If this is not a variadic macro, and too many args were specified, emit
384 // an error.
385 if (!isVariadic && NumFixedArgsLeft == 0) {
386 if (ArgTokens.size() != ArgTokenStart)
387 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000389 // Emit the diagnostic at the macro name in case there is a missing ).
390 // Emitting it at the , could be far away from the macro name.
391 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
392 return 0;
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattnera3b605e2008-03-09 03:13:06 +0000395 // Empty arguments are standard in C99 and supported as an extension in
396 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000397 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000398 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400 // Add a marker EOF token to the end of the token list for this argument.
401 Token EOFTok;
402 EOFTok.startToken();
403 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000404 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000405 EOFTok.setLength(0);
406 ArgTokens.push_back(EOFTok);
407 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000408 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000409 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000410 }
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Chris Lattnera3b605e2008-03-09 03:13:06 +0000412 // Okay, we either found the r_paren. Check to see if we parsed too few
413 // arguments.
414 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattnera3b605e2008-03-09 03:13:06 +0000416 // See MacroArgs instance var for description of this.
417 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattnera3b605e2008-03-09 03:13:06 +0000419 if (NumActuals < MinArgsExpected) {
420 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000421 if (NumActuals == 0 && MinArgsExpected == 1) {
422 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner97e2de12009-04-20 21:08:10 +0000424 // If there is exactly one argument, and that argument is missing,
425 // then we have an empty "()" argument empty list. This is fine, even if
426 // the macro expects one argument (the argument is just empty).
427 isVarargsElided = MI->isVariadic();
428 } else if (MI->isVariadic() &&
429 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
430 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000431 // Varargs where the named vararg parameter is missing: ok as extension.
432 // #define A(x, ...)
433 // A("blah")
434 Diag(Tok, diag::ext_missing_varargs_arg);
435
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000436 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000437 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000438 // #define A(x, foo...) blah(a, ## foo)
439 // #define B(x, ...) blah(a, ## __VA_ARGS__)
440 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000441 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000442 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000443 } else {
444 // Otherwise, emit the error.
445 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
446 return 0;
447 }
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Chris Lattnera3b605e2008-03-09 03:13:06 +0000449 // Add a marker EOF token to the end of the token list for this argument.
450 SourceLocation EndLoc = Tok.getLocation();
451 Tok.startToken();
452 Tok.setKind(tok::eof);
453 Tok.setLocation(EndLoc);
454 Tok.setLength(0);
455 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000456
457 // If we expect two arguments, add both as empty.
458 if (NumActuals == 0 && MinArgsExpected == 2)
459 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000461 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
462 // Emit the diagnostic at the macro name in case there is a missing ).
463 // Emitting it at the , could be far away from the macro name.
464 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
465 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000466 }
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Jay Foadbeaaccd2009-05-21 09:52:38 +0000468 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000469 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000470}
471
472/// ComputeDATE_TIME - Compute the current time, enter it into the specified
473/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
474/// the identifier tokens inserted.
475static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
476 Preprocessor &PP) {
477 time_t TT = time(0);
478 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattnera3b605e2008-03-09 03:13:06 +0000480 static const char * const Months[] = {
481 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
482 };
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Chris Lattnera3b605e2008-03-09 03:13:06 +0000484 char TmpBuffer[100];
Mike Stump1eb44332009-09-09 15:08:12 +0000485 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000486 TM->tm_year+1900);
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattner47246be2009-01-26 19:29:26 +0000488 Token TmpTok;
489 TmpTok.startToken();
490 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
491 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000492
493 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner47246be2009-01-26 19:29:26 +0000494 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
495 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000496}
497
Chris Lattner148772a2009-06-13 07:13:28 +0000498
499/// HasFeature - Return true if we recognize and implement the specified feature
500/// specified by the identifier.
501static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
502 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Benjamin Kramer32592e82010-01-09 18:53:11 +0000504 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000505 .Case("attribute_analyzer_noreturn", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000506 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000507 .Case("attribute_cf_returns_retained", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000508 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000509 .Case("attribute_ns_returns_not_retained", true)
510 .Case("attribute_ns_returns_retained", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000511 .Case("attribute_objc_ivar_unused", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000512 .Case("attribute_overloadable", true)
513 .Case("blocks", LangOpts.Blocks)
514 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
515 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
516 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
517 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
518 .Case("cxx_exceptions", LangOpts.Exceptions)
519 .Case("cxx_rtti", LangOpts.RTTI)
520 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
521 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000522 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000523 .Case("ownership_holds", true)
524 .Case("ownership_returns", true)
525 .Case("ownership_takes", true)
Sebastian Redlf6c09772010-08-31 23:28:47 +0000526 .Case("cxx_inline_namespaces", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000527 //.Case("cxx_concepts", false)
528 //.Case("cxx_lambdas", false)
529 //.Case("cxx_nullptr", false)
530 //.Case("cxx_rvalue_references", false)
531 //.Case("cxx_variadic_templates", false)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000532 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000533 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000534}
535
John Thompson92bd8c72009-11-02 22:28:12 +0000536/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
537/// or '__has_include_next("path")' expression.
538/// Returns true if successful.
539static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
540 IdentifierInfo *II, Preprocessor &PP,
541 const DirectoryLookup *LookupFrom) {
542 SourceLocation LParenLoc;
543
544 // Get '('.
545 PP.LexNonComment(Tok);
546
547 // Ensure we have a '('.
548 if (Tok.isNot(tok::l_paren)) {
549 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
550 return false;
551 }
552
553 // Save '(' location for possible missing ')' message.
554 LParenLoc = Tok.getLocation();
555
556 // Get the file name.
557 PP.getCurrentLexer()->LexIncludeFilename(Tok);
558
559 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000560 llvm::SmallString<128> FilenameBuffer;
561 llvm::StringRef Filename;
John Thompson92bd8c72009-11-02 22:28:12 +0000562
563 switch (Tok.getKind()) {
564 case tok::eom:
565 // If the token kind is EOM, the error has already been diagnosed.
566 return false;
567
568 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000569 case tok::string_literal: {
570 bool Invalid = false;
571 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
572 if (Invalid)
573 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000574 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000575 }
John Thompson92bd8c72009-11-02 22:28:12 +0000576
577 case tok::less:
578 // This could be a <foo/bar.h> file coming from a macro expansion. In this
579 // case, glue the tokens together into FilenameBuffer and interpret those.
580 FilenameBuffer.push_back('<');
581 if (PP.ConcatenateIncludeName(FilenameBuffer))
582 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000583 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000584 break;
585 default:
586 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
587 return false;
588 }
589
Chris Lattnera1394812010-01-10 01:35:12 +0000590 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000591 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
592 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000593 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000594 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000595
596 // Search include directories.
597 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +0000598 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000599
600 // Get the result value. Result = true means the file exists.
601 Result = File != 0;
602
603 // Get ')'.
604 PP.LexNonComment(Tok);
605
606 // Ensure we have a trailing ).
607 if (Tok.isNot(tok::r_paren)) {
608 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
609 PP.Diag(LParenLoc, diag::note_matching) << "(";
610 return false;
611 }
612
613 return true;
614}
615
616/// EvaluateHasInclude - Process a '__has_include("path")' expression.
617/// Returns true if successful.
618static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
619 Preprocessor &PP) {
620 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
621}
622
623/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
624/// Returns true if successful.
625static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
626 IdentifierInfo *II, Preprocessor &PP) {
627 // __has_include_next is like __has_include, except that we start
628 // searching after the current found directory. If we can't do this,
629 // issue a diagnostic.
630 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
631 if (PP.isInPrimaryFile()) {
632 Lookup = 0;
633 PP.Diag(Tok, diag::pp_include_next_in_primary);
634 } else if (Lookup == 0) {
635 PP.Diag(Tok, diag::pp_include_next_absolute_path);
636 } else {
637 // Start looking up in the next directory.
638 ++Lookup;
639 }
640
641 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
642}
Chris Lattner148772a2009-06-13 07:13:28 +0000643
Chris Lattnera3b605e2008-03-09 03:13:06 +0000644/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
645/// as a builtin macro, handle it and return the next token as 'Tok'.
646void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
647 // Figure out which token this is.
648 IdentifierInfo *II = Tok.getIdentifierInfo();
649 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000650
John McCall1ef8a2e2010-08-28 22:34:47 +0000651 // If this is an _Pragma or Microsoft __pragma directive, expand it,
652 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000653 if (II == Ident_Pragma)
654 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000655 else if (II == Ident__pragma) // in non-MS mode this is null
656 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattnera3b605e2008-03-09 03:13:06 +0000658 ++NumBuiltinMacroExpanded;
659
Benjamin Kramerb1765912010-01-27 16:38:22 +0000660 llvm::SmallString<128> TmpBuffer;
661 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000662
663 // Set up the return result.
664 Tok.setIdentifierInfo(0);
665 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattnera3b605e2008-03-09 03:13:06 +0000667 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000668 // C99 6.10.8: "__LINE__: The presumed line number (within the current
669 // source file) of the current source line (an integer constant)". This can
670 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000671 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattnerdff070f2009-04-18 22:29:33 +0000673 // Advance to the location of the first _, this might not be the first byte
674 // of the token if it starts with an escaped newline.
675 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattner081927b2009-02-15 21:06:39 +0000677 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
678 // a macro instantiation. This doesn't matter for object-like macros, but
679 // can matter for a function-like macro that expands to contain __LINE__.
680 // Skip down through instantiation points until we find a file loc for the
681 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000682 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000683 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner1fa49532009-03-08 08:08:45 +0000685 // __LINE__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000686 OS << PLoc.getLine();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000687 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000688 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000689 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
690 // character string literal)". This can be affected by #line.
691 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
692
693 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
694 // #include stack instead of the current file.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000695 if (II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000696 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000697 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000698 PLoc = SourceMgr.getPresumedLoc(NextLoc);
699 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000700 }
701 }
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnera3b605e2008-03-09 03:13:06 +0000703 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000704 llvm::SmallString<128> FN;
705 FN += PLoc.getFilename();
706 Lexer::Stringify(FN);
707 OS << '"' << FN.str() << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000708 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000709 } else if (II == Ident__DATE__) {
710 if (!DATELoc.isValid())
711 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
712 Tok.setKind(tok::string_literal);
713 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000714 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000715 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000716 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000717 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000718 } else if (II == Ident__TIME__) {
719 if (!TIMELoc.isValid())
720 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
721 Tok.setKind(tok::string_literal);
722 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000723 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000724 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000725 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000726 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000727 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000728 // Compute the presumed include depth of this token. This can be affected
729 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000730 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000732 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
733 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
734 for (; PLoc.isValid(); ++Depth)
735 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Chris Lattner1fa49532009-03-08 08:08:45 +0000737 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000738 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000739 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000740 } else if (II == Ident__TIMESTAMP__) {
741 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
742 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000743
744 // Get the file that we are lexing out of. If we're currently lexing from
745 // a macro, dig into the include stack.
746 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000747 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Chris Lattnera3b605e2008-03-09 03:13:06 +0000749 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000750 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattnera3b605e2008-03-09 03:13:06 +0000752 const char *Result;
753 if (CurFile) {
754 time_t TT = CurFile->getModificationTime();
755 struct tm *TM = localtime(&TT);
756 Result = asctime(TM);
757 } else {
758 Result = "??? ??? ?? ??:??:?? ????\n";
759 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000760 // Surround the string with " and strip the trailing newline.
761 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000762 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000763 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000764 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000765 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000766 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000767 } else if (II == Ident__has_feature ||
768 II == Ident__has_builtin) {
769 // The argument to these two builtins should be a parenthesized identifier.
770 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Chris Lattner148772a2009-06-13 07:13:28 +0000772 bool IsValid = false;
773 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattner148772a2009-06-13 07:13:28 +0000775 // Read the '('.
776 Lex(Tok);
777 if (Tok.is(tok::l_paren)) {
778 // Read the identifier
779 Lex(Tok);
780 if (Tok.is(tok::identifier)) {
781 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattner148772a2009-06-13 07:13:28 +0000783 // Read the ')'.
784 Lex(Tok);
785 if (Tok.is(tok::r_paren))
786 IsValid = true;
787 }
788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Chris Lattner148772a2009-06-13 07:13:28 +0000790 bool Value = false;
791 if (!IsValid)
792 Diag(StartLoc, diag::err_feature_check_malformed);
793 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000794 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000795 Value = FeatureII->getBuiltinID() != 0;
796 } else {
797 assert(II == Ident__has_feature && "Must be feature check");
798 Value = HasFeature(*this, FeatureII);
799 }
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Benjamin Kramerb1765912010-01-27 16:38:22 +0000801 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000802 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000803 } else if (II == Ident__has_include ||
804 II == Ident__has_include_next) {
805 // The argument to these two builtins should be a parenthesized
806 // file name string literal using angle brackets (<>) or
807 // double-quotes ("").
808 bool Value = false;
809 bool IsValid;
810 if (II == Ident__has_include)
811 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
812 else
813 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000814 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000815 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000816 } else {
817 assert(0 && "Unknown identifier!");
818 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000819 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000820}