blob: 712918b7c3b201dd2281a847573d1671837a1f88 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/Lex/LexDiagnostic.h"
Chris Lattner3daed522009-03-02 22:20:04 +000021#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000022#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000023using namespace clang;
24
25/// setMacroInfo - Specify a macro for this identifier.
26///
27void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
28 if (MI == 0) {
29 if (II->hasMacroDefinition()) {
30 Macros.erase(II);
31 II->setHasMacroDefinition(false);
32 }
33 } else {
34 Macros[II] = MI;
35 II->setHasMacroDefinition(true);
36 }
37}
38
39/// RegisterBuiltinMacro - Register the specified identifier in the identifier
40/// table and mark it as a builtin macro to be expanded.
41IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
42 // Get the identifier.
43 IdentifierInfo *Id = getIdentifierInfo(Name);
44
45 // Mark it as being a macro that is builtin.
Ted Kremenek0ea76722008-12-15 19:56:42 +000046 MacroInfo *MI = AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000047 MI->setIsBuiltinMacro();
48 setMacroInfo(Id, MI);
49 return Id;
50}
51
52
53/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
54/// identifier table.
55void Preprocessor::RegisterBuiltinMacros() {
56 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
57 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
58 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
59 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
60 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
61
62 // GCC Extensions.
63 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
64 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
65 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
66}
67
68/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
69/// in its expansion, currently expands to that token literally.
70static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
71 const IdentifierInfo *MacroIdent,
72 Preprocessor &PP) {
73 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
74
75 // If the token isn't an identifier, it's always literally expanded.
76 if (II == 0) return true;
77
78 // If the identifier is a macro, and if that macro is enabled, it may be
79 // expanded so it's not a trivial expansion.
80 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
81 // Fast expanding "#define X X" is ok, because X would be disabled.
82 II != MacroIdent)
83 return false;
84
85 // If this is an object-like macro invocation, it is safe to trivially expand
86 // it.
87 if (MI->isObjectLike()) return true;
88
89 // If this is a function-like macro invocation, it's safe to trivially expand
90 // as long as the identifier is not a macro argument.
91 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
92 I != E; ++I)
93 if (*I == II)
94 return false; // Identifier is a macro argument.
95
96 return true;
97}
98
99
100/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
101/// lexed is a '('. If so, consume the token and return true, if not, this
102/// method should have no observable side-effect on the lexed tokens.
103bool Preprocessor::isNextPPTokenLParen() {
104 // Do some quick tests for rejection cases.
105 unsigned Val;
106 if (CurLexer)
107 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000108 else if (CurPTHLexer)
109 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000110 else
111 Val = CurTokenLexer->isNextTokenLParen();
112
113 if (Val == 2) {
114 // We have run off the end. If it's a source file we don't
115 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
116 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000117 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000118 return false;
119 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
120 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
121 if (Entry.TheLexer)
122 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000123 else if (Entry.ThePTHLexer)
124 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000125 else
126 Val = Entry.TheTokenLexer->isNextTokenLParen();
127
128 if (Val != 2)
129 break;
130
131 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000132 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000133 return false;
134 }
135 }
136
137 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
138 // have found something that isn't a '(' or we found the end of the
139 // translation unit. In either case, return false.
140 if (Val != 1)
141 return false;
142
143 Token Tok;
144 LexUnexpandedToken(Tok);
145 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
146 return true;
147}
148
149/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
150/// expanded as a macro, handle it and return the next token as 'Identifier'.
151bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
152 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000153 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
154
Chris Lattnera3b605e2008-03-09 03:13:06 +0000155 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
156 // then the macro could expand to different things in other contexts, we need
157 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000158 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000159
160 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
161 if (MI->isBuiltinMacro()) {
162 ExpandBuiltinMacro(Identifier);
163 return false;
164 }
165
166 /// Args - If this is a function-like macro expansion, this contains,
167 /// for each macro argument, the list of tokens that were provided to the
168 /// invocation.
169 MacroArgs *Args = 0;
170
Chris Lattnere7fb4842009-02-15 20:52:18 +0000171 // Remember where the end of the instantiation occurred. For an object-like
172 // macro, this is the identifier. For a function-like macro, this is the ')'.
173 SourceLocation InstantiationEnd = Identifier.getLocation();
174
Chris Lattnera3b605e2008-03-09 03:13:06 +0000175 // If this is a function-like macro, read the arguments.
176 if (MI->isFunctionLike()) {
177 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
178 // name isn't a '(', this macro should not be expanded. Otherwise, consume
179 // it.
180 if (!isNextPPTokenLParen())
181 return true;
182
183 // Remember that we are now parsing the arguments to a macro invocation.
184 // Preprocessor directives used inside macro arguments are not portable, and
185 // this enables the warning.
186 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000187 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000188
189 // Finished parsing args.
190 InMacroArgs = false;
191
192 // If there was an error parsing the arguments, bail out.
193 if (Args == 0) return false;
194
195 ++NumFnMacroExpanded;
196 } else {
197 ++NumMacroExpanded;
198 }
199
200 // Notice that this macro has been used.
201 MI->setIsUsed(true);
202
203 // If we started lexing a macro, enter the macro expansion body.
204
205 // If this macro expands to no tokens, don't bother to push it onto the
206 // expansion stack, only to take it right back off.
207 if (MI->getNumTokens() == 0) {
208 // No need for arg info.
209 if (Args) Args->destroy();
210
211 // Ignore this macro use, just return the next token in the current
212 // buffer.
213 bool HadLeadingSpace = Identifier.hasLeadingSpace();
214 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
215
216 Lex(Identifier);
217
218 // If the identifier isn't on some OTHER line, inherit the leading
219 // whitespace/first-on-a-line property of this token. This handles
220 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
221 // empty.
222 if (!Identifier.isAtStartOfLine()) {
223 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
224 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
225 }
226 ++NumFastMacroExpanded;
227 return false;
228
229 } else if (MI->getNumTokens() == 1 &&
230 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000231 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000232 // Otherwise, if this macro expands into a single trivially-expanded
233 // token: expand it now. This handles common cases like
234 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000235
236 // No need for arg info.
237 if (Args) Args->destroy();
238
Chris Lattnera3b605e2008-03-09 03:13:06 +0000239 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
240 // identifier to the expanded token.
241 bool isAtStartOfLine = Identifier.isAtStartOfLine();
242 bool hasLeadingSpace = Identifier.hasLeadingSpace();
243
244 // Remember where the token is instantiated.
245 SourceLocation InstantiateLoc = Identifier.getLocation();
246
247 // Replace the result token.
248 Identifier = MI->getReplacementToken(0);
249
250 // Restore the StartOfLine/LeadingSpace markers.
251 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
252 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
253
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000254 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000255 // locations.
256 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000257 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000258 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000259 Identifier.setLocation(Loc);
260
261 // If this is #define X X, we must mark the result as unexpandible.
262 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
263 if (getMacroInfo(NewII) == MI)
264 Identifier.setFlag(Token::DisableExpand);
265
266 // Since this is not an identifier token, it can't be macro expanded, so
267 // we're done.
268 ++NumFastMacroExpanded;
269 return false;
270 }
271
272 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000273 EnterMacro(Identifier, InstantiationEnd, Args);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000274
275 // Now that the macro is at the top of the include stack, ask the
276 // preprocessor to read the next token from it.
277 Lex(Identifier);
278 return false;
279}
280
281/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
282/// invoked to read all of the actual arguments specified for the macro
283/// invocation. This returns null on error.
284MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000285 MacroInfo *MI,
286 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000287 // The number of fixed arguments to parse.
288 unsigned NumFixedArgsLeft = MI->getNumArgs();
289 bool isVariadic = MI->isVariadic();
290
291 // Outer loop, while there are more arguments, keep reading them.
292 Token Tok;
293 Tok.setKind(tok::comma);
294 --NumFixedArgsLeft; // Start reading the first arg.
295
296 // ArgTokens - Build up a list of tokens that make up each argument. Each
297 // argument is separated by an EOF token. Use a SmallVector so we can avoid
298 // heap allocations in the common case.
299 llvm::SmallVector<Token, 64> ArgTokens;
300
301 unsigned NumActuals = 0;
302 while (Tok.is(tok::comma)) {
303 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
304 // that we already consumed the first one.
305 unsigned NumParens = 0;
306
307 while (1) {
308 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
309 // an argument value in a macro could expand to ',' or '(' or ')'.
310 LexUnexpandedToken(Tok);
311
312 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
313 Diag(MacroName, diag::err_unterm_macro_invoc);
314 // Do not lose the EOF/EOM. Return it to the client.
315 MacroName = Tok;
316 return 0;
317 } else if (Tok.is(tok::r_paren)) {
318 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000319 if (NumParens-- == 0) {
320 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000322 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000323 } else if (Tok.is(tok::l_paren)) {
324 ++NumParens;
325 } else if (Tok.is(tok::comma) && NumParens == 0) {
326 // Comma ends this argument if there are more fixed arguments expected.
327 if (NumFixedArgsLeft)
328 break;
329
330 // If this is not a variadic macro, too many args were specified.
331 if (!isVariadic) {
332 // Emit the diagnostic at the macro name in case there is a missing ).
333 // Emitting it at the , could be far away from the macro name.
334 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
335 return 0;
336 }
337 // Otherwise, continue to add the tokens to this variable argument.
338 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
339 // If this is a comment token in the argument list and we're just in
340 // -C mode (not -CC mode), discard the comment.
341 continue;
342 } else if (Tok.is(tok::identifier)) {
343 // Reading macro arguments can cause macros that we are currently
344 // expanding from to be popped off the expansion stack. Doing so causes
345 // them to be reenabled for expansion. Here we record whether any
346 // identifiers we lex as macro arguments correspond to disabled macros.
347 // If so, we mark the token as noexpand. This is a subtle aspect of
348 // C99 6.10.3.4p2.
349 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
350 if (!MI->isEnabled())
351 Tok.setFlag(Token::DisableExpand);
352 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000353 ArgTokens.push_back(Tok);
354 }
355
356 // Empty arguments are standard in C99 and supported as an extension in
357 // other modes.
358 if (ArgTokens.empty() && !Features.C99)
359 Diag(Tok, diag::ext_empty_fnmacro_arg);
360
361 // Add a marker EOF token to the end of the token list for this argument.
362 Token EOFTok;
363 EOFTok.startToken();
364 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000365 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000366 EOFTok.setLength(0);
367 ArgTokens.push_back(EOFTok);
368 ++NumActuals;
369 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000370 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000371
372 // Okay, we either found the r_paren. Check to see if we parsed too few
373 // arguments.
374 unsigned MinArgsExpected = MI->getNumArgs();
375
376 // See MacroArgs instance var for description of this.
377 bool isVarargsElided = false;
378
379 if (NumActuals < MinArgsExpected) {
380 // There are several cases where too few arguments is ok, handle them now.
381 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
382 // Varargs where the named vararg parameter is missing: ok as extension.
383 // #define A(x, ...)
384 // A("blah")
385 Diag(Tok, diag::ext_missing_varargs_arg);
386
Chris Lattner63bc0352008-05-08 05:10:33 +0000387 // Remember this occurred if this is a macro invocation with at least
388 // one actual argument. This allows us to elide the comma when used for
389 // cases like:
390 // #define A(x, foo...) blah(a, ## foo)
391 // #define A(x, ...) blah(a, ## __VA_ARGS__)
392 isVarargsElided = MI->getNumArgs() > 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000393 } else if (MI->getNumArgs() == 1) {
394 // #define A(x)
395 // A()
396 // is ok because it is an empty argument.
397
398 // Empty arguments are standard in C99 and supported as an extension in
399 // other modes.
400 if (ArgTokens.empty() && !Features.C99)
401 Diag(Tok, diag::ext_empty_fnmacro_arg);
402 } else {
403 // Otherwise, emit the error.
404 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
405 return 0;
406 }
407
408 // Add a marker EOF token to the end of the token list for this argument.
409 SourceLocation EndLoc = Tok.getLocation();
410 Tok.startToken();
411 Tok.setKind(tok::eof);
412 Tok.setLocation(EndLoc);
413 Tok.setLength(0);
414 ArgTokens.push_back(Tok);
415 }
416
417 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
418}
419
420/// ComputeDATE_TIME - Compute the current time, enter it into the specified
421/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
422/// the identifier tokens inserted.
423static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
424 Preprocessor &PP) {
425 time_t TT = time(0);
426 struct tm *TM = localtime(&TT);
427
428 static const char * const Months[] = {
429 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
430 };
431
432 char TmpBuffer[100];
433 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
434 TM->tm_year+1900);
Chris Lattner47246be2009-01-26 19:29:26 +0000435
436 Token TmpTok;
437 TmpTok.startToken();
438 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
439 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000440
441 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner47246be2009-01-26 19:29:26 +0000442 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
443 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000444}
445
446/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
447/// as a builtin macro, handle it and return the next token as 'Tok'.
448void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
449 // Figure out which token this is.
450 IdentifierInfo *II = Tok.getIdentifierInfo();
451 assert(II && "Can't be a macro without id info!");
452
453 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
454 // lex the token after it.
455 if (II == Ident_Pragma)
456 return Handle_Pragma(Tok);
457
458 ++NumBuiltinMacroExpanded;
459
460 char TmpBuffer[100];
461
462 // Set up the return result.
463 Tok.setIdentifierInfo(0);
464 Tok.clearFlag(Token::NeedsCleaning);
465
466 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000467 // C99 6.10.8: "__LINE__: The presumed line number (within the current
468 // source file) of the current source line (an integer constant)". This can
469 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000470 SourceLocation Loc = Tok.getLocation();
471
472 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
473 // a macro instantiation. This doesn't matter for object-like macros, but
474 // can matter for a function-like macro that expands to contain __LINE__.
475 // Skip down through instantiation points until we find a file loc for the
476 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000477 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000478 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000479
Chris Lattner1fa49532009-03-08 08:08:45 +0000480 // __LINE__ expands to a simple numeric value.
481 sprintf(TmpBuffer, "%u", PLoc.getLine());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000482 Tok.setKind(tok::numeric_constant);
Chris Lattner1fa49532009-03-08 08:08:45 +0000483 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000484 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000485 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
486 // character string literal)". This can be affected by #line.
487 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
488
489 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
490 // #include stack instead of the current file.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000491 if (II == Ident__BASE_FILE__) {
492 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000493 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000494 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000495 PLoc = SourceMgr.getPresumedLoc(NextLoc);
496 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000497 }
498 }
499
500 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000501 std::string FN = PLoc.getFilename();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000502 FN = '"' + Lexer::Stringify(FN) + '"';
503 Tok.setKind(tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000504 CreateString(&FN[0], FN.size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000505 } else if (II == Ident__DATE__) {
506 if (!DATELoc.isValid())
507 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
508 Tok.setKind(tok::string_literal);
509 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000510 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000511 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000512 Tok.getLength()));
Chris Lattnera3b605e2008-03-09 03:13:06 +0000513 } else if (II == Ident__TIME__) {
514 if (!TIMELoc.isValid())
515 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
516 Tok.setKind(tok::string_literal);
517 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000518 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000519 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000520 Tok.getLength()));
Chris Lattnera3b605e2008-03-09 03:13:06 +0000521 } else if (II == Ident__INCLUDE_LEVEL__) {
522 Diag(Tok, diag::ext_pp_include_level);
523
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000524 // Compute the presumed include depth of this token. This can be affected
525 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000526 unsigned Depth = 0;
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000527
528 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
529 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
530 for (; PLoc.isValid(); ++Depth)
531 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000532
Chris Lattner1fa49532009-03-08 08:08:45 +0000533 // __INCLUDE_LEVEL__ expands to a simple numeric value.
534 sprintf(TmpBuffer, "%u", Depth);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000535 Tok.setKind(tok::numeric_constant);
Chris Lattner1fa49532009-03-08 08:08:45 +0000536 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000537 } else if (II == Ident__TIMESTAMP__) {
538 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
539 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
540 Diag(Tok, diag::ext_pp_timestamp);
541
542 // Get the file that we are lexing out of. If we're currently lexing from
543 // a macro, dig into the include stack.
544 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000545 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000546
547 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000548 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000549
550 // If this file is older than the file it depends on, emit a diagnostic.
551 const char *Result;
552 if (CurFile) {
553 time_t TT = CurFile->getModificationTime();
554 struct tm *TM = localtime(&TT);
555 Result = asctime(TM);
556 } else {
557 Result = "??? ??? ?? ??:??:?? ????\n";
558 }
559 TmpBuffer[0] = '"';
560 strcpy(TmpBuffer+1, Result);
561 unsigned Len = strlen(TmpBuffer);
Chris Lattner1fa49532009-03-08 08:08:45 +0000562 TmpBuffer[Len] = '"'; // Replace the newline with a quote.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000563 Tok.setKind(tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000564 CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000565 } else {
566 assert(0 && "Unknown identifier!");
567 }
568}