blob: 84056c3f4b5b384cbe783651bb18522d2e7af4fd [file] [log] [blame]
Chris Lattnerc7a39682008-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 Lattner545f39e2009-01-29 05:15:15 +000020#include "clang/Lex/LexDiagnostic.h"
Chris Lattner7d6220c2009-03-02 22:20:04 +000021#include <cstdio>
Chris Lattner54fd1812008-03-18 05:59:11 +000022#include <ctime>
Chris Lattnerc7a39682008-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 Kremenek5f9fb3f2008-12-15 19:56:42 +000046 MacroInfo *MI = AllocateMacroInfo(SourceLocation());
Chris Lattnerc7a39682008-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 Kremenek3acf6702008-11-19 22:43:49 +0000108 else if (CurPTHLexer)
109 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnerc7a39682008-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 Kremenekb53b1f42008-11-19 22:21:33 +0000117 if (CurPPLexer)
Chris Lattnerc7a39682008-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 Kremenekdc640532008-11-20 16:46:54 +0000123 else if (Entry.ThePTHLexer)
124 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnerc7a39682008-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 Kremenekdc640532008-11-20 16:46:54 +0000132 if (Entry.ThePPLexer)
Chris Lattnerc7a39682008-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) {
153 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
154 // then the macro could expand to different things in other contexts, we need
155 // to disable the optimization in this case.
Ted Kremenek31dd0262008-11-18 01:12:54 +0000156 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000157
158 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
159 if (MI->isBuiltinMacro()) {
160 ExpandBuiltinMacro(Identifier);
161 return false;
162 }
163
164 /// Args - If this is a function-like macro expansion, this contains,
165 /// for each macro argument, the list of tokens that were provided to the
166 /// invocation.
167 MacroArgs *Args = 0;
168
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000169 // Remember where the end of the instantiation occurred. For an object-like
170 // macro, this is the identifier. For a function-like macro, this is the ')'.
171 SourceLocation InstantiationEnd = Identifier.getLocation();
172
Chris Lattnerc7a39682008-03-09 03:13:06 +0000173 // If this is a function-like macro, read the arguments.
174 if (MI->isFunctionLike()) {
175 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
176 // name isn't a '(', this macro should not be expanded. Otherwise, consume
177 // it.
178 if (!isNextPPTokenLParen())
179 return true;
180
181 // Remember that we are now parsing the arguments to a macro invocation.
182 // Preprocessor directives used inside macro arguments are not portable, and
183 // this enables the warning.
184 InMacroArgs = true;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000185 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000186
187 // Finished parsing args.
188 InMacroArgs = false;
189
190 // If there was an error parsing the arguments, bail out.
191 if (Args == 0) return false;
192
193 ++NumFnMacroExpanded;
194 } else {
195 ++NumMacroExpanded;
196 }
197
198 // Notice that this macro has been used.
199 MI->setIsUsed(true);
200
201 // If we started lexing a macro, enter the macro expansion body.
202
203 // If this macro expands to no tokens, don't bother to push it onto the
204 // expansion stack, only to take it right back off.
205 if (MI->getNumTokens() == 0) {
206 // No need for arg info.
207 if (Args) Args->destroy();
208
209 // Ignore this macro use, just return the next token in the current
210 // buffer.
211 bool HadLeadingSpace = Identifier.hasLeadingSpace();
212 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
213
214 Lex(Identifier);
215
216 // If the identifier isn't on some OTHER line, inherit the leading
217 // whitespace/first-on-a-line property of this token. This handles
218 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
219 // empty.
220 if (!Identifier.isAtStartOfLine()) {
221 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
222 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
223 }
224 ++NumFastMacroExpanded;
225 return false;
226
227 } else if (MI->getNumTokens() == 1 &&
228 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000229 *this)) {
Chris Lattnerc7a39682008-03-09 03:13:06 +0000230 // Otherwise, if this macro expands into a single trivially-expanded
231 // token: expand it now. This handles common cases like
232 // "#define VAL 42".
Sam Bishopa7fa72f2008-03-21 07:13:02 +0000233
234 // No need for arg info.
235 if (Args) Args->destroy();
236
Chris Lattnerc7a39682008-03-09 03:13:06 +0000237 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
238 // identifier to the expanded token.
239 bool isAtStartOfLine = Identifier.isAtStartOfLine();
240 bool hasLeadingSpace = Identifier.hasLeadingSpace();
241
242 // Remember where the token is instantiated.
243 SourceLocation InstantiateLoc = Identifier.getLocation();
244
245 // Replace the result token.
246 Identifier = MI->getReplacementToken(0);
247
248 // Restore the StartOfLine/LeadingSpace markers.
249 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
250 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
251
Chris Lattner18c8dc02009-01-16 07:36:28 +0000252 // Update the tokens location to include both its instantiation and physical
Chris Lattnerc7a39682008-03-09 03:13:06 +0000253 // locations.
254 SourceLocation Loc =
Chris Lattner27c0ced2009-01-26 00:43:02 +0000255 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000256 InstantiationEnd,Identifier.getLength());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000257 Identifier.setLocation(Loc);
258
259 // If this is #define X X, we must mark the result as unexpandible.
260 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
261 if (getMacroInfo(NewII) == MI)
262 Identifier.setFlag(Token::DisableExpand);
263
264 // Since this is not an identifier token, it can't be macro expanded, so
265 // we're done.
266 ++NumFastMacroExpanded;
267 return false;
268 }
269
270 // Start expanding the macro.
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000271 EnterMacro(Identifier, InstantiationEnd, Args);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000272
273 // Now that the macro is at the top of the include stack, ask the
274 // preprocessor to read the next token from it.
275 Lex(Identifier);
276 return false;
277}
278
279/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
280/// invoked to read all of the actual arguments specified for the macro
281/// invocation. This returns null on error.
282MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000283 MacroInfo *MI,
284 SourceLocation &MacroEnd) {
Chris Lattnerc7a39682008-03-09 03:13:06 +0000285 // The number of fixed arguments to parse.
286 unsigned NumFixedArgsLeft = MI->getNumArgs();
287 bool isVariadic = MI->isVariadic();
288
289 // Outer loop, while there are more arguments, keep reading them.
290 Token Tok;
291 Tok.setKind(tok::comma);
292 --NumFixedArgsLeft; // Start reading the first arg.
293
294 // ArgTokens - Build up a list of tokens that make up each argument. Each
295 // argument is separated by an EOF token. Use a SmallVector so we can avoid
296 // heap allocations in the common case.
297 llvm::SmallVector<Token, 64> ArgTokens;
298
299 unsigned NumActuals = 0;
300 while (Tok.is(tok::comma)) {
301 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
302 // that we already consumed the first one.
303 unsigned NumParens = 0;
304
305 while (1) {
306 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
307 // an argument value in a macro could expand to ',' or '(' or ')'.
308 LexUnexpandedToken(Tok);
309
310 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
311 Diag(MacroName, diag::err_unterm_macro_invoc);
312 // Do not lose the EOF/EOM. Return it to the client.
313 MacroName = Tok;
314 return 0;
315 } else if (Tok.is(tok::r_paren)) {
316 // If we found the ) token, the macro arg list is done.
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000317 if (NumParens-- == 0) {
318 MacroEnd = Tok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000319 break;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000320 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000321 } else if (Tok.is(tok::l_paren)) {
322 ++NumParens;
323 } else if (Tok.is(tok::comma) && NumParens == 0) {
324 // Comma ends this argument if there are more fixed arguments expected.
325 if (NumFixedArgsLeft)
326 break;
327
328 // If this is not a variadic macro, too many args were specified.
329 if (!isVariadic) {
330 // Emit the diagnostic at the macro name in case there is a missing ).
331 // Emitting it at the , could be far away from the macro name.
332 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
333 return 0;
334 }
335 // Otherwise, continue to add the tokens to this variable argument.
336 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
337 // If this is a comment token in the argument list and we're just in
338 // -C mode (not -CC mode), discard the comment.
339 continue;
340 } else if (Tok.is(tok::identifier)) {
341 // Reading macro arguments can cause macros that we are currently
342 // expanding from to be popped off the expansion stack. Doing so causes
343 // them to be reenabled for expansion. Here we record whether any
344 // identifiers we lex as macro arguments correspond to disabled macros.
345 // If so, we mark the token as noexpand. This is a subtle aspect of
346 // C99 6.10.3.4p2.
347 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
348 if (!MI->isEnabled())
349 Tok.setFlag(Token::DisableExpand);
350 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000351 ArgTokens.push_back(Tok);
352 }
353
354 // Empty arguments are standard in C99 and supported as an extension in
355 // other modes.
356 if (ArgTokens.empty() && !Features.C99)
357 Diag(Tok, diag::ext_empty_fnmacro_arg);
358
359 // Add a marker EOF token to the end of the token list for this argument.
360 Token EOFTok;
361 EOFTok.startToken();
362 EOFTok.setKind(tok::eof);
Chris Lattner5ccf92d2009-01-26 20:24:53 +0000363 EOFTok.setLocation(Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000364 EOFTok.setLength(0);
365 ArgTokens.push_back(EOFTok);
366 ++NumActuals;
367 --NumFixedArgsLeft;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000368 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000369
370 // Okay, we either found the r_paren. Check to see if we parsed too few
371 // arguments.
372 unsigned MinArgsExpected = MI->getNumArgs();
373
374 // See MacroArgs instance var for description of this.
375 bool isVarargsElided = false;
376
377 if (NumActuals < MinArgsExpected) {
378 // There are several cases where too few arguments is ok, handle them now.
379 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
380 // Varargs where the named vararg parameter is missing: ok as extension.
381 // #define A(x, ...)
382 // A("blah")
383 Diag(Tok, diag::ext_missing_varargs_arg);
384
Chris Lattnerdd2e5312008-05-08 05:10:33 +0000385 // Remember this occurred if this is a macro invocation with at least
386 // one actual argument. This allows us to elide the comma when used for
387 // cases like:
388 // #define A(x, foo...) blah(a, ## foo)
389 // #define A(x, ...) blah(a, ## __VA_ARGS__)
390 isVarargsElided = MI->getNumArgs() > 1;
Chris Lattnerc7a39682008-03-09 03:13:06 +0000391 } else if (MI->getNumArgs() == 1) {
392 // #define A(x)
393 // A()
394 // is ok because it is an empty argument.
395
396 // Empty arguments are standard in C99 and supported as an extension in
397 // other modes.
398 if (ArgTokens.empty() && !Features.C99)
399 Diag(Tok, diag::ext_empty_fnmacro_arg);
400 } else {
401 // Otherwise, emit the error.
402 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
403 return 0;
404 }
405
406 // Add a marker EOF token to the end of the token list for this argument.
407 SourceLocation EndLoc = Tok.getLocation();
408 Tok.startToken();
409 Tok.setKind(tok::eof);
410 Tok.setLocation(EndLoc);
411 Tok.setLength(0);
412 ArgTokens.push_back(Tok);
413 }
414
415 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
416}
417
418/// ComputeDATE_TIME - Compute the current time, enter it into the specified
419/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
420/// the identifier tokens inserted.
421static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
422 Preprocessor &PP) {
423 time_t TT = time(0);
424 struct tm *TM = localtime(&TT);
425
426 static const char * const Months[] = {
427 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
428 };
429
430 char TmpBuffer[100];
431 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
432 TM->tm_year+1900);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000433
434 Token TmpTok;
435 TmpTok.startToken();
436 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
437 DATELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000438
439 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000440 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
441 TIMELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000442}
443
444/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
445/// as a builtin macro, handle it and return the next token as 'Tok'.
446void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
447 // Figure out which token this is.
448 IdentifierInfo *II = Tok.getIdentifierInfo();
449 assert(II && "Can't be a macro without id info!");
450
451 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
452 // lex the token after it.
453 if (II == Ident_Pragma)
454 return Handle_Pragma(Tok);
455
456 ++NumBuiltinMacroExpanded;
457
458 char TmpBuffer[100];
459
460 // Set up the return result.
461 Tok.setIdentifierInfo(0);
462 Tok.clearFlag(Token::NeedsCleaning);
463
464 if (II == Ident__LINE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000465 // C99 6.10.8: "__LINE__: The presumed line number (within the current
466 // source file) of the current source line (an integer constant)". This can
467 // be affected by #line.
Chris Lattner844525a2009-02-15 21:06:39 +0000468 SourceLocation Loc = Tok.getLocation();
469
470 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
471 // a macro instantiation. This doesn't matter for object-like macros, but
472 // can matter for a function-like macro that expands to contain __LINE__.
473 // Skip down through instantiation points until we find a file loc for the
474 // end of the instantiation history.
Chris Lattner46558bf2009-02-15 21:26:50 +0000475 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner844525a2009-02-15 21:06:39 +0000476 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattner836774b2009-01-27 07:57:44 +0000477
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000478 // __LINE__ expands to a simple numeric value.
479 sprintf(TmpBuffer, "%u", PLoc.getLine());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000480 Tok.setKind(tok::numeric_constant);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000481 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000482 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000483 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
484 // character string literal)". This can be affected by #line.
485 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
486
487 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
488 // #include stack instead of the current file.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000489 if (II == Ident__BASE_FILE__) {
490 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner836774b2009-01-27 07:57:44 +0000491 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000492 while (NextLoc.isValid()) {
Chris Lattner836774b2009-01-27 07:57:44 +0000493 PLoc = SourceMgr.getPresumedLoc(NextLoc);
494 NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000495 }
496 }
497
498 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner836774b2009-01-27 07:57:44 +0000499 std::string FN = PLoc.getFilename();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000500 FN = '"' + Lexer::Stringify(FN) + '"';
501 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000502 CreateString(&FN[0], FN.size(), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000503 } else if (II == Ident__DATE__) {
504 if (!DATELoc.isValid())
505 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
506 Tok.setKind(tok::string_literal);
507 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000508 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000509 Tok.getLocation(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000510 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000511 } else if (II == Ident__TIME__) {
512 if (!TIMELoc.isValid())
513 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
514 Tok.setKind(tok::string_literal);
515 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000516 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000517 Tok.getLocation(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000518 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000519 } else if (II == Ident__INCLUDE_LEVEL__) {
520 Diag(Tok, diag::ext_pp_include_level);
521
Chris Lattner836774b2009-01-27 07:57:44 +0000522 // Compute the presumed include depth of this token. This can be affected
523 // by GNU line markers.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000524 unsigned Depth = 0;
Chris Lattner836774b2009-01-27 07:57:44 +0000525
526 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
527 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
528 for (; PLoc.isValid(); ++Depth)
529 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000530
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000531 // __INCLUDE_LEVEL__ expands to a simple numeric value.
532 sprintf(TmpBuffer, "%u", Depth);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000533 Tok.setKind(tok::numeric_constant);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000534 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000535 } else if (II == Ident__TIMESTAMP__) {
536 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
537 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
538 Diag(Tok, diag::ext_pp_timestamp);
539
540 // Get the file that we are lexing out of. If we're currently lexing from
541 // a macro, dig into the include stack.
542 const FileEntry *CurFile = 0;
Ted Kremenek23fb7962008-11-20 01:35:24 +0000543 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000544
545 if (TheLexer)
Ted Kremenek03467f62008-11-19 22:55:25 +0000546 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000547
548 // If this file is older than the file it depends on, emit a diagnostic.
549 const char *Result;
550 if (CurFile) {
551 time_t TT = CurFile->getModificationTime();
552 struct tm *TM = localtime(&TT);
553 Result = asctime(TM);
554 } else {
555 Result = "??? ??? ?? ??:??:?? ????\n";
556 }
557 TmpBuffer[0] = '"';
558 strcpy(TmpBuffer+1, Result);
559 unsigned Len = strlen(TmpBuffer);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000560 TmpBuffer[Len] = '"'; // Replace the newline with a quote.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000561 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000562 CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000563 } else {
564 assert(0 && "Unknown identifier!");
565 }
566}