blob: 1c6a5ad0ebce705a7ba8a07b29a80ac6ba06696c [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"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/Lex/LexDiagnostic.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000021#include "llvm/ADT/StringSwitch.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000022#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000023#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000024#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000025using namespace clang;
26
27/// setMacroInfo - Specify a macro for this identifier.
28///
29void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000030 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000031 Macros[II] = MI;
32 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000033 } else if (II->hasMacroDefinition()) {
34 Macros.erase(II);
35 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000036 }
37}
38
39/// RegisterBuiltinMacro - Register the specified identifier in the identifier
40/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000041static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000042 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000043 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattnera3b605e2008-03-09 03:13:06 +000045 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000046 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000047 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000048 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000049 return Id;
50}
51
52
53/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
54/// identifier table.
55void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000056 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
57 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
58 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
59 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
60 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
61 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattnera3b605e2008-03-09 03:13:06 +000063 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000064 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
65 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
66 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner148772a2009-06-13 07:13:28 +000068 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000069 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
70 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
71 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
72 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Chris Lattnera3b605e2008-03-09 03:13:06 +000073}
74
75/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
76/// in its expansion, currently expands to that token literally.
77static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
78 const IdentifierInfo *MacroIdent,
79 Preprocessor &PP) {
80 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
81
82 // If the token isn't an identifier, it's always literally expanded.
83 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Chris Lattnera3b605e2008-03-09 03:13:06 +000085 // If the identifier is a macro, and if that macro is enabled, it may be
86 // expanded so it's not a trivial expansion.
87 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
88 // Fast expanding "#define X X" is ok, because X would be disabled.
89 II != MacroIdent)
90 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnera3b605e2008-03-09 03:13:06 +000092 // If this is an object-like macro invocation, it is safe to trivially expand
93 // it.
94 if (MI->isObjectLike()) return true;
95
96 // If this is a function-like macro invocation, it's safe to trivially expand
97 // as long as the identifier is not a macro argument.
98 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
99 I != E; ++I)
100 if (*I == II)
101 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattnera3b605e2008-03-09 03:13:06 +0000103 return true;
104}
105
106
107/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
108/// lexed is a '('. If so, consume the token and return true, if not, this
109/// method should have no observable side-effect on the lexed tokens.
110bool Preprocessor::isNextPPTokenLParen() {
111 // Do some quick tests for rejection cases.
112 unsigned Val;
113 if (CurLexer)
114 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000115 else if (CurPTHLexer)
116 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000117 else
118 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattnera3b605e2008-03-09 03:13:06 +0000120 if (Val == 2) {
121 // We have run off the end. If it's a source file we don't
122 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
123 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000124 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000125 return false;
126 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
127 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
128 if (Entry.TheLexer)
129 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000130 else if (Entry.ThePTHLexer)
131 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000132 else
133 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Chris Lattnera3b605e2008-03-09 03:13:06 +0000135 if (Val != 2)
136 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattnera3b605e2008-03-09 03:13:06 +0000138 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000139 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000140 return false;
141 }
142 }
143
144 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
145 // have found something that isn't a '(' or we found the end of the
146 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000147 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000148}
149
150/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
151/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000152bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000153 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000154 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Douglas Gregor13678972010-01-26 19:43:43 +0000156 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157 // then the macro could expand to different things in other contexts, we need
158 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000159 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattnera3b605e2008-03-09 03:13:06 +0000161 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
162 if (MI->isBuiltinMacro()) {
163 ExpandBuiltinMacro(Identifier);
164 return false;
165 }
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattnera3b605e2008-03-09 03:13:06 +0000167 /// Args - If this is a function-like macro expansion, this contains,
168 /// for each macro argument, the list of tokens that were provided to the
169 /// invocation.
170 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Chris Lattnere7fb4842009-02-15 20:52:18 +0000172 // Remember where the end of the instantiation occurred. For an object-like
173 // macro, this is the identifier. For a function-like macro, this is the ')'.
174 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Chris Lattnera3b605e2008-03-09 03:13:06 +0000176 // If this is a function-like macro, read the arguments.
177 if (MI->isFunctionLike()) {
178 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000179 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000180 if (!isNextPPTokenLParen())
181 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattnera3b605e2008-03-09 03:13:06 +0000183 // Remember that we are now parsing the arguments to a macro invocation.
184 // Preprocessor directives used inside macro arguments are not portable, and
185 // this enables the warning.
186 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000187 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Chris Lattnera3b605e2008-03-09 03:13:06 +0000189 // Finished parsing args.
190 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattnera3b605e2008-03-09 03:13:06 +0000192 // If there was an error parsing the arguments, bail out.
193 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattnera3b605e2008-03-09 03:13:06 +0000195 ++NumFnMacroExpanded;
196 } else {
197 ++NumMacroExpanded;
198 }
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattnera3b605e2008-03-09 03:13:06 +0000200 // Notice that this macro has been used.
201 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Chris Lattnera3b605e2008-03-09 03:13:06 +0000203 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Chris Lattnera3b605e2008-03-09 03:13:06 +0000205 // If this macro expands to no tokens, don't bother to push it onto the
206 // expansion stack, only to take it right back off.
207 if (MI->getNumTokens() == 0) {
208 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000209 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chris Lattnera3b605e2008-03-09 03:13:06 +0000211 // Ignore this macro use, just return the next token in the current
212 // buffer.
213 bool HadLeadingSpace = Identifier.hasLeadingSpace();
214 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattnera3b605e2008-03-09 03:13:06 +0000216 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Chris Lattnera3b605e2008-03-09 03:13:06 +0000218 // If the identifier isn't on some OTHER line, inherit the leading
219 // whitespace/first-on-a-line property of this token. This handles
220 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
221 // empty.
222 if (!Identifier.isAtStartOfLine()) {
223 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
224 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
225 }
226 ++NumFastMacroExpanded;
227 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnera3b605e2008-03-09 03:13:06 +0000229 } else if (MI->getNumTokens() == 1 &&
230 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000231 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000232 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000233 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000234 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000235
236 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000237 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000238
Chris Lattnera3b605e2008-03-09 03:13:06 +0000239 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
240 // identifier to the expanded token.
241 bool isAtStartOfLine = Identifier.isAtStartOfLine();
242 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattnera3b605e2008-03-09 03:13:06 +0000244 // Remember where the token is instantiated.
245 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattnera3b605e2008-03-09 03:13:06 +0000247 // Replace the result token.
248 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattnera3b605e2008-03-09 03:13:06 +0000250 // Restore the StartOfLine/LeadingSpace markers.
251 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
252 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000254 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000255 // locations.
256 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000257 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000258 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000259 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner8ff66de2010-03-26 17:49:16 +0000261 // If this is a disabled macro or #define X X, we must mark the result as
262 // unexpandable.
263 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
264 if (MacroInfo *NewMI = getMacroInfo(NewII))
265 if (!NewMI->isEnabled() || NewMI == MI)
266 Identifier.setFlag(Token::DisableExpand);
267 }
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Chris Lattnera3b605e2008-03-09 03:13:06 +0000269 // Since this is not an identifier token, it can't be macro expanded, so
270 // we're done.
271 ++NumFastMacroExpanded;
272 return false;
273 }
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattnera3b605e2008-03-09 03:13:06 +0000275 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000276 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattnera3b605e2008-03-09 03:13:06 +0000278 // Now that the macro is at the top of the include stack, ask the
279 // preprocessor to read the next token from it.
280 Lex(Identifier);
281 return false;
282}
283
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000284/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
285/// token is the '(' of the macro, this method is invoked to read all of the
286/// actual arguments specified for the macro invocation. This returns null on
287/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000288MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000289 MacroInfo *MI,
290 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000291 // The number of fixed arguments to parse.
292 unsigned NumFixedArgsLeft = MI->getNumArgs();
293 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattnera3b605e2008-03-09 03:13:06 +0000295 // Outer loop, while there are more arguments, keep reading them.
296 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000297
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000298 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
299 // an argument value in a macro could expand to ',' or '(' or ')'.
300 LexUnexpandedToken(Tok);
301 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattnera3b605e2008-03-09 03:13:06 +0000303 // ArgTokens - Build up a list of tokens that make up each argument. Each
304 // argument is separated by an EOF token. Use a SmallVector so we can avoid
305 // heap allocations in the common case.
306 llvm::SmallVector<Token, 64> ArgTokens;
307
308 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000309 while (Tok.isNot(tok::r_paren)) {
310 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
311 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000313 unsigned ArgTokenStart = ArgTokens.size();
314 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattnera3b605e2008-03-09 03:13:06 +0000316 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
317 // that we already consumed the first one.
318 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattnera3b605e2008-03-09 03:13:06 +0000320 while (1) {
321 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
322 // an argument value in a macro could expand to ',' or '(' or ')'.
323 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chris Lattnera3b605e2008-03-09 03:13:06 +0000325 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
326 Diag(MacroName, diag::err_unterm_macro_invoc);
327 // Do not lose the EOF/EOM. Return it to the client.
328 MacroName = Tok;
329 return 0;
330 } else if (Tok.is(tok::r_paren)) {
331 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000332 if (NumParens-- == 0) {
333 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000334 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000335 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000336 } else if (Tok.is(tok::l_paren)) {
337 ++NumParens;
338 } else if (Tok.is(tok::comma) && NumParens == 0) {
339 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000340 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000341 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000342 if (!isVariadic) break;
343 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000344 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000345 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
346 // If this is a comment token in the argument list and we're just in
347 // -C mode (not -CC mode), discard the comment.
348 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000349 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000350 // Reading macro arguments can cause macros that we are currently
351 // expanding from to be popped off the expansion stack. Doing so causes
352 // them to be reenabled for expansion. Here we record whether any
353 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000354 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000355 // C99 6.10.3.4p2.
356 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
357 if (!MI->isEnabled())
358 Tok.setFlag(Token::DisableExpand);
359 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000360 ArgTokens.push_back(Tok);
361 }
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000363 // If this was an empty argument list foo(), don't add this as an empty
364 // argument.
365 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
366 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000367
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000368 // If this is not a variadic macro, and too many args were specified, emit
369 // an error.
370 if (!isVariadic && NumFixedArgsLeft == 0) {
371 if (ArgTokens.size() != ArgTokenStart)
372 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000374 // Emit the diagnostic at the macro name in case there is a missing ).
375 // Emitting it at the , could be far away from the macro name.
376 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
377 return 0;
378 }
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattnera3b605e2008-03-09 03:13:06 +0000380 // Empty arguments are standard in C99 and supported as an extension in
381 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000382 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000383 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Chris Lattnera3b605e2008-03-09 03:13:06 +0000385 // Add a marker EOF token to the end of the token list for this argument.
386 Token EOFTok;
387 EOFTok.startToken();
388 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000389 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000390 EOFTok.setLength(0);
391 ArgTokens.push_back(EOFTok);
392 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000393 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000394 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattnera3b605e2008-03-09 03:13:06 +0000397 // Okay, we either found the r_paren. Check to see if we parsed too few
398 // arguments.
399 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattnera3b605e2008-03-09 03:13:06 +0000401 // See MacroArgs instance var for description of this.
402 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattnera3b605e2008-03-09 03:13:06 +0000404 if (NumActuals < MinArgsExpected) {
405 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000406 if (NumActuals == 0 && MinArgsExpected == 1) {
407 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner97e2de12009-04-20 21:08:10 +0000409 // If there is exactly one argument, and that argument is missing,
410 // then we have an empty "()" argument empty list. This is fine, even if
411 // the macro expects one argument (the argument is just empty).
412 isVarargsElided = MI->isVariadic();
413 } else if (MI->isVariadic() &&
414 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
415 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000416 // Varargs where the named vararg parameter is missing: ok as extension.
417 // #define A(x, ...)
418 // A("blah")
419 Diag(Tok, diag::ext_missing_varargs_arg);
420
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000421 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000422 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000423 // #define A(x, foo...) blah(a, ## foo)
424 // #define B(x, ...) blah(a, ## __VA_ARGS__)
425 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000426 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000427 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000428 } else {
429 // Otherwise, emit the error.
430 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
431 return 0;
432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattnera3b605e2008-03-09 03:13:06 +0000434 // Add a marker EOF token to the end of the token list for this argument.
435 SourceLocation EndLoc = Tok.getLocation();
436 Tok.startToken();
437 Tok.setKind(tok::eof);
438 Tok.setLocation(EndLoc);
439 Tok.setLength(0);
440 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000441
442 // If we expect two arguments, add both as empty.
443 if (NumActuals == 0 && MinArgsExpected == 2)
444 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000446 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
447 // Emit the diagnostic at the macro name in case there is a missing ).
448 // Emitting it at the , could be far away from the macro name.
449 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
450 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000451 }
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Jay Foadbeaaccd2009-05-21 09:52:38 +0000453 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000454 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000455}
456
457/// ComputeDATE_TIME - Compute the current time, enter it into the specified
458/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
459/// the identifier tokens inserted.
460static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
461 Preprocessor &PP) {
462 time_t TT = time(0);
463 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattnera3b605e2008-03-09 03:13:06 +0000465 static const char * const Months[] = {
466 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
467 };
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chris Lattnera3b605e2008-03-09 03:13:06 +0000469 char TmpBuffer[100];
Mike Stump1eb44332009-09-09 15:08:12 +0000470 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000471 TM->tm_year+1900);
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner47246be2009-01-26 19:29:26 +0000473 Token TmpTok;
474 TmpTok.startToken();
475 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
476 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000477
478 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner47246be2009-01-26 19:29:26 +0000479 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
480 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000481}
482
Chris Lattner148772a2009-06-13 07:13:28 +0000483
484/// HasFeature - Return true if we recognize and implement the specified feature
485/// specified by the identifier.
486static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
487 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Benjamin Kramer32592e82010-01-09 18:53:11 +0000489 return llvm::StringSwitch<bool>(II->getName())
490 .Case("blocks", LangOpts.Blocks)
491 .Case("cxx_rtti", LangOpts.RTTI)
Sean Hunt4ef4c6b2010-01-13 08:31:49 +0000492 //.Case("cxx_lambdas", false)
493 //.Case("cxx_nullptr", false)
494 //.Case("cxx_concepts", false)
495 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
496 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000497 .Case("cxx_exceptions", LangOpts.Exceptions)
Sean Hunt4ef4c6b2010-01-13 08:31:49 +0000498 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
499 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000500 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Sean Hunt4ef4c6b2010-01-13 08:31:49 +0000501 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
502 //.Case("cxx_rvalue_references", false)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000503 .Case("attribute_overloadable", true)
Sean Hunt4ef4c6b2010-01-13 08:31:49 +0000504 //.Case("cxx_variadic_templates", false)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000505 .Case("attribute_ext_vector_type", true)
506 .Case("attribute_analyzer_noreturn", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000507 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000508 .Case("attribute_cf_returns_retained", 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)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000512 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000513}
514
John Thompson92bd8c72009-11-02 22:28:12 +0000515/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
516/// or '__has_include_next("path")' expression.
517/// Returns true if successful.
518static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
519 IdentifierInfo *II, Preprocessor &PP,
520 const DirectoryLookup *LookupFrom) {
521 SourceLocation LParenLoc;
522
523 // Get '('.
524 PP.LexNonComment(Tok);
525
526 // Ensure we have a '('.
527 if (Tok.isNot(tok::l_paren)) {
528 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
529 return false;
530 }
531
532 // Save '(' location for possible missing ')' message.
533 LParenLoc = Tok.getLocation();
534
535 // Get the file name.
536 PP.getCurrentLexer()->LexIncludeFilename(Tok);
537
538 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000539 llvm::SmallString<128> FilenameBuffer;
540 llvm::StringRef Filename;
John Thompson92bd8c72009-11-02 22:28:12 +0000541
542 switch (Tok.getKind()) {
543 case tok::eom:
544 // If the token kind is EOM, the error has already been diagnosed.
545 return false;
546
547 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000548 case tok::string_literal: {
549 bool Invalid = false;
550 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
551 if (Invalid)
552 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000553 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000554 }
John Thompson92bd8c72009-11-02 22:28:12 +0000555
556 case tok::less:
557 // This could be a <foo/bar.h> file coming from a macro expansion. In this
558 // case, glue the tokens together into FilenameBuffer and interpret those.
559 FilenameBuffer.push_back('<');
560 if (PP.ConcatenateIncludeName(FilenameBuffer))
561 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000562 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000563 break;
564 default:
565 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
566 return false;
567 }
568
Chris Lattnera1394812010-01-10 01:35:12 +0000569 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000570 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
571 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000572 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000573 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000574
575 // Search include directories.
576 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +0000577 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000578
579 // Get the result value. Result = true means the file exists.
580 Result = File != 0;
581
582 // Get ')'.
583 PP.LexNonComment(Tok);
584
585 // Ensure we have a trailing ).
586 if (Tok.isNot(tok::r_paren)) {
587 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
588 PP.Diag(LParenLoc, diag::note_matching) << "(";
589 return false;
590 }
591
592 return true;
593}
594
595/// EvaluateHasInclude - Process a '__has_include("path")' expression.
596/// Returns true if successful.
597static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
598 Preprocessor &PP) {
599 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
600}
601
602/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
603/// Returns true if successful.
604static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
605 IdentifierInfo *II, Preprocessor &PP) {
606 // __has_include_next is like __has_include, except that we start
607 // searching after the current found directory. If we can't do this,
608 // issue a diagnostic.
609 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
610 if (PP.isInPrimaryFile()) {
611 Lookup = 0;
612 PP.Diag(Tok, diag::pp_include_next_in_primary);
613 } else if (Lookup == 0) {
614 PP.Diag(Tok, diag::pp_include_next_absolute_path);
615 } else {
616 // Start looking up in the next directory.
617 ++Lookup;
618 }
619
620 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
621}
Chris Lattner148772a2009-06-13 07:13:28 +0000622
Chris Lattnera3b605e2008-03-09 03:13:06 +0000623/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
624/// as a builtin macro, handle it and return the next token as 'Tok'.
625void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
626 // Figure out which token this is.
627 IdentifierInfo *II = Tok.getIdentifierInfo();
628 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Chris Lattnera3b605e2008-03-09 03:13:06 +0000630 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
631 // lex the token after it.
632 if (II == Ident_Pragma)
633 return Handle_Pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattnera3b605e2008-03-09 03:13:06 +0000635 ++NumBuiltinMacroExpanded;
636
Benjamin Kramerb1765912010-01-27 16:38:22 +0000637 llvm::SmallString<128> TmpBuffer;
638 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000639
640 // Set up the return result.
641 Tok.setIdentifierInfo(0);
642 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Chris Lattnera3b605e2008-03-09 03:13:06 +0000644 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000645 // C99 6.10.8: "__LINE__: The presumed line number (within the current
646 // source file) of the current source line (an integer constant)". This can
647 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000648 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Chris Lattnerdff070f2009-04-18 22:29:33 +0000650 // Advance to the location of the first _, this might not be the first byte
651 // of the token if it starts with an escaped newline.
652 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Chris Lattner081927b2009-02-15 21:06:39 +0000654 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
655 // a macro instantiation. This doesn't matter for object-like macros, but
656 // can matter for a function-like macro that expands to contain __LINE__.
657 // Skip down through instantiation points until we find a file loc for the
658 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000659 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000660 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Chris Lattner1fa49532009-03-08 08:08:45 +0000662 // __LINE__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000663 OS << PLoc.getLine();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000664 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000665 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000666 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
667 // character string literal)". This can be affected by #line.
668 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
669
670 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
671 // #include stack instead of the current file.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000672 if (II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000673 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000674 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000675 PLoc = SourceMgr.getPresumedLoc(NextLoc);
676 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000677 }
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Chris Lattnera3b605e2008-03-09 03:13:06 +0000680 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000681 llvm::SmallString<128> FN;
682 FN += PLoc.getFilename();
683 Lexer::Stringify(FN);
684 OS << '"' << FN.str() << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000685 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000686 } else if (II == Ident__DATE__) {
687 if (!DATELoc.isValid())
688 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
689 Tok.setKind(tok::string_literal);
690 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000691 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000692 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000693 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000694 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000695 } else if (II == Ident__TIME__) {
696 if (!TIMELoc.isValid())
697 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
698 Tok.setKind(tok::string_literal);
699 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000700 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000701 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000702 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000703 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000704 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000705 // Compute the presumed include depth of this token. This can be affected
706 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000707 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000709 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
710 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
711 for (; PLoc.isValid(); ++Depth)
712 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner1fa49532009-03-08 08:08:45 +0000714 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000715 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000716 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000717 } else if (II == Ident__TIMESTAMP__) {
718 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
719 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000720
721 // Get the file that we are lexing out of. If we're currently lexing from
722 // a macro, dig into the include stack.
723 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000724 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattnera3b605e2008-03-09 03:13:06 +0000726 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000727 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Chris Lattnera3b605e2008-03-09 03:13:06 +0000729 const char *Result;
730 if (CurFile) {
731 time_t TT = CurFile->getModificationTime();
732 struct tm *TM = localtime(&TT);
733 Result = asctime(TM);
734 } else {
735 Result = "??? ??? ?? ??:??:?? ????\n";
736 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000737 // Surround the string with " and strip the trailing newline.
738 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000739 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000740 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000741 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000742 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000743 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000744 } else if (II == Ident__has_feature ||
745 II == Ident__has_builtin) {
746 // The argument to these two builtins should be a parenthesized identifier.
747 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Chris Lattner148772a2009-06-13 07:13:28 +0000749 bool IsValid = false;
750 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattner148772a2009-06-13 07:13:28 +0000752 // Read the '('.
753 Lex(Tok);
754 if (Tok.is(tok::l_paren)) {
755 // Read the identifier
756 Lex(Tok);
757 if (Tok.is(tok::identifier)) {
758 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattner148772a2009-06-13 07:13:28 +0000760 // Read the ')'.
761 Lex(Tok);
762 if (Tok.is(tok::r_paren))
763 IsValid = true;
764 }
765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattner148772a2009-06-13 07:13:28 +0000767 bool Value = false;
768 if (!IsValid)
769 Diag(StartLoc, diag::err_feature_check_malformed);
770 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000771 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000772 Value = FeatureII->getBuiltinID() != 0;
773 } else {
774 assert(II == Ident__has_feature && "Must be feature check");
775 Value = HasFeature(*this, FeatureII);
776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Benjamin Kramerb1765912010-01-27 16:38:22 +0000778 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000779 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000780 } else if (II == Ident__has_include ||
781 II == Ident__has_include_next) {
782 // The argument to these two builtins should be a parenthesized
783 // file name string literal using angle brackets (<>) or
784 // double-quotes ("").
785 bool Value = false;
786 bool IsValid;
787 if (II == Ident__has_include)
788 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
789 else
790 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000791 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000792 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000793 } else {
794 assert(0 && "Unknown identifier!");
795 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000796 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000797}