blob: 32b2188af58cde5e6c6533234b229806847f112d [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");
88 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000089 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000090 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
91 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall1ef8a2e2010-08-28 22:34:47 +000092
93 // Microsoft Extensions.
94 if (Features.Microsoft)
95 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
96 else
97 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +000098}
99
100/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
101/// in its expansion, currently expands to that token literally.
102static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
103 const IdentifierInfo *MacroIdent,
104 Preprocessor &PP) {
105 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
106
107 // If the token isn't an identifier, it's always literally expanded.
108 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Chris Lattnera3b605e2008-03-09 03:13:06 +0000110 // If the identifier is a macro, and if that macro is enabled, it may be
111 // expanded so it's not a trivial expansion.
112 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
113 // Fast expanding "#define X X" is ok, because X would be disabled.
114 II != MacroIdent)
115 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattnera3b605e2008-03-09 03:13:06 +0000117 // If this is an object-like macro invocation, it is safe to trivially expand
118 // it.
119 if (MI->isObjectLike()) return true;
120
121 // If this is a function-like macro invocation, it's safe to trivially expand
122 // as long as the identifier is not a macro argument.
123 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
124 I != E; ++I)
125 if (*I == II)
126 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Chris Lattnera3b605e2008-03-09 03:13:06 +0000128 return true;
129}
130
131
132/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
133/// lexed is a '('. If so, consume the token and return true, if not, this
134/// method should have no observable side-effect on the lexed tokens.
135bool Preprocessor::isNextPPTokenLParen() {
136 // Do some quick tests for rejection cases.
137 unsigned Val;
138 if (CurLexer)
139 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000140 else if (CurPTHLexer)
141 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000142 else
143 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattnera3b605e2008-03-09 03:13:06 +0000145 if (Val == 2) {
146 // We have run off the end. If it's a source file we don't
147 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
148 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000149 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000150 return false;
151 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
152 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
153 if (Entry.TheLexer)
154 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000155 else if (Entry.ThePTHLexer)
156 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157 else
158 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattnera3b605e2008-03-09 03:13:06 +0000160 if (Val != 2)
161 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattnera3b605e2008-03-09 03:13:06 +0000163 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000164 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 return false;
166 }
167 }
168
169 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
170 // have found something that isn't a '(' or we found the end of the
171 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000172 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000173}
174
175/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
176/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000177bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000178 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000179 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Douglas Gregor13678972010-01-26 19:43:43 +0000181 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000182 // then the macro could expand to different things in other contexts, we need
183 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000184 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattnera3b605e2008-03-09 03:13:06 +0000186 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
187 if (MI->isBuiltinMacro()) {
188 ExpandBuiltinMacro(Identifier);
189 return false;
190 }
Mike 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
Chris Lattnera3b605e2008-03-09 03:13:06 +0000228 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000230 // Remember where the token is instantiated.
231 SourceLocation InstantiateLoc = Identifier.getLocation();
232
Chris Lattnera3b605e2008-03-09 03:13:06 +0000233 // If this macro expands to no tokens, don't bother to push it onto the
234 // expansion stack, only to take it right back off.
235 if (MI->getNumTokens() == 0) {
236 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000237 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattnera3b605e2008-03-09 03:13:06 +0000239 // Ignore this macro use, just return the next token in the current
240 // buffer.
241 bool HadLeadingSpace = Identifier.hasLeadingSpace();
242 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattnera3b605e2008-03-09 03:13:06 +0000244 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattnera3b605e2008-03-09 03:13:06 +0000246 // If the identifier isn't on some OTHER line, inherit the leading
247 // whitespace/first-on-a-line property of this token. This handles
248 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
249 // empty.
250 if (!Identifier.isAtStartOfLine()) {
251 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
252 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
253 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000254 Identifier.setFlag(Token::LeadingEmptyMacro);
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000255 LastEmptyMacroInstantiationLoc = InstantiateLoc;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000256 ++NumFastMacroExpanded;
257 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Chris Lattnera3b605e2008-03-09 03:13:06 +0000259 } else if (MI->getNumTokens() == 1 &&
260 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000261 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000262 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000263 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000264 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000265
266 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000267 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000268
Chris Lattnera3b605e2008-03-09 03:13:06 +0000269 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
270 // identifier to the expanded token.
271 bool isAtStartOfLine = Identifier.isAtStartOfLine();
272 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnera3b605e2008-03-09 03:13:06 +0000274 // Replace the result token.
275 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattnera3b605e2008-03-09 03:13:06 +0000277 // Restore the StartOfLine/LeadingSpace markers.
278 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
279 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000281 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000282 // locations.
283 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000284 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000285 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000286 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Chris Lattner8ff66de2010-03-26 17:49:16 +0000288 // If this is a disabled macro or #define X X, we must mark the result as
289 // unexpandable.
290 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
291 if (MacroInfo *NewMI = getMacroInfo(NewII))
292 if (!NewMI->isEnabled() || NewMI == MI)
293 Identifier.setFlag(Token::DisableExpand);
294 }
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Chris Lattnera3b605e2008-03-09 03:13:06 +0000296 // Since this is not an identifier token, it can't be macro expanded, so
297 // we're done.
298 ++NumFastMacroExpanded;
299 return false;
300 }
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Chris Lattnera3b605e2008-03-09 03:13:06 +0000302 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000303 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattnera3b605e2008-03-09 03:13:06 +0000305 // Now that the macro is at the top of the include stack, ask the
306 // preprocessor to read the next token from it.
307 Lex(Identifier);
308 return false;
309}
310
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000311/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
312/// token is the '(' of the macro, this method is invoked to read all of the
313/// actual arguments specified for the macro invocation. This returns null on
314/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000315MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000316 MacroInfo *MI,
317 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000318 // The number of fixed arguments to parse.
319 unsigned NumFixedArgsLeft = MI->getNumArgs();
320 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattnera3b605e2008-03-09 03:13:06 +0000322 // Outer loop, while there are more arguments, keep reading them.
323 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000324
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000325 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
326 // an argument value in a macro could expand to ',' or '(' or ')'.
327 LexUnexpandedToken(Tok);
328 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Chris Lattnera3b605e2008-03-09 03:13:06 +0000330 // ArgTokens - Build up a list of tokens that make up each argument. Each
331 // argument is separated by an EOF token. Use a SmallVector so we can avoid
332 // heap allocations in the common case.
333 llvm::SmallVector<Token, 64> ArgTokens;
334
335 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000336 while (Tok.isNot(tok::r_paren)) {
337 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
338 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000340 unsigned ArgTokenStart = ArgTokens.size();
341 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Chris Lattnera3b605e2008-03-09 03:13:06 +0000343 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
344 // that we already consumed the first one.
345 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Chris Lattnera3b605e2008-03-09 03:13:06 +0000347 while (1) {
348 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
349 // an argument value in a macro could expand to ',' or '(' or ')'.
350 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Douglas Gregorf29c5232010-08-24 22:20:20 +0000352 if (Tok.is(tok::code_completion)) {
353 if (CodeComplete)
354 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
355 MI, NumActuals);
356 LexUnexpandedToken(Tok);
357 }
358
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);
393 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000394 ArgTokens.push_back(Tok);
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000397 // If this was an empty argument list foo(), don't add this as an empty
398 // argument.
399 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
400 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000401
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000402 // If this is not a variadic macro, and too many args were specified, emit
403 // an error.
404 if (!isVariadic && NumFixedArgsLeft == 0) {
405 if (ArgTokens.size() != ArgTokenStart)
406 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000408 // Emit the diagnostic at the macro name in case there is a missing ).
409 // Emitting it at the , could be far away from the macro name.
410 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
411 return 0;
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner32c13882011-04-22 23:25:09 +0000414 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000415 // other modes.
Chris Lattner32c13882011-04-22 23:25:09 +0000416 if (ArgTokens.size() == ArgTokenStart && !Features.C99 && !Features.CPlusPlus0x)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000417 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattnera3b605e2008-03-09 03:13:06 +0000419 // Add a marker EOF token to the end of the token list for this argument.
420 Token EOFTok;
421 EOFTok.startToken();
422 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000423 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000424 EOFTok.setLength(0);
425 ArgTokens.push_back(EOFTok);
426 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000427 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000428 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattnera3b605e2008-03-09 03:13:06 +0000431 // Okay, we either found the r_paren. Check to see if we parsed too few
432 // arguments.
433 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattnera3b605e2008-03-09 03:13:06 +0000435 // See MacroArgs instance var for description of this.
436 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattnera3b605e2008-03-09 03:13:06 +0000438 if (NumActuals < MinArgsExpected) {
439 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000440 if (NumActuals == 0 && MinArgsExpected == 1) {
441 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Chris Lattner97e2de12009-04-20 21:08:10 +0000443 // If there is exactly one argument, and that argument is missing,
444 // then we have an empty "()" argument empty list. This is fine, even if
445 // the macro expects one argument (the argument is just empty).
446 isVarargsElided = MI->isVariadic();
447 } else if (MI->isVariadic() &&
448 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
449 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000450 // Varargs where the named vararg parameter is missing: ok as extension.
451 // #define A(x, ...)
452 // A("blah")
453 Diag(Tok, diag::ext_missing_varargs_arg);
454
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000455 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000456 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000457 // #define A(x, foo...) blah(a, ## foo)
458 // #define B(x, ...) blah(a, ## __VA_ARGS__)
459 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000460 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000461 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000462 } else {
463 // Otherwise, emit the error.
464 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
465 return 0;
466 }
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattnera3b605e2008-03-09 03:13:06 +0000468 // Add a marker EOF token to the end of the token list for this argument.
469 SourceLocation EndLoc = Tok.getLocation();
470 Tok.startToken();
471 Tok.setKind(tok::eof);
472 Tok.setLocation(EndLoc);
473 Tok.setLength(0);
474 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000475
476 // If we expect two arguments, add both as empty.
477 if (NumActuals == 0 && MinArgsExpected == 2)
478 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000480 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
481 // Emit the diagnostic at the macro name in case there is a missing ).
482 // Emitting it at the , could be far away from the macro name.
483 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
484 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Jay Foadbeaaccd2009-05-21 09:52:38 +0000487 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000488 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000489}
490
491/// ComputeDATE_TIME - Compute the current time, enter it into the specified
492/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
493/// the identifier tokens inserted.
494static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
495 Preprocessor &PP) {
496 time_t TT = time(0);
497 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattnera3b605e2008-03-09 03:13:06 +0000499 static const char * const Months[] = {
500 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
501 };
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000503 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000504#ifdef LLVM_ON_WIN32
505 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
506 TM->tm_year+1900);
507#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000508 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000509 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000510#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner47246be2009-01-26 19:29:26 +0000512 Token TmpTok;
513 TmpTok.startToken();
514 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
515 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000516
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000517#ifdef LLVM_ON_WIN32
518 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
519#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000520 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000521#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000522 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
523 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000524}
525
Chris Lattner148772a2009-06-13 07:13:28 +0000526
527/// HasFeature - Return true if we recognize and implement the specified feature
528/// specified by the identifier.
529static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
530 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Benjamin Kramer32592e82010-01-09 18:53:11 +0000532 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000533 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000534 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000535 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000536 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000537 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000538 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000539 .Case("attribute_ns_returns_not_retained", true)
540 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000541 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000542 .Case("attribute_ns_consumed", true)
543 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000544 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000545 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000546 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000547 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000548 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000549 .Case("cxx_exceptions", LangOpts.Exceptions)
550 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000551 .Case("enumerator_attributes", true)
Peter Collingbournef111d932011-04-15 00:35:48 +0000552 .Case("generic_selections", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000553 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000554 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000555 .Case("ownership_holds", true)
556 .Case("ownership_returns", true)
557 .Case("ownership_takes", true)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000558 // C++0x features
559 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000560 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000561 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000562 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000563 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
564 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000565 //.Case("cxx_lambdas", false)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000566 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000567 //.Case("cxx_nullptr", false)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000568 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000569 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000570 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000571 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
572 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
573 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
574 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
575 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000576 // Type traits
577 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
578 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
579 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
580 .Case("has_trivial_assign", LangOpts.CPlusPlus)
581 .Case("has_trivial_copy", LangOpts.CPlusPlus)
582 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
583 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
584 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
585 .Case("is_abstract", LangOpts.CPlusPlus)
586 .Case("is_base_of", LangOpts.CPlusPlus)
587 .Case("is_class", LangOpts.CPlusPlus)
588 .Case("is_convertible_to", LangOpts.CPlusPlus)
589 .Case("is_empty", LangOpts.CPlusPlus)
590 .Case("is_enum", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000591 .Case("is_literal", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000592 .Case("is_pod", LangOpts.CPlusPlus)
593 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000594 .Case("is_trivial", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000595 .Case("is_union", LangOpts.CPlusPlus)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000596 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000597 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000598}
599
Anders Carlssoncae50952010-10-20 02:31:43 +0000600/// HasAttribute - Return true if we recognize and implement the attribute
601/// specified by the given identifier.
602static bool HasAttribute(const IdentifierInfo *II) {
603 return llvm::StringSwitch<bool>(II->getName())
604#include "clang/Lex/AttrSpellings.inc"
605 .Default(false);
606}
607
John Thompson92bd8c72009-11-02 22:28:12 +0000608/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
609/// or '__has_include_next("path")' expression.
610/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000611static bool EvaluateHasIncludeCommon(Token &Tok,
612 IdentifierInfo *II, Preprocessor &PP,
613 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000614 SourceLocation LParenLoc;
615
616 // Get '('.
617 PP.LexNonComment(Tok);
618
619 // Ensure we have a '('.
620 if (Tok.isNot(tok::l_paren)) {
621 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
622 return false;
623 }
624
625 // Save '(' location for possible missing ')' message.
626 LParenLoc = Tok.getLocation();
627
628 // Get the file name.
629 PP.getCurrentLexer()->LexIncludeFilename(Tok);
630
631 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000632 llvm::SmallString<128> FilenameBuffer;
633 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000634 SourceLocation EndLoc;
635
John Thompson92bd8c72009-11-02 22:28:12 +0000636 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000637 case tok::eod:
638 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000639 return false;
640
641 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000642 case tok::string_literal: {
643 bool Invalid = false;
644 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
645 if (Invalid)
646 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000647 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000648 }
John Thompson92bd8c72009-11-02 22:28:12 +0000649
650 case tok::less:
651 // This could be a <foo/bar.h> file coming from a macro expansion. In this
652 // case, glue the tokens together into FilenameBuffer and interpret those.
653 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000654 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000655 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000656 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000657 break;
658 default:
659 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
660 return false;
661 }
662
Chris Lattnera1394812010-01-10 01:35:12 +0000663 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000664 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
665 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000666 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000667 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000668
669 // Search include directories.
670 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000671 const FileEntry *File =
Manuel Klimek74124942011-04-26 21:50:03 +0000672 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000673
674 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000675 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000676
677 // Get ')'.
678 PP.LexNonComment(Tok);
679
680 // Ensure we have a trailing ).
681 if (Tok.isNot(tok::r_paren)) {
682 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
683 PP.Diag(LParenLoc, diag::note_matching) << "(";
684 return false;
685 }
686
Chris Lattner3ed572e2011-01-15 06:57:04 +0000687 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000688}
689
690/// EvaluateHasInclude - Process a '__has_include("path")' expression.
691/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000692static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000693 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000694 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000695}
696
697/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
698/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000699static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000700 IdentifierInfo *II, Preprocessor &PP) {
701 // __has_include_next is like __has_include, except that we start
702 // searching after the current found directory. If we can't do this,
703 // issue a diagnostic.
704 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
705 if (PP.isInPrimaryFile()) {
706 Lookup = 0;
707 PP.Diag(Tok, diag::pp_include_next_in_primary);
708 } else if (Lookup == 0) {
709 PP.Diag(Tok, diag::pp_include_next_absolute_path);
710 } else {
711 // Start looking up in the next directory.
712 ++Lookup;
713 }
714
Chris Lattner3ed572e2011-01-15 06:57:04 +0000715 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000716}
Chris Lattner148772a2009-06-13 07:13:28 +0000717
Chris Lattnera3b605e2008-03-09 03:13:06 +0000718/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
719/// as a builtin macro, handle it and return the next token as 'Tok'.
720void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
721 // Figure out which token this is.
722 IdentifierInfo *II = Tok.getIdentifierInfo();
723 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000724
John McCall1ef8a2e2010-08-28 22:34:47 +0000725 // If this is an _Pragma or Microsoft __pragma directive, expand it,
726 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000727 if (II == Ident_Pragma)
728 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000729 else if (II == Ident__pragma) // in non-MS mode this is null
730 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnera3b605e2008-03-09 03:13:06 +0000732 ++NumBuiltinMacroExpanded;
733
Benjamin Kramerb1765912010-01-27 16:38:22 +0000734 llvm::SmallString<128> TmpBuffer;
735 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000736
737 // Set up the return result.
738 Tok.setIdentifierInfo(0);
739 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattnera3b605e2008-03-09 03:13:06 +0000741 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000742 // C99 6.10.8: "__LINE__: The presumed line number (within the current
743 // source file) of the current source line (an integer constant)". This can
744 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000745 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattnerdff070f2009-04-18 22:29:33 +0000747 // Advance to the location of the first _, this might not be the first byte
748 // of the token if it starts with an escaped newline.
749 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Chris Lattner081927b2009-02-15 21:06:39 +0000751 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
752 // a macro instantiation. This doesn't matter for object-like macros, but
753 // can matter for a function-like macro that expands to contain __LINE__.
754 // Skip down through instantiation points until we find a file loc for the
755 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000756 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000757 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattner1fa49532009-03-08 08:08:45 +0000759 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000760 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000761 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000762 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000763 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
764 // character string literal)". This can be affected by #line.
765 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
766
767 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
768 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000769 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000770 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000771 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000772 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000773 if (PLoc.isInvalid())
774 break;
775
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000776 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000777 }
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattnera3b605e2008-03-09 03:13:06 +0000780 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000781 llvm::SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000782 if (PLoc.isValid()) {
783 FN += PLoc.getFilename();
784 Lexer::Stringify(FN);
785 OS << '"' << FN.str() << '"';
786 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000787 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000788 } else if (II == Ident__DATE__) {
789 if (!DATELoc.isValid())
790 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
791 Tok.setKind(tok::string_literal);
792 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000793 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000794 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000795 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000796 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000797 } else if (II == Ident__TIME__) {
798 if (!TIMELoc.isValid())
799 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
800 Tok.setKind(tok::string_literal);
801 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000802 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000803 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000804 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000805 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000806 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000807 // Compute the presumed include depth of this token. This can be affected
808 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000809 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000811 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000812 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000813 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000814 for (; PLoc.isValid(); ++Depth)
815 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Chris Lattner1fa49532009-03-08 08:08:45 +0000818 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000819 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000820 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000821 } else if (II == Ident__TIMESTAMP__) {
822 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
823 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000824
825 // Get the file that we are lexing out of. If we're currently lexing from
826 // a macro, dig into the include stack.
827 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000828 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattnera3b605e2008-03-09 03:13:06 +0000830 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000831 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Chris Lattnera3b605e2008-03-09 03:13:06 +0000833 const char *Result;
834 if (CurFile) {
835 time_t TT = CurFile->getModificationTime();
836 struct tm *TM = localtime(&TT);
837 Result = asctime(TM);
838 } else {
839 Result = "??? ??? ?? ??:??:?? ????\n";
840 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000841 // Surround the string with " and strip the trailing newline.
842 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000843 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000844 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000845 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000846 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000847 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000848 } else if (II == Ident__has_feature ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000849 II == Ident__has_builtin ||
850 II == Ident__has_attribute) {
Chris Lattner148772a2009-06-13 07:13:28 +0000851 // The argument to these two builtins should be a parenthesized identifier.
852 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattner148772a2009-06-13 07:13:28 +0000854 bool IsValid = false;
855 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Chris Lattner148772a2009-06-13 07:13:28 +0000857 // Read the '('.
858 Lex(Tok);
859 if (Tok.is(tok::l_paren)) {
860 // Read the identifier
861 Lex(Tok);
862 if (Tok.is(tok::identifier)) {
863 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Chris Lattner148772a2009-06-13 07:13:28 +0000865 // Read the ')'.
866 Lex(Tok);
867 if (Tok.is(tok::r_paren))
868 IsValid = true;
869 }
870 }
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Chris Lattner148772a2009-06-13 07:13:28 +0000872 bool Value = false;
873 if (!IsValid)
874 Diag(StartLoc, diag::err_feature_check_malformed);
875 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000876 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000877 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +0000878 } else if (II == Ident__has_attribute)
879 Value = HasAttribute(FeatureII);
880 else {
Chris Lattner148772a2009-06-13 07:13:28 +0000881 assert(II == Ident__has_feature && "Must be feature check");
882 Value = HasFeature(*this, FeatureII);
883 }
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Benjamin Kramerb1765912010-01-27 16:38:22 +0000885 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000886 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000887 } else if (II == Ident__has_include ||
888 II == Ident__has_include_next) {
889 // The argument to these two builtins should be a parenthesized
890 // file name string literal using angle brackets (<>) or
891 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +0000892 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000893 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +0000894 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +0000895 else
Chris Lattner3ed572e2011-01-15 06:57:04 +0000896 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000897 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000898 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000899 } else {
900 assert(0 && "Unknown identifier!");
901 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000902 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000903}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000904
905void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
906 // If the 'used' status changed, and the macro requires 'unused' warning,
907 // remove its SourceLocation from the warn-for-unused-macro locations.
908 if (MI->isWarnIfUnused() && !MI->isUsed())
909 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
910 MI->setIsUsed(true);
911}