blob: 2428f9af4504db0a33236ec214fa49ec67bebd33 [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"
Eric Christopher03256c32010-06-24 02:02:00 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000021#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorec00a262010-08-24 22:20:20 +000022#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor5ef9e332010-10-30 00:23:06 +000023#include "clang/Lex/ExternalPreprocessorSource.h"
Benjamin Kramer60fbd642010-01-09 18:53:11 +000024#include "llvm/ADT/StringSwitch.h"
Douglas Gregorae674f32010-11-09 05:43:53 +000025#include "llvm/Config/config.h"
Benjamin Kramerb925f772010-01-27 16:38:22 +000026#include "llvm/Support/raw_ostream.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000027#include <cstdio>
Chris Lattner0725a3e2008-03-18 05:59:11 +000028#include <ctime>
Chris Lattner89620152008-03-09 03:13:06 +000029using namespace clang;
30
Douglas Gregor5ef9e332010-10-30 00:23:06 +000031MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
32 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
33
34 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
35 = Macros.find(II);
36 if (Pos == Macros.end()) {
37 // Load this macro from the external source.
38 getExternalSource()->LoadMacroDefinition(II);
39 Pos = Macros.find(II);
40 }
41 assert(Pos != Macros.end() && "Identifier macro info is missing!");
42 return Pos->second;
43}
44
Chris Lattner89620152008-03-09 03:13:06 +000045/// setMacroInfo - Specify a macro for this identifier.
46///
47void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner5ec5a302009-04-10 21:17:07 +000048 if (MI) {
Chris Lattner89620152008-03-09 03:13:06 +000049 Macros[II] = MI;
50 II->setHasMacroDefinition(true);
Chris Lattner5ec5a302009-04-10 21:17:07 +000051 } else if (II->hasMacroDefinition()) {
52 Macros.erase(II);
53 II->setHasMacroDefinition(false);
Chris Lattner89620152008-03-09 03:13:06 +000054 }
55}
56
57/// RegisterBuiltinMacro - Register the specified identifier in the identifier
58/// table and mark it as a builtin macro to be expanded.
Chris Lattnerb6f77af2009-06-13 07:13:28 +000059static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattner89620152008-03-09 03:13:06 +000060 // Get the identifier.
Chris Lattnerb6f77af2009-06-13 07:13:28 +000061 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattner89620152008-03-09 03:13:06 +000063 // Mark it as being a macro that is builtin.
Chris Lattnerb6f77af2009-06-13 07:13:28 +000064 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattner89620152008-03-09 03:13:06 +000065 MI->setIsBuiltinMacro();
Chris Lattnerb6f77af2009-06-13 07:13:28 +000066 PP.setMacroInfo(Id, MI);
Chris Lattner89620152008-03-09 03:13:06 +000067 return Id;
68}
69
70
71/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
72/// identifier table.
73void Preprocessor::RegisterBuiltinMacros() {
Chris Lattnerb6f77af2009-06-13 07:13:28 +000074 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
75 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
76 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
77 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
78 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
79 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner89620152008-03-09 03:13:06 +000081 // GCC Extensions.
Chris Lattnerb6f77af2009-06-13 07:13:28 +000082 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
83 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
84 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattnerb6f77af2009-06-13 07:13:28 +000086 // Clang Extensions.
John Thompsonac0b0982009-11-02 22:28:12 +000087 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
88 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlsson274a70e2010-10-20 02:31:43 +000089 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompsonac0b0982009-11-02 22:28:12 +000090 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
91 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall89e925d2010-08-28 22:34:47 +000092
93 // Microsoft Extensions.
94 if (Features.Microsoft)
95 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
96 else
97 Ident__pragma = 0;
Chris Lattner89620152008-03-09 03:13:06 +000098}
99
100/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
101/// in its expansion, currently expands to that token literally.
102static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
103 const IdentifierInfo *MacroIdent,
104 Preprocessor &PP) {
105 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
106
107 // If the token isn't an identifier, it's always literally expanded.
108 if (II == 0) return true;
Mike Stump11289f42009-09-09 15:08:12 +0000109
Chris Lattner89620152008-03-09 03:13:06 +0000110 // If the identifier is a macro, and if that macro is enabled, it may be
111 // expanded so it's not a trivial expansion.
112 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
113 // Fast expanding "#define X X" is ok, because X would be disabled.
114 II != MacroIdent)
115 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattner89620152008-03-09 03:13:06 +0000117 // If this is an object-like macro invocation, it is safe to trivially expand
118 // it.
119 if (MI->isObjectLike()) return true;
120
121 // If this is a function-like macro invocation, it's safe to trivially expand
122 // as long as the identifier is not a macro argument.
123 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
124 I != E; ++I)
125 if (*I == II)
126 return false; // Identifier is a macro argument.
Mike Stump11289f42009-09-09 15:08:12 +0000127
Chris Lattner89620152008-03-09 03:13:06 +0000128 return true;
129}
130
131
132/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
133/// lexed is a '('. If so, consume the token and return true, if not, this
134/// method should have no observable side-effect on the lexed tokens.
135bool Preprocessor::isNextPPTokenLParen() {
136 // Do some quick tests for rejection cases.
137 unsigned Val;
138 if (CurLexer)
139 Val = CurLexer->isNextPPTokenLParen();
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000140 else if (CurPTHLexer)
141 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattner89620152008-03-09 03:13:06 +0000142 else
143 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump11289f42009-09-09 15:08:12 +0000144
Chris Lattner89620152008-03-09 03:13:06 +0000145 if (Val == 2) {
146 // We have run off the end. If it's a source file we don't
147 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
148 // macro stack.
Ted Kremenek76c34412008-11-19 22:21:33 +0000149 if (CurPPLexer)
Chris Lattner89620152008-03-09 03:13:06 +0000150 return false;
151 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
152 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
153 if (Entry.TheLexer)
154 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekcbc984162008-11-20 16:46:54 +0000155 else if (Entry.ThePTHLexer)
156 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattner89620152008-03-09 03:13:06 +0000157 else
158 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Chris Lattner89620152008-03-09 03:13:06 +0000160 if (Val != 2)
161 break;
Mike Stump11289f42009-09-09 15:08:12 +0000162
Chris Lattner89620152008-03-09 03:13:06 +0000163 // Ran off the end of a source file?
Ted Kremenekcbc984162008-11-20 16:46:54 +0000164 if (Entry.ThePPLexer)
Chris Lattner89620152008-03-09 03:13:06 +0000165 return false;
166 }
167 }
168
169 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
170 // have found something that isn't a '(' or we found the end of the
171 // translation unit. In either case, return false.
Chris Lattnerc17925d2009-04-18 01:13:56 +0000172 return Val == 1;
Chris Lattner89620152008-03-09 03:13:06 +0000173}
174
175/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
176/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump11289f42009-09-09 15:08:12 +0000177bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattner89620152008-03-09 03:13:06 +0000178 MacroInfo *MI) {
Chris Lattnercf35ce92009-03-12 17:31:43 +0000179 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump11289f42009-09-09 15:08:12 +0000180
Douglas Gregor64213262010-01-26 19:43:43 +0000181 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattner89620152008-03-09 03:13:06 +0000182 // then the macro could expand to different things in other contexts, we need
183 // to disable the optimization in this case.
Ted Kremenek551c82a2008-11-18 01:12:54 +0000184 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattner89620152008-03-09 03:13:06 +0000186 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
187 if (MI->isBuiltinMacro()) {
188 ExpandBuiltinMacro(Identifier);
189 return false;
190 }
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattner89620152008-03-09 03:13:06 +0000192 /// Args - If this is a function-like macro expansion, this contains,
193 /// for each macro argument, the list of tokens that were provided to the
194 /// invocation.
195 MacroArgs *Args = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000196
Chris Lattner9dc9c202009-02-15 20:52:18 +0000197 // Remember where the end of the instantiation occurred. For an object-like
198 // macro, this is the identifier. For a function-like macro, this is the ')'.
199 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000200
Chris Lattner89620152008-03-09 03:13:06 +0000201 // If this is a function-like macro, read the arguments.
202 if (MI->isFunctionLike()) {
203 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattnerc17925d2009-04-18 01:13:56 +0000204 // name isn't a '(', this macro should not be expanded.
Chris Lattner89620152008-03-09 03:13:06 +0000205 if (!isNextPPTokenLParen())
206 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000207
Chris Lattner89620152008-03-09 03:13:06 +0000208 // Remember that we are now parsing the arguments to a macro invocation.
209 // Preprocessor directives used inside macro arguments are not portable, and
210 // this enables the warning.
211 InMacroArgs = true;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000212 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner89620152008-03-09 03:13:06 +0000214 // Finished parsing args.
215 InMacroArgs = false;
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner89620152008-03-09 03:13:06 +0000217 // If there was an error parsing the arguments, bail out.
218 if (Args == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000219
Chris Lattner89620152008-03-09 03:13:06 +0000220 ++NumFnMacroExpanded;
221 } else {
222 ++NumMacroExpanded;
223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224
Chris Lattner89620152008-03-09 03:13:06 +0000225 // Notice that this macro has been used.
226 MI->setIsUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner89620152008-03-09 03:13:06 +0000228 // If we started lexing a macro, enter the macro expansion body.
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattner89620152008-03-09 03:13:06 +0000230 // If this macro expands to no tokens, don't bother to push it onto the
231 // expansion stack, only to take it right back off.
232 if (MI->getNumTokens() == 0) {
233 // No need for arg info.
Chris Lattnerffbf2de2009-12-14 22:12:52 +0000234 if (Args) Args->destroy(*this);
Mike Stump11289f42009-09-09 15:08:12 +0000235
Chris Lattner89620152008-03-09 03:13:06 +0000236 // Ignore this macro use, just return the next token in the current
237 // buffer.
238 bool HadLeadingSpace = Identifier.hasLeadingSpace();
239 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump11289f42009-09-09 15:08:12 +0000240
Chris Lattner89620152008-03-09 03:13:06 +0000241 Lex(Identifier);
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattner89620152008-03-09 03:13:06 +0000243 // If the identifier isn't on some OTHER line, inherit the leading
244 // whitespace/first-on-a-line property of this token. This handles
245 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
246 // empty.
247 if (!Identifier.isAtStartOfLine()) {
248 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
249 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
250 }
251 ++NumFastMacroExpanded;
252 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000253
Chris Lattner89620152008-03-09 03:13:06 +0000254 } else if (MI->getNumTokens() == 1 &&
255 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattner4fa23622009-01-26 00:43:02 +0000256 *this)) {
Chris Lattner89620152008-03-09 03:13:06 +0000257 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump11289f42009-09-09 15:08:12 +0000258 // token: expand it now. This handles common cases like
Chris Lattner89620152008-03-09 03:13:06 +0000259 // "#define VAL 42".
Sam Bishop27654982008-03-21 07:13:02 +0000260
261 // No need for arg info.
Chris Lattnerffbf2de2009-12-14 22:12:52 +0000262 if (Args) Args->destroy(*this);
Sam Bishop27654982008-03-21 07:13:02 +0000263
Chris Lattner89620152008-03-09 03:13:06 +0000264 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
265 // identifier to the expanded token.
266 bool isAtStartOfLine = Identifier.isAtStartOfLine();
267 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump11289f42009-09-09 15:08:12 +0000268
Chris Lattner89620152008-03-09 03:13:06 +0000269 // Remember where the token is instantiated.
270 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattner89620152008-03-09 03:13:06 +0000272 // Replace the result token.
273 Identifier = MI->getReplacementToken(0);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner89620152008-03-09 03:13:06 +0000275 // Restore the StartOfLine/LeadingSpace markers.
276 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
277 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattner8a425862009-01-16 07:36:28 +0000279 // Update the tokens location to include both its instantiation and physical
Chris Lattner89620152008-03-09 03:13:06 +0000280 // locations.
281 SourceLocation Loc =
Chris Lattner4fa23622009-01-26 00:43:02 +0000282 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000283 InstantiationEnd,Identifier.getLength());
Chris Lattner89620152008-03-09 03:13:06 +0000284 Identifier.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner8c5d05a2010-03-26 17:49:16 +0000286 // If this is a disabled macro or #define X X, we must mark the result as
287 // unexpandable.
288 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
289 if (MacroInfo *NewMI = getMacroInfo(NewII))
290 if (!NewMI->isEnabled() || NewMI == MI)
291 Identifier.setFlag(Token::DisableExpand);
292 }
Mike Stump11289f42009-09-09 15:08:12 +0000293
Chris Lattner89620152008-03-09 03:13:06 +0000294 // Since this is not an identifier token, it can't be macro expanded, so
295 // we're done.
296 ++NumFastMacroExpanded;
297 return false;
298 }
Mike Stump11289f42009-09-09 15:08:12 +0000299
Chris Lattner89620152008-03-09 03:13:06 +0000300 // Start expanding the macro.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000301 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000302
Chris Lattner89620152008-03-09 03:13:06 +0000303 // Now that the macro is at the top of the include stack, ask the
304 // preprocessor to read the next token from it.
305 Lex(Identifier);
306 return false;
307}
308
Chris Lattnerc17925d2009-04-18 01:13:56 +0000309/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
310/// token is the '(' of the macro, this method is invoked to read all of the
311/// actual arguments specified for the macro invocation. This returns null on
312/// error.
Chris Lattner89620152008-03-09 03:13:06 +0000313MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000314 MacroInfo *MI,
315 SourceLocation &MacroEnd) {
Chris Lattner89620152008-03-09 03:13:06 +0000316 // The number of fixed arguments to parse.
317 unsigned NumFixedArgsLeft = MI->getNumArgs();
318 bool isVariadic = MI->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chris Lattner89620152008-03-09 03:13:06 +0000320 // Outer loop, while there are more arguments, keep reading them.
321 Token Tok;
Chris Lattner89620152008-03-09 03:13:06 +0000322
Chris Lattnerc17925d2009-04-18 01:13:56 +0000323 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
324 // an argument value in a macro could expand to ',' or '(' or ')'.
325 LexUnexpandedToken(Tok);
326 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattner89620152008-03-09 03:13:06 +0000328 // ArgTokens - Build up a list of tokens that make up each argument. Each
329 // argument is separated by an EOF token. Use a SmallVector so we can avoid
330 // heap allocations in the common case.
331 llvm::SmallVector<Token, 64> ArgTokens;
332
333 unsigned NumActuals = 0;
Chris Lattnerc17925d2009-04-18 01:13:56 +0000334 while (Tok.isNot(tok::r_paren)) {
335 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
336 "only expect argument separators here");
Mike Stump11289f42009-09-09 15:08:12 +0000337
Chris Lattnerc17925d2009-04-18 01:13:56 +0000338 unsigned ArgTokenStart = ArgTokens.size();
339 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000340
Chris Lattner89620152008-03-09 03:13:06 +0000341 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
342 // that we already consumed the first one.
343 unsigned NumParens = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000344
Chris Lattner89620152008-03-09 03:13:06 +0000345 while (1) {
346 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
347 // an argument value in a macro could expand to ',' or '(' or ')'.
348 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000349
Douglas Gregorec00a262010-08-24 22:20:20 +0000350 if (Tok.is(tok::code_completion)) {
351 if (CodeComplete)
352 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
353 MI, NumActuals);
354 LexUnexpandedToken(Tok);
355 }
356
Chris Lattner89620152008-03-09 03:13:06 +0000357 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
358 Diag(MacroName, diag::err_unterm_macro_invoc);
359 // Do not lose the EOF/EOM. Return it to the client.
360 MacroName = Tok;
361 return 0;
362 } else if (Tok.is(tok::r_paren)) {
363 // If we found the ) token, the macro arg list is done.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000364 if (NumParens-- == 0) {
365 MacroEnd = Tok.getLocation();
Chris Lattner89620152008-03-09 03:13:06 +0000366 break;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000367 }
Chris Lattner89620152008-03-09 03:13:06 +0000368 } else if (Tok.is(tok::l_paren)) {
369 ++NumParens;
370 } else if (Tok.is(tok::comma) && NumParens == 0) {
371 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattnerc17925d2009-04-18 01:13:56 +0000372 // However, if this is a variadic macro, and this is part of the
Mike Stump11289f42009-09-09 15:08:12 +0000373 // variadic part, then the comma is just an argument token.
Chris Lattnerc17925d2009-04-18 01:13:56 +0000374 if (!isVariadic) break;
375 if (NumFixedArgsLeft > 1)
Chris Lattner89620152008-03-09 03:13:06 +0000376 break;
Chris Lattner89620152008-03-09 03:13:06 +0000377 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
378 // If this is a comment token in the argument list and we're just in
379 // -C mode (not -CC mode), discard the comment.
380 continue;
Chris Lattner35dd5052009-04-18 06:44:18 +0000381 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattner89620152008-03-09 03:13:06 +0000382 // Reading macro arguments can cause macros that we are currently
383 // expanding from to be popped off the expansion stack. Doing so causes
384 // them to be reenabled for expansion. Here we record whether any
385 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump11289f42009-09-09 15:08:12 +0000386 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattner89620152008-03-09 03:13:06 +0000387 // C99 6.10.3.4p2.
388 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
389 if (!MI->isEnabled())
390 Tok.setFlag(Token::DisableExpand);
391 }
Chris Lattner89620152008-03-09 03:13:06 +0000392 ArgTokens.push_back(Tok);
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnerc17925d2009-04-18 01:13:56 +0000395 // If this was an empty argument list foo(), don't add this as an empty
396 // argument.
397 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
398 break;
Chris Lattner89620152008-03-09 03:13:06 +0000399
Chris Lattnerc17925d2009-04-18 01:13:56 +0000400 // If this is not a variadic macro, and too many args were specified, emit
401 // an error.
402 if (!isVariadic && NumFixedArgsLeft == 0) {
403 if (ArgTokens.size() != ArgTokenStart)
404 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattnerc17925d2009-04-18 01:13:56 +0000406 // Emit the diagnostic at the macro name in case there is a missing ).
407 // Emitting it at the , could be far away from the macro name.
408 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
409 return 0;
410 }
Mike Stump11289f42009-09-09 15:08:12 +0000411
Chris Lattner89620152008-03-09 03:13:06 +0000412 // Empty arguments are standard in C99 and supported as an extension in
413 // other modes.
Chris Lattnerc17925d2009-04-18 01:13:56 +0000414 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattner89620152008-03-09 03:13:06 +0000415 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattner89620152008-03-09 03:13:06 +0000417 // Add a marker EOF token to the end of the token list for this argument.
418 Token EOFTok;
419 EOFTok.startToken();
420 EOFTok.setKind(tok::eof);
Chris Lattner357b57d2009-01-26 20:24:53 +0000421 EOFTok.setLocation(Tok.getLocation());
Chris Lattner89620152008-03-09 03:13:06 +0000422 EOFTok.setLength(0);
423 ArgTokens.push_back(EOFTok);
424 ++NumActuals;
Chris Lattnerc17925d2009-04-18 01:13:56 +0000425 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattner89620152008-03-09 03:13:06 +0000426 --NumFixedArgsLeft;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000427 }
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattner89620152008-03-09 03:13:06 +0000429 // Okay, we either found the r_paren. Check to see if we parsed too few
430 // arguments.
431 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +0000432
Chris Lattner89620152008-03-09 03:13:06 +0000433 // See MacroArgs instance var for description of this.
434 bool isVarargsElided = false;
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattner89620152008-03-09 03:13:06 +0000436 if (NumActuals < MinArgsExpected) {
437 // There are several cases where too few arguments is ok, handle them now.
Chris Lattnerf4c68742009-04-20 21:08:10 +0000438 if (NumActuals == 0 && MinArgsExpected == 1) {
439 // #define A(X) or #define A(...) ---> A()
Mike Stump11289f42009-09-09 15:08:12 +0000440
Chris Lattnerf4c68742009-04-20 21:08:10 +0000441 // If there is exactly one argument, and that argument is missing,
442 // then we have an empty "()" argument empty list. This is fine, even if
443 // the macro expects one argument (the argument is just empty).
444 isVarargsElided = MI->isVariadic();
445 } else if (MI->isVariadic() &&
446 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
447 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattner89620152008-03-09 03:13:06 +0000448 // Varargs where the named vararg parameter is missing: ok as extension.
449 // #define A(x, ...)
450 // A("blah")
451 Diag(Tok, diag::ext_missing_varargs_arg);
452
Chris Lattnerc17925d2009-04-18 01:13:56 +0000453 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattnerd3300362008-05-08 05:10:33 +0000454 // cases like:
Mike Stump11289f42009-09-09 15:08:12 +0000455 // #define A(x, foo...) blah(a, ## foo)
456 // #define B(x, ...) blah(a, ## __VA_ARGS__)
457 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattnerc17925d2009-04-18 01:13:56 +0000458 // A(x) B(x) C()
Chris Lattnerf4c68742009-04-20 21:08:10 +0000459 isVarargsElided = true;
Chris Lattner89620152008-03-09 03:13:06 +0000460 } else {
461 // Otherwise, emit the error.
462 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
463 return 0;
464 }
Mike Stump11289f42009-09-09 15:08:12 +0000465
Chris Lattner89620152008-03-09 03:13:06 +0000466 // Add a marker EOF token to the end of the token list for this argument.
467 SourceLocation EndLoc = Tok.getLocation();
468 Tok.startToken();
469 Tok.setKind(tok::eof);
470 Tok.setLocation(EndLoc);
471 Tok.setLength(0);
472 ArgTokens.push_back(Tok);
Chris Lattnerf160b5f2009-05-13 00:55:26 +0000473
474 // If we expect two arguments, add both as empty.
475 if (NumActuals == 0 && MinArgsExpected == 2)
476 ArgTokens.push_back(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000477
Chris Lattnerc17925d2009-04-18 01:13:56 +0000478 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
479 // Emit the diagnostic at the macro name in case there is a missing ).
480 // Emitting it at the , could be far away from the macro name.
481 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
482 return 0;
Chris Lattner89620152008-03-09 03:13:06 +0000483 }
Mike Stump11289f42009-09-09 15:08:12 +0000484
Jay Foad7d0479f2009-05-21 09:52:38 +0000485 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattnerffbf2de2009-12-14 22:12:52 +0000486 isVarargsElided, *this);
Chris Lattner89620152008-03-09 03:13:06 +0000487}
488
489/// ComputeDATE_TIME - Compute the current time, enter it into the specified
490/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
491/// the identifier tokens inserted.
492static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
493 Preprocessor &PP) {
494 time_t TT = time(0);
495 struct tm *TM = localtime(&TT);
Mike Stump11289f42009-09-09 15:08:12 +0000496
Chris Lattner89620152008-03-09 03:13:06 +0000497 static const char * const Months[] = {
498 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
499 };
Mike Stump11289f42009-09-09 15:08:12 +0000500
Douglas Gregor9169dcb2010-11-09 03:20:07 +0000501 char TmpBuffer[32];
Douglas Gregor416463f2010-11-09 04:38:09 +0000502#ifdef LLVM_ON_WIN32
503 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
504 TM->tm_year+1900);
505#else
Douglas Gregor9169dcb2010-11-09 03:20:07 +0000506 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattner89620152008-03-09 03:13:06 +0000507 TM->tm_year+1900);
Douglas Gregor416463f2010-11-09 04:38:09 +0000508#endif
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattner5a7971e2009-01-26 19:29:26 +0000510 Token TmpTok;
511 TmpTok.startToken();
512 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
513 DATELoc = TmpTok.getLocation();
Chris Lattner89620152008-03-09 03:13:06 +0000514
NAKAMURA Takumic0d7d992010-11-09 06:27:32 +0000515#ifdef LLVM_ON_WIN32
516 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
517#else
Douglas Gregor9169dcb2010-11-09 03:20:07 +0000518 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumic0d7d992010-11-09 06:27:32 +0000519#endif
Chris Lattner5a7971e2009-01-26 19:29:26 +0000520 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
521 TIMELoc = TmpTok.getLocation();
Chris Lattner89620152008-03-09 03:13:06 +0000522}
523
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000524
525/// HasFeature - Return true if we recognize and implement the specified feature
526/// specified by the identifier.
527static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
528 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump11289f42009-09-09 15:08:12 +0000529
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000530 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000531 .Case("attribute_analyzer_noreturn", true)
Ted Kremenekf2b64ba2010-02-18 00:06:04 +0000532 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000533 .Case("attribute_cf_returns_retained", true)
John McCallf71b4532010-11-08 19:48:17 +0000534 .Case("attribute_deprecated_with_message", true)
Ted Kremenek64599392010-04-29 02:06:42 +0000535 .Case("attribute_ext_vector_type", true)
Ted Kremenekf2b64ba2010-02-18 00:06:04 +0000536 .Case("attribute_ns_returns_not_retained", true)
537 .Case("attribute_ns_returns_retained", true)
Ted Kremeneka00c5db2010-03-05 22:43:32 +0000538 .Case("attribute_objc_ivar_unused", true)
Ted Kremenek64599392010-04-29 02:06:42 +0000539 .Case("attribute_overloadable", true)
John McCallf71b4532010-11-08 19:48:17 +0000540 .Case("attribute_unavailable_with_message", true)
Ted Kremenek64599392010-04-29 02:06:42 +0000541 .Case("blocks", LangOpts.Blocks)
542 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
543 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
544 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Anders Carlsson991285e2010-09-24 21:25:25 +0000545 .Case("cxx_deleted_functions", true) // Accepted as an extension.
Ted Kremenek64599392010-04-29 02:06:42 +0000546 .Case("cxx_exceptions", LangOpts.Exceptions)
547 .Case("cxx_rtti", LangOpts.RTTI)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000548 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
Ted Kremenek64599392010-04-29 02:06:42 +0000549 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
Douglas Gregor7fb25412010-10-01 18:44:50 +0000550 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
John McCallf71b4532010-11-08 19:48:17 +0000551 .Case("enumerator_attributes", true)
Ted Kremenek64599392010-04-29 02:06:42 +0000552 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremeneke506ddc2010-04-29 02:06:46 +0000553 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekd21139a2010-07-31 01:52:11 +0000554 .Case("ownership_holds", true)
555 .Case("ownership_returns", true)
556 .Case("ownership_takes", true)
Sebastian Redla93bb5b2010-08-31 23:28:47 +0000557 .Case("cxx_inline_namespaces", true)
Ted Kremenek64599392010-04-29 02:06:42 +0000558 //.Case("cxx_concepts", false)
559 //.Case("cxx_lambdas", false)
560 //.Case("cxx_nullptr", false)
561 //.Case("cxx_rvalue_references", false)
562 //.Case("cxx_variadic_templates", false)
Eric Christopher03256c32010-06-24 02:02:00 +0000563 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer60fbd642010-01-09 18:53:11 +0000564 .Default(false);
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000565}
566
Anders Carlsson274a70e2010-10-20 02:31:43 +0000567/// HasAttribute - Return true if we recognize and implement the attribute
568/// specified by the given identifier.
569static bool HasAttribute(const IdentifierInfo *II) {
570 return llvm::StringSwitch<bool>(II->getName())
571#include "clang/Lex/AttrSpellings.inc"
572 .Default(false);
573}
574
John Thompsonac0b0982009-11-02 22:28:12 +0000575/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
576/// or '__has_include_next("path")' expression.
577/// Returns true if successful.
578static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
579 IdentifierInfo *II, Preprocessor &PP,
580 const DirectoryLookup *LookupFrom) {
581 SourceLocation LParenLoc;
582
583 // Get '('.
584 PP.LexNonComment(Tok);
585
586 // Ensure we have a '('.
587 if (Tok.isNot(tok::l_paren)) {
588 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
589 return false;
590 }
591
592 // Save '(' location for possible missing ')' message.
593 LParenLoc = Tok.getLocation();
594
595 // Get the file name.
596 PP.getCurrentLexer()->LexIncludeFilename(Tok);
597
598 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000599 llvm::SmallString<128> FilenameBuffer;
600 llvm::StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +0000601 SourceLocation EndLoc;
602
John Thompsonac0b0982009-11-02 22:28:12 +0000603 switch (Tok.getKind()) {
604 case tok::eom:
605 // If the token kind is EOM, the error has already been diagnosed.
606 return false;
607
608 case tok::angle_string_literal:
Douglas Gregordc970f02010-03-16 22:30:13 +0000609 case tok::string_literal: {
610 bool Invalid = false;
611 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
612 if (Invalid)
613 return false;
John Thompsonac0b0982009-11-02 22:28:12 +0000614 break;
Douglas Gregordc970f02010-03-16 22:30:13 +0000615 }
John Thompsonac0b0982009-11-02 22:28:12 +0000616
617 case tok::less:
618 // This could be a <foo/bar.h> file coming from a macro expansion. In this
619 // case, glue the tokens together into FilenameBuffer and interpret those.
620 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +0000621 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
John Thompsonac0b0982009-11-02 22:28:12 +0000622 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000623 Filename = FilenameBuffer.str();
John Thompsonac0b0982009-11-02 22:28:12 +0000624 break;
625 default:
626 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
627 return false;
628 }
629
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000630 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompsonac0b0982009-11-02 22:28:12 +0000631 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
632 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000633 if (Filename.empty())
John Thompsonac0b0982009-11-02 22:28:12 +0000634 return false;
John Thompsonac0b0982009-11-02 22:28:12 +0000635
636 // Search include directories.
637 const DirectoryLookup *CurDir;
Chris Lattnerfde85352010-01-22 00:14:44 +0000638 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompsonac0b0982009-11-02 22:28:12 +0000639
640 // Get the result value. Result = true means the file exists.
641 Result = File != 0;
642
643 // Get ')'.
644 PP.LexNonComment(Tok);
645
646 // Ensure we have a trailing ).
647 if (Tok.isNot(tok::r_paren)) {
648 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
649 PP.Diag(LParenLoc, diag::note_matching) << "(";
650 return false;
651 }
652
653 return true;
654}
655
656/// EvaluateHasInclude - Process a '__has_include("path")' expression.
657/// Returns true if successful.
658static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
659 Preprocessor &PP) {
660 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
661}
662
663/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
664/// Returns true if successful.
665static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
666 IdentifierInfo *II, Preprocessor &PP) {
667 // __has_include_next is like __has_include, except that we start
668 // searching after the current found directory. If we can't do this,
669 // issue a diagnostic.
670 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
671 if (PP.isInPrimaryFile()) {
672 Lookup = 0;
673 PP.Diag(Tok, diag::pp_include_next_in_primary);
674 } else if (Lookup == 0) {
675 PP.Diag(Tok, diag::pp_include_next_absolute_path);
676 } else {
677 // Start looking up in the next directory.
678 ++Lookup;
679 }
680
681 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
682}
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000683
Chris Lattner89620152008-03-09 03:13:06 +0000684/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
685/// as a builtin macro, handle it and return the next token as 'Tok'.
686void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
687 // Figure out which token this is.
688 IdentifierInfo *II = Tok.getIdentifierInfo();
689 assert(II && "Can't be a macro without id info!");
Mike Stump11289f42009-09-09 15:08:12 +0000690
John McCall89e925d2010-08-28 22:34:47 +0000691 // If this is an _Pragma or Microsoft __pragma directive, expand it,
692 // invoke the pragma handler, then lex the token after it.
Chris Lattner89620152008-03-09 03:13:06 +0000693 if (II == Ident_Pragma)
694 return Handle_Pragma(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000695 else if (II == Ident__pragma) // in non-MS mode this is null
696 return HandleMicrosoft__pragma(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner89620152008-03-09 03:13:06 +0000698 ++NumBuiltinMacroExpanded;
699
Benjamin Kramerb925f772010-01-27 16:38:22 +0000700 llvm::SmallString<128> TmpBuffer;
701 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattner89620152008-03-09 03:13:06 +0000702
703 // Set up the return result.
704 Tok.setIdentifierInfo(0);
705 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner89620152008-03-09 03:13:06 +0000707 if (II == Ident__LINE__) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000708 // C99 6.10.8: "__LINE__: The presumed line number (within the current
709 // source file) of the current source line (an integer constant)". This can
710 // be affected by #line.
Chris Lattner5a2e9cb2009-02-15 21:06:39 +0000711 SourceLocation Loc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000712
Chris Lattnerbf78da72009-04-18 22:29:33 +0000713 // Advance to the location of the first _, this might not be the first byte
714 // of the token if it starts with an escaped newline.
715 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000716
Chris Lattner5a2e9cb2009-02-15 21:06:39 +0000717 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
718 // a macro instantiation. This doesn't matter for object-like macros, but
719 // can matter for a function-like macro that expands to contain __LINE__.
720 // Skip down through instantiation points until we find a file loc for the
721 // end of the instantiation history.
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000722 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner5a2e9cb2009-02-15 21:06:39 +0000723 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000725 // __LINE__ expands to a simple numeric value.
Douglas Gregor453b0122010-11-12 07:15:47 +0000726 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattner89620152008-03-09 03:13:06 +0000727 Tok.setKind(tok::numeric_constant);
Chris Lattner89620152008-03-09 03:13:06 +0000728 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000729 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
730 // character string literal)". This can be affected by #line.
731 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
732
733 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
734 // #include stack instead of the current file.
Douglas Gregor453b0122010-11-12 07:15:47 +0000735 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000736 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattner89620152008-03-09 03:13:06 +0000737 while (NextLoc.isValid()) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000738 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregor453b0122010-11-12 07:15:47 +0000739 if (PLoc.isInvalid())
740 break;
741
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000742 NextLoc = PLoc.getIncludeLoc();
Chris Lattner89620152008-03-09 03:13:06 +0000743 }
744 }
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattner89620152008-03-09 03:13:06 +0000746 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb925f772010-01-27 16:38:22 +0000747 llvm::SmallString<128> FN;
Douglas Gregor453b0122010-11-12 07:15:47 +0000748 if (PLoc.isValid()) {
749 FN += PLoc.getFilename();
750 Lexer::Stringify(FN);
751 OS << '"' << FN.str() << '"';
752 }
Chris Lattner89620152008-03-09 03:13:06 +0000753 Tok.setKind(tok::string_literal);
Chris Lattner89620152008-03-09 03:13:06 +0000754 } else if (II == Ident__DATE__) {
755 if (!DATELoc.isValid())
756 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
757 Tok.setKind(tok::string_literal);
758 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattner4fa23622009-01-26 00:43:02 +0000759 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattner9dc9c202009-02-15 20:52:18 +0000760 Tok.getLocation(),
Chris Lattner4fa23622009-01-26 00:43:02 +0000761 Tok.getLength()));
Benjamin Kramerb925f772010-01-27 16:38:22 +0000762 return;
Chris Lattner89620152008-03-09 03:13:06 +0000763 } else if (II == Ident__TIME__) {
764 if (!TIMELoc.isValid())
765 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
766 Tok.setKind(tok::string_literal);
767 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattner4fa23622009-01-26 00:43:02 +0000768 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattner9dc9c202009-02-15 20:52:18 +0000769 Tok.getLocation(),
Chris Lattner4fa23622009-01-26 00:43:02 +0000770 Tok.getLength()));
Benjamin Kramerb925f772010-01-27 16:38:22 +0000771 return;
Chris Lattner89620152008-03-09 03:13:06 +0000772 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000773 // Compute the presumed include depth of this token. This can be affected
774 // by GNU line markers.
Chris Lattner89620152008-03-09 03:13:06 +0000775 unsigned Depth = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000776
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000777 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000778 if (PLoc.isValid()) {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000779 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregor453b0122010-11-12 07:15:47 +0000780 for (; PLoc.isValid(); ++Depth)
781 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000784 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb925f772010-01-27 16:38:22 +0000785 OS << Depth;
Chris Lattner89620152008-03-09 03:13:06 +0000786 Tok.setKind(tok::numeric_constant);
Chris Lattner89620152008-03-09 03:13:06 +0000787 } else if (II == Ident__TIMESTAMP__) {
788 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
789 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattner89620152008-03-09 03:13:06 +0000790
791 // Get the file that we are lexing out of. If we're currently lexing from
792 // a macro, dig into the include stack.
793 const FileEntry *CurFile = 0;
Ted Kremenek6552d252008-11-20 01:35:24 +0000794 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000795
Chris Lattner89620152008-03-09 03:13:06 +0000796 if (TheLexer)
Ted Kremenek2861cf42008-11-19 22:55:25 +0000797 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000798
Chris Lattner89620152008-03-09 03:13:06 +0000799 const char *Result;
800 if (CurFile) {
801 time_t TT = CurFile->getModificationTime();
802 struct tm *TM = localtime(&TT);
803 Result = asctime(TM);
804 } else {
805 Result = "??? ??? ?? ??:??:?? ????\n";
806 }
Benjamin Kramerb925f772010-01-27 16:38:22 +0000807 // Surround the string with " and strip the trailing newline.
808 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattner89620152008-03-09 03:13:06 +0000809 Tok.setKind(tok::string_literal);
Chris Lattner0af3ba12009-04-13 01:29:17 +0000810 } else if (II == Ident__COUNTER__) {
Chris Lattner0af3ba12009-04-13 01:29:17 +0000811 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb925f772010-01-27 16:38:22 +0000812 OS << CounterValue++;
Chris Lattner0af3ba12009-04-13 01:29:17 +0000813 Tok.setKind(tok::numeric_constant);
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000814 } else if (II == Ident__has_feature ||
Anders Carlsson274a70e2010-10-20 02:31:43 +0000815 II == Ident__has_builtin ||
816 II == Ident__has_attribute) {
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000817 // The argument to these two builtins should be a parenthesized identifier.
818 SourceLocation StartLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000819
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000820 bool IsValid = false;
821 IdentifierInfo *FeatureII = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000822
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000823 // Read the '('.
824 Lex(Tok);
825 if (Tok.is(tok::l_paren)) {
826 // Read the identifier
827 Lex(Tok);
828 if (Tok.is(tok::identifier)) {
829 FeatureII = Tok.getIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000831 // Read the ')'.
832 Lex(Tok);
833 if (Tok.is(tok::r_paren))
834 IsValid = true;
835 }
836 }
Mike Stump11289f42009-09-09 15:08:12 +0000837
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000838 bool Value = false;
839 if (!IsValid)
840 Diag(StartLoc, diag::err_feature_check_malformed);
841 else if (II == Ident__has_builtin) {
Mike Stump11289f42009-09-09 15:08:12 +0000842 // Check for a builtin is trivial.
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000843 Value = FeatureII->getBuiltinID() != 0;
Anders Carlsson274a70e2010-10-20 02:31:43 +0000844 } else if (II == Ident__has_attribute)
845 Value = HasAttribute(FeatureII);
846 else {
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000847 assert(II == Ident__has_feature && "Must be feature check");
848 Value = HasFeature(*this, FeatureII);
849 }
Mike Stump11289f42009-09-09 15:08:12 +0000850
Benjamin Kramerb925f772010-01-27 16:38:22 +0000851 OS << (int)Value;
Chris Lattnerb6f77af2009-06-13 07:13:28 +0000852 Tok.setKind(tok::numeric_constant);
John Thompsonac0b0982009-11-02 22:28:12 +0000853 } else if (II == Ident__has_include ||
854 II == Ident__has_include_next) {
855 // The argument to these two builtins should be a parenthesized
856 // file name string literal using angle brackets (<>) or
857 // double-quotes ("").
858 bool Value = false;
859 bool IsValid;
860 if (II == Ident__has_include)
861 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
862 else
863 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
Benjamin Kramerb925f772010-01-27 16:38:22 +0000864 OS << (int)Value;
John Thompsonac0b0982009-11-02 22:28:12 +0000865 Tok.setKind(tok::numeric_constant);
Chris Lattner89620152008-03-09 03:13:06 +0000866 } else {
867 assert(0 && "Unknown identifier!");
868 }
Benjamin Kramerb925f772010-01-27 16:38:22 +0000869 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattner89620152008-03-09 03:13:06 +0000870}