1 //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements # directive processing for the Preprocessor.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/Preprocessor.h"
15 #include "clang/Lex/LiteralSupport.h"
16 #include "clang/Lex/HeaderSearch.h"
17 #include "clang/Lex/MacroInfo.h"
18 #include "clang/Lex/LexDiagnostic.h"
19 #include "clang/Lex/CodeCompletionHandler.h"
20 #include "clang/Lex/ModuleLoader.h"
21 #include "clang/Lex/Pragma.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/ADT/APInt.h"
25 using namespace clang;
27 //===----------------------------------------------------------------------===//
28 // Utility Methods for Preprocessor Directive Handling.
29 //===----------------------------------------------------------------------===//
31 MacroInfo *Preprocessor::AllocateMacroInfo() {
32 MacroInfoChain *MIChain;
36 MICache = MICache->Next;
39 MIChain = BP.Allocate<MacroInfoChain>();
42 MIChain->Next = MIChainHead;
45 MIChainHead->Prev = MIChain;
46 MIChainHead = MIChain;
48 return &(MIChain->MI);
51 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
52 MacroInfo *MI = AllocateMacroInfo();
53 new (MI) MacroInfo(L);
57 MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
58 MacroInfo *MI = AllocateMacroInfo();
59 new (MI) MacroInfo(MacroToClone, BP);
63 /// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
64 /// be reused for allocating new MacroInfo objects.
65 void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
66 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
67 if (MacroInfoChain *Prev = MIChain->Prev) {
68 MacroInfoChain *Next = MIChain->Next;
74 assert(MIChainHead == MIChain);
75 MIChainHead = MIChain->Next;
76 MIChainHead->Prev = 0;
78 MIChain->Next = MICache;
84 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
85 /// current line until the tok::eod token is found.
86 void Preprocessor::DiscardUntilEndOfDirective() {
89 LexUnexpandedToken(Tmp);
90 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
91 } while (Tmp.isNot(tok::eod));
94 /// ReadMacroName - Lex and validate a macro name, which occurs after a
95 /// #define or #undef. This sets the token kind to eod and discards the rest
96 /// of the macro line if the macro name is invalid. isDefineUndef is 1 if
97 /// this is due to a a #define, 2 if #undef directive, 0 if it is something
98 /// else (e.g. #ifdef).
99 void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
100 // Read the token, don't allow macro expansion on it.
101 LexUnexpandedToken(MacroNameTok);
103 if (MacroNameTok.is(tok::code_completion)) {
105 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
106 setCodeCompletionReached();
107 LexUnexpandedToken(MacroNameTok);
110 // Missing macro name?
111 if (MacroNameTok.is(tok::eod)) {
112 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
116 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
118 bool Invalid = false;
119 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
123 const IdentifierInfo &Info = Identifiers.get(Spelling);
124 if (Info.isCPlusPlusOperatorKeyword())
125 // C++ 2.5p2: Alternative tokens behave the same as its primary token
126 // except for their spellings.
127 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
129 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
130 // Fall through on error.
131 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
132 // Error if defining "defined": C99 6.10.8.4.
133 Diag(MacroNameTok, diag::err_defined_macro_name);
134 } else if (isDefineUndef && II->hasMacroDefinition() &&
135 getMacroInfo(II)->isBuiltinMacro()) {
136 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
137 if (isDefineUndef == 1)
138 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
140 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
142 // Okay, we got a good identifier node. Return it.
146 // Invalid macro name, read and discard the rest of the line. Then set the
147 // token kind to tok::eod.
148 MacroNameTok.setKind(tok::eod);
149 return DiscardUntilEndOfDirective();
152 /// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
153 /// not, emit a diagnostic and consume up until the eod. If EnableMacros is
154 /// true, then we consider macros that expand to zero tokens as being ok.
155 void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
157 // Lex unexpanded tokens for most directives: macros might expand to zero
158 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
159 // #line) allow empty macros.
163 LexUnexpandedToken(Tmp);
165 // There should be no tokens after the directive, but we allow them as an
167 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
168 LexUnexpandedToken(Tmp);
170 if (Tmp.isNot(tok::eod)) {
171 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
172 // or if this is a macro-style preprocessing directive, because it is more
173 // trouble than it is worth to insert /**/ and check that there is no /**/
174 // in the range also.
176 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
178 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
179 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
180 DiscardUntilEndOfDirective();
186 /// SkipExcludedConditionalBlock - We just read a #if or related directive and
187 /// decided that the subsequent tokens are in the #if'd out portion of the
188 /// file. Lex the rest of the file, until we see an #endif. If
189 /// FoundNonSkipPortion is true, then we have already emitted code for part of
190 /// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
191 /// is true, then #else directives are ok, if not, then we have already seen one
192 /// so a #else directive is a duplicate. When this returns, the caller can lex
193 /// the first valid token.
194 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
195 bool FoundNonSkipPortion,
197 SourceLocation ElseLoc) {
199 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
201 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
202 FoundNonSkipPortion, FoundElse);
205 PTHSkipExcludedConditionalBlock();
209 // Enter raw mode to disable identifier lookup (and thus macro expansion),
210 // disabling warnings, etc.
211 CurPPLexer->LexingRawMode = true;
216 if (Tok.is(tok::code_completion)) {
218 CodeComplete->CodeCompleteInConditionalExclusion();
219 setCodeCompletionReached();
223 // If this is the end of the buffer, we have an error.
224 if (Tok.is(tok::eof)) {
225 // Emit errors for each unterminated conditional on the stack, including
227 while (!CurPPLexer->ConditionalStack.empty()) {
228 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
229 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
230 diag::err_pp_unterminated_conditional);
231 CurPPLexer->ConditionalStack.pop_back();
234 // Just return and let the caller lex after this #include.
238 // If this token is not a preprocessor directive, just skip it.
239 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
242 // We just parsed a # character at the start of a line, so we're in
243 // directive mode. Tell the lexer this so any newlines we see will be
244 // converted into an EOD token (this terminates the macro).
245 CurPPLexer->ParsingPreprocessorDirective = true;
246 if (CurLexer) CurLexer->SetCommentRetentionState(false);
249 // Read the next token, the directive flavor.
250 LexUnexpandedToken(Tok);
252 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
253 // something bogus), skip it.
254 if (Tok.isNot(tok::raw_identifier)) {
255 CurPPLexer->ParsingPreprocessorDirective = false;
256 // Restore comment saving mode.
257 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
261 // If the first letter isn't i or e, it isn't intesting to us. We know that
262 // this is safe in the face of spelling differences, because there is no way
263 // to spell an i/e in a strange way that is another letter. Skipping this
264 // allows us to avoid looking up the identifier info for #define/#undef and
265 // other common directives.
266 const char *RawCharData = Tok.getRawIdentifierData();
268 char FirstChar = RawCharData[0];
269 if (FirstChar >= 'a' && FirstChar <= 'z' &&
270 FirstChar != 'i' && FirstChar != 'e') {
271 CurPPLexer->ParsingPreprocessorDirective = false;
272 // Restore comment saving mode.
273 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
277 // Get the identifier name without trigraphs or embedded newlines. Note
278 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
280 char DirectiveBuf[20];
282 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
283 Directive = StringRef(RawCharData, Tok.getLength());
285 std::string DirectiveStr = getSpelling(Tok);
286 unsigned IdLen = DirectiveStr.size();
288 CurPPLexer->ParsingPreprocessorDirective = false;
289 // Restore comment saving mode.
290 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
293 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
294 Directive = StringRef(DirectiveBuf, IdLen);
297 if (Directive.startswith("if")) {
298 StringRef Sub = Directive.substr(2);
299 if (Sub.empty() || // "if"
300 Sub == "def" || // "ifdef"
301 Sub == "ndef") { // "ifndef"
302 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
303 // bother parsing the condition.
304 DiscardUntilEndOfDirective();
305 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
306 /*foundnonskip*/false,
312 } else if (Directive[0] == 'e') {
313 StringRef Sub = Directive.substr(1);
314 if (Sub == "ndif") { // "endif"
315 CheckEndOfDirective("endif");
316 PPConditionalInfo CondInfo;
317 CondInfo.WasSkipping = true; // Silence bogus warning.
318 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
319 (void)InCond; // Silence warning in no-asserts mode.
320 assert(!InCond && "Can't be skipping if not in a conditional!");
322 // If we popped the outermost skipping block, we're done skipping!
323 if (!CondInfo.WasSkipping)
325 } else if (Sub == "lse") { // "else".
326 // #else directive in a skipping conditional. If not in some other
327 // skipping conditional, and if #else hasn't already been seen, enter it
328 // as a non-skipping conditional.
329 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
331 // If this is a #else with a #else before it, report the error.
332 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
334 // Note that we've seen a #else in this conditional.
335 CondInfo.FoundElse = true;
340 // If the conditional is at the top level, and the #if block wasn't
341 // entered, enter the #else block now.
342 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
343 CondInfo.FoundNonSkip = true;
344 CheckEndOfDirective("else");
347 DiscardUntilEndOfDirective(); // C99 6.10p4.
349 } else if (Sub == "lif") { // "elif".
350 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
353 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
354 // If this is in a skipping block or if we're already handled this #if
355 // block, don't bother parsing the condition.
356 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
357 DiscardUntilEndOfDirective();
360 // Restore the value of LexingRawMode so that identifiers are
361 // looked up, etc, inside the #elif expression.
362 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
363 CurPPLexer->LexingRawMode = false;
364 IdentifierInfo *IfNDefMacro = 0;
365 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
366 CurPPLexer->LexingRawMode = true;
368 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
370 // If this is a #elif with a #else before it, report the error.
371 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
374 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
376 // If this condition is true, enter it!
378 CondInfo.FoundNonSkip = true;
384 CurPPLexer->ParsingPreprocessorDirective = false;
385 // Restore comment saving mode.
386 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
389 // Finally, if we are out of the conditional (saw an #endif or ran off the end
390 // of the file, just stop skipping and return to lexing whatever came after
392 CurPPLexer->LexingRawMode = false;
395 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
396 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
400 void Preprocessor::PTHSkipExcludedConditionalBlock() {
404 assert(CurPTHLexer->LexingRawMode == false);
406 // Skip to the next '#else', '#elif', or #endif.
407 if (CurPTHLexer->SkipBlock()) {
408 // We have reached an #endif. Both the '#' and 'endif' tokens
409 // have been consumed by the PTHLexer. Just pop off the condition level.
410 PPConditionalInfo CondInfo;
411 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
412 (void)InCond; // Silence warning in no-asserts mode.
413 assert(!InCond && "Can't be skipping if not in a conditional!");
417 // We have reached a '#else' or '#elif'. Lex the next token to get
418 // the directive flavor.
420 LexUnexpandedToken(Tok);
422 // We can actually look up the IdentifierInfo here since we aren't in
424 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
426 if (K == tok::pp_else) {
427 // #else: Enter the else condition. We aren't in a nested condition
428 // since we skip those. We're always in the one matching the last
429 // blocked we skipped.
430 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
431 // Note that we've seen a #else in this conditional.
432 CondInfo.FoundElse = true;
434 // If the #if block wasn't entered then enter the #else block now.
435 if (!CondInfo.FoundNonSkip) {
436 CondInfo.FoundNonSkip = true;
438 // Scan until the eod token.
439 CurPTHLexer->ParsingPreprocessorDirective = true;
440 DiscardUntilEndOfDirective();
441 CurPTHLexer->ParsingPreprocessorDirective = false;
446 // Otherwise skip this block.
450 assert(K == tok::pp_elif);
451 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
453 // If this is a #elif with a #else before it, report the error.
454 if (CondInfo.FoundElse)
455 Diag(Tok, diag::pp_err_elif_after_else);
457 // If this is in a skipping block or if we're already handled this #if
458 // block, don't bother parsing the condition. We just skip this block.
459 if (CondInfo.FoundNonSkip)
462 // Evaluate the condition of the #elif.
463 IdentifierInfo *IfNDefMacro = 0;
464 CurPTHLexer->ParsingPreprocessorDirective = true;
465 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
466 CurPTHLexer->ParsingPreprocessorDirective = false;
468 // If this condition is true, enter it!
470 CondInfo.FoundNonSkip = true;
474 // Otherwise, skip this block and go to the next one.
479 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
480 /// return null on failure. isAngled indicates whether the file reference is
481 /// for system #include's or not (i.e. using <> instead of "").
482 const FileEntry *Preprocessor::LookupFile(
485 const DirectoryLookup *FromDir,
486 const DirectoryLookup *&CurDir,
487 SmallVectorImpl<char> *SearchPath,
488 SmallVectorImpl<char> *RelativePath,
489 StringRef *SuggestedModule) {
490 // If the header lookup mechanism may be relative to the current file, pass in
491 // info about where the current file is.
492 const FileEntry *CurFileEnt = 0;
494 FileID FID = getCurrentFileLexer()->getFileID();
495 CurFileEnt = SourceMgr.getFileEntryForID(FID);
497 // If there is no file entry associated with this file, it must be the
498 // predefines buffer. Any other file is not lexed with a normal lexer, so
499 // it won't be scanned for preprocessor directives. If we have the
500 // predefines buffer, resolve #include references (which come from the
501 // -include command line argument) as if they came from the main file, this
502 // affects file lookup etc.
503 if (CurFileEnt == 0) {
504 FID = SourceMgr.getMainFileID();
505 CurFileEnt = SourceMgr.getFileEntryForID(FID);
509 // Do a standard file entry lookup.
510 CurDir = CurDirLookup;
511 const FileEntry *FE = HeaderInfo.LookupFile(
512 Filename, isAngled, FromDir, CurDir, CurFileEnt,
513 SearchPath, RelativePath, SuggestedModule);
516 // Otherwise, see if this is a subframework header. If so, this is relative
517 // to one of the headers on the #include stack. Walk the list of the current
518 // headers on the #include stack and pass them to HeaderInfo.
519 // FIXME: SuggestedModule!
521 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
522 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
523 SearchPath, RelativePath)))
527 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
528 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
529 if (IsFileLexer(ISEntry)) {
531 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
532 if ((FE = HeaderInfo.LookupSubframeworkHeader(
533 Filename, CurFileEnt, SearchPath, RelativePath)))
538 // Otherwise, we really couldn't find the file.
543 //===----------------------------------------------------------------------===//
544 // Preprocessor Directive Handling.
545 //===----------------------------------------------------------------------===//
547 /// HandleDirective - This callback is invoked when the lexer sees a # token
548 /// at the start of a line. This consumes the directive, modifies the
549 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
550 /// read is the correct one.
551 void Preprocessor::HandleDirective(Token &Result) {
552 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
554 // We just parsed a # character at the start of a line, so we're in directive
555 // mode. Tell the lexer this so any newlines we see will be converted into an
556 // EOD token (which terminates the directive).
557 CurPPLexer->ParsingPreprocessorDirective = true;
561 // We are about to read a token. For the multiple-include optimization FA to
562 // work, we have to remember if we had read any tokens *before* this
564 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
566 // Save the '#' token in case we need to return it later.
567 Token SavedHash = Result;
569 // Read the next token, the directive flavor. This isn't expanded due to
571 LexUnexpandedToken(Result);
573 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
578 // If so, the user is relying on non-portable behavior, emit a diagnostic.
580 Diag(Result, diag::ext_embedded_directive);
583 switch (Result.getKind()) {
585 return; // null directive.
587 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
588 LexUnexpandedToken(Result);
590 case tok::code_completion:
592 CodeComplete->CodeCompleteDirective(
593 CurPPLexer->getConditionalStackDepth() > 0);
594 setCodeCompletionReached();
596 case tok::numeric_constant: // # 7 GNU line marker directive.
597 if (getLangOptions().AsmPreprocessor)
598 break; // # 4 is not a preprocessor directive in .S files.
599 return HandleDigitDirective(Result);
601 IdentifierInfo *II = Result.getIdentifierInfo();
602 if (II == 0) break; // Not an identifier.
604 // Ask what the preprocessor keyword ID is.
605 switch (II->getPPKeywordID()) {
607 // C99 6.10.1 - Conditional Inclusion.
609 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
611 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
613 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
615 return HandleElifDirective(Result);
617 return HandleElseDirective(Result);
619 return HandleEndifDirective(Result);
621 // C99 6.10.2 - Source File Inclusion.
622 case tok::pp_include:
624 return HandleIncludeDirective(SavedHash.getLocation(), Result);
625 case tok::pp___include_macros:
627 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
629 // C99 6.10.3 - Macro Replacement.
631 return HandleDefineDirective(Result);
633 return HandleUndefDirective(Result);
635 // C99 6.10.4 - Line Control.
637 return HandleLineDirective(Result);
639 // C99 6.10.5 - Error Directive.
641 return HandleUserDiagnosticDirective(Result, false);
643 // C99 6.10.6 - Pragma Directive.
645 return HandlePragmaDirective(PIK_HashPragma);
649 return HandleImportDirective(SavedHash.getLocation(), Result);
650 case tok::pp_include_next:
651 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
653 case tok::pp_warning:
654 Diag(Result, diag::ext_pp_warning_directive);
655 return HandleUserDiagnosticDirective(Result, true);
657 return HandleIdentSCCSDirective(Result);
659 return HandleIdentSCCSDirective(Result);
661 //isExtension = true; // FIXME: implement #assert
663 case tok::pp_unassert:
664 //isExtension = true; // FIXME: implement #unassert
667 case tok::pp___export_macro__:
668 return HandleMacroExportDirective(Result);
673 // If this is a .S file, treat unknown # directives as non-preprocessor
674 // directives. This is important because # may be a comment or introduce
675 // various pseudo-ops. Just return the # token and push back the following
676 // token to be lexed next time.
677 if (getLangOptions().AsmPreprocessor) {
678 Token *Toks = new Token[2];
679 // Return the # and the token after it.
683 // If the second token is a hashhash token, then we need to translate it to
684 // unknown so the token lexer doesn't try to perform token pasting.
685 if (Result.is(tok::hashhash))
686 Toks[1].setKind(tok::unknown);
688 // Enter this token stream so that we re-lex the tokens. Make sure to
689 // enable macro expansion, in case the token after the # is an identifier
691 EnterTokenStream(Toks, 2, false, true);
695 // If we reached here, the preprocessing token is not valid!
696 Diag(Result, diag::err_pp_invalid_directive);
698 // Read the rest of the PP line.
699 DiscardUntilEndOfDirective();
701 // Okay, we're done parsing the directive.
704 /// GetLineValue - Convert a numeric token into an unsigned value, emitting
705 /// Diagnostic DiagID if it is invalid, and returning the value in Val.
706 static bool GetLineValue(Token &DigitTok, unsigned &Val,
707 unsigned DiagID, Preprocessor &PP) {
708 if (DigitTok.isNot(tok::numeric_constant)) {
709 PP.Diag(DigitTok, DiagID);
711 if (DigitTok.isNot(tok::eod))
712 PP.DiscardUntilEndOfDirective();
716 llvm::SmallString<64> IntegerBuffer;
717 IntegerBuffer.resize(DigitTok.getLength());
718 const char *DigitTokBegin = &IntegerBuffer[0];
719 bool Invalid = false;
720 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
724 // Verify that we have a simple digit-sequence, and compute the value. This
725 // is always a simple digit string computed in decimal, so we do this manually
728 for (unsigned i = 0; i != ActualLength; ++i) {
729 if (!isdigit(DigitTokBegin[i])) {
730 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
731 diag::err_pp_line_digit_sequence);
732 PP.DiscardUntilEndOfDirective();
736 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
737 if (NextVal < Val) { // overflow.
738 PP.Diag(DigitTok, DiagID);
739 PP.DiscardUntilEndOfDirective();
745 // Reject 0, this is needed both by #line numbers and flags.
747 PP.Diag(DigitTok, DiagID);
748 PP.DiscardUntilEndOfDirective();
752 if (DigitTokBegin[0] == '0')
753 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
758 /// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
759 /// acceptable forms are:
760 /// # line digit-sequence
761 /// # line digit-sequence "s-char-sequence"
762 void Preprocessor::HandleLineDirective(Token &Tok) {
763 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
768 // Validate the number and convert it to an unsigned.
770 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
773 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
774 // number greater than 2147483647". C90 requires that the line # be <= 32767.
775 unsigned LineLimit = 32768U;
776 if (Features.C99 || Features.CPlusPlus0x)
777 LineLimit = 2147483648U;
778 if (LineNo >= LineLimit)
779 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
780 else if (Features.CPlusPlus0x && LineNo >= 32768U)
781 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
787 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
788 // string followed by eod.
789 if (StrTok.is(tok::eod))
791 else if (StrTok.isNot(tok::string_literal)) {
792 Diag(StrTok, diag::err_pp_line_invalid_filename);
793 DiscardUntilEndOfDirective();
796 // Parse and validate the string, converting it into a unique ID.
797 StringLiteralParser Literal(&StrTok, 1, *this);
798 assert(Literal.isAscii() && "Didn't allow wide strings in");
799 if (Literal.hadError)
800 return DiscardUntilEndOfDirective();
801 if (Literal.Pascal) {
802 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
803 return DiscardUntilEndOfDirective();
805 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
807 // Verify that there is nothing after the string, other than EOD. Because
808 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
809 CheckEndOfDirective("line", true);
812 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
815 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
816 PPCallbacks::RenameFile,
820 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
821 /// marker directive.
822 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
823 bool &IsSystemHeader, bool &IsExternCHeader,
828 if (FlagTok.is(tok::eod)) return false;
829 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
836 if (FlagTok.is(tok::eod)) return false;
837 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
839 } else if (FlagVal == 2) {
842 SourceManager &SM = PP.getSourceManager();
843 // If we are leaving the current presumed file, check to make sure the
844 // presumed include stack isn't empty!
846 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
847 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
848 if (PLoc.isInvalid())
851 // If there is no include loc (main file) or if the include loc is in a
852 // different physical file, then we aren't in a "1" line marker flag region.
853 SourceLocation IncLoc = PLoc.getIncludeLoc();
854 if (IncLoc.isInvalid() ||
855 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
856 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
857 PP.DiscardUntilEndOfDirective();
862 if (FlagTok.is(tok::eod)) return false;
863 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
867 // We must have 3 if there are still flags.
869 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
870 PP.DiscardUntilEndOfDirective();
874 IsSystemHeader = true;
877 if (FlagTok.is(tok::eod)) return false;
878 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
881 // We must have 4 if there is yet another flag.
883 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
884 PP.DiscardUntilEndOfDirective();
888 IsExternCHeader = true;
891 if (FlagTok.is(tok::eod)) return false;
893 // There are no more valid flags here.
894 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
895 PP.DiscardUntilEndOfDirective();
899 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
900 /// one of the following forms:
903 /// # 42 "file" ('1' | '2')?
904 /// # 42 "file" ('1' | '2')? '3' '4'?
906 void Preprocessor::HandleDigitDirective(Token &DigitTok) {
907 // Validate the number and convert it to an unsigned. GNU does not have a
908 // line # limit other than it fit in 32-bits.
910 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
917 bool IsFileEntry = false, IsFileExit = false;
918 bool IsSystemHeader = false, IsExternCHeader = false;
921 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
922 // string followed by eod.
923 if (StrTok.is(tok::eod))
925 else if (StrTok.isNot(tok::string_literal)) {
926 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
927 return DiscardUntilEndOfDirective();
929 // Parse and validate the string, converting it into a unique ID.
930 StringLiteralParser Literal(&StrTok, 1, *this);
931 assert(Literal.isAscii() && "Didn't allow wide strings in");
932 if (Literal.hadError)
933 return DiscardUntilEndOfDirective();
934 if (Literal.Pascal) {
935 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
936 return DiscardUntilEndOfDirective();
938 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
940 // If a filename was present, read any flags that are present.
941 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
942 IsSystemHeader, IsExternCHeader, *this))
946 // Create a line note with this information.
947 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
948 IsFileEntry, IsFileExit,
949 IsSystemHeader, IsExternCHeader);
951 // If the preprocessor has callbacks installed, notify them of the #line
952 // change. This is used so that the line marker comes out in -E mode for
955 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
957 Reason = PPCallbacks::EnterFile;
959 Reason = PPCallbacks::ExitFile;
960 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
962 FileKind = SrcMgr::C_ExternCSystem;
963 else if (IsSystemHeader)
964 FileKind = SrcMgr::C_System;
966 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
971 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
973 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
975 // PTH doesn't emit #warning or #error directives.
977 return CurPTHLexer->DiscardToEndOfLine();
979 // Read the rest of the line raw. We do this because we don't want macros
980 // to be expanded and we don't require that the tokens be valid preprocessing
981 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
982 // collapse multiple consequtive white space between tokens, but this isn't
983 // specified by the standard.
984 std::string Message = CurLexer->ReadToEndOfLine();
986 Diag(Tok, diag::pp_hash_warning) << Message;
988 Diag(Tok, diag::err_pp_hash_error) << Message;
991 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
993 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
994 // Yes, this directive is an extension.
995 Diag(Tok, diag::ext_pp_ident_directive);
997 // Read the string argument.
1001 // If the token kind isn't a string, it's a malformed directive.
1002 if (StrTok.isNot(tok::string_literal) &&
1003 StrTok.isNot(tok::wide_string_literal)) {
1004 Diag(StrTok, diag::err_pp_malformed_ident);
1005 if (StrTok.isNot(tok::eod))
1006 DiscardUntilEndOfDirective();
1010 // Verify that there is nothing after the string, other than EOD.
1011 CheckEndOfDirective("ident");
1014 bool Invalid = false;
1015 std::string Str = getSpelling(StrTok, &Invalid);
1017 Callbacks->Ident(Tok.getLocation(), Str);
1021 /// \brief Handle a #__export_macro__ directive.
1022 void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1024 ReadMacroName(MacroNameTok, 2);
1026 // Error reading macro name? If so, diagnostic already issued.
1027 if (MacroNameTok.is(tok::eod))
1030 // Check to see if this is the last token on the #__export_macro__ line.
1031 CheckEndOfDirective("__export_macro__");
1033 // Okay, we finally have a valid identifier to undef.
1034 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1036 // If the macro is not defined, this is an error.
1038 Diag(MacroNameTok, diag::err_pp_export_non_macro)
1039 << MacroNameTok.getIdentifierInfo();
1043 // Note that this macro has now been exported.
1044 MI->setExportLocation(MacroNameTok.getLocation());
1046 // If this macro definition came from a PCH file, mark it
1047 // as having changed since serialization.
1048 if (MI->isFromAST())
1049 MI->setChangedAfterLoad();
1052 //===----------------------------------------------------------------------===//
1053 // Preprocessor Include Directive Handling.
1054 //===----------------------------------------------------------------------===//
1056 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1057 /// checked and spelled filename, e.g. as an operand of #include. This returns
1058 /// true if the input filename was in <>'s or false if it were in ""'s. The
1059 /// caller is expected to provide a buffer that is large enough to hold the
1060 /// spelling of the filename, but is also expected to handle the case when
1061 /// this method decides to use a different buffer.
1062 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1063 StringRef &Buffer) {
1064 // Get the text form of the filename.
1065 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1067 // Make sure the filename is <x> or "x".
1069 if (Buffer[0] == '<') {
1070 if (Buffer.back() != '>') {
1071 Diag(Loc, diag::err_pp_expects_filename);
1072 Buffer = StringRef();
1076 } else if (Buffer[0] == '"') {
1077 if (Buffer.back() != '"') {
1078 Diag(Loc, diag::err_pp_expects_filename);
1079 Buffer = StringRef();
1084 Diag(Loc, diag::err_pp_expects_filename);
1085 Buffer = StringRef();
1089 // Diagnose #include "" as invalid.
1090 if (Buffer.size() <= 2) {
1091 Diag(Loc, diag::err_pp_empty_filename);
1092 Buffer = StringRef();
1096 // Skip the brackets.
1097 Buffer = Buffer.substr(1, Buffer.size()-2);
1101 /// ConcatenateIncludeName - Handle cases where the #include name is expanded
1102 /// from a macro as multiple tokens, which need to be glued together. This
1103 /// occurs for code like:
1104 /// #define FOO <a/b.h>
1106 /// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1108 /// This code concatenates and consumes tokens up to the '>' token. It returns
1109 /// false if the > was found, otherwise it returns true if it finds and consumes
1111 bool Preprocessor::ConcatenateIncludeName(
1112 llvm::SmallString<128> &FilenameBuffer,
1113 SourceLocation &End) {
1117 while (CurTok.isNot(tok::eod)) {
1118 End = CurTok.getLocation();
1120 // FIXME: Provide code completion for #includes.
1121 if (CurTok.is(tok::code_completion)) {
1122 setCodeCompletionReached();
1127 // Append the spelling of this token to the buffer. If there was a space
1128 // before it, add it now.
1129 if (CurTok.hasLeadingSpace())
1130 FilenameBuffer.push_back(' ');
1132 // Get the spelling of the token, directly into FilenameBuffer if possible.
1133 unsigned PreAppendSize = FilenameBuffer.size();
1134 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1136 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1137 unsigned ActualLen = getSpelling(CurTok, BufPtr);
1139 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1140 if (BufPtr != &FilenameBuffer[PreAppendSize])
1141 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1143 // Resize FilenameBuffer to the correct size.
1144 if (CurTok.getLength() != ActualLen)
1145 FilenameBuffer.resize(PreAppendSize+ActualLen);
1147 // If we found the '>' marker, return success.
1148 if (CurTok.is(tok::greater))
1154 // If we hit the eod marker, emit an error and return true so that the caller
1155 // knows the EOD has been read.
1156 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1160 /// HandleIncludeDirective - The "#include" tokens have just been read, read the
1161 /// file to be included from the lexer, then include it! This is a common
1162 /// routine with functionality shared between #include, #include_next and
1163 /// #import. LookupFrom is set when this is a #include_next directive, it
1164 /// specifies the file to start searching from.
1165 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1167 const DirectoryLookup *LookupFrom,
1171 CurPPLexer->LexIncludeFilename(FilenameTok);
1173 // Reserve a buffer to get the spelling.
1174 llvm::SmallString<128> FilenameBuffer;
1178 switch (FilenameTok.getKind()) {
1180 // If the token kind is EOD, the error has already been diagnosed.
1183 case tok::angle_string_literal:
1184 case tok::string_literal:
1185 Filename = getSpelling(FilenameTok, FilenameBuffer);
1186 End = FilenameTok.getLocation();
1190 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1191 // case, glue the tokens together into FilenameBuffer and interpret those.
1192 FilenameBuffer.push_back('<');
1193 if (ConcatenateIncludeName(FilenameBuffer, End))
1194 return; // Found <eod> but no ">"? Diagnostic already emitted.
1195 Filename = FilenameBuffer.str();
1198 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1199 DiscardUntilEndOfDirective();
1204 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1205 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1207 if (Filename.empty()) {
1208 DiscardUntilEndOfDirective();
1212 // Verify that there is nothing after the filename, other than EOD. Note that
1213 // we allow macros that expand to nothing after the filename, because this
1214 // falls into the category of "#include pp-tokens new-line" specified in
1216 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1218 // Check that we don't have infinite #include recursion.
1219 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1220 Diag(FilenameTok, diag::err_pp_include_too_deep);
1224 // Complain about attempts to #include files in an audit pragma.
1225 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1226 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1227 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1229 // Immediately leave the pragma.
1230 PragmaARCCFCodeAuditedLoc = SourceLocation();
1233 // Search include directories.
1234 const DirectoryLookup *CurDir;
1235 llvm::SmallString<1024> SearchPath;
1236 llvm::SmallString<1024> RelativePath;
1237 // We get the raw path only if we have 'Callbacks' to which we later pass
1239 StringRef SuggestedModule;
1240 const FileEntry *File = LookupFile(
1241 Filename, isAngled, LookupFrom, CurDir,
1242 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
1243 AutoModuleImport? &SuggestedModule : 0);
1245 // If we are supposed to import a module rather than including the header,
1247 if (!SuggestedModule.empty()) {
1248 TheModuleLoader.loadModule(IncludeTok.getLocation(),
1249 Identifiers.get(SuggestedModule),
1250 FilenameTok.getLocation());
1254 // Notify the callback object that we've seen an inclusion directive.
1256 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1257 End, SearchPath, RelativePath);
1260 if (!SuppressIncludeNotFoundError)
1261 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1265 // The #included file will be considered to be a system header if either it is
1266 // in a system include directory, or if the #includer is a system include
1268 SrcMgr::CharacteristicKind FileCharacter =
1269 std::max(HeaderInfo.getFileDirFlavor(File),
1270 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
1272 // Ask HeaderInfo if we should enter this #include file. If not, #including
1273 // this file will have no effect.
1274 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1276 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
1280 // Look up the file, create a File ID for it.
1281 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1283 assert(!FID.isInvalid() && "Expected valid file ID");
1285 // Finally, if all is good, enter the new file!
1286 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
1289 /// HandleIncludeNextDirective - Implements #include_next.
1291 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1292 Token &IncludeNextTok) {
1293 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1295 // #include_next is like #include, except that we start searching after
1296 // the current found directory. If we can't do this, issue a
1298 const DirectoryLookup *Lookup = CurDirLookup;
1299 if (isInPrimaryFile()) {
1301 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1302 } else if (Lookup == 0) {
1303 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1305 // Start looking up in the next directory.
1309 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
1312 /// HandleImportDirective - Implements #import.
1314 void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1316 if (!Features.ObjC1) // #import is standard for ObjC.
1317 Diag(ImportTok, diag::ext_pp_import_directive);
1319 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
1322 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1323 /// pseudo directive in the predefines buffer. This handles it by sucking all
1324 /// tokens through the preprocessor and discarding them (only keeping the side
1325 /// effects on the preprocessor).
1326 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1327 Token &IncludeMacrosTok) {
1328 // This directive should only occur in the predefines buffer. If not, emit an
1329 // error and reject it.
1330 SourceLocation Loc = IncludeMacrosTok.getLocation();
1331 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1332 Diag(IncludeMacrosTok.getLocation(),
1333 diag::pp_include_macros_out_of_predefines);
1334 DiscardUntilEndOfDirective();
1338 // Treat this as a normal #include for checking purposes. If this is
1339 // successful, it will push a new lexer onto the include stack.
1340 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
1345 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1346 } while (TmpTok.isNot(tok::hashhash));
1349 //===----------------------------------------------------------------------===//
1350 // Preprocessor Macro Directive Handling.
1351 //===----------------------------------------------------------------------===//
1353 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1354 /// definition has just been read. Lex the rest of the arguments and the
1355 /// closing ), updating MI with what we learn. Return true if an error occurs
1356 /// parsing the arg list.
1357 bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1358 SmallVector<IdentifierInfo*, 32> Arguments;
1362 LexUnexpandedToken(Tok);
1363 switch (Tok.getKind()) {
1365 // Found the end of the argument list.
1366 if (Arguments.empty()) // #define FOO()
1368 // Otherwise we have #define FOO(A,)
1369 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1371 case tok::ellipsis: // #define X(... -> C99 varargs
1373 Diag(Tok, Features.CPlusPlus0x ?
1374 diag::warn_cxx98_compat_variadic_macro :
1375 diag::ext_variadic_macro);
1377 // Lex the token after the identifier.
1378 LexUnexpandedToken(Tok);
1379 if (Tok.isNot(tok::r_paren)) {
1380 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1383 // Add the __VA_ARGS__ identifier as an argument.
1384 Arguments.push_back(Ident__VA_ARGS__);
1385 MI->setIsC99Varargs();
1386 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1388 case tok::eod: // #define X(
1389 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1392 // Handle keywords and identifiers here to accept things like
1393 // #define Foo(for) for.
1394 IdentifierInfo *II = Tok.getIdentifierInfo();
1397 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1401 // If this is already used as an argument, it is used multiple times (e.g.
1403 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1404 Arguments.end()) { // C99 6.10.3p6
1405 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
1409 // Add the argument to the macro info.
1410 Arguments.push_back(II);
1412 // Lex the token after the identifier.
1413 LexUnexpandedToken(Tok);
1415 switch (Tok.getKind()) {
1416 default: // #define X(A B
1417 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1419 case tok::r_paren: // #define X(A)
1420 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1422 case tok::comma: // #define X(A,
1424 case tok::ellipsis: // #define X(A... -> GCC extension
1425 // Diagnose extension.
1426 Diag(Tok, diag::ext_named_variadic_macro);
1428 // Lex the token after the identifier.
1429 LexUnexpandedToken(Tok);
1430 if (Tok.isNot(tok::r_paren)) {
1431 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1435 MI->setIsGNUVarargs();
1436 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1443 /// HandleDefineDirective - Implements #define. This consumes the entire macro
1444 /// line then lets the caller lex the next real token.
1445 void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1449 ReadMacroName(MacroNameTok, 1);
1451 // Error reading macro name? If so, diagnostic already issued.
1452 if (MacroNameTok.is(tok::eod))
1455 Token LastTok = MacroNameTok;
1457 // If we are supposed to keep comments in #defines, reenable comment saving
1459 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
1461 // Create the new macro.
1462 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
1465 LexUnexpandedToken(Tok);
1467 // If this is a function-like macro definition, parse the argument list,
1468 // marking each of the identifiers as being used as macro arguments. Also,
1469 // check other constraints on the first token of the macro body.
1470 if (Tok.is(tok::eod)) {
1471 // If there is no body to this macro, we have no special handling here.
1472 } else if (Tok.hasLeadingSpace()) {
1473 // This is a normal token with leading space. Clear the leading space
1474 // marker on the first token to get proper expansion.
1475 Tok.clearFlag(Token::LeadingSpace);
1476 } else if (Tok.is(tok::l_paren)) {
1477 // This is a function-like macro definition. Read the argument list.
1478 MI->setIsFunctionLike();
1479 if (ReadMacroDefinitionArgList(MI)) {
1481 ReleaseMacroInfo(MI);
1482 // Throw away the rest of the line.
1483 if (CurPPLexer->ParsingPreprocessorDirective)
1484 DiscardUntilEndOfDirective();
1488 // If this is a definition of a variadic C99 function-like macro, not using
1489 // the GNU named varargs extension, enabled __VA_ARGS__.
1491 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1492 // This gets unpoisoned where it is allowed.
1493 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1494 if (MI->isC99Varargs())
1495 Ident__VA_ARGS__->setIsPoisoned(false);
1497 // Read the first token after the arg list for down below.
1498 LexUnexpandedToken(Tok);
1499 } else if (Features.C99 || Features.CPlusPlus0x) {
1500 // C99 requires whitespace between the macro definition and the body. Emit
1501 // a diagnostic for something like "#define X+".
1502 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1504 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1505 // first character of a replacement list is not a character required by
1506 // subclause 5.2.1, then there shall be white-space separation between the
1507 // identifier and the replacement list.". 5.2.1 lists this set:
1508 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1509 // is irrelevant here.
1510 bool isInvalid = false;
1511 if (Tok.is(tok::at)) // @ is not in the list above.
1513 else if (Tok.is(tok::unknown)) {
1514 // If we have an unknown token, it is something strange like "`". Since
1515 // all of valid characters would have lexed into a single character
1516 // token of some sort, we know this is not a valid case.
1520 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1522 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
1525 if (!Tok.is(tok::eod))
1528 // Read the rest of the macro body.
1529 if (MI->isObjectLike()) {
1530 // Object-like macros are very simple, just read their body.
1531 while (Tok.isNot(tok::eod)) {
1533 MI->AddTokenToBody(Tok);
1534 // Get the next token of the macro.
1535 LexUnexpandedToken(Tok);
1539 // Otherwise, read the body of a function-like macro. While we are at it,
1540 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1541 // parameters in function-like macro expansions.
1542 while (Tok.isNot(tok::eod)) {
1545 if (Tok.isNot(tok::hash)) {
1546 MI->AddTokenToBody(Tok);
1548 // Get the next token of the macro.
1549 LexUnexpandedToken(Tok);
1553 // Get the next token of the macro.
1554 LexUnexpandedToken(Tok);
1556 // Check for a valid macro arg identifier.
1557 if (Tok.getIdentifierInfo() == 0 ||
1558 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1560 // If this is assembler-with-cpp mode, we accept random gibberish after
1561 // the '#' because '#' is often a comment character. However, change
1562 // the kind of the token to tok::unknown so that the preprocessor isn't
1564 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
1565 LastTok.setKind(tok::unknown);
1567 Diag(Tok, diag::err_pp_stringize_not_parameter);
1568 ReleaseMacroInfo(MI);
1570 // Disable __VA_ARGS__ again.
1571 Ident__VA_ARGS__->setIsPoisoned(true);
1576 // Things look ok, add the '#' and param name tokens to the macro.
1577 MI->AddTokenToBody(LastTok);
1578 MI->AddTokenToBody(Tok);
1581 // Get the next token of the macro.
1582 LexUnexpandedToken(Tok);
1587 // Disable __VA_ARGS__ again.
1588 Ident__VA_ARGS__->setIsPoisoned(true);
1590 // Check that there is no paste (##) operator at the beginning or end of the
1591 // replacement list.
1592 unsigned NumTokens = MI->getNumTokens();
1593 if (NumTokens != 0) {
1594 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1595 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
1596 ReleaseMacroInfo(MI);
1599 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1600 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
1601 ReleaseMacroInfo(MI);
1606 MI->setDefinitionEndLoc(LastTok.getLocation());
1608 // Finally, if this identifier already had a macro defined for it, verify that
1609 // the macro bodies are identical and free the old definition.
1610 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
1611 // It is very common for system headers to have tons of macro redefinitions
1612 // and for warnings to be disabled in system headers. If this is the case,
1613 // then don't bother calling MacroInfo::isIdenticalTo.
1614 if (!getDiagnostics().getSuppressSystemWarnings() ||
1615 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1616 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
1617 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1619 // Macros must be identical. This means all tokens and whitespace
1620 // separation must be the same. C99 6.10.3.2.
1621 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1622 !MI->isIdenticalTo(*OtherMI, *this)) {
1623 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1624 << MacroNameTok.getIdentifierInfo();
1625 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1628 if (OtherMI->isWarnIfUnused())
1629 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
1630 ReleaseMacroInfo(OtherMI);
1633 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1635 assert(!MI->isUsed());
1636 // If we need warning for not using the macro, add its location in the
1637 // warn-because-unused-macro set. If it gets used it will be removed from set.
1638 if (isInPrimaryFile() && // don't warn for include'd macros.
1639 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1640 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
1641 MI->setIsWarnIfUnused(true);
1642 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1645 // If the callbacks want to know, tell them about the macro definition.
1647 Callbacks->MacroDefined(MacroNameTok, MI);
1650 /// HandleUndefDirective - Implements #undef.
1652 void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1656 ReadMacroName(MacroNameTok, 2);
1658 // Error reading macro name? If so, diagnostic already issued.
1659 if (MacroNameTok.is(tok::eod))
1662 // Check to see if this is the last token on the #undef line.
1663 CheckEndOfDirective("undef");
1665 // Okay, we finally have a valid identifier to undef.
1666 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1668 // If the macro is not defined, this is a noop undef, just return.
1669 if (MI == 0) return;
1671 if (!MI->isUsed() && MI->isWarnIfUnused())
1672 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1674 // If the callbacks want to know, tell them about the macro #undef.
1676 Callbacks->MacroUndefined(MacroNameTok, MI);
1678 if (MI->isWarnIfUnused())
1679 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1681 // Free macro definition.
1682 ReleaseMacroInfo(MI);
1683 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1687 //===----------------------------------------------------------------------===//
1688 // Preprocessor Conditional Directive Handling.
1689 //===----------------------------------------------------------------------===//
1691 /// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1692 /// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1693 /// if any tokens have been returned or pp-directives activated before this
1694 /// #ifndef has been lexed.
1696 void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1697 bool ReadAnyTokensBeforeDirective) {
1699 Token DirectiveTok = Result;
1702 ReadMacroName(MacroNameTok);
1704 // Error reading macro name? If so, diagnostic already issued.
1705 if (MacroNameTok.is(tok::eod)) {
1706 // Skip code until we get to #endif. This helps with recovery by not
1707 // emitting an error when the #endif is reached.
1708 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1709 /*Foundnonskip*/false, /*FoundElse*/false);
1713 // Check to see if this is the last token on the #if[n]def line.
1714 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
1716 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1717 MacroInfo *MI = getMacroInfo(MII);
1719 if (CurPPLexer->getConditionalStackDepth() == 0) {
1720 // If the start of a top-level #ifdef and if the macro is not defined,
1721 // inform MIOpt that this might be the start of a proper include guard.
1722 // Otherwise it is some other form of unknown conditional which we can't
1724 if (!ReadAnyTokensBeforeDirective && MI == 0) {
1725 assert(isIfndef && "#ifdef shouldn't reach here");
1726 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
1728 CurPPLexer->MIOpt.EnterTopLevelConditional();
1731 // If there is a macro, process it.
1732 if (MI) // Mark it used.
1733 markMacroAsUsed(MI);
1735 // Should we include the stuff contained by this directive?
1736 if (!MI == isIfndef) {
1737 // Yes, remember that we are inside a conditional, then lex the next token.
1738 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1739 /*wasskip*/false, /*foundnonskip*/true,
1740 /*foundelse*/false);
1742 // No, skip the contents of this block.
1743 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1744 /*Foundnonskip*/false,
1745 /*FoundElse*/false);
1750 Callbacks->Ifndef(MacroNameTok);
1752 Callbacks->Ifdef(MacroNameTok);
1756 /// HandleIfDirective - Implements the #if directive.
1758 void Preprocessor::HandleIfDirective(Token &IfToken,
1759 bool ReadAnyTokensBeforeDirective) {
1762 // Parse and evaluate the conditional expression.
1763 IdentifierInfo *IfNDefMacro = 0;
1764 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1765 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1766 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
1768 // If this condition is equivalent to #ifndef X, and if this is the first
1769 // directive seen, handle it for the multiple-include optimization.
1770 if (CurPPLexer->getConditionalStackDepth() == 0) {
1771 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
1772 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1774 CurPPLexer->MIOpt.EnterTopLevelConditional();
1777 // Should we include the stuff contained by this directive?
1778 if (ConditionalTrue) {
1779 // Yes, remember that we are inside a conditional, then lex the next token.
1780 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
1781 /*foundnonskip*/true, /*foundelse*/false);
1783 // No, skip the contents of this block.
1784 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1785 /*FoundElse*/false);
1789 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
1792 /// HandleEndifDirective - Implements the #endif directive.
1794 void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1797 // Check that this is the whole directive.
1798 CheckEndOfDirective("endif");
1800 PPConditionalInfo CondInfo;
1801 if (CurPPLexer->popConditionalLevel(CondInfo)) {
1802 // No conditionals on the stack: this is an #endif without an #if.
1803 Diag(EndifToken, diag::err_pp_endif_without_if);
1807 // If this the end of a top-level #endif, inform MIOpt.
1808 if (CurPPLexer->getConditionalStackDepth() == 0)
1809 CurPPLexer->MIOpt.ExitTopLevelConditional();
1811 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
1812 "This code should only be reachable in the non-skipping case!");
1818 /// HandleElseDirective - Implements the #else directive.
1820 void Preprocessor::HandleElseDirective(Token &Result) {
1823 // #else directive in a non-skipping conditional... start skipping.
1824 CheckEndOfDirective("else");
1826 PPConditionalInfo CI;
1827 if (CurPPLexer->popConditionalLevel(CI)) {
1828 Diag(Result, diag::pp_err_else_without_if);
1832 // If this is a top-level #else, inform the MIOpt.
1833 if (CurPPLexer->getConditionalStackDepth() == 0)
1834 CurPPLexer->MIOpt.EnterTopLevelConditional();
1836 // If this is a #else with a #else before it, report the error.
1837 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1839 // Finally, skip the rest of the contents of this block.
1840 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1841 /*FoundElse*/true, Result.getLocation());
1847 /// HandleElifDirective - Implements the #elif directive.
1849 void Preprocessor::HandleElifDirective(Token &ElifToken) {
1852 // #elif directive in a non-skipping conditional... start skipping.
1853 // We don't care what the condition is, because we will always skip it (since
1854 // the block immediately before it was included).
1855 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1856 DiscardUntilEndOfDirective();
1857 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
1859 PPConditionalInfo CI;
1860 if (CurPPLexer->popConditionalLevel(CI)) {
1861 Diag(ElifToken, diag::pp_err_elif_without_if);
1865 // If this is a top-level #elif, inform the MIOpt.
1866 if (CurPPLexer->getConditionalStackDepth() == 0)
1867 CurPPLexer->MIOpt.EnterTopLevelConditional();
1869 // If this is a #elif with a #else before it, report the error.
1870 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1872 // Finally, skip the rest of the contents of this block.
1873 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1874 /*FoundElse*/CI.FoundElse,
1875 ElifToken.getLocation());
1878 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));