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