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