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