blob: b14df735ad1c408b3762b6211933ea966dcf6d52 [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"
20#include "clang/Basic/Diagnostic.h"
Chris Lattner54fd1812008-03-18 05:59:11 +000021#include <ctime>
Chris Lattnerc7a39682008-03-09 03:13:06 +000022using namespace clang;
23
24/// setMacroInfo - Specify a macro for this identifier.
25///
26void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
27 if (MI == 0) {
28 if (II->hasMacroDefinition()) {
29 Macros.erase(II);
30 II->setHasMacroDefinition(false);
31 }
32 } else {
33 Macros[II] = MI;
34 II->setHasMacroDefinition(true);
35 }
36}
37
38/// RegisterBuiltinMacro - Register the specified identifier in the identifier
39/// table and mark it as a builtin macro to be expanded.
40IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
41 // Get the identifier.
42 IdentifierInfo *Id = getIdentifierInfo(Name);
43
44 // Mark it as being a macro that is builtin.
Ted Kremenek5f9fb3f2008-12-15 19:56:42 +000045 MacroInfo *MI = AllocateMacroInfo(SourceLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +000046 MI->setIsBuiltinMacro();
47 setMacroInfo(Id, MI);
48 return Id;
49}
50
51
52/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
53/// identifier table.
54void Preprocessor::RegisterBuiltinMacros() {
55 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
56 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
57 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
58 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
59 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
60
61 // GCC Extensions.
62 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
63 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
64 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
65}
66
67/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
68/// in its expansion, currently expands to that token literally.
69static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
70 const IdentifierInfo *MacroIdent,
71 Preprocessor &PP) {
72 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
73
74 // If the token isn't an identifier, it's always literally expanded.
75 if (II == 0) return true;
76
77 // If the identifier is a macro, and if that macro is enabled, it may be
78 // expanded so it's not a trivial expansion.
79 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
80 // Fast expanding "#define X X" is ok, because X would be disabled.
81 II != MacroIdent)
82 return false;
83
84 // If this is an object-like macro invocation, it is safe to trivially expand
85 // it.
86 if (MI->isObjectLike()) return true;
87
88 // If this is a function-like macro invocation, it's safe to trivially expand
89 // as long as the identifier is not a macro argument.
90 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
91 I != E; ++I)
92 if (*I == II)
93 return false; // Identifier is a macro argument.
94
95 return true;
96}
97
98
99/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
100/// lexed is a '('. If so, consume the token and return true, if not, this
101/// method should have no observable side-effect on the lexed tokens.
102bool Preprocessor::isNextPPTokenLParen() {
103 // Do some quick tests for rejection cases.
104 unsigned Val;
105 if (CurLexer)
106 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek3acf6702008-11-19 22:43:49 +0000107 else if (CurPTHLexer)
108 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000109 else
110 Val = CurTokenLexer->isNextTokenLParen();
111
112 if (Val == 2) {
113 // We have run off the end. If it's a source file we don't
114 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
115 // macro stack.
Ted Kremenekb53b1f42008-11-19 22:21:33 +0000116 if (CurPPLexer)
Chris Lattnerc7a39682008-03-09 03:13:06 +0000117 return false;
118 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
119 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
120 if (Entry.TheLexer)
121 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdc640532008-11-20 16:46:54 +0000122 else if (Entry.ThePTHLexer)
123 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000124 else
125 Val = Entry.TheTokenLexer->isNextTokenLParen();
126
127 if (Val != 2)
128 break;
129
130 // Ran off the end of a source file?
Ted Kremenekdc640532008-11-20 16:46:54 +0000131 if (Entry.ThePPLexer)
Chris Lattnerc7a39682008-03-09 03:13:06 +0000132 return false;
133 }
134 }
135
136 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
137 // have found something that isn't a '(' or we found the end of the
138 // translation unit. In either case, return false.
139 if (Val != 1)
140 return false;
141
142 Token Tok;
143 LexUnexpandedToken(Tok);
144 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
145 return true;
146}
147
148/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
149/// expanded as a macro, handle it and return the next token as 'Identifier'.
150bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
151 MacroInfo *MI) {
152 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
153 // then the macro could expand to different things in other contexts, we need
154 // to disable the optimization in this case.
Ted Kremenek31dd0262008-11-18 01:12:54 +0000155 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000156
157 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
158 if (MI->isBuiltinMacro()) {
159 ExpandBuiltinMacro(Identifier);
160 return false;
161 }
162
163 /// Args - If this is a function-like macro expansion, this contains,
164 /// for each macro argument, the list of tokens that were provided to the
165 /// invocation.
166 MacroArgs *Args = 0;
167
168 // If this is a function-like macro, read the arguments.
169 if (MI->isFunctionLike()) {
170 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
171 // name isn't a '(', this macro should not be expanded. Otherwise, consume
172 // it.
173 if (!isNextPPTokenLParen())
174 return true;
175
176 // Remember that we are now parsing the arguments to a macro invocation.
177 // Preprocessor directives used inside macro arguments are not portable, and
178 // this enables the warning.
179 InMacroArgs = true;
180 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
181
182 // Finished parsing args.
183 InMacroArgs = false;
184
185 // If there was an error parsing the arguments, bail out.
186 if (Args == 0) return false;
187
188 ++NumFnMacroExpanded;
189 } else {
190 ++NumMacroExpanded;
191 }
192
193 // Notice that this macro has been used.
194 MI->setIsUsed(true);
195
196 // If we started lexing a macro, enter the macro expansion body.
197
198 // If this macro expands to no tokens, don't bother to push it onto the
199 // expansion stack, only to take it right back off.
200 if (MI->getNumTokens() == 0) {
201 // No need for arg info.
202 if (Args) Args->destroy();
203
204 // Ignore this macro use, just return the next token in the current
205 // buffer.
206 bool HadLeadingSpace = Identifier.hasLeadingSpace();
207 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
208
209 Lex(Identifier);
210
211 // If the identifier isn't on some OTHER line, inherit the leading
212 // whitespace/first-on-a-line property of this token. This handles
213 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
214 // empty.
215 if (!Identifier.isAtStartOfLine()) {
216 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
217 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
218 }
219 ++NumFastMacroExpanded;
220 return false;
221
222 } else if (MI->getNumTokens() == 1 &&
223 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000224 *this)) {
Chris Lattnerc7a39682008-03-09 03:13:06 +0000225 // Otherwise, if this macro expands into a single trivially-expanded
226 // token: expand it now. This handles common cases like
227 // "#define VAL 42".
Sam Bishopa7fa72f2008-03-21 07:13:02 +0000228
229 // No need for arg info.
230 if (Args) Args->destroy();
231
Chris Lattnerc7a39682008-03-09 03:13:06 +0000232 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
233 // identifier to the expanded token.
234 bool isAtStartOfLine = Identifier.isAtStartOfLine();
235 bool hasLeadingSpace = Identifier.hasLeadingSpace();
236
237 // Remember where the token is instantiated.
238 SourceLocation InstantiateLoc = Identifier.getLocation();
239
240 // Replace the result token.
241 Identifier = MI->getReplacementToken(0);
242
243 // Restore the StartOfLine/LeadingSpace markers.
244 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
245 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
246
Chris Lattner18c8dc02009-01-16 07:36:28 +0000247 // Update the tokens location to include both its instantiation and physical
Chris Lattnerc7a39682008-03-09 03:13:06 +0000248 // locations.
249 SourceLocation Loc =
Chris Lattner27c0ced2009-01-26 00:43:02 +0000250 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
251 Identifier.getLength());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000252 Identifier.setLocation(Loc);
253
254 // If this is #define X X, we must mark the result as unexpandible.
255 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
256 if (getMacroInfo(NewII) == MI)
257 Identifier.setFlag(Token::DisableExpand);
258
259 // Since this is not an identifier token, it can't be macro expanded, so
260 // we're done.
261 ++NumFastMacroExpanded;
262 return false;
263 }
264
265 // Start expanding the macro.
266 EnterMacro(Identifier, Args);
267
268 // Now that the macro is at the top of the include stack, ask the
269 // preprocessor to read the next token from it.
270 Lex(Identifier);
271 return false;
272}
273
274/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
275/// invoked to read all of the actual arguments specified for the macro
276/// invocation. This returns null on error.
277MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
278 MacroInfo *MI) {
279 // The number of fixed arguments to parse.
280 unsigned NumFixedArgsLeft = MI->getNumArgs();
281 bool isVariadic = MI->isVariadic();
282
283 // Outer loop, while there are more arguments, keep reading them.
284 Token Tok;
285 Tok.setKind(tok::comma);
286 --NumFixedArgsLeft; // Start reading the first arg.
287
288 // ArgTokens - Build up a list of tokens that make up each argument. Each
289 // argument is separated by an EOF token. Use a SmallVector so we can avoid
290 // heap allocations in the common case.
291 llvm::SmallVector<Token, 64> ArgTokens;
292
293 unsigned NumActuals = 0;
294 while (Tok.is(tok::comma)) {
295 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
296 // that we already consumed the first one.
297 unsigned NumParens = 0;
298
299 while (1) {
300 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
301 // an argument value in a macro could expand to ',' or '(' or ')'.
302 LexUnexpandedToken(Tok);
303
304 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
305 Diag(MacroName, diag::err_unterm_macro_invoc);
306 // Do not lose the EOF/EOM. Return it to the client.
307 MacroName = Tok;
308 return 0;
309 } else if (Tok.is(tok::r_paren)) {
310 // If we found the ) token, the macro arg list is done.
311 if (NumParens-- == 0)
312 break;
313 } else if (Tok.is(tok::l_paren)) {
314 ++NumParens;
315 } else if (Tok.is(tok::comma) && NumParens == 0) {
316 // Comma ends this argument if there are more fixed arguments expected.
317 if (NumFixedArgsLeft)
318 break;
319
320 // If this is not a variadic macro, too many args were specified.
321 if (!isVariadic) {
322 // Emit the diagnostic at the macro name in case there is a missing ).
323 // Emitting it at the , could be far away from the macro name.
324 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
325 return 0;
326 }
327 // Otherwise, continue to add the tokens to this variable argument.
328 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
329 // If this is a comment token in the argument list and we're just in
330 // -C mode (not -CC mode), discard the comment.
331 continue;
332 } else if (Tok.is(tok::identifier)) {
333 // Reading macro arguments can cause macros that we are currently
334 // expanding from to be popped off the expansion stack. Doing so causes
335 // them to be reenabled for expansion. Here we record whether any
336 // identifiers we lex as macro arguments correspond to disabled macros.
337 // If so, we mark the token as noexpand. This is a subtle aspect of
338 // C99 6.10.3.4p2.
339 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
340 if (!MI->isEnabled())
341 Tok.setFlag(Token::DisableExpand);
342 }
Chris Lattner93c6f482009-01-26 04:06:48 +0000343
344 // If this token has instantiation location, resolve it down to its
345 // spelling location. This is not strictly needed, but avoids extra
346 // resolutions for macros that are expanded frequently.
347 if (!Tok.getLocation().isFileID())
348 Tok.setLocation(SourceMgr.getSpellingLoc(Tok.getLocation()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000349
350 ArgTokens.push_back(Tok);
351 }
352
353 // Empty arguments are standard in C99 and supported as an extension in
354 // other modes.
355 if (ArgTokens.empty() && !Features.C99)
356 Diag(Tok, diag::ext_empty_fnmacro_arg);
357
358 // Add a marker EOF token to the end of the token list for this argument.
359 Token EOFTok;
360 EOFTok.startToken();
361 EOFTok.setKind(tok::eof);
Chris Lattner9c348b72009-01-26 04:33:10 +0000362 EOFTok.setLocation(SourceMgr.getSpellingLoc(Tok.getLocation()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000363 EOFTok.setLength(0);
364 ArgTokens.push_back(EOFTok);
365 ++NumActuals;
366 --NumFixedArgsLeft;
367 };
368
369 // Okay, we either found the r_paren. Check to see if we parsed too few
370 // arguments.
371 unsigned MinArgsExpected = MI->getNumArgs();
372
373 // See MacroArgs instance var for description of this.
374 bool isVarargsElided = false;
375
376 if (NumActuals < MinArgsExpected) {
377 // There are several cases where too few arguments is ok, handle them now.
378 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
379 // Varargs where the named vararg parameter is missing: ok as extension.
380 // #define A(x, ...)
381 // A("blah")
382 Diag(Tok, diag::ext_missing_varargs_arg);
383
Chris Lattnerdd2e5312008-05-08 05:10:33 +0000384 // Remember this occurred if this is a macro invocation with at least
385 // one actual argument. This allows us to elide the comma when used for
386 // cases like:
387 // #define A(x, foo...) blah(a, ## foo)
388 // #define A(x, ...) blah(a, ## __VA_ARGS__)
389 isVarargsElided = MI->getNumArgs() > 1;
Chris Lattnerc7a39682008-03-09 03:13:06 +0000390 } else if (MI->getNumArgs() == 1) {
391 // #define A(x)
392 // A()
393 // is ok because it is an empty argument.
394
395 // Empty arguments are standard in C99 and supported as an extension in
396 // other modes.
397 if (ArgTokens.empty() && !Features.C99)
398 Diag(Tok, diag::ext_empty_fnmacro_arg);
399 } else {
400 // Otherwise, emit the error.
401 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
402 return 0;
403 }
404
405 // Add a marker EOF token to the end of the token list for this argument.
406 SourceLocation EndLoc = Tok.getLocation();
407 Tok.startToken();
408 Tok.setKind(tok::eof);
409 Tok.setLocation(EndLoc);
410 Tok.setLength(0);
411 ArgTokens.push_back(Tok);
412 }
413
414 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
415}
416
417/// ComputeDATE_TIME - Compute the current time, enter it into the specified
418/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
419/// the identifier tokens inserted.
420static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
421 Preprocessor &PP) {
422 time_t TT = time(0);
423 struct tm *TM = localtime(&TT);
424
425 static const char * const Months[] = {
426 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
427 };
428
429 char TmpBuffer[100];
430 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
431 TM->tm_year+1900);
432 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
433
434 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
435 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
436}
437
438/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
439/// as a builtin macro, handle it and return the next token as 'Tok'.
440void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
441 // Figure out which token this is.
442 IdentifierInfo *II = Tok.getIdentifierInfo();
443 assert(II && "Can't be a macro without id info!");
444
445 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
446 // lex the token after it.
447 if (II == Ident_Pragma)
448 return Handle_Pragma(Tok);
449
450 ++NumBuiltinMacroExpanded;
451
452 char TmpBuffer[100];
453
454 // Set up the return result.
455 Tok.setIdentifierInfo(0);
456 Tok.clearFlag(Token::NeedsCleaning);
457
458 if (II == Ident__LINE__) {
Chris Lattner9501a482008-09-29 23:12:31 +0000459 // __LINE__ expands to a simple numeric value. Add a space after it so that
460 // it will tokenize as a number (and not run into stuff after it in the temp
461 // buffer).
462 sprintf(TmpBuffer, "%u ",
Chris Lattner18c8dc02009-01-16 07:36:28 +0000463 SourceMgr.getInstantiationLineNumber(Tok.getLocation()));
Chris Lattner9501a482008-09-29 23:12:31 +0000464 unsigned Length = strlen(TmpBuffer)-1;
Chris Lattnerc7a39682008-03-09 03:13:06 +0000465 Tok.setKind(tok::numeric_constant);
466 Tok.setLength(Length);
Chris Lattner9501a482008-09-29 23:12:31 +0000467 Tok.setLocation(CreateString(TmpBuffer, Length+1, Tok.getLocation()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000468 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
469 SourceLocation Loc = Tok.getLocation();
470 if (II == Ident__BASE_FILE__) {
471 Diag(Tok, diag::ext_pp_base_file);
472 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
473 while (NextLoc.isValid()) {
474 Loc = NextLoc;
475 NextLoc = SourceMgr.getIncludeLoc(Loc);
476 }
477 }
478
479 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner18c8dc02009-01-16 07:36:28 +0000480 std::string FN =SourceMgr.getSourceName(SourceMgr.getInstantiationLoc(Loc));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000481 FN = '"' + Lexer::Stringify(FN) + '"';
482 Tok.setKind(tok::string_literal);
483 Tok.setLength(FN.size());
484 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
485 } else if (II == Ident__DATE__) {
486 if (!DATELoc.isValid())
487 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
488 Tok.setKind(tok::string_literal);
489 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000490 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
491 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000492 } else if (II == Ident__TIME__) {
493 if (!TIMELoc.isValid())
494 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
495 Tok.setKind(tok::string_literal);
496 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000497 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
498 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000499 } else if (II == Ident__INCLUDE_LEVEL__) {
500 Diag(Tok, diag::ext_pp_include_level);
501
502 // Compute the include depth of this token.
503 unsigned Depth = 0;
504 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
505 for (; Loc.isValid(); ++Depth)
506 Loc = SourceMgr.getIncludeLoc(Loc);
507
Chris Lattner9501a482008-09-29 23:12:31 +0000508 // __INCLUDE_LEVEL__ expands to a simple numeric value. Add a space after
509 // it so that it will tokenize as a number (and not run into stuff after it
510 // in the temp buffer).
511 sprintf(TmpBuffer, "%u ", Depth);
512 unsigned Length = strlen(TmpBuffer)-1;
Chris Lattnerc7a39682008-03-09 03:13:06 +0000513 Tok.setKind(tok::numeric_constant);
514 Tok.setLength(Length);
515 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
516 } else if (II == Ident__TIMESTAMP__) {
517 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
518 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
519 Diag(Tok, diag::ext_pp_timestamp);
520
521 // Get the file that we are lexing out of. If we're currently lexing from
522 // a macro, dig into the include stack.
523 const FileEntry *CurFile = 0;
Ted Kremenek23fb7962008-11-20 01:35:24 +0000524 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000525
526 if (TheLexer)
Ted Kremenek03467f62008-11-19 22:55:25 +0000527 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000528
529 // If this file is older than the file it depends on, emit a diagnostic.
530 const char *Result;
531 if (CurFile) {
532 time_t TT = CurFile->getModificationTime();
533 struct tm *TM = localtime(&TT);
534 Result = asctime(TM);
535 } else {
536 Result = "??? ??? ?? ??:??:?? ????\n";
537 }
538 TmpBuffer[0] = '"';
539 strcpy(TmpBuffer+1, Result);
540 unsigned Len = strlen(TmpBuffer);
541 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
542 Tok.setKind(tok::string_literal);
543 Tok.setLength(Len);
Chris Lattner9501a482008-09-29 23:12:31 +0000544 Tok.setLocation(CreateString(TmpBuffer, Len+1, Tok.getLocation()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000545 } else {
546 assert(0 && "Unknown identifier!");
547 }
548}