blob: ba7be5c648c12d35d12ff11138c46ecad1bfc40d [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/Lex/LexDiagnostic.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000021#include "llvm/ADT/StringSwitch.h"
Chris Lattner3daed522009-03-02 22:20:04 +000022#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000023#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000024using namespace clang;
25
26/// setMacroInfo - Specify a macro for this identifier.
27///
28void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000029 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000030 Macros[II] = MI;
31 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000032 } else if (II->hasMacroDefinition()) {
33 Macros.erase(II);
34 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000035 }
36}
37
38/// RegisterBuiltinMacro - Register the specified identifier in the identifier
39/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000040static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000041 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000042 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattnera3b605e2008-03-09 03:13:06 +000044 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000045 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000046 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000047 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000048 return Id;
49}
50
51
52/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
53/// identifier table.
54void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000055 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
56 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
57 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
58 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
59 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
60 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattnera3b605e2008-03-09 03:13:06 +000062 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000063 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
64 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
65 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner148772a2009-06-13 07:13:28 +000067 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000068 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
69 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
70 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
71 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Chris Lattnera3b605e2008-03-09 03:13:06 +000072}
73
74/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
75/// in its expansion, currently expands to that token literally.
76static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
77 const IdentifierInfo *MacroIdent,
78 Preprocessor &PP) {
79 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
80
81 // If the token isn't an identifier, it's always literally expanded.
82 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Chris Lattnera3b605e2008-03-09 03:13:06 +000084 // If the identifier is a macro, and if that macro is enabled, it may be
85 // expanded so it's not a trivial expansion.
86 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
87 // Fast expanding "#define X X" is ok, because X would be disabled.
88 II != MacroIdent)
89 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattnera3b605e2008-03-09 03:13:06 +000091 // If this is an object-like macro invocation, it is safe to trivially expand
92 // it.
93 if (MI->isObjectLike()) return true;
94
95 // If this is a function-like macro invocation, it's safe to trivially expand
96 // as long as the identifier is not a macro argument.
97 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
98 I != E; ++I)
99 if (*I == II)
100 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Chris Lattnera3b605e2008-03-09 03:13:06 +0000102 return true;
103}
104
105
106/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
107/// lexed is a '('. If so, consume the token and return true, if not, this
108/// method should have no observable side-effect on the lexed tokens.
109bool Preprocessor::isNextPPTokenLParen() {
110 // Do some quick tests for rejection cases.
111 unsigned Val;
112 if (CurLexer)
113 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000114 else if (CurPTHLexer)
115 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000116 else
117 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Chris Lattnera3b605e2008-03-09 03:13:06 +0000119 if (Val == 2) {
120 // We have run off the end. If it's a source file we don't
121 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
122 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000123 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000124 return false;
125 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
126 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
127 if (Entry.TheLexer)
128 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000129 else if (Entry.ThePTHLexer)
130 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000131 else
132 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Chris Lattnera3b605e2008-03-09 03:13:06 +0000134 if (Val != 2)
135 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattnera3b605e2008-03-09 03:13:06 +0000137 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000138 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000139 return false;
140 }
141 }
142
143 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
144 // have found something that isn't a '(' or we found the end of the
145 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000146 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000147}
148
149/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
150/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000151bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000152 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000153 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnera3b605e2008-03-09 03:13:06 +0000155 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
156 // then the macro could expand to different things in other contexts, we need
157 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000158 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattnera3b605e2008-03-09 03:13:06 +0000160 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
161 if (MI->isBuiltinMacro()) {
162 ExpandBuiltinMacro(Identifier);
163 return false;
164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattnera3b605e2008-03-09 03:13:06 +0000166 /// Args - If this is a function-like macro expansion, this contains,
167 /// for each macro argument, the list of tokens that were provided to the
168 /// invocation.
169 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Chris Lattnere7fb4842009-02-15 20:52:18 +0000171 // Remember where the end of the instantiation occurred. For an object-like
172 // macro, this is the identifier. For a function-like macro, this is the ')'.
173 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnera3b605e2008-03-09 03:13:06 +0000175 // If this is a function-like macro, read the arguments.
176 if (MI->isFunctionLike()) {
177 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000178 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000179 if (!isNextPPTokenLParen())
180 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattnera3b605e2008-03-09 03:13:06 +0000182 // Remember that we are now parsing the arguments to a macro invocation.
183 // Preprocessor directives used inside macro arguments are not portable, and
184 // this enables the warning.
185 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000186 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnera3b605e2008-03-09 03:13:06 +0000188 // Finished parsing args.
189 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnera3b605e2008-03-09 03:13:06 +0000191 // If there was an error parsing the arguments, bail out.
192 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattnera3b605e2008-03-09 03:13:06 +0000194 ++NumFnMacroExpanded;
195 } else {
196 ++NumMacroExpanded;
197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattnera3b605e2008-03-09 03:13:06 +0000199 // Notice that this macro has been used.
200 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Chris Lattnera3b605e2008-03-09 03:13:06 +0000202 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattnera3b605e2008-03-09 03:13:06 +0000204 // If this macro expands to no tokens, don't bother to push it onto the
205 // expansion stack, only to take it right back off.
206 if (MI->getNumTokens() == 0) {
207 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000208 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Chris Lattnera3b605e2008-03-09 03:13:06 +0000210 // Ignore this macro use, just return the next token in the current
211 // buffer.
212 bool HadLeadingSpace = Identifier.hasLeadingSpace();
213 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Chris Lattnera3b605e2008-03-09 03:13:06 +0000215 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattnera3b605e2008-03-09 03:13:06 +0000217 // If the identifier isn't on some OTHER line, inherit the leading
218 // whitespace/first-on-a-line property of this token. This handles
219 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
220 // empty.
221 if (!Identifier.isAtStartOfLine()) {
222 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
223 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
224 }
225 ++NumFastMacroExpanded;
226 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattnera3b605e2008-03-09 03:13:06 +0000228 } else if (MI->getNumTokens() == 1 &&
229 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000230 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000231 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000232 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000233 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000234
235 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000236 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000237
Chris Lattnera3b605e2008-03-09 03:13:06 +0000238 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
239 // identifier to the expanded token.
240 bool isAtStartOfLine = Identifier.isAtStartOfLine();
241 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattnera3b605e2008-03-09 03:13:06 +0000243 // Remember where the token is instantiated.
244 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattnera3b605e2008-03-09 03:13:06 +0000246 // Replace the result token.
247 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Chris Lattnera3b605e2008-03-09 03:13:06 +0000249 // Restore the StartOfLine/LeadingSpace markers.
250 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
251 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000253 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000254 // locations.
255 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000256 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000257 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000258 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Chris Lattnera3b605e2008-03-09 03:13:06 +0000260 // If this is #define X X, we must mark the result as unexpandible.
261 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
262 if (getMacroInfo(NewII) == MI)
263 Identifier.setFlag(Token::DisableExpand);
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Chris Lattnera3b605e2008-03-09 03:13:06 +0000265 // Since this is not an identifier token, it can't be macro expanded, so
266 // we're done.
267 ++NumFastMacroExpanded;
268 return false;
269 }
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Chris Lattnera3b605e2008-03-09 03:13:06 +0000271 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000272 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnera3b605e2008-03-09 03:13:06 +0000274 // Now that the macro is at the top of the include stack, ask the
275 // preprocessor to read the next token from it.
276 Lex(Identifier);
277 return false;
278}
279
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000280/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
281/// token is the '(' of the macro, this method is invoked to read all of the
282/// actual arguments specified for the macro invocation. This returns null on
283/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000284MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000285 MacroInfo *MI,
286 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000287 // The number of fixed arguments to parse.
288 unsigned NumFixedArgsLeft = MI->getNumArgs();
289 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattnera3b605e2008-03-09 03:13:06 +0000291 // Outer loop, while there are more arguments, keep reading them.
292 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000293
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000294 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
295 // an argument value in a macro could expand to ',' or '(' or ')'.
296 LexUnexpandedToken(Tok);
297 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattnera3b605e2008-03-09 03:13:06 +0000299 // ArgTokens - Build up a list of tokens that make up each argument. Each
300 // argument is separated by an EOF token. Use a SmallVector so we can avoid
301 // heap allocations in the common case.
302 llvm::SmallVector<Token, 64> ArgTokens;
303
304 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000305 while (Tok.isNot(tok::r_paren)) {
306 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
307 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000309 unsigned ArgTokenStart = ArgTokens.size();
310 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnera3b605e2008-03-09 03:13:06 +0000312 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
313 // that we already consumed the first one.
314 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattnera3b605e2008-03-09 03:13:06 +0000316 while (1) {
317 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
318 // an argument value in a macro could expand to ',' or '(' or ')'.
319 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
322 Diag(MacroName, diag::err_unterm_macro_invoc);
323 // Do not lose the EOF/EOM. Return it to the client.
324 MacroName = Tok;
325 return 0;
326 } else if (Tok.is(tok::r_paren)) {
327 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000328 if (NumParens-- == 0) {
329 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000330 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000331 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000332 } else if (Tok.is(tok::l_paren)) {
333 ++NumParens;
334 } else if (Tok.is(tok::comma) && NumParens == 0) {
335 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000336 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000337 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000338 if (!isVariadic) break;
339 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000340 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000341 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
342 // If this is a comment token in the argument list and we're just in
343 // -C mode (not -CC mode), discard the comment.
344 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000345 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000346 // Reading macro arguments can cause macros that we are currently
347 // expanding from to be popped off the expansion stack. Doing so causes
348 // them to be reenabled for expansion. Here we record whether any
349 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000350 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000351 // C99 6.10.3.4p2.
352 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
353 if (!MI->isEnabled())
354 Tok.setFlag(Token::DisableExpand);
355 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000356 ArgTokens.push_back(Tok);
357 }
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000359 // If this was an empty argument list foo(), don't add this as an empty
360 // argument.
361 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
362 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000363
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000364 // If this is not a variadic macro, and too many args were specified, emit
365 // an error.
366 if (!isVariadic && NumFixedArgsLeft == 0) {
367 if (ArgTokens.size() != ArgTokenStart)
368 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000370 // Emit the diagnostic at the macro name in case there is a missing ).
371 // Emitting it at the , could be far away from the macro name.
372 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
373 return 0;
374 }
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattnera3b605e2008-03-09 03:13:06 +0000376 // Empty arguments are standard in C99 and supported as an extension in
377 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000378 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000379 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattnera3b605e2008-03-09 03:13:06 +0000381 // Add a marker EOF token to the end of the token list for this argument.
382 Token EOFTok;
383 EOFTok.startToken();
384 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000385 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000386 EOFTok.setLength(0);
387 ArgTokens.push_back(EOFTok);
388 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000389 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000390 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000391 }
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattnera3b605e2008-03-09 03:13:06 +0000393 // Okay, we either found the r_paren. Check to see if we parsed too few
394 // arguments.
395 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattnera3b605e2008-03-09 03:13:06 +0000397 // See MacroArgs instance var for description of this.
398 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400 if (NumActuals < MinArgsExpected) {
401 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000402 if (NumActuals == 0 && MinArgsExpected == 1) {
403 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner97e2de12009-04-20 21:08:10 +0000405 // If there is exactly one argument, and that argument is missing,
406 // then we have an empty "()" argument empty list. This is fine, even if
407 // the macro expects one argument (the argument is just empty).
408 isVarargsElided = MI->isVariadic();
409 } else if (MI->isVariadic() &&
410 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
411 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000412 // Varargs where the named vararg parameter is missing: ok as extension.
413 // #define A(x, ...)
414 // A("blah")
415 Diag(Tok, diag::ext_missing_varargs_arg);
416
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000417 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000418 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000419 // #define A(x, foo...) blah(a, ## foo)
420 // #define B(x, ...) blah(a, ## __VA_ARGS__)
421 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000422 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000423 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000424 } else {
425 // Otherwise, emit the error.
426 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
427 return 0;
428 }
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattnera3b605e2008-03-09 03:13:06 +0000430 // Add a marker EOF token to the end of the token list for this argument.
431 SourceLocation EndLoc = Tok.getLocation();
432 Tok.startToken();
433 Tok.setKind(tok::eof);
434 Tok.setLocation(EndLoc);
435 Tok.setLength(0);
436 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000437
438 // If we expect two arguments, add both as empty.
439 if (NumActuals == 0 && MinArgsExpected == 2)
440 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000442 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
443 // Emit the diagnostic at the macro name in case there is a missing ).
444 // Emitting it at the , could be far away from the macro name.
445 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
446 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000447 }
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Jay Foadbeaaccd2009-05-21 09:52:38 +0000449 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000450 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000451}
452
453/// ComputeDATE_TIME - Compute the current time, enter it into the specified
454/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
455/// the identifier tokens inserted.
456static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
457 Preprocessor &PP) {
458 time_t TT = time(0);
459 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattnera3b605e2008-03-09 03:13:06 +0000461 static const char * const Months[] = {
462 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
463 };
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattnera3b605e2008-03-09 03:13:06 +0000465 char TmpBuffer[100];
Mike Stump1eb44332009-09-09 15:08:12 +0000466 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000467 TM->tm_year+1900);
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chris Lattner47246be2009-01-26 19:29:26 +0000469 Token TmpTok;
470 TmpTok.startToken();
471 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
472 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000473
474 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner47246be2009-01-26 19:29:26 +0000475 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
476 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000477}
478
Chris Lattner148772a2009-06-13 07:13:28 +0000479
480/// HasFeature - Return true if we recognize and implement the specified feature
481/// specified by the identifier.
482static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
483 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Benjamin Kramer32592e82010-01-09 18:53:11 +0000485 return llvm::StringSwitch<bool>(II->getName())
486 .Case("blocks", LangOpts.Blocks)
487 .Case("cxx_rtti", LangOpts.RTTI)
488 .Case("cxx_exceptions", LangOpts.Exceptions)
489 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
490 .Case("attribute_overloadable", true)
491 .Case("attribute_ext_vector_type", true)
492 .Case("attribute_analyzer_noreturn", true)
493 .Case("attribute_ns_returns_retained", true)
494 .Case("attribute_cf_returns_retained", true)
495 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000496}
497
John Thompson92bd8c72009-11-02 22:28:12 +0000498/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
499/// or '__has_include_next("path")' expression.
500/// Returns true if successful.
501static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
502 IdentifierInfo *II, Preprocessor &PP,
503 const DirectoryLookup *LookupFrom) {
504 SourceLocation LParenLoc;
505
506 // Get '('.
507 PP.LexNonComment(Tok);
508
509 // Ensure we have a '('.
510 if (Tok.isNot(tok::l_paren)) {
511 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
512 return false;
513 }
514
515 // Save '(' location for possible missing ')' message.
516 LParenLoc = Tok.getLocation();
517
518 // Get the file name.
519 PP.getCurrentLexer()->LexIncludeFilename(Tok);
520
521 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000522 llvm::SmallString<128> FilenameBuffer;
523 llvm::StringRef Filename;
John Thompson92bd8c72009-11-02 22:28:12 +0000524
525 switch (Tok.getKind()) {
526 case tok::eom:
527 // If the token kind is EOM, the error has already been diagnosed.
528 return false;
529
530 case tok::angle_string_literal:
531 case tok::string_literal: {
532 FilenameBuffer.resize(Tok.getLength());
Chris Lattnera1394812010-01-10 01:35:12 +0000533 const char *FilenameStart = &FilenameBuffer[0];
John Thompson92bd8c72009-11-02 22:28:12 +0000534 unsigned Len = PP.getSpelling(Tok, FilenameStart);
Chris Lattnera1394812010-01-10 01:35:12 +0000535 Filename = llvm::StringRef(FilenameStart, Len);
John Thompson92bd8c72009-11-02 22:28:12 +0000536 break;
537 }
538
539 case tok::less:
540 // This could be a <foo/bar.h> file coming from a macro expansion. In this
541 // case, glue the tokens together into FilenameBuffer and interpret those.
542 FilenameBuffer.push_back('<');
543 if (PP.ConcatenateIncludeName(FilenameBuffer))
544 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000545 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000546 break;
547 default:
548 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
549 return false;
550 }
551
Chris Lattnera1394812010-01-10 01:35:12 +0000552 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000553 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
554 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000555 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000556 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000557
558 // Search include directories.
559 const DirectoryLookup *CurDir;
Chris Lattnera1394812010-01-10 01:35:12 +0000560 const FileEntry *File = PP.LookupFile(Filename,
Chris Lattner804f6522010-01-10 00:24:58 +0000561 SourceLocation(),// produce no warnings.
562 isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000563
564 // Get the result value. Result = true means the file exists.
565 Result = File != 0;
566
567 // Get ')'.
568 PP.LexNonComment(Tok);
569
570 // Ensure we have a trailing ).
571 if (Tok.isNot(tok::r_paren)) {
572 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
573 PP.Diag(LParenLoc, diag::note_matching) << "(";
574 return false;
575 }
576
577 return true;
578}
579
580/// EvaluateHasInclude - Process a '__has_include("path")' expression.
581/// Returns true if successful.
582static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
583 Preprocessor &PP) {
584 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
585}
586
587/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
588/// Returns true if successful.
589static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
590 IdentifierInfo *II, Preprocessor &PP) {
591 // __has_include_next is like __has_include, except that we start
592 // searching after the current found directory. If we can't do this,
593 // issue a diagnostic.
594 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
595 if (PP.isInPrimaryFile()) {
596 Lookup = 0;
597 PP.Diag(Tok, diag::pp_include_next_in_primary);
598 } else if (Lookup == 0) {
599 PP.Diag(Tok, diag::pp_include_next_absolute_path);
600 } else {
601 // Start looking up in the next directory.
602 ++Lookup;
603 }
604
605 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
606}
Chris Lattner148772a2009-06-13 07:13:28 +0000607
Chris Lattnera3b605e2008-03-09 03:13:06 +0000608/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
609/// as a builtin macro, handle it and return the next token as 'Tok'.
610void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
611 // Figure out which token this is.
612 IdentifierInfo *II = Tok.getIdentifierInfo();
613 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattnera3b605e2008-03-09 03:13:06 +0000615 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
616 // lex the token after it.
617 if (II == Ident_Pragma)
618 return Handle_Pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattnera3b605e2008-03-09 03:13:06 +0000620 ++NumBuiltinMacroExpanded;
621
622 char TmpBuffer[100];
623
624 // Set up the return result.
625 Tok.setIdentifierInfo(0);
626 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattnera3b605e2008-03-09 03:13:06 +0000628 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000629 // C99 6.10.8: "__LINE__: The presumed line number (within the current
630 // source file) of the current source line (an integer constant)". This can
631 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000632 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattnerdff070f2009-04-18 22:29:33 +0000634 // Advance to the location of the first _, this might not be the first byte
635 // of the token if it starts with an escaped newline.
636 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner081927b2009-02-15 21:06:39 +0000638 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
639 // a macro instantiation. This doesn't matter for object-like macros, but
640 // can matter for a function-like macro that expands to contain __LINE__.
641 // Skip down through instantiation points until we find a file loc for the
642 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000643 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000644 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattner1fa49532009-03-08 08:08:45 +0000646 // __LINE__ expands to a simple numeric value.
647 sprintf(TmpBuffer, "%u", PLoc.getLine());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000648 Tok.setKind(tok::numeric_constant);
Chris Lattner1fa49532009-03-08 08:08:45 +0000649 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000650 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000651 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
652 // character string literal)". This can be affected by #line.
653 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
654
655 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
656 // #include stack instead of the current file.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000657 if (II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000658 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000659 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000660 PLoc = SourceMgr.getPresumedLoc(NextLoc);
661 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000662 }
663 }
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Chris Lattnera3b605e2008-03-09 03:13:06 +0000665 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000666 std::string FN = PLoc.getFilename();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000667 FN = '"' + Lexer::Stringify(FN) + '"';
668 Tok.setKind(tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000669 CreateString(&FN[0], FN.size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000670 } else if (II == Ident__DATE__) {
671 if (!DATELoc.isValid())
672 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
673 Tok.setKind(tok::string_literal);
674 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000675 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000676 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000677 Tok.getLength()));
Chris Lattnera3b605e2008-03-09 03:13:06 +0000678 } else if (II == Ident__TIME__) {
679 if (!TIMELoc.isValid())
680 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
681 Tok.setKind(tok::string_literal);
682 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000683 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000684 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000685 Tok.getLength()));
Chris Lattnera3b605e2008-03-09 03:13:06 +0000686 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000687 // Compute the presumed include depth of this token. This can be affected
688 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000689 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000691 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
692 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
693 for (; PLoc.isValid(); ++Depth)
694 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattner1fa49532009-03-08 08:08:45 +0000696 // __INCLUDE_LEVEL__ expands to a simple numeric value.
697 sprintf(TmpBuffer, "%u", Depth);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000698 Tok.setKind(tok::numeric_constant);
Chris Lattner1fa49532009-03-08 08:08:45 +0000699 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000700 } else if (II == Ident__TIMESTAMP__) {
701 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
702 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000703
704 // Get the file that we are lexing out of. If we're currently lexing from
705 // a macro, dig into the include stack.
706 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000707 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattnera3b605e2008-03-09 03:13:06 +0000709 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000710 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattnera3b605e2008-03-09 03:13:06 +0000712 const char *Result;
713 if (CurFile) {
714 time_t TT = CurFile->getModificationTime();
715 struct tm *TM = localtime(&TT);
716 Result = asctime(TM);
717 } else {
718 Result = "??? ??? ?? ??:??:?? ????\n";
719 }
720 TmpBuffer[0] = '"';
Benjamin Kramer37473822009-09-16 13:10:04 +0000721 unsigned Len = strlen(Result);
722 memcpy(TmpBuffer+1, Result, Len-1); // Copy string without the newline.
723 TmpBuffer[Len] = '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000724 Tok.setKind(tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000725 CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation());
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000726 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000727 // __COUNTER__ expands to a simple numeric value.
728 sprintf(TmpBuffer, "%u", CounterValue++);
729 Tok.setKind(tok::numeric_constant);
730 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattner148772a2009-06-13 07:13:28 +0000731 } else if (II == Ident__has_feature ||
732 II == Ident__has_builtin) {
733 // The argument to these two builtins should be a parenthesized identifier.
734 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Chris Lattner148772a2009-06-13 07:13:28 +0000736 bool IsValid = false;
737 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Chris Lattner148772a2009-06-13 07:13:28 +0000739 // Read the '('.
740 Lex(Tok);
741 if (Tok.is(tok::l_paren)) {
742 // Read the identifier
743 Lex(Tok);
744 if (Tok.is(tok::identifier)) {
745 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattner148772a2009-06-13 07:13:28 +0000747 // Read the ')'.
748 Lex(Tok);
749 if (Tok.is(tok::r_paren))
750 IsValid = true;
751 }
752 }
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Chris Lattner148772a2009-06-13 07:13:28 +0000754 bool Value = false;
755 if (!IsValid)
756 Diag(StartLoc, diag::err_feature_check_malformed);
757 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000758 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000759 Value = FeatureII->getBuiltinID() != 0;
760 } else {
761 assert(II == Ident__has_feature && "Must be feature check");
762 Value = HasFeature(*this, FeatureII);
763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner148772a2009-06-13 07:13:28 +0000765 sprintf(TmpBuffer, "%d", (int)Value);
766 Tok.setKind(tok::numeric_constant);
767 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
John Thompson92bd8c72009-11-02 22:28:12 +0000768 } else if (II == Ident__has_include ||
769 II == Ident__has_include_next) {
770 // The argument to these two builtins should be a parenthesized
771 // file name string literal using angle brackets (<>) or
772 // double-quotes ("").
773 bool Value = false;
774 bool IsValid;
775 if (II == Ident__has_include)
776 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
777 else
778 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
779 sprintf(TmpBuffer, "%d", (int)Value);
780 Tok.setKind(tok::numeric_constant);
781 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000782 } else {
783 assert(0 && "Unknown identifier!");
784 }
785}