blob: 5fe2ef172e2f12957c810b538d0e485b314c204d [file] [log] [blame]
Chris Lattner89620152008-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 Lattner60f36222009-01-29 05:15:15 +000020#include "clang/Lex/LexDiagnostic.h"
Benjamin Kramer60fbd642010-01-09 18:53:11 +000021#include "llvm/ADT/StringSwitch.h"
Benjamin Kramerb925f772010-01-27 16:38:22 +000022#include "llvm/Support/raw_ostream.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000023#include <cstdio>
Chris Lattner0725a3e2008-03-18 05:59:11 +000024#include <ctime>
Chris Lattner89620152008-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 Lattner5ec5a302009-04-10 21:17:07 +000030 if (MI) {
Chris Lattner89620152008-03-09 03:13:06 +000031 Macros[II] = MI;
32 II->setHasMacroDefinition(true);
Chris Lattner5ec5a302009-04-10 21:17:07 +000033 } else if (II->hasMacroDefinition()) {
34 Macros.erase(II);
35 II->setHasMacroDefinition(false);
Chris Lattner89620152008-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 Lattnerb6f77af2009-06-13 07:13:28 +000041static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattner89620152008-03-09 03:13:06 +000042 // Get the identifier.
Chris Lattnerb6f77af2009-06-13 07:13:28 +000043 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattner89620152008-03-09 03:13:06 +000045 // Mark it as being a macro that is builtin.
Chris Lattnerb6f77af2009-06-13 07:13:28 +000046 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattner89620152008-03-09 03:13:06 +000047 MI->setIsBuiltinMacro();
Chris Lattnerb6f77af2009-06-13 07:13:28 +000048 PP.setMacroInfo(Id, MI);
Chris Lattner89620152008-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 Lattnerb6f77af2009-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 Stump11289f42009-09-09 15:08:12 +000062
Chris Lattner89620152008-03-09 03:13:06 +000063 // GCC Extensions.
Chris Lattnerb6f77af2009-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 Stump11289f42009-09-09 15:08:12 +000067
Chris Lattnerb6f77af2009-06-13 07:13:28 +000068 // Clang Extensions.
John Thompsonac0b0982009-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 Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +000084
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +0000102
Chris Lattner89620152008-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 Kremeneka2c3c8d2008-11-19 22:43:49 +0000115 else if (CurPTHLexer)
116 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattner89620152008-03-09 03:13:06 +0000117 else
118 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump11289f42009-09-09 15:08:12 +0000119
Chris Lattner89620152008-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 Kremenek76c34412008-11-19 22:21:33 +0000124 if (CurPPLexer)
Chris Lattner89620152008-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 Kremenekcbc984162008-11-20 16:46:54 +0000130 else if (Entry.ThePTHLexer)
131 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattner89620152008-03-09 03:13:06 +0000132 else
133 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattner89620152008-03-09 03:13:06 +0000135 if (Val != 2)
136 break;
Mike Stump11289f42009-09-09 15:08:12 +0000137
Chris Lattner89620152008-03-09 03:13:06 +0000138 // Ran off the end of a source file?
Ted Kremenekcbc984162008-11-20 16:46:54 +0000139 if (Entry.ThePPLexer)
Chris Lattner89620152008-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 Lattnerc17925d2009-04-18 01:13:56 +0000147 return Val == 1;
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +0000152bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattner89620152008-03-09 03:13:06 +0000153 MacroInfo *MI) {
Chris Lattnercf35ce92009-03-12 17:31:43 +0000154 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump11289f42009-09-09 15:08:12 +0000155
Douglas Gregor64213262010-01-26 19:43:43 +0000156 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattner89620152008-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 Kremenek551c82a2008-11-18 01:12:54 +0000159 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump11289f42009-09-09 15:08:12 +0000160
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +0000171
Chris Lattner9dc9c202009-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 Stump11289f42009-09-09 15:08:12 +0000175
Chris Lattner89620152008-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 Lattnerc17925d2009-04-18 01:13:56 +0000179 // name isn't a '(', this macro should not be expanded.
Chris Lattner89620152008-03-09 03:13:06 +0000180 if (!isNextPPTokenLParen())
181 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattner89620152008-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 Lattner9dc9c202009-02-15 20:52:18 +0000187 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner89620152008-03-09 03:13:06 +0000189 // Finished parsing args.
190 InMacroArgs = false;
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattner89620152008-03-09 03:13:06 +0000192 // If there was an error parsing the arguments, bail out.
193 if (Args == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner89620152008-03-09 03:13:06 +0000195 ++NumFnMacroExpanded;
196 } else {
197 ++NumMacroExpanded;
198 }
Mike Stump11289f42009-09-09 15:08:12 +0000199
Chris Lattner89620152008-03-09 03:13:06 +0000200 // Notice that this macro has been used.
201 MI->setIsUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner89620152008-03-09 03:13:06 +0000203 // If we started lexing a macro, enter the macro expansion body.
Mike Stump11289f42009-09-09 15:08:12 +0000204
Chris Lattner89620152008-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 Lattnerffbf2de2009-12-14 22:12:52 +0000209 if (Args) Args->destroy(*this);
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +0000215
Chris Lattner89620152008-03-09 03:13:06 +0000216 Lex(Identifier);
Mike Stump11289f42009-09-09 15:08:12 +0000217
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner89620152008-03-09 03:13:06 +0000229 } else if (MI->getNumTokens() == 1 &&
230 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattner4fa23622009-01-26 00:43:02 +0000231 *this)) {
Chris Lattner89620152008-03-09 03:13:06 +0000232 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump11289f42009-09-09 15:08:12 +0000233 // token: expand it now. This handles common cases like
Chris Lattner89620152008-03-09 03:13:06 +0000234 // "#define VAL 42".
Sam Bishop27654982008-03-21 07:13:02 +0000235
236 // No need for arg info.
Chris Lattnerffbf2de2009-12-14 22:12:52 +0000237 if (Args) Args->destroy(*this);
Sam Bishop27654982008-03-21 07:13:02 +0000238
Chris Lattner89620152008-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 Stump11289f42009-09-09 15:08:12 +0000243
Chris Lattner89620152008-03-09 03:13:06 +0000244 // Remember where the token is instantiated.
245 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner89620152008-03-09 03:13:06 +0000247 // Replace the result token.
248 Identifier = MI->getReplacementToken(0);
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattner89620152008-03-09 03:13:06 +0000250 // Restore the StartOfLine/LeadingSpace markers.
251 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
252 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +0000253
Chris Lattner8a425862009-01-16 07:36:28 +0000254 // Update the tokens location to include both its instantiation and physical
Chris Lattner89620152008-03-09 03:13:06 +0000255 // locations.
256 SourceLocation Loc =
Chris Lattner4fa23622009-01-26 00:43:02 +0000257 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000258 InstantiationEnd,Identifier.getLength());
Chris Lattner89620152008-03-09 03:13:06 +0000259 Identifier.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Chris Lattner89620152008-03-09 03:13:06 +0000261 // If this is #define X X, we must mark the result as unexpandible.
262 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
263 if (getMacroInfo(NewII) == MI)
264 Identifier.setFlag(Token::DisableExpand);
Mike Stump11289f42009-09-09 15:08:12 +0000265
Chris Lattner89620152008-03-09 03:13:06 +0000266 // Since this is not an identifier token, it can't be macro expanded, so
267 // we're done.
268 ++NumFastMacroExpanded;
269 return false;
270 }
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattner89620152008-03-09 03:13:06 +0000272 // Start expanding the macro.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000273 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner89620152008-03-09 03:13:06 +0000275 // Now that the macro is at the top of the include stack, ask the
276 // preprocessor to read the next token from it.
277 Lex(Identifier);
278 return false;
279}
280
Chris Lattnerc17925d2009-04-18 01:13:56 +0000281/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
282/// token is the '(' of the macro, this method is invoked to read all of the
283/// actual arguments specified for the macro invocation. This returns null on
284/// error.
Chris Lattner89620152008-03-09 03:13:06 +0000285MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000286 MacroInfo *MI,
287 SourceLocation &MacroEnd) {
Chris Lattner89620152008-03-09 03:13:06 +0000288 // The number of fixed arguments to parse.
289 unsigned NumFixedArgsLeft = MI->getNumArgs();
290 bool isVariadic = MI->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner89620152008-03-09 03:13:06 +0000292 // Outer loop, while there are more arguments, keep reading them.
293 Token Tok;
Chris Lattner89620152008-03-09 03:13:06 +0000294
Chris Lattnerc17925d2009-04-18 01:13:56 +0000295 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
296 // an argument value in a macro could expand to ',' or '(' or ')'.
297 LexUnexpandedToken(Tok);
298 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump11289f42009-09-09 15:08:12 +0000299
Chris Lattner89620152008-03-09 03:13:06 +0000300 // ArgTokens - Build up a list of tokens that make up each argument. Each
301 // argument is separated by an EOF token. Use a SmallVector so we can avoid
302 // heap allocations in the common case.
303 llvm::SmallVector<Token, 64> ArgTokens;
304
305 unsigned NumActuals = 0;
Chris Lattnerc17925d2009-04-18 01:13:56 +0000306 while (Tok.isNot(tok::r_paren)) {
307 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
308 "only expect argument separators here");
Mike Stump11289f42009-09-09 15:08:12 +0000309
Chris Lattnerc17925d2009-04-18 01:13:56 +0000310 unsigned ArgTokenStart = ArgTokens.size();
311 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner89620152008-03-09 03:13:06 +0000313 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
314 // that we already consumed the first one.
315 unsigned NumParens = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000316
Chris Lattner89620152008-03-09 03:13:06 +0000317 while (1) {
318 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
319 // an argument value in a macro could expand to ',' or '(' or ')'.
320 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattner89620152008-03-09 03:13:06 +0000322 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
323 Diag(MacroName, diag::err_unterm_macro_invoc);
324 // Do not lose the EOF/EOM. Return it to the client.
325 MacroName = Tok;
326 return 0;
327 } else if (Tok.is(tok::r_paren)) {
328 // If we found the ) token, the macro arg list is done.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000329 if (NumParens-- == 0) {
330 MacroEnd = Tok.getLocation();
Chris Lattner89620152008-03-09 03:13:06 +0000331 break;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000332 }
Chris Lattner89620152008-03-09 03:13:06 +0000333 } else if (Tok.is(tok::l_paren)) {
334 ++NumParens;
335 } else if (Tok.is(tok::comma) && NumParens == 0) {
336 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattnerc17925d2009-04-18 01:13:56 +0000337 // However, if this is a variadic macro, and this is part of the
Mike Stump11289f42009-09-09 15:08:12 +0000338 // variadic part, then the comma is just an argument token.
Chris Lattnerc17925d2009-04-18 01:13:56 +0000339 if (!isVariadic) break;
340 if (NumFixedArgsLeft > 1)
Chris Lattner89620152008-03-09 03:13:06 +0000341 break;
Chris Lattner89620152008-03-09 03:13:06 +0000342 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
343 // If this is a comment token in the argument list and we're just in
344 // -C mode (not -CC mode), discard the comment.
345 continue;
Chris Lattner35dd5052009-04-18 06:44:18 +0000346 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattner89620152008-03-09 03:13:06 +0000347 // Reading macro arguments can cause macros that we are currently
348 // expanding from to be popped off the expansion stack. Doing so causes
349 // them to be reenabled for expansion. Here we record whether any
350 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump11289f42009-09-09 15:08:12 +0000351 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattner89620152008-03-09 03:13:06 +0000352 // C99 6.10.3.4p2.
353 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
354 if (!MI->isEnabled())
355 Tok.setFlag(Token::DisableExpand);
356 }
Chris Lattner89620152008-03-09 03:13:06 +0000357 ArgTokens.push_back(Tok);
358 }
Mike Stump11289f42009-09-09 15:08:12 +0000359
Chris Lattnerc17925d2009-04-18 01:13:56 +0000360 // If this was an empty argument list foo(), don't add this as an empty
361 // argument.
362 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
363 break;
Chris Lattner89620152008-03-09 03:13:06 +0000364
Chris Lattnerc17925d2009-04-18 01:13:56 +0000365 // If this is not a variadic macro, and too many args were specified, emit
366 // an error.
367 if (!isVariadic && NumFixedArgsLeft == 0) {
368 if (ArgTokens.size() != ArgTokenStart)
369 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattnerc17925d2009-04-18 01:13:56 +0000371 // Emit the diagnostic at the macro name in case there is a missing ).
372 // Emitting it at the , could be far away from the macro name.
373 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
374 return 0;
375 }
Mike Stump11289f42009-09-09 15:08:12 +0000376
Chris Lattner89620152008-03-09 03:13:06 +0000377 // Empty arguments are standard in C99 and supported as an extension in
378 // other modes.
Chris Lattnerc17925d2009-04-18 01:13:56 +0000379 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattner89620152008-03-09 03:13:06 +0000380 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattner89620152008-03-09 03:13:06 +0000382 // Add a marker EOF token to the end of the token list for this argument.
383 Token EOFTok;
384 EOFTok.startToken();
385 EOFTok.setKind(tok::eof);
Chris Lattner357b57d2009-01-26 20:24:53 +0000386 EOFTok.setLocation(Tok.getLocation());
Chris Lattner89620152008-03-09 03:13:06 +0000387 EOFTok.setLength(0);
388 ArgTokens.push_back(EOFTok);
389 ++NumActuals;
Chris Lattnerc17925d2009-04-18 01:13:56 +0000390 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattner89620152008-03-09 03:13:06 +0000391 --NumFixedArgsLeft;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000392 }
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattner89620152008-03-09 03:13:06 +0000394 // Okay, we either found the r_paren. Check to see if we parsed too few
395 // arguments.
396 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +0000397
Chris Lattner89620152008-03-09 03:13:06 +0000398 // See MacroArgs instance var for description of this.
399 bool isVarargsElided = false;
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner89620152008-03-09 03:13:06 +0000401 if (NumActuals < MinArgsExpected) {
402 // There are several cases where too few arguments is ok, handle them now.
Chris Lattnerf4c68742009-04-20 21:08:10 +0000403 if (NumActuals == 0 && MinArgsExpected == 1) {
404 // #define A(X) or #define A(...) ---> A()
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattnerf4c68742009-04-20 21:08:10 +0000406 // If there is exactly one argument, and that argument is missing,
407 // then we have an empty "()" argument empty list. This is fine, even if
408 // the macro expects one argument (the argument is just empty).
409 isVarargsElided = MI->isVariadic();
410 } else if (MI->isVariadic() &&
411 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
412 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattner89620152008-03-09 03:13:06 +0000413 // Varargs where the named vararg parameter is missing: ok as extension.
414 // #define A(x, ...)
415 // A("blah")
416 Diag(Tok, diag::ext_missing_varargs_arg);
417
Chris Lattnerc17925d2009-04-18 01:13:56 +0000418 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattnerd3300362008-05-08 05:10:33 +0000419 // cases like:
Mike Stump11289f42009-09-09 15:08:12 +0000420 // #define A(x, foo...) blah(a, ## foo)
421 // #define B(x, ...) blah(a, ## __VA_ARGS__)
422 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattnerc17925d2009-04-18 01:13:56 +0000423 // A(x) B(x) C()
Chris Lattnerf4c68742009-04-20 21:08:10 +0000424 isVarargsElided = true;
Chris Lattner89620152008-03-09 03:13:06 +0000425 } else {
426 // Otherwise, emit the error.
427 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
428 return 0;
429 }
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattner89620152008-03-09 03:13:06 +0000431 // Add a marker EOF token to the end of the token list for this argument.
432 SourceLocation EndLoc = Tok.getLocation();
433 Tok.startToken();
434 Tok.setKind(tok::eof);
435 Tok.setLocation(EndLoc);
436 Tok.setLength(0);
437 ArgTokens.push_back(Tok);
Chris Lattnerf160b5f2009-05-13 00:55:26 +0000438
439 // If we expect two arguments, add both as empty.
440 if (NumActuals == 0 && MinArgsExpected == 2)
441 ArgTokens.push_back(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000442
Chris Lattnerc17925d2009-04-18 01:13:56 +0000443 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
444 // Emit the diagnostic at the macro name in case there is a missing ).
445 // Emitting it at the , could be far away from the macro name.
446 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
447 return 0;
Chris Lattner89620152008-03-09 03:13:06 +0000448 }
Mike Stump11289f42009-09-09 15:08:12 +0000449
Jay Foad7d0479f2009-05-21 09:52:38 +0000450 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattnerffbf2de2009-12-14 22:12:52 +0000451 isVarargsElided, *this);
Chris Lattner89620152008-03-09 03:13:06 +0000452}
453
454/// ComputeDATE_TIME - Compute the current time, enter it into the specified
455/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
456/// the identifier tokens inserted.
457static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
458 Preprocessor &PP) {
459 time_t TT = time(0);
460 struct tm *TM = localtime(&TT);
Mike Stump11289f42009-09-09 15:08:12 +0000461
Chris Lattner89620152008-03-09 03:13:06 +0000462 static const char * const Months[] = {
463 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
464 };
Mike Stump11289f42009-09-09 15:08:12 +0000465
Chris Lattner89620152008-03-09 03:13:06 +0000466 char TmpBuffer[100];
Mike Stump11289f42009-09-09 15:08:12 +0000467 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattner89620152008-03-09 03:13:06 +0000468 TM->tm_year+1900);
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattner5a7971e2009-01-26 19:29:26 +0000470 Token TmpTok;
471 TmpTok.startToken();
472 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
473 DATELoc = TmpTok.getLocation();
Chris Lattner89620152008-03-09 03:13:06 +0000474
475 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000476 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
477 TIMELoc = TmpTok.getLocation();
Chris Lattner89620152008-03-09 03:13:06 +0000478}
479
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000480
481/// HasFeature - Return true if we recognize and implement the specified feature
482/// specified by the identifier.
483static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
484 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump11289f42009-09-09 15:08:12 +0000485
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000486 return llvm::StringSwitch<bool>(II->getName())
487 .Case("blocks", LangOpts.Blocks)
488 .Case("cxx_rtti", LangOpts.RTTI)
Alexis Huntaf4e28d2010-01-13 08:31:49 +0000489 //.Case("cxx_lambdas", false)
490 //.Case("cxx_nullptr", false)
491 //.Case("cxx_concepts", false)
492 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
493 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000494 .Case("cxx_exceptions", LangOpts.Exceptions)
Alexis Huntaf4e28d2010-01-13 08:31:49 +0000495 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
496 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000497 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Alexis Huntaf4e28d2010-01-13 08:31:49 +0000498 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
499 //.Case("cxx_rvalue_references", false)
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000500 .Case("attribute_overloadable", true)
Alexis Huntaf4e28d2010-01-13 08:31:49 +0000501 //.Case("cxx_variadic_templates", false)
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000502 .Case("attribute_ext_vector_type", true)
503 .Case("attribute_analyzer_noreturn", true)
Ted Kremenekf2b64ba2010-02-18 00:06:04 +0000504 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000505 .Case("attribute_cf_returns_retained", true)
Ted Kremenekf2b64ba2010-02-18 00:06:04 +0000506 .Case("attribute_ns_returns_not_retained", true)
507 .Case("attribute_ns_returns_retained", true)
Ted Kremeneka00c5db2010-03-05 22:43:32 +0000508 .Case("attribute_objc_ivar_unused", true)
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000509 .Default(false);
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000510}
511
John Thompsonac0b0982009-11-02 22:28:12 +0000512/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
513/// or '__has_include_next("path")' expression.
514/// Returns true if successful.
515static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
516 IdentifierInfo *II, Preprocessor &PP,
517 const DirectoryLookup *LookupFrom) {
518 SourceLocation LParenLoc;
519
520 // Get '('.
521 PP.LexNonComment(Tok);
522
523 // Ensure we have a '('.
524 if (Tok.isNot(tok::l_paren)) {
525 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
526 return false;
527 }
528
529 // Save '(' location for possible missing ')' message.
530 LParenLoc = Tok.getLocation();
531
532 // Get the file name.
533 PP.getCurrentLexer()->LexIncludeFilename(Tok);
534
535 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000536 llvm::SmallString<128> FilenameBuffer;
537 llvm::StringRef Filename;
John Thompsonac0b0982009-11-02 22:28:12 +0000538
539 switch (Tok.getKind()) {
540 case tok::eom:
541 // If the token kind is EOM, the error has already been diagnosed.
542 return false;
543
544 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +0000545 case tok::string_literal:
546 Filename = PP.getSpelling(Tok, FilenameBuffer);
John Thompsonac0b0982009-11-02 22:28:12 +0000547 break;
John Thompsonac0b0982009-11-02 22:28:12 +0000548
549 case tok::less:
550 // This could be a <foo/bar.h> file coming from a macro expansion. In this
551 // case, glue the tokens together into FilenameBuffer and interpret those.
552 FilenameBuffer.push_back('<');
553 if (PP.ConcatenateIncludeName(FilenameBuffer))
554 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000555 Filename = FilenameBuffer.str();
John Thompsonac0b0982009-11-02 22:28:12 +0000556 break;
557 default:
558 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
559 return false;
560 }
561
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000562 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompsonac0b0982009-11-02 22:28:12 +0000563 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
564 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000565 if (Filename.empty())
John Thompsonac0b0982009-11-02 22:28:12 +0000566 return false;
John Thompsonac0b0982009-11-02 22:28:12 +0000567
568 // Search include directories.
569 const DirectoryLookup *CurDir;
Chris Lattnerfde85352010-01-22 00:14:44 +0000570 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompsonac0b0982009-11-02 22:28:12 +0000571
572 // Get the result value. Result = true means the file exists.
573 Result = File != 0;
574
575 // Get ')'.
576 PP.LexNonComment(Tok);
577
578 // Ensure we have a trailing ).
579 if (Tok.isNot(tok::r_paren)) {
580 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
581 PP.Diag(LParenLoc, diag::note_matching) << "(";
582 return false;
583 }
584
585 return true;
586}
587
588/// EvaluateHasInclude - Process a '__has_include("path")' expression.
589/// Returns true if successful.
590static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
591 Preprocessor &PP) {
592 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
593}
594
595/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
596/// Returns true if successful.
597static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
598 IdentifierInfo *II, Preprocessor &PP) {
599 // __has_include_next is like __has_include, except that we start
600 // searching after the current found directory. If we can't do this,
601 // issue a diagnostic.
602 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
603 if (PP.isInPrimaryFile()) {
604 Lookup = 0;
605 PP.Diag(Tok, diag::pp_include_next_in_primary);
606 } else if (Lookup == 0) {
607 PP.Diag(Tok, diag::pp_include_next_absolute_path);
608 } else {
609 // Start looking up in the next directory.
610 ++Lookup;
611 }
612
613 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
614}
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000615
Chris Lattner89620152008-03-09 03:13:06 +0000616/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
617/// as a builtin macro, handle it and return the next token as 'Tok'.
618void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
619 // Figure out which token this is.
620 IdentifierInfo *II = Tok.getIdentifierInfo();
621 assert(II && "Can't be a macro without id info!");
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattner89620152008-03-09 03:13:06 +0000623 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
624 // lex the token after it.
625 if (II == Ident_Pragma)
626 return Handle_Pragma(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000627
Chris Lattner89620152008-03-09 03:13:06 +0000628 ++NumBuiltinMacroExpanded;
629
Benjamin Kramerb925f772010-01-27 16:38:22 +0000630 llvm::SmallString<128> TmpBuffer;
631 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattner89620152008-03-09 03:13:06 +0000632
633 // Set up the return result.
634 Tok.setIdentifierInfo(0);
635 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump11289f42009-09-09 15:08:12 +0000636
Chris Lattner89620152008-03-09 03:13:06 +0000637 if (II == Ident__LINE__) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000638 // C99 6.10.8: "__LINE__: The presumed line number (within the current
639 // source file) of the current source line (an integer constant)". This can
640 // be affected by #line.
Chris Lattner5a2e9cb2009-02-15 21:06:39 +0000641 SourceLocation Loc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000642
Chris Lattnerbf78da72009-04-18 22:29:33 +0000643 // Advance to the location of the first _, this might not be the first byte
644 // of the token if it starts with an escaped newline.
645 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattner5a2e9cb2009-02-15 21:06:39 +0000647 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
648 // a macro instantiation. This doesn't matter for object-like macros, but
649 // can matter for a function-like macro that expands to contain __LINE__.
650 // Skip down through instantiation points until we find a file loc for the
651 // end of the instantiation history.
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000652 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner5a2e9cb2009-02-15 21:06:39 +0000653 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000654
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000655 // __LINE__ expands to a simple numeric value.
Benjamin Kramerb925f772010-01-27 16:38:22 +0000656 OS << PLoc.getLine();
Chris Lattner89620152008-03-09 03:13:06 +0000657 Tok.setKind(tok::numeric_constant);
Chris Lattner89620152008-03-09 03:13:06 +0000658 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000659 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
660 // character string literal)". This can be affected by #line.
661 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
662
663 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
664 // #include stack instead of the current file.
Chris Lattner89620152008-03-09 03:13:06 +0000665 if (II == Ident__BASE_FILE__) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000666 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattner89620152008-03-09 03:13:06 +0000667 while (NextLoc.isValid()) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000668 PLoc = SourceMgr.getPresumedLoc(NextLoc);
669 NextLoc = PLoc.getIncludeLoc();
Chris Lattner89620152008-03-09 03:13:06 +0000670 }
671 }
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattner89620152008-03-09 03:13:06 +0000673 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb925f772010-01-27 16:38:22 +0000674 llvm::SmallString<128> FN;
675 FN += PLoc.getFilename();
676 Lexer::Stringify(FN);
677 OS << '"' << FN.str() << '"';
Chris Lattner89620152008-03-09 03:13:06 +0000678 Tok.setKind(tok::string_literal);
Chris Lattner89620152008-03-09 03:13:06 +0000679 } else if (II == Ident__DATE__) {
680 if (!DATELoc.isValid())
681 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
682 Tok.setKind(tok::string_literal);
683 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattner4fa23622009-01-26 00:43:02 +0000684 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattner9dc9c202009-02-15 20:52:18 +0000685 Tok.getLocation(),
Chris Lattner4fa23622009-01-26 00:43:02 +0000686 Tok.getLength()));
Benjamin Kramerb925f772010-01-27 16:38:22 +0000687 return;
Chris Lattner89620152008-03-09 03:13:06 +0000688 } else if (II == Ident__TIME__) {
689 if (!TIMELoc.isValid())
690 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
691 Tok.setKind(tok::string_literal);
692 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattner4fa23622009-01-26 00:43:02 +0000693 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattner9dc9c202009-02-15 20:52:18 +0000694 Tok.getLocation(),
Chris Lattner4fa23622009-01-26 00:43:02 +0000695 Tok.getLength()));
Benjamin Kramerb925f772010-01-27 16:38:22 +0000696 return;
Chris Lattner89620152008-03-09 03:13:06 +0000697 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000698 // Compute the presumed include depth of this token. This can be affected
699 // by GNU line markers.
Chris Lattner89620152008-03-09 03:13:06 +0000700 unsigned Depth = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000701
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000702 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
703 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
704 for (; PLoc.isValid(); ++Depth)
705 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000707 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb925f772010-01-27 16:38:22 +0000708 OS << Depth;
Chris Lattner89620152008-03-09 03:13:06 +0000709 Tok.setKind(tok::numeric_constant);
Chris Lattner89620152008-03-09 03:13:06 +0000710 } else if (II == Ident__TIMESTAMP__) {
711 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
712 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattner89620152008-03-09 03:13:06 +0000713
714 // Get the file that we are lexing out of. If we're currently lexing from
715 // a macro, dig into the include stack.
716 const FileEntry *CurFile = 0;
Ted Kremenek6552d252008-11-20 01:35:24 +0000717 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattner89620152008-03-09 03:13:06 +0000719 if (TheLexer)
Ted Kremenek2861cf42008-11-19 22:55:25 +0000720 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000721
Chris Lattner89620152008-03-09 03:13:06 +0000722 const char *Result;
723 if (CurFile) {
724 time_t TT = CurFile->getModificationTime();
725 struct tm *TM = localtime(&TT);
726 Result = asctime(TM);
727 } else {
728 Result = "??? ??? ?? ??:??:?? ????\n";
729 }
Benjamin Kramerb925f772010-01-27 16:38:22 +0000730 // Surround the string with " and strip the trailing newline.
731 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattner89620152008-03-09 03:13:06 +0000732 Tok.setKind(tok::string_literal);
Chris Lattner0af3ba12009-04-13 01:29:17 +0000733 } else if (II == Ident__COUNTER__) {
Chris Lattner0af3ba12009-04-13 01:29:17 +0000734 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb925f772010-01-27 16:38:22 +0000735 OS << CounterValue++;
Chris Lattner0af3ba12009-04-13 01:29:17 +0000736 Tok.setKind(tok::numeric_constant);
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000737 } else if (II == Ident__has_feature ||
738 II == Ident__has_builtin) {
739 // The argument to these two builtins should be a parenthesized identifier.
740 SourceLocation StartLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000742 bool IsValid = false;
743 IdentifierInfo *FeatureII = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000744
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000745 // Read the '('.
746 Lex(Tok);
747 if (Tok.is(tok::l_paren)) {
748 // Read the identifier
749 Lex(Tok);
750 if (Tok.is(tok::identifier)) {
751 FeatureII = Tok.getIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000752
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000753 // Read the ')'.
754 Lex(Tok);
755 if (Tok.is(tok::r_paren))
756 IsValid = true;
757 }
758 }
Mike Stump11289f42009-09-09 15:08:12 +0000759
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000760 bool Value = false;
761 if (!IsValid)
762 Diag(StartLoc, diag::err_feature_check_malformed);
763 else if (II == Ident__has_builtin) {
Mike Stump11289f42009-09-09 15:08:12 +0000764 // Check for a builtin is trivial.
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000765 Value = FeatureII->getBuiltinID() != 0;
766 } else {
767 assert(II == Ident__has_feature && "Must be feature check");
768 Value = HasFeature(*this, FeatureII);
769 }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Benjamin Kramerb925f772010-01-27 16:38:22 +0000771 OS << (int)Value;
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000772 Tok.setKind(tok::numeric_constant);
John Thompsonac0b0982009-11-02 22:28:12 +0000773 } else if (II == Ident__has_include ||
774 II == Ident__has_include_next) {
775 // The argument to these two builtins should be a parenthesized
776 // file name string literal using angle brackets (<>) or
777 // double-quotes ("").
778 bool Value = false;
779 bool IsValid;
780 if (II == Ident__has_include)
781 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
782 else
783 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
Benjamin Kramerb925f772010-01-27 16:38:22 +0000784 OS << (int)Value;
John Thompsonac0b0982009-11-02 22:28:12 +0000785 Tok.setKind(tok::numeric_constant);
Chris Lattner89620152008-03-09 03:13:06 +0000786 } else {
787 assert(0 && "Unknown identifier!");
788 }
Benjamin Kramerb925f772010-01-27 16:38:22 +0000789 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattner89620152008-03-09 03:13:06 +0000790}