blob: b23311af19274ce658e301ffab60232d122ed291 [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) {
Chris Lattnerc90096f2009-04-10 21:17:07 +000028 if (MI) {
Chris Lattnerc7a39682008-03-09 03:13:06 +000029 Macros[II] = MI;
30 II->setHasMacroDefinition(true);
Chris Lattnerc90096f2009-04-10 21:17:07 +000031 } else if (II->hasMacroDefinition()) {
32 Macros.erase(II);
33 II->setHasMacroDefinition(false);
Chris Lattnerc7a39682008-03-09 03:13:06 +000034 }
35}
36
37/// RegisterBuiltinMacro - Register the specified identifier in the identifier
38/// table and mark it as a builtin macro to be expanded.
39IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
40 // Get the identifier.
41 IdentifierInfo *Id = getIdentifierInfo(Name);
42
43 // Mark it as being a macro that is builtin.
Ted Kremenek5f9fb3f2008-12-15 19:56:42 +000044 MacroInfo *MI = AllocateMacroInfo(SourceLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +000045 MI->setIsBuiltinMacro();
46 setMacroInfo(Id, MI);
47 return Id;
48}
49
50
51/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
52/// identifier table.
53void Preprocessor::RegisterBuiltinMacros() {
54 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
55 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
56 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
57 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
58 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
59
60 // GCC Extensions.
61 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
62 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
63 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
64}
65
66/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
67/// in its expansion, currently expands to that token literally.
68static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
69 const IdentifierInfo *MacroIdent,
70 Preprocessor &PP) {
71 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
72
73 // If the token isn't an identifier, it's always literally expanded.
74 if (II == 0) return true;
75
76 // If the identifier is a macro, and if that macro is enabled, it may be
77 // expanded so it's not a trivial expansion.
78 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
79 // Fast expanding "#define X X" is ok, because X would be disabled.
80 II != MacroIdent)
81 return false;
82
83 // If this is an object-like macro invocation, it is safe to trivially expand
84 // it.
85 if (MI->isObjectLike()) return true;
86
87 // If this is a function-like macro invocation, it's safe to trivially expand
88 // as long as the identifier is not a macro argument.
89 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
90 I != E; ++I)
91 if (*I == II)
92 return false; // Identifier is a macro argument.
93
94 return true;
95}
96
97
98/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
99/// lexed is a '('. If so, consume the token and return true, if not, this
100/// method should have no observable side-effect on the lexed tokens.
101bool Preprocessor::isNextPPTokenLParen() {
102 // Do some quick tests for rejection cases.
103 unsigned Val;
104 if (CurLexer)
105 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek3acf6702008-11-19 22:43:49 +0000106 else if (CurPTHLexer)
107 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000108 else
109 Val = CurTokenLexer->isNextTokenLParen();
110
111 if (Val == 2) {
112 // We have run off the end. If it's a source file we don't
113 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
114 // macro stack.
Ted Kremenekb53b1f42008-11-19 22:21:33 +0000115 if (CurPPLexer)
Chris Lattnerc7a39682008-03-09 03:13:06 +0000116 return false;
117 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
118 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
119 if (Entry.TheLexer)
120 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdc640532008-11-20 16:46:54 +0000121 else if (Entry.ThePTHLexer)
122 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000123 else
124 Val = Entry.TheTokenLexer->isNextTokenLParen();
125
126 if (Val != 2)
127 break;
128
129 // Ran off the end of a source file?
Ted Kremenekdc640532008-11-20 16:46:54 +0000130 if (Entry.ThePPLexer)
Chris Lattnerc7a39682008-03-09 03:13:06 +0000131 return false;
132 }
133 }
134
135 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
136 // have found something that isn't a '(' or we found the end of the
137 // translation unit. In either case, return false.
138 if (Val != 1)
139 return false;
140
141 Token Tok;
142 LexUnexpandedToken(Tok);
143 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
144 return true;
145}
146
147/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
148/// expanded as a macro, handle it and return the next token as 'Identifier'.
149bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
150 MacroInfo *MI) {
Chris Lattner643e0102009-03-12 17:31:43 +0000151 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
152
Chris Lattnerc7a39682008-03-09 03:13:06 +0000153 // 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 {
392 // Otherwise, emit the error.
393 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
394 return 0;
395 }
396
397 // Add a marker EOF token to the end of the token list for this argument.
398 SourceLocation EndLoc = Tok.getLocation();
399 Tok.startToken();
400 Tok.setKind(tok::eof);
401 Tok.setLocation(EndLoc);
402 Tok.setLength(0);
403 ArgTokens.push_back(Tok);
Chris Lattnerd8242d82009-03-25 21:08:24 +0000404 } else if (NumActuals == 1 && ArgTokens.size() == 1) {
405 // If there is exactly one argument, and that argument is just an EOF token,
406 // then we have an empty "()" argument empty list. This is fine, even if
407 // the macro expects one argument (the argument is just empty). However, if
408 // the macro expects "...", then we need to know that it was elided.
409 isVarargsElided = MinArgsExpected == 1 && MI->isVariadic();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000410 }
411
412 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
413}
414
415/// ComputeDATE_TIME - Compute the current time, enter it into the specified
416/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
417/// the identifier tokens inserted.
418static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
419 Preprocessor &PP) {
420 time_t TT = time(0);
421 struct tm *TM = localtime(&TT);
422
423 static const char * const Months[] = {
424 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
425 };
426
427 char TmpBuffer[100];
428 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
429 TM->tm_year+1900);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000430
431 Token TmpTok;
432 TmpTok.startToken();
433 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
434 DATELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000435
436 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000437 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
438 TIMELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000439}
440
441/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
442/// as a builtin macro, handle it and return the next token as 'Tok'.
443void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
444 // Figure out which token this is.
445 IdentifierInfo *II = Tok.getIdentifierInfo();
446 assert(II && "Can't be a macro without id info!");
447
448 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
449 // lex the token after it.
450 if (II == Ident_Pragma)
451 return Handle_Pragma(Tok);
452
453 ++NumBuiltinMacroExpanded;
454
455 char TmpBuffer[100];
456
457 // Set up the return result.
458 Tok.setIdentifierInfo(0);
459 Tok.clearFlag(Token::NeedsCleaning);
460
461 if (II == Ident__LINE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000462 // C99 6.10.8: "__LINE__: The presumed line number (within the current
463 // source file) of the current source line (an integer constant)". This can
464 // be affected by #line.
Chris Lattner844525a2009-02-15 21:06:39 +0000465 SourceLocation Loc = Tok.getLocation();
466
467 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
468 // a macro instantiation. This doesn't matter for object-like macros, but
469 // can matter for a function-like macro that expands to contain __LINE__.
470 // Skip down through instantiation points until we find a file loc for the
471 // end of the instantiation history.
Chris Lattner46558bf2009-02-15 21:26:50 +0000472 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner844525a2009-02-15 21:06:39 +0000473 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattner836774b2009-01-27 07:57:44 +0000474
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000475 // __LINE__ expands to a simple numeric value.
476 sprintf(TmpBuffer, "%u", PLoc.getLine());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000477 Tok.setKind(tok::numeric_constant);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000478 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000479 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000480 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
481 // character string literal)". This can be affected by #line.
482 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
483
484 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
485 // #include stack instead of the current file.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000486 if (II == Ident__BASE_FILE__) {
487 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner836774b2009-01-27 07:57:44 +0000488 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000489 while (NextLoc.isValid()) {
Chris Lattner836774b2009-01-27 07:57:44 +0000490 PLoc = SourceMgr.getPresumedLoc(NextLoc);
491 NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000492 }
493 }
494
495 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner836774b2009-01-27 07:57:44 +0000496 std::string FN = PLoc.getFilename();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000497 FN = '"' + Lexer::Stringify(FN) + '"';
498 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000499 CreateString(&FN[0], FN.size(), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000500 } else if (II == Ident__DATE__) {
501 if (!DATELoc.isValid())
502 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
503 Tok.setKind(tok::string_literal);
504 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000505 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000506 Tok.getLocation(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000507 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000508 } else if (II == Ident__TIME__) {
509 if (!TIMELoc.isValid())
510 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
511 Tok.setKind(tok::string_literal);
512 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000513 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000514 Tok.getLocation(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000515 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000516 } else if (II == Ident__INCLUDE_LEVEL__) {
517 Diag(Tok, diag::ext_pp_include_level);
518
Chris Lattner836774b2009-01-27 07:57:44 +0000519 // Compute the presumed include depth of this token. This can be affected
520 // by GNU line markers.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000521 unsigned Depth = 0;
Chris Lattner836774b2009-01-27 07:57:44 +0000522
523 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
524 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
525 for (; PLoc.isValid(); ++Depth)
526 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000527
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000528 // __INCLUDE_LEVEL__ expands to a simple numeric value.
529 sprintf(TmpBuffer, "%u", Depth);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000530 Tok.setKind(tok::numeric_constant);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000531 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000532 } else if (II == Ident__TIMESTAMP__) {
533 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
534 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
535 Diag(Tok, diag::ext_pp_timestamp);
536
537 // Get the file that we are lexing out of. If we're currently lexing from
538 // a macro, dig into the include stack.
539 const FileEntry *CurFile = 0;
Ted Kremenek23fb7962008-11-20 01:35:24 +0000540 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000541
542 if (TheLexer)
Ted Kremenek03467f62008-11-19 22:55:25 +0000543 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000544
545 // If this file is older than the file it depends on, emit a diagnostic.
546 const char *Result;
547 if (CurFile) {
548 time_t TT = CurFile->getModificationTime();
549 struct tm *TM = localtime(&TT);
550 Result = asctime(TM);
551 } else {
552 Result = "??? ??? ?? ??:??:?? ????\n";
553 }
554 TmpBuffer[0] = '"';
555 strcpy(TmpBuffer+1, Result);
556 unsigned Len = strlen(TmpBuffer);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000557 TmpBuffer[Len] = '"'; // Replace the newline with a quote.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000558 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000559 CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000560 } else {
561 assert(0 && "Unknown identifier!");
562 }
563}