blob: 797a5bf6f2c4304208cf464df1b97bc86857e02a [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__");
Chris Lattner4b21c202009-04-13 01:29:17 +000058 Ident__COUNTER__ = RegisterBuiltinMacro("__COUNTER__");
Chris Lattnerc7a39682008-03-09 03:13:06 +000059 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) {
Chris Lattner643e0102009-03-12 17:31:43 +0000152 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
153
Chris Lattnerc7a39682008-03-09 03:13:06 +0000154 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
155 // then the macro could expand to different things in other contexts, we need
156 // to disable the optimization in this case.
Ted Kremenek31dd0262008-11-18 01:12:54 +0000157 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000158
159 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
160 if (MI->isBuiltinMacro()) {
161 ExpandBuiltinMacro(Identifier);
162 return false;
163 }
164
165 /// Args - If this is a function-like macro expansion, this contains,
166 /// for each macro argument, the list of tokens that were provided to the
167 /// invocation.
168 MacroArgs *Args = 0;
169
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000170 // Remember where the end of the instantiation occurred. For an object-like
171 // macro, this is the identifier. For a function-like macro, this is the ')'.
172 SourceLocation InstantiationEnd = Identifier.getLocation();
173
Chris Lattnerc7a39682008-03-09 03:13:06 +0000174 // If this is a function-like macro, read the arguments.
175 if (MI->isFunctionLike()) {
176 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
177 // name isn't a '(', this macro should not be expanded. Otherwise, consume
178 // it.
179 if (!isNextPPTokenLParen())
180 return true;
181
182 // Remember that we are now parsing the arguments to a macro invocation.
183 // Preprocessor directives used inside macro arguments are not portable, and
184 // this enables the warning.
185 InMacroArgs = true;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000186 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000187
188 // Finished parsing args.
189 InMacroArgs = false;
190
191 // If there was an error parsing the arguments, bail out.
192 if (Args == 0) return false;
193
194 ++NumFnMacroExpanded;
195 } else {
196 ++NumMacroExpanded;
197 }
198
199 // Notice that this macro has been used.
200 MI->setIsUsed(true);
201
202 // If we started lexing a macro, enter the macro expansion body.
203
204 // If this macro expands to no tokens, don't bother to push it onto the
205 // expansion stack, only to take it right back off.
206 if (MI->getNumTokens() == 0) {
207 // No need for arg info.
208 if (Args) Args->destroy();
209
210 // Ignore this macro use, just return the next token in the current
211 // buffer.
212 bool HadLeadingSpace = Identifier.hasLeadingSpace();
213 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
214
215 Lex(Identifier);
216
217 // If the identifier isn't on some OTHER line, inherit the leading
218 // whitespace/first-on-a-line property of this token. This handles
219 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
220 // empty.
221 if (!Identifier.isAtStartOfLine()) {
222 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
223 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
224 }
225 ++NumFastMacroExpanded;
226 return false;
227
228 } else if (MI->getNumTokens() == 1 &&
229 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000230 *this)) {
Chris Lattnerc7a39682008-03-09 03:13:06 +0000231 // Otherwise, if this macro expands into a single trivially-expanded
232 // token: expand it now. This handles common cases like
233 // "#define VAL 42".
Sam Bishopa7fa72f2008-03-21 07:13:02 +0000234
235 // No need for arg info.
236 if (Args) Args->destroy();
237
Chris Lattnerc7a39682008-03-09 03:13:06 +0000238 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
239 // identifier to the expanded token.
240 bool isAtStartOfLine = Identifier.isAtStartOfLine();
241 bool hasLeadingSpace = Identifier.hasLeadingSpace();
242
243 // Remember where the token is instantiated.
244 SourceLocation InstantiateLoc = Identifier.getLocation();
245
246 // Replace the result token.
247 Identifier = MI->getReplacementToken(0);
248
249 // Restore the StartOfLine/LeadingSpace markers.
250 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
251 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
252
Chris Lattner18c8dc02009-01-16 07:36:28 +0000253 // Update the tokens location to include both its instantiation and physical
Chris Lattnerc7a39682008-03-09 03:13:06 +0000254 // locations.
255 SourceLocation Loc =
Chris Lattner27c0ced2009-01-26 00:43:02 +0000256 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000257 InstantiationEnd,Identifier.getLength());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000258 Identifier.setLocation(Loc);
259
260 // If this is #define X X, we must mark the result as unexpandible.
261 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
262 if (getMacroInfo(NewII) == MI)
263 Identifier.setFlag(Token::DisableExpand);
264
265 // Since this is not an identifier token, it can't be macro expanded, so
266 // we're done.
267 ++NumFastMacroExpanded;
268 return false;
269 }
270
271 // Start expanding the macro.
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000272 EnterMacro(Identifier, InstantiationEnd, Args);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000273
274 // Now that the macro is at the top of the include stack, ask the
275 // preprocessor to read the next token from it.
276 Lex(Identifier);
277 return false;
278}
279
280/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
281/// invoked to read all of the actual arguments specified for the macro
282/// invocation. This returns null on error.
283MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000284 MacroInfo *MI,
285 SourceLocation &MacroEnd) {
Chris Lattnerc7a39682008-03-09 03:13:06 +0000286 // The number of fixed arguments to parse.
287 unsigned NumFixedArgsLeft = MI->getNumArgs();
288 bool isVariadic = MI->isVariadic();
289
290 // Outer loop, while there are more arguments, keep reading them.
291 Token Tok;
292 Tok.setKind(tok::comma);
293 --NumFixedArgsLeft; // Start reading the first arg.
294
295 // ArgTokens - Build up a list of tokens that make up each argument. Each
296 // argument is separated by an EOF token. Use a SmallVector so we can avoid
297 // heap allocations in the common case.
298 llvm::SmallVector<Token, 64> ArgTokens;
299
300 unsigned NumActuals = 0;
301 while (Tok.is(tok::comma)) {
302 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
303 // that we already consumed the first one.
304 unsigned NumParens = 0;
305
306 while (1) {
307 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
308 // an argument value in a macro could expand to ',' or '(' or ')'.
309 LexUnexpandedToken(Tok);
310
311 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
312 Diag(MacroName, diag::err_unterm_macro_invoc);
313 // Do not lose the EOF/EOM. Return it to the client.
314 MacroName = Tok;
315 return 0;
316 } else if (Tok.is(tok::r_paren)) {
317 // If we found the ) token, the macro arg list is done.
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000318 if (NumParens-- == 0) {
319 MacroEnd = Tok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000320 break;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000321 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000322 } else if (Tok.is(tok::l_paren)) {
323 ++NumParens;
324 } else if (Tok.is(tok::comma) && NumParens == 0) {
325 // Comma ends this argument if there are more fixed arguments expected.
326 if (NumFixedArgsLeft)
327 break;
328
329 // If this is not a variadic macro, too many args were specified.
330 if (!isVariadic) {
331 // Emit the diagnostic at the macro name in case there is a missing ).
332 // Emitting it at the , could be far away from the macro name.
333 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
334 return 0;
335 }
336 // Otherwise, continue to add the tokens to this variable argument.
337 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
338 // If this is a comment token in the argument list and we're just in
339 // -C mode (not -CC mode), discard the comment.
340 continue;
341 } else if (Tok.is(tok::identifier)) {
342 // Reading macro arguments can cause macros that we are currently
343 // expanding from to be popped off the expansion stack. Doing so causes
344 // them to be reenabled for expansion. Here we record whether any
345 // identifiers we lex as macro arguments correspond to disabled macros.
346 // If so, we mark the token as noexpand. This is a subtle aspect of
347 // C99 6.10.3.4p2.
348 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
349 if (!MI->isEnabled())
350 Tok.setFlag(Token::DisableExpand);
351 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000352 ArgTokens.push_back(Tok);
353 }
354
355 // Empty arguments are standard in C99 and supported as an extension in
356 // other modes.
357 if (ArgTokens.empty() && !Features.C99)
358 Diag(Tok, diag::ext_empty_fnmacro_arg);
359
360 // Add a marker EOF token to the end of the token list for this argument.
361 Token EOFTok;
362 EOFTok.startToken();
363 EOFTok.setKind(tok::eof);
Chris Lattner5ccf92d2009-01-26 20:24:53 +0000364 EOFTok.setLocation(Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000365 EOFTok.setLength(0);
366 ArgTokens.push_back(EOFTok);
367 ++NumActuals;
368 --NumFixedArgsLeft;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000369 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000370
371 // Okay, we either found the r_paren. Check to see if we parsed too few
372 // arguments.
373 unsigned MinArgsExpected = MI->getNumArgs();
374
375 // See MacroArgs instance var for description of this.
376 bool isVarargsElided = false;
377
378 if (NumActuals < MinArgsExpected) {
379 // There are several cases where too few arguments is ok, handle them now.
380 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
381 // Varargs where the named vararg parameter is missing: ok as extension.
382 // #define A(x, ...)
383 // A("blah")
384 Diag(Tok, diag::ext_missing_varargs_arg);
385
Chris Lattnerdd2e5312008-05-08 05:10:33 +0000386 // Remember this occurred if this is a macro invocation with at least
387 // one actual argument. This allows us to elide the comma when used for
388 // cases like:
389 // #define A(x, foo...) blah(a, ## foo)
390 // #define A(x, ...) blah(a, ## __VA_ARGS__)
391 isVarargsElided = MI->getNumArgs() > 1;
Chris Lattnerc7a39682008-03-09 03:13:06 +0000392 } else {
393 // Otherwise, emit the error.
394 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
395 return 0;
396 }
397
398 // Add a marker EOF token to the end of the token list for this argument.
399 SourceLocation EndLoc = Tok.getLocation();
400 Tok.startToken();
401 Tok.setKind(tok::eof);
402 Tok.setLocation(EndLoc);
403 Tok.setLength(0);
404 ArgTokens.push_back(Tok);
Chris Lattnerd8242d82009-03-25 21:08:24 +0000405 } else if (NumActuals == 1 && ArgTokens.size() == 1) {
406 // If there is exactly one argument, and that argument is just an EOF token,
407 // then we have an empty "()" argument empty list. This is fine, even if
408 // the macro expects one argument (the argument is just empty). However, if
409 // the macro expects "...", then we need to know that it was elided.
410 isVarargsElided = MinArgsExpected == 1 && MI->isVariadic();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000411 }
412
413 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
414}
415
416/// ComputeDATE_TIME - Compute the current time, enter it into the specified
417/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
418/// the identifier tokens inserted.
419static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
420 Preprocessor &PP) {
421 time_t TT = time(0);
422 struct tm *TM = localtime(&TT);
423
424 static const char * const Months[] = {
425 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
426 };
427
428 char TmpBuffer[100];
429 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
430 TM->tm_year+1900);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000431
432 Token TmpTok;
433 TmpTok.startToken();
434 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
435 DATELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000436
437 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000438 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
439 TIMELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000440}
441
442/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
443/// as a builtin macro, handle it and return the next token as 'Tok'.
444void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
445 // Figure out which token this is.
446 IdentifierInfo *II = Tok.getIdentifierInfo();
447 assert(II && "Can't be a macro without id info!");
448
449 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
450 // lex the token after it.
451 if (II == Ident_Pragma)
452 return Handle_Pragma(Tok);
453
454 ++NumBuiltinMacroExpanded;
455
456 char TmpBuffer[100];
457
458 // Set up the return result.
459 Tok.setIdentifierInfo(0);
460 Tok.clearFlag(Token::NeedsCleaning);
461
462 if (II == Ident__LINE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000463 // C99 6.10.8: "__LINE__: The presumed line number (within the current
464 // source file) of the current source line (an integer constant)". This can
465 // be affected by #line.
Chris Lattner844525a2009-02-15 21:06:39 +0000466 SourceLocation Loc = Tok.getLocation();
467
468 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
469 // a macro instantiation. This doesn't matter for object-like macros, but
470 // can matter for a function-like macro that expands to contain __LINE__.
471 // Skip down through instantiation points until we find a file loc for the
472 // end of the instantiation history.
Chris Lattner46558bf2009-02-15 21:26:50 +0000473 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner844525a2009-02-15 21:06:39 +0000474 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattner836774b2009-01-27 07:57:44 +0000475
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000476 // __LINE__ expands to a simple numeric value.
477 sprintf(TmpBuffer, "%u", PLoc.getLine());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000478 Tok.setKind(tok::numeric_constant);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000479 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000480 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000481 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
482 // character string literal)". This can be affected by #line.
483 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
484
485 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
486 // #include stack instead of the current file.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000487 if (II == Ident__BASE_FILE__) {
488 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner836774b2009-01-27 07:57:44 +0000489 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000490 while (NextLoc.isValid()) {
Chris Lattner836774b2009-01-27 07:57:44 +0000491 PLoc = SourceMgr.getPresumedLoc(NextLoc);
492 NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000493 }
494 }
495
496 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner836774b2009-01-27 07:57:44 +0000497 std::string FN = PLoc.getFilename();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000498 FN = '"' + Lexer::Stringify(FN) + '"';
499 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000500 CreateString(&FN[0], FN.size(), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000501 } else if (II == Ident__DATE__) {
502 if (!DATELoc.isValid())
503 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
504 Tok.setKind(tok::string_literal);
505 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000506 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000507 Tok.getLocation(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000508 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000509 } else if (II == Ident__TIME__) {
510 if (!TIMELoc.isValid())
511 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
512 Tok.setKind(tok::string_literal);
513 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000514 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000515 Tok.getLocation(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000516 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000517 } else if (II == Ident__INCLUDE_LEVEL__) {
518 Diag(Tok, diag::ext_pp_include_level);
519
Chris Lattner836774b2009-01-27 07:57:44 +0000520 // Compute the presumed include depth of this token. This can be affected
521 // by GNU line markers.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000522 unsigned Depth = 0;
Chris Lattner836774b2009-01-27 07:57:44 +0000523
524 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
525 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
526 for (; PLoc.isValid(); ++Depth)
527 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000528
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000529 // __INCLUDE_LEVEL__ expands to a simple numeric value.
530 sprintf(TmpBuffer, "%u", Depth);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000531 Tok.setKind(tok::numeric_constant);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000532 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000533 } else if (II == Ident__TIMESTAMP__) {
534 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
535 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
536 Diag(Tok, diag::ext_pp_timestamp);
537
538 // Get the file that we are lexing out of. If we're currently lexing from
539 // a macro, dig into the include stack.
540 const FileEntry *CurFile = 0;
Ted Kremenek23fb7962008-11-20 01:35:24 +0000541 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000542
543 if (TheLexer)
Ted Kremenek03467f62008-11-19 22:55:25 +0000544 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000545
546 // If this file is older than the file it depends on, emit a diagnostic.
547 const char *Result;
548 if (CurFile) {
549 time_t TT = CurFile->getModificationTime();
550 struct tm *TM = localtime(&TT);
551 Result = asctime(TM);
552 } else {
553 Result = "??? ??? ?? ??:??:?? ????\n";
554 }
555 TmpBuffer[0] = '"';
556 strcpy(TmpBuffer+1, Result);
557 unsigned Len = strlen(TmpBuffer);
Chris Lattnerd6d3feb2009-03-08 08:08:45 +0000558 TmpBuffer[Len] = '"'; // Replace the newline with a quote.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000559 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000560 CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation());
Chris Lattner4b21c202009-04-13 01:29:17 +0000561 } else if (II == Ident__COUNTER__) {
562 Diag(Tok, diag::ext_pp_counter);
563
564 // __COUNTER__ expands to a simple numeric value.
565 sprintf(TmpBuffer, "%u", CounterValue++);
566 Tok.setKind(tok::numeric_constant);
567 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000568 } else {
569 assert(0 && "Unknown identifier!");
570 }
571}