blob: 68fc56f7b7893dff2c28aa8ad8be86ea9e2ac0b2 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
Eric Christopher1f84f8d2010-06-24 02:02:00 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000021#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf29c5232010-08-24 22:20:20 +000022#include "clang/Lex/CodeCompletionHandler.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000023#include "llvm/ADT/StringSwitch.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000024#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000025#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000026#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000027using namespace clang;
28
29/// setMacroInfo - Specify a macro for this identifier.
30///
31void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000032 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000033 Macros[II] = MI;
34 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000035 } else if (II->hasMacroDefinition()) {
36 Macros.erase(II);
37 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000038 }
39}
40
41/// RegisterBuiltinMacro - Register the specified identifier in the identifier
42/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000043static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000044 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000045 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattnera3b605e2008-03-09 03:13:06 +000047 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000048 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000049 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000050 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000051 return Id;
52}
53
54
55/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
56/// identifier table.
57void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000058 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
59 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
60 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
61 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
62 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
63 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattnera3b605e2008-03-09 03:13:06 +000065 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000066 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
67 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
68 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner148772a2009-06-13 07:13:28 +000070 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000071 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
72 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000073 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000074 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
75 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall1ef8a2e2010-08-28 22:34:47 +000076
77 // Microsoft Extensions.
78 if (Features.Microsoft)
79 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
80 else
81 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +000082}
83
84/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
85/// in its expansion, currently expands to that token literally.
86static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
87 const IdentifierInfo *MacroIdent,
88 Preprocessor &PP) {
89 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
90
91 // If the token isn't an identifier, it's always literally expanded.
92 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattnera3b605e2008-03-09 03:13:06 +000094 // If the identifier is a macro, and if that macro is enabled, it may be
95 // expanded so it's not a trivial expansion.
96 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
97 // Fast expanding "#define X X" is ok, because X would be disabled.
98 II != MacroIdent)
99 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Chris Lattnera3b605e2008-03-09 03:13:06 +0000101 // If this is an object-like macro invocation, it is safe to trivially expand
102 // it.
103 if (MI->isObjectLike()) return true;
104
105 // If this is a function-like macro invocation, it's safe to trivially expand
106 // as long as the identifier is not a macro argument.
107 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
108 I != E; ++I)
109 if (*I == II)
110 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Chris Lattnera3b605e2008-03-09 03:13:06 +0000112 return true;
113}
114
115
116/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
117/// lexed is a '('. If so, consume the token and return true, if not, this
118/// method should have no observable side-effect on the lexed tokens.
119bool Preprocessor::isNextPPTokenLParen() {
120 // Do some quick tests for rejection cases.
121 unsigned Val;
122 if (CurLexer)
123 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000124 else if (CurPTHLexer)
125 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000126 else
127 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Chris Lattnera3b605e2008-03-09 03:13:06 +0000129 if (Val == 2) {
130 // We have run off the end. If it's a source file we don't
131 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
132 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000133 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000134 return false;
135 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
136 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
137 if (Entry.TheLexer)
138 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000139 else if (Entry.ThePTHLexer)
140 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000141 else
142 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Chris Lattnera3b605e2008-03-09 03:13:06 +0000144 if (Val != 2)
145 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Chris Lattnera3b605e2008-03-09 03:13:06 +0000147 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000148 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000149 return false;
150 }
151 }
152
153 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
154 // have found something that isn't a '(' or we found the end of the
155 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000156 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157}
158
159/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
160/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000161bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000162 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000163 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Douglas Gregor13678972010-01-26 19:43:43 +0000165 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000166 // then the macro could expand to different things in other contexts, we need
167 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000168 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattnera3b605e2008-03-09 03:13:06 +0000170 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
171 if (MI->isBuiltinMacro()) {
172 ExpandBuiltinMacro(Identifier);
173 return false;
174 }
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Chris Lattnera3b605e2008-03-09 03:13:06 +0000176 /// Args - If this is a function-like macro expansion, this contains,
177 /// for each macro argument, the list of tokens that were provided to the
178 /// invocation.
179 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattnere7fb4842009-02-15 20:52:18 +0000181 // Remember where the end of the instantiation occurred. For an object-like
182 // macro, this is the identifier. For a function-like macro, this is the ')'.
183 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattnera3b605e2008-03-09 03:13:06 +0000185 // If this is a function-like macro, read the arguments.
186 if (MI->isFunctionLike()) {
187 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000188 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000189 if (!isNextPPTokenLParen())
190 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattnera3b605e2008-03-09 03:13:06 +0000192 // Remember that we are now parsing the arguments to a macro invocation.
193 // Preprocessor directives used inside macro arguments are not portable, and
194 // this enables the warning.
195 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000196 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattnera3b605e2008-03-09 03:13:06 +0000198 // Finished parsing args.
199 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnera3b605e2008-03-09 03:13:06 +0000201 // If there was an error parsing the arguments, bail out.
202 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattnera3b605e2008-03-09 03:13:06 +0000204 ++NumFnMacroExpanded;
205 } else {
206 ++NumMacroExpanded;
207 }
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Chris Lattnera3b605e2008-03-09 03:13:06 +0000209 // Notice that this macro has been used.
210 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chris Lattnera3b605e2008-03-09 03:13:06 +0000212 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattnera3b605e2008-03-09 03:13:06 +0000214 // If this macro expands to no tokens, don't bother to push it onto the
215 // expansion stack, only to take it right back off.
216 if (MI->getNumTokens() == 0) {
217 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000218 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattnera3b605e2008-03-09 03:13:06 +0000220 // Ignore this macro use, just return the next token in the current
221 // buffer.
222 bool HadLeadingSpace = Identifier.hasLeadingSpace();
223 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattnera3b605e2008-03-09 03:13:06 +0000225 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattnera3b605e2008-03-09 03:13:06 +0000227 // If the identifier isn't on some OTHER line, inherit the leading
228 // whitespace/first-on-a-line property of this token. This handles
229 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
230 // empty.
231 if (!Identifier.isAtStartOfLine()) {
232 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
233 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
234 }
235 ++NumFastMacroExpanded;
236 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Chris Lattnera3b605e2008-03-09 03:13:06 +0000238 } else if (MI->getNumTokens() == 1 &&
239 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000240 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000241 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000242 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000243 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000244
245 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000246 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000247
Chris Lattnera3b605e2008-03-09 03:13:06 +0000248 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
249 // identifier to the expanded token.
250 bool isAtStartOfLine = Identifier.isAtStartOfLine();
251 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattnera3b605e2008-03-09 03:13:06 +0000253 // Remember where the token is instantiated.
254 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Chris Lattnera3b605e2008-03-09 03:13:06 +0000256 // Replace the result token.
257 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Chris Lattnera3b605e2008-03-09 03:13:06 +0000259 // Restore the StartOfLine/LeadingSpace markers.
260 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
261 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000263 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000264 // locations.
265 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000266 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000267 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000268 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Chris Lattner8ff66de2010-03-26 17:49:16 +0000270 // If this is a disabled macro or #define X X, we must mark the result as
271 // unexpandable.
272 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
273 if (MacroInfo *NewMI = getMacroInfo(NewII))
274 if (!NewMI->isEnabled() || NewMI == MI)
275 Identifier.setFlag(Token::DisableExpand);
276 }
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattnera3b605e2008-03-09 03:13:06 +0000278 // Since this is not an identifier token, it can't be macro expanded, so
279 // we're done.
280 ++NumFastMacroExpanded;
281 return false;
282 }
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattnera3b605e2008-03-09 03:13:06 +0000284 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000285 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Chris Lattnera3b605e2008-03-09 03:13:06 +0000287 // Now that the macro is at the top of the include stack, ask the
288 // preprocessor to read the next token from it.
289 Lex(Identifier);
290 return false;
291}
292
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000293/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
294/// token is the '(' of the macro, this method is invoked to read all of the
295/// actual arguments specified for the macro invocation. This returns null on
296/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000297MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000298 MacroInfo *MI,
299 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000300 // The number of fixed arguments to parse.
301 unsigned NumFixedArgsLeft = MI->getNumArgs();
302 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnera3b605e2008-03-09 03:13:06 +0000304 // Outer loop, while there are more arguments, keep reading them.
305 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000306
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000307 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
308 // an argument value in a macro could expand to ',' or '(' or ')'.
309 LexUnexpandedToken(Tok);
310 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnera3b605e2008-03-09 03:13:06 +0000312 // ArgTokens - Build up a list of tokens that make up each argument. Each
313 // argument is separated by an EOF token. Use a SmallVector so we can avoid
314 // heap allocations in the common case.
315 llvm::SmallVector<Token, 64> ArgTokens;
316
317 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000318 while (Tok.isNot(tok::r_paren)) {
319 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
320 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000322 unsigned ArgTokenStart = ArgTokens.size();
323 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chris Lattnera3b605e2008-03-09 03:13:06 +0000325 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
326 // that we already consumed the first one.
327 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattnera3b605e2008-03-09 03:13:06 +0000329 while (1) {
330 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
331 // an argument value in a macro could expand to ',' or '(' or ')'.
332 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Douglas Gregorf29c5232010-08-24 22:20:20 +0000334 if (Tok.is(tok::code_completion)) {
335 if (CodeComplete)
336 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
337 MI, NumActuals);
338 LexUnexpandedToken(Tok);
339 }
340
Chris Lattnera3b605e2008-03-09 03:13:06 +0000341 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
342 Diag(MacroName, diag::err_unterm_macro_invoc);
343 // Do not lose the EOF/EOM. Return it to the client.
344 MacroName = Tok;
345 return 0;
346 } else if (Tok.is(tok::r_paren)) {
347 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000348 if (NumParens-- == 0) {
349 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000350 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000351 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000352 } else if (Tok.is(tok::l_paren)) {
353 ++NumParens;
354 } else if (Tok.is(tok::comma) && NumParens == 0) {
355 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000356 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000357 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000358 if (!isVariadic) break;
359 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000360 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000361 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
362 // If this is a comment token in the argument list and we're just in
363 // -C mode (not -CC mode), discard the comment.
364 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000365 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000366 // Reading macro arguments can cause macros that we are currently
367 // expanding from to be popped off the expansion stack. Doing so causes
368 // them to be reenabled for expansion. Here we record whether any
369 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000370 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000371 // C99 6.10.3.4p2.
372 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
373 if (!MI->isEnabled())
374 Tok.setFlag(Token::DisableExpand);
375 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000376 ArgTokens.push_back(Tok);
377 }
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000379 // If this was an empty argument list foo(), don't add this as an empty
380 // argument.
381 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
382 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000383
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000384 // If this is not a variadic macro, and too many args were specified, emit
385 // an error.
386 if (!isVariadic && NumFixedArgsLeft == 0) {
387 if (ArgTokens.size() != ArgTokenStart)
388 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000390 // Emit the diagnostic at the macro name in case there is a missing ).
391 // Emitting it at the , could be far away from the macro name.
392 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
393 return 0;
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattnera3b605e2008-03-09 03:13:06 +0000396 // Empty arguments are standard in C99 and supported as an extension in
397 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000398 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000399 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattnera3b605e2008-03-09 03:13:06 +0000401 // Add a marker EOF token to the end of the token list for this argument.
402 Token EOFTok;
403 EOFTok.startToken();
404 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000405 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000406 EOFTok.setLength(0);
407 ArgTokens.push_back(EOFTok);
408 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000409 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000410 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattnera3b605e2008-03-09 03:13:06 +0000413 // Okay, we either found the r_paren. Check to see if we parsed too few
414 // arguments.
415 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattnera3b605e2008-03-09 03:13:06 +0000417 // See MacroArgs instance var for description of this.
418 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattnera3b605e2008-03-09 03:13:06 +0000420 if (NumActuals < MinArgsExpected) {
421 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000422 if (NumActuals == 0 && MinArgsExpected == 1) {
423 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner97e2de12009-04-20 21:08:10 +0000425 // If there is exactly one argument, and that argument is missing,
426 // then we have an empty "()" argument empty list. This is fine, even if
427 // the macro expects one argument (the argument is just empty).
428 isVarargsElided = MI->isVariadic();
429 } else if (MI->isVariadic() &&
430 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
431 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000432 // Varargs where the named vararg parameter is missing: ok as extension.
433 // #define A(x, ...)
434 // A("blah")
435 Diag(Tok, diag::ext_missing_varargs_arg);
436
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000437 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000438 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000439 // #define A(x, foo...) blah(a, ## foo)
440 // #define B(x, ...) blah(a, ## __VA_ARGS__)
441 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000442 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000443 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000444 } else {
445 // Otherwise, emit the error.
446 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
447 return 0;
448 }
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Chris Lattnera3b605e2008-03-09 03:13:06 +0000450 // Add a marker EOF token to the end of the token list for this argument.
451 SourceLocation EndLoc = Tok.getLocation();
452 Tok.startToken();
453 Tok.setKind(tok::eof);
454 Tok.setLocation(EndLoc);
455 Tok.setLength(0);
456 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000457
458 // If we expect two arguments, add both as empty.
459 if (NumActuals == 0 && MinArgsExpected == 2)
460 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000462 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
463 // Emit the diagnostic at the macro name in case there is a missing ).
464 // Emitting it at the , could be far away from the macro name.
465 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
466 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Jay Foadbeaaccd2009-05-21 09:52:38 +0000469 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000470 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000471}
472
473/// ComputeDATE_TIME - Compute the current time, enter it into the specified
474/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
475/// the identifier tokens inserted.
476static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
477 Preprocessor &PP) {
478 time_t TT = time(0);
479 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattnera3b605e2008-03-09 03:13:06 +0000481 static const char * const Months[] = {
482 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
483 };
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattnera3b605e2008-03-09 03:13:06 +0000485 char TmpBuffer[100];
Mike Stump1eb44332009-09-09 15:08:12 +0000486 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000487 TM->tm_year+1900);
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattner47246be2009-01-26 19:29:26 +0000489 Token TmpTok;
490 TmpTok.startToken();
491 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
492 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000493
494 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner47246be2009-01-26 19:29:26 +0000495 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
496 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000497}
498
Chris Lattner148772a2009-06-13 07:13:28 +0000499
500/// HasFeature - Return true if we recognize and implement the specified feature
501/// specified by the identifier.
502static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
503 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Benjamin Kramer32592e82010-01-09 18:53:11 +0000505 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000506 .Case("attribute_analyzer_noreturn", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000507 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000508 .Case("attribute_cf_returns_retained", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000509 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000510 .Case("attribute_ns_returns_not_retained", true)
511 .Case("attribute_ns_returns_retained", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000512 .Case("attribute_objc_ivar_unused", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000513 .Case("attribute_overloadable", true)
514 .Case("blocks", LangOpts.Blocks)
515 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
516 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
517 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Anders Carlsson37bf9d22010-09-24 21:25:25 +0000518 .Case("cxx_deleted_functions", true) // Accepted as an extension.
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000519 .Case("cxx_exceptions", LangOpts.Exceptions)
520 .Case("cxx_rtti", LangOpts.RTTI)
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000521 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000522 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
Douglas Gregordab60ad2010-10-01 18:44:50 +0000523 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000524 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000525 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000526 .Case("ownership_holds", true)
527 .Case("ownership_returns", true)
528 .Case("ownership_takes", true)
Sebastian Redlf6c09772010-08-31 23:28:47 +0000529 .Case("cxx_inline_namespaces", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000530 //.Case("cxx_concepts", false)
531 //.Case("cxx_lambdas", false)
532 //.Case("cxx_nullptr", false)
533 //.Case("cxx_rvalue_references", false)
534 //.Case("cxx_variadic_templates", false)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000535 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000536 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000537}
538
Anders Carlssoncae50952010-10-20 02:31:43 +0000539/// HasAttribute - Return true if we recognize and implement the attribute
540/// specified by the given identifier.
541static bool HasAttribute(const IdentifierInfo *II) {
542 return llvm::StringSwitch<bool>(II->getName())
543#include "clang/Lex/AttrSpellings.inc"
544 .Default(false);
545}
546
John Thompson92bd8c72009-11-02 22:28:12 +0000547/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
548/// or '__has_include_next("path")' expression.
549/// Returns true if successful.
550static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
551 IdentifierInfo *II, Preprocessor &PP,
552 const DirectoryLookup *LookupFrom) {
553 SourceLocation LParenLoc;
554
555 // Get '('.
556 PP.LexNonComment(Tok);
557
558 // Ensure we have a '('.
559 if (Tok.isNot(tok::l_paren)) {
560 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
561 return false;
562 }
563
564 // Save '(' location for possible missing ')' message.
565 LParenLoc = Tok.getLocation();
566
567 // Get the file name.
568 PP.getCurrentLexer()->LexIncludeFilename(Tok);
569
570 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000571 llvm::SmallString<128> FilenameBuffer;
572 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000573 SourceLocation EndLoc;
574
John Thompson92bd8c72009-11-02 22:28:12 +0000575 switch (Tok.getKind()) {
576 case tok::eom:
577 // If the token kind is EOM, the error has already been diagnosed.
578 return false;
579
580 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000581 case tok::string_literal: {
582 bool Invalid = false;
583 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
584 if (Invalid)
585 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000586 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000587 }
John Thompson92bd8c72009-11-02 22:28:12 +0000588
589 case tok::less:
590 // This could be a <foo/bar.h> file coming from a macro expansion. In this
591 // case, glue the tokens together into FilenameBuffer and interpret those.
592 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000593 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
John Thompson92bd8c72009-11-02 22:28:12 +0000594 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000595 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000596 break;
597 default:
598 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
599 return false;
600 }
601
Chris Lattnera1394812010-01-10 01:35:12 +0000602 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000603 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
604 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000605 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000606 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000607
608 // Search include directories.
609 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +0000610 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000611
612 // Get the result value. Result = true means the file exists.
613 Result = File != 0;
614
615 // Get ')'.
616 PP.LexNonComment(Tok);
617
618 // Ensure we have a trailing ).
619 if (Tok.isNot(tok::r_paren)) {
620 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
621 PP.Diag(LParenLoc, diag::note_matching) << "(";
622 return false;
623 }
624
625 return true;
626}
627
628/// EvaluateHasInclude - Process a '__has_include("path")' expression.
629/// Returns true if successful.
630static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
631 Preprocessor &PP) {
632 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
633}
634
635/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
636/// Returns true if successful.
637static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
638 IdentifierInfo *II, Preprocessor &PP) {
639 // __has_include_next is like __has_include, except that we start
640 // searching after the current found directory. If we can't do this,
641 // issue a diagnostic.
642 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
643 if (PP.isInPrimaryFile()) {
644 Lookup = 0;
645 PP.Diag(Tok, diag::pp_include_next_in_primary);
646 } else if (Lookup == 0) {
647 PP.Diag(Tok, diag::pp_include_next_absolute_path);
648 } else {
649 // Start looking up in the next directory.
650 ++Lookup;
651 }
652
653 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
654}
Chris Lattner148772a2009-06-13 07:13:28 +0000655
Chris Lattnera3b605e2008-03-09 03:13:06 +0000656/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
657/// as a builtin macro, handle it and return the next token as 'Tok'.
658void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
659 // Figure out which token this is.
660 IdentifierInfo *II = Tok.getIdentifierInfo();
661 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000662
John McCall1ef8a2e2010-08-28 22:34:47 +0000663 // If this is an _Pragma or Microsoft __pragma directive, expand it,
664 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000665 if (II == Ident_Pragma)
666 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000667 else if (II == Ident__pragma) // in non-MS mode this is null
668 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000669
Chris Lattnera3b605e2008-03-09 03:13:06 +0000670 ++NumBuiltinMacroExpanded;
671
Benjamin Kramerb1765912010-01-27 16:38:22 +0000672 llvm::SmallString<128> TmpBuffer;
673 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000674
675 // Set up the return result.
676 Tok.setIdentifierInfo(0);
677 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattnera3b605e2008-03-09 03:13:06 +0000679 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000680 // C99 6.10.8: "__LINE__: The presumed line number (within the current
681 // source file) of the current source line (an integer constant)". This can
682 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000683 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattnerdff070f2009-04-18 22:29:33 +0000685 // Advance to the location of the first _, this might not be the first byte
686 // of the token if it starts with an escaped newline.
687 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattner081927b2009-02-15 21:06:39 +0000689 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
690 // a macro instantiation. This doesn't matter for object-like macros, but
691 // can matter for a function-like macro that expands to contain __LINE__.
692 // Skip down through instantiation points until we find a file loc for the
693 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000694 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000695 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner1fa49532009-03-08 08:08:45 +0000697 // __LINE__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000698 OS << PLoc.getLine();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000699 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000700 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000701 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
702 // character string literal)". This can be affected by #line.
703 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
704
705 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
706 // #include stack instead of the current file.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000707 if (II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000708 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000709 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000710 PLoc = SourceMgr.getPresumedLoc(NextLoc);
711 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000712 }
713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattnera3b605e2008-03-09 03:13:06 +0000715 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000716 llvm::SmallString<128> FN;
717 FN += PLoc.getFilename();
718 Lexer::Stringify(FN);
719 OS << '"' << FN.str() << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000720 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000721 } else if (II == Ident__DATE__) {
722 if (!DATELoc.isValid())
723 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
724 Tok.setKind(tok::string_literal);
725 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000726 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000727 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000728 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000729 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000730 } else if (II == Ident__TIME__) {
731 if (!TIMELoc.isValid())
732 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
733 Tok.setKind(tok::string_literal);
734 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000735 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000736 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000737 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000738 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000739 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000740 // Compute the presumed include depth of this token. This can be affected
741 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000742 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000744 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
745 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
746 for (; PLoc.isValid(); ++Depth)
747 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Chris Lattner1fa49532009-03-08 08:08:45 +0000749 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000750 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000751 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000752 } else if (II == Ident__TIMESTAMP__) {
753 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
754 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000755
756 // Get the file that we are lexing out of. If we're currently lexing from
757 // a macro, dig into the include stack.
758 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000759 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattnera3b605e2008-03-09 03:13:06 +0000761 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000762 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Chris Lattnera3b605e2008-03-09 03:13:06 +0000764 const char *Result;
765 if (CurFile) {
766 time_t TT = CurFile->getModificationTime();
767 struct tm *TM = localtime(&TT);
768 Result = asctime(TM);
769 } else {
770 Result = "??? ??? ?? ??:??:?? ????\n";
771 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000772 // Surround the string with " and strip the trailing newline.
773 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000774 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000775 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000776 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000777 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000778 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000779 } else if (II == Ident__has_feature ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000780 II == Ident__has_builtin ||
781 II == Ident__has_attribute) {
Chris Lattner148772a2009-06-13 07:13:28 +0000782 // The argument to these two builtins should be a parenthesized identifier.
783 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Chris Lattner148772a2009-06-13 07:13:28 +0000785 bool IsValid = false;
786 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Chris Lattner148772a2009-06-13 07:13:28 +0000788 // Read the '('.
789 Lex(Tok);
790 if (Tok.is(tok::l_paren)) {
791 // Read the identifier
792 Lex(Tok);
793 if (Tok.is(tok::identifier)) {
794 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Chris Lattner148772a2009-06-13 07:13:28 +0000796 // Read the ')'.
797 Lex(Tok);
798 if (Tok.is(tok::r_paren))
799 IsValid = true;
800 }
801 }
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattner148772a2009-06-13 07:13:28 +0000803 bool Value = false;
804 if (!IsValid)
805 Diag(StartLoc, diag::err_feature_check_malformed);
806 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000807 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000808 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +0000809 } else if (II == Ident__has_attribute)
810 Value = HasAttribute(FeatureII);
811 else {
Chris Lattner148772a2009-06-13 07:13:28 +0000812 assert(II == Ident__has_feature && "Must be feature check");
813 Value = HasFeature(*this, FeatureII);
814 }
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Benjamin Kramerb1765912010-01-27 16:38:22 +0000816 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000817 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000818 } else if (II == Ident__has_include ||
819 II == Ident__has_include_next) {
820 // The argument to these two builtins should be a parenthesized
821 // file name string literal using angle brackets (<>) or
822 // double-quotes ("").
823 bool Value = false;
824 bool IsValid;
825 if (II == Ident__has_include)
826 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
827 else
828 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000829 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000830 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000831 } else {
832 assert(0 && "Unknown identifier!");
833 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000834 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000835}