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 //===----------------------------------------------------------------------===//
11 /// \brief Implements # directive processing for the Preprocessor.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/CodeCompletionHandler.h"
19 #include "clang/Lex/HeaderSearch.h"
20 #include "clang/Lex/HeaderSearchOptions.h"
21 #include "clang/Lex/LexDiagnostic.h"
22 #include "clang/Lex/LiteralSupport.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "clang/Lex/ModuleLoader.h"
25 #include "clang/Lex/Pragma.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/SaveAndRestore.h"
30 using namespace clang
;
32 //===----------------------------------------------------------------------===//
33 // Utility Methods for Preprocessor Directive Handling.
34 //===----------------------------------------------------------------------===//
36 MacroInfo
*Preprocessor::AllocateMacroInfo() {
37 MacroInfoChain
*MIChain
= BP
.Allocate
<MacroInfoChain
>();
38 MIChain
->Next
= MIChainHead
;
39 MIChainHead
= MIChain
;
43 MacroInfo
*Preprocessor::AllocateMacroInfo(SourceLocation L
) {
44 MacroInfo
*MI
= AllocateMacroInfo();
45 new (MI
) MacroInfo(L
);
49 MacroInfo
*Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L
,
50 unsigned SubModuleID
) {
51 static_assert(llvm::AlignOf
<MacroInfo
>::Alignment
>= sizeof(SubModuleID
),
52 "alignment for MacroInfo is less than the ID");
53 DeserializedMacroInfoChain
*MIChain
=
54 BP
.Allocate
<DeserializedMacroInfoChain
>();
55 MIChain
->Next
= DeserialMIChainHead
;
56 DeserialMIChainHead
= MIChain
;
58 MacroInfo
*MI
= &MIChain
->MI
;
59 new (MI
) MacroInfo(L
);
60 MI
->FromASTFile
= true;
61 MI
->setOwningModuleID(SubModuleID
);
66 Preprocessor::AllocateDefMacroDirective(MacroInfo
*MI
, SourceLocation Loc
,
67 unsigned ImportedFromModuleID
,
68 ArrayRef
<unsigned> Overrides
) {
69 unsigned NumExtra
= (ImportedFromModuleID
? 1 : 0) + Overrides
.size();
70 return new (BP
.Allocate(sizeof(DefMacroDirective
) +
71 sizeof(unsigned) * NumExtra
,
72 llvm::alignOf
<DefMacroDirective
>()))
73 DefMacroDirective(MI
, Loc
, ImportedFromModuleID
, Overrides
);
77 Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc
,
78 unsigned ImportedFromModuleID
,
79 ArrayRef
<unsigned> Overrides
) {
80 unsigned NumExtra
= (ImportedFromModuleID
? 1 : 0) + Overrides
.size();
81 return new (BP
.Allocate(sizeof(UndefMacroDirective
) +
82 sizeof(unsigned) * NumExtra
,
83 llvm::alignOf
<UndefMacroDirective
>()))
84 UndefMacroDirective(UndefLoc
, ImportedFromModuleID
, Overrides
);
87 VisibilityMacroDirective
*
88 Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc
,
90 return new (BP
) VisibilityMacroDirective(Loc
, isPublic
);
93 /// \brief Read and discard all tokens remaining on the current line until
94 /// the tok::eod token is found.
95 void Preprocessor::DiscardUntilEndOfDirective() {
98 LexUnexpandedToken(Tmp
);
99 assert(Tmp
.isNot(tok::eof
) && "EOF seen while discarding directive tokens");
100 } while (Tmp
.isNot(tok::eod
));
103 /// \brief Enumerates possible cases of #define/#undef a reserved identifier.
105 MD_NoWarn
, //> Not a reserved identifier
106 MD_KeywordDef
, //> Macro hides keyword, enabled by default
107 MD_ReservedMacro
//> #define of #undef reserved id, disabled by default
110 /// \brief Checks if the specified identifier is reserved in the specified
112 /// This function does not check if the identifier is a keyword.
113 static bool isReservedId(StringRef Text
, const LangOptions
&Lang
) {
114 // C++ [macro.names], C11 7.1.3:
115 // All identifiers that begin with an underscore and either an uppercase
116 // letter or another underscore are always reserved for any use.
117 if (Text
.size() >= 2 && Text
[0] == '_' &&
118 (isUppercase(Text
[1]) || Text
[1] == '_'))
120 // C++ [global.names]
121 // Each name that contains a double underscore ... is reserved to the
122 // implementation for any use.
123 if (Lang
.CPlusPlus
) {
124 if (Text
.find("__") != StringRef::npos
)
130 static MacroDiag
shouldWarnOnMacroDef(Preprocessor
&PP
, IdentifierInfo
*II
) {
131 const LangOptions
&Lang
= PP
.getLangOpts();
132 StringRef Text
= II
->getName();
133 if (isReservedId(Text
, Lang
))
134 return MD_ReservedMacro
;
135 if (II
->isKeyword(Lang
))
136 return MD_KeywordDef
;
137 if (Lang
.CPlusPlus11
&& (Text
.equals("override") || Text
.equals("final")))
138 return MD_KeywordDef
;
142 static MacroDiag
shouldWarnOnMacroUndef(Preprocessor
&PP
, IdentifierInfo
*II
) {
143 const LangOptions
&Lang
= PP
.getLangOpts();
144 StringRef Text
= II
->getName();
145 // Do not warn on keyword undef. It is generally harmless and widely used.
146 if (isReservedId(Text
, Lang
))
147 return MD_ReservedMacro
;
151 bool Preprocessor::CheckMacroName(Token
&MacroNameTok
, MacroUse isDefineUndef
,
153 // Missing macro name?
154 if (MacroNameTok
.is(tok::eod
))
155 return Diag(MacroNameTok
, diag::err_pp_missing_macro_name
);
157 IdentifierInfo
*II
= MacroNameTok
.getIdentifierInfo();
159 bool Invalid
= false;
160 std::string Spelling
= getSpelling(MacroNameTok
, &Invalid
);
162 return Diag(MacroNameTok
, diag::err_pp_macro_not_identifier
);
163 II
= getIdentifierInfo(Spelling
);
165 if (!II
->isCPlusPlusOperatorKeyword())
166 return Diag(MacroNameTok
, diag::err_pp_macro_not_identifier
);
168 // C++ 2.5p2: Alternative tokens behave the same as its primary token
169 // except for their spellings.
170 Diag(MacroNameTok
, getLangOpts().MicrosoftExt
171 ? diag::ext_pp_operator_used_as_macro_name
172 : diag::err_pp_operator_used_as_macro_name
)
173 << II
<< MacroNameTok
.getKind();
175 // Allow #defining |and| and friends for Microsoft compatibility or
176 // recovery when legacy C headers are included in C++.
177 MacroNameTok
.setIdentifierInfo(II
);
180 if ((isDefineUndef
!= MU_Other
) && II
->getPPKeywordID() == tok::pp_defined
) {
181 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
182 return Diag(MacroNameTok
, diag::err_defined_macro_name
);
185 if (isDefineUndef
== MU_Undef
&& II
->hasMacroDefinition() &&
186 getMacroInfo(II
)->isBuiltinMacro()) {
187 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
188 // and C++ [cpp.predefined]p4], but allow it as an extension.
189 Diag(MacroNameTok
, diag::ext_pp_undef_builtin_macro
);
192 // If defining/undefining reserved identifier or a keyword, we need to issue
194 SourceLocation MacroNameLoc
= MacroNameTok
.getLocation();
197 if (!SourceMgr
.isInSystemHeader(MacroNameLoc
) &&
198 (strcmp(SourceMgr
.getBufferName(MacroNameLoc
), "<built-in>") != 0)) {
199 MacroDiag D
= MD_NoWarn
;
200 if (isDefineUndef
== MU_Define
) {
201 D
= shouldWarnOnMacroDef(*this, II
);
203 else if (isDefineUndef
== MU_Undef
)
204 D
= shouldWarnOnMacroUndef(*this, II
);
205 if (D
== MD_KeywordDef
) {
206 // We do not want to warn on some patterns widely used in configuration
207 // scripts. This requires analyzing next tokens, so do not issue warnings
208 // now, only inform caller.
212 if (D
== MD_ReservedMacro
)
213 Diag(MacroNameTok
, diag::warn_pp_macro_is_reserved_id
);
216 // Okay, we got a good identifier.
220 /// \brief Lex and validate a macro name, which occurs after a
221 /// \#define or \#undef.
223 /// This sets the token kind to eod and discards the rest of the macro line if
224 /// the macro name is invalid.
226 /// \param MacroNameTok Token that is expected to be a macro name.
227 /// \param isDefineUndef Context in which macro is used.
228 /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
229 void Preprocessor::ReadMacroName(Token
&MacroNameTok
, MacroUse isDefineUndef
,
231 // Read the token, don't allow macro expansion on it.
232 LexUnexpandedToken(MacroNameTok
);
234 if (MacroNameTok
.is(tok::code_completion
)) {
236 CodeComplete
->CodeCompleteMacroName(isDefineUndef
== MU_Define
);
237 setCodeCompletionReached();
238 LexUnexpandedToken(MacroNameTok
);
241 if (!CheckMacroName(MacroNameTok
, isDefineUndef
, ShadowFlag
))
244 // Invalid macro name, read and discard the rest of the line and set the
245 // token kind to tok::eod if necessary.
246 if (MacroNameTok
.isNot(tok::eod
)) {
247 MacroNameTok
.setKind(tok::eod
);
248 DiscardUntilEndOfDirective();
252 /// \brief Ensure that the next token is a tok::eod token.
254 /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
255 /// true, then we consider macros that expand to zero tokens as being ok.
256 void Preprocessor::CheckEndOfDirective(const char *DirType
, bool EnableMacros
) {
258 // Lex unexpanded tokens for most directives: macros might expand to zero
259 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
260 // #line) allow empty macros.
264 LexUnexpandedToken(Tmp
);
266 // There should be no tokens after the directive, but we allow them as an
268 while (Tmp
.is(tok::comment
)) // Skip comments in -C mode.
269 LexUnexpandedToken(Tmp
);
271 if (Tmp
.isNot(tok::eod
)) {
272 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
273 // or if this is a macro-style preprocessing directive, because it is more
274 // trouble than it is worth to insert /**/ and check that there is no /**/
275 // in the range also.
277 if ((LangOpts
.GNUMode
|| LangOpts
.C99
|| LangOpts
.CPlusPlus
) &&
279 Hint
= FixItHint::CreateInsertion(Tmp
.getLocation(),"//");
280 Diag(Tmp
, diag::ext_pp_extra_tokens_at_eol
) << DirType
<< Hint
;
281 DiscardUntilEndOfDirective();
287 /// SkipExcludedConditionalBlock - We just read a \#if or related directive and
288 /// decided that the subsequent tokens are in the \#if'd out portion of the
289 /// file. Lex the rest of the file, until we see an \#endif. If
290 /// FoundNonSkipPortion is true, then we have already emitted code for part of
291 /// this \#if directive, so \#else/\#elif blocks should never be entered.
292 /// If ElseOk is true, then \#else directives are ok, if not, then we have
293 /// already seen one so a \#else directive is a duplicate. When this returns,
294 /// the caller can lex the first valid token.
295 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc
,
296 bool FoundNonSkipPortion
,
298 SourceLocation ElseLoc
) {
300 assert(!CurTokenLexer
&& CurPPLexer
&& "Lexing a macro, not a file?");
302 CurPPLexer
->pushConditionalLevel(IfTokenLoc
, /*isSkipping*/false,
303 FoundNonSkipPortion
, FoundElse
);
306 PTHSkipExcludedConditionalBlock();
310 // Enter raw mode to disable identifier lookup (and thus macro expansion),
311 // disabling warnings, etc.
312 CurPPLexer
->LexingRawMode
= true;
317 if (Tok
.is(tok::code_completion
)) {
319 CodeComplete
->CodeCompleteInConditionalExclusion();
320 setCodeCompletionReached();
324 // If this is the end of the buffer, we have an error.
325 if (Tok
.is(tok::eof
)) {
326 // Emit errors for each unterminated conditional on the stack, including
328 while (!CurPPLexer
->ConditionalStack
.empty()) {
329 if (CurLexer
->getFileLoc() != CodeCompletionFileLoc
)
330 Diag(CurPPLexer
->ConditionalStack
.back().IfLoc
,
331 diag::err_pp_unterminated_conditional
);
332 CurPPLexer
->ConditionalStack
.pop_back();
335 // Just return and let the caller lex after this #include.
339 // If this token is not a preprocessor directive, just skip it.
340 if (Tok
.isNot(tok::hash
) || !Tok
.isAtStartOfLine())
343 // We just parsed a # character at the start of a line, so we're in
344 // directive mode. Tell the lexer this so any newlines we see will be
345 // converted into an EOD token (this terminates the macro).
346 CurPPLexer
->ParsingPreprocessorDirective
= true;
347 if (CurLexer
) CurLexer
->SetKeepWhitespaceMode(false);
350 // Read the next token, the directive flavor.
351 LexUnexpandedToken(Tok
);
353 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
354 // something bogus), skip it.
355 if (Tok
.isNot(tok::raw_identifier
)) {
356 CurPPLexer
->ParsingPreprocessorDirective
= false;
357 // Restore comment saving mode.
358 if (CurLexer
) CurLexer
->resetExtendedTokenMode();
362 // If the first letter isn't i or e, it isn't intesting to us. We know that
363 // this is safe in the face of spelling differences, because there is no way
364 // to spell an i/e in a strange way that is another letter. Skipping this
365 // allows us to avoid looking up the identifier info for #define/#undef and
366 // other common directives.
367 StringRef RI
= Tok
.getRawIdentifier();
369 char FirstChar
= RI
[0];
370 if (FirstChar
>= 'a' && FirstChar
<= 'z' &&
371 FirstChar
!= 'i' && FirstChar
!= 'e') {
372 CurPPLexer
->ParsingPreprocessorDirective
= false;
373 // Restore comment saving mode.
374 if (CurLexer
) CurLexer
->resetExtendedTokenMode();
378 // Get the identifier name without trigraphs or embedded newlines. Note
379 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
381 char DirectiveBuf
[20];
383 if (!Tok
.needsCleaning() && RI
.size() < 20) {
386 std::string DirectiveStr
= getSpelling(Tok
);
387 unsigned IdLen
= DirectiveStr
.size();
389 CurPPLexer
->ParsingPreprocessorDirective
= false;
390 // Restore comment saving mode.
391 if (CurLexer
) CurLexer
->resetExtendedTokenMode();
394 memcpy(DirectiveBuf
, &DirectiveStr
[0], IdLen
);
395 Directive
= StringRef(DirectiveBuf
, IdLen
);
398 if (Directive
.startswith("if")) {
399 StringRef Sub
= Directive
.substr(2);
400 if (Sub
.empty() || // "if"
401 Sub
== "def" || // "ifdef"
402 Sub
== "ndef") { // "ifndef"
403 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
404 // bother parsing the condition.
405 DiscardUntilEndOfDirective();
406 CurPPLexer
->pushConditionalLevel(Tok
.getLocation(), /*wasskipping*/true,
407 /*foundnonskip*/false,
410 } else if (Directive
[0] == 'e') {
411 StringRef Sub
= Directive
.substr(1);
412 if (Sub
== "ndif") { // "endif"
413 PPConditionalInfo CondInfo
;
414 CondInfo
.WasSkipping
= true; // Silence bogus warning.
415 bool InCond
= CurPPLexer
->popConditionalLevel(CondInfo
);
416 (void)InCond
; // Silence warning in no-asserts mode.
417 assert(!InCond
&& "Can't be skipping if not in a conditional!");
419 // If we popped the outermost skipping block, we're done skipping!
420 if (!CondInfo
.WasSkipping
) {
421 // Restore the value of LexingRawMode so that trailing comments
422 // are handled correctly, if we've reached the outermost block.
423 CurPPLexer
->LexingRawMode
= false;
424 CheckEndOfDirective("endif");
425 CurPPLexer
->LexingRawMode
= true;
427 Callbacks
->Endif(Tok
.getLocation(), CondInfo
.IfLoc
);
430 DiscardUntilEndOfDirective();
432 } else if (Sub
== "lse") { // "else".
433 // #else directive in a skipping conditional. If not in some other
434 // skipping conditional, and if #else hasn't already been seen, enter it
435 // as a non-skipping conditional.
436 PPConditionalInfo
&CondInfo
= CurPPLexer
->peekConditionalLevel();
438 // If this is a #else with a #else before it, report the error.
439 if (CondInfo
.FoundElse
) Diag(Tok
, diag::pp_err_else_after_else
);
441 // Note that we've seen a #else in this conditional.
442 CondInfo
.FoundElse
= true;
444 // If the conditional is at the top level, and the #if block wasn't
445 // entered, enter the #else block now.
446 if (!CondInfo
.WasSkipping
&& !CondInfo
.FoundNonSkip
) {
447 CondInfo
.FoundNonSkip
= true;
448 // Restore the value of LexingRawMode so that trailing comments
449 // are handled correctly.
450 CurPPLexer
->LexingRawMode
= false;
451 CheckEndOfDirective("else");
452 CurPPLexer
->LexingRawMode
= true;
454 Callbacks
->Else(Tok
.getLocation(), CondInfo
.IfLoc
);
457 DiscardUntilEndOfDirective(); // C99 6.10p4.
459 } else if (Sub
== "lif") { // "elif".
460 PPConditionalInfo
&CondInfo
= CurPPLexer
->peekConditionalLevel();
462 // If this is a #elif with a #else before it, report the error.
463 if (CondInfo
.FoundElse
) Diag(Tok
, diag::pp_err_elif_after_else
);
465 // If this is in a skipping block or if we're already handled this #if
466 // block, don't bother parsing the condition.
467 if (CondInfo
.WasSkipping
|| CondInfo
.FoundNonSkip
) {
468 DiscardUntilEndOfDirective();
470 const SourceLocation CondBegin
= CurPPLexer
->getSourceLocation();
471 // Restore the value of LexingRawMode so that identifiers are
472 // looked up, etc, inside the #elif expression.
473 assert(CurPPLexer
->LexingRawMode
&& "We have to be skipping here!");
474 CurPPLexer
->LexingRawMode
= false;
475 IdentifierInfo
*IfNDefMacro
= nullptr;
476 const bool CondValue
= EvaluateDirectiveExpression(IfNDefMacro
);
477 CurPPLexer
->LexingRawMode
= true;
479 const SourceLocation CondEnd
= CurPPLexer
->getSourceLocation();
480 Callbacks
->Elif(Tok
.getLocation(),
481 SourceRange(CondBegin
, CondEnd
),
482 (CondValue
? PPCallbacks::CVK_True
: PPCallbacks::CVK_False
), CondInfo
.IfLoc
);
484 // If this condition is true, enter it!
486 CondInfo
.FoundNonSkip
= true;
493 CurPPLexer
->ParsingPreprocessorDirective
= false;
494 // Restore comment saving mode.
495 if (CurLexer
) CurLexer
->resetExtendedTokenMode();
498 // Finally, if we are out of the conditional (saw an #endif or ran off the end
499 // of the file, just stop skipping and return to lexing whatever came after
501 CurPPLexer
->LexingRawMode
= false;
504 SourceLocation BeginLoc
= ElseLoc
.isValid() ? ElseLoc
: IfTokenLoc
;
505 Callbacks
->SourceRangeSkipped(SourceRange(BeginLoc
, Tok
.getLocation()));
509 void Preprocessor::PTHSkipExcludedConditionalBlock() {
513 assert(CurPTHLexer
->LexingRawMode
== false);
515 // Skip to the next '#else', '#elif', or #endif.
516 if (CurPTHLexer
->SkipBlock()) {
517 // We have reached an #endif. Both the '#' and 'endif' tokens
518 // have been consumed by the PTHLexer. Just pop off the condition level.
519 PPConditionalInfo CondInfo
;
520 bool InCond
= CurPTHLexer
->popConditionalLevel(CondInfo
);
521 (void)InCond
; // Silence warning in no-asserts mode.
522 assert(!InCond
&& "Can't be skipping if not in a conditional!");
526 // We have reached a '#else' or '#elif'. Lex the next token to get
527 // the directive flavor.
529 LexUnexpandedToken(Tok
);
531 // We can actually look up the IdentifierInfo here since we aren't in
533 tok::PPKeywordKind K
= Tok
.getIdentifierInfo()->getPPKeywordID();
535 if (K
== tok::pp_else
) {
536 // #else: Enter the else condition. We aren't in a nested condition
537 // since we skip those. We're always in the one matching the last
538 // blocked we skipped.
539 PPConditionalInfo
&CondInfo
= CurPTHLexer
->peekConditionalLevel();
540 // Note that we've seen a #else in this conditional.
541 CondInfo
.FoundElse
= true;
543 // If the #if block wasn't entered then enter the #else block now.
544 if (!CondInfo
.FoundNonSkip
) {
545 CondInfo
.FoundNonSkip
= true;
547 // Scan until the eod token.
548 CurPTHLexer
->ParsingPreprocessorDirective
= true;
549 DiscardUntilEndOfDirective();
550 CurPTHLexer
->ParsingPreprocessorDirective
= false;
555 // Otherwise skip this block.
559 assert(K
== tok::pp_elif
);
560 PPConditionalInfo
&CondInfo
= CurPTHLexer
->peekConditionalLevel();
562 // If this is a #elif with a #else before it, report the error.
563 if (CondInfo
.FoundElse
)
564 Diag(Tok
, diag::pp_err_elif_after_else
);
566 // If this is in a skipping block or if we're already handled this #if
567 // block, don't bother parsing the condition. We just skip this block.
568 if (CondInfo
.FoundNonSkip
)
571 // Evaluate the condition of the #elif.
572 IdentifierInfo
*IfNDefMacro
= nullptr;
573 CurPTHLexer
->ParsingPreprocessorDirective
= true;
574 bool ShouldEnter
= EvaluateDirectiveExpression(IfNDefMacro
);
575 CurPTHLexer
->ParsingPreprocessorDirective
= false;
577 // If this condition is true, enter it!
579 CondInfo
.FoundNonSkip
= true;
583 // Otherwise, skip this block and go to the next one.
588 Module
*Preprocessor::getModuleForLocation(SourceLocation FilenameLoc
) {
589 ModuleMap
&ModMap
= HeaderInfo
.getModuleMap();
590 if (SourceMgr
.isInMainFile(FilenameLoc
)) {
591 if (Module
*CurMod
= getCurrentModule())
592 return CurMod
; // Compiling a module.
593 return HeaderInfo
.getModuleMap().SourceModule
; // Compiling a source.
595 // Try to determine the module of the include directive.
596 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
597 FileID IDOfIncl
= SourceMgr
.getFileID(SourceMgr
.getExpansionLoc(FilenameLoc
));
598 if (const FileEntry
*EntryOfIncl
= SourceMgr
.getFileEntryForID(IDOfIncl
)) {
599 // The include comes from a file.
600 return ModMap
.findModuleForHeader(EntryOfIncl
).getModule();
602 // The include does not come from a file,
603 // so it is probably a module compilation.
604 return getCurrentModule();
608 const FileEntry
*Preprocessor::LookupFile(
609 SourceLocation FilenameLoc
,
612 const DirectoryLookup
*FromDir
,
613 const FileEntry
*FromFile
,
614 const DirectoryLookup
*&CurDir
,
615 SmallVectorImpl
<char> *SearchPath
,
616 SmallVectorImpl
<char> *RelativePath
,
617 ModuleMap::KnownHeader
*SuggestedModule
,
619 // If the header lookup mechanism may be relative to the current inclusion
620 // stack, record the parent #includes.
621 SmallVector
<std::pair
<const FileEntry
*, const DirectoryEntry
*>, 16>
623 if (!FromDir
&& !FromFile
) {
624 FileID FID
= getCurrentFileLexer()->getFileID();
625 const FileEntry
*FileEnt
= SourceMgr
.getFileEntryForID(FID
);
627 // If there is no file entry associated with this file, it must be the
628 // predefines buffer or the module includes buffer. Any other file is not
629 // lexed with a normal lexer, so it won't be scanned for preprocessor
632 // If we have the predefines buffer, resolve #include references (which come
633 // from the -include command line argument) from the current working
634 // directory instead of relative to the main file.
636 // If we have the module includes buffer, resolve #include references (which
637 // come from header declarations in the module map) relative to the module
640 if (FID
== SourceMgr
.getMainFileID() && MainFileDir
)
641 Includers
.push_back(std::make_pair(nullptr, MainFileDir
));
643 SourceMgr
.getFileEntryForID(SourceMgr
.getMainFileID())))
644 Includers
.push_back(std::make_pair(FileEnt
, FileMgr
.getDirectory(".")));
646 Includers
.push_back(std::make_pair(FileEnt
, FileEnt
->getDir()));
649 // MSVC searches the current include stack from top to bottom for
650 // headers included by quoted include directives.
651 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
652 if (LangOpts
.MSVCCompat
&& !isAngled
) {
653 for (unsigned i
= 0, e
= IncludeMacroStack
.size(); i
!= e
; ++i
) {
654 IncludeStackInfo
&ISEntry
= IncludeMacroStack
[e
- i
- 1];
655 if (IsFileLexer(ISEntry
))
656 if ((FileEnt
= SourceMgr
.getFileEntryForID(
657 ISEntry
.ThePPLexer
->getFileID())))
658 Includers
.push_back(std::make_pair(FileEnt
, FileEnt
->getDir()));
663 CurDir
= CurDirLookup
;
666 // We're supposed to start looking from after a particular file. Search
667 // the include path until we find that file or run out of files.
668 const DirectoryLookup
*TmpCurDir
= CurDir
;
669 const DirectoryLookup
*TmpFromDir
= nullptr;
670 while (const FileEntry
*FE
= HeaderInfo
.LookupFile(
671 Filename
, FilenameLoc
, isAngled
, TmpFromDir
, TmpCurDir
,
672 Includers
, SearchPath
, RelativePath
, SuggestedModule
,
674 // Keep looking as if this file did a #include_next.
675 TmpFromDir
= TmpCurDir
;
677 if (FE
== FromFile
) {
679 FromDir
= TmpFromDir
;
686 // Do a standard file entry lookup.
687 const FileEntry
*FE
= HeaderInfo
.LookupFile(
688 Filename
, FilenameLoc
, isAngled
, FromDir
, CurDir
, Includers
, SearchPath
,
689 RelativePath
, SuggestedModule
, SkipCache
);
691 if (SuggestedModule
&& !LangOpts
.AsmPreprocessor
)
692 HeaderInfo
.getModuleMap().diagnoseHeaderInclusion(
693 getModuleForLocation(FilenameLoc
), FilenameLoc
, Filename
, FE
);
697 const FileEntry
*CurFileEnt
;
698 // Otherwise, see if this is a subframework header. If so, this is relative
699 // to one of the headers on the #include stack. Walk the list of the current
700 // headers on the #include stack and pass them to HeaderInfo.
702 if ((CurFileEnt
= SourceMgr
.getFileEntryForID(CurPPLexer
->getFileID()))) {
703 if ((FE
= HeaderInfo
.LookupSubframeworkHeader(Filename
, CurFileEnt
,
704 SearchPath
, RelativePath
,
706 if (SuggestedModule
&& !LangOpts
.AsmPreprocessor
)
707 HeaderInfo
.getModuleMap().diagnoseHeaderInclusion(
708 getModuleForLocation(FilenameLoc
), FilenameLoc
, Filename
, FE
);
714 for (unsigned i
= 0, e
= IncludeMacroStack
.size(); i
!= e
; ++i
) {
715 IncludeStackInfo
&ISEntry
= IncludeMacroStack
[e
-i
-1];
716 if (IsFileLexer(ISEntry
)) {
718 SourceMgr
.getFileEntryForID(ISEntry
.ThePPLexer
->getFileID()))) {
719 if ((FE
= HeaderInfo
.LookupSubframeworkHeader(
720 Filename
, CurFileEnt
, SearchPath
, RelativePath
,
722 if (SuggestedModule
&& !LangOpts
.AsmPreprocessor
)
723 HeaderInfo
.getModuleMap().diagnoseHeaderInclusion(
724 getModuleForLocation(FilenameLoc
), FilenameLoc
, Filename
, FE
);
731 // Otherwise, we really couldn't find the file.
736 //===----------------------------------------------------------------------===//
737 // Preprocessor Directive Handling.
738 //===----------------------------------------------------------------------===//
740 class Preprocessor::ResetMacroExpansionHelper
{
742 ResetMacroExpansionHelper(Preprocessor
*pp
)
743 : PP(pp
), save(pp
->DisableMacroExpansion
) {
744 if (pp
->MacroExpansionInDirectivesOverride
)
745 pp
->DisableMacroExpansion
= false;
747 ~ResetMacroExpansionHelper() {
748 PP
->DisableMacroExpansion
= save
;
755 /// HandleDirective - This callback is invoked when the lexer sees a # token
756 /// at the start of a line. This consumes the directive, modifies the
757 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
758 /// read is the correct one.
759 void Preprocessor::HandleDirective(Token
&Result
) {
760 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
762 // We just parsed a # character at the start of a line, so we're in directive
763 // mode. Tell the lexer this so any newlines we see will be converted into an
764 // EOD token (which terminates the directive).
765 CurPPLexer
->ParsingPreprocessorDirective
= true;
766 if (CurLexer
) CurLexer
->SetKeepWhitespaceMode(false);
768 bool ImmediatelyAfterTopLevelIfndef
=
769 CurPPLexer
->MIOpt
.getImmediatelyAfterTopLevelIfndef();
770 CurPPLexer
->MIOpt
.resetImmediatelyAfterTopLevelIfndef();
774 // We are about to read a token. For the multiple-include optimization FA to
775 // work, we have to remember if we had read any tokens *before* this
777 bool ReadAnyTokensBeforeDirective
=CurPPLexer
->MIOpt
.getHasReadAnyTokensVal();
779 // Save the '#' token in case we need to return it later.
780 Token SavedHash
= Result
;
782 // Read the next token, the directive flavor. This isn't expanded due to
784 LexUnexpandedToken(Result
);
786 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
791 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
792 // not support this for #include-like directives, since that can result in
793 // terrible diagnostics, and does not work in GCC.
795 if (IdentifierInfo
*II
= Result
.getIdentifierInfo()) {
796 switch (II
->getPPKeywordID()) {
797 case tok::pp_include
:
799 case tok::pp_include_next
:
800 case tok::pp___include_macros
:
802 Diag(Result
, diag::err_embedded_directive
) << II
->getName();
803 DiscardUntilEndOfDirective();
809 Diag(Result
, diag::ext_embedded_directive
);
812 // Temporarily enable macro expansion if set so
813 // and reset to previous state when returning from this function.
814 ResetMacroExpansionHelper
helper(this);
816 switch (Result
.getKind()) {
818 return; // null directive.
819 case tok::code_completion
:
821 CodeComplete
->CodeCompleteDirective(
822 CurPPLexer
->getConditionalStackDepth() > 0);
823 setCodeCompletionReached();
825 case tok::numeric_constant
: // # 7 GNU line marker directive.
826 if (getLangOpts().AsmPreprocessor
)
827 break; // # 4 is not a preprocessor directive in .S files.
828 return HandleDigitDirective(Result
);
830 IdentifierInfo
*II
= Result
.getIdentifierInfo();
831 if (!II
) break; // Not an identifier.
833 // Ask what the preprocessor keyword ID is.
834 switch (II
->getPPKeywordID()) {
836 // C99 6.10.1 - Conditional Inclusion.
838 return HandleIfDirective(Result
, ReadAnyTokensBeforeDirective
);
840 return HandleIfdefDirective(Result
, false, true/*not valid for miopt*/);
842 return HandleIfdefDirective(Result
, true, ReadAnyTokensBeforeDirective
);
844 return HandleElifDirective(Result
);
846 return HandleElseDirective(Result
);
848 return HandleEndifDirective(Result
);
850 // C99 6.10.2 - Source File Inclusion.
851 case tok::pp_include
:
853 return HandleIncludeDirective(SavedHash
.getLocation(), Result
);
854 case tok::pp___include_macros
:
856 return HandleIncludeMacrosDirective(SavedHash
.getLocation(), Result
);
858 // C99 6.10.3 - Macro Replacement.
860 return HandleDefineDirective(Result
, ImmediatelyAfterTopLevelIfndef
);
862 return HandleUndefDirective(Result
);
864 // C99 6.10.4 - Line Control.
866 return HandleLineDirective(Result
);
868 // C99 6.10.5 - Error Directive.
870 return HandleUserDiagnosticDirective(Result
, false);
872 // C99 6.10.6 - Pragma Directive.
874 return HandlePragmaDirective(SavedHash
.getLocation(), PIK_HashPragma
);
878 return HandleImportDirective(SavedHash
.getLocation(), Result
);
879 case tok::pp_include_next
:
880 return HandleIncludeNextDirective(SavedHash
.getLocation(), Result
);
882 case tok::pp_warning
:
883 Diag(Result
, diag::ext_pp_warning_directive
);
884 return HandleUserDiagnosticDirective(Result
, true);
886 return HandleIdentSCCSDirective(Result
);
888 return HandleIdentSCCSDirective(Result
);
890 //isExtension = true; // FIXME: implement #assert
892 case tok::pp_unassert
:
893 //isExtension = true; // FIXME: implement #unassert
896 case tok::pp___public_macro
:
897 if (getLangOpts().Modules
)
898 return HandleMacroPublicDirective(Result
);
901 case tok::pp___private_macro
:
902 if (getLangOpts().Modules
)
903 return HandleMacroPrivateDirective(Result
);
909 // If this is a .S file, treat unknown # directives as non-preprocessor
910 // directives. This is important because # may be a comment or introduce
911 // various pseudo-ops. Just return the # token and push back the following
912 // token to be lexed next time.
913 if (getLangOpts().AsmPreprocessor
) {
914 Token
*Toks
= new Token
[2];
915 // Return the # and the token after it.
919 // If the second token is a hashhash token, then we need to translate it to
920 // unknown so the token lexer doesn't try to perform token pasting.
921 if (Result
.is(tok::hashhash
))
922 Toks
[1].setKind(tok::unknown
);
924 // Enter this token stream so that we re-lex the tokens. Make sure to
925 // enable macro expansion, in case the token after the # is an identifier
927 EnterTokenStream(Toks
, 2, false, true);
931 // If we reached here, the preprocessing token is not valid!
932 Diag(Result
, diag::err_pp_invalid_directive
);
934 // Read the rest of the PP line.
935 DiscardUntilEndOfDirective();
937 // Okay, we're done parsing the directive.
940 /// GetLineValue - Convert a numeric token into an unsigned value, emitting
941 /// Diagnostic DiagID if it is invalid, and returning the value in Val.
942 static bool GetLineValue(Token
&DigitTok
, unsigned &Val
,
943 unsigned DiagID
, Preprocessor
&PP
,
944 bool IsGNULineDirective
=false) {
945 if (DigitTok
.isNot(tok::numeric_constant
)) {
946 PP
.Diag(DigitTok
, DiagID
);
948 if (DigitTok
.isNot(tok::eod
))
949 PP
.DiscardUntilEndOfDirective();
953 SmallString
<64> IntegerBuffer
;
954 IntegerBuffer
.resize(DigitTok
.getLength());
955 const char *DigitTokBegin
= &IntegerBuffer
[0];
956 bool Invalid
= false;
957 unsigned ActualLength
= PP
.getSpelling(DigitTok
, DigitTokBegin
, &Invalid
);
961 // Verify that we have a simple digit-sequence, and compute the value. This
962 // is always a simple digit string computed in decimal, so we do this manually
965 for (unsigned i
= 0; i
!= ActualLength
; ++i
) {
966 // C++1y [lex.fcon]p1:
967 // Optional separating single quotes in a digit-sequence are ignored
968 if (DigitTokBegin
[i
] == '\'')
971 if (!isDigit(DigitTokBegin
[i
])) {
972 PP
.Diag(PP
.AdvanceToTokenCharacter(DigitTok
.getLocation(), i
),
973 diag::err_pp_line_digit_sequence
) << IsGNULineDirective
;
974 PP
.DiscardUntilEndOfDirective();
978 unsigned NextVal
= Val
*10+(DigitTokBegin
[i
]-'0');
979 if (NextVal
< Val
) { // overflow.
980 PP
.Diag(DigitTok
, DiagID
);
981 PP
.DiscardUntilEndOfDirective();
987 if (DigitTokBegin
[0] == '0' && Val
)
988 PP
.Diag(DigitTok
.getLocation(), diag::warn_pp_line_decimal
)
989 << IsGNULineDirective
;
994 /// \brief Handle a \#line directive: C99 6.10.4.
996 /// The two acceptable forms are:
998 /// # line digit-sequence
999 /// # line digit-sequence "s-char-sequence"
1001 void Preprocessor::HandleLineDirective(Token
&Tok
) {
1002 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1007 // Validate the number and convert it to an unsigned.
1009 if (GetLineValue(DigitTok
, LineNo
, diag::err_pp_line_requires_integer
,*this))
1013 Diag(DigitTok
, diag::ext_pp_line_zero
);
1015 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1016 // number greater than 2147483647". C90 requires that the line # be <= 32767.
1017 unsigned LineLimit
= 32768U;
1018 if (LangOpts
.C99
|| LangOpts
.CPlusPlus11
)
1019 LineLimit
= 2147483648U;
1020 if (LineNo
>= LineLimit
)
1021 Diag(DigitTok
, diag::ext_pp_line_too_big
) << LineLimit
;
1022 else if (LangOpts
.CPlusPlus11
&& LineNo
>= 32768U)
1023 Diag(DigitTok
, diag::warn_cxx98_compat_pp_line_too_big
);
1025 int FilenameID
= -1;
1029 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1030 // string followed by eod.
1031 if (StrTok
.is(tok::eod
))
1033 else if (StrTok
.isNot(tok::string_literal
)) {
1034 Diag(StrTok
, diag::err_pp_line_invalid_filename
);
1035 return DiscardUntilEndOfDirective();
1036 } else if (StrTok
.hasUDSuffix()) {
1037 Diag(StrTok
, diag::err_invalid_string_udl
);
1038 return DiscardUntilEndOfDirective();
1040 // Parse and validate the string, converting it into a unique ID.
1041 StringLiteralParser
Literal(StrTok
, *this);
1042 assert(Literal
.isAscii() && "Didn't allow wide strings in");
1043 if (Literal
.hadError
)
1044 return DiscardUntilEndOfDirective();
1045 if (Literal
.Pascal
) {
1046 Diag(StrTok
, diag::err_pp_linemarker_invalid_filename
);
1047 return DiscardUntilEndOfDirective();
1049 FilenameID
= SourceMgr
.getLineTableFilenameID(Literal
.GetString());
1051 // Verify that there is nothing after the string, other than EOD. Because
1052 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1053 CheckEndOfDirective("line", true);
1056 SourceMgr
.AddLineNote(DigitTok
.getLocation(), LineNo
, FilenameID
);
1059 Callbacks
->FileChanged(CurPPLexer
->getSourceLocation(),
1060 PPCallbacks::RenameFile
,
1064 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1065 /// marker directive.
1066 static bool ReadLineMarkerFlags(bool &IsFileEntry
, bool &IsFileExit
,
1067 bool &IsSystemHeader
, bool &IsExternCHeader
,
1072 if (FlagTok
.is(tok::eod
)) return false;
1073 if (GetLineValue(FlagTok
, FlagVal
, diag::err_pp_linemarker_invalid_flag
, PP
))
1080 if (FlagTok
.is(tok::eod
)) return false;
1081 if (GetLineValue(FlagTok
, FlagVal
, diag::err_pp_linemarker_invalid_flag
,PP
))
1083 } else if (FlagVal
== 2) {
1086 SourceManager
&SM
= PP
.getSourceManager();
1087 // If we are leaving the current presumed file, check to make sure the
1088 // presumed include stack isn't empty!
1090 SM
.getDecomposedExpansionLoc(FlagTok
.getLocation()).first
;
1091 PresumedLoc PLoc
= SM
.getPresumedLoc(FlagTok
.getLocation());
1092 if (PLoc
.isInvalid())
1095 // If there is no include loc (main file) or if the include loc is in a
1096 // different physical file, then we aren't in a "1" line marker flag region.
1097 SourceLocation IncLoc
= PLoc
.getIncludeLoc();
1098 if (IncLoc
.isInvalid() ||
1099 SM
.getDecomposedExpansionLoc(IncLoc
).first
!= CurFileID
) {
1100 PP
.Diag(FlagTok
, diag::err_pp_linemarker_invalid_pop
);
1101 PP
.DiscardUntilEndOfDirective();
1106 if (FlagTok
.is(tok::eod
)) return false;
1107 if (GetLineValue(FlagTok
, FlagVal
, diag::err_pp_linemarker_invalid_flag
,PP
))
1111 // We must have 3 if there are still flags.
1113 PP
.Diag(FlagTok
, diag::err_pp_linemarker_invalid_flag
);
1114 PP
.DiscardUntilEndOfDirective();
1118 IsSystemHeader
= true;
1121 if (FlagTok
.is(tok::eod
)) return false;
1122 if (GetLineValue(FlagTok
, FlagVal
, diag::err_pp_linemarker_invalid_flag
, PP
))
1125 // We must have 4 if there is yet another flag.
1127 PP
.Diag(FlagTok
, diag::err_pp_linemarker_invalid_flag
);
1128 PP
.DiscardUntilEndOfDirective();
1132 IsExternCHeader
= true;
1135 if (FlagTok
.is(tok::eod
)) return false;
1137 // There are no more valid flags here.
1138 PP
.Diag(FlagTok
, diag::err_pp_linemarker_invalid_flag
);
1139 PP
.DiscardUntilEndOfDirective();
1143 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1144 /// one of the following forms:
1147 /// # 42 "file" ('1' | '2')?
1148 /// # 42 "file" ('1' | '2')? '3' '4'?
1150 void Preprocessor::HandleDigitDirective(Token
&DigitTok
) {
1151 // Validate the number and convert it to an unsigned. GNU does not have a
1152 // line # limit other than it fit in 32-bits.
1154 if (GetLineValue(DigitTok
, LineNo
, diag::err_pp_linemarker_requires_integer
,
1161 bool IsFileEntry
= false, IsFileExit
= false;
1162 bool IsSystemHeader
= false, IsExternCHeader
= false;
1163 int FilenameID
= -1;
1165 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1166 // string followed by eod.
1167 if (StrTok
.is(tok::eod
))
1169 else if (StrTok
.isNot(tok::string_literal
)) {
1170 Diag(StrTok
, diag::err_pp_linemarker_invalid_filename
);
1171 return DiscardUntilEndOfDirective();
1172 } else if (StrTok
.hasUDSuffix()) {
1173 Diag(StrTok
, diag::err_invalid_string_udl
);
1174 return DiscardUntilEndOfDirective();
1176 // Parse and validate the string, converting it into a unique ID.
1177 StringLiteralParser
Literal(StrTok
, *this);
1178 assert(Literal
.isAscii() && "Didn't allow wide strings in");
1179 if (Literal
.hadError
)
1180 return DiscardUntilEndOfDirective();
1181 if (Literal
.Pascal
) {
1182 Diag(StrTok
, diag::err_pp_linemarker_invalid_filename
);
1183 return DiscardUntilEndOfDirective();
1185 FilenameID
= SourceMgr
.getLineTableFilenameID(Literal
.GetString());
1187 // If a filename was present, read any flags that are present.
1188 if (ReadLineMarkerFlags(IsFileEntry
, IsFileExit
,
1189 IsSystemHeader
, IsExternCHeader
, *this))
1193 // Create a line note with this information.
1194 SourceMgr
.AddLineNote(DigitTok
.getLocation(), LineNo
, FilenameID
,
1195 IsFileEntry
, IsFileExit
,
1196 IsSystemHeader
, IsExternCHeader
);
1198 // If the preprocessor has callbacks installed, notify them of the #line
1199 // change. This is used so that the line marker comes out in -E mode for
1202 PPCallbacks::FileChangeReason Reason
= PPCallbacks::RenameFile
;
1204 Reason
= PPCallbacks::EnterFile
;
1205 else if (IsFileExit
)
1206 Reason
= PPCallbacks::ExitFile
;
1207 SrcMgr::CharacteristicKind FileKind
= SrcMgr::C_User
;
1208 if (IsExternCHeader
)
1209 FileKind
= SrcMgr::C_ExternCSystem
;
1210 else if (IsSystemHeader
)
1211 FileKind
= SrcMgr::C_System
;
1213 Callbacks
->FileChanged(CurPPLexer
->getSourceLocation(), Reason
, FileKind
);
1218 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1220 void Preprocessor::HandleUserDiagnosticDirective(Token
&Tok
,
1222 // PTH doesn't emit #warning or #error directives.
1224 return CurPTHLexer
->DiscardToEndOfLine();
1226 // Read the rest of the line raw. We do this because we don't want macros
1227 // to be expanded and we don't require that the tokens be valid preprocessing
1228 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1229 // collapse multiple consequtive white space between tokens, but this isn't
1230 // specified by the standard.
1231 SmallString
<128> Message
;
1232 CurLexer
->ReadToEndOfLine(&Message
);
1234 // Find the first non-whitespace character, so that we can make the
1235 // diagnostic more succinct.
1236 StringRef Msg
= Message
.str().ltrim(" ");
1239 Diag(Tok
, diag::pp_hash_warning
) << Msg
;
1241 Diag(Tok
, diag::err_pp_hash_error
) << Msg
;
1244 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1246 void Preprocessor::HandleIdentSCCSDirective(Token
&Tok
) {
1247 // Yes, this directive is an extension.
1248 Diag(Tok
, diag::ext_pp_ident_directive
);
1250 // Read the string argument.
1254 // If the token kind isn't a string, it's a malformed directive.
1255 if (StrTok
.isNot(tok::string_literal
) &&
1256 StrTok
.isNot(tok::wide_string_literal
)) {
1257 Diag(StrTok
, diag::err_pp_malformed_ident
);
1258 if (StrTok
.isNot(tok::eod
))
1259 DiscardUntilEndOfDirective();
1263 if (StrTok
.hasUDSuffix()) {
1264 Diag(StrTok
, diag::err_invalid_string_udl
);
1265 return DiscardUntilEndOfDirective();
1268 // Verify that there is nothing after the string, other than EOD.
1269 CheckEndOfDirective("ident");
1272 bool Invalid
= false;
1273 std::string Str
= getSpelling(StrTok
, &Invalid
);
1275 Callbacks
->Ident(Tok
.getLocation(), Str
);
1279 /// \brief Handle a #public directive.
1280 void Preprocessor::HandleMacroPublicDirective(Token
&Tok
) {
1282 ReadMacroName(MacroNameTok
, MU_Undef
);
1284 // Error reading macro name? If so, diagnostic already issued.
1285 if (MacroNameTok
.is(tok::eod
))
1288 // Check to see if this is the last token on the #__public_macro line.
1289 CheckEndOfDirective("__public_macro");
1291 IdentifierInfo
*II
= MacroNameTok
.getIdentifierInfo();
1292 // Okay, we finally have a valid identifier to undef.
1293 MacroDirective
*MD
= getMacroDirective(II
);
1295 // If the macro is not defined, this is an error.
1297 Diag(MacroNameTok
, diag::err_pp_visibility_non_macro
) << II
;
1301 // Note that this macro has now been exported.
1302 appendMacroDirective(II
, AllocateVisibilityMacroDirective(
1303 MacroNameTok
.getLocation(), /*IsPublic=*/true));
1306 /// \brief Handle a #private directive.
1307 void Preprocessor::HandleMacroPrivateDirective(Token
&Tok
) {
1309 ReadMacroName(MacroNameTok
, MU_Undef
);
1311 // Error reading macro name? If so, diagnostic already issued.
1312 if (MacroNameTok
.is(tok::eod
))
1315 // Check to see if this is the last token on the #__private_macro line.
1316 CheckEndOfDirective("__private_macro");
1318 IdentifierInfo
*II
= MacroNameTok
.getIdentifierInfo();
1319 // Okay, we finally have a valid identifier to undef.
1320 MacroDirective
*MD
= getMacroDirective(II
);
1322 // If the macro is not defined, this is an error.
1324 Diag(MacroNameTok
, diag::err_pp_visibility_non_macro
) << II
;
1328 // Note that this macro has now been marked private.
1329 appendMacroDirective(II
, AllocateVisibilityMacroDirective(
1330 MacroNameTok
.getLocation(), /*IsPublic=*/false));
1333 //===----------------------------------------------------------------------===//
1334 // Preprocessor Include Directive Handling.
1335 //===----------------------------------------------------------------------===//
1337 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1338 /// checked and spelled filename, e.g. as an operand of \#include. This returns
1339 /// true if the input filename was in <>'s or false if it were in ""'s. The
1340 /// caller is expected to provide a buffer that is large enough to hold the
1341 /// spelling of the filename, but is also expected to handle the case when
1342 /// this method decides to use a different buffer.
1343 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc
,
1344 StringRef
&Buffer
) {
1345 // Get the text form of the filename.
1346 assert(!Buffer
.empty() && "Can't have tokens with empty spellings!");
1348 // Make sure the filename is <x> or "x".
1350 if (Buffer
[0] == '<') {
1351 if (Buffer
.back() != '>') {
1352 Diag(Loc
, diag::err_pp_expects_filename
);
1353 Buffer
= StringRef();
1357 } else if (Buffer
[0] == '"') {
1358 if (Buffer
.back() != '"') {
1359 Diag(Loc
, diag::err_pp_expects_filename
);
1360 Buffer
= StringRef();
1365 Diag(Loc
, diag::err_pp_expects_filename
);
1366 Buffer
= StringRef();
1370 // Diagnose #include "" as invalid.
1371 if (Buffer
.size() <= 2) {
1372 Diag(Loc
, diag::err_pp_empty_filename
);
1373 Buffer
= StringRef();
1377 // Skip the brackets.
1378 Buffer
= Buffer
.substr(1, Buffer
.size()-2);
1382 // \brief Handle cases where the \#include name is expanded from a macro
1383 // as multiple tokens, which need to be glued together.
1385 // This occurs for code like:
1387 // \#define FOO <a/b.h>
1390 // because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1392 // This code concatenates and consumes tokens up to the '>' token. It returns
1393 // false if the > was found, otherwise it returns true if it finds and consumes
1395 bool Preprocessor::ConcatenateIncludeName(SmallString
<128> &FilenameBuffer
,
1396 SourceLocation
&End
) {
1400 while (CurTok
.isNot(tok::eod
)) {
1401 End
= CurTok
.getLocation();
1403 // FIXME: Provide code completion for #includes.
1404 if (CurTok
.is(tok::code_completion
)) {
1405 setCodeCompletionReached();
1410 // Append the spelling of this token to the buffer. If there was a space
1411 // before it, add it now.
1412 if (CurTok
.hasLeadingSpace())
1413 FilenameBuffer
.push_back(' ');
1415 // Get the spelling of the token, directly into FilenameBuffer if possible.
1416 unsigned PreAppendSize
= FilenameBuffer
.size();
1417 FilenameBuffer
.resize(PreAppendSize
+CurTok
.getLength());
1419 const char *BufPtr
= &FilenameBuffer
[PreAppendSize
];
1420 unsigned ActualLen
= getSpelling(CurTok
, BufPtr
);
1422 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1423 if (BufPtr
!= &FilenameBuffer
[PreAppendSize
])
1424 memcpy(&FilenameBuffer
[PreAppendSize
], BufPtr
, ActualLen
);
1426 // Resize FilenameBuffer to the correct size.
1427 if (CurTok
.getLength() != ActualLen
)
1428 FilenameBuffer
.resize(PreAppendSize
+ActualLen
);
1430 // If we found the '>' marker, return success.
1431 if (CurTok
.is(tok::greater
))
1437 // If we hit the eod marker, emit an error and return true so that the caller
1438 // knows the EOD has been read.
1439 Diag(CurTok
.getLocation(), diag::err_pp_expects_filename
);
1443 /// \brief Push a token onto the token stream containing an annotation.
1444 static void EnterAnnotationToken(Preprocessor
&PP
,
1445 SourceLocation Begin
, SourceLocation End
,
1446 tok::TokenKind Kind
, void *AnnotationVal
) {
1447 Token
*Tok
= new Token
[1];
1448 Tok
[0].startToken();
1449 Tok
[0].setKind(Kind
);
1450 Tok
[0].setLocation(Begin
);
1451 Tok
[0].setAnnotationEndLoc(End
);
1452 Tok
[0].setAnnotationValue(AnnotationVal
);
1453 PP
.EnterTokenStream(Tok
, 1, true, true);
1456 /// HandleIncludeDirective - The "\#include" tokens have just been read, read
1457 /// the file to be included from the lexer, then include it! This is a common
1458 /// routine with functionality shared between \#include, \#include_next and
1459 /// \#import. LookupFrom is set when this is a \#include_next directive, it
1460 /// specifies the file to start searching from.
1461 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc
,
1463 const DirectoryLookup
*LookupFrom
,
1464 const FileEntry
*LookupFromFile
,
1468 CurPPLexer
->LexIncludeFilename(FilenameTok
);
1470 // Reserve a buffer to get the spelling.
1471 SmallString
<128> FilenameBuffer
;
1474 SourceLocation CharEnd
; // the end of this directive, in characters
1476 switch (FilenameTok
.getKind()) {
1478 // If the token kind is EOD, the error has already been diagnosed.
1481 case tok::angle_string_literal
:
1482 case tok::string_literal
:
1483 Filename
= getSpelling(FilenameTok
, FilenameBuffer
);
1484 End
= FilenameTok
.getLocation();
1485 CharEnd
= End
.getLocWithOffset(FilenameTok
.getLength());
1489 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1490 // case, glue the tokens together into FilenameBuffer and interpret those.
1491 FilenameBuffer
.push_back('<');
1492 if (ConcatenateIncludeName(FilenameBuffer
, End
))
1493 return; // Found <eod> but no ">"? Diagnostic already emitted.
1494 Filename
= FilenameBuffer
.str();
1495 CharEnd
= End
.getLocWithOffset(1);
1498 Diag(FilenameTok
.getLocation(), diag::err_pp_expects_filename
);
1499 DiscardUntilEndOfDirective();
1503 CharSourceRange FilenameRange
1504 = CharSourceRange::getCharRange(FilenameTok
.getLocation(), CharEnd
);
1505 StringRef OriginalFilename
= Filename
;
1507 GetIncludeFilenameSpelling(FilenameTok
.getLocation(), Filename
);
1508 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1510 if (Filename
.empty()) {
1511 DiscardUntilEndOfDirective();
1515 // Verify that there is nothing after the filename, other than EOD. Note that
1516 // we allow macros that expand to nothing after the filename, because this
1517 // falls into the category of "#include pp-tokens new-line" specified in
1519 CheckEndOfDirective(IncludeTok
.getIdentifierInfo()->getNameStart(), true);
1521 // Check that we don't have infinite #include recursion.
1522 if (IncludeMacroStack
.size() == MaxAllowedIncludeStackDepth
-1) {
1523 Diag(FilenameTok
, diag::err_pp_include_too_deep
);
1527 // Complain about attempts to #include files in an audit pragma.
1528 if (PragmaARCCFCodeAuditedLoc
.isValid()) {
1529 Diag(HashLoc
, diag::err_pp_include_in_arc_cf_code_audited
);
1530 Diag(PragmaARCCFCodeAuditedLoc
, diag::note_pragma_entered_here
);
1532 // Immediately leave the pragma.
1533 PragmaARCCFCodeAuditedLoc
= SourceLocation();
1536 if (HeaderInfo
.HasIncludeAliasMap()) {
1537 // Map the filename with the brackets still attached. If the name doesn't
1538 // map to anything, fall back on the filename we've already gotten the
1540 StringRef NewName
= HeaderInfo
.MapHeaderToIncludeAlias(OriginalFilename
);
1541 if (!NewName
.empty())
1545 // Search include directories.
1546 const DirectoryLookup
*CurDir
;
1547 SmallString
<1024> SearchPath
;
1548 SmallString
<1024> RelativePath
;
1549 // We get the raw path only if we have 'Callbacks' to which we later pass
1551 ModuleMap::KnownHeader SuggestedModule
;
1552 SourceLocation FilenameLoc
= FilenameTok
.getLocation();
1553 SmallString
<128> NormalizedPath
;
1554 if (LangOpts
.MSVCCompat
) {
1555 NormalizedPath
= Filename
.str();
1556 #ifndef LLVM_ON_WIN32
1557 llvm::sys::path::native(NormalizedPath
);
1560 const FileEntry
*File
= LookupFile(
1561 FilenameLoc
, LangOpts
.MSVCCompat
? NormalizedPath
.c_str() : Filename
,
1562 isAngled
, LookupFrom
, LookupFromFile
, CurDir
,
1563 Callbacks
? &SearchPath
: nullptr, Callbacks
? &RelativePath
: nullptr,
1564 HeaderInfo
.getHeaderSearchOpts().ModuleMaps
? &SuggestedModule
: nullptr);
1568 // Give the clients a chance to recover.
1569 SmallString
<128> RecoveryPath
;
1570 if (Callbacks
->FileNotFound(Filename
, RecoveryPath
)) {
1571 if (const DirectoryEntry
*DE
= FileMgr
.getDirectory(RecoveryPath
)) {
1572 // Add the recovery path to the list of search paths.
1573 DirectoryLookup
DL(DE
, SrcMgr::C_User
, false);
1574 HeaderInfo
.AddSearchPath(DL
, isAngled
);
1576 // Try the lookup again, skipping the cache.
1579 LangOpts
.MSVCCompat
? NormalizedPath
.c_str() : Filename
, isAngled
,
1580 LookupFrom
, LookupFromFile
, CurDir
, nullptr, nullptr,
1581 HeaderInfo
.getHeaderSearchOpts().ModuleMaps
? &SuggestedModule
1583 /*SkipCache*/ true);
1588 if (!SuggestedModule
|| !getLangOpts().Modules
) {
1589 // Notify the callback object that we've seen an inclusion directive.
1590 Callbacks
->InclusionDirective(HashLoc
, IncludeTok
,
1591 LangOpts
.MSVCCompat
? NormalizedPath
.c_str()
1593 isAngled
, FilenameRange
, File
, SearchPath
,
1594 RelativePath
, /*ImportedModule=*/nullptr);
1599 if (!SuppressIncludeNotFoundError
) {
1600 // If the file could not be located and it was included via angle
1601 // brackets, we can attempt a lookup as though it were a quoted path to
1602 // provide the user with a possible fixit.
1606 LangOpts
.MSVCCompat
? NormalizedPath
.c_str() : Filename
, false,
1607 LookupFrom
, LookupFromFile
, CurDir
,
1608 Callbacks
? &SearchPath
: nullptr,
1609 Callbacks
? &RelativePath
: nullptr,
1610 HeaderInfo
.getHeaderSearchOpts().ModuleMaps
? &SuggestedModule
1613 SourceRange
Range(FilenameTok
.getLocation(), CharEnd
);
1614 Diag(FilenameTok
, diag::err_pp_file_not_found_not_fatal
) <<
1616 FixItHint::CreateReplacement(Range
, "\"" + Filename
.str() + "\"");
1619 // If the file is still not found, just go with the vanilla diagnostic
1621 Diag(FilenameTok
, diag::err_pp_file_not_found
) << Filename
;
1627 // If we are supposed to import a module rather than including the header,
1629 if (SuggestedModule
&& getLangOpts().Modules
&&
1630 SuggestedModule
.getModule()->getTopLevelModuleName() !=
1631 getLangOpts().ImplementationOfModule
) {
1632 // Compute the module access path corresponding to this module.
1633 // FIXME: Should we have a second loadModule() overload to avoid this
1634 // extra lookup step?
1635 SmallVector
<std::pair
<IdentifierInfo
*, SourceLocation
>, 2> Path
;
1636 for (Module
*Mod
= SuggestedModule
.getModule(); Mod
; Mod
= Mod
->Parent
)
1637 Path
.push_back(std::make_pair(getIdentifierInfo(Mod
->Name
),
1638 FilenameTok
.getLocation()));
1639 std::reverse(Path
.begin(), Path
.end());
1641 // Warn that we're replacing the include/import with a module import.
1642 SmallString
<128> PathString
;
1643 for (unsigned I
= 0, N
= Path
.size(); I
!= N
; ++I
) {
1646 PathString
+= Path
[I
].first
->getName();
1648 int IncludeKind
= 0;
1650 switch (IncludeTok
.getIdentifierInfo()->getPPKeywordID()) {
1651 case tok::pp_include
:
1655 case tok::pp_import
:
1659 case tok::pp_include_next
:
1663 case tok::pp___include_macros
:
1668 llvm_unreachable("unknown include directive kind");
1671 // Determine whether we are actually building the module that this
1672 // include directive maps to.
1673 bool BuildingImportedModule
1674 = Path
[0].first
->getName() == getLangOpts().CurrentModule
;
1676 if (!BuildingImportedModule
&& getLangOpts().ObjC2
) {
1677 // If we're not building the imported module, warn that we're going
1678 // to automatically turn this inclusion directive into a module import.
1679 // We only do this in Objective-C, where we have a module-import syntax.
1680 CharSourceRange
ReplaceRange(SourceRange(HashLoc
, CharEnd
),
1681 /*IsTokenRange=*/false);
1682 Diag(HashLoc
, diag::warn_auto_module_import
)
1683 << IncludeKind
<< PathString
1684 << FixItHint::CreateReplacement(ReplaceRange
,
1685 "@import " + PathString
.str().str() + ";");
1688 // Load the module. Only make macros visible. We'll make the declarations
1689 // visible when the parser gets here.
1690 Module::NameVisibilityKind Visibility
= Module::MacrosVisible
;
1691 ModuleLoadResult Imported
1692 = TheModuleLoader
.loadModule(IncludeTok
.getLocation(), Path
, Visibility
,
1693 /*IsIncludeDirective=*/true);
1694 assert((Imported
== nullptr || Imported
== SuggestedModule
.getModule()) &&
1695 "the imported module is different than the suggested one");
1697 if (!Imported
&& hadModuleLoaderFatalFailure()) {
1698 // With a fatal failure in the module loader, we abort parsing.
1699 Token
&Result
= IncludeTok
;
1701 Result
.startToken();
1702 CurLexer
->FormTokenWithChars(Result
, CurLexer
->BufferEnd
, tok::eof
);
1703 CurLexer
->cutOffLexing();
1705 assert(CurPTHLexer
&& "#include but no current lexer set!");
1706 CurPTHLexer
->getEOF(Result
);
1711 // If this header isn't part of the module we're building, we're done.
1712 if (!BuildingImportedModule
&& Imported
) {
1714 Callbacks
->InclusionDirective(HashLoc
, IncludeTok
, Filename
, isAngled
,
1715 FilenameRange
, File
,
1716 SearchPath
, RelativePath
, Imported
);
1719 if (IncludeKind
!= 3) {
1720 // Let the parser know that we hit a module import, and it should
1721 // make the module visible.
1722 // FIXME: Produce this as the current token directly, rather than
1723 // allocating a new token for it.
1724 EnterAnnotationToken(*this, HashLoc
, End
, tok::annot_module_include
,
1730 // If we failed to find a submodule that we expected to find, we can
1731 // continue. Otherwise, there's an error in the included file, so we
1732 // don't want to include it.
1733 if (!BuildingImportedModule
&& !Imported
.isMissingExpected()) {
1738 if (Callbacks
&& SuggestedModule
) {
1739 // We didn't notify the callback object that we've seen an inclusion
1740 // directive before. Now that we are parsing the include normally and not
1741 // turning it to a module import, notify the callback object.
1742 Callbacks
->InclusionDirective(HashLoc
, IncludeTok
, Filename
, isAngled
,
1743 FilenameRange
, File
,
1744 SearchPath
, RelativePath
,
1745 /*ImportedModule=*/nullptr);
1748 // The #included file will be considered to be a system header if either it is
1749 // in a system include directory, or if the #includer is a system include
1751 SrcMgr::CharacteristicKind FileCharacter
=
1752 std::max(HeaderInfo
.getFileDirFlavor(File
),
1753 SourceMgr
.getFileCharacteristic(FilenameTok
.getLocation()));
1755 // Ask HeaderInfo if we should enter this #include file. If not, #including
1756 // this file will have no effect.
1757 if (!HeaderInfo
.ShouldEnterIncludeFile(File
, isImport
)) {
1759 Callbacks
->FileSkipped(*File
, FilenameTok
, FileCharacter
);
1763 // Look up the file, create a File ID for it.
1764 SourceLocation IncludePos
= End
;
1765 // If the filename string was the result of macro expansions, set the include
1766 // position on the file where it will be included and after the expansions.
1767 if (IncludePos
.isMacroID())
1768 IncludePos
= SourceMgr
.getExpansionRange(IncludePos
).second
;
1769 FileID FID
= SourceMgr
.createFileID(File
, IncludePos
, FileCharacter
);
1770 assert(!FID
.isInvalid() && "Expected valid file ID");
1772 // Determine if we're switching to building a new submodule, and which one.
1773 ModuleMap::KnownHeader BuildingModule
;
1774 if (getLangOpts().Modules
&& !getLangOpts().CurrentModule
.empty()) {
1775 Module
*RequestingModule
= getModuleForLocation(FilenameLoc
);
1777 HeaderInfo
.getModuleMap().findModuleForHeader(File
, RequestingModule
);
1780 // If all is good, enter the new file!
1781 if (EnterSourceFile(FID
, CurDir
, FilenameTok
.getLocation()))
1784 // If we're walking into another part of the same module, let the parser
1785 // know that any future declarations are within that other submodule.
1786 if (BuildingModule
) {
1787 assert(!CurSubmodule
&& "should not have marked this as a module yet");
1788 CurSubmodule
= BuildingModule
.getModule();
1790 EnterAnnotationToken(*this, HashLoc
, End
, tok::annot_module_begin
,
1795 /// HandleIncludeNextDirective - Implements \#include_next.
1797 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc
,
1798 Token
&IncludeNextTok
) {
1799 Diag(IncludeNextTok
, diag::ext_pp_include_next_directive
);
1801 // #include_next is like #include, except that we start searching after
1802 // the current found directory. If we can't do this, issue a
1804 const DirectoryLookup
*Lookup
= CurDirLookup
;
1805 const FileEntry
*LookupFromFile
= nullptr;
1806 if (isInPrimaryFile()) {
1808 Diag(IncludeNextTok
, diag::pp_include_next_in_primary
);
1809 } else if (CurSubmodule
) {
1810 // Start looking up in the directory *after* the one in which the current
1811 // file would be found, if any.
1812 assert(CurPPLexer
&& "#include_next directive in macro?");
1813 LookupFromFile
= CurPPLexer
->getFileEntry();
1815 } else if (!Lookup
) {
1816 Diag(IncludeNextTok
, diag::pp_include_next_absolute_path
);
1818 // Start looking up in the next directory.
1822 return HandleIncludeDirective(HashLoc
, IncludeNextTok
, Lookup
,
1826 /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
1827 void Preprocessor::HandleMicrosoftImportDirective(Token
&Tok
) {
1828 // The Microsoft #import directive takes a type library and generates header
1829 // files from it, and includes those. This is beyond the scope of what clang
1830 // does, so we ignore it and error out. However, #import can optionally have
1831 // trailing attributes that span multiple lines. We're going to eat those
1832 // so we can continue processing from there.
1833 Diag(Tok
, diag::err_pp_import_directive_ms
);
1835 // Read tokens until we get to the end of the directive. Note that the
1836 // directive can be split over multiple lines using the backslash character.
1837 DiscardUntilEndOfDirective();
1840 /// HandleImportDirective - Implements \#import.
1842 void Preprocessor::HandleImportDirective(SourceLocation HashLoc
,
1844 if (!LangOpts
.ObjC1
) { // #import is standard for ObjC.
1845 if (LangOpts
.MSVCCompat
)
1846 return HandleMicrosoftImportDirective(ImportTok
);
1847 Diag(ImportTok
, diag::ext_pp_import_directive
);
1849 return HandleIncludeDirective(HashLoc
, ImportTok
, nullptr, nullptr, true);
1852 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1853 /// pseudo directive in the predefines buffer. This handles it by sucking all
1854 /// tokens through the preprocessor and discarding them (only keeping the side
1855 /// effects on the preprocessor).
1856 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc
,
1857 Token
&IncludeMacrosTok
) {
1858 // This directive should only occur in the predefines buffer. If not, emit an
1859 // error and reject it.
1860 SourceLocation Loc
= IncludeMacrosTok
.getLocation();
1861 if (strcmp(SourceMgr
.getBufferName(Loc
), "<built-in>") != 0) {
1862 Diag(IncludeMacrosTok
.getLocation(),
1863 diag::pp_include_macros_out_of_predefines
);
1864 DiscardUntilEndOfDirective();
1868 // Treat this as a normal #include for checking purposes. If this is
1869 // successful, it will push a new lexer onto the include stack.
1870 HandleIncludeDirective(HashLoc
, IncludeMacrosTok
);
1875 assert(TmpTok
.isNot(tok::eof
) && "Didn't find end of -imacros!");
1876 } while (TmpTok
.isNot(tok::hashhash
));
1879 //===----------------------------------------------------------------------===//
1880 // Preprocessor Macro Directive Handling.
1881 //===----------------------------------------------------------------------===//
1883 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1884 /// definition has just been read. Lex the rest of the arguments and the
1885 /// closing ), updating MI with what we learn. Return true if an error occurs
1886 /// parsing the arg list.
1887 bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo
*MI
, Token
&Tok
) {
1888 SmallVector
<IdentifierInfo
*, 32> Arguments
;
1891 LexUnexpandedToken(Tok
);
1892 switch (Tok
.getKind()) {
1894 // Found the end of the argument list.
1895 if (Arguments
.empty()) // #define FOO()
1897 // Otherwise we have #define FOO(A,)
1898 Diag(Tok
, diag::err_pp_expected_ident_in_arg_list
);
1900 case tok::ellipsis
: // #define X(... -> C99 varargs
1902 Diag(Tok
, LangOpts
.CPlusPlus11
?
1903 diag::warn_cxx98_compat_variadic_macro
:
1904 diag::ext_variadic_macro
);
1906 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1907 if (LangOpts
.OpenCL
) {
1908 Diag(Tok
, diag::err_pp_opencl_variadic_macros
);
1912 // Lex the token after the identifier.
1913 LexUnexpandedToken(Tok
);
1914 if (Tok
.isNot(tok::r_paren
)) {
1915 Diag(Tok
, diag::err_pp_missing_rparen_in_macro_def
);
1918 // Add the __VA_ARGS__ identifier as an argument.
1919 Arguments
.push_back(Ident__VA_ARGS__
);
1920 MI
->setIsC99Varargs();
1921 MI
->setArgumentList(&Arguments
[0], Arguments
.size(), BP
);
1923 case tok::eod
: // #define X(
1924 Diag(Tok
, diag::err_pp_missing_rparen_in_macro_def
);
1927 // Handle keywords and identifiers here to accept things like
1928 // #define Foo(for) for.
1929 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1932 Diag(Tok
, diag::err_pp_invalid_tok_in_arg_list
);
1936 // If this is already used as an argument, it is used multiple times (e.g.
1938 if (std::find(Arguments
.begin(), Arguments
.end(), II
) !=
1939 Arguments
.end()) { // C99 6.10.3p6
1940 Diag(Tok
, diag::err_pp_duplicate_name_in_arg_list
) << II
;
1944 // Add the argument to the macro info.
1945 Arguments
.push_back(II
);
1947 // Lex the token after the identifier.
1948 LexUnexpandedToken(Tok
);
1950 switch (Tok
.getKind()) {
1951 default: // #define X(A B
1952 Diag(Tok
, diag::err_pp_expected_comma_in_arg_list
);
1954 case tok::r_paren
: // #define X(A)
1955 MI
->setArgumentList(&Arguments
[0], Arguments
.size(), BP
);
1957 case tok::comma
: // #define X(A,
1959 case tok::ellipsis
: // #define X(A... -> GCC extension
1960 // Diagnose extension.
1961 Diag(Tok
, diag::ext_named_variadic_macro
);
1963 // Lex the token after the identifier.
1964 LexUnexpandedToken(Tok
);
1965 if (Tok
.isNot(tok::r_paren
)) {
1966 Diag(Tok
, diag::err_pp_missing_rparen_in_macro_def
);
1970 MI
->setIsGNUVarargs();
1971 MI
->setArgumentList(&Arguments
[0], Arguments
.size(), BP
);
1978 static bool isConfigurationPattern(Token
&MacroName
, MacroInfo
*MI
,
1979 const LangOptions
&LOptions
) {
1980 if (MI
->getNumTokens() == 1) {
1981 const Token
&Value
= MI
->getReplacementToken(0);
1983 // Macro that is identity, like '#define inline inline' is a valid pattern.
1984 if (MacroName
.getKind() == Value
.getKind())
1987 // Macro that maps a keyword to the same keyword decorated with leading/
1988 // trailing underscores is a valid pattern:
1989 // #define inline __inline
1990 // #define inline __inline__
1991 // #define inline _inline (in MS compatibility mode)
1992 StringRef MacroText
= MacroName
.getIdentifierInfo()->getName();
1993 if (IdentifierInfo
*II
= Value
.getIdentifierInfo()) {
1994 if (!II
->isKeyword(LOptions
))
1996 StringRef ValueText
= II
->getName();
1997 StringRef TrimmedValue
= ValueText
;
1998 if (!ValueText
.startswith("__")) {
1999 if (ValueText
.startswith("_"))
2000 TrimmedValue
= TrimmedValue
.drop_front(1);
2004 TrimmedValue
= TrimmedValue
.drop_front(2);
2005 if (TrimmedValue
.endswith("__"))
2006 TrimmedValue
= TrimmedValue
.drop_back(2);
2008 return TrimmedValue
.equals(MacroText
);
2015 if ((MacroName
.is(tok::kw_extern
) || MacroName
.is(tok::kw_inline
) ||
2016 MacroName
.is(tok::kw_static
) || MacroName
.is(tok::kw_const
)) &&
2017 MI
->getNumTokens() == 0) {
2024 /// HandleDefineDirective - Implements \#define. This consumes the entire macro
2025 /// line then lets the caller lex the next real token.
2026 void Preprocessor::HandleDefineDirective(Token
&DefineTok
,
2027 bool ImmediatelyAfterHeaderGuard
) {
2031 bool MacroShadowsKeyword
;
2032 ReadMacroName(MacroNameTok
, MU_Define
, &MacroShadowsKeyword
);
2034 // Error reading macro name? If so, diagnostic already issued.
2035 if (MacroNameTok
.is(tok::eod
))
2038 Token LastTok
= MacroNameTok
;
2040 // If we are supposed to keep comments in #defines, reenable comment saving
2042 if (CurLexer
) CurLexer
->SetCommentRetentionState(KeepMacroComments
);
2044 // Create the new macro.
2045 MacroInfo
*MI
= AllocateMacroInfo(MacroNameTok
.getLocation());
2048 LexUnexpandedToken(Tok
);
2050 // If this is a function-like macro definition, parse the argument list,
2051 // marking each of the identifiers as being used as macro arguments. Also,
2052 // check other constraints on the first token of the macro body.
2053 if (Tok
.is(tok::eod
)) {
2054 if (ImmediatelyAfterHeaderGuard
) {
2055 // Save this macro information since it may part of a header guard.
2056 CurPPLexer
->MIOpt
.SetDefinedMacro(MacroNameTok
.getIdentifierInfo(),
2057 MacroNameTok
.getLocation());
2059 // If there is no body to this macro, we have no special handling here.
2060 } else if (Tok
.hasLeadingSpace()) {
2061 // This is a normal token with leading space. Clear the leading space
2062 // marker on the first token to get proper expansion.
2063 Tok
.clearFlag(Token::LeadingSpace
);
2064 } else if (Tok
.is(tok::l_paren
)) {
2065 // This is a function-like macro definition. Read the argument list.
2066 MI
->setIsFunctionLike();
2067 if (ReadMacroDefinitionArgList(MI
, LastTok
)) {
2068 // Throw away the rest of the line.
2069 if (CurPPLexer
->ParsingPreprocessorDirective
)
2070 DiscardUntilEndOfDirective();
2074 // If this is a definition of a variadic C99 function-like macro, not using
2075 // the GNU named varargs extension, enabled __VA_ARGS__.
2077 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2078 // This gets unpoisoned where it is allowed.
2079 assert(Ident__VA_ARGS__
->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2080 if (MI
->isC99Varargs())
2081 Ident__VA_ARGS__
->setIsPoisoned(false);
2083 // Read the first token after the arg list for down below.
2084 LexUnexpandedToken(Tok
);
2085 } else if (LangOpts
.C99
|| LangOpts
.CPlusPlus11
) {
2086 // C99 requires whitespace between the macro definition and the body. Emit
2087 // a diagnostic for something like "#define X+".
2088 Diag(Tok
, diag::ext_c99_whitespace_required_after_macro_name
);
2090 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2091 // first character of a replacement list is not a character required by
2092 // subclause 5.2.1, then there shall be white-space separation between the
2093 // identifier and the replacement list.". 5.2.1 lists this set:
2094 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2095 // is irrelevant here.
2096 bool isInvalid
= false;
2097 if (Tok
.is(tok::at
)) // @ is not in the list above.
2099 else if (Tok
.is(tok::unknown
)) {
2100 // If we have an unknown token, it is something strange like "`". Since
2101 // all of valid characters would have lexed into a single character
2102 // token of some sort, we know this is not a valid case.
2106 Diag(Tok
, diag::ext_missing_whitespace_after_macro_name
);
2108 Diag(Tok
, diag::warn_missing_whitespace_after_macro_name
);
2111 if (!Tok
.is(tok::eod
))
2114 // Read the rest of the macro body.
2115 if (MI
->isObjectLike()) {
2116 // Object-like macros are very simple, just read their body.
2117 while (Tok
.isNot(tok::eod
)) {
2119 MI
->AddTokenToBody(Tok
);
2120 // Get the next token of the macro.
2121 LexUnexpandedToken(Tok
);
2125 // Otherwise, read the body of a function-like macro. While we are at it,
2126 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2127 // parameters in function-like macro expansions.
2128 while (Tok
.isNot(tok::eod
)) {
2131 if (Tok
.isNot(tok::hash
) && Tok
.isNot(tok::hashhash
)) {
2132 MI
->AddTokenToBody(Tok
);
2134 // Get the next token of the macro.
2135 LexUnexpandedToken(Tok
);
2139 // If we're in -traditional mode, then we should ignore stringification
2140 // and token pasting. Mark the tokens as unknown so as not to confuse
2142 if (getLangOpts().TraditionalCPP
) {
2143 Tok
.setKind(tok::unknown
);
2144 MI
->AddTokenToBody(Tok
);
2146 // Get the next token of the macro.
2147 LexUnexpandedToken(Tok
);
2151 if (Tok
.is(tok::hashhash
)) {
2153 // If we see token pasting, check if it looks like the gcc comma
2154 // pasting extension. We'll use this information to suppress
2155 // diagnostics later on.
2157 // Get the next token of the macro.
2158 LexUnexpandedToken(Tok
);
2160 if (Tok
.is(tok::eod
)) {
2161 MI
->AddTokenToBody(LastTok
);
2165 unsigned NumTokens
= MI
->getNumTokens();
2166 if (NumTokens
&& Tok
.getIdentifierInfo() == Ident__VA_ARGS__
&&
2167 MI
->getReplacementToken(NumTokens
-1).is(tok::comma
))
2168 MI
->setHasCommaPasting();
2170 // Things look ok, add the '##' token to the macro.
2171 MI
->AddTokenToBody(LastTok
);
2175 // Get the next token of the macro.
2176 LexUnexpandedToken(Tok
);
2178 // Check for a valid macro arg identifier.
2179 if (Tok
.getIdentifierInfo() == nullptr ||
2180 MI
->getArgumentNum(Tok
.getIdentifierInfo()) == -1) {
2182 // If this is assembler-with-cpp mode, we accept random gibberish after
2183 // the '#' because '#' is often a comment character. However, change
2184 // the kind of the token to tok::unknown so that the preprocessor isn't
2186 if (getLangOpts().AsmPreprocessor
&& Tok
.isNot(tok::eod
)) {
2187 LastTok
.setKind(tok::unknown
);
2188 MI
->AddTokenToBody(LastTok
);
2191 Diag(Tok
, diag::err_pp_stringize_not_parameter
);
2193 // Disable __VA_ARGS__ again.
2194 Ident__VA_ARGS__
->setIsPoisoned(true);
2199 // Things look ok, add the '#' and param name tokens to the macro.
2200 MI
->AddTokenToBody(LastTok
);
2201 MI
->AddTokenToBody(Tok
);
2204 // Get the next token of the macro.
2205 LexUnexpandedToken(Tok
);
2209 if (MacroShadowsKeyword
&&
2210 !isConfigurationPattern(MacroNameTok
, MI
, getLangOpts())) {
2211 Diag(MacroNameTok
, diag::warn_pp_macro_hides_keyword
);
2214 // Disable __VA_ARGS__ again.
2215 Ident__VA_ARGS__
->setIsPoisoned(true);
2217 // Check that there is no paste (##) operator at the beginning or end of the
2218 // replacement list.
2219 unsigned NumTokens
= MI
->getNumTokens();
2220 if (NumTokens
!= 0) {
2221 if (MI
->getReplacementToken(0).is(tok::hashhash
)) {
2222 Diag(MI
->getReplacementToken(0), diag::err_paste_at_start
);
2225 if (MI
->getReplacementToken(NumTokens
-1).is(tok::hashhash
)) {
2226 Diag(MI
->getReplacementToken(NumTokens
-1), diag::err_paste_at_end
);
2231 MI
->setDefinitionEndLoc(LastTok
.getLocation());
2233 // Finally, if this identifier already had a macro defined for it, verify that
2234 // the macro bodies are identical, and issue diagnostics if they are not.
2235 if (const MacroInfo
*OtherMI
=getMacroInfo(MacroNameTok
.getIdentifierInfo())) {
2236 // It is very common for system headers to have tons of macro redefinitions
2237 // and for warnings to be disabled in system headers. If this is the case,
2238 // then don't bother calling MacroInfo::isIdenticalTo.
2239 if (!getDiagnostics().getSuppressSystemWarnings() ||
2240 !SourceMgr
.isInSystemHeader(DefineTok
.getLocation())) {
2241 if (!OtherMI
->isUsed() && OtherMI
->isWarnIfUnused())
2242 Diag(OtherMI
->getDefinitionLoc(), diag::pp_macro_not_used
);
2244 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2245 // C++ [cpp.predefined]p4, but allow it as an extension.
2246 if (OtherMI
->isBuiltinMacro())
2247 Diag(MacroNameTok
, diag::ext_pp_redef_builtin_macro
);
2248 // Macros must be identical. This means all tokens and whitespace
2249 // separation must be the same. C99 6.10.3p2.
2250 else if (!OtherMI
->isAllowRedefinitionsWithoutWarning() &&
2251 !MI
->isIdenticalTo(*OtherMI
, *this, /*Syntactic=*/LangOpts
.MicrosoftExt
)) {
2252 Diag(MI
->getDefinitionLoc(), diag::ext_pp_macro_redef
)
2253 << MacroNameTok
.getIdentifierInfo();
2254 Diag(OtherMI
->getDefinitionLoc(), diag::note_previous_definition
);
2257 if (OtherMI
->isWarnIfUnused())
2258 WarnUnusedMacroLocs
.erase(OtherMI
->getDefinitionLoc());
2261 DefMacroDirective
*MD
=
2262 appendDefMacroDirective(MacroNameTok
.getIdentifierInfo(), MI
);
2264 assert(!MI
->isUsed());
2265 // If we need warning for not using the macro, add its location in the
2266 // warn-because-unused-macro set. If it gets used it will be removed from set.
2267 if (getSourceManager().isInMainFile(MI
->getDefinitionLoc()) &&
2268 !Diags
->isIgnored(diag::pp_macro_not_used
, MI
->getDefinitionLoc())) {
2269 MI
->setIsWarnIfUnused(true);
2270 WarnUnusedMacroLocs
.insert(MI
->getDefinitionLoc());
2273 // If the callbacks want to know, tell them about the macro definition.
2275 Callbacks
->MacroDefined(MacroNameTok
, MD
);
2278 /// HandleUndefDirective - Implements \#undef.
2280 void Preprocessor::HandleUndefDirective(Token
&UndefTok
) {
2284 ReadMacroName(MacroNameTok
, MU_Undef
);
2286 // Error reading macro name? If so, diagnostic already issued.
2287 if (MacroNameTok
.is(tok::eod
))
2290 // Check to see if this is the last token on the #undef line.
2291 CheckEndOfDirective("undef");
2293 // Okay, we finally have a valid identifier to undef.
2294 MacroDirective
*MD
= getMacroDirective(MacroNameTok
.getIdentifierInfo());
2295 const MacroInfo
*MI
= MD
? MD
->getMacroInfo() : nullptr;
2297 // If the callbacks want to know, tell them about the macro #undef.
2298 // Note: no matter if the macro was defined or not.
2300 Callbacks
->MacroUndefined(MacroNameTok
, MD
);
2302 // If the macro is not defined, this is a noop undef, just return.
2306 if (!MI
->isUsed() && MI
->isWarnIfUnused())
2307 Diag(MI
->getDefinitionLoc(), diag::pp_macro_not_used
);
2309 if (MI
->isWarnIfUnused())
2310 WarnUnusedMacroLocs
.erase(MI
->getDefinitionLoc());
2312 appendMacroDirective(MacroNameTok
.getIdentifierInfo(),
2313 AllocateUndefMacroDirective(MacroNameTok
.getLocation()));
2317 //===----------------------------------------------------------------------===//
2318 // Preprocessor Conditional Directive Handling.
2319 //===----------------------------------------------------------------------===//
2321 /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2322 /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2323 /// true if any tokens have been returned or pp-directives activated before this
2324 /// \#ifndef has been lexed.
2326 void Preprocessor::HandleIfdefDirective(Token
&Result
, bool isIfndef
,
2327 bool ReadAnyTokensBeforeDirective
) {
2329 Token DirectiveTok
= Result
;
2332 ReadMacroName(MacroNameTok
);
2334 // Error reading macro name? If so, diagnostic already issued.
2335 if (MacroNameTok
.is(tok::eod
)) {
2336 // Skip code until we get to #endif. This helps with recovery by not
2337 // emitting an error when the #endif is reached.
2338 SkipExcludedConditionalBlock(DirectiveTok
.getLocation(),
2339 /*Foundnonskip*/false, /*FoundElse*/false);
2343 // Check to see if this is the last token on the #if[n]def line.
2344 CheckEndOfDirective(isIfndef
? "ifndef" : "ifdef");
2346 IdentifierInfo
*MII
= MacroNameTok
.getIdentifierInfo();
2347 MacroDirective
*MD
= getMacroDirective(MII
);
2348 MacroInfo
*MI
= MD
? MD
->getMacroInfo() : nullptr;
2350 if (CurPPLexer
->getConditionalStackDepth() == 0) {
2351 // If the start of a top-level #ifdef and if the macro is not defined,
2352 // inform MIOpt that this might be the start of a proper include guard.
2353 // Otherwise it is some other form of unknown conditional which we can't
2355 if (!ReadAnyTokensBeforeDirective
&& !MI
) {
2356 assert(isIfndef
&& "#ifdef shouldn't reach here");
2357 CurPPLexer
->MIOpt
.EnterTopLevelIfndef(MII
, MacroNameTok
.getLocation());
2359 CurPPLexer
->MIOpt
.EnterTopLevelConditional();
2362 // If there is a macro, process it.
2363 if (MI
) // Mark it used.
2364 markMacroAsUsed(MI
);
2368 Callbacks
->Ifndef(DirectiveTok
.getLocation(), MacroNameTok
, MD
);
2370 Callbacks
->Ifdef(DirectiveTok
.getLocation(), MacroNameTok
, MD
);
2373 // Should we include the stuff contained by this directive?
2374 if (!MI
== isIfndef
) {
2375 // Yes, remember that we are inside a conditional, then lex the next token.
2376 CurPPLexer
->pushConditionalLevel(DirectiveTok
.getLocation(),
2377 /*wasskip*/false, /*foundnonskip*/true,
2378 /*foundelse*/false);
2380 // No, skip the contents of this block.
2381 SkipExcludedConditionalBlock(DirectiveTok
.getLocation(),
2382 /*Foundnonskip*/false,
2383 /*FoundElse*/false);
2387 /// HandleIfDirective - Implements the \#if directive.
2389 void Preprocessor::HandleIfDirective(Token
&IfToken
,
2390 bool ReadAnyTokensBeforeDirective
) {
2393 // Parse and evaluate the conditional expression.
2394 IdentifierInfo
*IfNDefMacro
= nullptr;
2395 const SourceLocation ConditionalBegin
= CurPPLexer
->getSourceLocation();
2396 const bool ConditionalTrue
= EvaluateDirectiveExpression(IfNDefMacro
);
2397 const SourceLocation ConditionalEnd
= CurPPLexer
->getSourceLocation();
2399 // If this condition is equivalent to #ifndef X, and if this is the first
2400 // directive seen, handle it for the multiple-include optimization.
2401 if (CurPPLexer
->getConditionalStackDepth() == 0) {
2402 if (!ReadAnyTokensBeforeDirective
&& IfNDefMacro
&& ConditionalTrue
)
2403 // FIXME: Pass in the location of the macro name, not the 'if' token.
2404 CurPPLexer
->MIOpt
.EnterTopLevelIfndef(IfNDefMacro
, IfToken
.getLocation());
2406 CurPPLexer
->MIOpt
.EnterTopLevelConditional();
2410 Callbacks
->If(IfToken
.getLocation(),
2411 SourceRange(ConditionalBegin
, ConditionalEnd
),
2412 (ConditionalTrue
? PPCallbacks::CVK_True
: PPCallbacks::CVK_False
));
2414 // Should we include the stuff contained by this directive?
2415 if (ConditionalTrue
) {
2416 // Yes, remember that we are inside a conditional, then lex the next token.
2417 CurPPLexer
->pushConditionalLevel(IfToken
.getLocation(), /*wasskip*/false,
2418 /*foundnonskip*/true, /*foundelse*/false);
2420 // No, skip the contents of this block.
2421 SkipExcludedConditionalBlock(IfToken
.getLocation(), /*Foundnonskip*/false,
2422 /*FoundElse*/false);
2426 /// HandleEndifDirective - Implements the \#endif directive.
2428 void Preprocessor::HandleEndifDirective(Token
&EndifToken
) {
2431 // Check that this is the whole directive.
2432 CheckEndOfDirective("endif");
2434 PPConditionalInfo CondInfo
;
2435 if (CurPPLexer
->popConditionalLevel(CondInfo
)) {
2436 // No conditionals on the stack: this is an #endif without an #if.
2437 Diag(EndifToken
, diag::err_pp_endif_without_if
);
2441 // If this the end of a top-level #endif, inform MIOpt.
2442 if (CurPPLexer
->getConditionalStackDepth() == 0)
2443 CurPPLexer
->MIOpt
.ExitTopLevelConditional();
2445 assert(!CondInfo
.WasSkipping
&& !CurPPLexer
->LexingRawMode
&&
2446 "This code should only be reachable in the non-skipping case!");
2449 Callbacks
->Endif(EndifToken
.getLocation(), CondInfo
.IfLoc
);
2452 /// HandleElseDirective - Implements the \#else directive.
2454 void Preprocessor::HandleElseDirective(Token
&Result
) {
2457 // #else directive in a non-skipping conditional... start skipping.
2458 CheckEndOfDirective("else");
2460 PPConditionalInfo CI
;
2461 if (CurPPLexer
->popConditionalLevel(CI
)) {
2462 Diag(Result
, diag::pp_err_else_without_if
);
2466 // If this is a top-level #else, inform the MIOpt.
2467 if (CurPPLexer
->getConditionalStackDepth() == 0)
2468 CurPPLexer
->MIOpt
.EnterTopLevelConditional();
2470 // If this is a #else with a #else before it, report the error.
2471 if (CI
.FoundElse
) Diag(Result
, diag::pp_err_else_after_else
);
2474 Callbacks
->Else(Result
.getLocation(), CI
.IfLoc
);
2476 // Finally, skip the rest of the contents of this block.
2477 SkipExcludedConditionalBlock(CI
.IfLoc
, /*Foundnonskip*/true,
2478 /*FoundElse*/true, Result
.getLocation());
2481 /// HandleElifDirective - Implements the \#elif directive.
2483 void Preprocessor::HandleElifDirective(Token
&ElifToken
) {
2486 // #elif directive in a non-skipping conditional... start skipping.
2487 // We don't care what the condition is, because we will always skip it (since
2488 // the block immediately before it was included).
2489 const SourceLocation ConditionalBegin
= CurPPLexer
->getSourceLocation();
2490 DiscardUntilEndOfDirective();
2491 const SourceLocation ConditionalEnd
= CurPPLexer
->getSourceLocation();
2493 PPConditionalInfo CI
;
2494 if (CurPPLexer
->popConditionalLevel(CI
)) {
2495 Diag(ElifToken
, diag::pp_err_elif_without_if
);
2499 // If this is a top-level #elif, inform the MIOpt.
2500 if (CurPPLexer
->getConditionalStackDepth() == 0)
2501 CurPPLexer
->MIOpt
.EnterTopLevelConditional();
2503 // If this is a #elif with a #else before it, report the error.
2504 if (CI
.FoundElse
) Diag(ElifToken
, diag::pp_err_elif_after_else
);
2507 Callbacks
->Elif(ElifToken
.getLocation(),
2508 SourceRange(ConditionalBegin
, ConditionalEnd
),
2509 PPCallbacks::CVK_NotEvaluated
, CI
.IfLoc
);
2511 // Finally, skip the rest of the contents of this block.
2512 SkipExcludedConditionalBlock(CI
.IfLoc
, /*Foundnonskip*/true,
2513 /*FoundElse*/CI
.FoundElse
,
2514 ElifToken
.getLocation());