]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Lex/PPMacroExpansion.cpp
Update clang to r94309.
[FreeBSD/FreeBSD.git] / lib / Lex / PPMacroExpansion.cpp
1 //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the top level handling of macro expasion for the
11 // preprocessor.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Lex/Preprocessor.h"
16 #include "MacroArgs.h"
17 #include "clang/Lex/MacroInfo.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include <cstdio>
23 #include <ctime>
24 using namespace clang;
25
26 /// setMacroInfo - Specify a macro for this identifier.
27 ///
28 void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
29   if (MI) {
30     Macros[II] = MI;
31     II->setHasMacroDefinition(true);
32   } else if (II->hasMacroDefinition()) {
33     Macros.erase(II);
34     II->setHasMacroDefinition(false);
35   }
36 }
37
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);
43
44   // Mark it as being a macro that is builtin.
45   MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
46   MI->setIsBuiltinMacro();
47   PP.setMacroInfo(Id, MI);
48   return Id;
49 }
50
51
52 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
53 /// identifier table.
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");
61
62   // GCC Extensions.
63   Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
64   Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
65   Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
66
67   // Clang Extensions.
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");
72 }
73
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,
78                                           Preprocessor &PP) {
79   IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
80
81   // If the token isn't an identifier, it's always literally expanded.
82   if (II == 0) return true;
83
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.
88       II != MacroIdent)
89     return false;
90
91   // If this is an object-like macro invocation, it is safe to trivially expand
92   // it.
93   if (MI->isObjectLike()) return true;
94
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();
98        I != E; ++I)
99     if (*I == II)
100       return false;   // Identifier is a macro argument.
101
102   return true;
103 }
104
105
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.
111   unsigned Val;
112   if (CurLexer)
113     Val = CurLexer->isNextPPTokenLParen();
114   else if (CurPTHLexer)
115     Val = CurPTHLexer->isNextPPTokenLParen();
116   else
117     Val = CurTokenLexer->isNextTokenLParen();
118
119   if (Val == 2) {
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
122     // macro stack.
123     if (CurPPLexer)
124       return false;
125     for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
126       IncludeStackInfo &Entry = IncludeMacroStack[i-1];
127       if (Entry.TheLexer)
128         Val = Entry.TheLexer->isNextPPTokenLParen();
129       else if (Entry.ThePTHLexer)
130         Val = Entry.ThePTHLexer->isNextPPTokenLParen();
131       else
132         Val = Entry.TheTokenLexer->isNextTokenLParen();
133
134       if (Val != 2)
135         break;
136
137       // Ran off the end of a source file?
138       if (Entry.ThePPLexer)
139         return false;
140     }
141   }
142
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.
146   return Val == 1;
147 }
148
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,
152                                                  MacroInfo *MI) {
153   if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
154
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();
159
160   // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
161   if (MI->isBuiltinMacro()) {
162     ExpandBuiltinMacro(Identifier);
163     return false;
164   }
165
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
168   /// invocation.
169   MacroArgs *Args = 0;
170
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();
174
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())
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;
186     Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
187
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(*this);
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(),
230                                            *this)) {
231     // Otherwise, if this macro expands into a single trivially-expanded
232     // token: expand it now.  This handles common cases like
233     // "#define VAL 42".
234
235     // No need for arg info.
236     if (Args) Args->destroy(*this);
237
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();
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
253     // Update the tokens location to include both its instantiation and physical
254     // locations.
255     SourceLocation Loc =
256       SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
257                                        InstantiationEnd,Identifier.getLength());
258     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.
272   EnterMacro(Identifier, InstantiationEnd, Args);
273
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" 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
283 /// error.
284 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
285                                                    MacroInfo *MI,
286                                                    SourceLocation &MacroEnd) {
287   // The number of fixed arguments to parse.
288   unsigned NumFixedArgsLeft = MI->getNumArgs();
289   bool isVariadic = MI->isVariadic();
290
291   // Outer loop, while there are more arguments, keep reading them.
292   Token Tok;
293
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?");
298
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;
303
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");
308
309     unsigned ArgTokenStart = ArgTokens.size();
310     SourceLocation ArgStartLoc = Tok.getLocation();
311
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;
315
316     while (1) {
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);
320
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.
324         MacroName = Tok;
325         return 0;
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();
330           break;
331         }
332       } else if (Tok.is(tok::l_paren)) {
333         ++NumParens;
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)
340           break;
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.
344         continue;
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
351         // C99 6.10.3.4p2.
352         if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
353           if (!MI->isEnabled())
354             Tok.setFlag(Token::DisableExpand);
355       }
356       ArgTokens.push_back(Tok);
357     }
358
359     // If this was an empty argument list foo(), don't add this as an empty
360     // argument.
361     if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
362       break;
363
364     // If this is not a variadic macro, and too many args were specified, emit
365     // an error.
366     if (!isVariadic && NumFixedArgsLeft == 0) {
367       if (ArgTokens.size() != ArgTokenStart)
368         ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
369
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);
373       return 0;
374     }
375
376     // Empty arguments are standard in C99 and supported as an extension in
377     // other modes.
378     if (ArgTokens.size() == ArgTokenStart && !Features.C99)
379       Diag(Tok, diag::ext_empty_fnmacro_arg);
380
381     // Add a marker EOF token to the end of the token list for this argument.
382     Token EOFTok;
383     EOFTok.startToken();
384     EOFTok.setKind(tok::eof);
385     EOFTok.setLocation(Tok.getLocation());
386     EOFTok.setLength(0);
387     ArgTokens.push_back(EOFTok);
388     ++NumActuals;
389     assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
390     --NumFixedArgsLeft;
391   }
392
393   // Okay, we either found the r_paren.  Check to see if we parsed too few
394   // arguments.
395   unsigned MinArgsExpected = MI->getNumArgs();
396
397   // See MacroArgs instance var for description of this.
398   bool isVarargsElided = false;
399
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()
404
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.
413       // #define A(x, ...)
414       // A("blah")
415       Diag(Tok, diag::ext_missing_varargs_arg);
416
417       // Remember this occurred, allowing us to elide the comma when used for
418       // cases like:
419       //   #define A(x, foo...) blah(a, ## foo)
420       //   #define B(x, ...) blah(a, ## __VA_ARGS__)
421       //   #define C(...) blah(a, ## __VA_ARGS__)
422       //  A(x) B(x) C()
423       isVarargsElided = true;
424     } else {
425       // Otherwise, emit the error.
426       Diag(Tok, diag::err_too_few_args_in_macro_invoc);
427       return 0;
428     }
429
430     // Add a marker EOF token to the end of the token list for this argument.
431     SourceLocation EndLoc = Tok.getLocation();
432     Tok.startToken();
433     Tok.setKind(tok::eof);
434     Tok.setLocation(EndLoc);
435     Tok.setLength(0);
436     ArgTokens.push_back(Tok);
437
438     // If we expect two arguments, add both as empty.
439     if (NumActuals == 0 && MinArgsExpected == 2)
440       ArgTokens.push_back(Tok);
441
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);
446     return 0;
447   }
448
449   return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
450                            isVarargsElided, *this);
451 }
452
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,
457                              Preprocessor &PP) {
458   time_t TT = time(0);
459   struct tm *TM = localtime(&TT);
460
461   static const char * const Months[] = {
462     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
463   };
464
465   char TmpBuffer[100];
466   sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
467           TM->tm_year+1900);
468
469   Token TmpTok;
470   TmpTok.startToken();
471   PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
472   DATELoc = TmpTok.getLocation();
473
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();
477 }
478
479
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();
484
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)
505            .Default(false);
506 }
507
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;
515
516   // Get '('.
517   PP.LexNonComment(Tok);
518
519   // Ensure we have a '('.
520   if (Tok.isNot(tok::l_paren)) {
521     PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
522     return false;
523   }
524
525   // Save '(' location for possible missing ')' message.
526   LParenLoc = Tok.getLocation();
527
528   // Get the file name.
529   PP.getCurrentLexer()->LexIncludeFilename(Tok);
530
531   // Reserve a buffer to get the spelling.
532   llvm::SmallString<128> FilenameBuffer;
533   llvm::StringRef Filename;
534
535   switch (Tok.getKind()) {
536   case tok::eom:
537     // If the token kind is EOM, the error has already been diagnosed.
538     return false;
539
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);
546     break;
547   }
548
549   case tok::less:
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();
556     break;
557   default:
558     PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
559     return false;
560   }
561
562   bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
563   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
564   // error.
565   if (Filename.empty())
566     return false;
567
568   // Search include directories.
569   const DirectoryLookup *CurDir;
570   const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
571
572   // Get the result value.  Result = true means the file exists.
573   Result = File != 0;
574
575   // Get ')'.
576   PP.LexNonComment(Tok);
577
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) << "(";
582     return false;
583   }
584
585   return true;
586 }
587
588 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
589 /// Returns true if successful.
590 static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
591                                Preprocessor &PP) {
592   return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
593 }
594
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()) {
604     Lookup = 0;
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);
608   } else {
609     // Start looking up in the next directory.
610     ++Lookup;
611   }
612
613   return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
614 }
615
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!");
622
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);
627
628   ++NumBuiltinMacroExpanded;
629
630   char TmpBuffer[100];
631
632   // Set up the return result.
633   Tok.setIdentifierInfo(0);
634   Tok.clearFlag(Token::NeedsCleaning);
635
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();
641
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);
645
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);
653
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());
662
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();
670       }
671     }
672
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(),
684                                                      Tok.getLocation(),
685                                                      Tok.getLength()));
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(),
692                                                      Tok.getLocation(),
693                                                      Tok.getLength()));
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.
697     unsigned Depth = 0;
698
699     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
700     PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
701     for (; PLoc.isValid(); ++Depth)
702       PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
703
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.
711
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();
716
717     if (TheLexer)
718       CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
719
720     const char *Result;
721     if (CurFile) {
722       time_t TT = CurFile->getModificationTime();
723       struct tm *TM = localtime(&TT);
724       Result = asctime(TM);
725     } else {
726       Result = "??? ??? ?? ??:??:?? ????\n";
727     }
728     TmpBuffer[0] = '"';
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();
743
744     bool IsValid = false;
745     IdentifierInfo *FeatureII = 0;
746
747     // Read the '('.
748     Lex(Tok);
749     if (Tok.is(tok::l_paren)) {
750       // Read the identifier
751       Lex(Tok);
752       if (Tok.is(tok::identifier)) {
753         FeatureII = Tok.getIdentifierInfo();
754
755         // Read the ')'.
756         Lex(Tok);
757         if (Tok.is(tok::r_paren))
758           IsValid = true;
759       }
760     }
761
762     bool Value = false;
763     if (!IsValid)
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;
768     } else {
769       assert(II == Ident__has_feature && "Must be feature check");
770       Value = HasFeature(*this, FeatureII);
771     }
772
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 ("").
781     bool Value = false;
782     bool IsValid;
783     if (II == Ident__has_include)
784       IsValid = EvaluateHasInclude(Value, Tok, II, *this);
785     else
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());
790   } else {
791     assert(0 && "Unknown identifier!");
792   }
793 }