blob: 9b20605124d027362f55cf093459fea46ef38deb [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"
Douglas Gregor295a2a62010-10-30 00:23:06 +000023#include "clang/Lex/ExternalPreprocessorSource.h"
Ted Kremenekd7681502011-10-12 19:46:30 +000024#include "clang/Lex/LiteralSupport.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000025#include "llvm/ADT/StringSwitch.h"
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor6665ffb2010-11-09 05:43:53 +000027#include "llvm/Config/config.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000028#include "llvm/Support/raw_ostream.h"
David Blaikie9fe8c742011-09-23 05:35:21 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner3daed522009-03-02 22:20:04 +000030#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000031#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000032using namespace clang;
33
Douglas Gregor295a2a62010-10-30 00:23:06 +000034MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
35 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
36
37 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
38 = Macros.find(II);
39 if (Pos == Macros.end()) {
40 // Load this macro from the external source.
41 getExternalSource()->LoadMacroDefinition(II);
42 Pos = Macros.find(II);
43 }
44 assert(Pos != Macros.end() && "Identifier macro info is missing!");
45 return Pos->second;
46}
47
Chris Lattnera3b605e2008-03-09 03:13:06 +000048/// setMacroInfo - Specify a macro for this identifier.
49///
50void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000051 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000052 Macros[II] = MI;
53 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000054 } else if (II->hasMacroDefinition()) {
55 Macros.erase(II);
56 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000057 }
58}
59
60/// RegisterBuiltinMacro - Register the specified identifier in the identifier
61/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000062static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000063 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000064 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnera3b605e2008-03-09 03:13:06 +000066 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000067 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000068 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000069 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000070 return Id;
71}
72
73
74/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
75/// identifier table.
76void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000077 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
78 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
79 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
80 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
81 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
82 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000083
Chris Lattnera3b605e2008-03-09 03:13:06 +000084 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000085 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
86 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
87 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattner148772a2009-06-13 07:13:28 +000089 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000090 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
Peter Collingbournec1b5fa42011-05-13 20:54:45 +000091 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
John Thompson92bd8c72009-11-02 22:28:12 +000092 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000093 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000094 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
95 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Ted Kremenekd7681502011-10-12 19:46:30 +000096 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
John McCall1ef8a2e2010-08-28 22:34:47 +000097
98 // Microsoft Extensions.
Francois Pichet62ec1f22011-09-17 17:15:52 +000099 if (Features.MicrosoftExt)
John McCall1ef8a2e2010-08-28 22:34:47 +0000100 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
101 else
102 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000103}
104
105/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
106/// in its expansion, currently expands to that token literally.
107static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
108 const IdentifierInfo *MacroIdent,
109 Preprocessor &PP) {
110 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
111
112 // If the token isn't an identifier, it's always literally expanded.
113 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Chris Lattnera3b605e2008-03-09 03:13:06 +0000115 // If the identifier is a macro, and if that macro is enabled, it may be
116 // expanded so it's not a trivial expansion.
117 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
118 // Fast expanding "#define X X" is ok, because X would be disabled.
119 II != MacroIdent)
120 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattnera3b605e2008-03-09 03:13:06 +0000122 // If this is an object-like macro invocation, it is safe to trivially expand
123 // it.
124 if (MI->isObjectLike()) return true;
125
126 // If this is a function-like macro invocation, it's safe to trivially expand
127 // as long as the identifier is not a macro argument.
128 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
129 I != E; ++I)
130 if (*I == II)
131 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Chris Lattnera3b605e2008-03-09 03:13:06 +0000133 return true;
134}
135
136
137/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
138/// lexed is a '('. If so, consume the token and return true, if not, this
139/// method should have no observable side-effect on the lexed tokens.
140bool Preprocessor::isNextPPTokenLParen() {
141 // Do some quick tests for rejection cases.
142 unsigned Val;
143 if (CurLexer)
144 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000145 else if (CurPTHLexer)
146 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000147 else
148 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Chris Lattnera3b605e2008-03-09 03:13:06 +0000150 if (Val == 2) {
151 // We have run off the end. If it's a source file we don't
152 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
153 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000154 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000155 return false;
156 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
157 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
158 if (Entry.TheLexer)
159 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000160 else if (Entry.ThePTHLexer)
161 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000162 else
163 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 if (Val != 2)
166 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattnera3b605e2008-03-09 03:13:06 +0000168 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000169 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000170 return false;
171 }
172 }
173
174 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
175 // have found something that isn't a '(' or we found the end of the
176 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000177 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000178}
179
180/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
181/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000182bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000183 MacroInfo *MI) {
Douglas Gregor13678972010-01-26 19:43:43 +0000184 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000185 // then the macro could expand to different things in other contexts, we need
186 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000187 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Chris Lattnera3b605e2008-03-09 03:13:06 +0000189 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
190 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000191 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
192 Identifier.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000193 ExpandBuiltinMacro(Identifier);
194 return false;
195 }
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattnera3b605e2008-03-09 03:13:06 +0000197 /// Args - If this is a function-like macro expansion, this contains,
198 /// for each macro argument, the list of tokens that were provided to the
199 /// invocation.
200 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000202 // Remember where the end of the expansion occurred. For an object-like
Chris Lattnere7fb4842009-02-15 20:52:18 +0000203 // macro, this is the identifier. For a function-like macro, this is the ')'.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000204 SourceLocation ExpansionEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Chris Lattnera3b605e2008-03-09 03:13:06 +0000206 // If this is a function-like macro, read the arguments.
207 if (MI->isFunctionLike()) {
208 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000209 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000210 if (!isNextPPTokenLParen())
211 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattnera3b605e2008-03-09 03:13:06 +0000213 // Remember that we are now parsing the arguments to a macro invocation.
214 // Preprocessor directives used inside macro arguments are not portable, and
215 // this enables the warning.
216 InMacroArgs = true;
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000217 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Chris Lattnera3b605e2008-03-09 03:13:06 +0000219 // Finished parsing args.
220 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattnera3b605e2008-03-09 03:13:06 +0000222 // If there was an error parsing the arguments, bail out.
223 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattnera3b605e2008-03-09 03:13:06 +0000225 ++NumFnMacroExpanded;
226 } else {
227 ++NumMacroExpanded;
228 }
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattnera3b605e2008-03-09 03:13:06 +0000230 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000231 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000233 // Remember where the token is expanded.
234 SourceLocation ExpandLoc = Identifier.getLocation();
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000235
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000236 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
237 SourceRange(ExpandLoc, ExpansionEnd));
238
239 // If we started lexing a macro, enter the macro expansion body.
240
Chris Lattnera3b605e2008-03-09 03:13:06 +0000241 // If this macro expands to no tokens, don't bother to push it onto the
242 // expansion stack, only to take it right back off.
243 if (MI->getNumTokens() == 0) {
244 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000245 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattnera3b605e2008-03-09 03:13:06 +0000247 // Ignore this macro use, just return the next token in the current
248 // buffer.
249 bool HadLeadingSpace = Identifier.hasLeadingSpace();
250 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattnera3b605e2008-03-09 03:13:06 +0000252 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattnera3b605e2008-03-09 03:13:06 +0000254 // If the identifier isn't on some OTHER line, inherit the leading
255 // whitespace/first-on-a-line property of this token. This handles
256 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
257 // empty.
258 if (!Identifier.isAtStartOfLine()) {
259 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
260 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
261 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000262 Identifier.setFlag(Token::LeadingEmptyMacro);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000263 ++NumFastMacroExpanded;
264 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Chris Lattnera3b605e2008-03-09 03:13:06 +0000266 } else if (MI->getNumTokens() == 1 &&
267 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000268 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000269 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000270 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000271 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000272
273 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000274 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000275
Chris Lattnera3b605e2008-03-09 03:13:06 +0000276 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
277 // identifier to the expanded token.
278 bool isAtStartOfLine = Identifier.isAtStartOfLine();
279 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnera3b605e2008-03-09 03:13:06 +0000281 // Replace the result token.
282 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattnera3b605e2008-03-09 03:13:06 +0000284 // Restore the StartOfLine/LeadingSpace markers.
285 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
286 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000288 // Update the tokens location to include both its expansion and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000289 // locations.
290 SourceLocation Loc =
Chandler Carruthbf340e42011-07-26 03:03:05 +0000291 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
292 ExpansionEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000293 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattner8ff66de2010-03-26 17:49:16 +0000295 // If this is a disabled macro or #define X X, we must mark the result as
296 // unexpandable.
297 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
298 if (MacroInfo *NewMI = getMacroInfo(NewII))
299 if (!NewMI->isEnabled() || NewMI == MI)
300 Identifier.setFlag(Token::DisableExpand);
301 }
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattnera3b605e2008-03-09 03:13:06 +0000303 // Since this is not an identifier token, it can't be macro expanded, so
304 // we're done.
305 ++NumFastMacroExpanded;
306 return false;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattnera3b605e2008-03-09 03:13:06 +0000309 // Start expanding the macro.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000310 EnterMacro(Identifier, ExpansionEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnera3b605e2008-03-09 03:13:06 +0000312 // Now that the macro is at the top of the include stack, ask the
313 // preprocessor to read the next token from it.
314 Lex(Identifier);
315 return false;
316}
317
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000318/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
319/// token is the '(' of the macro, this method is invoked to read all of the
320/// actual arguments specified for the macro invocation. This returns null on
321/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000322MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000323 MacroInfo *MI,
324 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000325 // The number of fixed arguments to parse.
326 unsigned NumFixedArgsLeft = MI->getNumArgs();
327 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattnera3b605e2008-03-09 03:13:06 +0000329 // Outer loop, while there are more arguments, keep reading them.
330 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000331
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000332 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
333 // an argument value in a macro could expand to ',' or '(' or ')'.
334 LexUnexpandedToken(Tok);
335 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattnera3b605e2008-03-09 03:13:06 +0000337 // ArgTokens - Build up a list of tokens that make up each argument. Each
338 // argument is separated by an EOF token. Use a SmallVector so we can avoid
339 // heap allocations in the common case.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000340 SmallVector<Token, 64> ArgTokens;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000341
342 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000343 while (Tok.isNot(tok::r_paren)) {
344 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
345 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000347 unsigned ArgTokenStart = ArgTokens.size();
348 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattnera3b605e2008-03-09 03:13:06 +0000350 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
351 // that we already consumed the first one.
352 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Chris Lattnera3b605e2008-03-09 03:13:06 +0000354 while (1) {
355 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
356 // an argument value in a macro could expand to ',' or '(' or ')'.
357 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Peter Collingbourne84021552011-02-28 02:37:51 +0000359 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattnera3b605e2008-03-09 03:13:06 +0000360 Diag(MacroName, diag::err_unterm_macro_invoc);
Peter Collingbourne84021552011-02-28 02:37:51 +0000361 // Do not lose the EOF/EOD. Return it to the client.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000362 MacroName = Tok;
363 return 0;
364 } else if (Tok.is(tok::r_paren)) {
365 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000366 if (NumParens-- == 0) {
367 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000368 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000369 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000370 } else if (Tok.is(tok::l_paren)) {
371 ++NumParens;
372 } else if (Tok.is(tok::comma) && NumParens == 0) {
373 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000374 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000375 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000376 if (!isVariadic) break;
377 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000378 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000379 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
380 // If this is a comment token in the argument list and we're just in
381 // -C mode (not -CC mode), discard the comment.
382 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000383 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000384 // Reading macro arguments can cause macros that we are currently
385 // expanding from to be popped off the expansion stack. Doing so causes
386 // them to be reenabled for expansion. Here we record whether any
387 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000388 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000389 // C99 6.10.3.4p2.
390 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
391 if (!MI->isEnabled())
392 Tok.setFlag(Token::DisableExpand);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000393 } else if (Tok.is(tok::code_completion)) {
394 if (CodeComplete)
395 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
396 MI, NumActuals);
397 // Don't mark that we reached the code-completion point because the
398 // parser is going to handle the token and there will be another
399 // code-completion callback.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000401
Chris Lattnera3b605e2008-03-09 03:13:06 +0000402 ArgTokens.push_back(Tok);
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000405 // If this was an empty argument list foo(), don't add this as an empty
406 // argument.
407 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
408 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000409
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000410 // If this is not a variadic macro, and too many args were specified, emit
411 // an error.
412 if (!isVariadic && NumFixedArgsLeft == 0) {
413 if (ArgTokens.size() != ArgTokenStart)
414 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000416 // Emit the diagnostic at the macro name in case there is a missing ).
417 // Emitting it at the , could be far away from the macro name.
418 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
419 return 0;
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner32c13882011-04-22 23:25:09 +0000422 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000423 // other modes.
Chris Lattner32c13882011-04-22 23:25:09 +0000424 if (ArgTokens.size() == ArgTokenStart && !Features.C99 && !Features.CPlusPlus0x)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000425 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattnera3b605e2008-03-09 03:13:06 +0000427 // Add a marker EOF token to the end of the token list for this argument.
428 Token EOFTok;
429 EOFTok.startToken();
430 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000431 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000432 EOFTok.setLength(0);
433 ArgTokens.push_back(EOFTok);
434 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000435 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000436 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattnera3b605e2008-03-09 03:13:06 +0000439 // Okay, we either found the r_paren. Check to see if we parsed too few
440 // arguments.
441 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Chris Lattnera3b605e2008-03-09 03:13:06 +0000443 // See MacroArgs instance var for description of this.
444 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattnera3b605e2008-03-09 03:13:06 +0000446 if (NumActuals < MinArgsExpected) {
447 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000448 if (NumActuals == 0 && MinArgsExpected == 1) {
449 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner97e2de12009-04-20 21:08:10 +0000451 // If there is exactly one argument, and that argument is missing,
452 // then we have an empty "()" argument empty list. This is fine, even if
453 // the macro expects one argument (the argument is just empty).
454 isVarargsElided = MI->isVariadic();
455 } else if (MI->isVariadic() &&
456 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
457 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000458 // Varargs where the named vararg parameter is missing: ok as extension.
459 // #define A(x, ...)
460 // A("blah")
461 Diag(Tok, diag::ext_missing_varargs_arg);
462
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000463 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000464 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000465 // #define A(x, foo...) blah(a, ## foo)
466 // #define B(x, ...) blah(a, ## __VA_ARGS__)
467 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000468 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000469 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000470 } else {
471 // Otherwise, emit the error.
472 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
473 return 0;
474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Chris Lattnera3b605e2008-03-09 03:13:06 +0000476 // Add a marker EOF token to the end of the token list for this argument.
477 SourceLocation EndLoc = Tok.getLocation();
478 Tok.startToken();
479 Tok.setKind(tok::eof);
480 Tok.setLocation(EndLoc);
481 Tok.setLength(0);
482 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000483
484 // If we expect two arguments, add both as empty.
485 if (NumActuals == 0 && MinArgsExpected == 2)
486 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000488 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
489 // Emit the diagnostic at the macro name in case there is a missing ).
490 // Emitting it at the , could be far away from the macro name.
491 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
492 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
David Blaikied7bb6a02011-09-22 02:03:12 +0000495 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000496}
497
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000498/// \brief Keeps macro expanded tokens for TokenLexers.
499//
500/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
501/// going to lex in the cache and when it finishes the tokens are removed
502/// from the end of the cache.
503Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +0000504 ArrayRef<Token> tokens) {
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000505 assert(tokLexer);
506 if (tokens.empty())
507 return 0;
508
509 size_t newIndex = MacroExpandedTokens.size();
510 bool cacheNeedsToGrow = tokens.size() >
511 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
512 MacroExpandedTokens.append(tokens.begin(), tokens.end());
513
514 if (cacheNeedsToGrow) {
515 // Go through all the TokenLexers whose 'Tokens' pointer points in the
516 // buffer and update the pointers to the (potential) new buffer array.
517 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
518 TokenLexer *prevLexer;
519 size_t tokIndex;
520 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
521 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
522 }
523 }
524
525 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
526 return MacroExpandedTokens.data() + newIndex;
527}
528
529void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
530 assert(!MacroExpandingLexersStack.empty());
531 size_t tokIndex = MacroExpandingLexersStack.back().second;
532 assert(tokIndex < MacroExpandedTokens.size());
533 // Pop the cached macro expanded tokens from the end.
534 MacroExpandedTokens.resize(tokIndex);
535 MacroExpandingLexersStack.pop_back();
536}
537
Chris Lattnera3b605e2008-03-09 03:13:06 +0000538/// ComputeDATE_TIME - Compute the current time, enter it into the specified
539/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
540/// the identifier tokens inserted.
541static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
542 Preprocessor &PP) {
543 time_t TT = time(0);
544 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattnera3b605e2008-03-09 03:13:06 +0000546 static const char * const Months[] = {
547 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
548 };
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000550 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000551#ifdef LLVM_ON_WIN32
552 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
553 TM->tm_year+1900);
554#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000555 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000556 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000557#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner47246be2009-01-26 19:29:26 +0000559 Token TmpTok;
560 TmpTok.startToken();
561 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
562 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000563
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000564#ifdef LLVM_ON_WIN32
565 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
566#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000567 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000568#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000569 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
570 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000571}
572
Chris Lattner148772a2009-06-13 07:13:28 +0000573
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000574/// HasFeature - Return true if we recognize and implement the feature
575/// specified by the identifier as a standard language feature.
Chris Lattner148772a2009-06-13 07:13:28 +0000576static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
577 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Benjamin Kramer32592e82010-01-09 18:53:11 +0000579 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000580 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000581 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000582 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000583 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000584 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000585 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000586 .Case("attribute_ns_returns_not_retained", true)
587 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000588 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000589 .Case("attribute_ns_consumed", true)
590 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000591 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000592 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000593 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000594 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000595 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000596 .Case("cxx_exceptions", LangOpts.Exceptions)
597 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000598 .Case("enumerator_attributes", true)
John McCallf85e1932011-06-15 23:02:42 +0000599 // Objective-C features
600 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
601 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
602 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
John McCall9f084a32011-07-06 00:26:06 +0000603 LangOpts.ObjCRuntimeHasWeak)
Douglas Gregor5471bc82011-09-08 17:18:35 +0000604 .Case("objc_fixed_enum", LangOpts.ObjC2)
Douglas Gregore97179c2011-09-08 01:46:34 +0000605 .Case("objc_instancetype", LangOpts.ObjC2)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000606 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000607 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000608 .Case("ownership_holds", true)
609 .Case("ownership_returns", true)
610 .Case("ownership_takes", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000611 // C1X features
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000612 .Case("c_alignas", LangOpts.C1X)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000613 .Case("c_generic_selections", LangOpts.C1X)
614 .Case("c_static_assert", LangOpts.C1X)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000615 // C++0x features
Douglas Gregor7822ee32011-05-11 23:45:11 +0000616 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000617 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000618 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000619 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000620 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000621 //.Case("cxx_constexpr", false);
Douglas Gregorc78e2592011-01-26 15:36:03 +0000622 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000623 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Sean Hunt059ce0d2011-05-01 07:04:31 +0000624 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000625 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000626 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
Sean Hunte1f6dea2011-08-07 00:34:32 +0000627 //.Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
Sebastian Redl74e611a2011-09-04 18:14:28 +0000628 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000629 //.Case("cxx_inheriting_constructors", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000630 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000631 //.Case("cxx_lambdas", false)
Douglas Gregorece38942011-08-29 17:28:38 +0000632 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000633 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000634 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000635 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000636 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000637 //.Case("cxx_raw_string_literals", false)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000638 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000639 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
640 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
641 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
642 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000643 //.Case("cxx_unicode_literals", false)
644 //.Case("cxx_unrestricted_unions", false)
645 //.Case("cxx_user_literals", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000646 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000647 // Type traits
648 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
649 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
650 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
651 .Case("has_trivial_assign", LangOpts.CPlusPlus)
652 .Case("has_trivial_copy", LangOpts.CPlusPlus)
653 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
654 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
655 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
656 .Case("is_abstract", LangOpts.CPlusPlus)
657 .Case("is_base_of", LangOpts.CPlusPlus)
658 .Case("is_class", LangOpts.CPlusPlus)
659 .Case("is_convertible_to", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000660 // __is_empty is available only if the horrible
661 // "struct __is_empty" parsing hack hasn't been needed in this
662 // translation unit. If it has, __is_empty reverts to a normal
663 // identifier and __has_feature(is_empty) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000664 .Case("is_empty",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000665 LangOpts.CPlusPlus &&
666 PP.getIdentifierInfo("__is_empty")->getTokenID()
667 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000668 .Case("is_enum", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000669 .Case("is_literal", LangOpts.CPlusPlus)
Howard Hinnanta55e68b2011-05-12 19:52:14 +0000670 .Case("is_standard_layout", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000671 // __is_pod is available only if the horrible
672 // "struct __is_pod" parsing hack hasn't been needed in this
673 // translation unit. If it has, __is_pod reverts to a normal
674 // identifier and __has_feature(is_pod) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000675 .Case("is_pod",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000676 LangOpts.CPlusPlus &&
677 PP.getIdentifierInfo("__is_pod")->getTokenID()
678 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000679 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000680 .Case("is_trivial", LangOpts.CPlusPlus)
Sean Huntfeb375d2011-05-13 00:31:07 +0000681 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000682 .Case("is_union", LangOpts.CPlusPlus)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000683 .Case("tls", PP.getTargetInfo().isTLSSupported())
Sean Hunt858a3252011-07-18 17:08:00 +0000684 .Case("underlying_type", LangOpts.CPlusPlus)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000685 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000686}
687
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000688/// HasExtension - Return true if we recognize and implement the feature
689/// specified by the identifier, either as an extension or a standard language
690/// feature.
691static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
692 if (HasFeature(PP, II))
693 return true;
694
695 // If the use of an extension results in an error diagnostic, extensions are
696 // effectively unavailable, so just return false here.
David Blaikied6471f72011-09-25 23:23:43 +0000697 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
698 DiagnosticsEngine::Ext_Error)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000699 return false;
700
701 const LangOptions &LangOpts = PP.getLangOptions();
702
703 // Because we inherit the feature list from HasFeature, this string switch
704 // must be less restrictive than HasFeature's.
705 return llvm::StringSwitch<bool>(II->getName())
706 // C1X features supported by other languages as extensions.
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000707 .Case("c_alignas", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000708 .Case("c_generic_selections", true)
709 .Case("c_static_assert", true)
710 // C++0x features supported by other languages as extensions.
711 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000712 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000713 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000714 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000715 .Case("cxx_override_control", LangOpts.CPlusPlus)
Richard Smith7640c002011-09-06 18:03:41 +0000716 .Case("cxx_range_for", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000717 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
718 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
719 .Default(false);
720}
721
Anders Carlssoncae50952010-10-20 02:31:43 +0000722/// HasAttribute - Return true if we recognize and implement the attribute
723/// specified by the given identifier.
724static bool HasAttribute(const IdentifierInfo *II) {
725 return llvm::StringSwitch<bool>(II->getName())
726#include "clang/Lex/AttrSpellings.inc"
727 .Default(false);
728}
729
John Thompson92bd8c72009-11-02 22:28:12 +0000730/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
731/// or '__has_include_next("path")' expression.
732/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000733static bool EvaluateHasIncludeCommon(Token &Tok,
734 IdentifierInfo *II, Preprocessor &PP,
735 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000736 SourceLocation LParenLoc;
737
738 // Get '('.
739 PP.LexNonComment(Tok);
740
741 // Ensure we have a '('.
742 if (Tok.isNot(tok::l_paren)) {
743 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
744 return false;
745 }
746
747 // Save '(' location for possible missing ')' message.
748 LParenLoc = Tok.getLocation();
749
750 // Get the file name.
751 PP.getCurrentLexer()->LexIncludeFilename(Tok);
752
753 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000754 llvm::SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000755 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000756 SourceLocation EndLoc;
757
John Thompson92bd8c72009-11-02 22:28:12 +0000758 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000759 case tok::eod:
760 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000761 return false;
762
763 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000764 case tok::string_literal: {
765 bool Invalid = false;
766 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
767 if (Invalid)
768 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000769 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000770 }
John Thompson92bd8c72009-11-02 22:28:12 +0000771
772 case tok::less:
773 // This could be a <foo/bar.h> file coming from a macro expansion. In this
774 // case, glue the tokens together into FilenameBuffer and interpret those.
775 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000776 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000777 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000778 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000779 break;
780 default:
781 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
782 return false;
783 }
784
Chris Lattnera1394812010-01-10 01:35:12 +0000785 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000786 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
787 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000788 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000789 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000790
791 // Search include directories.
792 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000793 const FileEntry *File =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000794 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000795
796 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000797 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000798
799 // Get ')'.
800 PP.LexNonComment(Tok);
801
802 // Ensure we have a trailing ).
803 if (Tok.isNot(tok::r_paren)) {
804 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
805 PP.Diag(LParenLoc, diag::note_matching) << "(";
806 return false;
807 }
808
Chris Lattner3ed572e2011-01-15 06:57:04 +0000809 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000810}
811
812/// EvaluateHasInclude - Process a '__has_include("path")' expression.
813/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000814static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000815 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000816 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000817}
818
819/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
820/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000821static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000822 IdentifierInfo *II, Preprocessor &PP) {
823 // __has_include_next is like __has_include, except that we start
824 // searching after the current found directory. If we can't do this,
825 // issue a diagnostic.
826 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
827 if (PP.isInPrimaryFile()) {
828 Lookup = 0;
829 PP.Diag(Tok, diag::pp_include_next_in_primary);
830 } else if (Lookup == 0) {
831 PP.Diag(Tok, diag::pp_include_next_absolute_path);
832 } else {
833 // Start looking up in the next directory.
834 ++Lookup;
835 }
836
Chris Lattner3ed572e2011-01-15 06:57:04 +0000837 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000838}
Chris Lattner148772a2009-06-13 07:13:28 +0000839
Chris Lattnera3b605e2008-03-09 03:13:06 +0000840/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
841/// as a builtin macro, handle it and return the next token as 'Tok'.
842void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
843 // Figure out which token this is.
844 IdentifierInfo *II = Tok.getIdentifierInfo();
845 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000846
John McCall1ef8a2e2010-08-28 22:34:47 +0000847 // If this is an _Pragma or Microsoft __pragma directive, expand it,
848 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000849 if (II == Ident_Pragma)
850 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000851 else if (II == Ident__pragma) // in non-MS mode this is null
852 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattnera3b605e2008-03-09 03:13:06 +0000854 ++NumBuiltinMacroExpanded;
855
Benjamin Kramerb1765912010-01-27 16:38:22 +0000856 llvm::SmallString<128> TmpBuffer;
857 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000858
859 // Set up the return result.
860 Tok.setIdentifierInfo(0);
861 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattnera3b605e2008-03-09 03:13:06 +0000863 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000864 // C99 6.10.8: "__LINE__: The presumed line number (within the current
865 // source file) of the current source line (an integer constant)". This can
866 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000867 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Chris Lattnerdff070f2009-04-18 22:29:33 +0000869 // Advance to the location of the first _, this might not be the first byte
870 // of the token if it starts with an escaped newline.
871 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Chris Lattner081927b2009-02-15 21:06:39 +0000873 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000874 // a macro expansion. This doesn't matter for object-like macros, but
Chris Lattner081927b2009-02-15 21:06:39 +0000875 // can matter for a function-like macro that expands to contain __LINE__.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000876 // Skip down through expansion points until we find a file loc for the
877 // end of the expansion history.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000878 Loc = SourceMgr.getExpansionRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000879 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner1fa49532009-03-08 08:08:45 +0000881 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000882 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000883 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000884 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000885 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
886 // character string literal)". This can be affected by #line.
887 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
888
889 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
890 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000891 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000892 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000893 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000894 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000895 if (PLoc.isInvalid())
896 break;
897
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000898 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000899 }
900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Chris Lattnera3b605e2008-03-09 03:13:06 +0000902 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000903 llvm::SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000904 if (PLoc.isValid()) {
905 FN += PLoc.getFilename();
906 Lexer::Stringify(FN);
907 OS << '"' << FN.str() << '"';
908 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000909 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000910 } else if (II == Ident__DATE__) {
911 if (!DATELoc.isValid())
912 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
913 Tok.setKind(tok::string_literal);
914 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000915 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
916 Tok.getLocation(),
917 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000918 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000919 } else if (II == Ident__TIME__) {
920 if (!TIMELoc.isValid())
921 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
922 Tok.setKind(tok::string_literal);
923 Tok.setLength(strlen("\"hh:mm:ss\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000924 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
925 Tok.getLocation(),
926 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000927 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000928 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000929 // Compute the presumed include depth of this token. This can be affected
930 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000931 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000933 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000934 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000935 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000936 for (; PLoc.isValid(); ++Depth)
937 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner1fa49532009-03-08 08:08:45 +0000940 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000941 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000942 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000943 } else if (II == Ident__TIMESTAMP__) {
944 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
945 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000946
947 // Get the file that we are lexing out of. If we're currently lexing from
948 // a macro, dig into the include stack.
949 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000950 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Chris Lattnera3b605e2008-03-09 03:13:06 +0000952 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000953 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattnera3b605e2008-03-09 03:13:06 +0000955 const char *Result;
956 if (CurFile) {
957 time_t TT = CurFile->getModificationTime();
958 struct tm *TM = localtime(&TT);
959 Result = asctime(TM);
960 } else {
961 Result = "??? ??? ?? ??:??:?? ????\n";
962 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000963 // Surround the string with " and strip the trailing newline.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000964 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000965 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000966 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000967 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000968 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000969 Tok.setKind(tok::numeric_constant);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000970 } else if (II == Ident__has_feature ||
971 II == Ident__has_extension ||
972 II == Ident__has_builtin ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000973 II == Ident__has_attribute) {
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000974 // The argument to these builtins should be a parenthesized identifier.
Chris Lattner148772a2009-06-13 07:13:28 +0000975 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chris Lattner148772a2009-06-13 07:13:28 +0000977 bool IsValid = false;
978 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner148772a2009-06-13 07:13:28 +0000980 // Read the '('.
981 Lex(Tok);
982 if (Tok.is(tok::l_paren)) {
983 // Read the identifier
984 Lex(Tok);
985 if (Tok.is(tok::identifier)) {
986 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattner148772a2009-06-13 07:13:28 +0000988 // Read the ')'.
989 Lex(Tok);
990 if (Tok.is(tok::r_paren))
991 IsValid = true;
992 }
993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattner148772a2009-06-13 07:13:28 +0000995 bool Value = false;
996 if (!IsValid)
997 Diag(StartLoc, diag::err_feature_check_malformed);
998 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000999 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +00001000 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +00001001 } else if (II == Ident__has_attribute)
1002 Value = HasAttribute(FeatureII);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001003 else if (II == Ident__has_extension)
1004 Value = HasExtension(*this, FeatureII);
Anders Carlssoncae50952010-10-20 02:31:43 +00001005 else {
Chris Lattner148772a2009-06-13 07:13:28 +00001006 assert(II == Ident__has_feature && "Must be feature check");
1007 Value = HasFeature(*this, FeatureII);
1008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Benjamin Kramerb1765912010-01-27 16:38:22 +00001010 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +00001011 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +00001012 } else if (II == Ident__has_include ||
1013 II == Ident__has_include_next) {
1014 // The argument to these two builtins should be a parenthesized
1015 // file name string literal using angle brackets (<>) or
1016 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +00001017 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001018 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +00001019 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +00001020 else
Chris Lattner3ed572e2011-01-15 06:57:04 +00001021 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +00001022 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001023 Tok.setKind(tok::numeric_constant);
Ted Kremenekd7681502011-10-12 19:46:30 +00001024 } else if (II == Ident__has_warning) {
1025 // The argument should be a parenthesized string literal.
1026 // The argument to these builtins should be a parenthesized identifier.
1027 SourceLocation StartLoc = Tok.getLocation();
1028 bool IsValid = false;
1029 bool Value = false;
1030 // Read the '('.
1031 Lex(Tok);
1032 do {
1033 if (Tok.is(tok::l_paren)) {
1034 // Read the string.
1035 Lex(Tok);
1036
1037 // We need at least one string literal.
1038 if (!Tok.is(tok::string_literal)) {
1039 StartLoc = Tok.getLocation();
1040 IsValid = false;
1041 // Eat tokens until ')'.
1042 do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1043 break;
1044 }
1045
1046 // String concatenation allows multiple strings, which can even come
1047 // from macro expansion.
1048 SmallVector<Token, 4> StrToks;
1049 while (Tok.is(tok::string_literal)) {
1050 StrToks.push_back(Tok);
1051 LexUnexpandedToken(Tok);
1052 }
1053
1054 // Is the end a ')'?
1055 if (!(IsValid = Tok.is(tok::r_paren)))
1056 break;
1057
1058 // Concatenate and parse the strings.
1059 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1060 assert(Literal.isAscii() && "Didn't allow wide strings in");
1061 if (Literal.hadError)
1062 break;
1063 if (Literal.Pascal) {
1064 Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1065 break;
1066 }
1067
1068 StringRef WarningName(Literal.GetString());
1069
1070 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1071 WarningName[1] != 'W') {
1072 Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1073 break;
1074 }
1075
1076 // Finally, check if the warning flags maps to a diagnostic group.
1077 // We construct a SmallVector here to talk to getDiagnosticIDs().
1078 // Although we don't use the result, this isn't a hot path, and not
1079 // worth special casing.
1080 llvm::SmallVector<diag::kind, 10> Diags;
1081 Value = !getDiagnostics().getDiagnosticIDs()->
1082 getDiagnosticsInGroup(WarningName.substr(2), Diags);
1083 }
1084 } while (false);
1085
1086 if (!IsValid)
1087 Diag(StartLoc, diag::err_warning_check_malformed);
1088
1089 OS << (int)Value;
1090 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001091 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001092 llvm_unreachable("Unknown identifier!");
Chris Lattnera3b605e2008-03-09 03:13:06 +00001093 }
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001094 CreateString(OS.str().data(), OS.str().size(), Tok,
1095 Tok.getLocation(), Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +00001096}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001097
1098void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1099 // If the 'used' status changed, and the macro requires 'unused' warning,
1100 // remove its SourceLocation from the warn-for-unused-macro locations.
1101 if (MI->isWarnIfUnused() && !MI->isUsed())
1102 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1103 MI->setIsUsed(true);
1104}