1 //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the top level handling of macro expasion for the
13 //===----------------------------------------------------------------------===//
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/Lex/LexDiagnostic.h"
21 #include "llvm/ADT/StringSwitch.h"
24 using namespace clang;
26 /// setMacroInfo - Specify a macro for this identifier.
28 void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
31 II->setHasMacroDefinition(true);
32 } else if (II->hasMacroDefinition()) {
34 II->setHasMacroDefinition(false);
38 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
39 /// table and mark it as a builtin macro to be expanded.
40 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
41 // Get the identifier.
42 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
44 // Mark it as being a macro that is builtin.
45 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
46 MI->setIsBuiltinMacro();
47 PP.setMacroInfo(Id, MI);
52 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
54 void Preprocessor::RegisterBuiltinMacros() {
55 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
56 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
57 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
58 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
59 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
60 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
63 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
64 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
65 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
68 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
69 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
70 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
71 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
74 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
75 /// in its expansion, currently expands to that token literally.
76 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
77 const IdentifierInfo *MacroIdent,
79 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
81 // If the token isn't an identifier, it's always literally expanded.
82 if (II == 0) return true;
84 // If the identifier is a macro, and if that macro is enabled, it may be
85 // expanded so it's not a trivial expansion.
86 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
87 // Fast expanding "#define X X" is ok, because X would be disabled.
91 // If this is an object-like macro invocation, it is safe to trivially expand
93 if (MI->isObjectLike()) return true;
95 // If this is a function-like macro invocation, it's safe to trivially expand
96 // as long as the identifier is not a macro argument.
97 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
100 return false; // Identifier is a macro argument.
106 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
107 /// lexed is a '('. If so, consume the token and return true, if not, this
108 /// method should have no observable side-effect on the lexed tokens.
109 bool Preprocessor::isNextPPTokenLParen() {
110 // Do some quick tests for rejection cases.
113 Val = CurLexer->isNextPPTokenLParen();
114 else if (CurPTHLexer)
115 Val = CurPTHLexer->isNextPPTokenLParen();
117 Val = CurTokenLexer->isNextTokenLParen();
120 // We have run off the end. If it's a source file we don't
121 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
125 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
126 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
128 Val = Entry.TheLexer->isNextPPTokenLParen();
129 else if (Entry.ThePTHLexer)
130 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
132 Val = Entry.TheTokenLexer->isNextTokenLParen();
137 // Ran off the end of a source file?
138 if (Entry.ThePPLexer)
143 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
144 // have found something that isn't a '(' or we found the end of the
145 // translation unit. In either case, return false.
149 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
150 /// expanded as a macro, handle it and return the next token as 'Identifier'.
151 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
153 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
155 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
156 // then the macro could expand to different things in other contexts, we need
157 // to disable the optimization in this case.
158 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
160 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
161 if (MI->isBuiltinMacro()) {
162 ExpandBuiltinMacro(Identifier);
166 /// Args - If this is a function-like macro expansion, this contains,
167 /// for each macro argument, the list of tokens that were provided to the
171 // Remember where the end of the instantiation occurred. For an object-like
172 // macro, this is the identifier. For a function-like macro, this is the ')'.
173 SourceLocation InstantiationEnd = Identifier.getLocation();
175 // If this is a function-like macro, read the arguments.
176 if (MI->isFunctionLike()) {
177 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
178 // name isn't a '(', this macro should not be expanded.
179 if (!isNextPPTokenLParen())
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.
186 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
188 // Finished parsing args.
191 // If there was an error parsing the arguments, bail out.
192 if (Args == 0) return false;
194 ++NumFnMacroExpanded;
199 // Notice that this macro has been used.
202 // If we started lexing a macro, enter the macro expansion body.
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(*this);
210 // Ignore this macro use, just return the next token in the current
212 bool HadLeadingSpace = Identifier.hasLeadingSpace();
213 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
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
221 if (!Identifier.isAtStartOfLine()) {
222 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
223 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
225 ++NumFastMacroExpanded;
228 } else if (MI->getNumTokens() == 1 &&
229 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
231 // Otherwise, if this macro expands into a single trivially-expanded
232 // token: expand it now. This handles common cases like
235 // No need for arg info.
236 if (Args) Args->destroy(*this);
238 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
239 // identifier to the expanded token.
240 bool isAtStartOfLine = Identifier.isAtStartOfLine();
241 bool hasLeadingSpace = Identifier.hasLeadingSpace();
243 // Remember where the token is instantiated.
244 SourceLocation InstantiateLoc = Identifier.getLocation();
246 // Replace the result token.
247 Identifier = MI->getReplacementToken(0);
249 // Restore the StartOfLine/LeadingSpace markers.
250 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
251 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
253 // Update the tokens location to include both its instantiation and physical
256 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
257 InstantiationEnd,Identifier.getLength());
258 Identifier.setLocation(Loc);
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);
265 // Since this is not an identifier token, it can't be macro expanded, so
267 ++NumFastMacroExpanded;
271 // Start expanding the macro.
272 EnterMacro(Identifier, InstantiationEnd, Args);
274 // Now that the macro is at the top of the include stack, ask the
275 // preprocessor to read the next token from it.
280 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
281 /// token is the '(' of the macro, this method is invoked to read all of the
282 /// actual arguments specified for the macro invocation. This returns null on
284 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
286 SourceLocation &MacroEnd) {
287 // The number of fixed arguments to parse.
288 unsigned NumFixedArgsLeft = MI->getNumArgs();
289 bool isVariadic = MI->isVariadic();
291 // Outer loop, while there are more arguments, keep reading them.
294 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
295 // an argument value in a macro could expand to ',' or '(' or ')'.
296 LexUnexpandedToken(Tok);
297 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
299 // ArgTokens - Build up a list of tokens that make up each argument. Each
300 // argument is separated by an EOF token. Use a SmallVector so we can avoid
301 // heap allocations in the common case.
302 llvm::SmallVector<Token, 64> ArgTokens;
304 unsigned NumActuals = 0;
305 while (Tok.isNot(tok::r_paren)) {
306 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
307 "only expect argument separators here");
309 unsigned ArgTokenStart = ArgTokens.size();
310 SourceLocation ArgStartLoc = Tok.getLocation();
312 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
313 // that we already consumed the first one.
314 unsigned NumParens = 0;
317 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
318 // an argument value in a macro could expand to ',' or '(' or ')'.
319 LexUnexpandedToken(Tok);
321 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
322 Diag(MacroName, diag::err_unterm_macro_invoc);
323 // Do not lose the EOF/EOM. Return it to the client.
326 } else if (Tok.is(tok::r_paren)) {
327 // If we found the ) token, the macro arg list is done.
328 if (NumParens-- == 0) {
329 MacroEnd = Tok.getLocation();
332 } else if (Tok.is(tok::l_paren)) {
334 } else if (Tok.is(tok::comma) && NumParens == 0) {
335 // Comma ends this argument if there are more fixed arguments expected.
336 // However, if this is a variadic macro, and this is part of the
337 // variadic part, then the comma is just an argument token.
338 if (!isVariadic) break;
339 if (NumFixedArgsLeft > 1)
341 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
342 // If this is a comment token in the argument list and we're just in
343 // -C mode (not -CC mode), discard the comment.
345 } else if (Tok.getIdentifierInfo() != 0) {
346 // Reading macro arguments can cause macros that we are currently
347 // expanding from to be popped off the expansion stack. Doing so causes
348 // them to be reenabled for expansion. Here we record whether any
349 // identifiers we lex as macro arguments correspond to disabled macros.
350 // If so, we mark the token as noexpand. This is a subtle aspect of
352 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
353 if (!MI->isEnabled())
354 Tok.setFlag(Token::DisableExpand);
356 ArgTokens.push_back(Tok);
359 // If this was an empty argument list foo(), don't add this as an empty
361 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
364 // If this is not a variadic macro, and too many args were specified, emit
366 if (!isVariadic && NumFixedArgsLeft == 0) {
367 if (ArgTokens.size() != ArgTokenStart)
368 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
370 // Emit the diagnostic at the macro name in case there is a missing ).
371 // Emitting it at the , could be far away from the macro name.
372 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
376 // Empty arguments are standard in C99 and supported as an extension in
378 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
379 Diag(Tok, diag::ext_empty_fnmacro_arg);
381 // Add a marker EOF token to the end of the token list for this argument.
384 EOFTok.setKind(tok::eof);
385 EOFTok.setLocation(Tok.getLocation());
387 ArgTokens.push_back(EOFTok);
389 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
393 // Okay, we either found the r_paren. Check to see if we parsed too few
395 unsigned MinArgsExpected = MI->getNumArgs();
397 // See MacroArgs instance var for description of this.
398 bool isVarargsElided = false;
400 if (NumActuals < MinArgsExpected) {
401 // There are several cases where too few arguments is ok, handle them now.
402 if (NumActuals == 0 && MinArgsExpected == 1) {
403 // #define A(X) or #define A(...) ---> A()
405 // If there is exactly one argument, and that argument is missing,
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).
408 isVarargsElided = MI->isVariadic();
409 } else if (MI->isVariadic() &&
410 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
411 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
412 // Varargs where the named vararg parameter is missing: ok as extension.
415 Diag(Tok, diag::ext_missing_varargs_arg);
417 // Remember this occurred, allowing us to elide the comma when used for
419 // #define A(x, foo...) blah(a, ## foo)
420 // #define B(x, ...) blah(a, ## __VA_ARGS__)
421 // #define C(...) blah(a, ## __VA_ARGS__)
423 isVarargsElided = true;
425 // Otherwise, emit the error.
426 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
430 // Add a marker EOF token to the end of the token list for this argument.
431 SourceLocation EndLoc = Tok.getLocation();
433 Tok.setKind(tok::eof);
434 Tok.setLocation(EndLoc);
436 ArgTokens.push_back(Tok);
438 // If we expect two arguments, add both as empty.
439 if (NumActuals == 0 && MinArgsExpected == 2)
440 ArgTokens.push_back(Tok);
442 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
443 // Emit the diagnostic at the macro name in case there is a missing ).
444 // Emitting it at the , could be far away from the macro name.
445 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
449 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
450 isVarargsElided, *this);
453 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
454 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
455 /// the identifier tokens inserted.
456 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
459 struct tm *TM = localtime(&TT);
461 static const char * const Months[] = {
462 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
466 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
471 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
472 DATELoc = TmpTok.getLocation();
474 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
475 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
476 TIMELoc = TmpTok.getLocation();
480 /// HasFeature - Return true if we recognize and implement the specified feature
481 /// specified by the identifier.
482 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
483 const LangOptions &LangOpts = PP.getLangOptions();
485 return llvm::StringSwitch<bool>(II->getName())
486 .Case("blocks", LangOpts.Blocks)
487 .Case("cxx_rtti", LangOpts.RTTI)
488 //.Case("cxx_lambdas", false)
489 //.Case("cxx_nullptr", false)
490 //.Case("cxx_concepts", false)
491 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
492 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
493 .Case("cxx_exceptions", LangOpts.Exceptions)
494 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
495 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
496 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
497 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
498 //.Case("cxx_rvalue_references", false)
499 .Case("attribute_overloadable", true)
500 //.Case("cxx_variadic_templates", false)
501 .Case("attribute_ext_vector_type", true)
502 .Case("attribute_analyzer_noreturn", true)
503 .Case("attribute_ns_returns_retained", true)
504 .Case("attribute_cf_returns_retained", true)
508 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
509 /// or '__has_include_next("path")' expression.
510 /// Returns true if successful.
511 static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
512 IdentifierInfo *II, Preprocessor &PP,
513 const DirectoryLookup *LookupFrom) {
514 SourceLocation LParenLoc;
517 PP.LexNonComment(Tok);
519 // Ensure we have a '('.
520 if (Tok.isNot(tok::l_paren)) {
521 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
525 // Save '(' location for possible missing ')' message.
526 LParenLoc = Tok.getLocation();
528 // Get the file name.
529 PP.getCurrentLexer()->LexIncludeFilename(Tok);
531 // Reserve a buffer to get the spelling.
532 llvm::SmallString<128> FilenameBuffer;
533 llvm::StringRef Filename;
535 switch (Tok.getKind()) {
537 // If the token kind is EOM, the error has already been diagnosed.
540 case tok::angle_string_literal:
541 case tok::string_literal: {
542 FilenameBuffer.resize(Tok.getLength());
543 const char *FilenameStart = &FilenameBuffer[0];
544 unsigned Len = PP.getSpelling(Tok, FilenameStart);
545 Filename = llvm::StringRef(FilenameStart, Len);
550 // This could be a <foo/bar.h> file coming from a macro expansion. In this
551 // case, glue the tokens together into FilenameBuffer and interpret those.
552 FilenameBuffer.push_back('<');
553 if (PP.ConcatenateIncludeName(FilenameBuffer))
554 return false; // Found <eom> but no ">"? Diagnostic already emitted.
555 Filename = FilenameBuffer.str();
558 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
562 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
563 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
565 if (Filename.empty())
568 // Search include directories.
569 const DirectoryLookup *CurDir;
570 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
572 // Get the result value. Result = true means the file exists.
576 PP.LexNonComment(Tok);
578 // Ensure we have a trailing ).
579 if (Tok.isNot(tok::r_paren)) {
580 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
581 PP.Diag(LParenLoc, diag::note_matching) << "(";
588 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
589 /// Returns true if successful.
590 static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
592 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
595 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
596 /// Returns true if successful.
597 static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
598 IdentifierInfo *II, Preprocessor &PP) {
599 // __has_include_next is like __has_include, except that we start
600 // searching after the current found directory. If we can't do this,
601 // issue a diagnostic.
602 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
603 if (PP.isInPrimaryFile()) {
605 PP.Diag(Tok, diag::pp_include_next_in_primary);
606 } else if (Lookup == 0) {
607 PP.Diag(Tok, diag::pp_include_next_absolute_path);
609 // Start looking up in the next directory.
613 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
616 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
617 /// as a builtin macro, handle it and return the next token as 'Tok'.
618 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
619 // Figure out which token this is.
620 IdentifierInfo *II = Tok.getIdentifierInfo();
621 assert(II && "Can't be a macro without id info!");
623 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
624 // lex the token after it.
625 if (II == Ident_Pragma)
626 return Handle_Pragma(Tok);
628 ++NumBuiltinMacroExpanded;
632 // Set up the return result.
633 Tok.setIdentifierInfo(0);
634 Tok.clearFlag(Token::NeedsCleaning);
636 if (II == Ident__LINE__) {
637 // C99 6.10.8: "__LINE__: The presumed line number (within the current
638 // source file) of the current source line (an integer constant)". This can
639 // be affected by #line.
640 SourceLocation Loc = Tok.getLocation();
642 // Advance to the location of the first _, this might not be the first byte
643 // of the token if it starts with an escaped newline.
644 Loc = AdvanceToTokenCharacter(Loc, 0);
646 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
647 // a macro instantiation. This doesn't matter for object-like macros, but
648 // can matter for a function-like macro that expands to contain __LINE__.
649 // Skip down through instantiation points until we find a file loc for the
650 // end of the instantiation history.
651 Loc = SourceMgr.getInstantiationRange(Loc).second;
652 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
654 // __LINE__ expands to a simple numeric value.
655 sprintf(TmpBuffer, "%u", PLoc.getLine());
656 Tok.setKind(tok::numeric_constant);
657 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
658 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
659 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
660 // character string literal)". This can be affected by #line.
661 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
663 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
664 // #include stack instead of the current file.
665 if (II == Ident__BASE_FILE__) {
666 SourceLocation NextLoc = PLoc.getIncludeLoc();
667 while (NextLoc.isValid()) {
668 PLoc = SourceMgr.getPresumedLoc(NextLoc);
669 NextLoc = PLoc.getIncludeLoc();
673 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
674 std::string FN = PLoc.getFilename();
675 FN = '"' + Lexer::Stringify(FN) + '"';
676 Tok.setKind(tok::string_literal);
677 CreateString(&FN[0], FN.size(), Tok, Tok.getLocation());
678 } else if (II == Ident__DATE__) {
679 if (!DATELoc.isValid())
680 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
681 Tok.setKind(tok::string_literal);
682 Tok.setLength(strlen("\"Mmm dd yyyy\""));
683 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
686 } else if (II == Ident__TIME__) {
687 if (!TIMELoc.isValid())
688 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
689 Tok.setKind(tok::string_literal);
690 Tok.setLength(strlen("\"hh:mm:ss\""));
691 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
694 } else if (II == Ident__INCLUDE_LEVEL__) {
695 // Compute the presumed include depth of this token. This can be affected
696 // by GNU line markers.
699 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
700 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
701 for (; PLoc.isValid(); ++Depth)
702 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
704 // __INCLUDE_LEVEL__ expands to a simple numeric value.
705 sprintf(TmpBuffer, "%u", Depth);
706 Tok.setKind(tok::numeric_constant);
707 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
708 } else if (II == Ident__TIMESTAMP__) {
709 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
710 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
712 // Get the file that we are lexing out of. If we're currently lexing from
713 // a macro, dig into the include stack.
714 const FileEntry *CurFile = 0;
715 PreprocessorLexer *TheLexer = getCurrentFileLexer();
718 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
722 time_t TT = CurFile->getModificationTime();
723 struct tm *TM = localtime(&TT);
724 Result = asctime(TM);
726 Result = "??? ??? ?? ??:??:?? ????\n";
729 unsigned Len = strlen(Result);
730 memcpy(TmpBuffer+1, Result, Len-1); // Copy string without the newline.
731 TmpBuffer[Len] = '"';
732 Tok.setKind(tok::string_literal);
733 CreateString(TmpBuffer, Len+1, Tok, Tok.getLocation());
734 } else if (II == Ident__COUNTER__) {
735 // __COUNTER__ expands to a simple numeric value.
736 sprintf(TmpBuffer, "%u", CounterValue++);
737 Tok.setKind(tok::numeric_constant);
738 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
739 } else if (II == Ident__has_feature ||
740 II == Ident__has_builtin) {
741 // The argument to these two builtins should be a parenthesized identifier.
742 SourceLocation StartLoc = Tok.getLocation();
744 bool IsValid = false;
745 IdentifierInfo *FeatureII = 0;
749 if (Tok.is(tok::l_paren)) {
750 // Read the identifier
752 if (Tok.is(tok::identifier)) {
753 FeatureII = Tok.getIdentifierInfo();
757 if (Tok.is(tok::r_paren))
764 Diag(StartLoc, diag::err_feature_check_malformed);
765 else if (II == Ident__has_builtin) {
766 // Check for a builtin is trivial.
767 Value = FeatureII->getBuiltinID() != 0;
769 assert(II == Ident__has_feature && "Must be feature check");
770 Value = HasFeature(*this, FeatureII);
773 sprintf(TmpBuffer, "%d", (int)Value);
774 Tok.setKind(tok::numeric_constant);
775 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
776 } else if (II == Ident__has_include ||
777 II == Ident__has_include_next) {
778 // The argument to these two builtins should be a parenthesized
779 // file name string literal using angle brackets (<>) or
780 // double-quotes ("").
783 if (II == Ident__has_include)
784 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
786 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
787 sprintf(TmpBuffer, "%d", (int)Value);
788 Tok.setKind(tok::numeric_constant);
789 CreateString(TmpBuffer, strlen(TmpBuffer), Tok, Tok.getLocation());
791 assert(0 && "Unknown identifier!");