PPMacroExpansion.cpp revision 203955
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 "llvm/Support/raw_ostream.h"
23#include <cstdio>
24#include <ctime>
25using namespace clang;
26
27/// setMacroInfo - Specify a macro for this identifier.
28///
29void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
30  if (MI) {
31    Macros[II] = MI;
32    II->setHasMacroDefinition(true);
33  } else if (II->hasMacroDefinition()) {
34    Macros.erase(II);
35    II->setHasMacroDefinition(false);
36  }
37}
38
39/// RegisterBuiltinMacro - Register the specified identifier in the identifier
40/// table and mark it as a builtin macro to be expanded.
41static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
42  // Get the identifier.
43  IdentifierInfo *Id = PP.getIdentifierInfo(Name);
44
45  // Mark it as being a macro that is builtin.
46  MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
47  MI->setIsBuiltinMacro();
48  PP.setMacroInfo(Id, MI);
49  return Id;
50}
51
52
53/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
54/// identifier table.
55void Preprocessor::RegisterBuiltinMacros() {
56  Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
57  Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
58  Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
59  Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
60  Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
61  Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
62
63  // GCC Extensions.
64  Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
65  Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
66  Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
67
68  // Clang Extensions.
69  Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
70  Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
71  Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
72  Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
73}
74
75/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
76/// in its expansion, currently expands to that token literally.
77static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
78                                          const IdentifierInfo *MacroIdent,
79                                          Preprocessor &PP) {
80  IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
81
82  // If the token isn't an identifier, it's always literally expanded.
83  if (II == 0) return true;
84
85  // If the identifier is a macro, and if that macro is enabled, it may be
86  // expanded so it's not a trivial expansion.
87  if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
88      // Fast expanding "#define X X" is ok, because X would be disabled.
89      II != MacroIdent)
90    return false;
91
92  // If this is an object-like macro invocation, it is safe to trivially expand
93  // it.
94  if (MI->isObjectLike()) return true;
95
96  // If this is a function-like macro invocation, it's safe to trivially expand
97  // as long as the identifier is not a macro argument.
98  for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
99       I != E; ++I)
100    if (*I == II)
101      return false;   // Identifier is a macro argument.
102
103  return true;
104}
105
106
107/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
108/// lexed is a '('.  If so, consume the token and return true, if not, this
109/// method should have no observable side-effect on the lexed tokens.
110bool Preprocessor::isNextPPTokenLParen() {
111  // Do some quick tests for rejection cases.
112  unsigned Val;
113  if (CurLexer)
114    Val = CurLexer->isNextPPTokenLParen();
115  else if (CurPTHLexer)
116    Val = CurPTHLexer->isNextPPTokenLParen();
117  else
118    Val = CurTokenLexer->isNextTokenLParen();
119
120  if (Val == 2) {
121    // We have run off the end.  If it's a source file we don't
122    // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
123    // macro stack.
124    if (CurPPLexer)
125      return false;
126    for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
127      IncludeStackInfo &Entry = IncludeMacroStack[i-1];
128      if (Entry.TheLexer)
129        Val = Entry.TheLexer->isNextPPTokenLParen();
130      else if (Entry.ThePTHLexer)
131        Val = Entry.ThePTHLexer->isNextPPTokenLParen();
132      else
133        Val = Entry.TheTokenLexer->isNextTokenLParen();
134
135      if (Val != 2)
136        break;
137
138      // Ran off the end of a source file?
139      if (Entry.ThePPLexer)
140        return false;
141    }
142  }
143
144  // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
145  // have found something that isn't a '(' or we found the end of the
146  // translation unit.  In either case, return false.
147  return Val == 1;
148}
149
150/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
151/// expanded as a macro, handle it and return the next token as 'Identifier'.
152bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
153                                                 MacroInfo *MI) {
154  if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
155
156  // If this is a macro expansion in the "#if !defined(x)" line for the file,
157  // then the macro could expand to different things in other contexts, we need
158  // to disable the optimization in this case.
159  if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
160
161  // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
162  if (MI->isBuiltinMacro()) {
163    ExpandBuiltinMacro(Identifier);
164    return false;
165  }
166
167  /// Args - If this is a function-like macro expansion, this contains,
168  /// for each macro argument, the list of tokens that were provided to the
169  /// invocation.
170  MacroArgs *Args = 0;
171
172  // Remember where the end of the instantiation occurred.  For an object-like
173  // macro, this is the identifier.  For a function-like macro, this is the ')'.
174  SourceLocation InstantiationEnd = Identifier.getLocation();
175
176  // If this is a function-like macro, read the arguments.
177  if (MI->isFunctionLike()) {
178    // C99 6.10.3p10: If the preprocessing token immediately after the the macro
179    // name isn't a '(', this macro should not be expanded.
180    if (!isNextPPTokenLParen())
181      return true;
182
183    // Remember that we are now parsing the arguments to a macro invocation.
184    // Preprocessor directives used inside macro arguments are not portable, and
185    // this enables the warning.
186    InMacroArgs = true;
187    Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
188
189    // Finished parsing args.
190    InMacroArgs = false;
191
192    // If there was an error parsing the arguments, bail out.
193    if (Args == 0) return false;
194
195    ++NumFnMacroExpanded;
196  } else {
197    ++NumMacroExpanded;
198  }
199
200  // Notice that this macro has been used.
201  MI->setIsUsed(true);
202
203  // If we started lexing a macro, enter the macro expansion body.
204
205  // If this macro expands to no tokens, don't bother to push it onto the
206  // expansion stack, only to take it right back off.
207  if (MI->getNumTokens() == 0) {
208    // No need for arg info.
209    if (Args) Args->destroy(*this);
210
211    // Ignore this macro use, just return the next token in the current
212    // buffer.
213    bool HadLeadingSpace = Identifier.hasLeadingSpace();
214    bool IsAtStartOfLine = Identifier.isAtStartOfLine();
215
216    Lex(Identifier);
217
218    // If the identifier isn't on some OTHER line, inherit the leading
219    // whitespace/first-on-a-line property of this token.  This handles
220    // stuff like "! XX," -> "! ," and "   XX," -> "    ,", when XX is
221    // empty.
222    if (!Identifier.isAtStartOfLine()) {
223      if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
224      if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
225    }
226    ++NumFastMacroExpanded;
227    return false;
228
229  } else if (MI->getNumTokens() == 1 &&
230             isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
231                                           *this)) {
232    // Otherwise, if this macro expands into a single trivially-expanded
233    // token: expand it now.  This handles common cases like
234    // "#define VAL 42".
235
236    // No need for arg info.
237    if (Args) Args->destroy(*this);
238
239    // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
240    // identifier to the expanded token.
241    bool isAtStartOfLine = Identifier.isAtStartOfLine();
242    bool hasLeadingSpace = Identifier.hasLeadingSpace();
243
244    // Remember where the token is instantiated.
245    SourceLocation InstantiateLoc = Identifier.getLocation();
246
247    // Replace the result token.
248    Identifier = MI->getReplacementToken(0);
249
250    // Restore the StartOfLine/LeadingSpace markers.
251    Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
252    Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
253
254    // Update the tokens location to include both its instantiation and physical
255    // locations.
256    SourceLocation Loc =
257      SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
258                                       InstantiationEnd,Identifier.getLength());
259    Identifier.setLocation(Loc);
260
261    // If this is #define X X, we must mark the result as unexpandible.
262    if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
263      if (getMacroInfo(NewII) == MI)
264        Identifier.setFlag(Token::DisableExpand);
265
266    // Since this is not an identifier token, it can't be macro expanded, so
267    // we're done.
268    ++NumFastMacroExpanded;
269    return false;
270  }
271
272  // Start expanding the macro.
273  EnterMacro(Identifier, InstantiationEnd, Args);
274
275  // Now that the macro is at the top of the include stack, ask the
276  // preprocessor to read the next token from it.
277  Lex(Identifier);
278  return false;
279}
280
281/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
282/// token is the '(' of the macro, this method is invoked to read all of the
283/// actual arguments specified for the macro invocation.  This returns null on
284/// error.
285MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
286                                                   MacroInfo *MI,
287                                                   SourceLocation &MacroEnd) {
288  // The number of fixed arguments to parse.
289  unsigned NumFixedArgsLeft = MI->getNumArgs();
290  bool isVariadic = MI->isVariadic();
291
292  // Outer loop, while there are more arguments, keep reading them.
293  Token Tok;
294
295  // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
296  // an argument value in a macro could expand to ',' or '(' or ')'.
297  LexUnexpandedToken(Tok);
298  assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
299
300  // ArgTokens - Build up a list of tokens that make up each argument.  Each
301  // argument is separated by an EOF token.  Use a SmallVector so we can avoid
302  // heap allocations in the common case.
303  llvm::SmallVector<Token, 64> ArgTokens;
304
305  unsigned NumActuals = 0;
306  while (Tok.isNot(tok::r_paren)) {
307    assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
308           "only expect argument separators here");
309
310    unsigned ArgTokenStart = ArgTokens.size();
311    SourceLocation ArgStartLoc = Tok.getLocation();
312
313    // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
314    // that we already consumed the first one.
315    unsigned NumParens = 0;
316
317    while (1) {
318      // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
319      // an argument value in a macro could expand to ',' or '(' or ')'.
320      LexUnexpandedToken(Tok);
321
322      if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
323        Diag(MacroName, diag::err_unterm_macro_invoc);
324        // Do not lose the EOF/EOM.  Return it to the client.
325        MacroName = Tok;
326        return 0;
327      } else if (Tok.is(tok::r_paren)) {
328        // If we found the ) token, the macro arg list is done.
329        if (NumParens-- == 0) {
330          MacroEnd = Tok.getLocation();
331          break;
332        }
333      } else if (Tok.is(tok::l_paren)) {
334        ++NumParens;
335      } else if (Tok.is(tok::comma) && NumParens == 0) {
336        // Comma ends this argument if there are more fixed arguments expected.
337        // However, if this is a variadic macro, and this is part of the
338        // variadic part, then the comma is just an argument token.
339        if (!isVariadic) break;
340        if (NumFixedArgsLeft > 1)
341          break;
342      } else if (Tok.is(tok::comment) && !KeepMacroComments) {
343        // If this is a comment token in the argument list and we're just in
344        // -C mode (not -CC mode), discard the comment.
345        continue;
346      } else if (Tok.getIdentifierInfo() != 0) {
347        // Reading macro arguments can cause macros that we are currently
348        // expanding from to be popped off the expansion stack.  Doing so causes
349        // them to be reenabled for expansion.  Here we record whether any
350        // identifiers we lex as macro arguments correspond to disabled macros.
351        // If so, we mark the token as noexpand.  This is a subtle aspect of
352        // C99 6.10.3.4p2.
353        if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
354          if (!MI->isEnabled())
355            Tok.setFlag(Token::DisableExpand);
356      }
357      ArgTokens.push_back(Tok);
358    }
359
360    // If this was an empty argument list foo(), don't add this as an empty
361    // argument.
362    if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
363      break;
364
365    // If this is not a variadic macro, and too many args were specified, emit
366    // an error.
367    if (!isVariadic && NumFixedArgsLeft == 0) {
368      if (ArgTokens.size() != ArgTokenStart)
369        ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
370
371      // Emit the diagnostic at the macro name in case there is a missing ).
372      // Emitting it at the , could be far away from the macro name.
373      Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
374      return 0;
375    }
376
377    // Empty arguments are standard in C99 and supported as an extension in
378    // other modes.
379    if (ArgTokens.size() == ArgTokenStart && !Features.C99)
380      Diag(Tok, diag::ext_empty_fnmacro_arg);
381
382    // Add a marker EOF token to the end of the token list for this argument.
383    Token EOFTok;
384    EOFTok.startToken();
385    EOFTok.setKind(tok::eof);
386    EOFTok.setLocation(Tok.getLocation());
387    EOFTok.setLength(0);
388    ArgTokens.push_back(EOFTok);
389    ++NumActuals;
390    assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
391    --NumFixedArgsLeft;
392  }
393
394  // Okay, we either found the r_paren.  Check to see if we parsed too few
395  // arguments.
396  unsigned MinArgsExpected = MI->getNumArgs();
397
398  // See MacroArgs instance var for description of this.
399  bool isVarargsElided = false;
400
401  if (NumActuals < MinArgsExpected) {
402    // There are several cases where too few arguments is ok, handle them now.
403    if (NumActuals == 0 && MinArgsExpected == 1) {
404      // #define A(X)  or  #define A(...)   ---> A()
405
406      // If there is exactly one argument, and that argument is missing,
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).
409      isVarargsElided = MI->isVariadic();
410    } else if (MI->isVariadic() &&
411               (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
412                (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
413      // Varargs where the named vararg parameter is missing: ok as extension.
414      // #define A(x, ...)
415      // A("blah")
416      Diag(Tok, diag::ext_missing_varargs_arg);
417
418      // Remember this occurred, allowing us to elide the comma when used for
419      // cases like:
420      //   #define A(x, foo...) blah(a, ## foo)
421      //   #define B(x, ...) blah(a, ## __VA_ARGS__)
422      //   #define C(...) blah(a, ## __VA_ARGS__)
423      //  A(x) B(x) C()
424      isVarargsElided = true;
425    } else {
426      // Otherwise, emit the error.
427      Diag(Tok, diag::err_too_few_args_in_macro_invoc);
428      return 0;
429    }
430
431    // Add a marker EOF token to the end of the token list for this argument.
432    SourceLocation EndLoc = Tok.getLocation();
433    Tok.startToken();
434    Tok.setKind(tok::eof);
435    Tok.setLocation(EndLoc);
436    Tok.setLength(0);
437    ArgTokens.push_back(Tok);
438
439    // If we expect two arguments, add both as empty.
440    if (NumActuals == 0 && MinArgsExpected == 2)
441      ArgTokens.push_back(Tok);
442
443  } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
444    // Emit the diagnostic at the macro name in case there is a missing ).
445    // Emitting it at the , could be far away from the macro name.
446    Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
447    return 0;
448  }
449
450  return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
451                           isVarargsElided, *this);
452}
453
454/// ComputeDATE_TIME - Compute the current time, enter it into the specified
455/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
456/// the identifier tokens inserted.
457static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
458                             Preprocessor &PP) {
459  time_t TT = time(0);
460  struct tm *TM = localtime(&TT);
461
462  static const char * const Months[] = {
463    "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
464  };
465
466  char TmpBuffer[100];
467  sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
468          TM->tm_year+1900);
469
470  Token TmpTok;
471  TmpTok.startToken();
472  PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
473  DATELoc = TmpTok.getLocation();
474
475  sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
476  PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
477  TIMELoc = TmpTok.getLocation();
478}
479
480
481/// HasFeature - Return true if we recognize and implement the specified feature
482/// specified by the identifier.
483static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
484  const LangOptions &LangOpts = PP.getLangOptions();
485
486  return llvm::StringSwitch<bool>(II->getName())
487           .Case("blocks", LangOpts.Blocks)
488           .Case("cxx_rtti", LangOpts.RTTI)
489         //.Case("cxx_lambdas", false)
490         //.Case("cxx_nullptr", false)
491         //.Case("cxx_concepts", false)
492           .Case("cxx_decltype", LangOpts.CPlusPlus0x)
493           .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
494           .Case("cxx_exceptions", LangOpts.Exceptions)
495           .Case("cxx_attributes", LangOpts.CPlusPlus0x)
496           .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
497           .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
498           .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
499         //.Case("cxx_rvalue_references", false)
500           .Case("attribute_overloadable", true)
501         //.Case("cxx_variadic_templates", false)
502           .Case("attribute_ext_vector_type", true)
503           .Case("attribute_analyzer_noreturn", true)
504           .Case("attribute_ns_returns_retained", true)
505           .Case("attribute_cf_returns_retained", true)
506           .Default(false);
507}
508
509/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
510/// or '__has_include_next("path")' expression.
511/// Returns true if successful.
512static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
513        IdentifierInfo *II, Preprocessor &PP,
514        const DirectoryLookup *LookupFrom) {
515  SourceLocation LParenLoc;
516
517  // Get '('.
518  PP.LexNonComment(Tok);
519
520  // Ensure we have a '('.
521  if (Tok.isNot(tok::l_paren)) {
522    PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
523    return false;
524  }
525
526  // Save '(' location for possible missing ')' message.
527  LParenLoc = Tok.getLocation();
528
529  // Get the file name.
530  PP.getCurrentLexer()->LexIncludeFilename(Tok);
531
532  // Reserve a buffer to get the spelling.
533  llvm::SmallString<128> FilenameBuffer;
534  llvm::StringRef Filename;
535
536  switch (Tok.getKind()) {
537  case tok::eom:
538    // If the token kind is EOM, the error has already been diagnosed.
539    return false;
540
541  case tok::angle_string_literal:
542  case tok::string_literal: {
543    FilenameBuffer.resize(Tok.getLength());
544    const char *FilenameStart = &FilenameBuffer[0];
545    unsigned Len = PP.getSpelling(Tok, FilenameStart);
546    Filename = llvm::StringRef(FilenameStart, Len);
547    break;
548  }
549
550  case tok::less:
551    // This could be a <foo/bar.h> file coming from a macro expansion.  In this
552    // case, glue the tokens together into FilenameBuffer and interpret those.
553    FilenameBuffer.push_back('<');
554    if (PP.ConcatenateIncludeName(FilenameBuffer))
555      return false;   // Found <eom> but no ">"?  Diagnostic already emitted.
556    Filename = FilenameBuffer.str();
557    break;
558  default:
559    PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
560    return false;
561  }
562
563  bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
564  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
565  // error.
566  if (Filename.empty())
567    return false;
568
569  // Search include directories.
570  const DirectoryLookup *CurDir;
571  const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
572
573  // Get the result value.  Result = true means the file exists.
574  Result = File != 0;
575
576  // Get ')'.
577  PP.LexNonComment(Tok);
578
579  // Ensure we have a trailing ).
580  if (Tok.isNot(tok::r_paren)) {
581    PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
582    PP.Diag(LParenLoc, diag::note_matching) << "(";
583    return false;
584  }
585
586  return true;
587}
588
589/// EvaluateHasInclude - Process a '__has_include("path")' expression.
590/// Returns true if successful.
591static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
592                               Preprocessor &PP) {
593  return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
594}
595
596/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
597/// Returns true if successful.
598static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
599                                   IdentifierInfo *II, Preprocessor &PP) {
600  // __has_include_next is like __has_include, except that we start
601  // searching after the current found directory.  If we can't do this,
602  // issue a diagnostic.
603  const DirectoryLookup *Lookup = PP.GetCurDirLookup();
604  if (PP.isInPrimaryFile()) {
605    Lookup = 0;
606    PP.Diag(Tok, diag::pp_include_next_in_primary);
607  } else if (Lookup == 0) {
608    PP.Diag(Tok, diag::pp_include_next_absolute_path);
609  } else {
610    // Start looking up in the next directory.
611    ++Lookup;
612  }
613
614  return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
615}
616
617/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
618/// as a builtin macro, handle it and return the next token as 'Tok'.
619void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
620  // Figure out which token this is.
621  IdentifierInfo *II = Tok.getIdentifierInfo();
622  assert(II && "Can't be a macro without id info!");
623
624  // If this is an _Pragma directive, expand it, invoke the pragma handler, then
625  // lex the token after it.
626  if (II == Ident_Pragma)
627    return Handle_Pragma(Tok);
628
629  ++NumBuiltinMacroExpanded;
630
631  llvm::SmallString<128> TmpBuffer;
632  llvm::raw_svector_ostream OS(TmpBuffer);
633
634  // Set up the return result.
635  Tok.setIdentifierInfo(0);
636  Tok.clearFlag(Token::NeedsCleaning);
637
638  if (II == Ident__LINE__) {
639    // C99 6.10.8: "__LINE__: The presumed line number (within the current
640    // source file) of the current source line (an integer constant)".  This can
641    // be affected by #line.
642    SourceLocation Loc = Tok.getLocation();
643
644    // Advance to the location of the first _, this might not be the first byte
645    // of the token if it starts with an escaped newline.
646    Loc = AdvanceToTokenCharacter(Loc, 0);
647
648    // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
649    // a macro instantiation.  This doesn't matter for object-like macros, but
650    // can matter for a function-like macro that expands to contain __LINE__.
651    // Skip down through instantiation points until we find a file loc for the
652    // end of the instantiation history.
653    Loc = SourceMgr.getInstantiationRange(Loc).second;
654    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
655
656    // __LINE__ expands to a simple numeric value.
657    OS << PLoc.getLine();
658    Tok.setKind(tok::numeric_constant);
659  } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
660    // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
661    // character string literal)". This can be affected by #line.
662    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
663
664    // __BASE_FILE__ is a GNU extension that returns the top of the presumed
665    // #include stack instead of the current file.
666    if (II == Ident__BASE_FILE__) {
667      SourceLocation NextLoc = PLoc.getIncludeLoc();
668      while (NextLoc.isValid()) {
669        PLoc = SourceMgr.getPresumedLoc(NextLoc);
670        NextLoc = PLoc.getIncludeLoc();
671      }
672    }
673
674    // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
675    llvm::SmallString<128> FN;
676    FN += PLoc.getFilename();
677    Lexer::Stringify(FN);
678    OS << '"' << FN.str() << '"';
679    Tok.setKind(tok::string_literal);
680  } else if (II == Ident__DATE__) {
681    if (!DATELoc.isValid())
682      ComputeDATE_TIME(DATELoc, TIMELoc, *this);
683    Tok.setKind(tok::string_literal);
684    Tok.setLength(strlen("\"Mmm dd yyyy\""));
685    Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
686                                                     Tok.getLocation(),
687                                                     Tok.getLength()));
688    return;
689  } else if (II == Ident__TIME__) {
690    if (!TIMELoc.isValid())
691      ComputeDATE_TIME(DATELoc, TIMELoc, *this);
692    Tok.setKind(tok::string_literal);
693    Tok.setLength(strlen("\"hh:mm:ss\""));
694    Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
695                                                     Tok.getLocation(),
696                                                     Tok.getLength()));
697    return;
698  } else if (II == Ident__INCLUDE_LEVEL__) {
699    // Compute the presumed include depth of this token.  This can be affected
700    // by GNU line markers.
701    unsigned Depth = 0;
702
703    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
704    PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
705    for (; PLoc.isValid(); ++Depth)
706      PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
707
708    // __INCLUDE_LEVEL__ expands to a simple numeric value.
709    OS << Depth;
710    Tok.setKind(tok::numeric_constant);
711  } else if (II == Ident__TIMESTAMP__) {
712    // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
713    // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
714
715    // Get the file that we are lexing out of.  If we're currently lexing from
716    // a macro, dig into the include stack.
717    const FileEntry *CurFile = 0;
718    PreprocessorLexer *TheLexer = getCurrentFileLexer();
719
720    if (TheLexer)
721      CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
722
723    const char *Result;
724    if (CurFile) {
725      time_t TT = CurFile->getModificationTime();
726      struct tm *TM = localtime(&TT);
727      Result = asctime(TM);
728    } else {
729      Result = "??? ??? ?? ??:??:?? ????\n";
730    }
731    // Surround the string with " and strip the trailing newline.
732    OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
733    Tok.setKind(tok::string_literal);
734  } else if (II == Ident__COUNTER__) {
735    // __COUNTER__ expands to a simple numeric value.
736    OS << CounterValue++;
737    Tok.setKind(tok::numeric_constant);
738  } else if (II == Ident__has_feature ||
739             II == Ident__has_builtin) {
740    // The argument to these two builtins should be a parenthesized identifier.
741    SourceLocation StartLoc = Tok.getLocation();
742
743    bool IsValid = false;
744    IdentifierInfo *FeatureII = 0;
745
746    // Read the '('.
747    Lex(Tok);
748    if (Tok.is(tok::l_paren)) {
749      // Read the identifier
750      Lex(Tok);
751      if (Tok.is(tok::identifier)) {
752        FeatureII = Tok.getIdentifierInfo();
753
754        // Read the ')'.
755        Lex(Tok);
756        if (Tok.is(tok::r_paren))
757          IsValid = true;
758      }
759    }
760
761    bool Value = false;
762    if (!IsValid)
763      Diag(StartLoc, diag::err_feature_check_malformed);
764    else if (II == Ident__has_builtin) {
765      // Check for a builtin is trivial.
766      Value = FeatureII->getBuiltinID() != 0;
767    } else {
768      assert(II == Ident__has_feature && "Must be feature check");
769      Value = HasFeature(*this, FeatureII);
770    }
771
772    OS << (int)Value;
773    Tok.setKind(tok::numeric_constant);
774  } else if (II == Ident__has_include ||
775             II == Ident__has_include_next) {
776    // The argument to these two builtins should be a parenthesized
777    // file name string literal using angle brackets (<>) or
778    // double-quotes ("").
779    bool Value = false;
780    bool IsValid;
781    if (II == Ident__has_include)
782      IsValid = EvaluateHasInclude(Value, Tok, II, *this);
783    else
784      IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
785    OS << (int)Value;
786    Tok.setKind(tok::numeric_constant);
787  } else {
788    assert(0 && "Unknown identifier!");
789  }
790  CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
791}
792