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