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