PPDirectives.cpp revision 10285d9113c14d1e523f86a55b193eb752638ea5
1//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
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 # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
15#include "clang/Lex/LiteralSupport.h"
16#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/LexDiagnostic.h"
19#include "clang/Lex/CodeCompletionHandler.h"
20#include "clang/Lex/ModuleLoader.h"
21#include "clang/Lex/Pragma.h"
22#include "clang/Basic/FileManager.h"
23#include "clang/Basic/SourceManager.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/Support/ErrorHandling.h"
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// Utility Methods for Preprocessor Directive Handling.
30//===----------------------------------------------------------------------===//
31
32MacroInfo *Preprocessor::AllocateMacroInfo() {
33  MacroInfoChain *MIChain;
34
35  if (MICache) {
36    MIChain = MICache;
37    MICache = MICache->Next;
38  }
39  else {
40    MIChain = BP.Allocate<MacroInfoChain>();
41  }
42
43  MIChain->Next = MIChainHead;
44  MIChain->Prev = 0;
45  if (MIChainHead)
46    MIChainHead->Prev = MIChain;
47  MIChainHead = MIChain;
48
49  return &(MIChain->MI);
50}
51
52MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
53  MacroInfo *MI = AllocateMacroInfo();
54  new (MI) MacroInfo(L);
55  return MI;
56}
57
58MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
59  MacroInfo *MI = AllocateMacroInfo();
60  new (MI) MacroInfo(MacroToClone, BP);
61  return MI;
62}
63
64/// ReleaseMacroInfo - Release the specified MacroInfo.  This memory will
65///  be reused for allocating new MacroInfo objects.
66void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
67  MacroInfoChain *MIChain = (MacroInfoChain*) MI;
68  if (MacroInfoChain *Prev = MIChain->Prev) {
69    MacroInfoChain *Next = MIChain->Next;
70    Prev->Next = Next;
71    if (Next)
72      Next->Prev = Prev;
73  }
74  else {
75    assert(MIChainHead == MIChain);
76    MIChainHead = MIChain->Next;
77    MIChainHead->Prev = 0;
78  }
79  MIChain->Next = MICache;
80  MICache = MIChain;
81
82  MI->Destroy();
83}
84
85/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
86/// current line until the tok::eod token is found.
87void Preprocessor::DiscardUntilEndOfDirective() {
88  Token Tmp;
89  do {
90    LexUnexpandedToken(Tmp);
91    assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
92  } while (Tmp.isNot(tok::eod));
93}
94
95/// ReadMacroName - Lex and validate a macro name, which occurs after a
96/// #define or #undef.  This sets the token kind to eod and discards the rest
97/// of the macro line if the macro name is invalid.  isDefineUndef is 1 if
98/// this is due to a a #define, 2 if #undef directive, 0 if it is something
99/// else (e.g. #ifdef).
100void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
101  // Read the token, don't allow macro expansion on it.
102  LexUnexpandedToken(MacroNameTok);
103
104  if (MacroNameTok.is(tok::code_completion)) {
105    if (CodeComplete)
106      CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
107    setCodeCompletionReached();
108    LexUnexpandedToken(MacroNameTok);
109  }
110
111  // Missing macro name?
112  if (MacroNameTok.is(tok::eod)) {
113    Diag(MacroNameTok, diag::err_pp_missing_macro_name);
114    return;
115  }
116
117  IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
118  if (II == 0) {
119    bool Invalid = false;
120    std::string Spelling = getSpelling(MacroNameTok, &Invalid);
121    if (Invalid)
122      return;
123
124    const IdentifierInfo &Info = Identifiers.get(Spelling);
125
126    // Allow #defining |and| and friends in microsoft mode.
127    if (Info.isCPlusPlusOperatorKeyword() && getLangOptions().MicrosoftMode) {
128      MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
129      return;
130    }
131
132    if (Info.isCPlusPlusOperatorKeyword())
133      // C++ 2.5p2: Alternative tokens behave the same as its primary token
134      // except for their spellings.
135      Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
136    else
137      Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
138    // Fall through on error.
139  } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
140    // Error if defining "defined": C99 6.10.8.4.
141    Diag(MacroNameTok, diag::err_defined_macro_name);
142  } else if (isDefineUndef && II->hasMacroDefinition() &&
143             getMacroInfo(II)->isBuiltinMacro()) {
144    // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
145    if (isDefineUndef == 1)
146      Diag(MacroNameTok, diag::pp_redef_builtin_macro);
147    else
148      Diag(MacroNameTok, diag::pp_undef_builtin_macro);
149  } else {
150    // Okay, we got a good identifier node.  Return it.
151    return;
152  }
153
154  // Invalid macro name, read and discard the rest of the line.  Then set the
155  // token kind to tok::eod.
156  MacroNameTok.setKind(tok::eod);
157  return DiscardUntilEndOfDirective();
158}
159
160/// CheckEndOfDirective - Ensure that the next token is a tok::eod token.  If
161/// not, emit a diagnostic and consume up until the eod.  If EnableMacros is
162/// true, then we consider macros that expand to zero tokens as being ok.
163void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
164  Token Tmp;
165  // Lex unexpanded tokens for most directives: macros might expand to zero
166  // tokens, causing us to miss diagnosing invalid lines.  Some directives (like
167  // #line) allow empty macros.
168  if (EnableMacros)
169    Lex(Tmp);
170  else
171    LexUnexpandedToken(Tmp);
172
173  // There should be no tokens after the directive, but we allow them as an
174  // extension.
175  while (Tmp.is(tok::comment))  // Skip comments in -C mode.
176    LexUnexpandedToken(Tmp);
177
178  if (Tmp.isNot(tok::eod)) {
179    // Add a fixit in GNU/C99/C++ mode.  Don't offer a fixit for strict-C89,
180    // or if this is a macro-style preprocessing directive, because it is more
181    // trouble than it is worth to insert /**/ and check that there is no /**/
182    // in the range also.
183    FixItHint Hint;
184    if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
185        !CurTokenLexer)
186      Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
187    Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
188    DiscardUntilEndOfDirective();
189  }
190}
191
192
193
194/// SkipExcludedConditionalBlock - We just read a #if or related directive and
195/// decided that the subsequent tokens are in the #if'd out portion of the
196/// file.  Lex the rest of the file, until we see an #endif.  If
197/// FoundNonSkipPortion is true, then we have already emitted code for part of
198/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
199/// is true, then #else directives are ok, if not, then we have already seen one
200/// so a #else directive is a duplicate.  When this returns, the caller can lex
201/// the first valid token.
202void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
203                                                bool FoundNonSkipPortion,
204                                                bool FoundElse,
205                                                SourceLocation ElseLoc) {
206  ++NumSkipped;
207  assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
208
209  CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
210                                 FoundNonSkipPortion, FoundElse);
211
212  if (CurPTHLexer) {
213    PTHSkipExcludedConditionalBlock();
214    return;
215  }
216
217  // Enter raw mode to disable identifier lookup (and thus macro expansion),
218  // disabling warnings, etc.
219  CurPPLexer->LexingRawMode = true;
220  Token Tok;
221  while (1) {
222    CurLexer->Lex(Tok);
223
224    if (Tok.is(tok::code_completion)) {
225      if (CodeComplete)
226        CodeComplete->CodeCompleteInConditionalExclusion();
227      setCodeCompletionReached();
228      continue;
229    }
230
231    // If this is the end of the buffer, we have an error.
232    if (Tok.is(tok::eof)) {
233      // Emit errors for each unterminated conditional on the stack, including
234      // the current one.
235      while (!CurPPLexer->ConditionalStack.empty()) {
236        if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
237          Diag(CurPPLexer->ConditionalStack.back().IfLoc,
238               diag::err_pp_unterminated_conditional);
239        CurPPLexer->ConditionalStack.pop_back();
240      }
241
242      // Just return and let the caller lex after this #include.
243      break;
244    }
245
246    // If this token is not a preprocessor directive, just skip it.
247    if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
248      continue;
249
250    // We just parsed a # character at the start of a line, so we're in
251    // directive mode.  Tell the lexer this so any newlines we see will be
252    // converted into an EOD token (this terminates the macro).
253    CurPPLexer->ParsingPreprocessorDirective = true;
254    if (CurLexer) CurLexer->SetCommentRetentionState(false);
255
256
257    // Read the next token, the directive flavor.
258    LexUnexpandedToken(Tok);
259
260    // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
261    // something bogus), skip it.
262    if (Tok.isNot(tok::raw_identifier)) {
263      CurPPLexer->ParsingPreprocessorDirective = false;
264      // Restore comment saving mode.
265      if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
266      continue;
267    }
268
269    // If the first letter isn't i or e, it isn't intesting to us.  We know that
270    // this is safe in the face of spelling differences, because there is no way
271    // to spell an i/e in a strange way that is another letter.  Skipping this
272    // allows us to avoid looking up the identifier info for #define/#undef and
273    // other common directives.
274    const char *RawCharData = Tok.getRawIdentifierData();
275
276    char FirstChar = RawCharData[0];
277    if (FirstChar >= 'a' && FirstChar <= 'z' &&
278        FirstChar != 'i' && FirstChar != 'e') {
279      CurPPLexer->ParsingPreprocessorDirective = false;
280      // Restore comment saving mode.
281      if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
282      continue;
283    }
284
285    // Get the identifier name without trigraphs or embedded newlines.  Note
286    // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
287    // when skipping.
288    char DirectiveBuf[20];
289    StringRef Directive;
290    if (!Tok.needsCleaning() && Tok.getLength() < 20) {
291      Directive = StringRef(RawCharData, Tok.getLength());
292    } else {
293      std::string DirectiveStr = getSpelling(Tok);
294      unsigned IdLen = DirectiveStr.size();
295      if (IdLen >= 20) {
296        CurPPLexer->ParsingPreprocessorDirective = false;
297        // Restore comment saving mode.
298        if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
299        continue;
300      }
301      memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
302      Directive = StringRef(DirectiveBuf, IdLen);
303    }
304
305    if (Directive.startswith("if")) {
306      StringRef Sub = Directive.substr(2);
307      if (Sub.empty() ||   // "if"
308          Sub == "def" ||   // "ifdef"
309          Sub == "ndef") {  // "ifndef"
310        // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
311        // bother parsing the condition.
312        DiscardUntilEndOfDirective();
313        CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
314                                       /*foundnonskip*/false,
315                                       /*foundelse*/false);
316
317        if (Callbacks)
318          Callbacks->Endif();
319      }
320    } else if (Directive[0] == 'e') {
321      StringRef Sub = Directive.substr(1);
322      if (Sub == "ndif") {  // "endif"
323        CheckEndOfDirective("endif");
324        PPConditionalInfo CondInfo;
325        CondInfo.WasSkipping = true; // Silence bogus warning.
326        bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
327        (void)InCond;  // Silence warning in no-asserts mode.
328        assert(!InCond && "Can't be skipping if not in a conditional!");
329
330        // If we popped the outermost skipping block, we're done skipping!
331        if (!CondInfo.WasSkipping)
332          break;
333      } else if (Sub == "lse") { // "else".
334        // #else directive in a skipping conditional.  If not in some other
335        // skipping conditional, and if #else hasn't already been seen, enter it
336        // as a non-skipping conditional.
337        PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
338
339        // If this is a #else with a #else before it, report the error.
340        if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
341
342        // Note that we've seen a #else in this conditional.
343        CondInfo.FoundElse = true;
344
345        if (Callbacks)
346          Callbacks->Else();
347
348        // If the conditional is at the top level, and the #if block wasn't
349        // entered, enter the #else block now.
350        if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
351          CondInfo.FoundNonSkip = true;
352          CheckEndOfDirective("else");
353          break;
354        } else {
355          DiscardUntilEndOfDirective();  // C99 6.10p4.
356        }
357      } else if (Sub == "lif") {  // "elif".
358        PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
359
360        bool ShouldEnter;
361        const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
362        // If this is in a skipping block or if we're already handled this #if
363        // block, don't bother parsing the condition.
364        if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
365          DiscardUntilEndOfDirective();
366          ShouldEnter = false;
367        } else {
368          // Restore the value of LexingRawMode so that identifiers are
369          // looked up, etc, inside the #elif expression.
370          assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
371          CurPPLexer->LexingRawMode = false;
372          IdentifierInfo *IfNDefMacro = 0;
373          ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
374          CurPPLexer->LexingRawMode = true;
375        }
376        const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
377
378        // If this is a #elif with a #else before it, report the error.
379        if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
380
381        if (Callbacks)
382          Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
383
384        // If this condition is true, enter it!
385        if (ShouldEnter) {
386          CondInfo.FoundNonSkip = true;
387          break;
388        }
389      }
390    }
391
392    CurPPLexer->ParsingPreprocessorDirective = false;
393    // Restore comment saving mode.
394    if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
395  }
396
397  // Finally, if we are out of the conditional (saw an #endif or ran off the end
398  // of the file, just stop skipping and return to lexing whatever came after
399  // the #if block.
400  CurPPLexer->LexingRawMode = false;
401
402  if (Callbacks) {
403    SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
404    Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
405  }
406}
407
408void Preprocessor::PTHSkipExcludedConditionalBlock() {
409
410  while (1) {
411    assert(CurPTHLexer);
412    assert(CurPTHLexer->LexingRawMode == false);
413
414    // Skip to the next '#else', '#elif', or #endif.
415    if (CurPTHLexer->SkipBlock()) {
416      // We have reached an #endif.  Both the '#' and 'endif' tokens
417      // have been consumed by the PTHLexer.  Just pop off the condition level.
418      PPConditionalInfo CondInfo;
419      bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
420      (void)InCond;  // Silence warning in no-asserts mode.
421      assert(!InCond && "Can't be skipping if not in a conditional!");
422      break;
423    }
424
425    // We have reached a '#else' or '#elif'.  Lex the next token to get
426    // the directive flavor.
427    Token Tok;
428    LexUnexpandedToken(Tok);
429
430    // We can actually look up the IdentifierInfo here since we aren't in
431    // raw mode.
432    tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
433
434    if (K == tok::pp_else) {
435      // #else: Enter the else condition.  We aren't in a nested condition
436      //  since we skip those. We're always in the one matching the last
437      //  blocked we skipped.
438      PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
439      // Note that we've seen a #else in this conditional.
440      CondInfo.FoundElse = true;
441
442      // If the #if block wasn't entered then enter the #else block now.
443      if (!CondInfo.FoundNonSkip) {
444        CondInfo.FoundNonSkip = true;
445
446        // Scan until the eod token.
447        CurPTHLexer->ParsingPreprocessorDirective = true;
448        DiscardUntilEndOfDirective();
449        CurPTHLexer->ParsingPreprocessorDirective = false;
450
451        break;
452      }
453
454      // Otherwise skip this block.
455      continue;
456    }
457
458    assert(K == tok::pp_elif);
459    PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
460
461    // If this is a #elif with a #else before it, report the error.
462    if (CondInfo.FoundElse)
463      Diag(Tok, diag::pp_err_elif_after_else);
464
465    // If this is in a skipping block or if we're already handled this #if
466    // block, don't bother parsing the condition.  We just skip this block.
467    if (CondInfo.FoundNonSkip)
468      continue;
469
470    // Evaluate the condition of the #elif.
471    IdentifierInfo *IfNDefMacro = 0;
472    CurPTHLexer->ParsingPreprocessorDirective = true;
473    bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
474    CurPTHLexer->ParsingPreprocessorDirective = false;
475
476    // If this condition is true, enter it!
477    if (ShouldEnter) {
478      CondInfo.FoundNonSkip = true;
479      break;
480    }
481
482    // Otherwise, skip this block and go to the next one.
483    continue;
484  }
485}
486
487/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
488/// return null on failure.  isAngled indicates whether the file reference is
489/// for system #include's or not (i.e. using <> instead of "").
490const FileEntry *Preprocessor::LookupFile(
491    StringRef Filename,
492    bool isAngled,
493    const DirectoryLookup *FromDir,
494    const DirectoryLookup *&CurDir,
495    SmallVectorImpl<char> *SearchPath,
496    SmallVectorImpl<char> *RelativePath,
497    Module **SuggestedModule,
498    bool SkipCache) {
499  // If the header lookup mechanism may be relative to the current file, pass in
500  // info about where the current file is.
501  const FileEntry *CurFileEnt = 0;
502  if (!FromDir) {
503    FileID FID = getCurrentFileLexer()->getFileID();
504    CurFileEnt = SourceMgr.getFileEntryForID(FID);
505
506    // If there is no file entry associated with this file, it must be the
507    // predefines buffer.  Any other file is not lexed with a normal lexer, so
508    // it won't be scanned for preprocessor directives.   If we have the
509    // predefines buffer, resolve #include references (which come from the
510    // -include command line argument) as if they came from the main file, this
511    // affects file lookup etc.
512    if (CurFileEnt == 0) {
513      FID = SourceMgr.getMainFileID();
514      CurFileEnt = SourceMgr.getFileEntryForID(FID);
515    }
516  }
517
518  // Do a standard file entry lookup.
519  CurDir = CurDirLookup;
520  const FileEntry *FE = HeaderInfo.LookupFile(
521      Filename, isAngled, FromDir, CurDir, CurFileEnt,
522      SearchPath, RelativePath, SuggestedModule, SkipCache);
523  if (FE) return FE;
524
525  // Otherwise, see if this is a subframework header.  If so, this is relative
526  // to one of the headers on the #include stack.  Walk the list of the current
527  // headers on the #include stack and pass them to HeaderInfo.
528  // FIXME: SuggestedModule!
529  if (IsFileLexer()) {
530    if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
531      if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
532                                                    SearchPath, RelativePath)))
533        return FE;
534  }
535
536  for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
537    IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
538    if (IsFileLexer(ISEntry)) {
539      if ((CurFileEnt =
540           SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
541        if ((FE = HeaderInfo.LookupSubframeworkHeader(
542                Filename, CurFileEnt, SearchPath, RelativePath)))
543          return FE;
544    }
545  }
546
547  // Otherwise, we really couldn't find the file.
548  return 0;
549}
550
551
552//===----------------------------------------------------------------------===//
553// Preprocessor Directive Handling.
554//===----------------------------------------------------------------------===//
555
556/// HandleDirective - This callback is invoked when the lexer sees a # token
557/// at the start of a line.  This consumes the directive, modifies the
558/// lexer/preprocessor state, and advances the lexer(s) so that the next token
559/// read is the correct one.
560void Preprocessor::HandleDirective(Token &Result) {
561  // FIXME: Traditional: # with whitespace before it not recognized by K&R?
562
563  // We just parsed a # character at the start of a line, so we're in directive
564  // mode.  Tell the lexer this so any newlines we see will be converted into an
565  // EOD token (which terminates the directive).
566  CurPPLexer->ParsingPreprocessorDirective = true;
567
568  ++NumDirectives;
569
570  // We are about to read a token.  For the multiple-include optimization FA to
571  // work, we have to remember if we had read any tokens *before* this
572  // pp-directive.
573  bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
574
575  // Save the '#' token in case we need to return it later.
576  Token SavedHash = Result;
577
578  // Read the next token, the directive flavor.  This isn't expanded due to
579  // C99 6.10.3p8.
580  LexUnexpandedToken(Result);
581
582  // C99 6.10.3p11: Is this preprocessor directive in macro invocation?  e.g.:
583  //   #define A(x) #x
584  //   A(abc
585  //     #warning blah
586  //   def)
587  // If so, the user is relying on undefined behavior, emit a diagnostic. Do
588  // not support this for #include-like directives, since that can result in
589  // terrible diagnostics, and does not work in GCC.
590  if (InMacroArgs) {
591    if (IdentifierInfo *II = Result.getIdentifierInfo()) {
592      switch (II->getPPKeywordID()) {
593      case tok::pp_include:
594      case tok::pp_import:
595      case tok::pp_include_next:
596      case tok::pp___include_macros:
597        Diag(Result, diag::err_embedded_include) << II->getName();
598        DiscardUntilEndOfDirective();
599        return;
600      default:
601        break;
602      }
603    }
604    Diag(Result, diag::ext_embedded_directive);
605  }
606
607TryAgain:
608  switch (Result.getKind()) {
609  case tok::eod:
610    return;   // null directive.
611  case tok::comment:
612    // Handle stuff like "# /*foo*/ define X" in -E -C mode.
613    LexUnexpandedToken(Result);
614    goto TryAgain;
615  case tok::code_completion:
616    if (CodeComplete)
617      CodeComplete->CodeCompleteDirective(
618                                    CurPPLexer->getConditionalStackDepth() > 0);
619    setCodeCompletionReached();
620    return;
621  case tok::numeric_constant:  // # 7  GNU line marker directive.
622    if (getLangOptions().AsmPreprocessor)
623      break;  // # 4 is not a preprocessor directive in .S files.
624    return HandleDigitDirective(Result);
625  default:
626    IdentifierInfo *II = Result.getIdentifierInfo();
627    if (II == 0) break;  // Not an identifier.
628
629    // Ask what the preprocessor keyword ID is.
630    switch (II->getPPKeywordID()) {
631    default: break;
632    // C99 6.10.1 - Conditional Inclusion.
633    case tok::pp_if:
634      return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
635    case tok::pp_ifdef:
636      return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
637    case tok::pp_ifndef:
638      return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
639    case tok::pp_elif:
640      return HandleElifDirective(Result);
641    case tok::pp_else:
642      return HandleElseDirective(Result);
643    case tok::pp_endif:
644      return HandleEndifDirective(Result);
645
646    // C99 6.10.2 - Source File Inclusion.
647    case tok::pp_include:
648      // Handle #include.
649      return HandleIncludeDirective(SavedHash.getLocation(), Result);
650    case tok::pp___include_macros:
651      // Handle -imacros.
652      return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
653
654    // C99 6.10.3 - Macro Replacement.
655    case tok::pp_define:
656      return HandleDefineDirective(Result);
657    case tok::pp_undef:
658      return HandleUndefDirective(Result);
659
660    // C99 6.10.4 - Line Control.
661    case tok::pp_line:
662      return HandleLineDirective(Result);
663
664    // C99 6.10.5 - Error Directive.
665    case tok::pp_error:
666      return HandleUserDiagnosticDirective(Result, false);
667
668    // C99 6.10.6 - Pragma Directive.
669    case tok::pp_pragma:
670      return HandlePragmaDirective(PIK_HashPragma);
671
672    // GNU Extensions.
673    case tok::pp_import:
674      return HandleImportDirective(SavedHash.getLocation(), Result);
675    case tok::pp_include_next:
676      return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
677
678    case tok::pp_warning:
679      Diag(Result, diag::ext_pp_warning_directive);
680      return HandleUserDiagnosticDirective(Result, true);
681    case tok::pp_ident:
682      return HandleIdentSCCSDirective(Result);
683    case tok::pp_sccs:
684      return HandleIdentSCCSDirective(Result);
685    case tok::pp_assert:
686      //isExtension = true;  // FIXME: implement #assert
687      break;
688    case tok::pp_unassert:
689      //isExtension = true;  // FIXME: implement #unassert
690      break;
691
692    case tok::pp___public_macro:
693      if (getLangOptions().Modules)
694        return HandleMacroPublicDirective(Result);
695      break;
696
697    case tok::pp___private_macro:
698      if (getLangOptions().Modules)
699        return HandleMacroPrivateDirective(Result);
700      break;
701    }
702    break;
703  }
704
705  // If this is a .S file, treat unknown # directives as non-preprocessor
706  // directives.  This is important because # may be a comment or introduce
707  // various pseudo-ops.  Just return the # token and push back the following
708  // token to be lexed next time.
709  if (getLangOptions().AsmPreprocessor) {
710    Token *Toks = new Token[2];
711    // Return the # and the token after it.
712    Toks[0] = SavedHash;
713    Toks[1] = Result;
714
715    // If the second token is a hashhash token, then we need to translate it to
716    // unknown so the token lexer doesn't try to perform token pasting.
717    if (Result.is(tok::hashhash))
718      Toks[1].setKind(tok::unknown);
719
720    // Enter this token stream so that we re-lex the tokens.  Make sure to
721    // enable macro expansion, in case the token after the # is an identifier
722    // that is expanded.
723    EnterTokenStream(Toks, 2, false, true);
724    return;
725  }
726
727  // If we reached here, the preprocessing token is not valid!
728  Diag(Result, diag::err_pp_invalid_directive);
729
730  // Read the rest of the PP line.
731  DiscardUntilEndOfDirective();
732
733  // Okay, we're done parsing the directive.
734}
735
736/// GetLineValue - Convert a numeric token into an unsigned value, emitting
737/// Diagnostic DiagID if it is invalid, and returning the value in Val.
738static bool GetLineValue(Token &DigitTok, unsigned &Val,
739                         unsigned DiagID, Preprocessor &PP) {
740  if (DigitTok.isNot(tok::numeric_constant)) {
741    PP.Diag(DigitTok, DiagID);
742
743    if (DigitTok.isNot(tok::eod))
744      PP.DiscardUntilEndOfDirective();
745    return true;
746  }
747
748  SmallString<64> IntegerBuffer;
749  IntegerBuffer.resize(DigitTok.getLength());
750  const char *DigitTokBegin = &IntegerBuffer[0];
751  bool Invalid = false;
752  unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
753  if (Invalid)
754    return true;
755
756  // Verify that we have a simple digit-sequence, and compute the value.  This
757  // is always a simple digit string computed in decimal, so we do this manually
758  // here.
759  Val = 0;
760  for (unsigned i = 0; i != ActualLength; ++i) {
761    if (!isdigit(DigitTokBegin[i])) {
762      PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
763              diag::err_pp_line_digit_sequence);
764      PP.DiscardUntilEndOfDirective();
765      return true;
766    }
767
768    unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
769    if (NextVal < Val) { // overflow.
770      PP.Diag(DigitTok, DiagID);
771      PP.DiscardUntilEndOfDirective();
772      return true;
773    }
774    Val = NextVal;
775  }
776
777  // Reject 0, this is needed both by #line numbers and flags.
778  if (Val == 0) {
779    PP.Diag(DigitTok, DiagID);
780    PP.DiscardUntilEndOfDirective();
781    return true;
782  }
783
784  if (DigitTokBegin[0] == '0')
785    PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
786
787  return false;
788}
789
790/// HandleLineDirective - Handle #line directive: C99 6.10.4.  The two
791/// acceptable forms are:
792///   # line digit-sequence
793///   # line digit-sequence "s-char-sequence"
794void Preprocessor::HandleLineDirective(Token &Tok) {
795  // Read the line # and string argument.  Per C99 6.10.4p5, these tokens are
796  // expanded.
797  Token DigitTok;
798  Lex(DigitTok);
799
800  // Validate the number and convert it to an unsigned.
801  unsigned LineNo;
802  if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
803    return;
804
805  // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
806  // number greater than 2147483647".  C90 requires that the line # be <= 32767.
807  unsigned LineLimit = 32768U;
808  if (Features.C99 || Features.CPlusPlus0x)
809    LineLimit = 2147483648U;
810  if (LineNo >= LineLimit)
811    Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
812  else if (Features.CPlusPlus0x && LineNo >= 32768U)
813    Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
814
815  int FilenameID = -1;
816  Token StrTok;
817  Lex(StrTok);
818
819  // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
820  // string followed by eod.
821  if (StrTok.is(tok::eod))
822    ; // ok
823  else if (StrTok.isNot(tok::string_literal)) {
824    Diag(StrTok, diag::err_pp_line_invalid_filename);
825    DiscardUntilEndOfDirective();
826    return;
827  } else {
828    // Parse and validate the string, converting it into a unique ID.
829    StringLiteralParser Literal(&StrTok, 1, *this);
830    assert(Literal.isAscii() && "Didn't allow wide strings in");
831    if (Literal.hadError)
832      return DiscardUntilEndOfDirective();
833    if (Literal.Pascal) {
834      Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
835      return DiscardUntilEndOfDirective();
836    }
837    FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
838
839    // Verify that there is nothing after the string, other than EOD.  Because
840    // of C99 6.10.4p5, macros that expand to empty tokens are ok.
841    CheckEndOfDirective("line", true);
842  }
843
844  SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
845
846  if (Callbacks)
847    Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
848                           PPCallbacks::RenameFile,
849                           SrcMgr::C_User);
850}
851
852/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
853/// marker directive.
854static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
855                                bool &IsSystemHeader, bool &IsExternCHeader,
856                                Preprocessor &PP) {
857  unsigned FlagVal;
858  Token FlagTok;
859  PP.Lex(FlagTok);
860  if (FlagTok.is(tok::eod)) return false;
861  if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
862    return true;
863
864  if (FlagVal == 1) {
865    IsFileEntry = true;
866
867    PP.Lex(FlagTok);
868    if (FlagTok.is(tok::eod)) return false;
869    if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
870      return true;
871  } else if (FlagVal == 2) {
872    IsFileExit = true;
873
874    SourceManager &SM = PP.getSourceManager();
875    // If we are leaving the current presumed file, check to make sure the
876    // presumed include stack isn't empty!
877    FileID CurFileID =
878      SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
879    PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
880    if (PLoc.isInvalid())
881      return true;
882
883    // If there is no include loc (main file) or if the include loc is in a
884    // different physical file, then we aren't in a "1" line marker flag region.
885    SourceLocation IncLoc = PLoc.getIncludeLoc();
886    if (IncLoc.isInvalid() ||
887        SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
888      PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
889      PP.DiscardUntilEndOfDirective();
890      return true;
891    }
892
893    PP.Lex(FlagTok);
894    if (FlagTok.is(tok::eod)) return false;
895    if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
896      return true;
897  }
898
899  // We must have 3 if there are still flags.
900  if (FlagVal != 3) {
901    PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
902    PP.DiscardUntilEndOfDirective();
903    return true;
904  }
905
906  IsSystemHeader = true;
907
908  PP.Lex(FlagTok);
909  if (FlagTok.is(tok::eod)) return false;
910  if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
911    return true;
912
913  // We must have 4 if there is yet another flag.
914  if (FlagVal != 4) {
915    PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
916    PP.DiscardUntilEndOfDirective();
917    return true;
918  }
919
920  IsExternCHeader = true;
921
922  PP.Lex(FlagTok);
923  if (FlagTok.is(tok::eod)) return false;
924
925  // There are no more valid flags here.
926  PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
927  PP.DiscardUntilEndOfDirective();
928  return true;
929}
930
931/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
932/// one of the following forms:
933///
934///     # 42
935///     # 42 "file" ('1' | '2')?
936///     # 42 "file" ('1' | '2')? '3' '4'?
937///
938void Preprocessor::HandleDigitDirective(Token &DigitTok) {
939  // Validate the number and convert it to an unsigned.  GNU does not have a
940  // line # limit other than it fit in 32-bits.
941  unsigned LineNo;
942  if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
943                   *this))
944    return;
945
946  Token StrTok;
947  Lex(StrTok);
948
949  bool IsFileEntry = false, IsFileExit = false;
950  bool IsSystemHeader = false, IsExternCHeader = false;
951  int FilenameID = -1;
952
953  // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
954  // string followed by eod.
955  if (StrTok.is(tok::eod))
956    ; // ok
957  else if (StrTok.isNot(tok::string_literal)) {
958    Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
959    return DiscardUntilEndOfDirective();
960  } else {
961    // Parse and validate the string, converting it into a unique ID.
962    StringLiteralParser Literal(&StrTok, 1, *this);
963    assert(Literal.isAscii() && "Didn't allow wide strings in");
964    if (Literal.hadError)
965      return DiscardUntilEndOfDirective();
966    if (Literal.Pascal) {
967      Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
968      return DiscardUntilEndOfDirective();
969    }
970    FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
971
972    // If a filename was present, read any flags that are present.
973    if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
974                            IsSystemHeader, IsExternCHeader, *this))
975      return;
976  }
977
978  // Create a line note with this information.
979  SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
980                        IsFileEntry, IsFileExit,
981                        IsSystemHeader, IsExternCHeader);
982
983  // If the preprocessor has callbacks installed, notify them of the #line
984  // change.  This is used so that the line marker comes out in -E mode for
985  // example.
986  if (Callbacks) {
987    PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
988    if (IsFileEntry)
989      Reason = PPCallbacks::EnterFile;
990    else if (IsFileExit)
991      Reason = PPCallbacks::ExitFile;
992    SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
993    if (IsExternCHeader)
994      FileKind = SrcMgr::C_ExternCSystem;
995    else if (IsSystemHeader)
996      FileKind = SrcMgr::C_System;
997
998    Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
999  }
1000}
1001
1002
1003/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1004///
1005void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
1006                                                 bool isWarning) {
1007  // PTH doesn't emit #warning or #error directives.
1008  if (CurPTHLexer)
1009    return CurPTHLexer->DiscardToEndOfLine();
1010
1011  // Read the rest of the line raw.  We do this because we don't want macros
1012  // to be expanded and we don't require that the tokens be valid preprocessing
1013  // tokens.  For example, this is allowed: "#warning `   'foo".  GCC does
1014  // collapse multiple consequtive white space between tokens, but this isn't
1015  // specified by the standard.
1016  std::string Message = CurLexer->ReadToEndOfLine();
1017
1018  // Find the first non-whitespace character, so that we can make the
1019  // diagnostic more succinct.
1020  StringRef Msg(Message);
1021  size_t i = Msg.find_first_not_of(' ');
1022  if (i < Msg.size())
1023    Msg = Msg.substr(i);
1024
1025  if (isWarning)
1026    Diag(Tok, diag::pp_hash_warning) << Msg;
1027  else
1028    Diag(Tok, diag::err_pp_hash_error) << Msg;
1029}
1030
1031/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1032///
1033void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1034  // Yes, this directive is an extension.
1035  Diag(Tok, diag::ext_pp_ident_directive);
1036
1037  // Read the string argument.
1038  Token StrTok;
1039  Lex(StrTok);
1040
1041  // If the token kind isn't a string, it's a malformed directive.
1042  if (StrTok.isNot(tok::string_literal) &&
1043      StrTok.isNot(tok::wide_string_literal)) {
1044    Diag(StrTok, diag::err_pp_malformed_ident);
1045    if (StrTok.isNot(tok::eod))
1046      DiscardUntilEndOfDirective();
1047    return;
1048  }
1049
1050  // Verify that there is nothing after the string, other than EOD.
1051  CheckEndOfDirective("ident");
1052
1053  if (Callbacks) {
1054    bool Invalid = false;
1055    std::string Str = getSpelling(StrTok, &Invalid);
1056    if (!Invalid)
1057      Callbacks->Ident(Tok.getLocation(), Str);
1058  }
1059}
1060
1061/// \brief Handle a #public directive.
1062void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
1063  Token MacroNameTok;
1064  ReadMacroName(MacroNameTok, 2);
1065
1066  // Error reading macro name?  If so, diagnostic already issued.
1067  if (MacroNameTok.is(tok::eod))
1068    return;
1069
1070  // Check to see if this is the last token on the #__public_macro line.
1071  CheckEndOfDirective("__public_macro");
1072
1073  // Okay, we finally have a valid identifier to undef.
1074  MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1075
1076  // If the macro is not defined, this is an error.
1077  if (MI == 0) {
1078    Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1079      << MacroNameTok.getIdentifierInfo();
1080    return;
1081  }
1082
1083  // Note that this macro has now been exported.
1084  MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1085
1086  // If this macro definition came from a PCH file, mark it
1087  // as having changed since serialization.
1088  if (MI->isFromAST())
1089    MI->setChangedAfterLoad();
1090}
1091
1092/// \brief Handle a #private directive.
1093void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1094  Token MacroNameTok;
1095  ReadMacroName(MacroNameTok, 2);
1096
1097  // Error reading macro name?  If so, diagnostic already issued.
1098  if (MacroNameTok.is(tok::eod))
1099    return;
1100
1101  // Check to see if this is the last token on the #__private_macro line.
1102  CheckEndOfDirective("__private_macro");
1103
1104  // Okay, we finally have a valid identifier to undef.
1105  MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1106
1107  // If the macro is not defined, this is an error.
1108  if (MI == 0) {
1109    Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1110      << MacroNameTok.getIdentifierInfo();
1111    return;
1112  }
1113
1114  // Note that this macro has now been marked private.
1115  MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
1116
1117  // If this macro definition came from a PCH file, mark it
1118  // as having changed since serialization.
1119  if (MI->isFromAST())
1120    MI->setChangedAfterLoad();
1121}
1122
1123//===----------------------------------------------------------------------===//
1124// Preprocessor Include Directive Handling.
1125//===----------------------------------------------------------------------===//
1126
1127/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1128/// checked and spelled filename, e.g. as an operand of #include. This returns
1129/// true if the input filename was in <>'s or false if it were in ""'s.  The
1130/// caller is expected to provide a buffer that is large enough to hold the
1131/// spelling of the filename, but is also expected to handle the case when
1132/// this method decides to use a different buffer.
1133bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1134                                              StringRef &Buffer) {
1135  // Get the text form of the filename.
1136  assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1137
1138  // Make sure the filename is <x> or "x".
1139  bool isAngled;
1140  if (Buffer[0] == '<') {
1141    if (Buffer.back() != '>') {
1142      Diag(Loc, diag::err_pp_expects_filename);
1143      Buffer = StringRef();
1144      return true;
1145    }
1146    isAngled = true;
1147  } else if (Buffer[0] == '"') {
1148    if (Buffer.back() != '"') {
1149      Diag(Loc, diag::err_pp_expects_filename);
1150      Buffer = StringRef();
1151      return true;
1152    }
1153    isAngled = false;
1154  } else {
1155    Diag(Loc, diag::err_pp_expects_filename);
1156    Buffer = StringRef();
1157    return true;
1158  }
1159
1160  // Diagnose #include "" as invalid.
1161  if (Buffer.size() <= 2) {
1162    Diag(Loc, diag::err_pp_empty_filename);
1163    Buffer = StringRef();
1164    return true;
1165  }
1166
1167  // Skip the brackets.
1168  Buffer = Buffer.substr(1, Buffer.size()-2);
1169  return isAngled;
1170}
1171
1172/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1173/// from a macro as multiple tokens, which need to be glued together.  This
1174/// occurs for code like:
1175///    #define FOO <a/b.h>
1176///    #include FOO
1177/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1178///
1179/// This code concatenates and consumes tokens up to the '>' token.  It returns
1180/// false if the > was found, otherwise it returns true if it finds and consumes
1181/// the EOD marker.
1182bool Preprocessor::ConcatenateIncludeName(
1183                                        SmallString<128> &FilenameBuffer,
1184                                          SourceLocation &End) {
1185  Token CurTok;
1186
1187  Lex(CurTok);
1188  while (CurTok.isNot(tok::eod)) {
1189    End = CurTok.getLocation();
1190
1191    // FIXME: Provide code completion for #includes.
1192    if (CurTok.is(tok::code_completion)) {
1193      setCodeCompletionReached();
1194      Lex(CurTok);
1195      continue;
1196    }
1197
1198    // Append the spelling of this token to the buffer. If there was a space
1199    // before it, add it now.
1200    if (CurTok.hasLeadingSpace())
1201      FilenameBuffer.push_back(' ');
1202
1203    // Get the spelling of the token, directly into FilenameBuffer if possible.
1204    unsigned PreAppendSize = FilenameBuffer.size();
1205    FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1206
1207    const char *BufPtr = &FilenameBuffer[PreAppendSize];
1208    unsigned ActualLen = getSpelling(CurTok, BufPtr);
1209
1210    // If the token was spelled somewhere else, copy it into FilenameBuffer.
1211    if (BufPtr != &FilenameBuffer[PreAppendSize])
1212      memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1213
1214    // Resize FilenameBuffer to the correct size.
1215    if (CurTok.getLength() != ActualLen)
1216      FilenameBuffer.resize(PreAppendSize+ActualLen);
1217
1218    // If we found the '>' marker, return success.
1219    if (CurTok.is(tok::greater))
1220      return false;
1221
1222    Lex(CurTok);
1223  }
1224
1225  // If we hit the eod marker, emit an error and return true so that the caller
1226  // knows the EOD has been read.
1227  Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1228  return true;
1229}
1230
1231/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1232/// file to be included from the lexer, then include it!  This is a common
1233/// routine with functionality shared between #include, #include_next and
1234/// #import.  LookupFrom is set when this is a #include_next directive, it
1235/// specifies the file to start searching from.
1236void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1237                                          Token &IncludeTok,
1238                                          const DirectoryLookup *LookupFrom,
1239                                          bool isImport) {
1240
1241  Token FilenameTok;
1242  CurPPLexer->LexIncludeFilename(FilenameTok);
1243
1244  // Reserve a buffer to get the spelling.
1245  SmallString<128> FilenameBuffer;
1246  StringRef Filename;
1247  SourceLocation End;
1248  SourceLocation CharEnd; // the end of this directive, in characters
1249
1250  switch (FilenameTok.getKind()) {
1251  case tok::eod:
1252    // If the token kind is EOD, the error has already been diagnosed.
1253    return;
1254
1255  case tok::angle_string_literal:
1256  case tok::string_literal:
1257    Filename = getSpelling(FilenameTok, FilenameBuffer);
1258    End = FilenameTok.getLocation();
1259    CharEnd = End.getLocWithOffset(Filename.size());
1260    break;
1261
1262  case tok::less:
1263    // This could be a <foo/bar.h> file coming from a macro expansion.  In this
1264    // case, glue the tokens together into FilenameBuffer and interpret those.
1265    FilenameBuffer.push_back('<');
1266    if (ConcatenateIncludeName(FilenameBuffer, End))
1267      return;   // Found <eod> but no ">"?  Diagnostic already emitted.
1268    Filename = FilenameBuffer.str();
1269    CharEnd = getLocForEndOfToken(End);
1270    break;
1271  default:
1272    Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1273    DiscardUntilEndOfDirective();
1274    return;
1275  }
1276
1277  bool isAngled =
1278    GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1279  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1280  // error.
1281  if (Filename.empty()) {
1282    DiscardUntilEndOfDirective();
1283    return;
1284  }
1285
1286  // Verify that there is nothing after the filename, other than EOD.  Note that
1287  // we allow macros that expand to nothing after the filename, because this
1288  // falls into the category of "#include pp-tokens new-line" specified in
1289  // C99 6.10.2p4.
1290  CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1291
1292  // Check that we don't have infinite #include recursion.
1293  if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1294    Diag(FilenameTok, diag::err_pp_include_too_deep);
1295    return;
1296  }
1297
1298  // Complain about attempts to #include files in an audit pragma.
1299  if (PragmaARCCFCodeAuditedLoc.isValid()) {
1300    Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1301    Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1302
1303    // Immediately leave the pragma.
1304    PragmaARCCFCodeAuditedLoc = SourceLocation();
1305  }
1306
1307  // Search include directories.
1308  const DirectoryLookup *CurDir;
1309  SmallString<1024> SearchPath;
1310  SmallString<1024> RelativePath;
1311  // We get the raw path only if we have 'Callbacks' to which we later pass
1312  // the path.
1313  Module *SuggestedModule = 0;
1314  const FileEntry *File = LookupFile(
1315      Filename, isAngled, LookupFrom, CurDir,
1316      Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
1317      getLangOptions().Modules? &SuggestedModule : 0);
1318
1319  if (Callbacks) {
1320    if (!File) {
1321      // Give the clients a chance to recover.
1322      SmallString<128> RecoveryPath;
1323      if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1324        if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1325          // Add the recovery path to the list of search paths.
1326          DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1327          HeaderInfo.AddSearchPath(DL, isAngled);
1328
1329          // Try the lookup again, skipping the cache.
1330          File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
1331                            getLangOptions().Modules? &SuggestedModule : 0,
1332                            /*SkipCache*/true);
1333        }
1334      }
1335    }
1336
1337    // Notify the callback object that we've seen an inclusion directive.
1338    Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1339                                  End, SearchPath, RelativePath);
1340  }
1341
1342  if (File == 0) {
1343    if (!SuppressIncludeNotFoundError)
1344      Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1345    return;
1346  }
1347
1348  // If we are supposed to import a module rather than including the header,
1349  // do so now.
1350  if (SuggestedModule) {
1351    // Compute the module access path corresponding to this module.
1352    // FIXME: Should we have a second loadModule() overload to avoid this
1353    // extra lookup step?
1354    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1355    for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
1356      Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1357                                    FilenameTok.getLocation()));
1358    std::reverse(Path.begin(), Path.end());
1359
1360    // Warn that we're replacing the include/import with a module import.
1361    SmallString<128> PathString;
1362    for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1363      if (I)
1364        PathString += '.';
1365      PathString += Path[I].first->getName();
1366    }
1367    int IncludeKind = 0;
1368
1369    switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1370    case tok::pp_include:
1371      IncludeKind = 0;
1372      break;
1373
1374    case tok::pp_import:
1375      IncludeKind = 1;
1376      break;
1377
1378    case tok::pp_include_next:
1379      IncludeKind = 2;
1380      break;
1381
1382    case tok::pp___include_macros:
1383      IncludeKind = 3;
1384      break;
1385
1386    default:
1387      llvm_unreachable("unknown include directive kind");
1388    }
1389
1390    // Determine whether we are actually building the module that this
1391    // include directive maps to.
1392    bool BuildingImportedModule
1393      = Path[0].first->getName() == getLangOptions().CurrentModule;
1394
1395    if (!BuildingImportedModule && getLangOptions().ObjC2) {
1396      // If we're not building the imported module, warn that we're going
1397      // to automatically turn this inclusion directive into a module import.
1398      // We only do this in Objective-C, where we have a module-import syntax.
1399      CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1400                                   /*IsTokenRange=*/false);
1401      Diag(HashLoc, diag::warn_auto_module_import)
1402        << IncludeKind << PathString
1403        << FixItHint::CreateReplacement(ReplaceRange,
1404             "@import " + PathString.str().str() + ";");
1405    }
1406
1407    // Load the module.
1408    // If this was an #__include_macros directive, only make macros visible.
1409    Module::NameVisibilityKind Visibility
1410      = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
1411    Module *Imported
1412      = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1413                                   /*IsIncludeDirective=*/true);
1414
1415    // If this header isn't part of the module we're building, we're done.
1416    if (!BuildingImportedModule && Imported)
1417      return;
1418  }
1419
1420  // The #included file will be considered to be a system header if either it is
1421  // in a system include directory, or if the #includer is a system include
1422  // header.
1423  SrcMgr::CharacteristicKind FileCharacter =
1424    std::max(HeaderInfo.getFileDirFlavor(File),
1425             SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
1426
1427  // Ask HeaderInfo if we should enter this #include file.  If not, #including
1428  // this file will have no effect.
1429  if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1430    if (Callbacks)
1431      Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
1432    return;
1433  }
1434
1435  // Look up the file, create a File ID for it.
1436  FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1437                                      FileCharacter);
1438  assert(!FID.isInvalid() && "Expected valid file ID");
1439
1440  // Finally, if all is good, enter the new file!
1441  EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
1442}
1443
1444/// HandleIncludeNextDirective - Implements #include_next.
1445///
1446void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1447                                              Token &IncludeNextTok) {
1448  Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1449
1450  // #include_next is like #include, except that we start searching after
1451  // the current found directory.  If we can't do this, issue a
1452  // diagnostic.
1453  const DirectoryLookup *Lookup = CurDirLookup;
1454  if (isInPrimaryFile()) {
1455    Lookup = 0;
1456    Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1457  } else if (Lookup == 0) {
1458    Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1459  } else {
1460    // Start looking up in the next directory.
1461    ++Lookup;
1462  }
1463
1464  return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
1465}
1466
1467/// HandleImportDirective - Implements #import.
1468///
1469void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1470                                         Token &ImportTok) {
1471  if (!Features.ObjC1)  // #import is standard for ObjC.
1472    Diag(ImportTok, diag::ext_pp_import_directive);
1473
1474  return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
1475}
1476
1477/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1478/// pseudo directive in the predefines buffer.  This handles it by sucking all
1479/// tokens through the preprocessor and discarding them (only keeping the side
1480/// effects on the preprocessor).
1481void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1482                                                Token &IncludeMacrosTok) {
1483  // This directive should only occur in the predefines buffer.  If not, emit an
1484  // error and reject it.
1485  SourceLocation Loc = IncludeMacrosTok.getLocation();
1486  if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1487    Diag(IncludeMacrosTok.getLocation(),
1488         diag::pp_include_macros_out_of_predefines);
1489    DiscardUntilEndOfDirective();
1490    return;
1491  }
1492
1493  // Treat this as a normal #include for checking purposes.  If this is
1494  // successful, it will push a new lexer onto the include stack.
1495  HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
1496
1497  Token TmpTok;
1498  do {
1499    Lex(TmpTok);
1500    assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1501  } while (TmpTok.isNot(tok::hashhash));
1502}
1503
1504//===----------------------------------------------------------------------===//
1505// Preprocessor Macro Directive Handling.
1506//===----------------------------------------------------------------------===//
1507
1508/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1509/// definition has just been read.  Lex the rest of the arguments and the
1510/// closing ), updating MI with what we learn.  Return true if an error occurs
1511/// parsing the arg list.
1512bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1513  SmallVector<IdentifierInfo*, 32> Arguments;
1514
1515  Token Tok;
1516  while (1) {
1517    LexUnexpandedToken(Tok);
1518    switch (Tok.getKind()) {
1519    case tok::r_paren:
1520      // Found the end of the argument list.
1521      if (Arguments.empty())  // #define FOO()
1522        return false;
1523      // Otherwise we have #define FOO(A,)
1524      Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1525      return true;
1526    case tok::ellipsis:  // #define X(... -> C99 varargs
1527      if (!Features.C99)
1528        Diag(Tok, Features.CPlusPlus0x ?
1529             diag::warn_cxx98_compat_variadic_macro :
1530             diag::ext_variadic_macro);
1531
1532      // Lex the token after the identifier.
1533      LexUnexpandedToken(Tok);
1534      if (Tok.isNot(tok::r_paren)) {
1535        Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1536        return true;
1537      }
1538      // Add the __VA_ARGS__ identifier as an argument.
1539      Arguments.push_back(Ident__VA_ARGS__);
1540      MI->setIsC99Varargs();
1541      MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1542      return false;
1543    case tok::eod:  // #define X(
1544      Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1545      return true;
1546    default:
1547      // Handle keywords and identifiers here to accept things like
1548      // #define Foo(for) for.
1549      IdentifierInfo *II = Tok.getIdentifierInfo();
1550      if (II == 0) {
1551        // #define X(1
1552        Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1553        return true;
1554      }
1555
1556      // If this is already used as an argument, it is used multiple times (e.g.
1557      // #define X(A,A.
1558      if (std::find(Arguments.begin(), Arguments.end(), II) !=
1559          Arguments.end()) {  // C99 6.10.3p6
1560        Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
1561        return true;
1562      }
1563
1564      // Add the argument to the macro info.
1565      Arguments.push_back(II);
1566
1567      // Lex the token after the identifier.
1568      LexUnexpandedToken(Tok);
1569
1570      switch (Tok.getKind()) {
1571      default:          // #define X(A B
1572        Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1573        return true;
1574      case tok::r_paren: // #define X(A)
1575        MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1576        return false;
1577      case tok::comma:  // #define X(A,
1578        break;
1579      case tok::ellipsis:  // #define X(A... -> GCC extension
1580        // Diagnose extension.
1581        Diag(Tok, diag::ext_named_variadic_macro);
1582
1583        // Lex the token after the identifier.
1584        LexUnexpandedToken(Tok);
1585        if (Tok.isNot(tok::r_paren)) {
1586          Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1587          return true;
1588        }
1589
1590        MI->setIsGNUVarargs();
1591        MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1592        return false;
1593      }
1594    }
1595  }
1596}
1597
1598/// HandleDefineDirective - Implements #define.  This consumes the entire macro
1599/// line then lets the caller lex the next real token.
1600void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1601  ++NumDefined;
1602
1603  Token MacroNameTok;
1604  ReadMacroName(MacroNameTok, 1);
1605
1606  // Error reading macro name?  If so, diagnostic already issued.
1607  if (MacroNameTok.is(tok::eod))
1608    return;
1609
1610  Token LastTok = MacroNameTok;
1611
1612  // If we are supposed to keep comments in #defines, reenable comment saving
1613  // mode.
1614  if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
1615
1616  // Create the new macro.
1617  MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
1618
1619  Token Tok;
1620  LexUnexpandedToken(Tok);
1621
1622  // If this is a function-like macro definition, parse the argument list,
1623  // marking each of the identifiers as being used as macro arguments.  Also,
1624  // check other constraints on the first token of the macro body.
1625  if (Tok.is(tok::eod)) {
1626    // If there is no body to this macro, we have no special handling here.
1627  } else if (Tok.hasLeadingSpace()) {
1628    // This is a normal token with leading space.  Clear the leading space
1629    // marker on the first token to get proper expansion.
1630    Tok.clearFlag(Token::LeadingSpace);
1631  } else if (Tok.is(tok::l_paren)) {
1632    // This is a function-like macro definition.  Read the argument list.
1633    MI->setIsFunctionLike();
1634    if (ReadMacroDefinitionArgList(MI)) {
1635      // Forget about MI.
1636      ReleaseMacroInfo(MI);
1637      // Throw away the rest of the line.
1638      if (CurPPLexer->ParsingPreprocessorDirective)
1639        DiscardUntilEndOfDirective();
1640      return;
1641    }
1642
1643    // If this is a definition of a variadic C99 function-like macro, not using
1644    // the GNU named varargs extension, enabled __VA_ARGS__.
1645
1646    // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1647    // This gets unpoisoned where it is allowed.
1648    assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1649    if (MI->isC99Varargs())
1650      Ident__VA_ARGS__->setIsPoisoned(false);
1651
1652    // Read the first token after the arg list for down below.
1653    LexUnexpandedToken(Tok);
1654  } else if (Features.C99 || Features.CPlusPlus0x) {
1655    // C99 requires whitespace between the macro definition and the body.  Emit
1656    // a diagnostic for something like "#define X+".
1657    Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1658  } else {
1659    // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1660    // first character of a replacement list is not a character required by
1661    // subclause 5.2.1, then there shall be white-space separation between the
1662    // identifier and the replacement list.".  5.2.1 lists this set:
1663    //   "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1664    // is irrelevant here.
1665    bool isInvalid = false;
1666    if (Tok.is(tok::at)) // @ is not in the list above.
1667      isInvalid = true;
1668    else if (Tok.is(tok::unknown)) {
1669      // If we have an unknown token, it is something strange like "`".  Since
1670      // all of valid characters would have lexed into a single character
1671      // token of some sort, we know this is not a valid case.
1672      isInvalid = true;
1673    }
1674    if (isInvalid)
1675      Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1676    else
1677      Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
1678  }
1679
1680  if (!Tok.is(tok::eod))
1681    LastTok = Tok;
1682
1683  // Read the rest of the macro body.
1684  if (MI->isObjectLike()) {
1685    // Object-like macros are very simple, just read their body.
1686    while (Tok.isNot(tok::eod)) {
1687      LastTok = Tok;
1688      MI->AddTokenToBody(Tok);
1689      // Get the next token of the macro.
1690      LexUnexpandedToken(Tok);
1691    }
1692
1693  } else {
1694    // Otherwise, read the body of a function-like macro.  While we are at it,
1695    // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1696    // parameters in function-like macro expansions.
1697    while (Tok.isNot(tok::eod)) {
1698      LastTok = Tok;
1699
1700      if (Tok.isNot(tok::hash)) {
1701        MI->AddTokenToBody(Tok);
1702
1703        // Get the next token of the macro.
1704        LexUnexpandedToken(Tok);
1705        continue;
1706      }
1707
1708      // Get the next token of the macro.
1709      LexUnexpandedToken(Tok);
1710
1711      // Check for a valid macro arg identifier.
1712      if (Tok.getIdentifierInfo() == 0 ||
1713          MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1714
1715        // If this is assembler-with-cpp mode, we accept random gibberish after
1716        // the '#' because '#' is often a comment character.  However, change
1717        // the kind of the token to tok::unknown so that the preprocessor isn't
1718        // confused.
1719        if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
1720          LastTok.setKind(tok::unknown);
1721        } else {
1722          Diag(Tok, diag::err_pp_stringize_not_parameter);
1723          ReleaseMacroInfo(MI);
1724
1725          // Disable __VA_ARGS__ again.
1726          Ident__VA_ARGS__->setIsPoisoned(true);
1727          return;
1728        }
1729      }
1730
1731      // Things look ok, add the '#' and param name tokens to the macro.
1732      MI->AddTokenToBody(LastTok);
1733      MI->AddTokenToBody(Tok);
1734      LastTok = Tok;
1735
1736      // Get the next token of the macro.
1737      LexUnexpandedToken(Tok);
1738    }
1739  }
1740
1741
1742  // Disable __VA_ARGS__ again.
1743  Ident__VA_ARGS__->setIsPoisoned(true);
1744
1745  // Check that there is no paste (##) operator at the beginning or end of the
1746  // replacement list.
1747  unsigned NumTokens = MI->getNumTokens();
1748  if (NumTokens != 0) {
1749    if (MI->getReplacementToken(0).is(tok::hashhash)) {
1750      Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
1751      ReleaseMacroInfo(MI);
1752      return;
1753    }
1754    if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1755      Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
1756      ReleaseMacroInfo(MI);
1757      return;
1758    }
1759  }
1760
1761  MI->setDefinitionEndLoc(LastTok.getLocation());
1762
1763  // Finally, if this identifier already had a macro defined for it, verify that
1764  // the macro bodies are identical and free the old definition.
1765  if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
1766    // It is very common for system headers to have tons of macro redefinitions
1767    // and for warnings to be disabled in system headers.  If this is the case,
1768    // then don't bother calling MacroInfo::isIdenticalTo.
1769    if (!getDiagnostics().getSuppressSystemWarnings() ||
1770        !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1771      if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
1772        Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1773
1774      // Macros must be identical.  This means all tokens and whitespace
1775      // separation must be the same.  C99 6.10.3.2.
1776      if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1777          !MI->isIdenticalTo(*OtherMI, *this)) {
1778        Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1779          << MacroNameTok.getIdentifierInfo();
1780        Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1781      }
1782    }
1783    if (OtherMI->isWarnIfUnused())
1784      WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
1785    ReleaseMacroInfo(OtherMI);
1786  }
1787
1788  setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1789
1790  assert(!MI->isUsed());
1791  // If we need warning for not using the macro, add its location in the
1792  // warn-because-unused-macro set. If it gets used it will be removed from set.
1793  if (isInPrimaryFile() && // don't warn for include'd macros.
1794      Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1795          MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
1796    MI->setIsWarnIfUnused(true);
1797    WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1798  }
1799
1800  // If the callbacks want to know, tell them about the macro definition.
1801  if (Callbacks)
1802    Callbacks->MacroDefined(MacroNameTok, MI);
1803}
1804
1805/// HandleUndefDirective - Implements #undef.
1806///
1807void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1808  ++NumUndefined;
1809
1810  Token MacroNameTok;
1811  ReadMacroName(MacroNameTok, 2);
1812
1813  // Error reading macro name?  If so, diagnostic already issued.
1814  if (MacroNameTok.is(tok::eod))
1815    return;
1816
1817  // Check to see if this is the last token on the #undef line.
1818  CheckEndOfDirective("undef");
1819
1820  // Okay, we finally have a valid identifier to undef.
1821  MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1822
1823  // If the macro is not defined, this is a noop undef, just return.
1824  if (MI == 0) return;
1825
1826  if (!MI->isUsed() && MI->isWarnIfUnused())
1827    Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1828
1829  // If the callbacks want to know, tell them about the macro #undef.
1830  if (Callbacks)
1831    Callbacks->MacroUndefined(MacroNameTok, MI);
1832
1833  if (MI->isWarnIfUnused())
1834    WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1835
1836  // Free macro definition.
1837  ReleaseMacroInfo(MI);
1838  setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1839}
1840
1841
1842//===----------------------------------------------------------------------===//
1843// Preprocessor Conditional Directive Handling.
1844//===----------------------------------------------------------------------===//
1845
1846/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive.  isIfndef is
1847/// true when this is a #ifndef directive.  ReadAnyTokensBeforeDirective is true
1848/// if any tokens have been returned or pp-directives activated before this
1849/// #ifndef has been lexed.
1850///
1851void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1852                                        bool ReadAnyTokensBeforeDirective) {
1853  ++NumIf;
1854  Token DirectiveTok = Result;
1855
1856  Token MacroNameTok;
1857  ReadMacroName(MacroNameTok);
1858
1859  // Error reading macro name?  If so, diagnostic already issued.
1860  if (MacroNameTok.is(tok::eod)) {
1861    // Skip code until we get to #endif.  This helps with recovery by not
1862    // emitting an error when the #endif is reached.
1863    SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1864                                 /*Foundnonskip*/false, /*FoundElse*/false);
1865    return;
1866  }
1867
1868  // Check to see if this is the last token on the #if[n]def line.
1869  CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
1870
1871  IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1872  MacroInfo *MI = getMacroInfo(MII);
1873
1874  if (CurPPLexer->getConditionalStackDepth() == 0) {
1875    // If the start of a top-level #ifdef and if the macro is not defined,
1876    // inform MIOpt that this might be the start of a proper include guard.
1877    // Otherwise it is some other form of unknown conditional which we can't
1878    // handle.
1879    if (!ReadAnyTokensBeforeDirective && MI == 0) {
1880      assert(isIfndef && "#ifdef shouldn't reach here");
1881      CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
1882    } else
1883      CurPPLexer->MIOpt.EnterTopLevelConditional();
1884  }
1885
1886  // If there is a macro, process it.
1887  if (MI)  // Mark it used.
1888    markMacroAsUsed(MI);
1889
1890  // Should we include the stuff contained by this directive?
1891  if (!MI == isIfndef) {
1892    // Yes, remember that we are inside a conditional, then lex the next token.
1893    CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1894                                     /*wasskip*/false, /*foundnonskip*/true,
1895                                     /*foundelse*/false);
1896  } else {
1897    // No, skip the contents of this block.
1898    SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1899                                 /*Foundnonskip*/false,
1900                                 /*FoundElse*/false);
1901  }
1902
1903  if (Callbacks) {
1904    if (isIfndef)
1905      Callbacks->Ifndef(MacroNameTok);
1906    else
1907      Callbacks->Ifdef(MacroNameTok);
1908  }
1909}
1910
1911/// HandleIfDirective - Implements the #if directive.
1912///
1913void Preprocessor::HandleIfDirective(Token &IfToken,
1914                                     bool ReadAnyTokensBeforeDirective) {
1915  ++NumIf;
1916
1917  // Parse and evaluate the conditional expression.
1918  IdentifierInfo *IfNDefMacro = 0;
1919  const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1920  const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1921  const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
1922
1923  // If this condition is equivalent to #ifndef X, and if this is the first
1924  // directive seen, handle it for the multiple-include optimization.
1925  if (CurPPLexer->getConditionalStackDepth() == 0) {
1926    if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
1927      CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1928    else
1929      CurPPLexer->MIOpt.EnterTopLevelConditional();
1930  }
1931
1932  // Should we include the stuff contained by this directive?
1933  if (ConditionalTrue) {
1934    // Yes, remember that we are inside a conditional, then lex the next token.
1935    CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
1936                                   /*foundnonskip*/true, /*foundelse*/false);
1937  } else {
1938    // No, skip the contents of this block.
1939    SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1940                                 /*FoundElse*/false);
1941  }
1942
1943  if (Callbacks)
1944    Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
1945}
1946
1947/// HandleEndifDirective - Implements the #endif directive.
1948///
1949void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1950  ++NumEndif;
1951
1952  // Check that this is the whole directive.
1953  CheckEndOfDirective("endif");
1954
1955  PPConditionalInfo CondInfo;
1956  if (CurPPLexer->popConditionalLevel(CondInfo)) {
1957    // No conditionals on the stack: this is an #endif without an #if.
1958    Diag(EndifToken, diag::err_pp_endif_without_if);
1959    return;
1960  }
1961
1962  // If this the end of a top-level #endif, inform MIOpt.
1963  if (CurPPLexer->getConditionalStackDepth() == 0)
1964    CurPPLexer->MIOpt.ExitTopLevelConditional();
1965
1966  assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
1967         "This code should only be reachable in the non-skipping case!");
1968
1969  if (Callbacks)
1970    Callbacks->Endif();
1971}
1972
1973/// HandleElseDirective - Implements the #else directive.
1974///
1975void Preprocessor::HandleElseDirective(Token &Result) {
1976  ++NumElse;
1977
1978  // #else directive in a non-skipping conditional... start skipping.
1979  CheckEndOfDirective("else");
1980
1981  PPConditionalInfo CI;
1982  if (CurPPLexer->popConditionalLevel(CI)) {
1983    Diag(Result, diag::pp_err_else_without_if);
1984    return;
1985  }
1986
1987  // If this is a top-level #else, inform the MIOpt.
1988  if (CurPPLexer->getConditionalStackDepth() == 0)
1989    CurPPLexer->MIOpt.EnterTopLevelConditional();
1990
1991  // If this is a #else with a #else before it, report the error.
1992  if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1993
1994  // Finally, skip the rest of the contents of this block.
1995  SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1996                               /*FoundElse*/true, Result.getLocation());
1997
1998  if (Callbacks)
1999    Callbacks->Else();
2000}
2001
2002/// HandleElifDirective - Implements the #elif directive.
2003///
2004void Preprocessor::HandleElifDirective(Token &ElifToken) {
2005  ++NumElse;
2006
2007  // #elif directive in a non-skipping conditional... start skipping.
2008  // We don't care what the condition is, because we will always skip it (since
2009  // the block immediately before it was included).
2010  const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2011  DiscardUntilEndOfDirective();
2012  const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
2013
2014  PPConditionalInfo CI;
2015  if (CurPPLexer->popConditionalLevel(CI)) {
2016    Diag(ElifToken, diag::pp_err_elif_without_if);
2017    return;
2018  }
2019
2020  // If this is a top-level #elif, inform the MIOpt.
2021  if (CurPPLexer->getConditionalStackDepth() == 0)
2022    CurPPLexer->MIOpt.EnterTopLevelConditional();
2023
2024  // If this is a #elif with a #else before it, report the error.
2025  if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2026
2027  // Finally, skip the rest of the contents of this block.
2028  SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2029                               /*FoundElse*/CI.FoundElse,
2030                               ElifToken.getLocation());
2031
2032  if (Callbacks)
2033    Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
2034}
2035