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