blob: 33b5ef8656838eb8c81c3598c2e50beded62160b [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 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
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000168 // Remember where the end of the instantiation occurred. For an object-like
169 // macro, this is the identifier. For a function-like macro, this is the ')'.
170 SourceLocation InstantiationEnd = Identifier.getLocation();
171
Chris Lattnerc7a39682008-03-09 03:13:06 +0000172 // If this is a function-like macro, read the arguments.
173 if (MI->isFunctionLike()) {
174 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
175 // name isn't a '(', this macro should not be expanded. Otherwise, consume
176 // it.
177 if (!isNextPPTokenLParen())
178 return true;
179
180 // Remember that we are now parsing the arguments to a macro invocation.
181 // Preprocessor directives used inside macro arguments are not portable, and
182 // this enables the warning.
183 InMacroArgs = true;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000184 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000185
186 // Finished parsing args.
187 InMacroArgs = false;
188
189 // If there was an error parsing the arguments, bail out.
190 if (Args == 0) return false;
191
192 ++NumFnMacroExpanded;
193 } else {
194 ++NumMacroExpanded;
195 }
196
197 // Notice that this macro has been used.
198 MI->setIsUsed(true);
199
200 // If we started lexing a macro, enter the macro expansion body.
201
202 // If this macro expands to no tokens, don't bother to push it onto the
203 // expansion stack, only to take it right back off.
204 if (MI->getNumTokens() == 0) {
205 // No need for arg info.
206 if (Args) Args->destroy();
207
208 // Ignore this macro use, just return the next token in the current
209 // buffer.
210 bool HadLeadingSpace = Identifier.hasLeadingSpace();
211 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
212
213 Lex(Identifier);
214
215 // If the identifier isn't on some OTHER line, inherit the leading
216 // whitespace/first-on-a-line property of this token. This handles
217 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
218 // empty.
219 if (!Identifier.isAtStartOfLine()) {
220 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
221 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
222 }
223 ++NumFastMacroExpanded;
224 return false;
225
226 } else if (MI->getNumTokens() == 1 &&
227 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000228 *this)) {
Chris Lattnerc7a39682008-03-09 03:13:06 +0000229 // Otherwise, if this macro expands into a single trivially-expanded
230 // token: expand it now. This handles common cases like
231 // "#define VAL 42".
Sam Bishopa7fa72f2008-03-21 07:13:02 +0000232
233 // No need for arg info.
234 if (Args) Args->destroy();
235
Chris Lattnerc7a39682008-03-09 03:13:06 +0000236 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
237 // identifier to the expanded token.
238 bool isAtStartOfLine = Identifier.isAtStartOfLine();
239 bool hasLeadingSpace = Identifier.hasLeadingSpace();
240
241 // Remember where the token is instantiated.
242 SourceLocation InstantiateLoc = Identifier.getLocation();
243
244 // Replace the result token.
245 Identifier = MI->getReplacementToken(0);
246
247 // Restore the StartOfLine/LeadingSpace markers.
248 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
249 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
250
Chris Lattner18c8dc02009-01-16 07:36:28 +0000251 // Update the tokens location to include both its instantiation and physical
Chris Lattnerc7a39682008-03-09 03:13:06 +0000252 // locations.
253 SourceLocation Loc =
Chris Lattner27c0ced2009-01-26 00:43:02 +0000254 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000255 InstantiationEnd,Identifier.getLength());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000256 Identifier.setLocation(Loc);
257
258 // If this is #define X X, we must mark the result as unexpandible.
259 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
260 if (getMacroInfo(NewII) == MI)
261 Identifier.setFlag(Token::DisableExpand);
262
263 // Since this is not an identifier token, it can't be macro expanded, so
264 // we're done.
265 ++NumFastMacroExpanded;
266 return false;
267 }
268
269 // Start expanding the macro.
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000270 EnterMacro(Identifier, InstantiationEnd, Args);
Chris Lattnerc7a39682008-03-09 03:13:06 +0000271
272 // Now that the macro is at the top of the include stack, ask the
273 // preprocessor to read the next token from it.
274 Lex(Identifier);
275 return false;
276}
277
278/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
279/// invoked to read all of the actual arguments specified for the macro
280/// invocation. This returns null on error.
281MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000282 MacroInfo *MI,
283 SourceLocation &MacroEnd) {
Chris Lattnerc7a39682008-03-09 03:13:06 +0000284 // The number of fixed arguments to parse.
285 unsigned NumFixedArgsLeft = MI->getNumArgs();
286 bool isVariadic = MI->isVariadic();
287
288 // Outer loop, while there are more arguments, keep reading them.
289 Token Tok;
290 Tok.setKind(tok::comma);
291 --NumFixedArgsLeft; // Start reading the first arg.
292
293 // ArgTokens - Build up a list of tokens that make up each argument. Each
294 // argument is separated by an EOF token. Use a SmallVector so we can avoid
295 // heap allocations in the common case.
296 llvm::SmallVector<Token, 64> ArgTokens;
297
298 unsigned NumActuals = 0;
299 while (Tok.is(tok::comma)) {
300 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
301 // that we already consumed the first one.
302 unsigned NumParens = 0;
303
304 while (1) {
305 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
306 // an argument value in a macro could expand to ',' or '(' or ')'.
307 LexUnexpandedToken(Tok);
308
309 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
310 Diag(MacroName, diag::err_unterm_macro_invoc);
311 // Do not lose the EOF/EOM. Return it to the client.
312 MacroName = Tok;
313 return 0;
314 } else if (Tok.is(tok::r_paren)) {
315 // If we found the ) token, the macro arg list is done.
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000316 if (NumParens-- == 0) {
317 MacroEnd = Tok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000318 break;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000319 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000320 } else if (Tok.is(tok::l_paren)) {
321 ++NumParens;
322 } else if (Tok.is(tok::comma) && NumParens == 0) {
323 // Comma ends this argument if there are more fixed arguments expected.
324 if (NumFixedArgsLeft)
325 break;
326
327 // If this is not a variadic macro, too many args were specified.
328 if (!isVariadic) {
329 // Emit the diagnostic at the macro name in case there is a missing ).
330 // Emitting it at the , could be far away from the macro name.
331 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
332 return 0;
333 }
334 // Otherwise, continue to add the tokens to this variable argument.
335 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
336 // If this is a comment token in the argument list and we're just in
337 // -C mode (not -CC mode), discard the comment.
338 continue;
339 } else if (Tok.is(tok::identifier)) {
340 // Reading macro arguments can cause macros that we are currently
341 // expanding from to be popped off the expansion stack. Doing so causes
342 // them to be reenabled for expansion. Here we record whether any
343 // identifiers we lex as macro arguments correspond to disabled macros.
344 // If so, we mark the token as noexpand. This is a subtle aspect of
345 // C99 6.10.3.4p2.
346 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
347 if (!MI->isEnabled())
348 Tok.setFlag(Token::DisableExpand);
349 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000350 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 Lattner5ccf92d2009-01-26 20:24:53 +0000362 EOFTok.setLocation(Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000363 EOFTok.setLength(0);
364 ArgTokens.push_back(EOFTok);
365 ++NumActuals;
366 --NumFixedArgsLeft;
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000367 }
Chris Lattnerc7a39682008-03-09 03:13:06 +0000368
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);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000432
433 Token TmpTok;
434 TmpTok.startToken();
435 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
436 DATELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000437
438 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000439 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
440 TIMELoc = TmpTok.getLocation();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000441}
442
443/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
444/// as a builtin macro, handle it and return the next token as 'Tok'.
445void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
446 // Figure out which token this is.
447 IdentifierInfo *II = Tok.getIdentifierInfo();
448 assert(II && "Can't be a macro without id info!");
449
450 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
451 // lex the token after it.
452 if (II == Ident_Pragma)
453 return Handle_Pragma(Tok);
454
455 ++NumBuiltinMacroExpanded;
456
457 char TmpBuffer[100];
458
459 // Set up the return result.
460 Tok.setIdentifierInfo(0);
461 Tok.clearFlag(Token::NeedsCleaning);
462
463 if (II == Ident__LINE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000464 // C99 6.10.8: "__LINE__: The presumed line number (within the current
465 // source file) of the current source line (an integer constant)". This can
466 // be affected by #line.
Chris Lattner844525a2009-02-15 21:06:39 +0000467 SourceLocation Loc = Tok.getLocation();
468
469 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
470 // a macro instantiation. This doesn't matter for object-like macros, but
471 // can matter for a function-like macro that expands to contain __LINE__.
472 // Skip down through instantiation points until we find a file loc for the
473 // end of the instantiation history.
474 while (!Loc.isFileID())
475 Loc = SourceMgr.getImmediateInstantiationRange(Loc).second;
476
477 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Chris Lattner836774b2009-01-27 07:57:44 +0000478
Chris Lattner9501a482008-09-29 23:12:31 +0000479 // __LINE__ expands to a simple numeric value. Add a space after it so that
480 // it will tokenize as a number (and not run into stuff after it in the temp
481 // buffer).
Chris Lattner836774b2009-01-27 07:57:44 +0000482 sprintf(TmpBuffer, "%u ", PLoc.getLine());
Chris Lattner9501a482008-09-29 23:12:31 +0000483 unsigned Length = strlen(TmpBuffer)-1;
Chris Lattnerc7a39682008-03-09 03:13:06 +0000484 Tok.setKind(tok::numeric_constant);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000485 CreateString(TmpBuffer, Length+1, Tok, Tok.getLocation());
486 Tok.setLength(Length); // Trim off space.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000487 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattner836774b2009-01-27 07:57:44 +0000488 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
489 // character string literal)". This can be affected by #line.
490 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
491
492 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
493 // #include stack instead of the current file.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000494 if (II == Ident__BASE_FILE__) {
495 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner836774b2009-01-27 07:57:44 +0000496 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000497 while (NextLoc.isValid()) {
Chris Lattner836774b2009-01-27 07:57:44 +0000498 PLoc = SourceMgr.getPresumedLoc(NextLoc);
499 NextLoc = PLoc.getIncludeLoc();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000500 }
501 }
502
503 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner836774b2009-01-27 07:57:44 +0000504 std::string FN = PLoc.getFilename();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000505 FN = '"' + Lexer::Stringify(FN) + '"';
506 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000507 CreateString(&FN[0], FN.size(), Tok, Tok.getLocation());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000508 } else if (II == Ident__DATE__) {
509 if (!DATELoc.isValid())
510 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
511 Tok.setKind(tok::string_literal);
512 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000513 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, 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__TIME__) {
517 if (!TIMELoc.isValid())
518 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
519 Tok.setKind(tok::string_literal);
520 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattner27c0ced2009-01-26 00:43:02 +0000521 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000522 Tok.getLocation(),
Chris Lattner27c0ced2009-01-26 00:43:02 +0000523 Tok.getLength()));
Chris Lattnerc7a39682008-03-09 03:13:06 +0000524 } else if (II == Ident__INCLUDE_LEVEL__) {
525 Diag(Tok, diag::ext_pp_include_level);
526
Chris Lattner836774b2009-01-27 07:57:44 +0000527 // Compute the presumed include depth of this token. This can be affected
528 // by GNU line markers.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000529 unsigned Depth = 0;
Chris Lattner836774b2009-01-27 07:57:44 +0000530
531 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
532 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
533 for (; PLoc.isValid(); ++Depth)
534 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000535
Chris Lattner9501a482008-09-29 23:12:31 +0000536 // __INCLUDE_LEVEL__ expands to a simple numeric value. Add a space after
537 // it so that it will tokenize as a number (and not run into stuff after it
538 // in the temp buffer).
539 sprintf(TmpBuffer, "%u ", Depth);
540 unsigned Length = strlen(TmpBuffer)-1;
Chris Lattnerc7a39682008-03-09 03:13:06 +0000541 Tok.setKind(tok::numeric_constant);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000542 CreateString(TmpBuffer, Length, Tok, Tok.getLocation());
543 Tok.setLength(Length); // Trim off space.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000544 } else if (II == Ident__TIMESTAMP__) {
545 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
546 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
547 Diag(Tok, diag::ext_pp_timestamp);
548
549 // Get the file that we are lexing out of. If we're currently lexing from
550 // a macro, dig into the include stack.
551 const FileEntry *CurFile = 0;
Ted Kremenek23fb7962008-11-20 01:35:24 +0000552 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Chris Lattnerc7a39682008-03-09 03:13:06 +0000553
554 if (TheLexer)
Ted Kremenek03467f62008-11-19 22:55:25 +0000555 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Chris Lattnerc7a39682008-03-09 03:13:06 +0000556
557 // If this file is older than the file it depends on, emit a diagnostic.
558 const char *Result;
559 if (CurFile) {
560 time_t TT = CurFile->getModificationTime();
561 struct tm *TM = localtime(&TT);
562 Result = asctime(TM);
563 } else {
564 Result = "??? ??? ?? ??:??:?? ????\n";
565 }
566 TmpBuffer[0] = '"';
567 strcpy(TmpBuffer+1, Result);
568 unsigned Len = strlen(TmpBuffer);
569 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
570 Tok.setKind(tok::string_literal);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000571 CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation());
572 Tok.setLength(Len); // Trim off space.
Chris Lattnerc7a39682008-03-09 03:13:06 +0000573 } else {
574 assert(0 && "Unknown identifier!");
575 }
576}