blob: 01cd75fa8485202561ffadd1681b4d9a6c472be1 [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"
Benjamin Kramer32592e82010-01-09 18:53:11 +000024#include "llvm/ADT/StringSwitch.h"
Douglas Gregor6665ffb2010-11-09 05:43:53 +000025#include "llvm/Config/config.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000026#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000027#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000028#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000029using namespace clang;
30
Douglas Gregor295a2a62010-10-30 00:23:06 +000031MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
32 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
33
34 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
35 = Macros.find(II);
36 if (Pos == Macros.end()) {
37 // Load this macro from the external source.
38 getExternalSource()->LoadMacroDefinition(II);
39 Pos = Macros.find(II);
40 }
41 assert(Pos != Macros.end() && "Identifier macro info is missing!");
42 return Pos->second;
43}
44
Chris Lattnera3b605e2008-03-09 03:13:06 +000045/// setMacroInfo - Specify a macro for this identifier.
46///
47void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000048 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000049 Macros[II] = MI;
50 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000051 } else if (II->hasMacroDefinition()) {
52 Macros.erase(II);
53 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000054 }
55}
56
57/// RegisterBuiltinMacro - Register the specified identifier in the identifier
58/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000059static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000060 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000061 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattnera3b605e2008-03-09 03:13:06 +000063 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000064 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000065 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000066 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000067 return Id;
68}
69
70
71/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
72/// identifier table.
73void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000074 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
75 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
76 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
77 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
78 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
79 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattnera3b605e2008-03-09 03:13:06 +000081 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000082 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
83 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
84 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattner148772a2009-06-13 07:13:28 +000086 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000087 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
Peter Collingbournec1b5fa42011-05-13 20:54:45 +000088 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
John Thompson92bd8c72009-11-02 22:28:12 +000089 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000090 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000091 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
92 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall1ef8a2e2010-08-28 22:34:47 +000093
94 // Microsoft Extensions.
95 if (Features.Microsoft)
96 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
97 else
98 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +000099}
100
101/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
102/// in its expansion, currently expands to that token literally.
103static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
104 const IdentifierInfo *MacroIdent,
105 Preprocessor &PP) {
106 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
107
108 // If the token isn't an identifier, it's always literally expanded.
109 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000110
Chris Lattnera3b605e2008-03-09 03:13:06 +0000111 // If the identifier is a macro, and if that macro is enabled, it may be
112 // expanded so it's not a trivial expansion.
113 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
114 // Fast expanding "#define X X" is ok, because X would be disabled.
115 II != MacroIdent)
116 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Chris Lattnera3b605e2008-03-09 03:13:06 +0000118 // If this is an object-like macro invocation, it is safe to trivially expand
119 // it.
120 if (MI->isObjectLike()) return true;
121
122 // If this is a function-like macro invocation, it's safe to trivially expand
123 // as long as the identifier is not a macro argument.
124 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
125 I != E; ++I)
126 if (*I == II)
127 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Chris Lattnera3b605e2008-03-09 03:13:06 +0000129 return true;
130}
131
132
133/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
134/// lexed is a '('. If so, consume the token and return true, if not, this
135/// method should have no observable side-effect on the lexed tokens.
136bool Preprocessor::isNextPPTokenLParen() {
137 // Do some quick tests for rejection cases.
138 unsigned Val;
139 if (CurLexer)
140 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000141 else if (CurPTHLexer)
142 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000143 else
144 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Chris Lattnera3b605e2008-03-09 03:13:06 +0000146 if (Val == 2) {
147 // We have run off the end. If it's a source file we don't
148 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
149 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000150 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000151 return false;
152 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
153 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
154 if (Entry.TheLexer)
155 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000156 else if (Entry.ThePTHLexer)
157 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000158 else
159 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattnera3b605e2008-03-09 03:13:06 +0000161 if (Val != 2)
162 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattnera3b605e2008-03-09 03:13:06 +0000164 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000165 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000166 return false;
167 }
168 }
169
170 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
171 // have found something that isn't a '(' or we found the end of the
172 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000173 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000174}
175
176/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
177/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000178bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000179 MacroInfo *MI) {
Douglas Gregor13678972010-01-26 19:43:43 +0000180 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000181 // then the macro could expand to different things in other contexts, we need
182 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000183 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattnera3b605e2008-03-09 03:13:06 +0000185 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
186 if (MI->isBuiltinMacro()) {
Douglas Gregor91d3df52011-04-28 16:36:13 +0000187 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000188 ExpandBuiltinMacro(Identifier);
189 return false;
190 }
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattnera3b605e2008-03-09 03:13:06 +0000192 /// Args - If this is a function-like macro expansion, this contains,
193 /// for each macro argument, the list of tokens that were provided to the
194 /// invocation.
195 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattnere7fb4842009-02-15 20:52:18 +0000197 // Remember where the end of the instantiation occurred. For an object-like
198 // macro, this is the identifier. For a function-like macro, this is the ')'.
199 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnera3b605e2008-03-09 03:13:06 +0000201 // If this is a function-like macro, read the arguments.
202 if (MI->isFunctionLike()) {
203 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000204 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000205 if (!isNextPPTokenLParen())
206 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Chris Lattnera3b605e2008-03-09 03:13:06 +0000208 // Remember that we are now parsing the arguments to a macro invocation.
209 // Preprocessor directives used inside macro arguments are not portable, and
210 // this enables the warning.
211 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000212 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattnera3b605e2008-03-09 03:13:06 +0000214 // Finished parsing args.
215 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattnera3b605e2008-03-09 03:13:06 +0000217 // If there was an error parsing the arguments, bail out.
218 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattnera3b605e2008-03-09 03:13:06 +0000220 ++NumFnMacroExpanded;
221 } else {
222 ++NumMacroExpanded;
223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattnera3b605e2008-03-09 03:13:06 +0000225 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000226 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Douglas Gregor91d3df52011-04-28 16:36:13 +0000228 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
229
Chris Lattnera3b605e2008-03-09 03:13:06 +0000230 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000232 // Remember where the token is instantiated.
233 SourceLocation InstantiateLoc = Identifier.getLocation();
234
Chris Lattnera3b605e2008-03-09 03:13:06 +0000235 // If this macro expands to no tokens, don't bother to push it onto the
236 // expansion stack, only to take it right back off.
237 if (MI->getNumTokens() == 0) {
238 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000239 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattnera3b605e2008-03-09 03:13:06 +0000241 // Ignore this macro use, just return the next token in the current
242 // buffer.
243 bool HadLeadingSpace = Identifier.hasLeadingSpace();
244 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattnera3b605e2008-03-09 03:13:06 +0000246 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattnera3b605e2008-03-09 03:13:06 +0000248 // If the identifier isn't on some OTHER line, inherit the leading
249 // whitespace/first-on-a-line property of this token. This handles
250 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
251 // empty.
252 if (!Identifier.isAtStartOfLine()) {
253 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
254 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
255 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000256 Identifier.setFlag(Token::LeadingEmptyMacro);
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000257 LastEmptyMacroInstantiationLoc = InstantiateLoc;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000258 ++NumFastMacroExpanded;
259 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattnera3b605e2008-03-09 03:13:06 +0000261 } else if (MI->getNumTokens() == 1 &&
262 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000263 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000264 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000265 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000266 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000267
268 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000269 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000270
Chris Lattnera3b605e2008-03-09 03:13:06 +0000271 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
272 // identifier to the expanded token.
273 bool isAtStartOfLine = Identifier.isAtStartOfLine();
274 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattnera3b605e2008-03-09 03:13:06 +0000276 // Replace the result token.
277 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattnera3b605e2008-03-09 03:13:06 +0000279 // Restore the StartOfLine/LeadingSpace markers.
280 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
281 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000283 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000284 // locations.
285 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000286 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000287 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000288 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattner8ff66de2010-03-26 17:49:16 +0000290 // If this is a disabled macro or #define X X, we must mark the result as
291 // unexpandable.
292 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
293 if (MacroInfo *NewMI = getMacroInfo(NewII))
294 if (!NewMI->isEnabled() || NewMI == MI)
295 Identifier.setFlag(Token::DisableExpand);
296 }
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattnera3b605e2008-03-09 03:13:06 +0000298 // Since this is not an identifier token, it can't be macro expanded, so
299 // we're done.
300 ++NumFastMacroExpanded;
301 return false;
302 }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnera3b605e2008-03-09 03:13:06 +0000304 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000305 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Chris Lattnera3b605e2008-03-09 03:13:06 +0000307 // Now that the macro is at the top of the include stack, ask the
308 // preprocessor to read the next token from it.
309 Lex(Identifier);
310 return false;
311}
312
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000313/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
314/// token is the '(' of the macro, this method is invoked to read all of the
315/// actual arguments specified for the macro invocation. This returns null on
316/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000317MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000318 MacroInfo *MI,
319 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000320 // The number of fixed arguments to parse.
321 unsigned NumFixedArgsLeft = MI->getNumArgs();
322 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattnera3b605e2008-03-09 03:13:06 +0000324 // Outer loop, while there are more arguments, keep reading them.
325 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000326
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000327 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
328 // an argument value in a macro could expand to ',' or '(' or ')'.
329 LexUnexpandedToken(Tok);
330 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattnera3b605e2008-03-09 03:13:06 +0000332 // ArgTokens - Build up a list of tokens that make up each argument. Each
333 // argument is separated by an EOF token. Use a SmallVector so we can avoid
334 // heap allocations in the common case.
335 llvm::SmallVector<Token, 64> ArgTokens;
336
337 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000338 while (Tok.isNot(tok::r_paren)) {
339 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
340 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000342 unsigned ArgTokenStart = ArgTokens.size();
343 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattnera3b605e2008-03-09 03:13:06 +0000345 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
346 // that we already consumed the first one.
347 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattnera3b605e2008-03-09 03:13:06 +0000349 while (1) {
350 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
351 // an argument value in a macro could expand to ',' or '(' or ')'.
352 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Douglas Gregorf29c5232010-08-24 22:20:20 +0000354 if (Tok.is(tok::code_completion)) {
355 if (CodeComplete)
356 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
357 MI, NumActuals);
358 LexUnexpandedToken(Tok);
359 }
360
Peter Collingbourne84021552011-02-28 02:37:51 +0000361 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattnera3b605e2008-03-09 03:13:06 +0000362 Diag(MacroName, diag::err_unterm_macro_invoc);
Peter Collingbourne84021552011-02-28 02:37:51 +0000363 // Do not lose the EOF/EOD. Return it to the client.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000364 MacroName = Tok;
365 return 0;
366 } else if (Tok.is(tok::r_paren)) {
367 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000368 if (NumParens-- == 0) {
369 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000370 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000371 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000372 } else if (Tok.is(tok::l_paren)) {
373 ++NumParens;
374 } else if (Tok.is(tok::comma) && NumParens == 0) {
375 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000376 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000377 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000378 if (!isVariadic) break;
379 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000380 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000381 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
382 // If this is a comment token in the argument list and we're just in
383 // -C mode (not -CC mode), discard the comment.
384 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000385 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000386 // Reading macro arguments can cause macros that we are currently
387 // expanding from to be popped off the expansion stack. Doing so causes
388 // them to be reenabled for expansion. Here we record whether any
389 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000390 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000391 // C99 6.10.3.4p2.
392 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
393 if (!MI->isEnabled())
394 Tok.setFlag(Token::DisableExpand);
395 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000396 ArgTokens.push_back(Tok);
397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000399 // If this was an empty argument list foo(), don't add this as an empty
400 // argument.
401 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
402 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000403
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000404 // If this is not a variadic macro, and too many args were specified, emit
405 // an error.
406 if (!isVariadic && NumFixedArgsLeft == 0) {
407 if (ArgTokens.size() != ArgTokenStart)
408 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000410 // Emit the diagnostic at the macro name in case there is a missing ).
411 // Emitting it at the , could be far away from the macro name.
412 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
413 return 0;
414 }
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner32c13882011-04-22 23:25:09 +0000416 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000417 // other modes.
Chris Lattner32c13882011-04-22 23:25:09 +0000418 if (ArgTokens.size() == ArgTokenStart && !Features.C99 && !Features.CPlusPlus0x)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000419 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Chris Lattnera3b605e2008-03-09 03:13:06 +0000421 // Add a marker EOF token to the end of the token list for this argument.
422 Token EOFTok;
423 EOFTok.startToken();
424 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000425 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000426 EOFTok.setLength(0);
427 ArgTokens.push_back(EOFTok);
428 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000429 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000430 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000431 }
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattnera3b605e2008-03-09 03:13:06 +0000433 // Okay, we either found the r_paren. Check to see if we parsed too few
434 // arguments.
435 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattnera3b605e2008-03-09 03:13:06 +0000437 // See MacroArgs instance var for description of this.
438 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattnera3b605e2008-03-09 03:13:06 +0000440 if (NumActuals < MinArgsExpected) {
441 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000442 if (NumActuals == 0 && MinArgsExpected == 1) {
443 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner97e2de12009-04-20 21:08:10 +0000445 // If there is exactly one argument, and that argument is missing,
446 // then we have an empty "()" argument empty list. This is fine, even if
447 // the macro expects one argument (the argument is just empty).
448 isVarargsElided = MI->isVariadic();
449 } else if (MI->isVariadic() &&
450 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
451 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000452 // Varargs where the named vararg parameter is missing: ok as extension.
453 // #define A(x, ...)
454 // A("blah")
455 Diag(Tok, diag::ext_missing_varargs_arg);
456
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000457 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000458 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000459 // #define A(x, foo...) blah(a, ## foo)
460 // #define B(x, ...) blah(a, ## __VA_ARGS__)
461 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000462 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000463 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000464 } else {
465 // Otherwise, emit the error.
466 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
467 return 0;
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Chris Lattnera3b605e2008-03-09 03:13:06 +0000470 // Add a marker EOF token to the end of the token list for this argument.
471 SourceLocation EndLoc = Tok.getLocation();
472 Tok.startToken();
473 Tok.setKind(tok::eof);
474 Tok.setLocation(EndLoc);
475 Tok.setLength(0);
476 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000477
478 // If we expect two arguments, add both as empty.
479 if (NumActuals == 0 && MinArgsExpected == 2)
480 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000482 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
483 // Emit the diagnostic at the macro name in case there is a missing ).
484 // Emitting it at the , could be far away from the macro name.
485 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
486 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Jay Foadbeaaccd2009-05-21 09:52:38 +0000489 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000490 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000491}
492
493/// ComputeDATE_TIME - Compute the current time, enter it into the specified
494/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
495/// the identifier tokens inserted.
496static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
497 Preprocessor &PP) {
498 time_t TT = time(0);
499 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattnera3b605e2008-03-09 03:13:06 +0000501 static const char * const Months[] = {
502 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
503 };
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000505 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000506#ifdef LLVM_ON_WIN32
507 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
508 TM->tm_year+1900);
509#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000510 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000511 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000512#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chris Lattner47246be2009-01-26 19:29:26 +0000514 Token TmpTok;
515 TmpTok.startToken();
516 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
517 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000518
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000519#ifdef LLVM_ON_WIN32
520 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
521#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000522 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000523#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000524 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
525 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000526}
527
Chris Lattner148772a2009-06-13 07:13:28 +0000528
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000529/// HasFeature - Return true if we recognize and implement the feature
530/// specified by the identifier as a standard language feature.
Chris Lattner148772a2009-06-13 07:13:28 +0000531static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
532 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Benjamin Kramer32592e82010-01-09 18:53:11 +0000534 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000535 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000536 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000537 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000538 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000539 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000540 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000541 .Case("attribute_ns_returns_not_retained", true)
542 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000543 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000544 .Case("attribute_ns_consumed", true)
545 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000546 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000547 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000548 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000549 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000550 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000551 .Case("cxx_exceptions", LangOpts.Exceptions)
552 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000553 .Case("enumerator_attributes", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000554 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000555 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000556 .Case("ownership_holds", true)
557 .Case("ownership_returns", true)
558 .Case("ownership_takes", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000559 // C1X features
560 .Case("c_generic_selections", LangOpts.C1X)
561 .Case("c_static_assert", LangOpts.C1X)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000562 // C++0x features
Douglas Gregor7822ee32011-05-11 23:45:11 +0000563 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000564 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000565 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000566 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000567 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000568 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Sean Hunt059ce0d2011-05-01 07:04:31 +0000569 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000570 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
571 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000572 //.Case("cxx_lambdas", false)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000573 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000574 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000575 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000576 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000577 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000578 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
579 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
580 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
581 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
582 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000583 // Type traits
584 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
585 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
586 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
587 .Case("has_trivial_assign", LangOpts.CPlusPlus)
588 .Case("has_trivial_copy", LangOpts.CPlusPlus)
589 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
590 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
591 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
592 .Case("is_abstract", LangOpts.CPlusPlus)
593 .Case("is_base_of", LangOpts.CPlusPlus)
594 .Case("is_class", LangOpts.CPlusPlus)
595 .Case("is_convertible_to", LangOpts.CPlusPlus)
596 .Case("is_empty", LangOpts.CPlusPlus)
597 .Case("is_enum", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000598 .Case("is_literal", LangOpts.CPlusPlus)
Howard Hinnanta55e68b2011-05-12 19:52:14 +0000599 .Case("is_standard_layout", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000600 .Case("is_pod", LangOpts.CPlusPlus)
601 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000602 .Case("is_trivial", LangOpts.CPlusPlus)
Sean Huntfeb375d2011-05-13 00:31:07 +0000603 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000604 .Case("is_union", LangOpts.CPlusPlus)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000605 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000606 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000607}
608
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000609/// HasExtension - Return true if we recognize and implement the feature
610/// specified by the identifier, either as an extension or a standard language
611/// feature.
612static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
613 if (HasFeature(PP, II))
614 return true;
615
616 // If the use of an extension results in an error diagnostic, extensions are
617 // effectively unavailable, so just return false here.
618 if (PP.getDiagnostics().getExtensionHandlingBehavior()==Diagnostic::Ext_Error)
619 return false;
620
621 const LangOptions &LangOpts = PP.getLangOptions();
622
623 // Because we inherit the feature list from HasFeature, this string switch
624 // must be less restrictive than HasFeature's.
625 return llvm::StringSwitch<bool>(II->getName())
626 // C1X features supported by other languages as extensions.
627 .Case("c_generic_selections", true)
628 .Case("c_static_assert", true)
629 // C++0x features supported by other languages as extensions.
630 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
631 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
632 .Case("cxx_override_control", LangOpts.CPlusPlus)
633 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
634 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
635 .Default(false);
636}
637
Anders Carlssoncae50952010-10-20 02:31:43 +0000638/// HasAttribute - Return true if we recognize and implement the attribute
639/// specified by the given identifier.
640static bool HasAttribute(const IdentifierInfo *II) {
641 return llvm::StringSwitch<bool>(II->getName())
642#include "clang/Lex/AttrSpellings.inc"
643 .Default(false);
644}
645
John Thompson92bd8c72009-11-02 22:28:12 +0000646/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
647/// or '__has_include_next("path")' expression.
648/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000649static bool EvaluateHasIncludeCommon(Token &Tok,
650 IdentifierInfo *II, Preprocessor &PP,
651 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000652 SourceLocation LParenLoc;
653
654 // Get '('.
655 PP.LexNonComment(Tok);
656
657 // Ensure we have a '('.
658 if (Tok.isNot(tok::l_paren)) {
659 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
660 return false;
661 }
662
663 // Save '(' location for possible missing ')' message.
664 LParenLoc = Tok.getLocation();
665
666 // Get the file name.
667 PP.getCurrentLexer()->LexIncludeFilename(Tok);
668
669 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000670 llvm::SmallString<128> FilenameBuffer;
671 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000672 SourceLocation EndLoc;
673
John Thompson92bd8c72009-11-02 22:28:12 +0000674 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000675 case tok::eod:
676 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000677 return false;
678
679 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000680 case tok::string_literal: {
681 bool Invalid = false;
682 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
683 if (Invalid)
684 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000685 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000686 }
John Thompson92bd8c72009-11-02 22:28:12 +0000687
688 case tok::less:
689 // This could be a <foo/bar.h> file coming from a macro expansion. In this
690 // case, glue the tokens together into FilenameBuffer and interpret those.
691 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000692 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000693 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000694 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000695 break;
696 default:
697 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
698 return false;
699 }
700
Chris Lattnera1394812010-01-10 01:35:12 +0000701 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000702 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
703 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000704 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000705 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000706
707 // Search include directories.
708 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000709 const FileEntry *File =
Manuel Klimek74124942011-04-26 21:50:03 +0000710 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000711
712 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000713 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000714
715 // Get ')'.
716 PP.LexNonComment(Tok);
717
718 // Ensure we have a trailing ).
719 if (Tok.isNot(tok::r_paren)) {
720 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
721 PP.Diag(LParenLoc, diag::note_matching) << "(";
722 return false;
723 }
724
Chris Lattner3ed572e2011-01-15 06:57:04 +0000725 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000726}
727
728/// EvaluateHasInclude - Process a '__has_include("path")' expression.
729/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000730static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000731 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000732 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000733}
734
735/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
736/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000737static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000738 IdentifierInfo *II, Preprocessor &PP) {
739 // __has_include_next is like __has_include, except that we start
740 // searching after the current found directory. If we can't do this,
741 // issue a diagnostic.
742 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
743 if (PP.isInPrimaryFile()) {
744 Lookup = 0;
745 PP.Diag(Tok, diag::pp_include_next_in_primary);
746 } else if (Lookup == 0) {
747 PP.Diag(Tok, diag::pp_include_next_absolute_path);
748 } else {
749 // Start looking up in the next directory.
750 ++Lookup;
751 }
752
Chris Lattner3ed572e2011-01-15 06:57:04 +0000753 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000754}
Chris Lattner148772a2009-06-13 07:13:28 +0000755
Chris Lattnera3b605e2008-03-09 03:13:06 +0000756/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
757/// as a builtin macro, handle it and return the next token as 'Tok'.
758void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
759 // Figure out which token this is.
760 IdentifierInfo *II = Tok.getIdentifierInfo();
761 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000762
John McCall1ef8a2e2010-08-28 22:34:47 +0000763 // If this is an _Pragma or Microsoft __pragma directive, expand it,
764 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000765 if (II == Ident_Pragma)
766 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000767 else if (II == Ident__pragma) // in non-MS mode this is null
768 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattnera3b605e2008-03-09 03:13:06 +0000770 ++NumBuiltinMacroExpanded;
771
Benjamin Kramerb1765912010-01-27 16:38:22 +0000772 llvm::SmallString<128> TmpBuffer;
773 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000774
775 // Set up the return result.
776 Tok.setIdentifierInfo(0);
777 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattnera3b605e2008-03-09 03:13:06 +0000779 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000780 // C99 6.10.8: "__LINE__: The presumed line number (within the current
781 // source file) of the current source line (an integer constant)". This can
782 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000783 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Chris Lattnerdff070f2009-04-18 22:29:33 +0000785 // Advance to the location of the first _, this might not be the first byte
786 // of the token if it starts with an escaped newline.
787 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Chris Lattner081927b2009-02-15 21:06:39 +0000789 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
790 // a macro instantiation. This doesn't matter for object-like macros, but
791 // can matter for a function-like macro that expands to contain __LINE__.
792 // Skip down through instantiation points until we find a file loc for the
793 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000794 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000795 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattner1fa49532009-03-08 08:08:45 +0000797 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000798 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000799 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000800 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000801 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
802 // character string literal)". This can be affected by #line.
803 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
804
805 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
806 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000807 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000808 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000809 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000810 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000811 if (PLoc.isInvalid())
812 break;
813
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000814 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000815 }
816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Chris Lattnera3b605e2008-03-09 03:13:06 +0000818 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000819 llvm::SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000820 if (PLoc.isValid()) {
821 FN += PLoc.getFilename();
822 Lexer::Stringify(FN);
823 OS << '"' << FN.str() << '"';
824 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000825 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000826 } else if (II == Ident__DATE__) {
827 if (!DATELoc.isValid())
828 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
829 Tok.setKind(tok::string_literal);
830 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000831 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000832 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000833 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000834 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000835 } else if (II == Ident__TIME__) {
836 if (!TIMELoc.isValid())
837 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
838 Tok.setKind(tok::string_literal);
839 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000840 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000841 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000842 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000843 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000844 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000845 // Compute the presumed include depth of this token. This can be affected
846 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000847 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000849 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000850 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000851 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000852 for (; PLoc.isValid(); ++Depth)
853 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
854 }
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattner1fa49532009-03-08 08:08:45 +0000856 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000857 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000858 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000859 } else if (II == Ident__TIMESTAMP__) {
860 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
861 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000862
863 // Get the file that we are lexing out of. If we're currently lexing from
864 // a macro, dig into the include stack.
865 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000866 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Chris Lattnera3b605e2008-03-09 03:13:06 +0000868 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000869 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Chris Lattnera3b605e2008-03-09 03:13:06 +0000871 const char *Result;
872 if (CurFile) {
873 time_t TT = CurFile->getModificationTime();
874 struct tm *TM = localtime(&TT);
875 Result = asctime(TM);
876 } else {
877 Result = "??? ??? ?? ??:??:?? ????\n";
878 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000879 // Surround the string with " and strip the trailing newline.
880 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000881 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000882 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000883 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000884 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000885 Tok.setKind(tok::numeric_constant);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000886 } else if (II == Ident__has_feature ||
887 II == Ident__has_extension ||
888 II == Ident__has_builtin ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000889 II == Ident__has_attribute) {
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000890 // The argument to these builtins should be a parenthesized identifier.
Chris Lattner148772a2009-06-13 07:13:28 +0000891 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattner148772a2009-06-13 07:13:28 +0000893 bool IsValid = false;
894 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner148772a2009-06-13 07:13:28 +0000896 // Read the '('.
897 Lex(Tok);
898 if (Tok.is(tok::l_paren)) {
899 // Read the identifier
900 Lex(Tok);
901 if (Tok.is(tok::identifier)) {
902 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner148772a2009-06-13 07:13:28 +0000904 // Read the ')'.
905 Lex(Tok);
906 if (Tok.is(tok::r_paren))
907 IsValid = true;
908 }
909 }
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Chris Lattner148772a2009-06-13 07:13:28 +0000911 bool Value = false;
912 if (!IsValid)
913 Diag(StartLoc, diag::err_feature_check_malformed);
914 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000915 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000916 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +0000917 } else if (II == Ident__has_attribute)
918 Value = HasAttribute(FeatureII);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000919 else if (II == Ident__has_extension)
920 Value = HasExtension(*this, FeatureII);
Anders Carlssoncae50952010-10-20 02:31:43 +0000921 else {
Chris Lattner148772a2009-06-13 07:13:28 +0000922 assert(II == Ident__has_feature && "Must be feature check");
923 Value = HasFeature(*this, FeatureII);
924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Benjamin Kramerb1765912010-01-27 16:38:22 +0000926 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000927 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000928 } else if (II == Ident__has_include ||
929 II == Ident__has_include_next) {
930 // The argument to these two builtins should be a parenthesized
931 // file name string literal using angle brackets (<>) or
932 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +0000933 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000934 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +0000935 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +0000936 else
Chris Lattner3ed572e2011-01-15 06:57:04 +0000937 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000938 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000939 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000940 } else {
941 assert(0 && "Unknown identifier!");
942 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000943 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000944}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000945
946void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
947 // If the 'used' status changed, and the macro requires 'unused' warning,
948 // remove its SourceLocation from the warn-for-unused-macro locations.
949 if (MI->isWarnIfUnused() && !MI->isUsed())
950 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
951 MI->setIsUsed(true);
952}