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