clang API Documentation

PPDirectives.cpp

Go to the documentation of this file.
00001 //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements # directive processing for the Preprocessor.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Lex/Preprocessor.h"
00015 #include "clang/Lex/LiteralSupport.h"
00016 #include "clang/Lex/HeaderSearch.h"
00017 #include "clang/Lex/MacroInfo.h"
00018 #include "clang/Lex/LexDiagnostic.h"
00019 #include "clang/Basic/FileManager.h"
00020 #include "clang/Basic/SourceManager.h"
00021 #include "llvm/ADT/APInt.h"
00022 using namespace clang;
00023 
00024 //===----------------------------------------------------------------------===//
00025 // Utility Methods for Preprocessor Directive Handling.
00026 //===----------------------------------------------------------------------===//
00027 
00028 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
00029   MacroInfo *MI;
00030 
00031   if (!MICache.empty()) {
00032     MI = MICache.back();
00033     MICache.pop_back();
00034   } else
00035     MI = (MacroInfo*) BP.Allocate<MacroInfo>();
00036   new (MI) MacroInfo(L);
00037   return MI;
00038 }
00039 
00040 /// ReleaseMacroInfo - Release the specified MacroInfo.  This memory will
00041 ///  be reused for allocating new MacroInfo objects.
00042 void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) {
00043   MICache.push_back(MI);
00044   MI->FreeArgumentList(BP);
00045 }
00046 
00047 
00048 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
00049 /// current line until the tok::eom token is found.
00050 void Preprocessor::DiscardUntilEndOfDirective() {
00051   Token Tmp;
00052   do {
00053     LexUnexpandedToken(Tmp);
00054   } while (Tmp.isNot(tok::eom));
00055 }
00056 
00057 /// ReadMacroName - Lex and validate a macro name, which occurs after a
00058 /// #define or #undef.  This sets the token kind to eom and discards the rest
00059 /// of the macro line if the macro name is invalid.  isDefineUndef is 1 if
00060 /// this is due to a a #define, 2 if #undef directive, 0 if it is something
00061 /// else (e.g. #ifdef).
00062 void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
00063   // Read the token, don't allow macro expansion on it.
00064   LexUnexpandedToken(MacroNameTok);
00065 
00066   // Missing macro name?
00067   if (MacroNameTok.is(tok::eom)) {
00068     Diag(MacroNameTok, diag::err_pp_missing_macro_name);
00069     return;
00070   }
00071 
00072   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
00073   if (II == 0) {
00074     bool Invalid = false;
00075     std::string Spelling = getSpelling(MacroNameTok, &Invalid);
00076     if (Invalid)
00077       return;
00078     
00079     const IdentifierInfo &Info = Identifiers.get(Spelling);
00080     if (Info.isCPlusPlusOperatorKeyword())
00081       // C++ 2.5p2: Alternative tokens behave the same as its primary token
00082       // except for their spellings.
00083       Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
00084     else
00085       Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
00086     // Fall through on error.
00087   } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
00088     // Error if defining "defined": C99 6.10.8.4.
00089     Diag(MacroNameTok, diag::err_defined_macro_name);
00090   } else if (isDefineUndef && II->hasMacroDefinition() &&
00091              getMacroInfo(II)->isBuiltinMacro()) {
00092     // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
00093     if (isDefineUndef == 1)
00094       Diag(MacroNameTok, diag::pp_redef_builtin_macro);
00095     else
00096       Diag(MacroNameTok, diag::pp_undef_builtin_macro);
00097   } else {
00098     // Okay, we got a good identifier node.  Return it.
00099     return;
00100   }
00101 
00102   // Invalid macro name, read and discard the rest of the line.  Then set the
00103   // token kind to tok::eom.
00104   MacroNameTok.setKind(tok::eom);
00105   return DiscardUntilEndOfDirective();
00106 }
00107 
00108 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token.  If
00109 /// not, emit a diagnostic and consume up until the eom.  If EnableMacros is
00110 /// true, then we consider macros that expand to zero tokens as being ok.
00111 void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
00112   Token Tmp;
00113   // Lex unexpanded tokens for most directives: macros might expand to zero
00114   // tokens, causing us to miss diagnosing invalid lines.  Some directives (like
00115   // #line) allow empty macros.
00116   if (EnableMacros)
00117     Lex(Tmp);
00118   else
00119     LexUnexpandedToken(Tmp);
00120 
00121   // There should be no tokens after the directive, but we allow them as an
00122   // extension.
00123   while (Tmp.is(tok::comment))  // Skip comments in -C mode.
00124     LexUnexpandedToken(Tmp);
00125 
00126   if (Tmp.isNot(tok::eom)) {
00127     // Add a fixit in GNU/C99/C++ mode.  Don't offer a fixit for strict-C89,
00128     // because it is more trouble than it is worth to insert /**/ and check that
00129     // there is no /**/ in the range also.
00130     FixItHint Hint;
00131     if (Features.GNUMode || Features.C99 || Features.CPlusPlus)
00132       Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
00133     Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
00134     DiscardUntilEndOfDirective();
00135   }
00136 }
00137 
00138 
00139 
00140 /// SkipExcludedConditionalBlock - We just read a #if or related directive and
00141 /// decided that the subsequent tokens are in the #if'd out portion of the
00142 /// file.  Lex the rest of the file, until we see an #endif.  If
00143 /// FoundNonSkipPortion is true, then we have already emitted code for part of
00144 /// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
00145 /// is true, then #else directives are ok, if not, then we have already seen one
00146 /// so a #else directive is a duplicate.  When this returns, the caller can lex
00147 /// the first valid token.
00148 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
00149                                                 bool FoundNonSkipPortion,
00150                                                 bool FoundElse) {
00151   ++NumSkipped;
00152   assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
00153 
00154   CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
00155                                  FoundNonSkipPortion, FoundElse);
00156 
00157   if (CurPTHLexer) {
00158     PTHSkipExcludedConditionalBlock();
00159     return;
00160   }
00161 
00162   // Enter raw mode to disable identifier lookup (and thus macro expansion),
00163   // disabling warnings, etc.
00164   CurPPLexer->LexingRawMode = true;
00165   Token Tok;
00166   while (1) {
00167     CurLexer->Lex(Tok);
00168 
00169     // If this is the end of the buffer, we have an error.
00170     if (Tok.is(tok::eof)) {
00171       // Emit errors for each unterminated conditional on the stack, including
00172       // the current one.
00173       while (!CurPPLexer->ConditionalStack.empty()) {
00174         Diag(CurPPLexer->ConditionalStack.back().IfLoc,
00175              diag::err_pp_unterminated_conditional);
00176         CurPPLexer->ConditionalStack.pop_back();
00177       }
00178 
00179       // Just return and let the caller lex after this #include.
00180       break;
00181     }
00182 
00183     // If this token is not a preprocessor directive, just skip it.
00184     if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
00185       continue;
00186 
00187     // We just parsed a # character at the start of a line, so we're in
00188     // directive mode.  Tell the lexer this so any newlines we see will be
00189     // converted into an EOM token (this terminates the macro).
00190     CurPPLexer->ParsingPreprocessorDirective = true;
00191     if (CurLexer) CurLexer->SetCommentRetentionState(false);
00192 
00193 
00194     // Read the next token, the directive flavor.
00195     LexUnexpandedToken(Tok);
00196 
00197     // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
00198     // something bogus), skip it.
00199     if (Tok.isNot(tok::identifier)) {
00200       CurPPLexer->ParsingPreprocessorDirective = false;
00201       // Restore comment saving mode.
00202       if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
00203       continue;
00204     }
00205 
00206     // If the first letter isn't i or e, it isn't intesting to us.  We know that
00207     // this is safe in the face of spelling differences, because there is no way
00208     // to spell an i/e in a strange way that is another letter.  Skipping this
00209     // allows us to avoid looking up the identifier info for #define/#undef and
00210     // other common directives.
00211     bool Invalid = false;
00212     const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation(),
00213                                                          &Invalid);
00214     if (Invalid)
00215       return;
00216     
00217     char FirstChar = RawCharData[0];
00218     if (FirstChar >= 'a' && FirstChar <= 'z' &&
00219         FirstChar != 'i' && FirstChar != 'e') {
00220       CurPPLexer->ParsingPreprocessorDirective = false;
00221       // Restore comment saving mode.
00222       if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
00223       continue;
00224     }
00225 
00226     // Get the identifier name without trigraphs or embedded newlines.  Note
00227     // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
00228     // when skipping.
00229     char DirectiveBuf[20];
00230     llvm::StringRef Directive;
00231     if (!Tok.needsCleaning() && Tok.getLength() < 20) {
00232       Directive = llvm::StringRef(RawCharData, Tok.getLength());
00233     } else {
00234       std::string DirectiveStr = getSpelling(Tok);
00235       unsigned IdLen = DirectiveStr.size();
00236       if (IdLen >= 20) {
00237         CurPPLexer->ParsingPreprocessorDirective = false;
00238         // Restore comment saving mode.
00239         if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
00240         continue;
00241       }
00242       memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
00243       Directive = llvm::StringRef(DirectiveBuf, IdLen);
00244     }
00245 
00246     if (Directive.startswith("if")) {
00247       llvm::StringRef Sub = Directive.substr(2);
00248       if (Sub.empty() ||   // "if"
00249           Sub == "def" ||   // "ifdef"
00250           Sub == "ndef") {  // "ifndef"
00251         // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
00252         // bother parsing the condition.
00253         DiscardUntilEndOfDirective();
00254         CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
00255                                        /*foundnonskip*/false,
00256                                        /*fnddelse*/false);
00257       }
00258     } else if (Directive[0] == 'e') {
00259       llvm::StringRef Sub = Directive.substr(1);
00260       if (Sub == "ndif") {  // "endif"
00261         CheckEndOfDirective("endif");
00262         PPConditionalInfo CondInfo;
00263         CondInfo.WasSkipping = true; // Silence bogus warning.
00264         bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
00265         InCond = InCond;  // Silence warning in no-asserts mode.
00266         assert(!InCond && "Can't be skipping if not in a conditional!");
00267 
00268         // If we popped the outermost skipping block, we're done skipping!
00269         if (!CondInfo.WasSkipping)
00270           break;
00271       } else if (Sub == "lse") { // "else".
00272         // #else directive in a skipping conditional.  If not in some other
00273         // skipping conditional, and if #else hasn't already been seen, enter it
00274         // as a non-skipping conditional.
00275         DiscardUntilEndOfDirective();  // C99 6.10p4.
00276         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
00277 
00278         // If this is a #else with a #else before it, report the error.
00279         if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
00280 
00281         // Note that we've seen a #else in this conditional.
00282         CondInfo.FoundElse = true;
00283 
00284         // If the conditional is at the top level, and the #if block wasn't
00285         // entered, enter the #else block now.
00286         if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
00287           CondInfo.FoundNonSkip = true;
00288           break;
00289         }
00290       } else if (Sub == "lif") {  // "elif".
00291         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
00292 
00293         bool ShouldEnter;
00294         // If this is in a skipping block or if we're already handled this #if
00295         // block, don't bother parsing the condition.
00296         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
00297           DiscardUntilEndOfDirective();
00298           ShouldEnter = false;
00299         } else {
00300           // Restore the value of LexingRawMode so that identifiers are
00301           // looked up, etc, inside the #elif expression.
00302           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
00303           CurPPLexer->LexingRawMode = false;
00304           IdentifierInfo *IfNDefMacro = 0;
00305           ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
00306           CurPPLexer->LexingRawMode = true;
00307         }
00308 
00309         // If this is a #elif with a #else before it, report the error.
00310         if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
00311 
00312         // If this condition is true, enter it!
00313         if (ShouldEnter) {
00314           CondInfo.FoundNonSkip = true;
00315           break;
00316         }
00317       }
00318     }
00319 
00320     CurPPLexer->ParsingPreprocessorDirective = false;
00321     // Restore comment saving mode.
00322     if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
00323   }
00324 
00325   // Finally, if we are out of the conditional (saw an #endif or ran off the end
00326   // of the file, just stop skipping and return to lexing whatever came after
00327   // the #if block.
00328   CurPPLexer->LexingRawMode = false;
00329 }
00330 
00331 void Preprocessor::PTHSkipExcludedConditionalBlock() {
00332 
00333   while (1) {
00334     assert(CurPTHLexer);
00335     assert(CurPTHLexer->LexingRawMode == false);
00336 
00337     // Skip to the next '#else', '#elif', or #endif.
00338     if (CurPTHLexer->SkipBlock()) {
00339       // We have reached an #endif.  Both the '#' and 'endif' tokens
00340       // have been consumed by the PTHLexer.  Just pop off the condition level.
00341       PPConditionalInfo CondInfo;
00342       bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
00343       InCond = InCond;  // Silence warning in no-asserts mode.
00344       assert(!InCond && "Can't be skipping if not in a conditional!");
00345       break;
00346     }
00347 
00348     // We have reached a '#else' or '#elif'.  Lex the next token to get
00349     // the directive flavor.
00350     Token Tok;
00351     LexUnexpandedToken(Tok);
00352 
00353     // We can actually look up the IdentifierInfo here since we aren't in
00354     // raw mode.
00355     tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
00356 
00357     if (K == tok::pp_else) {
00358       // #else: Enter the else condition.  We aren't in a nested condition
00359       //  since we skip those. We're always in the one matching the last
00360       //  blocked we skipped.
00361       PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
00362       // Note that we've seen a #else in this conditional.
00363       CondInfo.FoundElse = true;
00364 
00365       // If the #if block wasn't entered then enter the #else block now.
00366       if (!CondInfo.FoundNonSkip) {
00367         CondInfo.FoundNonSkip = true;
00368 
00369         // Scan until the eom token.
00370         CurPTHLexer->ParsingPreprocessorDirective = true;
00371         DiscardUntilEndOfDirective();
00372         CurPTHLexer->ParsingPreprocessorDirective = false;
00373 
00374         break;
00375       }
00376 
00377       // Otherwise skip this block.
00378       continue;
00379     }
00380 
00381     assert(K == tok::pp_elif);
00382     PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
00383 
00384     // If this is a #elif with a #else before it, report the error.
00385     if (CondInfo.FoundElse)
00386       Diag(Tok, diag::pp_err_elif_after_else);
00387 
00388     // If this is in a skipping block or if we're already handled this #if
00389     // block, don't bother parsing the condition.  We just skip this block.
00390     if (CondInfo.FoundNonSkip)
00391       continue;
00392 
00393     // Evaluate the condition of the #elif.
00394     IdentifierInfo *IfNDefMacro = 0;
00395     CurPTHLexer->ParsingPreprocessorDirective = true;
00396     bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
00397     CurPTHLexer->ParsingPreprocessorDirective = false;
00398 
00399     // If this condition is true, enter it!
00400     if (ShouldEnter) {
00401       CondInfo.FoundNonSkip = true;
00402       break;
00403     }
00404 
00405     // Otherwise, skip this block and go to the next one.
00406     continue;
00407   }
00408 }
00409 
00410 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
00411 /// return null on failure.  isAngled indicates whether the file reference is
00412 /// for system #include's or not (i.e. using <> instead of "").
00413 const FileEntry *Preprocessor::LookupFile(llvm::StringRef Filename,
00414                                           bool isAngled,
00415                                           const DirectoryLookup *FromDir,
00416                                           const DirectoryLookup *&CurDir) {
00417   // If the header lookup mechanism may be relative to the current file, pass in
00418   // info about where the current file is.
00419   const FileEntry *CurFileEnt = 0;
00420   if (!FromDir) {
00421     FileID FID = getCurrentFileLexer()->getFileID();
00422     CurFileEnt = SourceMgr.getFileEntryForID(FID);
00423 
00424     // If there is no file entry associated with this file, it must be the
00425     // predefines buffer.  Any other file is not lexed with a normal lexer, so
00426     // it won't be scanned for preprocessor directives.   If we have the
00427     // predefines buffer, resolve #include references (which come from the
00428     // -include command line argument) as if they came from the main file, this
00429     // affects file lookup etc.
00430     if (CurFileEnt == 0) {
00431       FID = SourceMgr.getMainFileID();
00432       CurFileEnt = SourceMgr.getFileEntryForID(FID);
00433     }
00434   }
00435 
00436   // Do a standard file entry lookup.
00437   CurDir = CurDirLookup;
00438   const FileEntry *FE =
00439     HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
00440   if (FE) return FE;
00441 
00442   // Otherwise, see if this is a subframework header.  If so, this is relative
00443   // to one of the headers on the #include stack.  Walk the list of the current
00444   // headers on the #include stack and pass them to HeaderInfo.
00445   if (IsFileLexer()) {
00446     if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
00447       if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
00448         return FE;
00449   }
00450 
00451   for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
00452     IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
00453     if (IsFileLexer(ISEntry)) {
00454       if ((CurFileEnt =
00455            SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
00456         if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt)))
00457           return FE;
00458     }
00459   }
00460 
00461   // Otherwise, we really couldn't find the file.
00462   return 0;
00463 }
00464 
00465 
00466 //===----------------------------------------------------------------------===//
00467 // Preprocessor Directive Handling.
00468 //===----------------------------------------------------------------------===//
00469 
00470 /// HandleDirective - This callback is invoked when the lexer sees a # token
00471 /// at the start of a line.  This consumes the directive, modifies the
00472 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
00473 /// read is the correct one.
00474 void Preprocessor::HandleDirective(Token &Result) {
00475   // FIXME: Traditional: # with whitespace before it not recognized by K&R?
00476 
00477   // We just parsed a # character at the start of a line, so we're in directive
00478   // mode.  Tell the lexer this so any newlines we see will be converted into an
00479   // EOM token (which terminates the directive).
00480   CurPPLexer->ParsingPreprocessorDirective = true;
00481 
00482   ++NumDirectives;
00483 
00484   // We are about to read a token.  For the multiple-include optimization FA to
00485   // work, we have to remember if we had read any tokens *before* this
00486   // pp-directive.
00487   bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
00488 
00489   // Save the '#' token in case we need to return it later.
00490   Token SavedHash = Result;
00491 
00492   // Read the next token, the directive flavor.  This isn't expanded due to
00493   // C99 6.10.3p8.
00494   LexUnexpandedToken(Result);
00495 
00496   // C99 6.10.3p11: Is this preprocessor directive in macro invocation?  e.g.:
00497   //   #define A(x) #x
00498   //   A(abc
00499   //     #warning blah
00500   //   def)
00501   // If so, the user is relying on non-portable behavior, emit a diagnostic.
00502   if (InMacroArgs)
00503     Diag(Result, diag::ext_embedded_directive);
00504 
00505 TryAgain:
00506   switch (Result.getKind()) {
00507   case tok::eom:
00508     return;   // null directive.
00509   case tok::comment:
00510     // Handle stuff like "# /*foo*/ define X" in -E -C mode.
00511     LexUnexpandedToken(Result);
00512     goto TryAgain;
00513 
00514   case tok::numeric_constant:  // # 7  GNU line marker directive.
00515     if (getLangOptions().AsmPreprocessor)
00516       break;  // # 4 is not a preprocessor directive in .S files.
00517     return HandleDigitDirective(Result);
00518   default:
00519     IdentifierInfo *II = Result.getIdentifierInfo();
00520     if (II == 0) break;  // Not an identifier.
00521 
00522     // Ask what the preprocessor keyword ID is.
00523     switch (II->getPPKeywordID()) {
00524     default: break;
00525     // C99 6.10.1 - Conditional Inclusion.
00526     case tok::pp_if:
00527       return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
00528     case tok::pp_ifdef:
00529       return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
00530     case tok::pp_ifndef:
00531       return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
00532     case tok::pp_elif:
00533       return HandleElifDirective(Result);
00534     case tok::pp_else:
00535       return HandleElseDirective(Result);
00536     case tok::pp_endif:
00537       return HandleEndifDirective(Result);
00538 
00539     // C99 6.10.2 - Source File Inclusion.
00540     case tok::pp_include:
00541       return HandleIncludeDirective(Result);       // Handle #include.
00542     case tok::pp___include_macros:
00543       return HandleIncludeMacrosDirective(Result); // Handle -imacros.
00544 
00545     // C99 6.10.3 - Macro Replacement.
00546     case tok::pp_define:
00547       return HandleDefineDirective(Result);
00548     case tok::pp_undef:
00549       return HandleUndefDirective(Result);
00550 
00551     // C99 6.10.4 - Line Control.
00552     case tok::pp_line:
00553       return HandleLineDirective(Result);
00554 
00555     // C99 6.10.5 - Error Directive.
00556     case tok::pp_error:
00557       return HandleUserDiagnosticDirective(Result, false);
00558 
00559     // C99 6.10.6 - Pragma Directive.
00560     case tok::pp_pragma:
00561       return HandlePragmaDirective();
00562 
00563     // GNU Extensions.
00564     case tok::pp_import:
00565       return HandleImportDirective(Result);
00566     case tok::pp_include_next:
00567       return HandleIncludeNextDirective(Result);
00568 
00569     case tok::pp_warning:
00570       Diag(Result, diag::ext_pp_warning_directive);
00571       return HandleUserDiagnosticDirective(Result, true);
00572     case tok::pp_ident:
00573       return HandleIdentSCCSDirective(Result);
00574     case tok::pp_sccs:
00575       return HandleIdentSCCSDirective(Result);
00576     case tok::pp_assert:
00577       //isExtension = true;  // FIXME: implement #assert
00578       break;
00579     case tok::pp_unassert:
00580       //isExtension = true;  // FIXME: implement #unassert
00581       break;
00582     }
00583     break;
00584   }
00585 
00586   // If this is a .S file, treat unknown # directives as non-preprocessor
00587   // directives.  This is important because # may be a comment or introduce
00588   // various pseudo-ops.  Just return the # token and push back the following
00589   // token to be lexed next time.
00590   if (getLangOptions().AsmPreprocessor) {
00591     Token *Toks = new Token[2];
00592     // Return the # and the token after it.
00593     Toks[0] = SavedHash;
00594     Toks[1] = Result;
00595     // Enter this token stream so that we re-lex the tokens.  Make sure to
00596     // enable macro expansion, in case the token after the # is an identifier
00597     // that is expanded.
00598     EnterTokenStream(Toks, 2, false, true);
00599     return;
00600   }
00601 
00602   // If we reached here, the preprocessing token is not valid!
00603   Diag(Result, diag::err_pp_invalid_directive);
00604 
00605   // Read the rest of the PP line.
00606   DiscardUntilEndOfDirective();
00607 
00608   // Okay, we're done parsing the directive.
00609 }
00610 
00611 /// GetLineValue - Convert a numeric token into an unsigned value, emitting
00612 /// Diagnostic DiagID if it is invalid, and returning the value in Val.
00613 static bool GetLineValue(Token &DigitTok, unsigned &Val,
00614                          unsigned DiagID, Preprocessor &PP) {
00615   if (DigitTok.isNot(tok::numeric_constant)) {
00616     PP.Diag(DigitTok, DiagID);
00617 
00618     if (DigitTok.isNot(tok::eom))
00619       PP.DiscardUntilEndOfDirective();
00620     return true;
00621   }
00622 
00623   llvm::SmallString<64> IntegerBuffer;
00624   IntegerBuffer.resize(DigitTok.getLength());
00625   const char *DigitTokBegin = &IntegerBuffer[0];
00626   bool Invalid = false;
00627   unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
00628   if (Invalid)
00629     return true;
00630   
00631   // Verify that we have a simple digit-sequence, and compute the value.  This
00632   // is always a simple digit string computed in decimal, so we do this manually
00633   // here.
00634   Val = 0;
00635   for (unsigned i = 0; i != ActualLength; ++i) {
00636     if (!isdigit(DigitTokBegin[i])) {
00637       PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
00638               diag::err_pp_line_digit_sequence);
00639       PP.DiscardUntilEndOfDirective();
00640       return true;
00641     }
00642 
00643     unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
00644     if (NextVal < Val) { // overflow.
00645       PP.Diag(DigitTok, DiagID);
00646       PP.DiscardUntilEndOfDirective();
00647       return true;
00648     }
00649     Val = NextVal;
00650   }
00651 
00652   // Reject 0, this is needed both by #line numbers and flags.
00653   if (Val == 0) {
00654     PP.Diag(DigitTok, DiagID);
00655     PP.DiscardUntilEndOfDirective();
00656     return true;
00657   }
00658 
00659   if (DigitTokBegin[0] == '0')
00660     PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
00661 
00662   return false;
00663 }
00664 
00665 /// HandleLineDirective - Handle #line directive: C99 6.10.4.  The two
00666 /// acceptable forms are:
00667 ///   # line digit-sequence
00668 ///   # line digit-sequence "s-char-sequence"
00669 void Preprocessor::HandleLineDirective(Token &Tok) {
00670   // Read the line # and string argument.  Per C99 6.10.4p5, these tokens are
00671   // expanded.
00672   Token DigitTok;
00673   Lex(DigitTok);
00674 
00675   // Validate the number and convert it to an unsigned.
00676   unsigned LineNo;
00677   if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
00678     return;
00679 
00680   // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
00681   // number greater than 2147483647".  C90 requires that the line # be <= 32767.
00682   unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
00683   if (LineNo >= LineLimit)
00684     Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
00685 
00686   int FilenameID = -1;
00687   Token StrTok;
00688   Lex(StrTok);
00689 
00690   // If the StrTok is "eom", then it wasn't present.  Otherwise, it must be a
00691   // string followed by eom.
00692   if (StrTok.is(tok::eom))
00693     ; // ok
00694   else if (StrTok.isNot(tok::string_literal)) {
00695     Diag(StrTok, diag::err_pp_line_invalid_filename);
00696     DiscardUntilEndOfDirective();
00697     return;
00698   } else {
00699     // Parse and validate the string, converting it into a unique ID.
00700     StringLiteralParser Literal(&StrTok, 1, *this);
00701     assert(!Literal.AnyWide && "Didn't allow wide strings in");
00702     if (Literal.hadError)
00703       return DiscardUntilEndOfDirective();
00704     if (Literal.Pascal) {
00705       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
00706       return DiscardUntilEndOfDirective();
00707     }
00708     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
00709                                                   Literal.GetStringLength());
00710 
00711     // Verify that there is nothing after the string, other than EOM.  Because
00712     // of C99 6.10.4p5, macros that expand to empty tokens are ok.
00713     CheckEndOfDirective("line", true);
00714   }
00715 
00716   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
00717 
00718   if (Callbacks)
00719     Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
00720                            PPCallbacks::RenameFile,
00721                            SrcMgr::C_User);
00722 }
00723 
00724 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
00725 /// marker directive.
00726 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
00727                                 bool &IsSystemHeader, bool &IsExternCHeader,
00728                                 Preprocessor &PP) {
00729   unsigned FlagVal;
00730   Token FlagTok;
00731   PP.Lex(FlagTok);
00732   if (FlagTok.is(tok::eom)) return false;
00733   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
00734     return true;
00735 
00736   if (FlagVal == 1) {
00737     IsFileEntry = true;
00738 
00739     PP.Lex(FlagTok);
00740     if (FlagTok.is(tok::eom)) return false;
00741     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
00742       return true;
00743   } else if (FlagVal == 2) {
00744     IsFileExit = true;
00745 
00746     SourceManager &SM = PP.getSourceManager();
00747     // If we are leaving the current presumed file, check to make sure the
00748     // presumed include stack isn't empty!
00749     FileID CurFileID =
00750       SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
00751     PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
00752 
00753     // If there is no include loc (main file) or if the include loc is in a
00754     // different physical file, then we aren't in a "1" line marker flag region.
00755     SourceLocation IncLoc = PLoc.getIncludeLoc();
00756     if (IncLoc.isInvalid() ||
00757         SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
00758       PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
00759       PP.DiscardUntilEndOfDirective();
00760       return true;
00761     }
00762 
00763     PP.Lex(FlagTok);
00764     if (FlagTok.is(tok::eom)) return false;
00765     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
00766       return true;
00767   }
00768 
00769   // We must have 3 if there are still flags.
00770   if (FlagVal != 3) {
00771     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
00772     PP.DiscardUntilEndOfDirective();
00773     return true;
00774   }
00775 
00776   IsSystemHeader = true;
00777 
00778   PP.Lex(FlagTok);
00779   if (FlagTok.is(tok::eom)) return false;
00780   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
00781     return true;
00782 
00783   // We must have 4 if there is yet another flag.
00784   if (FlagVal != 4) {
00785     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
00786     PP.DiscardUntilEndOfDirective();
00787     return true;
00788   }
00789 
00790   IsExternCHeader = true;
00791 
00792   PP.Lex(FlagTok);
00793   if (FlagTok.is(tok::eom)) return false;
00794 
00795   // There are no more valid flags here.
00796   PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
00797   PP.DiscardUntilEndOfDirective();
00798   return true;
00799 }
00800 
00801 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
00802 /// one of the following forms:
00803 ///
00804 ///     # 42
00805 ///     # 42 "file" ('1' | '2')?
00806 ///     # 42 "file" ('1' | '2')? '3' '4'?
00807 ///
00808 void Preprocessor::HandleDigitDirective(Token &DigitTok) {
00809   // Validate the number and convert it to an unsigned.  GNU does not have a
00810   // line # limit other than it fit in 32-bits.
00811   unsigned LineNo;
00812   if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
00813                    *this))
00814     return;
00815 
00816   Token StrTok;
00817   Lex(StrTok);
00818 
00819   bool IsFileEntry = false, IsFileExit = false;
00820   bool IsSystemHeader = false, IsExternCHeader = false;
00821   int FilenameID = -1;
00822 
00823   // If the StrTok is "eom", then it wasn't present.  Otherwise, it must be a
00824   // string followed by eom.
00825   if (StrTok.is(tok::eom))
00826     ; // ok
00827   else if (StrTok.isNot(tok::string_literal)) {
00828     Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
00829     return DiscardUntilEndOfDirective();
00830   } else {
00831     // Parse and validate the string, converting it into a unique ID.
00832     StringLiteralParser Literal(&StrTok, 1, *this);
00833     assert(!Literal.AnyWide && "Didn't allow wide strings in");
00834     if (Literal.hadError)
00835       return DiscardUntilEndOfDirective();
00836     if (Literal.Pascal) {
00837       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
00838       return DiscardUntilEndOfDirective();
00839     }
00840     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
00841                                                   Literal.GetStringLength());
00842 
00843     // If a filename was present, read any flags that are present.
00844     if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
00845                             IsSystemHeader, IsExternCHeader, *this))
00846       return;
00847   }
00848 
00849   // Create a line note with this information.
00850   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
00851                         IsFileEntry, IsFileExit,
00852                         IsSystemHeader, IsExternCHeader);
00853 
00854   // If the preprocessor has callbacks installed, notify them of the #line
00855   // change.  This is used so that the line marker comes out in -E mode for
00856   // example.
00857   if (Callbacks) {
00858     PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
00859     if (IsFileEntry)
00860       Reason = PPCallbacks::EnterFile;
00861     else if (IsFileExit)
00862       Reason = PPCallbacks::ExitFile;
00863     SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
00864     if (IsExternCHeader)
00865       FileKind = SrcMgr::C_ExternCSystem;
00866     else if (IsSystemHeader)
00867       FileKind = SrcMgr::C_System;
00868 
00869     Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
00870   }
00871 }
00872 
00873 
00874 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
00875 ///
00876 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
00877                                                  bool isWarning) {
00878   // PTH doesn't emit #warning or #error directives.
00879   if (CurPTHLexer)
00880     return CurPTHLexer->DiscardToEndOfLine();
00881 
00882   // Read the rest of the line raw.  We do this because we don't want macros
00883   // to be expanded and we don't require that the tokens be valid preprocessing
00884   // tokens.  For example, this is allowed: "#warning `   'foo".  GCC does
00885   // collapse multiple consequtive white space between tokens, but this isn't
00886   // specified by the standard.
00887   std::string Message = CurLexer->ReadToEndOfLine();
00888   if (isWarning)
00889     Diag(Tok, diag::pp_hash_warning) << Message;
00890   else
00891     Diag(Tok, diag::err_pp_hash_error) << Message;
00892 }
00893 
00894 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
00895 ///
00896 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
00897   // Yes, this directive is an extension.
00898   Diag(Tok, diag::ext_pp_ident_directive);
00899 
00900   // Read the string argument.
00901   Token StrTok;
00902   Lex(StrTok);
00903 
00904   // If the token kind isn't a string, it's a malformed directive.
00905   if (StrTok.isNot(tok::string_literal) &&
00906       StrTok.isNot(tok::wide_string_literal)) {
00907     Diag(StrTok, diag::err_pp_malformed_ident);
00908     if (StrTok.isNot(tok::eom))
00909       DiscardUntilEndOfDirective();
00910     return;
00911   }
00912 
00913   // Verify that there is nothing after the string, other than EOM.
00914   CheckEndOfDirective("ident");
00915 
00916   if (Callbacks) {
00917     bool Invalid = false;
00918     std::string Str = getSpelling(StrTok, &Invalid);
00919     if (!Invalid)
00920       Callbacks->Ident(Tok.getLocation(), Str);
00921   }
00922 }
00923 
00924 //===----------------------------------------------------------------------===//
00925 // Preprocessor Include Directive Handling.
00926 //===----------------------------------------------------------------------===//
00927 
00928 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
00929 /// checked and spelled filename, e.g. as an operand of #include. This returns
00930 /// true if the input filename was in <>'s or false if it were in ""'s.  The
00931 /// caller is expected to provide a buffer that is large enough to hold the
00932 /// spelling of the filename, but is also expected to handle the case when
00933 /// this method decides to use a different buffer.
00934 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
00935                                               llvm::StringRef &Buffer) {
00936   // Get the text form of the filename.
00937   assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
00938 
00939   // Make sure the filename is <x> or "x".
00940   bool isAngled;
00941   if (Buffer[0] == '<') {
00942     if (Buffer.back() != '>') {
00943       Diag(Loc, diag::err_pp_expects_filename);
00944       Buffer = llvm::StringRef();
00945       return true;
00946     }
00947     isAngled = true;
00948   } else if (Buffer[0] == '"') {
00949     if (Buffer.back() != '"') {
00950       Diag(Loc, diag::err_pp_expects_filename);
00951       Buffer = llvm::StringRef();
00952       return true;
00953     }
00954     isAngled = false;
00955   } else {
00956     Diag(Loc, diag::err_pp_expects_filename);
00957     Buffer = llvm::StringRef();
00958     return true;
00959   }
00960 
00961   // Diagnose #include "" as invalid.
00962   if (Buffer.size() <= 2) {
00963     Diag(Loc, diag::err_pp_empty_filename);
00964     Buffer = llvm::StringRef();
00965     return true;
00966   }
00967 
00968   // Skip the brackets.
00969   Buffer = Buffer.substr(1, Buffer.size()-2);
00970   return isAngled;
00971 }
00972 
00973 /// ConcatenateIncludeName - Handle cases where the #include name is expanded
00974 /// from a macro as multiple tokens, which need to be glued together.  This
00975 /// occurs for code like:
00976 ///    #define FOO <a/b.h>
00977 ///    #include FOO
00978 /// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
00979 ///
00980 /// This code concatenates and consumes tokens up to the '>' token.  It returns
00981 /// false if the > was found, otherwise it returns true if it finds and consumes
00982 /// the EOM marker.
00983 bool Preprocessor::ConcatenateIncludeName(
00984   llvm::SmallString<128> &FilenameBuffer) {
00985   Token CurTok;
00986 
00987   Lex(CurTok);
00988   while (CurTok.isNot(tok::eom)) {
00989     // Append the spelling of this token to the buffer. If there was a space
00990     // before it, add it now.
00991     if (CurTok.hasLeadingSpace())
00992       FilenameBuffer.push_back(' ');
00993 
00994     // Get the spelling of the token, directly into FilenameBuffer if possible.
00995     unsigned PreAppendSize = FilenameBuffer.size();
00996     FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
00997 
00998     const char *BufPtr = &FilenameBuffer[PreAppendSize];
00999     unsigned ActualLen = getSpelling(CurTok, BufPtr);
01000 
01001     // If the token was spelled somewhere else, copy it into FilenameBuffer.
01002     if (BufPtr != &FilenameBuffer[PreAppendSize])
01003       memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
01004 
01005     // Resize FilenameBuffer to the correct size.
01006     if (CurTok.getLength() != ActualLen)
01007       FilenameBuffer.resize(PreAppendSize+ActualLen);
01008 
01009     // If we found the '>' marker, return success.
01010     if (CurTok.is(tok::greater))
01011       return false;
01012 
01013     Lex(CurTok);
01014   }
01015 
01016   // If we hit the eom marker, emit an error and return true so that the caller
01017   // knows the EOM has been read.
01018   Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
01019   return true;
01020 }
01021 
01022 /// HandleIncludeDirective - The "#include" tokens have just been read, read the
01023 /// file to be included from the lexer, then include it!  This is a common
01024 /// routine with functionality shared between #include, #include_next and
01025 /// #import.  LookupFrom is set when this is a #include_next directive, it
01026 /// specifies the file to start searching from.
01027 void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
01028                                           const DirectoryLookup *LookupFrom,
01029                                           bool isImport) {
01030 
01031   Token FilenameTok;
01032   CurPPLexer->LexIncludeFilename(FilenameTok);
01033 
01034   // Reserve a buffer to get the spelling.
01035   llvm::SmallString<128> FilenameBuffer;
01036   llvm::StringRef Filename;
01037 
01038   switch (FilenameTok.getKind()) {
01039   case tok::eom:
01040     // If the token kind is EOM, the error has already been diagnosed.
01041     return;
01042 
01043   case tok::angle_string_literal:
01044   case tok::string_literal:
01045     Filename = getSpelling(FilenameTok, FilenameBuffer);
01046     break;
01047 
01048   case tok::less:
01049     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
01050     // case, glue the tokens together into FilenameBuffer and interpret those.
01051     FilenameBuffer.push_back('<');
01052     if (ConcatenateIncludeName(FilenameBuffer))
01053       return;   // Found <eom> but no ">"?  Diagnostic already emitted.
01054     Filename = FilenameBuffer.str();
01055     break;
01056   default:
01057     Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
01058     DiscardUntilEndOfDirective();
01059     return;
01060   }
01061 
01062   bool isAngled =
01063     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
01064   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
01065   // error.
01066   if (Filename.empty()) {
01067     DiscardUntilEndOfDirective();
01068     return;
01069   }
01070 
01071   // Verify that there is nothing after the filename, other than EOM.  Note that
01072   // we allow macros that expand to nothing after the filename, because this
01073   // falls into the category of "#include pp-tokens new-line" specified in
01074   // C99 6.10.2p4.
01075   CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
01076 
01077   // Check that we don't have infinite #include recursion.
01078   if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
01079     Diag(FilenameTok, diag::err_pp_include_too_deep);
01080     return;
01081   }
01082 
01083   // Search include directories.
01084   const DirectoryLookup *CurDir;
01085   const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
01086   if (File == 0) {
01087     Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
01088     return;
01089   }
01090 
01091   // The #included file will be considered to be a system header if either it is
01092   // in a system include directory, or if the #includer is a system include
01093   // header.
01094   SrcMgr::CharacteristicKind FileCharacter =
01095     std::max(HeaderInfo.getFileDirFlavor(File),
01096              SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
01097 
01098   // Ask HeaderInfo if we should enter this #include file.  If not, #including
01099   // this file will have no effect.
01100   if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
01101     if (Callbacks)
01102       Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
01103     return;
01104   }
01105 
01106   // Look up the file, create a File ID for it.
01107   FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
01108                                       FileCharacter);
01109   if (FID.isInvalid()) {
01110     Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
01111     return;
01112   }
01113 
01114   // Finally, if all is good, enter the new file!
01115   EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
01116 }
01117 
01118 /// HandleIncludeNextDirective - Implements #include_next.
01119 ///
01120 void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
01121   Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
01122 
01123   // #include_next is like #include, except that we start searching after
01124   // the current found directory.  If we can't do this, issue a
01125   // diagnostic.
01126   const DirectoryLookup *Lookup = CurDirLookup;
01127   if (isInPrimaryFile()) {
01128     Lookup = 0;
01129     Diag(IncludeNextTok, diag::pp_include_next_in_primary);
01130   } else if (Lookup == 0) {
01131     Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
01132   } else {
01133     // Start looking up in the next directory.
01134     ++Lookup;
01135   }
01136 
01137   return HandleIncludeDirective(IncludeNextTok, Lookup);
01138 }
01139 
01140 /// HandleImportDirective - Implements #import.
01141 ///
01142 void Preprocessor::HandleImportDirective(Token &ImportTok) {
01143   if (!Features.ObjC1)  // #import is standard for ObjC.
01144     Diag(ImportTok, diag::ext_pp_import_directive);
01145 
01146   return HandleIncludeDirective(ImportTok, 0, true);
01147 }
01148 
01149 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
01150 /// pseudo directive in the predefines buffer.  This handles it by sucking all
01151 /// tokens through the preprocessor and discarding them (only keeping the side
01152 /// effects on the preprocessor).
01153 void Preprocessor::HandleIncludeMacrosDirective(Token &IncludeMacrosTok) {
01154   // This directive should only occur in the predefines buffer.  If not, emit an
01155   // error and reject it.
01156   SourceLocation Loc = IncludeMacrosTok.getLocation();
01157   if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
01158     Diag(IncludeMacrosTok.getLocation(),
01159          diag::pp_include_macros_out_of_predefines);
01160     DiscardUntilEndOfDirective();
01161     return;
01162   }
01163 
01164   // Treat this as a normal #include for checking purposes.  If this is
01165   // successful, it will push a new lexer onto the include stack.
01166   HandleIncludeDirective(IncludeMacrosTok, 0, false);
01167 
01168   Token TmpTok;
01169   do {
01170     Lex(TmpTok);
01171     assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
01172   } while (TmpTok.isNot(tok::hashhash));
01173 }
01174 
01175 //===----------------------------------------------------------------------===//
01176 // Preprocessor Macro Directive Handling.
01177 //===----------------------------------------------------------------------===//
01178 
01179 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
01180 /// definition has just been read.  Lex the rest of the arguments and the
01181 /// closing ), updating MI with what we learn.  Return true if an error occurs
01182 /// parsing the arg list.
01183 bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
01184   llvm::SmallVector<IdentifierInfo*, 32> Arguments;
01185 
01186   Token Tok;
01187   while (1) {
01188     LexUnexpandedToken(Tok);
01189     switch (Tok.getKind()) {
01190     case tok::r_paren:
01191       // Found the end of the argument list.
01192       if (Arguments.empty())  // #define FOO()
01193         return false;
01194       // Otherwise we have #define FOO(A,)
01195       Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
01196       return true;
01197     case tok::ellipsis:  // #define X(... -> C99 varargs
01198       // Warn if use of C99 feature in non-C99 mode.
01199       if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
01200 
01201       // Lex the token after the identifier.
01202       LexUnexpandedToken(Tok);
01203       if (Tok.isNot(tok::r_paren)) {
01204         Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
01205         return true;
01206       }
01207       // Add the __VA_ARGS__ identifier as an argument.
01208       Arguments.push_back(Ident__VA_ARGS__);
01209       MI->setIsC99Varargs();
01210       MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
01211       return false;
01212     case tok::eom:  // #define X(
01213       Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
01214       return true;
01215     default:
01216       // Handle keywords and identifiers here to accept things like
01217       // #define Foo(for) for.
01218       IdentifierInfo *II = Tok.getIdentifierInfo();
01219       if (II == 0) {
01220         // #define X(1
01221         Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
01222         return true;
01223       }
01224 
01225       // If this is already used as an argument, it is used multiple times (e.g.
01226       // #define X(A,A.
01227       if (std::find(Arguments.begin(), Arguments.end(), II) !=
01228           Arguments.end()) {  // C99 6.10.3p6
01229         Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
01230         return true;
01231       }
01232 
01233       // Add the argument to the macro info.
01234       Arguments.push_back(II);
01235 
01236       // Lex the token after the identifier.
01237       LexUnexpandedToken(Tok);
01238 
01239       switch (Tok.getKind()) {
01240       default:          // #define X(A B
01241         Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
01242         return true;
01243       case tok::r_paren: // #define X(A)
01244         MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
01245         return false;
01246       case tok::comma:  // #define X(A,
01247         break;
01248       case tok::ellipsis:  // #define X(A... -> GCC extension
01249         // Diagnose extension.
01250         Diag(Tok, diag::ext_named_variadic_macro);
01251 
01252         // Lex the token after the identifier.
01253         LexUnexpandedToken(Tok);
01254         if (Tok.isNot(tok::r_paren)) {
01255           Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
01256           return true;
01257         }
01258 
01259         MI->setIsGNUVarargs();
01260         MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
01261         return false;
01262       }
01263     }
01264   }
01265 }
01266 
01267 /// HandleDefineDirective - Implements #define.  This consumes the entire macro
01268 /// line then lets the caller lex the next real token.
01269 void Preprocessor::HandleDefineDirective(Token &DefineTok) {
01270   ++NumDefined;
01271 
01272   Token MacroNameTok;
01273   ReadMacroName(MacroNameTok, 1);
01274 
01275   // Error reading macro name?  If so, diagnostic already issued.
01276   if (MacroNameTok.is(tok::eom))
01277     return;
01278 
01279   Token LastTok = MacroNameTok;
01280 
01281   // If we are supposed to keep comments in #defines, reenable comment saving
01282   // mode.
01283   if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
01284 
01285   // Create the new macro.
01286   MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
01287 
01288   Token Tok;
01289   LexUnexpandedToken(Tok);
01290 
01291   // If this is a function-like macro definition, parse the argument list,
01292   // marking each of the identifiers as being used as macro arguments.  Also,
01293   // check other constraints on the first token of the macro body.
01294   if (Tok.is(tok::eom)) {
01295     // If there is no body to this macro, we have no special handling here.
01296   } else if (Tok.hasLeadingSpace()) {
01297     // This is a normal token with leading space.  Clear the leading space
01298     // marker on the first token to get proper expansion.
01299     Tok.clearFlag(Token::LeadingSpace);
01300   } else if (Tok.is(tok::l_paren)) {
01301     // This is a function-like macro definition.  Read the argument list.
01302     MI->setIsFunctionLike();
01303     if (ReadMacroDefinitionArgList(MI)) {
01304       // Forget about MI.
01305       ReleaseMacroInfo(MI);
01306       // Throw away the rest of the line.
01307       if (CurPPLexer->ParsingPreprocessorDirective)
01308         DiscardUntilEndOfDirective();
01309       return;
01310     }
01311 
01312     // If this is a definition of a variadic C99 function-like macro, not using
01313     // the GNU named varargs extension, enabled __VA_ARGS__.
01314 
01315     // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
01316     // This gets unpoisoned where it is allowed.
01317     assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
01318     if (MI->isC99Varargs())
01319       Ident__VA_ARGS__->setIsPoisoned(false);
01320 
01321     // Read the first token after the arg list for down below.
01322     LexUnexpandedToken(Tok);
01323   } else if (Features.C99) {
01324     // C99 requires whitespace between the macro definition and the body.  Emit
01325     // a diagnostic for something like "#define X+".
01326     Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
01327   } else {
01328     // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
01329     // first character of a replacement list is not a character required by
01330     // subclause 5.2.1, then there shall be white-space separation between the
01331     // identifier and the replacement list.".  5.2.1 lists this set:
01332     //   "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
01333     // is irrelevant here.
01334     bool isInvalid = false;
01335     if (Tok.is(tok::at)) // @ is not in the list above.
01336       isInvalid = true;
01337     else if (Tok.is(tok::unknown)) {
01338       // If we have an unknown token, it is something strange like "`".  Since
01339       // all of valid characters would have lexed into a single character
01340       // token of some sort, we know this is not a valid case.
01341       isInvalid = true;
01342     }
01343     if (isInvalid)
01344       Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
01345     else
01346       Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
01347   }
01348 
01349   if (!Tok.is(tok::eom))
01350     LastTok = Tok;
01351 
01352   // Read the rest of the macro body.
01353   if (MI->isObjectLike()) {
01354     // Object-like macros are very simple, just read their body.
01355     while (Tok.isNot(tok::eom)) {
01356       LastTok = Tok;
01357       MI->AddTokenToBody(Tok);
01358       // Get the next token of the macro.
01359       LexUnexpandedToken(Tok);
01360     }
01361 
01362   } else {
01363     // Otherwise, read the body of a function-like macro.  While we are at it,
01364     // check C99 6.10.3.2p1: ensure that # operators are followed by macro
01365     // parameters in function-like macro expansions.
01366     while (Tok.isNot(tok::eom)) {
01367       LastTok = Tok;
01368 
01369       if (Tok.isNot(tok::hash)) {
01370         MI->AddTokenToBody(Tok);
01371 
01372         // Get the next token of the macro.
01373         LexUnexpandedToken(Tok);
01374         continue;
01375       }
01376 
01377       // Get the next token of the macro.
01378       LexUnexpandedToken(Tok);
01379 
01380       // Check for a valid macro arg identifier.
01381       if (Tok.getIdentifierInfo() == 0 ||
01382           MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
01383 
01384         // If this is assembler-with-cpp mode, we accept random gibberish after
01385         // the '#' because '#' is often a comment character.  However, change
01386         // the kind of the token to tok::unknown so that the preprocessor isn't
01387         // confused.
01388         if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eom)) {
01389           LastTok.setKind(tok::unknown);
01390         } else {
01391           Diag(Tok, diag::err_pp_stringize_not_parameter);
01392           ReleaseMacroInfo(MI);
01393 
01394           // Disable __VA_ARGS__ again.
01395           Ident__VA_ARGS__->setIsPoisoned(true);
01396           return;
01397         }
01398       }
01399 
01400       // Things look ok, add the '#' and param name tokens to the macro.
01401       MI->AddTokenToBody(LastTok);
01402       MI->AddTokenToBody(Tok);
01403       LastTok = Tok;
01404 
01405       // Get the next token of the macro.
01406       LexUnexpandedToken(Tok);
01407     }
01408   }
01409 
01410 
01411   // Disable __VA_ARGS__ again.
01412   Ident__VA_ARGS__->setIsPoisoned(true);
01413 
01414   // Check that there is no paste (##) operator at the begining or end of the
01415   // replacement list.
01416   unsigned NumTokens = MI->getNumTokens();
01417   if (NumTokens != 0) {
01418     if (MI->getReplacementToken(0).is(tok::hashhash)) {
01419       Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
01420       ReleaseMacroInfo(MI);
01421       return;
01422     }
01423     if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
01424       Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
01425       ReleaseMacroInfo(MI);
01426       return;
01427     }
01428   }
01429 
01430   // If this is the primary source file, remember that this macro hasn't been
01431   // used yet.
01432   if (isInPrimaryFile())
01433     MI->setIsUsed(false);
01434 
01435   MI->setDefinitionEndLoc(LastTok.getLocation());
01436 
01437   // Finally, if this identifier already had a macro defined for it, verify that
01438   // the macro bodies are identical and free the old definition.
01439   if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
01440     // It is very common for system headers to have tons of macro redefinitions
01441     // and for warnings to be disabled in system headers.  If this is the case,
01442     // then don't bother calling MacroInfo::isIdenticalTo.
01443     if (!getDiagnostics().getSuppressSystemWarnings() ||
01444         !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
01445       if (!OtherMI->isUsed())
01446         Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
01447 
01448       // Macros must be identical.  This means all tokes and whitespace
01449       // separation must be the same.  C99 6.10.3.2.
01450       if (!MI->isIdenticalTo(*OtherMI, *this)) {
01451         Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
01452           << MacroNameTok.getIdentifierInfo();
01453         Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
01454       }
01455     }
01456 
01457     ReleaseMacroInfo(OtherMI);
01458   }
01459 
01460   setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
01461 
01462   // If the callbacks want to know, tell them about the macro definition.
01463   if (Callbacks)
01464     Callbacks->MacroDefined(MacroNameTok.getIdentifierInfo(), MI);
01465 }
01466 
01467 /// HandleUndefDirective - Implements #undef.
01468 ///
01469 void Preprocessor::HandleUndefDirective(Token &UndefTok) {
01470   ++NumUndefined;
01471 
01472   Token MacroNameTok;
01473   ReadMacroName(MacroNameTok, 2);
01474 
01475   // Error reading macro name?  If so, diagnostic already issued.
01476   if (MacroNameTok.is(tok::eom))
01477     return;
01478 
01479   // Check to see if this is the last token on the #undef line.
01480   CheckEndOfDirective("undef");
01481 
01482   // Okay, we finally have a valid identifier to undef.
01483   MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
01484 
01485   // If the macro is not defined, this is a noop undef, just return.
01486   if (MI == 0) return;
01487 
01488   if (!MI->isUsed())
01489     Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
01490 
01491   // If the callbacks want to know, tell them about the macro #undef.
01492   if (Callbacks)
01493     Callbacks->MacroUndefined(MacroNameTok.getIdentifierInfo(), MI);
01494 
01495   // Free macro definition.
01496   ReleaseMacroInfo(MI);
01497   setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
01498 }
01499 
01500 
01501 //===----------------------------------------------------------------------===//
01502 // Preprocessor Conditional Directive Handling.
01503 //===----------------------------------------------------------------------===//
01504 
01505 /// HandleIfdefDirective - Implements the #ifdef/#ifndef directive.  isIfndef is
01506 /// true when this is a #ifndef directive.  ReadAnyTokensBeforeDirective is true
01507 /// if any tokens have been returned or pp-directives activated before this
01508 /// #ifndef has been lexed.
01509 ///
01510 void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
01511                                         bool ReadAnyTokensBeforeDirective) {
01512   ++NumIf;
01513   Token DirectiveTok = Result;
01514 
01515   Token MacroNameTok;
01516   ReadMacroName(MacroNameTok);
01517 
01518   // Error reading macro name?  If so, diagnostic already issued.
01519   if (MacroNameTok.is(tok::eom)) {
01520     // Skip code until we get to #endif.  This helps with recovery by not
01521     // emitting an error when the #endif is reached.
01522     SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
01523                                  /*Foundnonskip*/false, /*FoundElse*/false);
01524     return;
01525   }
01526 
01527   // Check to see if this is the last token on the #if[n]def line.
01528   CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
01529 
01530   IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
01531   MacroInfo *MI = getMacroInfo(MII);
01532 
01533   if (CurPPLexer->getConditionalStackDepth() == 0) {
01534     // If the start of a top-level #ifdef and if the macro is not defined,
01535     // inform MIOpt that this might be the start of a proper include guard.
01536     // Otherwise it is some other form of unknown conditional which we can't
01537     // handle.
01538     if (!ReadAnyTokensBeforeDirective && MI == 0) {
01539       assert(isIfndef && "#ifdef shouldn't reach here");
01540       CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
01541     } else
01542       CurPPLexer->MIOpt.EnterTopLevelConditional();
01543   }
01544 
01545   // If there is a macro, process it.
01546   if (MI)  // Mark it used.
01547     MI->setIsUsed(true);
01548 
01549   // Should we include the stuff contained by this directive?
01550   if (!MI == isIfndef) {
01551     // Yes, remember that we are inside a conditional, then lex the next token.
01552     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
01553                                      /*wasskip*/false, /*foundnonskip*/true,
01554                                      /*foundelse*/false);
01555   } else {
01556     // No, skip the contents of this block and return the first token after it.
01557     SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
01558                                  /*Foundnonskip*/false,
01559                                  /*FoundElse*/false);
01560   }
01561 }
01562 
01563 /// HandleIfDirective - Implements the #if directive.
01564 ///
01565 void Preprocessor::HandleIfDirective(Token &IfToken,
01566                                      bool ReadAnyTokensBeforeDirective) {
01567   ++NumIf;
01568 
01569   // Parse and evaluation the conditional expression.
01570   IdentifierInfo *IfNDefMacro = 0;
01571   bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
01572 
01573 
01574   // If this condition is equivalent to #ifndef X, and if this is the first
01575   // directive seen, handle it for the multiple-include optimization.
01576   if (CurPPLexer->getConditionalStackDepth() == 0) {
01577     if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
01578       CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
01579     else
01580       CurPPLexer->MIOpt.EnterTopLevelConditional();
01581   }
01582 
01583   // Should we include the stuff contained by this directive?
01584   if (ConditionalTrue) {
01585     // Yes, remember that we are inside a conditional, then lex the next token.
01586     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
01587                                    /*foundnonskip*/true, /*foundelse*/false);
01588   } else {
01589     // No, skip the contents of this block and return the first token after it.
01590     SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
01591                                  /*FoundElse*/false);
01592   }
01593 }
01594 
01595 /// HandleEndifDirective - Implements the #endif directive.
01596 ///
01597 void Preprocessor::HandleEndifDirective(Token &EndifToken) {
01598   ++NumEndif;
01599 
01600   // Check that this is the whole directive.
01601   CheckEndOfDirective("endif");
01602 
01603   PPConditionalInfo CondInfo;
01604   if (CurPPLexer->popConditionalLevel(CondInfo)) {
01605     // No conditionals on the stack: this is an #endif without an #if.
01606     Diag(EndifToken, diag::err_pp_endif_without_if);
01607     return;
01608   }
01609 
01610   // If this the end of a top-level #endif, inform MIOpt.
01611   if (CurPPLexer->getConditionalStackDepth() == 0)
01612     CurPPLexer->MIOpt.ExitTopLevelConditional();
01613 
01614   assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
01615          "This code should only be reachable in the non-skipping case!");
01616 }
01617 
01618 
01619 void Preprocessor::HandleElseDirective(Token &Result) {
01620   ++NumElse;
01621 
01622   // #else directive in a non-skipping conditional... start skipping.
01623   CheckEndOfDirective("else");
01624 
01625   PPConditionalInfo CI;
01626   if (CurPPLexer->popConditionalLevel(CI)) {
01627     Diag(Result, diag::pp_err_else_without_if);
01628     return;
01629   }
01630 
01631   // If this is a top-level #else, inform the MIOpt.
01632   if (CurPPLexer->getConditionalStackDepth() == 0)
01633     CurPPLexer->MIOpt.EnterTopLevelConditional();
01634 
01635   // If this is a #else with a #else before it, report the error.
01636   if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
01637 
01638   // Finally, skip the rest of the contents of this block and return the first
01639   // token after it.
01640   return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
01641                                       /*FoundElse*/true);
01642 }
01643 
01644 void Preprocessor::HandleElifDirective(Token &ElifToken) {
01645   ++NumElse;
01646 
01647   // #elif directive in a non-skipping conditional... start skipping.
01648   // We don't care what the condition is, because we will always skip it (since
01649   // the block immediately before it was included).
01650   DiscardUntilEndOfDirective();
01651 
01652   PPConditionalInfo CI;
01653   if (CurPPLexer->popConditionalLevel(CI)) {
01654     Diag(ElifToken, diag::pp_err_elif_without_if);
01655     return;
01656   }
01657 
01658   // If this is a top-level #elif, inform the MIOpt.
01659   if (CurPPLexer->getConditionalStackDepth() == 0)
01660     CurPPLexer->MIOpt.EnterTopLevelConditional();
01661 
01662   // If this is a #elif with a #else before it, report the error.
01663   if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
01664 
01665   // Finally, skip the rest of the contents of this block and return the first
01666   // token after it.
01667   return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
01668                                       /*FoundElse*/CI.FoundElse);
01669 }