1f4a2713aSLionel Sambuc //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc ///
10f4a2713aSLionel Sambuc /// \file
11f4a2713aSLionel Sambuc /// \brief Implements # directive processing for the Preprocessor.
12f4a2713aSLionel Sambuc ///
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc
15f4a2713aSLionel Sambuc #include "clang/Lex/Preprocessor.h"
16f4a2713aSLionel Sambuc #include "clang/Basic/FileManager.h"
17f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
18f4a2713aSLionel Sambuc #include "clang/Lex/CodeCompletionHandler.h"
19f4a2713aSLionel Sambuc #include "clang/Lex/HeaderSearch.h"
20f4a2713aSLionel Sambuc #include "clang/Lex/HeaderSearchOptions.h"
21f4a2713aSLionel Sambuc #include "clang/Lex/LexDiagnostic.h"
22f4a2713aSLionel Sambuc #include "clang/Lex/LiteralSupport.h"
23f4a2713aSLionel Sambuc #include "clang/Lex/MacroInfo.h"
24f4a2713aSLionel Sambuc #include "clang/Lex/ModuleLoader.h"
25f4a2713aSLionel Sambuc #include "clang/Lex/Pragma.h"
26f4a2713aSLionel Sambuc #include "llvm/ADT/APInt.h"
27f4a2713aSLionel Sambuc #include "llvm/Support/ErrorHandling.h"
28*0a6a1f1dSLionel Sambuc #include "llvm/Support/Path.h"
29f4a2713aSLionel Sambuc #include "llvm/Support/SaveAndRestore.h"
30f4a2713aSLionel Sambuc using namespace clang;
31f4a2713aSLionel Sambuc
32f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
33f4a2713aSLionel Sambuc // Utility Methods for Preprocessor Directive Handling.
34f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
35f4a2713aSLionel Sambuc
AllocateMacroInfo()36f4a2713aSLionel Sambuc MacroInfo *Preprocessor::AllocateMacroInfo() {
37*0a6a1f1dSLionel Sambuc MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
38f4a2713aSLionel Sambuc MIChain->Next = MIChainHead;
39f4a2713aSLionel Sambuc MIChainHead = MIChain;
40*0a6a1f1dSLionel Sambuc return &MIChain->MI;
41f4a2713aSLionel Sambuc }
42f4a2713aSLionel Sambuc
AllocateMacroInfo(SourceLocation L)43f4a2713aSLionel Sambuc MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
44f4a2713aSLionel Sambuc MacroInfo *MI = AllocateMacroInfo();
45f4a2713aSLionel Sambuc new (MI) MacroInfo(L);
46f4a2713aSLionel Sambuc return MI;
47f4a2713aSLionel Sambuc }
48f4a2713aSLionel Sambuc
AllocateDeserializedMacroInfo(SourceLocation L,unsigned SubModuleID)49f4a2713aSLionel Sambuc MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
50f4a2713aSLionel Sambuc unsigned SubModuleID) {
51*0a6a1f1dSLionel Sambuc static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
52f4a2713aSLionel Sambuc "alignment for MacroInfo is less than the ID");
53f4a2713aSLionel Sambuc DeserializedMacroInfoChain *MIChain =
54f4a2713aSLionel Sambuc BP.Allocate<DeserializedMacroInfoChain>();
55f4a2713aSLionel Sambuc MIChain->Next = DeserialMIChainHead;
56f4a2713aSLionel Sambuc DeserialMIChainHead = MIChain;
57f4a2713aSLionel Sambuc
58f4a2713aSLionel Sambuc MacroInfo *MI = &MIChain->MI;
59f4a2713aSLionel Sambuc new (MI) MacroInfo(L);
60f4a2713aSLionel Sambuc MI->FromASTFile = true;
61f4a2713aSLionel Sambuc MI->setOwningModuleID(SubModuleID);
62f4a2713aSLionel Sambuc return MI;
63f4a2713aSLionel Sambuc }
64f4a2713aSLionel Sambuc
65f4a2713aSLionel Sambuc DefMacroDirective *
AllocateDefMacroDirective(MacroInfo * MI,SourceLocation Loc,unsigned ImportedFromModuleID,ArrayRef<unsigned> Overrides)66f4a2713aSLionel Sambuc Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
67*0a6a1f1dSLionel Sambuc unsigned ImportedFromModuleID,
68*0a6a1f1dSLionel Sambuc ArrayRef<unsigned> Overrides) {
69*0a6a1f1dSLionel Sambuc unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size();
70*0a6a1f1dSLionel Sambuc return new (BP.Allocate(sizeof(DefMacroDirective) +
71*0a6a1f1dSLionel Sambuc sizeof(unsigned) * NumExtra,
72*0a6a1f1dSLionel Sambuc llvm::alignOf<DefMacroDirective>()))
73*0a6a1f1dSLionel Sambuc DefMacroDirective(MI, Loc, ImportedFromModuleID, Overrides);
74f4a2713aSLionel Sambuc }
75f4a2713aSLionel Sambuc
76f4a2713aSLionel Sambuc UndefMacroDirective *
AllocateUndefMacroDirective(SourceLocation UndefLoc,unsigned ImportedFromModuleID,ArrayRef<unsigned> Overrides)77*0a6a1f1dSLionel Sambuc Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc,
78*0a6a1f1dSLionel Sambuc unsigned ImportedFromModuleID,
79*0a6a1f1dSLionel Sambuc ArrayRef<unsigned> Overrides) {
80*0a6a1f1dSLionel Sambuc unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size();
81*0a6a1f1dSLionel Sambuc return new (BP.Allocate(sizeof(UndefMacroDirective) +
82*0a6a1f1dSLionel Sambuc sizeof(unsigned) * NumExtra,
83*0a6a1f1dSLionel Sambuc llvm::alignOf<UndefMacroDirective>()))
84*0a6a1f1dSLionel Sambuc UndefMacroDirective(UndefLoc, ImportedFromModuleID, Overrides);
85f4a2713aSLionel Sambuc }
86f4a2713aSLionel Sambuc
87f4a2713aSLionel Sambuc VisibilityMacroDirective *
AllocateVisibilityMacroDirective(SourceLocation Loc,bool isPublic)88f4a2713aSLionel Sambuc Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
89f4a2713aSLionel Sambuc bool isPublic) {
90*0a6a1f1dSLionel Sambuc return new (BP) VisibilityMacroDirective(Loc, isPublic);
91f4a2713aSLionel Sambuc }
92f4a2713aSLionel Sambuc
93f4a2713aSLionel Sambuc /// \brief Read and discard all tokens remaining on the current line until
94f4a2713aSLionel Sambuc /// the tok::eod token is found.
DiscardUntilEndOfDirective()95f4a2713aSLionel Sambuc void Preprocessor::DiscardUntilEndOfDirective() {
96f4a2713aSLionel Sambuc Token Tmp;
97f4a2713aSLionel Sambuc do {
98f4a2713aSLionel Sambuc LexUnexpandedToken(Tmp);
99f4a2713aSLionel Sambuc assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
100f4a2713aSLionel Sambuc } while (Tmp.isNot(tok::eod));
101f4a2713aSLionel Sambuc }
102f4a2713aSLionel Sambuc
103*0a6a1f1dSLionel Sambuc /// \brief Enumerates possible cases of #define/#undef a reserved identifier.
104*0a6a1f1dSLionel Sambuc enum MacroDiag {
105*0a6a1f1dSLionel Sambuc MD_NoWarn, //> Not a reserved identifier
106*0a6a1f1dSLionel Sambuc MD_KeywordDef, //> Macro hides keyword, enabled by default
107*0a6a1f1dSLionel Sambuc MD_ReservedMacro //> #define of #undef reserved id, disabled by default
108*0a6a1f1dSLionel Sambuc };
109*0a6a1f1dSLionel Sambuc
110*0a6a1f1dSLionel Sambuc /// \brief Checks if the specified identifier is reserved in the specified
111*0a6a1f1dSLionel Sambuc /// language.
112*0a6a1f1dSLionel Sambuc /// This function does not check if the identifier is a keyword.
isReservedId(StringRef Text,const LangOptions & Lang)113*0a6a1f1dSLionel Sambuc static bool isReservedId(StringRef Text, const LangOptions &Lang) {
114*0a6a1f1dSLionel Sambuc // C++ [macro.names], C11 7.1.3:
115*0a6a1f1dSLionel Sambuc // All identifiers that begin with an underscore and either an uppercase
116*0a6a1f1dSLionel Sambuc // letter or another underscore are always reserved for any use.
117*0a6a1f1dSLionel Sambuc if (Text.size() >= 2 && Text[0] == '_' &&
118*0a6a1f1dSLionel Sambuc (isUppercase(Text[1]) || Text[1] == '_'))
119*0a6a1f1dSLionel Sambuc return true;
120*0a6a1f1dSLionel Sambuc // C++ [global.names]
121*0a6a1f1dSLionel Sambuc // Each name that contains a double underscore ... is reserved to the
122*0a6a1f1dSLionel Sambuc // implementation for any use.
123*0a6a1f1dSLionel Sambuc if (Lang.CPlusPlus) {
124*0a6a1f1dSLionel Sambuc if (Text.find("__") != StringRef::npos)
125*0a6a1f1dSLionel Sambuc return true;
126*0a6a1f1dSLionel Sambuc }
127*0a6a1f1dSLionel Sambuc return false;
128*0a6a1f1dSLionel Sambuc }
129*0a6a1f1dSLionel Sambuc
shouldWarnOnMacroDef(Preprocessor & PP,IdentifierInfo * II)130*0a6a1f1dSLionel Sambuc static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
131*0a6a1f1dSLionel Sambuc const LangOptions &Lang = PP.getLangOpts();
132*0a6a1f1dSLionel Sambuc StringRef Text = II->getName();
133*0a6a1f1dSLionel Sambuc if (isReservedId(Text, Lang))
134*0a6a1f1dSLionel Sambuc return MD_ReservedMacro;
135*0a6a1f1dSLionel Sambuc if (II->isKeyword(Lang))
136*0a6a1f1dSLionel Sambuc return MD_KeywordDef;
137*0a6a1f1dSLionel Sambuc if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
138*0a6a1f1dSLionel Sambuc return MD_KeywordDef;
139*0a6a1f1dSLionel Sambuc return MD_NoWarn;
140*0a6a1f1dSLionel Sambuc }
141*0a6a1f1dSLionel Sambuc
shouldWarnOnMacroUndef(Preprocessor & PP,IdentifierInfo * II)142*0a6a1f1dSLionel Sambuc static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
143*0a6a1f1dSLionel Sambuc const LangOptions &Lang = PP.getLangOpts();
144*0a6a1f1dSLionel Sambuc StringRef Text = II->getName();
145*0a6a1f1dSLionel Sambuc // Do not warn on keyword undef. It is generally harmless and widely used.
146*0a6a1f1dSLionel Sambuc if (isReservedId(Text, Lang))
147*0a6a1f1dSLionel Sambuc return MD_ReservedMacro;
148*0a6a1f1dSLionel Sambuc return MD_NoWarn;
149*0a6a1f1dSLionel Sambuc }
150*0a6a1f1dSLionel Sambuc
CheckMacroName(Token & MacroNameTok,MacroUse isDefineUndef,bool * ShadowFlag)151*0a6a1f1dSLionel Sambuc bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
152*0a6a1f1dSLionel Sambuc bool *ShadowFlag) {
153*0a6a1f1dSLionel Sambuc // Missing macro name?
154*0a6a1f1dSLionel Sambuc if (MacroNameTok.is(tok::eod))
155*0a6a1f1dSLionel Sambuc return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
156*0a6a1f1dSLionel Sambuc
157*0a6a1f1dSLionel Sambuc IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
158*0a6a1f1dSLionel Sambuc if (!II) {
159*0a6a1f1dSLionel Sambuc bool Invalid = false;
160*0a6a1f1dSLionel Sambuc std::string Spelling = getSpelling(MacroNameTok, &Invalid);
161*0a6a1f1dSLionel Sambuc if (Invalid)
162*0a6a1f1dSLionel Sambuc return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
163*0a6a1f1dSLionel Sambuc II = getIdentifierInfo(Spelling);
164*0a6a1f1dSLionel Sambuc
165*0a6a1f1dSLionel Sambuc if (!II->isCPlusPlusOperatorKeyword())
166*0a6a1f1dSLionel Sambuc return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
167*0a6a1f1dSLionel Sambuc
168*0a6a1f1dSLionel Sambuc // C++ 2.5p2: Alternative tokens behave the same as its primary token
169*0a6a1f1dSLionel Sambuc // except for their spellings.
170*0a6a1f1dSLionel Sambuc Diag(MacroNameTok, getLangOpts().MicrosoftExt
171*0a6a1f1dSLionel Sambuc ? diag::ext_pp_operator_used_as_macro_name
172*0a6a1f1dSLionel Sambuc : diag::err_pp_operator_used_as_macro_name)
173*0a6a1f1dSLionel Sambuc << II << MacroNameTok.getKind();
174*0a6a1f1dSLionel Sambuc
175*0a6a1f1dSLionel Sambuc // Allow #defining |and| and friends for Microsoft compatibility or
176*0a6a1f1dSLionel Sambuc // recovery when legacy C headers are included in C++.
177*0a6a1f1dSLionel Sambuc MacroNameTok.setIdentifierInfo(II);
178*0a6a1f1dSLionel Sambuc }
179*0a6a1f1dSLionel Sambuc
180*0a6a1f1dSLionel Sambuc if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
181*0a6a1f1dSLionel Sambuc // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
182*0a6a1f1dSLionel Sambuc return Diag(MacroNameTok, diag::err_defined_macro_name);
183*0a6a1f1dSLionel Sambuc }
184*0a6a1f1dSLionel Sambuc
185*0a6a1f1dSLionel Sambuc if (isDefineUndef == MU_Undef && II->hasMacroDefinition() &&
186*0a6a1f1dSLionel Sambuc getMacroInfo(II)->isBuiltinMacro()) {
187*0a6a1f1dSLionel Sambuc // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
188*0a6a1f1dSLionel Sambuc // and C++ [cpp.predefined]p4], but allow it as an extension.
189*0a6a1f1dSLionel Sambuc Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
190*0a6a1f1dSLionel Sambuc }
191*0a6a1f1dSLionel Sambuc
192*0a6a1f1dSLionel Sambuc // If defining/undefining reserved identifier or a keyword, we need to issue
193*0a6a1f1dSLionel Sambuc // a warning.
194*0a6a1f1dSLionel Sambuc SourceLocation MacroNameLoc = MacroNameTok.getLocation();
195*0a6a1f1dSLionel Sambuc if (ShadowFlag)
196*0a6a1f1dSLionel Sambuc *ShadowFlag = false;
197*0a6a1f1dSLionel Sambuc if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
198*0a6a1f1dSLionel Sambuc (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
199*0a6a1f1dSLionel Sambuc MacroDiag D = MD_NoWarn;
200*0a6a1f1dSLionel Sambuc if (isDefineUndef == MU_Define) {
201*0a6a1f1dSLionel Sambuc D = shouldWarnOnMacroDef(*this, II);
202*0a6a1f1dSLionel Sambuc }
203*0a6a1f1dSLionel Sambuc else if (isDefineUndef == MU_Undef)
204*0a6a1f1dSLionel Sambuc D = shouldWarnOnMacroUndef(*this, II);
205*0a6a1f1dSLionel Sambuc if (D == MD_KeywordDef) {
206*0a6a1f1dSLionel Sambuc // We do not want to warn on some patterns widely used in configuration
207*0a6a1f1dSLionel Sambuc // scripts. This requires analyzing next tokens, so do not issue warnings
208*0a6a1f1dSLionel Sambuc // now, only inform caller.
209*0a6a1f1dSLionel Sambuc if (ShadowFlag)
210*0a6a1f1dSLionel Sambuc *ShadowFlag = true;
211*0a6a1f1dSLionel Sambuc }
212*0a6a1f1dSLionel Sambuc if (D == MD_ReservedMacro)
213*0a6a1f1dSLionel Sambuc Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
214*0a6a1f1dSLionel Sambuc }
215*0a6a1f1dSLionel Sambuc
216*0a6a1f1dSLionel Sambuc // Okay, we got a good identifier.
217*0a6a1f1dSLionel Sambuc return false;
218*0a6a1f1dSLionel Sambuc }
219*0a6a1f1dSLionel Sambuc
220f4a2713aSLionel Sambuc /// \brief Lex and validate a macro name, which occurs after a
221f4a2713aSLionel Sambuc /// \#define or \#undef.
222f4a2713aSLionel Sambuc ///
223*0a6a1f1dSLionel Sambuc /// This sets the token kind to eod and discards the rest of the macro line if
224*0a6a1f1dSLionel Sambuc /// the macro name is invalid.
225*0a6a1f1dSLionel Sambuc ///
226*0a6a1f1dSLionel Sambuc /// \param MacroNameTok Token that is expected to be a macro name.
227*0a6a1f1dSLionel Sambuc /// \param isDefineUndef Context in which macro is used.
228*0a6a1f1dSLionel Sambuc /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
ReadMacroName(Token & MacroNameTok,MacroUse isDefineUndef,bool * ShadowFlag)229*0a6a1f1dSLionel Sambuc void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
230*0a6a1f1dSLionel Sambuc bool *ShadowFlag) {
231f4a2713aSLionel Sambuc // Read the token, don't allow macro expansion on it.
232f4a2713aSLionel Sambuc LexUnexpandedToken(MacroNameTok);
233f4a2713aSLionel Sambuc
234f4a2713aSLionel Sambuc if (MacroNameTok.is(tok::code_completion)) {
235f4a2713aSLionel Sambuc if (CodeComplete)
236*0a6a1f1dSLionel Sambuc CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
237f4a2713aSLionel Sambuc setCodeCompletionReached();
238f4a2713aSLionel Sambuc LexUnexpandedToken(MacroNameTok);
239f4a2713aSLionel Sambuc }
240f4a2713aSLionel Sambuc
241*0a6a1f1dSLionel Sambuc if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
242f4a2713aSLionel Sambuc return;
243f4a2713aSLionel Sambuc
244*0a6a1f1dSLionel Sambuc // Invalid macro name, read and discard the rest of the line and set the
245*0a6a1f1dSLionel Sambuc // token kind to tok::eod if necessary.
246*0a6a1f1dSLionel Sambuc if (MacroNameTok.isNot(tok::eod)) {
247f4a2713aSLionel Sambuc MacroNameTok.setKind(tok::eod);
248*0a6a1f1dSLionel Sambuc DiscardUntilEndOfDirective();
249*0a6a1f1dSLionel Sambuc }
250f4a2713aSLionel Sambuc }
251f4a2713aSLionel Sambuc
252f4a2713aSLionel Sambuc /// \brief Ensure that the next token is a tok::eod token.
253f4a2713aSLionel Sambuc ///
254f4a2713aSLionel Sambuc /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
255f4a2713aSLionel Sambuc /// true, then we consider macros that expand to zero tokens as being ok.
CheckEndOfDirective(const char * DirType,bool EnableMacros)256f4a2713aSLionel Sambuc void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
257f4a2713aSLionel Sambuc Token Tmp;
258f4a2713aSLionel Sambuc // Lex unexpanded tokens for most directives: macros might expand to zero
259f4a2713aSLionel Sambuc // tokens, causing us to miss diagnosing invalid lines. Some directives (like
260f4a2713aSLionel Sambuc // #line) allow empty macros.
261f4a2713aSLionel Sambuc if (EnableMacros)
262f4a2713aSLionel Sambuc Lex(Tmp);
263f4a2713aSLionel Sambuc else
264f4a2713aSLionel Sambuc LexUnexpandedToken(Tmp);
265f4a2713aSLionel Sambuc
266f4a2713aSLionel Sambuc // There should be no tokens after the directive, but we allow them as an
267f4a2713aSLionel Sambuc // extension.
268f4a2713aSLionel Sambuc while (Tmp.is(tok::comment)) // Skip comments in -C mode.
269f4a2713aSLionel Sambuc LexUnexpandedToken(Tmp);
270f4a2713aSLionel Sambuc
271f4a2713aSLionel Sambuc if (Tmp.isNot(tok::eod)) {
272f4a2713aSLionel Sambuc // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
273f4a2713aSLionel Sambuc // or if this is a macro-style preprocessing directive, because it is more
274f4a2713aSLionel Sambuc // trouble than it is worth to insert /**/ and check that there is no /**/
275f4a2713aSLionel Sambuc // in the range also.
276f4a2713aSLionel Sambuc FixItHint Hint;
277f4a2713aSLionel Sambuc if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
278f4a2713aSLionel Sambuc !CurTokenLexer)
279f4a2713aSLionel Sambuc Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
280f4a2713aSLionel Sambuc Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
281f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
282f4a2713aSLionel Sambuc }
283f4a2713aSLionel Sambuc }
284f4a2713aSLionel Sambuc
285f4a2713aSLionel Sambuc
286f4a2713aSLionel Sambuc
287f4a2713aSLionel Sambuc /// SkipExcludedConditionalBlock - We just read a \#if or related directive and
288f4a2713aSLionel Sambuc /// decided that the subsequent tokens are in the \#if'd out portion of the
289f4a2713aSLionel Sambuc /// file. Lex the rest of the file, until we see an \#endif. If
290f4a2713aSLionel Sambuc /// FoundNonSkipPortion is true, then we have already emitted code for part of
291f4a2713aSLionel Sambuc /// this \#if directive, so \#else/\#elif blocks should never be entered.
292f4a2713aSLionel Sambuc /// If ElseOk is true, then \#else directives are ok, if not, then we have
293f4a2713aSLionel Sambuc /// already seen one so a \#else directive is a duplicate. When this returns,
294f4a2713aSLionel Sambuc /// the caller can lex the first valid token.
SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,bool FoundNonSkipPortion,bool FoundElse,SourceLocation ElseLoc)295f4a2713aSLionel Sambuc void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
296f4a2713aSLionel Sambuc bool FoundNonSkipPortion,
297f4a2713aSLionel Sambuc bool FoundElse,
298f4a2713aSLionel Sambuc SourceLocation ElseLoc) {
299f4a2713aSLionel Sambuc ++NumSkipped;
300f4a2713aSLionel Sambuc assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
301f4a2713aSLionel Sambuc
302f4a2713aSLionel Sambuc CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
303f4a2713aSLionel Sambuc FoundNonSkipPortion, FoundElse);
304f4a2713aSLionel Sambuc
305f4a2713aSLionel Sambuc if (CurPTHLexer) {
306f4a2713aSLionel Sambuc PTHSkipExcludedConditionalBlock();
307f4a2713aSLionel Sambuc return;
308f4a2713aSLionel Sambuc }
309f4a2713aSLionel Sambuc
310f4a2713aSLionel Sambuc // Enter raw mode to disable identifier lookup (and thus macro expansion),
311f4a2713aSLionel Sambuc // disabling warnings, etc.
312f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = true;
313f4a2713aSLionel Sambuc Token Tok;
314f4a2713aSLionel Sambuc while (1) {
315f4a2713aSLionel Sambuc CurLexer->Lex(Tok);
316f4a2713aSLionel Sambuc
317f4a2713aSLionel Sambuc if (Tok.is(tok::code_completion)) {
318f4a2713aSLionel Sambuc if (CodeComplete)
319f4a2713aSLionel Sambuc CodeComplete->CodeCompleteInConditionalExclusion();
320f4a2713aSLionel Sambuc setCodeCompletionReached();
321f4a2713aSLionel Sambuc continue;
322f4a2713aSLionel Sambuc }
323f4a2713aSLionel Sambuc
324f4a2713aSLionel Sambuc // If this is the end of the buffer, we have an error.
325f4a2713aSLionel Sambuc if (Tok.is(tok::eof)) {
326f4a2713aSLionel Sambuc // Emit errors for each unterminated conditional on the stack, including
327f4a2713aSLionel Sambuc // the current one.
328f4a2713aSLionel Sambuc while (!CurPPLexer->ConditionalStack.empty()) {
329f4a2713aSLionel Sambuc if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
330f4a2713aSLionel Sambuc Diag(CurPPLexer->ConditionalStack.back().IfLoc,
331f4a2713aSLionel Sambuc diag::err_pp_unterminated_conditional);
332f4a2713aSLionel Sambuc CurPPLexer->ConditionalStack.pop_back();
333f4a2713aSLionel Sambuc }
334f4a2713aSLionel Sambuc
335f4a2713aSLionel Sambuc // Just return and let the caller lex after this #include.
336f4a2713aSLionel Sambuc break;
337f4a2713aSLionel Sambuc }
338f4a2713aSLionel Sambuc
339f4a2713aSLionel Sambuc // If this token is not a preprocessor directive, just skip it.
340f4a2713aSLionel Sambuc if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
341f4a2713aSLionel Sambuc continue;
342f4a2713aSLionel Sambuc
343f4a2713aSLionel Sambuc // We just parsed a # character at the start of a line, so we're in
344f4a2713aSLionel Sambuc // directive mode. Tell the lexer this so any newlines we see will be
345f4a2713aSLionel Sambuc // converted into an EOD token (this terminates the macro).
346f4a2713aSLionel Sambuc CurPPLexer->ParsingPreprocessorDirective = true;
347f4a2713aSLionel Sambuc if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
348f4a2713aSLionel Sambuc
349f4a2713aSLionel Sambuc
350f4a2713aSLionel Sambuc // Read the next token, the directive flavor.
351f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
352f4a2713aSLionel Sambuc
353f4a2713aSLionel Sambuc // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
354f4a2713aSLionel Sambuc // something bogus), skip it.
355f4a2713aSLionel Sambuc if (Tok.isNot(tok::raw_identifier)) {
356f4a2713aSLionel Sambuc CurPPLexer->ParsingPreprocessorDirective = false;
357f4a2713aSLionel Sambuc // Restore comment saving mode.
358f4a2713aSLionel Sambuc if (CurLexer) CurLexer->resetExtendedTokenMode();
359f4a2713aSLionel Sambuc continue;
360f4a2713aSLionel Sambuc }
361f4a2713aSLionel Sambuc
362f4a2713aSLionel Sambuc // If the first letter isn't i or e, it isn't intesting to us. We know that
363f4a2713aSLionel Sambuc // this is safe in the face of spelling differences, because there is no way
364f4a2713aSLionel Sambuc // to spell an i/e in a strange way that is another letter. Skipping this
365f4a2713aSLionel Sambuc // allows us to avoid looking up the identifier info for #define/#undef and
366f4a2713aSLionel Sambuc // other common directives.
367*0a6a1f1dSLionel Sambuc StringRef RI = Tok.getRawIdentifier();
368f4a2713aSLionel Sambuc
369*0a6a1f1dSLionel Sambuc char FirstChar = RI[0];
370f4a2713aSLionel Sambuc if (FirstChar >= 'a' && FirstChar <= 'z' &&
371f4a2713aSLionel Sambuc FirstChar != 'i' && FirstChar != 'e') {
372f4a2713aSLionel Sambuc CurPPLexer->ParsingPreprocessorDirective = false;
373f4a2713aSLionel Sambuc // Restore comment saving mode.
374f4a2713aSLionel Sambuc if (CurLexer) CurLexer->resetExtendedTokenMode();
375f4a2713aSLionel Sambuc continue;
376f4a2713aSLionel Sambuc }
377f4a2713aSLionel Sambuc
378f4a2713aSLionel Sambuc // Get the identifier name without trigraphs or embedded newlines. Note
379f4a2713aSLionel Sambuc // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
380f4a2713aSLionel Sambuc // when skipping.
381f4a2713aSLionel Sambuc char DirectiveBuf[20];
382f4a2713aSLionel Sambuc StringRef Directive;
383*0a6a1f1dSLionel Sambuc if (!Tok.needsCleaning() && RI.size() < 20) {
384*0a6a1f1dSLionel Sambuc Directive = RI;
385f4a2713aSLionel Sambuc } else {
386f4a2713aSLionel Sambuc std::string DirectiveStr = getSpelling(Tok);
387f4a2713aSLionel Sambuc unsigned IdLen = DirectiveStr.size();
388f4a2713aSLionel Sambuc if (IdLen >= 20) {
389f4a2713aSLionel Sambuc CurPPLexer->ParsingPreprocessorDirective = false;
390f4a2713aSLionel Sambuc // Restore comment saving mode.
391f4a2713aSLionel Sambuc if (CurLexer) CurLexer->resetExtendedTokenMode();
392f4a2713aSLionel Sambuc continue;
393f4a2713aSLionel Sambuc }
394f4a2713aSLionel Sambuc memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
395f4a2713aSLionel Sambuc Directive = StringRef(DirectiveBuf, IdLen);
396f4a2713aSLionel Sambuc }
397f4a2713aSLionel Sambuc
398f4a2713aSLionel Sambuc if (Directive.startswith("if")) {
399f4a2713aSLionel Sambuc StringRef Sub = Directive.substr(2);
400f4a2713aSLionel Sambuc if (Sub.empty() || // "if"
401f4a2713aSLionel Sambuc Sub == "def" || // "ifdef"
402f4a2713aSLionel Sambuc Sub == "ndef") { // "ifndef"
403f4a2713aSLionel Sambuc // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
404f4a2713aSLionel Sambuc // bother parsing the condition.
405f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
406f4a2713aSLionel Sambuc CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
407f4a2713aSLionel Sambuc /*foundnonskip*/false,
408f4a2713aSLionel Sambuc /*foundelse*/false);
409f4a2713aSLionel Sambuc }
410f4a2713aSLionel Sambuc } else if (Directive[0] == 'e') {
411f4a2713aSLionel Sambuc StringRef Sub = Directive.substr(1);
412f4a2713aSLionel Sambuc if (Sub == "ndif") { // "endif"
413f4a2713aSLionel Sambuc PPConditionalInfo CondInfo;
414f4a2713aSLionel Sambuc CondInfo.WasSkipping = true; // Silence bogus warning.
415f4a2713aSLionel Sambuc bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
416f4a2713aSLionel Sambuc (void)InCond; // Silence warning in no-asserts mode.
417f4a2713aSLionel Sambuc assert(!InCond && "Can't be skipping if not in a conditional!");
418f4a2713aSLionel Sambuc
419f4a2713aSLionel Sambuc // If we popped the outermost skipping block, we're done skipping!
420f4a2713aSLionel Sambuc if (!CondInfo.WasSkipping) {
421f4a2713aSLionel Sambuc // Restore the value of LexingRawMode so that trailing comments
422f4a2713aSLionel Sambuc // are handled correctly, if we've reached the outermost block.
423f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = false;
424f4a2713aSLionel Sambuc CheckEndOfDirective("endif");
425f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = true;
426f4a2713aSLionel Sambuc if (Callbacks)
427f4a2713aSLionel Sambuc Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
428f4a2713aSLionel Sambuc break;
429f4a2713aSLionel Sambuc } else {
430f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
431f4a2713aSLionel Sambuc }
432f4a2713aSLionel Sambuc } else if (Sub == "lse") { // "else".
433f4a2713aSLionel Sambuc // #else directive in a skipping conditional. If not in some other
434f4a2713aSLionel Sambuc // skipping conditional, and if #else hasn't already been seen, enter it
435f4a2713aSLionel Sambuc // as a non-skipping conditional.
436f4a2713aSLionel Sambuc PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
437f4a2713aSLionel Sambuc
438f4a2713aSLionel Sambuc // If this is a #else with a #else before it, report the error.
439f4a2713aSLionel Sambuc if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
440f4a2713aSLionel Sambuc
441f4a2713aSLionel Sambuc // Note that we've seen a #else in this conditional.
442f4a2713aSLionel Sambuc CondInfo.FoundElse = true;
443f4a2713aSLionel Sambuc
444f4a2713aSLionel Sambuc // If the conditional is at the top level, and the #if block wasn't
445f4a2713aSLionel Sambuc // entered, enter the #else block now.
446f4a2713aSLionel Sambuc if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
447f4a2713aSLionel Sambuc CondInfo.FoundNonSkip = true;
448f4a2713aSLionel Sambuc // Restore the value of LexingRawMode so that trailing comments
449f4a2713aSLionel Sambuc // are handled correctly.
450f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = false;
451f4a2713aSLionel Sambuc CheckEndOfDirective("else");
452f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = true;
453f4a2713aSLionel Sambuc if (Callbacks)
454f4a2713aSLionel Sambuc Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
455f4a2713aSLionel Sambuc break;
456f4a2713aSLionel Sambuc } else {
457f4a2713aSLionel Sambuc DiscardUntilEndOfDirective(); // C99 6.10p4.
458f4a2713aSLionel Sambuc }
459f4a2713aSLionel Sambuc } else if (Sub == "lif") { // "elif".
460f4a2713aSLionel Sambuc PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
461f4a2713aSLionel Sambuc
462*0a6a1f1dSLionel Sambuc // If this is a #elif with a #else before it, report the error.
463*0a6a1f1dSLionel Sambuc if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
464*0a6a1f1dSLionel Sambuc
465f4a2713aSLionel Sambuc // If this is in a skipping block or if we're already handled this #if
466f4a2713aSLionel Sambuc // block, don't bother parsing the condition.
467f4a2713aSLionel Sambuc if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
468f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
469f4a2713aSLionel Sambuc } else {
470*0a6a1f1dSLionel Sambuc const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
471f4a2713aSLionel Sambuc // Restore the value of LexingRawMode so that identifiers are
472f4a2713aSLionel Sambuc // looked up, etc, inside the #elif expression.
473f4a2713aSLionel Sambuc assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
474f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = false;
475*0a6a1f1dSLionel Sambuc IdentifierInfo *IfNDefMacro = nullptr;
476*0a6a1f1dSLionel Sambuc const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
477f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = true;
478*0a6a1f1dSLionel Sambuc if (Callbacks) {
479*0a6a1f1dSLionel Sambuc const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
480f4a2713aSLionel Sambuc Callbacks->Elif(Tok.getLocation(),
481*0a6a1f1dSLionel Sambuc SourceRange(CondBegin, CondEnd),
482*0a6a1f1dSLionel Sambuc (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
483*0a6a1f1dSLionel Sambuc }
484*0a6a1f1dSLionel Sambuc // If this condition is true, enter it!
485*0a6a1f1dSLionel Sambuc if (CondValue) {
486*0a6a1f1dSLionel Sambuc CondInfo.FoundNonSkip = true;
487f4a2713aSLionel Sambuc break;
488f4a2713aSLionel Sambuc }
489f4a2713aSLionel Sambuc }
490f4a2713aSLionel Sambuc }
491*0a6a1f1dSLionel Sambuc }
492f4a2713aSLionel Sambuc
493f4a2713aSLionel Sambuc CurPPLexer->ParsingPreprocessorDirective = false;
494f4a2713aSLionel Sambuc // Restore comment saving mode.
495f4a2713aSLionel Sambuc if (CurLexer) CurLexer->resetExtendedTokenMode();
496f4a2713aSLionel Sambuc }
497f4a2713aSLionel Sambuc
498f4a2713aSLionel Sambuc // Finally, if we are out of the conditional (saw an #endif or ran off the end
499f4a2713aSLionel Sambuc // of the file, just stop skipping and return to lexing whatever came after
500f4a2713aSLionel Sambuc // the #if block.
501f4a2713aSLionel Sambuc CurPPLexer->LexingRawMode = false;
502f4a2713aSLionel Sambuc
503f4a2713aSLionel Sambuc if (Callbacks) {
504f4a2713aSLionel Sambuc SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
505f4a2713aSLionel Sambuc Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
506f4a2713aSLionel Sambuc }
507f4a2713aSLionel Sambuc }
508f4a2713aSLionel Sambuc
PTHSkipExcludedConditionalBlock()509f4a2713aSLionel Sambuc void Preprocessor::PTHSkipExcludedConditionalBlock() {
510f4a2713aSLionel Sambuc
511f4a2713aSLionel Sambuc while (1) {
512f4a2713aSLionel Sambuc assert(CurPTHLexer);
513f4a2713aSLionel Sambuc assert(CurPTHLexer->LexingRawMode == false);
514f4a2713aSLionel Sambuc
515f4a2713aSLionel Sambuc // Skip to the next '#else', '#elif', or #endif.
516f4a2713aSLionel Sambuc if (CurPTHLexer->SkipBlock()) {
517f4a2713aSLionel Sambuc // We have reached an #endif. Both the '#' and 'endif' tokens
518f4a2713aSLionel Sambuc // have been consumed by the PTHLexer. Just pop off the condition level.
519f4a2713aSLionel Sambuc PPConditionalInfo CondInfo;
520f4a2713aSLionel Sambuc bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
521f4a2713aSLionel Sambuc (void)InCond; // Silence warning in no-asserts mode.
522f4a2713aSLionel Sambuc assert(!InCond && "Can't be skipping if not in a conditional!");
523f4a2713aSLionel Sambuc break;
524f4a2713aSLionel Sambuc }
525f4a2713aSLionel Sambuc
526f4a2713aSLionel Sambuc // We have reached a '#else' or '#elif'. Lex the next token to get
527f4a2713aSLionel Sambuc // the directive flavor.
528f4a2713aSLionel Sambuc Token Tok;
529f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
530f4a2713aSLionel Sambuc
531f4a2713aSLionel Sambuc // We can actually look up the IdentifierInfo here since we aren't in
532f4a2713aSLionel Sambuc // raw mode.
533f4a2713aSLionel Sambuc tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
534f4a2713aSLionel Sambuc
535f4a2713aSLionel Sambuc if (K == tok::pp_else) {
536f4a2713aSLionel Sambuc // #else: Enter the else condition. We aren't in a nested condition
537f4a2713aSLionel Sambuc // since we skip those. We're always in the one matching the last
538f4a2713aSLionel Sambuc // blocked we skipped.
539f4a2713aSLionel Sambuc PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
540f4a2713aSLionel Sambuc // Note that we've seen a #else in this conditional.
541f4a2713aSLionel Sambuc CondInfo.FoundElse = true;
542f4a2713aSLionel Sambuc
543f4a2713aSLionel Sambuc // If the #if block wasn't entered then enter the #else block now.
544f4a2713aSLionel Sambuc if (!CondInfo.FoundNonSkip) {
545f4a2713aSLionel Sambuc CondInfo.FoundNonSkip = true;
546f4a2713aSLionel Sambuc
547f4a2713aSLionel Sambuc // Scan until the eod token.
548f4a2713aSLionel Sambuc CurPTHLexer->ParsingPreprocessorDirective = true;
549f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
550f4a2713aSLionel Sambuc CurPTHLexer->ParsingPreprocessorDirective = false;
551f4a2713aSLionel Sambuc
552f4a2713aSLionel Sambuc break;
553f4a2713aSLionel Sambuc }
554f4a2713aSLionel Sambuc
555f4a2713aSLionel Sambuc // Otherwise skip this block.
556f4a2713aSLionel Sambuc continue;
557f4a2713aSLionel Sambuc }
558f4a2713aSLionel Sambuc
559f4a2713aSLionel Sambuc assert(K == tok::pp_elif);
560f4a2713aSLionel Sambuc PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
561f4a2713aSLionel Sambuc
562f4a2713aSLionel Sambuc // If this is a #elif with a #else before it, report the error.
563f4a2713aSLionel Sambuc if (CondInfo.FoundElse)
564f4a2713aSLionel Sambuc Diag(Tok, diag::pp_err_elif_after_else);
565f4a2713aSLionel Sambuc
566f4a2713aSLionel Sambuc // If this is in a skipping block or if we're already handled this #if
567f4a2713aSLionel Sambuc // block, don't bother parsing the condition. We just skip this block.
568f4a2713aSLionel Sambuc if (CondInfo.FoundNonSkip)
569f4a2713aSLionel Sambuc continue;
570f4a2713aSLionel Sambuc
571f4a2713aSLionel Sambuc // Evaluate the condition of the #elif.
572*0a6a1f1dSLionel Sambuc IdentifierInfo *IfNDefMacro = nullptr;
573f4a2713aSLionel Sambuc CurPTHLexer->ParsingPreprocessorDirective = true;
574f4a2713aSLionel Sambuc bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
575f4a2713aSLionel Sambuc CurPTHLexer->ParsingPreprocessorDirective = false;
576f4a2713aSLionel Sambuc
577f4a2713aSLionel Sambuc // If this condition is true, enter it!
578f4a2713aSLionel Sambuc if (ShouldEnter) {
579f4a2713aSLionel Sambuc CondInfo.FoundNonSkip = true;
580f4a2713aSLionel Sambuc break;
581f4a2713aSLionel Sambuc }
582f4a2713aSLionel Sambuc
583f4a2713aSLionel Sambuc // Otherwise, skip this block and go to the next one.
584f4a2713aSLionel Sambuc continue;
585f4a2713aSLionel Sambuc }
586f4a2713aSLionel Sambuc }
587f4a2713aSLionel Sambuc
getModuleForLocation(SourceLocation FilenameLoc)588f4a2713aSLionel Sambuc Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) {
589f4a2713aSLionel Sambuc ModuleMap &ModMap = HeaderInfo.getModuleMap();
590f4a2713aSLionel Sambuc if (SourceMgr.isInMainFile(FilenameLoc)) {
591f4a2713aSLionel Sambuc if (Module *CurMod = getCurrentModule())
592f4a2713aSLionel Sambuc return CurMod; // Compiling a module.
593f4a2713aSLionel Sambuc return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
594f4a2713aSLionel Sambuc }
595f4a2713aSLionel Sambuc // Try to determine the module of the include directive.
596*0a6a1f1dSLionel Sambuc // FIXME: Look into directly passing the FileEntry from LookupFile instead.
597*0a6a1f1dSLionel Sambuc FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(FilenameLoc));
598f4a2713aSLionel Sambuc if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
599f4a2713aSLionel Sambuc // The include comes from a file.
600f4a2713aSLionel Sambuc return ModMap.findModuleForHeader(EntryOfIncl).getModule();
601f4a2713aSLionel Sambuc } else {
602f4a2713aSLionel Sambuc // The include does not come from a file,
603f4a2713aSLionel Sambuc // so it is probably a module compilation.
604f4a2713aSLionel Sambuc return getCurrentModule();
605f4a2713aSLionel Sambuc }
606f4a2713aSLionel Sambuc }
607f4a2713aSLionel Sambuc
LookupFile(SourceLocation FilenameLoc,StringRef Filename,bool isAngled,const DirectoryLookup * FromDir,const FileEntry * FromFile,const DirectoryLookup * & CurDir,SmallVectorImpl<char> * SearchPath,SmallVectorImpl<char> * RelativePath,ModuleMap::KnownHeader * SuggestedModule,bool SkipCache)608f4a2713aSLionel Sambuc const FileEntry *Preprocessor::LookupFile(
609f4a2713aSLionel Sambuc SourceLocation FilenameLoc,
610f4a2713aSLionel Sambuc StringRef Filename,
611f4a2713aSLionel Sambuc bool isAngled,
612f4a2713aSLionel Sambuc const DirectoryLookup *FromDir,
613*0a6a1f1dSLionel Sambuc const FileEntry *FromFile,
614f4a2713aSLionel Sambuc const DirectoryLookup *&CurDir,
615f4a2713aSLionel Sambuc SmallVectorImpl<char> *SearchPath,
616f4a2713aSLionel Sambuc SmallVectorImpl<char> *RelativePath,
617f4a2713aSLionel Sambuc ModuleMap::KnownHeader *SuggestedModule,
618f4a2713aSLionel Sambuc bool SkipCache) {
619*0a6a1f1dSLionel Sambuc // If the header lookup mechanism may be relative to the current inclusion
620*0a6a1f1dSLionel Sambuc // stack, record the parent #includes.
621*0a6a1f1dSLionel Sambuc SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
622*0a6a1f1dSLionel Sambuc Includers;
623*0a6a1f1dSLionel Sambuc if (!FromDir && !FromFile) {
624f4a2713aSLionel Sambuc FileID FID = getCurrentFileLexer()->getFileID();
625*0a6a1f1dSLionel Sambuc const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
626f4a2713aSLionel Sambuc
627f4a2713aSLionel Sambuc // If there is no file entry associated with this file, it must be the
628*0a6a1f1dSLionel Sambuc // predefines buffer or the module includes buffer. Any other file is not
629*0a6a1f1dSLionel Sambuc // lexed with a normal lexer, so it won't be scanned for preprocessor
630*0a6a1f1dSLionel Sambuc // directives.
631*0a6a1f1dSLionel Sambuc //
632*0a6a1f1dSLionel Sambuc // If we have the predefines buffer, resolve #include references (which come
633*0a6a1f1dSLionel Sambuc // from the -include command line argument) from the current working
634*0a6a1f1dSLionel Sambuc // directory instead of relative to the main file.
635*0a6a1f1dSLionel Sambuc //
636*0a6a1f1dSLionel Sambuc // If we have the module includes buffer, resolve #include references (which
637*0a6a1f1dSLionel Sambuc // come from header declarations in the module map) relative to the module
638*0a6a1f1dSLionel Sambuc // map file.
639*0a6a1f1dSLionel Sambuc if (!FileEnt) {
640*0a6a1f1dSLionel Sambuc if (FID == SourceMgr.getMainFileID() && MainFileDir)
641*0a6a1f1dSLionel Sambuc Includers.push_back(std::make_pair(nullptr, MainFileDir));
642*0a6a1f1dSLionel Sambuc else if ((FileEnt =
643*0a6a1f1dSLionel Sambuc SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
644*0a6a1f1dSLionel Sambuc Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
645*0a6a1f1dSLionel Sambuc } else {
646*0a6a1f1dSLionel Sambuc Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
647*0a6a1f1dSLionel Sambuc }
648*0a6a1f1dSLionel Sambuc
649*0a6a1f1dSLionel Sambuc // MSVC searches the current include stack from top to bottom for
650*0a6a1f1dSLionel Sambuc // headers included by quoted include directives.
651*0a6a1f1dSLionel Sambuc // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
652*0a6a1f1dSLionel Sambuc if (LangOpts.MSVCCompat && !isAngled) {
653*0a6a1f1dSLionel Sambuc for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
654*0a6a1f1dSLionel Sambuc IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
655*0a6a1f1dSLionel Sambuc if (IsFileLexer(ISEntry))
656*0a6a1f1dSLionel Sambuc if ((FileEnt = SourceMgr.getFileEntryForID(
657*0a6a1f1dSLionel Sambuc ISEntry.ThePPLexer->getFileID())))
658*0a6a1f1dSLionel Sambuc Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
659*0a6a1f1dSLionel Sambuc }
660*0a6a1f1dSLionel Sambuc }
661*0a6a1f1dSLionel Sambuc }
662*0a6a1f1dSLionel Sambuc
663*0a6a1f1dSLionel Sambuc CurDir = CurDirLookup;
664*0a6a1f1dSLionel Sambuc
665*0a6a1f1dSLionel Sambuc if (FromFile) {
666*0a6a1f1dSLionel Sambuc // We're supposed to start looking from after a particular file. Search
667*0a6a1f1dSLionel Sambuc // the include path until we find that file or run out of files.
668*0a6a1f1dSLionel Sambuc const DirectoryLookup *TmpCurDir = CurDir;
669*0a6a1f1dSLionel Sambuc const DirectoryLookup *TmpFromDir = nullptr;
670*0a6a1f1dSLionel Sambuc while (const FileEntry *FE = HeaderInfo.LookupFile(
671*0a6a1f1dSLionel Sambuc Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
672*0a6a1f1dSLionel Sambuc Includers, SearchPath, RelativePath, SuggestedModule,
673*0a6a1f1dSLionel Sambuc SkipCache)) {
674*0a6a1f1dSLionel Sambuc // Keep looking as if this file did a #include_next.
675*0a6a1f1dSLionel Sambuc TmpFromDir = TmpCurDir;
676*0a6a1f1dSLionel Sambuc ++TmpFromDir;
677*0a6a1f1dSLionel Sambuc if (FE == FromFile) {
678*0a6a1f1dSLionel Sambuc // Found it.
679*0a6a1f1dSLionel Sambuc FromDir = TmpFromDir;
680*0a6a1f1dSLionel Sambuc CurDir = TmpCurDir;
681*0a6a1f1dSLionel Sambuc break;
682*0a6a1f1dSLionel Sambuc }
683f4a2713aSLionel Sambuc }
684f4a2713aSLionel Sambuc }
685f4a2713aSLionel Sambuc
686f4a2713aSLionel Sambuc // Do a standard file entry lookup.
687f4a2713aSLionel Sambuc const FileEntry *FE = HeaderInfo.LookupFile(
688*0a6a1f1dSLionel Sambuc Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
689*0a6a1f1dSLionel Sambuc RelativePath, SuggestedModule, SkipCache);
690f4a2713aSLionel Sambuc if (FE) {
691*0a6a1f1dSLionel Sambuc if (SuggestedModule && !LangOpts.AsmPreprocessor)
692*0a6a1f1dSLionel Sambuc HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
693*0a6a1f1dSLionel Sambuc getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
694f4a2713aSLionel Sambuc return FE;
695f4a2713aSLionel Sambuc }
696f4a2713aSLionel Sambuc
697*0a6a1f1dSLionel Sambuc const FileEntry *CurFileEnt;
698f4a2713aSLionel Sambuc // Otherwise, see if this is a subframework header. If so, this is relative
699f4a2713aSLionel Sambuc // to one of the headers on the #include stack. Walk the list of the current
700f4a2713aSLionel Sambuc // headers on the #include stack and pass them to HeaderInfo.
701f4a2713aSLionel Sambuc if (IsFileLexer()) {
702*0a6a1f1dSLionel Sambuc if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
703f4a2713aSLionel Sambuc if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
704f4a2713aSLionel Sambuc SearchPath, RelativePath,
705*0a6a1f1dSLionel Sambuc SuggestedModule))) {
706*0a6a1f1dSLionel Sambuc if (SuggestedModule && !LangOpts.AsmPreprocessor)
707*0a6a1f1dSLionel Sambuc HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
708*0a6a1f1dSLionel Sambuc getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
709f4a2713aSLionel Sambuc return FE;
710f4a2713aSLionel Sambuc }
711*0a6a1f1dSLionel Sambuc }
712*0a6a1f1dSLionel Sambuc }
713f4a2713aSLionel Sambuc
714f4a2713aSLionel Sambuc for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
715f4a2713aSLionel Sambuc IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
716f4a2713aSLionel Sambuc if (IsFileLexer(ISEntry)) {
717f4a2713aSLionel Sambuc if ((CurFileEnt =
718*0a6a1f1dSLionel Sambuc SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
719f4a2713aSLionel Sambuc if ((FE = HeaderInfo.LookupSubframeworkHeader(
720f4a2713aSLionel Sambuc Filename, CurFileEnt, SearchPath, RelativePath,
721*0a6a1f1dSLionel Sambuc SuggestedModule))) {
722*0a6a1f1dSLionel Sambuc if (SuggestedModule && !LangOpts.AsmPreprocessor)
723*0a6a1f1dSLionel Sambuc HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
724*0a6a1f1dSLionel Sambuc getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
725f4a2713aSLionel Sambuc return FE;
726f4a2713aSLionel Sambuc }
727f4a2713aSLionel Sambuc }
728*0a6a1f1dSLionel Sambuc }
729*0a6a1f1dSLionel Sambuc }
730f4a2713aSLionel Sambuc
731f4a2713aSLionel Sambuc // Otherwise, we really couldn't find the file.
732*0a6a1f1dSLionel Sambuc return nullptr;
733f4a2713aSLionel Sambuc }
734f4a2713aSLionel Sambuc
735f4a2713aSLionel Sambuc
736f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
737f4a2713aSLionel Sambuc // Preprocessor Directive Handling.
738f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
739f4a2713aSLionel Sambuc
740f4a2713aSLionel Sambuc class Preprocessor::ResetMacroExpansionHelper {
741f4a2713aSLionel Sambuc public:
ResetMacroExpansionHelper(Preprocessor * pp)742f4a2713aSLionel Sambuc ResetMacroExpansionHelper(Preprocessor *pp)
743f4a2713aSLionel Sambuc : PP(pp), save(pp->DisableMacroExpansion) {
744f4a2713aSLionel Sambuc if (pp->MacroExpansionInDirectivesOverride)
745f4a2713aSLionel Sambuc pp->DisableMacroExpansion = false;
746f4a2713aSLionel Sambuc }
~ResetMacroExpansionHelper()747f4a2713aSLionel Sambuc ~ResetMacroExpansionHelper() {
748f4a2713aSLionel Sambuc PP->DisableMacroExpansion = save;
749f4a2713aSLionel Sambuc }
750f4a2713aSLionel Sambuc private:
751f4a2713aSLionel Sambuc Preprocessor *PP;
752f4a2713aSLionel Sambuc bool save;
753f4a2713aSLionel Sambuc };
754f4a2713aSLionel Sambuc
755f4a2713aSLionel Sambuc /// HandleDirective - This callback is invoked when the lexer sees a # token
756f4a2713aSLionel Sambuc /// at the start of a line. This consumes the directive, modifies the
757f4a2713aSLionel Sambuc /// lexer/preprocessor state, and advances the lexer(s) so that the next token
758f4a2713aSLionel Sambuc /// read is the correct one.
HandleDirective(Token & Result)759f4a2713aSLionel Sambuc void Preprocessor::HandleDirective(Token &Result) {
760f4a2713aSLionel Sambuc // FIXME: Traditional: # with whitespace before it not recognized by K&R?
761f4a2713aSLionel Sambuc
762f4a2713aSLionel Sambuc // We just parsed a # character at the start of a line, so we're in directive
763f4a2713aSLionel Sambuc // mode. Tell the lexer this so any newlines we see will be converted into an
764f4a2713aSLionel Sambuc // EOD token (which terminates the directive).
765f4a2713aSLionel Sambuc CurPPLexer->ParsingPreprocessorDirective = true;
766f4a2713aSLionel Sambuc if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
767f4a2713aSLionel Sambuc
768f4a2713aSLionel Sambuc bool ImmediatelyAfterTopLevelIfndef =
769f4a2713aSLionel Sambuc CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
770f4a2713aSLionel Sambuc CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
771f4a2713aSLionel Sambuc
772f4a2713aSLionel Sambuc ++NumDirectives;
773f4a2713aSLionel Sambuc
774f4a2713aSLionel Sambuc // We are about to read a token. For the multiple-include optimization FA to
775f4a2713aSLionel Sambuc // work, we have to remember if we had read any tokens *before* this
776f4a2713aSLionel Sambuc // pp-directive.
777f4a2713aSLionel Sambuc bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
778f4a2713aSLionel Sambuc
779f4a2713aSLionel Sambuc // Save the '#' token in case we need to return it later.
780f4a2713aSLionel Sambuc Token SavedHash = Result;
781f4a2713aSLionel Sambuc
782f4a2713aSLionel Sambuc // Read the next token, the directive flavor. This isn't expanded due to
783f4a2713aSLionel Sambuc // C99 6.10.3p8.
784f4a2713aSLionel Sambuc LexUnexpandedToken(Result);
785f4a2713aSLionel Sambuc
786f4a2713aSLionel Sambuc // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
787f4a2713aSLionel Sambuc // #define A(x) #x
788f4a2713aSLionel Sambuc // A(abc
789f4a2713aSLionel Sambuc // #warning blah
790f4a2713aSLionel Sambuc // def)
791f4a2713aSLionel Sambuc // If so, the user is relying on undefined behavior, emit a diagnostic. Do
792f4a2713aSLionel Sambuc // not support this for #include-like directives, since that can result in
793f4a2713aSLionel Sambuc // terrible diagnostics, and does not work in GCC.
794f4a2713aSLionel Sambuc if (InMacroArgs) {
795f4a2713aSLionel Sambuc if (IdentifierInfo *II = Result.getIdentifierInfo()) {
796f4a2713aSLionel Sambuc switch (II->getPPKeywordID()) {
797f4a2713aSLionel Sambuc case tok::pp_include:
798f4a2713aSLionel Sambuc case tok::pp_import:
799f4a2713aSLionel Sambuc case tok::pp_include_next:
800f4a2713aSLionel Sambuc case tok::pp___include_macros:
801*0a6a1f1dSLionel Sambuc case tok::pp_pragma:
802*0a6a1f1dSLionel Sambuc Diag(Result, diag::err_embedded_directive) << II->getName();
803f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
804f4a2713aSLionel Sambuc return;
805f4a2713aSLionel Sambuc default:
806f4a2713aSLionel Sambuc break;
807f4a2713aSLionel Sambuc }
808f4a2713aSLionel Sambuc }
809f4a2713aSLionel Sambuc Diag(Result, diag::ext_embedded_directive);
810f4a2713aSLionel Sambuc }
811f4a2713aSLionel Sambuc
812f4a2713aSLionel Sambuc // Temporarily enable macro expansion if set so
813f4a2713aSLionel Sambuc // and reset to previous state when returning from this function.
814f4a2713aSLionel Sambuc ResetMacroExpansionHelper helper(this);
815f4a2713aSLionel Sambuc
816f4a2713aSLionel Sambuc switch (Result.getKind()) {
817f4a2713aSLionel Sambuc case tok::eod:
818f4a2713aSLionel Sambuc return; // null directive.
819f4a2713aSLionel Sambuc case tok::code_completion:
820f4a2713aSLionel Sambuc if (CodeComplete)
821f4a2713aSLionel Sambuc CodeComplete->CodeCompleteDirective(
822f4a2713aSLionel Sambuc CurPPLexer->getConditionalStackDepth() > 0);
823f4a2713aSLionel Sambuc setCodeCompletionReached();
824f4a2713aSLionel Sambuc return;
825f4a2713aSLionel Sambuc case tok::numeric_constant: // # 7 GNU line marker directive.
826f4a2713aSLionel Sambuc if (getLangOpts().AsmPreprocessor)
827f4a2713aSLionel Sambuc break; // # 4 is not a preprocessor directive in .S files.
828f4a2713aSLionel Sambuc return HandleDigitDirective(Result);
829f4a2713aSLionel Sambuc default:
830f4a2713aSLionel Sambuc IdentifierInfo *II = Result.getIdentifierInfo();
831*0a6a1f1dSLionel Sambuc if (!II) break; // Not an identifier.
832f4a2713aSLionel Sambuc
833f4a2713aSLionel Sambuc // Ask what the preprocessor keyword ID is.
834f4a2713aSLionel Sambuc switch (II->getPPKeywordID()) {
835f4a2713aSLionel Sambuc default: break;
836f4a2713aSLionel Sambuc // C99 6.10.1 - Conditional Inclusion.
837f4a2713aSLionel Sambuc case tok::pp_if:
838f4a2713aSLionel Sambuc return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
839f4a2713aSLionel Sambuc case tok::pp_ifdef:
840f4a2713aSLionel Sambuc return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
841f4a2713aSLionel Sambuc case tok::pp_ifndef:
842f4a2713aSLionel Sambuc return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
843f4a2713aSLionel Sambuc case tok::pp_elif:
844f4a2713aSLionel Sambuc return HandleElifDirective(Result);
845f4a2713aSLionel Sambuc case tok::pp_else:
846f4a2713aSLionel Sambuc return HandleElseDirective(Result);
847f4a2713aSLionel Sambuc case tok::pp_endif:
848f4a2713aSLionel Sambuc return HandleEndifDirective(Result);
849f4a2713aSLionel Sambuc
850f4a2713aSLionel Sambuc // C99 6.10.2 - Source File Inclusion.
851f4a2713aSLionel Sambuc case tok::pp_include:
852f4a2713aSLionel Sambuc // Handle #include.
853f4a2713aSLionel Sambuc return HandleIncludeDirective(SavedHash.getLocation(), Result);
854f4a2713aSLionel Sambuc case tok::pp___include_macros:
855f4a2713aSLionel Sambuc // Handle -imacros.
856f4a2713aSLionel Sambuc return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
857f4a2713aSLionel Sambuc
858f4a2713aSLionel Sambuc // C99 6.10.3 - Macro Replacement.
859f4a2713aSLionel Sambuc case tok::pp_define:
860f4a2713aSLionel Sambuc return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
861f4a2713aSLionel Sambuc case tok::pp_undef:
862f4a2713aSLionel Sambuc return HandleUndefDirective(Result);
863f4a2713aSLionel Sambuc
864f4a2713aSLionel Sambuc // C99 6.10.4 - Line Control.
865f4a2713aSLionel Sambuc case tok::pp_line:
866f4a2713aSLionel Sambuc return HandleLineDirective(Result);
867f4a2713aSLionel Sambuc
868f4a2713aSLionel Sambuc // C99 6.10.5 - Error Directive.
869f4a2713aSLionel Sambuc case tok::pp_error:
870f4a2713aSLionel Sambuc return HandleUserDiagnosticDirective(Result, false);
871f4a2713aSLionel Sambuc
872f4a2713aSLionel Sambuc // C99 6.10.6 - Pragma Directive.
873f4a2713aSLionel Sambuc case tok::pp_pragma:
874f4a2713aSLionel Sambuc return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
875f4a2713aSLionel Sambuc
876f4a2713aSLionel Sambuc // GNU Extensions.
877f4a2713aSLionel Sambuc case tok::pp_import:
878f4a2713aSLionel Sambuc return HandleImportDirective(SavedHash.getLocation(), Result);
879f4a2713aSLionel Sambuc case tok::pp_include_next:
880f4a2713aSLionel Sambuc return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
881f4a2713aSLionel Sambuc
882f4a2713aSLionel Sambuc case tok::pp_warning:
883f4a2713aSLionel Sambuc Diag(Result, diag::ext_pp_warning_directive);
884f4a2713aSLionel Sambuc return HandleUserDiagnosticDirective(Result, true);
885f4a2713aSLionel Sambuc case tok::pp_ident:
886f4a2713aSLionel Sambuc return HandleIdentSCCSDirective(Result);
887f4a2713aSLionel Sambuc case tok::pp_sccs:
888f4a2713aSLionel Sambuc return HandleIdentSCCSDirective(Result);
889f4a2713aSLionel Sambuc case tok::pp_assert:
890f4a2713aSLionel Sambuc //isExtension = true; // FIXME: implement #assert
891f4a2713aSLionel Sambuc break;
892f4a2713aSLionel Sambuc case tok::pp_unassert:
893f4a2713aSLionel Sambuc //isExtension = true; // FIXME: implement #unassert
894f4a2713aSLionel Sambuc break;
895f4a2713aSLionel Sambuc
896f4a2713aSLionel Sambuc case tok::pp___public_macro:
897f4a2713aSLionel Sambuc if (getLangOpts().Modules)
898f4a2713aSLionel Sambuc return HandleMacroPublicDirective(Result);
899f4a2713aSLionel Sambuc break;
900f4a2713aSLionel Sambuc
901f4a2713aSLionel Sambuc case tok::pp___private_macro:
902f4a2713aSLionel Sambuc if (getLangOpts().Modules)
903f4a2713aSLionel Sambuc return HandleMacroPrivateDirective(Result);
904f4a2713aSLionel Sambuc break;
905f4a2713aSLionel Sambuc }
906f4a2713aSLionel Sambuc break;
907f4a2713aSLionel Sambuc }
908f4a2713aSLionel Sambuc
909f4a2713aSLionel Sambuc // If this is a .S file, treat unknown # directives as non-preprocessor
910f4a2713aSLionel Sambuc // directives. This is important because # may be a comment or introduce
911f4a2713aSLionel Sambuc // various pseudo-ops. Just return the # token and push back the following
912f4a2713aSLionel Sambuc // token to be lexed next time.
913f4a2713aSLionel Sambuc if (getLangOpts().AsmPreprocessor) {
914f4a2713aSLionel Sambuc Token *Toks = new Token[2];
915f4a2713aSLionel Sambuc // Return the # and the token after it.
916f4a2713aSLionel Sambuc Toks[0] = SavedHash;
917f4a2713aSLionel Sambuc Toks[1] = Result;
918f4a2713aSLionel Sambuc
919f4a2713aSLionel Sambuc // If the second token is a hashhash token, then we need to translate it to
920f4a2713aSLionel Sambuc // unknown so the token lexer doesn't try to perform token pasting.
921f4a2713aSLionel Sambuc if (Result.is(tok::hashhash))
922f4a2713aSLionel Sambuc Toks[1].setKind(tok::unknown);
923f4a2713aSLionel Sambuc
924f4a2713aSLionel Sambuc // Enter this token stream so that we re-lex the tokens. Make sure to
925f4a2713aSLionel Sambuc // enable macro expansion, in case the token after the # is an identifier
926f4a2713aSLionel Sambuc // that is expanded.
927f4a2713aSLionel Sambuc EnterTokenStream(Toks, 2, false, true);
928f4a2713aSLionel Sambuc return;
929f4a2713aSLionel Sambuc }
930f4a2713aSLionel Sambuc
931f4a2713aSLionel Sambuc // If we reached here, the preprocessing token is not valid!
932f4a2713aSLionel Sambuc Diag(Result, diag::err_pp_invalid_directive);
933f4a2713aSLionel Sambuc
934f4a2713aSLionel Sambuc // Read the rest of the PP line.
935f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
936f4a2713aSLionel Sambuc
937f4a2713aSLionel Sambuc // Okay, we're done parsing the directive.
938f4a2713aSLionel Sambuc }
939f4a2713aSLionel Sambuc
940f4a2713aSLionel Sambuc /// GetLineValue - Convert a numeric token into an unsigned value, emitting
941f4a2713aSLionel Sambuc /// Diagnostic DiagID if it is invalid, and returning the value in Val.
GetLineValue(Token & DigitTok,unsigned & Val,unsigned DiagID,Preprocessor & PP,bool IsGNULineDirective=false)942f4a2713aSLionel Sambuc static bool GetLineValue(Token &DigitTok, unsigned &Val,
943f4a2713aSLionel Sambuc unsigned DiagID, Preprocessor &PP,
944f4a2713aSLionel Sambuc bool IsGNULineDirective=false) {
945f4a2713aSLionel Sambuc if (DigitTok.isNot(tok::numeric_constant)) {
946f4a2713aSLionel Sambuc PP.Diag(DigitTok, DiagID);
947f4a2713aSLionel Sambuc
948f4a2713aSLionel Sambuc if (DigitTok.isNot(tok::eod))
949f4a2713aSLionel Sambuc PP.DiscardUntilEndOfDirective();
950f4a2713aSLionel Sambuc return true;
951f4a2713aSLionel Sambuc }
952f4a2713aSLionel Sambuc
953f4a2713aSLionel Sambuc SmallString<64> IntegerBuffer;
954f4a2713aSLionel Sambuc IntegerBuffer.resize(DigitTok.getLength());
955f4a2713aSLionel Sambuc const char *DigitTokBegin = &IntegerBuffer[0];
956f4a2713aSLionel Sambuc bool Invalid = false;
957f4a2713aSLionel Sambuc unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
958f4a2713aSLionel Sambuc if (Invalid)
959f4a2713aSLionel Sambuc return true;
960f4a2713aSLionel Sambuc
961f4a2713aSLionel Sambuc // Verify that we have a simple digit-sequence, and compute the value. This
962f4a2713aSLionel Sambuc // is always a simple digit string computed in decimal, so we do this manually
963f4a2713aSLionel Sambuc // here.
964f4a2713aSLionel Sambuc Val = 0;
965f4a2713aSLionel Sambuc for (unsigned i = 0; i != ActualLength; ++i) {
966f4a2713aSLionel Sambuc // C++1y [lex.fcon]p1:
967f4a2713aSLionel Sambuc // Optional separating single quotes in a digit-sequence are ignored
968f4a2713aSLionel Sambuc if (DigitTokBegin[i] == '\'')
969f4a2713aSLionel Sambuc continue;
970f4a2713aSLionel Sambuc
971f4a2713aSLionel Sambuc if (!isDigit(DigitTokBegin[i])) {
972f4a2713aSLionel Sambuc PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
973f4a2713aSLionel Sambuc diag::err_pp_line_digit_sequence) << IsGNULineDirective;
974f4a2713aSLionel Sambuc PP.DiscardUntilEndOfDirective();
975f4a2713aSLionel Sambuc return true;
976f4a2713aSLionel Sambuc }
977f4a2713aSLionel Sambuc
978f4a2713aSLionel Sambuc unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
979f4a2713aSLionel Sambuc if (NextVal < Val) { // overflow.
980f4a2713aSLionel Sambuc PP.Diag(DigitTok, DiagID);
981f4a2713aSLionel Sambuc PP.DiscardUntilEndOfDirective();
982f4a2713aSLionel Sambuc return true;
983f4a2713aSLionel Sambuc }
984f4a2713aSLionel Sambuc Val = NextVal;
985f4a2713aSLionel Sambuc }
986f4a2713aSLionel Sambuc
987f4a2713aSLionel Sambuc if (DigitTokBegin[0] == '0' && Val)
988f4a2713aSLionel Sambuc PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
989f4a2713aSLionel Sambuc << IsGNULineDirective;
990f4a2713aSLionel Sambuc
991f4a2713aSLionel Sambuc return false;
992f4a2713aSLionel Sambuc }
993f4a2713aSLionel Sambuc
994f4a2713aSLionel Sambuc /// \brief Handle a \#line directive: C99 6.10.4.
995f4a2713aSLionel Sambuc ///
996f4a2713aSLionel Sambuc /// The two acceptable forms are:
997f4a2713aSLionel Sambuc /// \verbatim
998f4a2713aSLionel Sambuc /// # line digit-sequence
999f4a2713aSLionel Sambuc /// # line digit-sequence "s-char-sequence"
1000f4a2713aSLionel Sambuc /// \endverbatim
HandleLineDirective(Token & Tok)1001f4a2713aSLionel Sambuc void Preprocessor::HandleLineDirective(Token &Tok) {
1002f4a2713aSLionel Sambuc // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1003f4a2713aSLionel Sambuc // expanded.
1004f4a2713aSLionel Sambuc Token DigitTok;
1005f4a2713aSLionel Sambuc Lex(DigitTok);
1006f4a2713aSLionel Sambuc
1007f4a2713aSLionel Sambuc // Validate the number and convert it to an unsigned.
1008f4a2713aSLionel Sambuc unsigned LineNo;
1009f4a2713aSLionel Sambuc if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
1010f4a2713aSLionel Sambuc return;
1011f4a2713aSLionel Sambuc
1012f4a2713aSLionel Sambuc if (LineNo == 0)
1013f4a2713aSLionel Sambuc Diag(DigitTok, diag::ext_pp_line_zero);
1014f4a2713aSLionel Sambuc
1015f4a2713aSLionel Sambuc // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1016f4a2713aSLionel Sambuc // number greater than 2147483647". C90 requires that the line # be <= 32767.
1017f4a2713aSLionel Sambuc unsigned LineLimit = 32768U;
1018f4a2713aSLionel Sambuc if (LangOpts.C99 || LangOpts.CPlusPlus11)
1019f4a2713aSLionel Sambuc LineLimit = 2147483648U;
1020f4a2713aSLionel Sambuc if (LineNo >= LineLimit)
1021f4a2713aSLionel Sambuc Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
1022f4a2713aSLionel Sambuc else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
1023f4a2713aSLionel Sambuc Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
1024f4a2713aSLionel Sambuc
1025f4a2713aSLionel Sambuc int FilenameID = -1;
1026f4a2713aSLionel Sambuc Token StrTok;
1027f4a2713aSLionel Sambuc Lex(StrTok);
1028f4a2713aSLionel Sambuc
1029f4a2713aSLionel Sambuc // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1030f4a2713aSLionel Sambuc // string followed by eod.
1031f4a2713aSLionel Sambuc if (StrTok.is(tok::eod))
1032f4a2713aSLionel Sambuc ; // ok
1033f4a2713aSLionel Sambuc else if (StrTok.isNot(tok::string_literal)) {
1034f4a2713aSLionel Sambuc Diag(StrTok, diag::err_pp_line_invalid_filename);
1035f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1036f4a2713aSLionel Sambuc } else if (StrTok.hasUDSuffix()) {
1037f4a2713aSLionel Sambuc Diag(StrTok, diag::err_invalid_string_udl);
1038f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1039f4a2713aSLionel Sambuc } else {
1040f4a2713aSLionel Sambuc // Parse and validate the string, converting it into a unique ID.
1041*0a6a1f1dSLionel Sambuc StringLiteralParser Literal(StrTok, *this);
1042f4a2713aSLionel Sambuc assert(Literal.isAscii() && "Didn't allow wide strings in");
1043f4a2713aSLionel Sambuc if (Literal.hadError)
1044f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1045f4a2713aSLionel Sambuc if (Literal.Pascal) {
1046f4a2713aSLionel Sambuc Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1047f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1048f4a2713aSLionel Sambuc }
1049f4a2713aSLionel Sambuc FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1050f4a2713aSLionel Sambuc
1051f4a2713aSLionel Sambuc // Verify that there is nothing after the string, other than EOD. Because
1052f4a2713aSLionel Sambuc // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1053f4a2713aSLionel Sambuc CheckEndOfDirective("line", true);
1054f4a2713aSLionel Sambuc }
1055f4a2713aSLionel Sambuc
1056f4a2713aSLionel Sambuc SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
1057f4a2713aSLionel Sambuc
1058f4a2713aSLionel Sambuc if (Callbacks)
1059f4a2713aSLionel Sambuc Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1060f4a2713aSLionel Sambuc PPCallbacks::RenameFile,
1061f4a2713aSLionel Sambuc SrcMgr::C_User);
1062f4a2713aSLionel Sambuc }
1063f4a2713aSLionel Sambuc
1064f4a2713aSLionel Sambuc /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1065f4a2713aSLionel Sambuc /// marker directive.
ReadLineMarkerFlags(bool & IsFileEntry,bool & IsFileExit,bool & IsSystemHeader,bool & IsExternCHeader,Preprocessor & PP)1066f4a2713aSLionel Sambuc static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1067f4a2713aSLionel Sambuc bool &IsSystemHeader, bool &IsExternCHeader,
1068f4a2713aSLionel Sambuc Preprocessor &PP) {
1069f4a2713aSLionel Sambuc unsigned FlagVal;
1070f4a2713aSLionel Sambuc Token FlagTok;
1071f4a2713aSLionel Sambuc PP.Lex(FlagTok);
1072f4a2713aSLionel Sambuc if (FlagTok.is(tok::eod)) return false;
1073f4a2713aSLionel Sambuc if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1074f4a2713aSLionel Sambuc return true;
1075f4a2713aSLionel Sambuc
1076f4a2713aSLionel Sambuc if (FlagVal == 1) {
1077f4a2713aSLionel Sambuc IsFileEntry = true;
1078f4a2713aSLionel Sambuc
1079f4a2713aSLionel Sambuc PP.Lex(FlagTok);
1080f4a2713aSLionel Sambuc if (FlagTok.is(tok::eod)) return false;
1081f4a2713aSLionel Sambuc if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1082f4a2713aSLionel Sambuc return true;
1083f4a2713aSLionel Sambuc } else if (FlagVal == 2) {
1084f4a2713aSLionel Sambuc IsFileExit = true;
1085f4a2713aSLionel Sambuc
1086f4a2713aSLionel Sambuc SourceManager &SM = PP.getSourceManager();
1087f4a2713aSLionel Sambuc // If we are leaving the current presumed file, check to make sure the
1088f4a2713aSLionel Sambuc // presumed include stack isn't empty!
1089f4a2713aSLionel Sambuc FileID CurFileID =
1090f4a2713aSLionel Sambuc SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
1091f4a2713aSLionel Sambuc PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
1092f4a2713aSLionel Sambuc if (PLoc.isInvalid())
1093f4a2713aSLionel Sambuc return true;
1094f4a2713aSLionel Sambuc
1095f4a2713aSLionel Sambuc // If there is no include loc (main file) or if the include loc is in a
1096f4a2713aSLionel Sambuc // different physical file, then we aren't in a "1" line marker flag region.
1097f4a2713aSLionel Sambuc SourceLocation IncLoc = PLoc.getIncludeLoc();
1098f4a2713aSLionel Sambuc if (IncLoc.isInvalid() ||
1099f4a2713aSLionel Sambuc SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
1100f4a2713aSLionel Sambuc PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1101f4a2713aSLionel Sambuc PP.DiscardUntilEndOfDirective();
1102f4a2713aSLionel Sambuc return true;
1103f4a2713aSLionel Sambuc }
1104f4a2713aSLionel Sambuc
1105f4a2713aSLionel Sambuc PP.Lex(FlagTok);
1106f4a2713aSLionel Sambuc if (FlagTok.is(tok::eod)) return false;
1107f4a2713aSLionel Sambuc if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1108f4a2713aSLionel Sambuc return true;
1109f4a2713aSLionel Sambuc }
1110f4a2713aSLionel Sambuc
1111f4a2713aSLionel Sambuc // We must have 3 if there are still flags.
1112f4a2713aSLionel Sambuc if (FlagVal != 3) {
1113f4a2713aSLionel Sambuc PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1114f4a2713aSLionel Sambuc PP.DiscardUntilEndOfDirective();
1115f4a2713aSLionel Sambuc return true;
1116f4a2713aSLionel Sambuc }
1117f4a2713aSLionel Sambuc
1118f4a2713aSLionel Sambuc IsSystemHeader = true;
1119f4a2713aSLionel Sambuc
1120f4a2713aSLionel Sambuc PP.Lex(FlagTok);
1121f4a2713aSLionel Sambuc if (FlagTok.is(tok::eod)) return false;
1122f4a2713aSLionel Sambuc if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1123f4a2713aSLionel Sambuc return true;
1124f4a2713aSLionel Sambuc
1125f4a2713aSLionel Sambuc // We must have 4 if there is yet another flag.
1126f4a2713aSLionel Sambuc if (FlagVal != 4) {
1127f4a2713aSLionel Sambuc PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1128f4a2713aSLionel Sambuc PP.DiscardUntilEndOfDirective();
1129f4a2713aSLionel Sambuc return true;
1130f4a2713aSLionel Sambuc }
1131f4a2713aSLionel Sambuc
1132f4a2713aSLionel Sambuc IsExternCHeader = true;
1133f4a2713aSLionel Sambuc
1134f4a2713aSLionel Sambuc PP.Lex(FlagTok);
1135f4a2713aSLionel Sambuc if (FlagTok.is(tok::eod)) return false;
1136f4a2713aSLionel Sambuc
1137f4a2713aSLionel Sambuc // There are no more valid flags here.
1138f4a2713aSLionel Sambuc PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1139f4a2713aSLionel Sambuc PP.DiscardUntilEndOfDirective();
1140f4a2713aSLionel Sambuc return true;
1141f4a2713aSLionel Sambuc }
1142f4a2713aSLionel Sambuc
1143f4a2713aSLionel Sambuc /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1144f4a2713aSLionel Sambuc /// one of the following forms:
1145f4a2713aSLionel Sambuc ///
1146f4a2713aSLionel Sambuc /// # 42
1147f4a2713aSLionel Sambuc /// # 42 "file" ('1' | '2')?
1148f4a2713aSLionel Sambuc /// # 42 "file" ('1' | '2')? '3' '4'?
1149f4a2713aSLionel Sambuc ///
HandleDigitDirective(Token & DigitTok)1150f4a2713aSLionel Sambuc void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1151f4a2713aSLionel Sambuc // Validate the number and convert it to an unsigned. GNU does not have a
1152f4a2713aSLionel Sambuc // line # limit other than it fit in 32-bits.
1153f4a2713aSLionel Sambuc unsigned LineNo;
1154f4a2713aSLionel Sambuc if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
1155f4a2713aSLionel Sambuc *this, true))
1156f4a2713aSLionel Sambuc return;
1157f4a2713aSLionel Sambuc
1158f4a2713aSLionel Sambuc Token StrTok;
1159f4a2713aSLionel Sambuc Lex(StrTok);
1160f4a2713aSLionel Sambuc
1161f4a2713aSLionel Sambuc bool IsFileEntry = false, IsFileExit = false;
1162f4a2713aSLionel Sambuc bool IsSystemHeader = false, IsExternCHeader = false;
1163f4a2713aSLionel Sambuc int FilenameID = -1;
1164f4a2713aSLionel Sambuc
1165f4a2713aSLionel Sambuc // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1166f4a2713aSLionel Sambuc // string followed by eod.
1167f4a2713aSLionel Sambuc if (StrTok.is(tok::eod))
1168f4a2713aSLionel Sambuc ; // ok
1169f4a2713aSLionel Sambuc else if (StrTok.isNot(tok::string_literal)) {
1170f4a2713aSLionel Sambuc Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1171f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1172f4a2713aSLionel Sambuc } else if (StrTok.hasUDSuffix()) {
1173f4a2713aSLionel Sambuc Diag(StrTok, diag::err_invalid_string_udl);
1174f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1175f4a2713aSLionel Sambuc } else {
1176f4a2713aSLionel Sambuc // Parse and validate the string, converting it into a unique ID.
1177*0a6a1f1dSLionel Sambuc StringLiteralParser Literal(StrTok, *this);
1178f4a2713aSLionel Sambuc assert(Literal.isAscii() && "Didn't allow wide strings in");
1179f4a2713aSLionel Sambuc if (Literal.hadError)
1180f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1181f4a2713aSLionel Sambuc if (Literal.Pascal) {
1182f4a2713aSLionel Sambuc Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1183f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1184f4a2713aSLionel Sambuc }
1185f4a2713aSLionel Sambuc FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1186f4a2713aSLionel Sambuc
1187f4a2713aSLionel Sambuc // If a filename was present, read any flags that are present.
1188f4a2713aSLionel Sambuc if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
1189f4a2713aSLionel Sambuc IsSystemHeader, IsExternCHeader, *this))
1190f4a2713aSLionel Sambuc return;
1191f4a2713aSLionel Sambuc }
1192f4a2713aSLionel Sambuc
1193f4a2713aSLionel Sambuc // Create a line note with this information.
1194f4a2713aSLionel Sambuc SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
1195f4a2713aSLionel Sambuc IsFileEntry, IsFileExit,
1196f4a2713aSLionel Sambuc IsSystemHeader, IsExternCHeader);
1197f4a2713aSLionel Sambuc
1198f4a2713aSLionel Sambuc // If the preprocessor has callbacks installed, notify them of the #line
1199f4a2713aSLionel Sambuc // change. This is used so that the line marker comes out in -E mode for
1200f4a2713aSLionel Sambuc // example.
1201f4a2713aSLionel Sambuc if (Callbacks) {
1202f4a2713aSLionel Sambuc PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1203f4a2713aSLionel Sambuc if (IsFileEntry)
1204f4a2713aSLionel Sambuc Reason = PPCallbacks::EnterFile;
1205f4a2713aSLionel Sambuc else if (IsFileExit)
1206f4a2713aSLionel Sambuc Reason = PPCallbacks::ExitFile;
1207f4a2713aSLionel Sambuc SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1208f4a2713aSLionel Sambuc if (IsExternCHeader)
1209f4a2713aSLionel Sambuc FileKind = SrcMgr::C_ExternCSystem;
1210f4a2713aSLionel Sambuc else if (IsSystemHeader)
1211f4a2713aSLionel Sambuc FileKind = SrcMgr::C_System;
1212f4a2713aSLionel Sambuc
1213f4a2713aSLionel Sambuc Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
1214f4a2713aSLionel Sambuc }
1215f4a2713aSLionel Sambuc }
1216f4a2713aSLionel Sambuc
1217f4a2713aSLionel Sambuc
1218f4a2713aSLionel Sambuc /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1219f4a2713aSLionel Sambuc ///
HandleUserDiagnosticDirective(Token & Tok,bool isWarning)1220f4a2713aSLionel Sambuc void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
1221f4a2713aSLionel Sambuc bool isWarning) {
1222f4a2713aSLionel Sambuc // PTH doesn't emit #warning or #error directives.
1223f4a2713aSLionel Sambuc if (CurPTHLexer)
1224f4a2713aSLionel Sambuc return CurPTHLexer->DiscardToEndOfLine();
1225f4a2713aSLionel Sambuc
1226f4a2713aSLionel Sambuc // Read the rest of the line raw. We do this because we don't want macros
1227f4a2713aSLionel Sambuc // to be expanded and we don't require that the tokens be valid preprocessing
1228f4a2713aSLionel Sambuc // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1229f4a2713aSLionel Sambuc // collapse multiple consequtive white space between tokens, but this isn't
1230f4a2713aSLionel Sambuc // specified by the standard.
1231f4a2713aSLionel Sambuc SmallString<128> Message;
1232f4a2713aSLionel Sambuc CurLexer->ReadToEndOfLine(&Message);
1233f4a2713aSLionel Sambuc
1234f4a2713aSLionel Sambuc // Find the first non-whitespace character, so that we can make the
1235f4a2713aSLionel Sambuc // diagnostic more succinct.
1236f4a2713aSLionel Sambuc StringRef Msg = Message.str().ltrim(" ");
1237f4a2713aSLionel Sambuc
1238f4a2713aSLionel Sambuc if (isWarning)
1239f4a2713aSLionel Sambuc Diag(Tok, diag::pp_hash_warning) << Msg;
1240f4a2713aSLionel Sambuc else
1241f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_hash_error) << Msg;
1242f4a2713aSLionel Sambuc }
1243f4a2713aSLionel Sambuc
1244f4a2713aSLionel Sambuc /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1245f4a2713aSLionel Sambuc ///
HandleIdentSCCSDirective(Token & Tok)1246f4a2713aSLionel Sambuc void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1247f4a2713aSLionel Sambuc // Yes, this directive is an extension.
1248f4a2713aSLionel Sambuc Diag(Tok, diag::ext_pp_ident_directive);
1249f4a2713aSLionel Sambuc
1250f4a2713aSLionel Sambuc // Read the string argument.
1251f4a2713aSLionel Sambuc Token StrTok;
1252f4a2713aSLionel Sambuc Lex(StrTok);
1253f4a2713aSLionel Sambuc
1254f4a2713aSLionel Sambuc // If the token kind isn't a string, it's a malformed directive.
1255f4a2713aSLionel Sambuc if (StrTok.isNot(tok::string_literal) &&
1256f4a2713aSLionel Sambuc StrTok.isNot(tok::wide_string_literal)) {
1257f4a2713aSLionel Sambuc Diag(StrTok, diag::err_pp_malformed_ident);
1258f4a2713aSLionel Sambuc if (StrTok.isNot(tok::eod))
1259f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
1260f4a2713aSLionel Sambuc return;
1261f4a2713aSLionel Sambuc }
1262f4a2713aSLionel Sambuc
1263f4a2713aSLionel Sambuc if (StrTok.hasUDSuffix()) {
1264f4a2713aSLionel Sambuc Diag(StrTok, diag::err_invalid_string_udl);
1265f4a2713aSLionel Sambuc return DiscardUntilEndOfDirective();
1266f4a2713aSLionel Sambuc }
1267f4a2713aSLionel Sambuc
1268f4a2713aSLionel Sambuc // Verify that there is nothing after the string, other than EOD.
1269f4a2713aSLionel Sambuc CheckEndOfDirective("ident");
1270f4a2713aSLionel Sambuc
1271f4a2713aSLionel Sambuc if (Callbacks) {
1272f4a2713aSLionel Sambuc bool Invalid = false;
1273f4a2713aSLionel Sambuc std::string Str = getSpelling(StrTok, &Invalid);
1274f4a2713aSLionel Sambuc if (!Invalid)
1275f4a2713aSLionel Sambuc Callbacks->Ident(Tok.getLocation(), Str);
1276f4a2713aSLionel Sambuc }
1277f4a2713aSLionel Sambuc }
1278f4a2713aSLionel Sambuc
1279f4a2713aSLionel Sambuc /// \brief Handle a #public directive.
HandleMacroPublicDirective(Token & Tok)1280f4a2713aSLionel Sambuc void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
1281f4a2713aSLionel Sambuc Token MacroNameTok;
1282*0a6a1f1dSLionel Sambuc ReadMacroName(MacroNameTok, MU_Undef);
1283f4a2713aSLionel Sambuc
1284f4a2713aSLionel Sambuc // Error reading macro name? If so, diagnostic already issued.
1285f4a2713aSLionel Sambuc if (MacroNameTok.is(tok::eod))
1286f4a2713aSLionel Sambuc return;
1287f4a2713aSLionel Sambuc
1288f4a2713aSLionel Sambuc // Check to see if this is the last token on the #__public_macro line.
1289f4a2713aSLionel Sambuc CheckEndOfDirective("__public_macro");
1290f4a2713aSLionel Sambuc
1291f4a2713aSLionel Sambuc IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1292f4a2713aSLionel Sambuc // Okay, we finally have a valid identifier to undef.
1293f4a2713aSLionel Sambuc MacroDirective *MD = getMacroDirective(II);
1294f4a2713aSLionel Sambuc
1295f4a2713aSLionel Sambuc // If the macro is not defined, this is an error.
1296*0a6a1f1dSLionel Sambuc if (!MD) {
1297f4a2713aSLionel Sambuc Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1298f4a2713aSLionel Sambuc return;
1299f4a2713aSLionel Sambuc }
1300f4a2713aSLionel Sambuc
1301f4a2713aSLionel Sambuc // Note that this macro has now been exported.
1302f4a2713aSLionel Sambuc appendMacroDirective(II, AllocateVisibilityMacroDirective(
1303f4a2713aSLionel Sambuc MacroNameTok.getLocation(), /*IsPublic=*/true));
1304f4a2713aSLionel Sambuc }
1305f4a2713aSLionel Sambuc
1306f4a2713aSLionel Sambuc /// \brief Handle a #private directive.
HandleMacroPrivateDirective(Token & Tok)1307f4a2713aSLionel Sambuc void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1308f4a2713aSLionel Sambuc Token MacroNameTok;
1309*0a6a1f1dSLionel Sambuc ReadMacroName(MacroNameTok, MU_Undef);
1310f4a2713aSLionel Sambuc
1311f4a2713aSLionel Sambuc // Error reading macro name? If so, diagnostic already issued.
1312f4a2713aSLionel Sambuc if (MacroNameTok.is(tok::eod))
1313f4a2713aSLionel Sambuc return;
1314f4a2713aSLionel Sambuc
1315f4a2713aSLionel Sambuc // Check to see if this is the last token on the #__private_macro line.
1316f4a2713aSLionel Sambuc CheckEndOfDirective("__private_macro");
1317f4a2713aSLionel Sambuc
1318f4a2713aSLionel Sambuc IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1319f4a2713aSLionel Sambuc // Okay, we finally have a valid identifier to undef.
1320f4a2713aSLionel Sambuc MacroDirective *MD = getMacroDirective(II);
1321f4a2713aSLionel Sambuc
1322f4a2713aSLionel Sambuc // If the macro is not defined, this is an error.
1323*0a6a1f1dSLionel Sambuc if (!MD) {
1324f4a2713aSLionel Sambuc Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1325f4a2713aSLionel Sambuc return;
1326f4a2713aSLionel Sambuc }
1327f4a2713aSLionel Sambuc
1328f4a2713aSLionel Sambuc // Note that this macro has now been marked private.
1329f4a2713aSLionel Sambuc appendMacroDirective(II, AllocateVisibilityMacroDirective(
1330f4a2713aSLionel Sambuc MacroNameTok.getLocation(), /*IsPublic=*/false));
1331f4a2713aSLionel Sambuc }
1332f4a2713aSLionel Sambuc
1333f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1334f4a2713aSLionel Sambuc // Preprocessor Include Directive Handling.
1335f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1336f4a2713aSLionel Sambuc
1337f4a2713aSLionel Sambuc /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1338f4a2713aSLionel Sambuc /// checked and spelled filename, e.g. as an operand of \#include. This returns
1339f4a2713aSLionel Sambuc /// true if the input filename was in <>'s or false if it were in ""'s. The
1340f4a2713aSLionel Sambuc /// caller is expected to provide a buffer that is large enough to hold the
1341f4a2713aSLionel Sambuc /// spelling of the filename, but is also expected to handle the case when
1342f4a2713aSLionel Sambuc /// this method decides to use a different buffer.
GetIncludeFilenameSpelling(SourceLocation Loc,StringRef & Buffer)1343f4a2713aSLionel Sambuc bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1344f4a2713aSLionel Sambuc StringRef &Buffer) {
1345f4a2713aSLionel Sambuc // Get the text form of the filename.
1346f4a2713aSLionel Sambuc assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1347f4a2713aSLionel Sambuc
1348f4a2713aSLionel Sambuc // Make sure the filename is <x> or "x".
1349f4a2713aSLionel Sambuc bool isAngled;
1350f4a2713aSLionel Sambuc if (Buffer[0] == '<') {
1351f4a2713aSLionel Sambuc if (Buffer.back() != '>') {
1352f4a2713aSLionel Sambuc Diag(Loc, diag::err_pp_expects_filename);
1353f4a2713aSLionel Sambuc Buffer = StringRef();
1354f4a2713aSLionel Sambuc return true;
1355f4a2713aSLionel Sambuc }
1356f4a2713aSLionel Sambuc isAngled = true;
1357f4a2713aSLionel Sambuc } else if (Buffer[0] == '"') {
1358f4a2713aSLionel Sambuc if (Buffer.back() != '"') {
1359f4a2713aSLionel Sambuc Diag(Loc, diag::err_pp_expects_filename);
1360f4a2713aSLionel Sambuc Buffer = StringRef();
1361f4a2713aSLionel Sambuc return true;
1362f4a2713aSLionel Sambuc }
1363f4a2713aSLionel Sambuc isAngled = false;
1364f4a2713aSLionel Sambuc } else {
1365f4a2713aSLionel Sambuc Diag(Loc, diag::err_pp_expects_filename);
1366f4a2713aSLionel Sambuc Buffer = StringRef();
1367f4a2713aSLionel Sambuc return true;
1368f4a2713aSLionel Sambuc }
1369f4a2713aSLionel Sambuc
1370f4a2713aSLionel Sambuc // Diagnose #include "" as invalid.
1371f4a2713aSLionel Sambuc if (Buffer.size() <= 2) {
1372f4a2713aSLionel Sambuc Diag(Loc, diag::err_pp_empty_filename);
1373f4a2713aSLionel Sambuc Buffer = StringRef();
1374f4a2713aSLionel Sambuc return true;
1375f4a2713aSLionel Sambuc }
1376f4a2713aSLionel Sambuc
1377f4a2713aSLionel Sambuc // Skip the brackets.
1378f4a2713aSLionel Sambuc Buffer = Buffer.substr(1, Buffer.size()-2);
1379f4a2713aSLionel Sambuc return isAngled;
1380f4a2713aSLionel Sambuc }
1381f4a2713aSLionel Sambuc
1382*0a6a1f1dSLionel Sambuc // \brief Handle cases where the \#include name is expanded from a macro
1383*0a6a1f1dSLionel Sambuc // as multiple tokens, which need to be glued together.
1384*0a6a1f1dSLionel Sambuc //
1385*0a6a1f1dSLionel Sambuc // This occurs for code like:
1386*0a6a1f1dSLionel Sambuc // \code
1387*0a6a1f1dSLionel Sambuc // \#define FOO <a/b.h>
1388*0a6a1f1dSLionel Sambuc // \#include FOO
1389*0a6a1f1dSLionel Sambuc // \endcode
1390*0a6a1f1dSLionel Sambuc // because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1391*0a6a1f1dSLionel Sambuc //
1392*0a6a1f1dSLionel Sambuc // This code concatenates and consumes tokens up to the '>' token. It returns
1393*0a6a1f1dSLionel Sambuc // false if the > was found, otherwise it returns true if it finds and consumes
1394*0a6a1f1dSLionel Sambuc // the EOD marker.
ConcatenateIncludeName(SmallString<128> & FilenameBuffer,SourceLocation & End)1395*0a6a1f1dSLionel Sambuc bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
1396f4a2713aSLionel Sambuc SourceLocation &End) {
1397f4a2713aSLionel Sambuc Token CurTok;
1398f4a2713aSLionel Sambuc
1399f4a2713aSLionel Sambuc Lex(CurTok);
1400f4a2713aSLionel Sambuc while (CurTok.isNot(tok::eod)) {
1401f4a2713aSLionel Sambuc End = CurTok.getLocation();
1402f4a2713aSLionel Sambuc
1403f4a2713aSLionel Sambuc // FIXME: Provide code completion for #includes.
1404f4a2713aSLionel Sambuc if (CurTok.is(tok::code_completion)) {
1405f4a2713aSLionel Sambuc setCodeCompletionReached();
1406f4a2713aSLionel Sambuc Lex(CurTok);
1407f4a2713aSLionel Sambuc continue;
1408f4a2713aSLionel Sambuc }
1409f4a2713aSLionel Sambuc
1410f4a2713aSLionel Sambuc // Append the spelling of this token to the buffer. If there was a space
1411f4a2713aSLionel Sambuc // before it, add it now.
1412f4a2713aSLionel Sambuc if (CurTok.hasLeadingSpace())
1413f4a2713aSLionel Sambuc FilenameBuffer.push_back(' ');
1414f4a2713aSLionel Sambuc
1415f4a2713aSLionel Sambuc // Get the spelling of the token, directly into FilenameBuffer if possible.
1416f4a2713aSLionel Sambuc unsigned PreAppendSize = FilenameBuffer.size();
1417f4a2713aSLionel Sambuc FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1418f4a2713aSLionel Sambuc
1419f4a2713aSLionel Sambuc const char *BufPtr = &FilenameBuffer[PreAppendSize];
1420f4a2713aSLionel Sambuc unsigned ActualLen = getSpelling(CurTok, BufPtr);
1421f4a2713aSLionel Sambuc
1422f4a2713aSLionel Sambuc // If the token was spelled somewhere else, copy it into FilenameBuffer.
1423f4a2713aSLionel Sambuc if (BufPtr != &FilenameBuffer[PreAppendSize])
1424f4a2713aSLionel Sambuc memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1425f4a2713aSLionel Sambuc
1426f4a2713aSLionel Sambuc // Resize FilenameBuffer to the correct size.
1427f4a2713aSLionel Sambuc if (CurTok.getLength() != ActualLen)
1428f4a2713aSLionel Sambuc FilenameBuffer.resize(PreAppendSize+ActualLen);
1429f4a2713aSLionel Sambuc
1430f4a2713aSLionel Sambuc // If we found the '>' marker, return success.
1431f4a2713aSLionel Sambuc if (CurTok.is(tok::greater))
1432f4a2713aSLionel Sambuc return false;
1433f4a2713aSLionel Sambuc
1434f4a2713aSLionel Sambuc Lex(CurTok);
1435f4a2713aSLionel Sambuc }
1436f4a2713aSLionel Sambuc
1437f4a2713aSLionel Sambuc // If we hit the eod marker, emit an error and return true so that the caller
1438f4a2713aSLionel Sambuc // knows the EOD has been read.
1439f4a2713aSLionel Sambuc Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1440f4a2713aSLionel Sambuc return true;
1441f4a2713aSLionel Sambuc }
1442f4a2713aSLionel Sambuc
1443*0a6a1f1dSLionel Sambuc /// \brief Push a token onto the token stream containing an annotation.
EnterAnnotationToken(Preprocessor & PP,SourceLocation Begin,SourceLocation End,tok::TokenKind Kind,void * AnnotationVal)1444*0a6a1f1dSLionel Sambuc static void EnterAnnotationToken(Preprocessor &PP,
1445*0a6a1f1dSLionel Sambuc SourceLocation Begin, SourceLocation End,
1446*0a6a1f1dSLionel Sambuc tok::TokenKind Kind, void *AnnotationVal) {
1447*0a6a1f1dSLionel Sambuc Token *Tok = new Token[1];
1448*0a6a1f1dSLionel Sambuc Tok[0].startToken();
1449*0a6a1f1dSLionel Sambuc Tok[0].setKind(Kind);
1450*0a6a1f1dSLionel Sambuc Tok[0].setLocation(Begin);
1451*0a6a1f1dSLionel Sambuc Tok[0].setAnnotationEndLoc(End);
1452*0a6a1f1dSLionel Sambuc Tok[0].setAnnotationValue(AnnotationVal);
1453*0a6a1f1dSLionel Sambuc PP.EnterTokenStream(Tok, 1, true, true);
1454*0a6a1f1dSLionel Sambuc }
1455*0a6a1f1dSLionel Sambuc
1456f4a2713aSLionel Sambuc /// HandleIncludeDirective - The "\#include" tokens have just been read, read
1457f4a2713aSLionel Sambuc /// the file to be included from the lexer, then include it! This is a common
1458f4a2713aSLionel Sambuc /// routine with functionality shared between \#include, \#include_next and
1459f4a2713aSLionel Sambuc /// \#import. LookupFrom is set when this is a \#include_next directive, it
1460f4a2713aSLionel Sambuc /// specifies the file to start searching from.
HandleIncludeDirective(SourceLocation HashLoc,Token & IncludeTok,const DirectoryLookup * LookupFrom,const FileEntry * LookupFromFile,bool isImport)1461f4a2713aSLionel Sambuc void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1462f4a2713aSLionel Sambuc Token &IncludeTok,
1463f4a2713aSLionel Sambuc const DirectoryLookup *LookupFrom,
1464*0a6a1f1dSLionel Sambuc const FileEntry *LookupFromFile,
1465f4a2713aSLionel Sambuc bool isImport) {
1466f4a2713aSLionel Sambuc
1467f4a2713aSLionel Sambuc Token FilenameTok;
1468f4a2713aSLionel Sambuc CurPPLexer->LexIncludeFilename(FilenameTok);
1469f4a2713aSLionel Sambuc
1470f4a2713aSLionel Sambuc // Reserve a buffer to get the spelling.
1471f4a2713aSLionel Sambuc SmallString<128> FilenameBuffer;
1472f4a2713aSLionel Sambuc StringRef Filename;
1473f4a2713aSLionel Sambuc SourceLocation End;
1474f4a2713aSLionel Sambuc SourceLocation CharEnd; // the end of this directive, in characters
1475f4a2713aSLionel Sambuc
1476f4a2713aSLionel Sambuc switch (FilenameTok.getKind()) {
1477f4a2713aSLionel Sambuc case tok::eod:
1478f4a2713aSLionel Sambuc // If the token kind is EOD, the error has already been diagnosed.
1479f4a2713aSLionel Sambuc return;
1480f4a2713aSLionel Sambuc
1481f4a2713aSLionel Sambuc case tok::angle_string_literal:
1482f4a2713aSLionel Sambuc case tok::string_literal:
1483f4a2713aSLionel Sambuc Filename = getSpelling(FilenameTok, FilenameBuffer);
1484f4a2713aSLionel Sambuc End = FilenameTok.getLocation();
1485f4a2713aSLionel Sambuc CharEnd = End.getLocWithOffset(FilenameTok.getLength());
1486f4a2713aSLionel Sambuc break;
1487f4a2713aSLionel Sambuc
1488f4a2713aSLionel Sambuc case tok::less:
1489f4a2713aSLionel Sambuc // This could be a <foo/bar.h> file coming from a macro expansion. In this
1490f4a2713aSLionel Sambuc // case, glue the tokens together into FilenameBuffer and interpret those.
1491f4a2713aSLionel Sambuc FilenameBuffer.push_back('<');
1492f4a2713aSLionel Sambuc if (ConcatenateIncludeName(FilenameBuffer, End))
1493f4a2713aSLionel Sambuc return; // Found <eod> but no ">"? Diagnostic already emitted.
1494f4a2713aSLionel Sambuc Filename = FilenameBuffer.str();
1495f4a2713aSLionel Sambuc CharEnd = End.getLocWithOffset(1);
1496f4a2713aSLionel Sambuc break;
1497f4a2713aSLionel Sambuc default:
1498f4a2713aSLionel Sambuc Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1499f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
1500f4a2713aSLionel Sambuc return;
1501f4a2713aSLionel Sambuc }
1502f4a2713aSLionel Sambuc
1503f4a2713aSLionel Sambuc CharSourceRange FilenameRange
1504f4a2713aSLionel Sambuc = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
1505f4a2713aSLionel Sambuc StringRef OriginalFilename = Filename;
1506f4a2713aSLionel Sambuc bool isAngled =
1507f4a2713aSLionel Sambuc GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1508f4a2713aSLionel Sambuc // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1509f4a2713aSLionel Sambuc // error.
1510f4a2713aSLionel Sambuc if (Filename.empty()) {
1511f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
1512f4a2713aSLionel Sambuc return;
1513f4a2713aSLionel Sambuc }
1514f4a2713aSLionel Sambuc
1515f4a2713aSLionel Sambuc // Verify that there is nothing after the filename, other than EOD. Note that
1516f4a2713aSLionel Sambuc // we allow macros that expand to nothing after the filename, because this
1517f4a2713aSLionel Sambuc // falls into the category of "#include pp-tokens new-line" specified in
1518f4a2713aSLionel Sambuc // C99 6.10.2p4.
1519f4a2713aSLionel Sambuc CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1520f4a2713aSLionel Sambuc
1521f4a2713aSLionel Sambuc // Check that we don't have infinite #include recursion.
1522f4a2713aSLionel Sambuc if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1523f4a2713aSLionel Sambuc Diag(FilenameTok, diag::err_pp_include_too_deep);
1524f4a2713aSLionel Sambuc return;
1525f4a2713aSLionel Sambuc }
1526f4a2713aSLionel Sambuc
1527f4a2713aSLionel Sambuc // Complain about attempts to #include files in an audit pragma.
1528f4a2713aSLionel Sambuc if (PragmaARCCFCodeAuditedLoc.isValid()) {
1529f4a2713aSLionel Sambuc Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1530f4a2713aSLionel Sambuc Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1531f4a2713aSLionel Sambuc
1532f4a2713aSLionel Sambuc // Immediately leave the pragma.
1533f4a2713aSLionel Sambuc PragmaARCCFCodeAuditedLoc = SourceLocation();
1534f4a2713aSLionel Sambuc }
1535f4a2713aSLionel Sambuc
1536f4a2713aSLionel Sambuc if (HeaderInfo.HasIncludeAliasMap()) {
1537f4a2713aSLionel Sambuc // Map the filename with the brackets still attached. If the name doesn't
1538f4a2713aSLionel Sambuc // map to anything, fall back on the filename we've already gotten the
1539f4a2713aSLionel Sambuc // spelling for.
1540f4a2713aSLionel Sambuc StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1541f4a2713aSLionel Sambuc if (!NewName.empty())
1542f4a2713aSLionel Sambuc Filename = NewName;
1543f4a2713aSLionel Sambuc }
1544f4a2713aSLionel Sambuc
1545f4a2713aSLionel Sambuc // Search include directories.
1546f4a2713aSLionel Sambuc const DirectoryLookup *CurDir;
1547f4a2713aSLionel Sambuc SmallString<1024> SearchPath;
1548f4a2713aSLionel Sambuc SmallString<1024> RelativePath;
1549f4a2713aSLionel Sambuc // We get the raw path only if we have 'Callbacks' to which we later pass
1550f4a2713aSLionel Sambuc // the path.
1551f4a2713aSLionel Sambuc ModuleMap::KnownHeader SuggestedModule;
1552f4a2713aSLionel Sambuc SourceLocation FilenameLoc = FilenameTok.getLocation();
1553*0a6a1f1dSLionel Sambuc SmallString<128> NormalizedPath;
1554*0a6a1f1dSLionel Sambuc if (LangOpts.MSVCCompat) {
1555*0a6a1f1dSLionel Sambuc NormalizedPath = Filename.str();
1556*0a6a1f1dSLionel Sambuc #ifndef LLVM_ON_WIN32
1557*0a6a1f1dSLionel Sambuc llvm::sys::path::native(NormalizedPath);
1558*0a6a1f1dSLionel Sambuc #endif
1559*0a6a1f1dSLionel Sambuc }
1560f4a2713aSLionel Sambuc const FileEntry *File = LookupFile(
1561*0a6a1f1dSLionel Sambuc FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
1562*0a6a1f1dSLionel Sambuc isAngled, LookupFrom, LookupFromFile, CurDir,
1563*0a6a1f1dSLionel Sambuc Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1564*0a6a1f1dSLionel Sambuc HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : nullptr);
1565f4a2713aSLionel Sambuc
1566f4a2713aSLionel Sambuc if (Callbacks) {
1567f4a2713aSLionel Sambuc if (!File) {
1568f4a2713aSLionel Sambuc // Give the clients a chance to recover.
1569f4a2713aSLionel Sambuc SmallString<128> RecoveryPath;
1570f4a2713aSLionel Sambuc if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1571f4a2713aSLionel Sambuc if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1572f4a2713aSLionel Sambuc // Add the recovery path to the list of search paths.
1573f4a2713aSLionel Sambuc DirectoryLookup DL(DE, SrcMgr::C_User, false);
1574f4a2713aSLionel Sambuc HeaderInfo.AddSearchPath(DL, isAngled);
1575f4a2713aSLionel Sambuc
1576f4a2713aSLionel Sambuc // Try the lookup again, skipping the cache.
1577*0a6a1f1dSLionel Sambuc File = LookupFile(
1578*0a6a1f1dSLionel Sambuc FilenameLoc,
1579*0a6a1f1dSLionel Sambuc LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1580*0a6a1f1dSLionel Sambuc LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
1581*0a6a1f1dSLionel Sambuc HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1582*0a6a1f1dSLionel Sambuc : nullptr,
1583f4a2713aSLionel Sambuc /*SkipCache*/ true);
1584f4a2713aSLionel Sambuc }
1585f4a2713aSLionel Sambuc }
1586f4a2713aSLionel Sambuc }
1587f4a2713aSLionel Sambuc
1588f4a2713aSLionel Sambuc if (!SuggestedModule || !getLangOpts().Modules) {
1589f4a2713aSLionel Sambuc // Notify the callback object that we've seen an inclusion directive.
1590*0a6a1f1dSLionel Sambuc Callbacks->InclusionDirective(HashLoc, IncludeTok,
1591*0a6a1f1dSLionel Sambuc LangOpts.MSVCCompat ? NormalizedPath.c_str()
1592*0a6a1f1dSLionel Sambuc : Filename,
1593*0a6a1f1dSLionel Sambuc isAngled, FilenameRange, File, SearchPath,
1594*0a6a1f1dSLionel Sambuc RelativePath, /*ImportedModule=*/nullptr);
1595f4a2713aSLionel Sambuc }
1596f4a2713aSLionel Sambuc }
1597f4a2713aSLionel Sambuc
1598*0a6a1f1dSLionel Sambuc if (!File) {
1599f4a2713aSLionel Sambuc if (!SuppressIncludeNotFoundError) {
1600f4a2713aSLionel Sambuc // If the file could not be located and it was included via angle
1601f4a2713aSLionel Sambuc // brackets, we can attempt a lookup as though it were a quoted path to
1602f4a2713aSLionel Sambuc // provide the user with a possible fixit.
1603f4a2713aSLionel Sambuc if (isAngled) {
1604f4a2713aSLionel Sambuc File = LookupFile(
1605*0a6a1f1dSLionel Sambuc FilenameLoc,
1606*0a6a1f1dSLionel Sambuc LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1607*0a6a1f1dSLionel Sambuc LookupFrom, LookupFromFile, CurDir,
1608*0a6a1f1dSLionel Sambuc Callbacks ? &SearchPath : nullptr,
1609*0a6a1f1dSLionel Sambuc Callbacks ? &RelativePath : nullptr,
1610*0a6a1f1dSLionel Sambuc HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1611*0a6a1f1dSLionel Sambuc : nullptr);
1612f4a2713aSLionel Sambuc if (File) {
1613f4a2713aSLionel Sambuc SourceRange Range(FilenameTok.getLocation(), CharEnd);
1614f4a2713aSLionel Sambuc Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1615f4a2713aSLionel Sambuc Filename <<
1616f4a2713aSLionel Sambuc FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1617f4a2713aSLionel Sambuc }
1618f4a2713aSLionel Sambuc }
1619f4a2713aSLionel Sambuc // If the file is still not found, just go with the vanilla diagnostic
1620f4a2713aSLionel Sambuc if (!File)
1621f4a2713aSLionel Sambuc Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1622f4a2713aSLionel Sambuc }
1623f4a2713aSLionel Sambuc if (!File)
1624f4a2713aSLionel Sambuc return;
1625f4a2713aSLionel Sambuc }
1626f4a2713aSLionel Sambuc
1627f4a2713aSLionel Sambuc // If we are supposed to import a module rather than including the header,
1628f4a2713aSLionel Sambuc // do so now.
1629*0a6a1f1dSLionel Sambuc if (SuggestedModule && getLangOpts().Modules &&
1630*0a6a1f1dSLionel Sambuc SuggestedModule.getModule()->getTopLevelModuleName() !=
1631*0a6a1f1dSLionel Sambuc getLangOpts().ImplementationOfModule) {
1632f4a2713aSLionel Sambuc // Compute the module access path corresponding to this module.
1633f4a2713aSLionel Sambuc // FIXME: Should we have a second loadModule() overload to avoid this
1634f4a2713aSLionel Sambuc // extra lookup step?
1635f4a2713aSLionel Sambuc SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1636f4a2713aSLionel Sambuc for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
1637f4a2713aSLionel Sambuc Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1638f4a2713aSLionel Sambuc FilenameTok.getLocation()));
1639f4a2713aSLionel Sambuc std::reverse(Path.begin(), Path.end());
1640f4a2713aSLionel Sambuc
1641f4a2713aSLionel Sambuc // Warn that we're replacing the include/import with a module import.
1642f4a2713aSLionel Sambuc SmallString<128> PathString;
1643f4a2713aSLionel Sambuc for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1644f4a2713aSLionel Sambuc if (I)
1645f4a2713aSLionel Sambuc PathString += '.';
1646f4a2713aSLionel Sambuc PathString += Path[I].first->getName();
1647f4a2713aSLionel Sambuc }
1648f4a2713aSLionel Sambuc int IncludeKind = 0;
1649f4a2713aSLionel Sambuc
1650f4a2713aSLionel Sambuc switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1651f4a2713aSLionel Sambuc case tok::pp_include:
1652f4a2713aSLionel Sambuc IncludeKind = 0;
1653f4a2713aSLionel Sambuc break;
1654f4a2713aSLionel Sambuc
1655f4a2713aSLionel Sambuc case tok::pp_import:
1656f4a2713aSLionel Sambuc IncludeKind = 1;
1657f4a2713aSLionel Sambuc break;
1658f4a2713aSLionel Sambuc
1659f4a2713aSLionel Sambuc case tok::pp_include_next:
1660f4a2713aSLionel Sambuc IncludeKind = 2;
1661f4a2713aSLionel Sambuc break;
1662f4a2713aSLionel Sambuc
1663f4a2713aSLionel Sambuc case tok::pp___include_macros:
1664f4a2713aSLionel Sambuc IncludeKind = 3;
1665f4a2713aSLionel Sambuc break;
1666f4a2713aSLionel Sambuc
1667f4a2713aSLionel Sambuc default:
1668f4a2713aSLionel Sambuc llvm_unreachable("unknown include directive kind");
1669f4a2713aSLionel Sambuc }
1670f4a2713aSLionel Sambuc
1671f4a2713aSLionel Sambuc // Determine whether we are actually building the module that this
1672f4a2713aSLionel Sambuc // include directive maps to.
1673f4a2713aSLionel Sambuc bool BuildingImportedModule
1674f4a2713aSLionel Sambuc = Path[0].first->getName() == getLangOpts().CurrentModule;
1675f4a2713aSLionel Sambuc
1676f4a2713aSLionel Sambuc if (!BuildingImportedModule && getLangOpts().ObjC2) {
1677f4a2713aSLionel Sambuc // If we're not building the imported module, warn that we're going
1678f4a2713aSLionel Sambuc // to automatically turn this inclusion directive into a module import.
1679f4a2713aSLionel Sambuc // We only do this in Objective-C, where we have a module-import syntax.
1680f4a2713aSLionel Sambuc CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1681f4a2713aSLionel Sambuc /*IsTokenRange=*/false);
1682f4a2713aSLionel Sambuc Diag(HashLoc, diag::warn_auto_module_import)
1683f4a2713aSLionel Sambuc << IncludeKind << PathString
1684f4a2713aSLionel Sambuc << FixItHint::CreateReplacement(ReplaceRange,
1685f4a2713aSLionel Sambuc "@import " + PathString.str().str() + ";");
1686f4a2713aSLionel Sambuc }
1687f4a2713aSLionel Sambuc
1688f4a2713aSLionel Sambuc // Load the module. Only make macros visible. We'll make the declarations
1689f4a2713aSLionel Sambuc // visible when the parser gets here.
1690f4a2713aSLionel Sambuc Module::NameVisibilityKind Visibility = Module::MacrosVisible;
1691f4a2713aSLionel Sambuc ModuleLoadResult Imported
1692f4a2713aSLionel Sambuc = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1693f4a2713aSLionel Sambuc /*IsIncludeDirective=*/true);
1694*0a6a1f1dSLionel Sambuc assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
1695f4a2713aSLionel Sambuc "the imported module is different than the suggested one");
1696f4a2713aSLionel Sambuc
1697f4a2713aSLionel Sambuc if (!Imported && hadModuleLoaderFatalFailure()) {
1698f4a2713aSLionel Sambuc // With a fatal failure in the module loader, we abort parsing.
1699f4a2713aSLionel Sambuc Token &Result = IncludeTok;
1700f4a2713aSLionel Sambuc if (CurLexer) {
1701f4a2713aSLionel Sambuc Result.startToken();
1702f4a2713aSLionel Sambuc CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1703f4a2713aSLionel Sambuc CurLexer->cutOffLexing();
1704f4a2713aSLionel Sambuc } else {
1705f4a2713aSLionel Sambuc assert(CurPTHLexer && "#include but no current lexer set!");
1706f4a2713aSLionel Sambuc CurPTHLexer->getEOF(Result);
1707f4a2713aSLionel Sambuc }
1708f4a2713aSLionel Sambuc return;
1709f4a2713aSLionel Sambuc }
1710f4a2713aSLionel Sambuc
1711f4a2713aSLionel Sambuc // If this header isn't part of the module we're building, we're done.
1712f4a2713aSLionel Sambuc if (!BuildingImportedModule && Imported) {
1713f4a2713aSLionel Sambuc if (Callbacks) {
1714f4a2713aSLionel Sambuc Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1715f4a2713aSLionel Sambuc FilenameRange, File,
1716f4a2713aSLionel Sambuc SearchPath, RelativePath, Imported);
1717f4a2713aSLionel Sambuc }
1718f4a2713aSLionel Sambuc
1719f4a2713aSLionel Sambuc if (IncludeKind != 3) {
1720f4a2713aSLionel Sambuc // Let the parser know that we hit a module import, and it should
1721f4a2713aSLionel Sambuc // make the module visible.
1722f4a2713aSLionel Sambuc // FIXME: Produce this as the current token directly, rather than
1723f4a2713aSLionel Sambuc // allocating a new token for it.
1724*0a6a1f1dSLionel Sambuc EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include,
1725*0a6a1f1dSLionel Sambuc Imported);
1726f4a2713aSLionel Sambuc }
1727f4a2713aSLionel Sambuc return;
1728f4a2713aSLionel Sambuc }
1729f4a2713aSLionel Sambuc
1730f4a2713aSLionel Sambuc // If we failed to find a submodule that we expected to find, we can
1731f4a2713aSLionel Sambuc // continue. Otherwise, there's an error in the included file, so we
1732f4a2713aSLionel Sambuc // don't want to include it.
1733f4a2713aSLionel Sambuc if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1734f4a2713aSLionel Sambuc return;
1735f4a2713aSLionel Sambuc }
1736f4a2713aSLionel Sambuc }
1737f4a2713aSLionel Sambuc
1738f4a2713aSLionel Sambuc if (Callbacks && SuggestedModule) {
1739f4a2713aSLionel Sambuc // We didn't notify the callback object that we've seen an inclusion
1740f4a2713aSLionel Sambuc // directive before. Now that we are parsing the include normally and not
1741f4a2713aSLionel Sambuc // turning it to a module import, notify the callback object.
1742f4a2713aSLionel Sambuc Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1743f4a2713aSLionel Sambuc FilenameRange, File,
1744f4a2713aSLionel Sambuc SearchPath, RelativePath,
1745*0a6a1f1dSLionel Sambuc /*ImportedModule=*/nullptr);
1746f4a2713aSLionel Sambuc }
1747f4a2713aSLionel Sambuc
1748f4a2713aSLionel Sambuc // The #included file will be considered to be a system header if either it is
1749f4a2713aSLionel Sambuc // in a system include directory, or if the #includer is a system include
1750f4a2713aSLionel Sambuc // header.
1751f4a2713aSLionel Sambuc SrcMgr::CharacteristicKind FileCharacter =
1752f4a2713aSLionel Sambuc std::max(HeaderInfo.getFileDirFlavor(File),
1753f4a2713aSLionel Sambuc SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
1754f4a2713aSLionel Sambuc
1755f4a2713aSLionel Sambuc // Ask HeaderInfo if we should enter this #include file. If not, #including
1756f4a2713aSLionel Sambuc // this file will have no effect.
1757f4a2713aSLionel Sambuc if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1758f4a2713aSLionel Sambuc if (Callbacks)
1759f4a2713aSLionel Sambuc Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
1760f4a2713aSLionel Sambuc return;
1761f4a2713aSLionel Sambuc }
1762f4a2713aSLionel Sambuc
1763f4a2713aSLionel Sambuc // Look up the file, create a File ID for it.
1764f4a2713aSLionel Sambuc SourceLocation IncludePos = End;
1765f4a2713aSLionel Sambuc // If the filename string was the result of macro expansions, set the include
1766f4a2713aSLionel Sambuc // position on the file where it will be included and after the expansions.
1767f4a2713aSLionel Sambuc if (IncludePos.isMacroID())
1768f4a2713aSLionel Sambuc IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1769f4a2713aSLionel Sambuc FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
1770f4a2713aSLionel Sambuc assert(!FID.isInvalid() && "Expected valid file ID");
1771f4a2713aSLionel Sambuc
1772*0a6a1f1dSLionel Sambuc // Determine if we're switching to building a new submodule, and which one.
1773*0a6a1f1dSLionel Sambuc ModuleMap::KnownHeader BuildingModule;
1774*0a6a1f1dSLionel Sambuc if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) {
1775*0a6a1f1dSLionel Sambuc Module *RequestingModule = getModuleForLocation(FilenameLoc);
1776*0a6a1f1dSLionel Sambuc BuildingModule =
1777*0a6a1f1dSLionel Sambuc HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule);
1778*0a6a1f1dSLionel Sambuc }
1779*0a6a1f1dSLionel Sambuc
1780*0a6a1f1dSLionel Sambuc // If all is good, enter the new file!
1781*0a6a1f1dSLionel Sambuc if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1782*0a6a1f1dSLionel Sambuc return;
1783*0a6a1f1dSLionel Sambuc
1784*0a6a1f1dSLionel Sambuc // If we're walking into another part of the same module, let the parser
1785*0a6a1f1dSLionel Sambuc // know that any future declarations are within that other submodule.
1786*0a6a1f1dSLionel Sambuc if (BuildingModule) {
1787*0a6a1f1dSLionel Sambuc assert(!CurSubmodule && "should not have marked this as a module yet");
1788*0a6a1f1dSLionel Sambuc CurSubmodule = BuildingModule.getModule();
1789*0a6a1f1dSLionel Sambuc
1790*0a6a1f1dSLionel Sambuc EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin,
1791*0a6a1f1dSLionel Sambuc CurSubmodule);
1792*0a6a1f1dSLionel Sambuc }
1793f4a2713aSLionel Sambuc }
1794f4a2713aSLionel Sambuc
1795f4a2713aSLionel Sambuc /// HandleIncludeNextDirective - Implements \#include_next.
1796f4a2713aSLionel Sambuc ///
HandleIncludeNextDirective(SourceLocation HashLoc,Token & IncludeNextTok)1797f4a2713aSLionel Sambuc void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1798f4a2713aSLionel Sambuc Token &IncludeNextTok) {
1799f4a2713aSLionel Sambuc Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1800f4a2713aSLionel Sambuc
1801f4a2713aSLionel Sambuc // #include_next is like #include, except that we start searching after
1802f4a2713aSLionel Sambuc // the current found directory. If we can't do this, issue a
1803f4a2713aSLionel Sambuc // diagnostic.
1804f4a2713aSLionel Sambuc const DirectoryLookup *Lookup = CurDirLookup;
1805*0a6a1f1dSLionel Sambuc const FileEntry *LookupFromFile = nullptr;
1806f4a2713aSLionel Sambuc if (isInPrimaryFile()) {
1807*0a6a1f1dSLionel Sambuc Lookup = nullptr;
1808f4a2713aSLionel Sambuc Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1809*0a6a1f1dSLionel Sambuc } else if (CurSubmodule) {
1810*0a6a1f1dSLionel Sambuc // Start looking up in the directory *after* the one in which the current
1811*0a6a1f1dSLionel Sambuc // file would be found, if any.
1812*0a6a1f1dSLionel Sambuc assert(CurPPLexer && "#include_next directive in macro?");
1813*0a6a1f1dSLionel Sambuc LookupFromFile = CurPPLexer->getFileEntry();
1814*0a6a1f1dSLionel Sambuc Lookup = nullptr;
1815*0a6a1f1dSLionel Sambuc } else if (!Lookup) {
1816f4a2713aSLionel Sambuc Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1817f4a2713aSLionel Sambuc } else {
1818f4a2713aSLionel Sambuc // Start looking up in the next directory.
1819f4a2713aSLionel Sambuc ++Lookup;
1820f4a2713aSLionel Sambuc }
1821f4a2713aSLionel Sambuc
1822*0a6a1f1dSLionel Sambuc return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
1823*0a6a1f1dSLionel Sambuc LookupFromFile);
1824f4a2713aSLionel Sambuc }
1825f4a2713aSLionel Sambuc
1826f4a2713aSLionel Sambuc /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
HandleMicrosoftImportDirective(Token & Tok)1827f4a2713aSLionel Sambuc void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1828f4a2713aSLionel Sambuc // The Microsoft #import directive takes a type library and generates header
1829f4a2713aSLionel Sambuc // files from it, and includes those. This is beyond the scope of what clang
1830f4a2713aSLionel Sambuc // does, so we ignore it and error out. However, #import can optionally have
1831f4a2713aSLionel Sambuc // trailing attributes that span multiple lines. We're going to eat those
1832f4a2713aSLionel Sambuc // so we can continue processing from there.
1833f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_import_directive_ms );
1834f4a2713aSLionel Sambuc
1835f4a2713aSLionel Sambuc // Read tokens until we get to the end of the directive. Note that the
1836f4a2713aSLionel Sambuc // directive can be split over multiple lines using the backslash character.
1837f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
1838f4a2713aSLionel Sambuc }
1839f4a2713aSLionel Sambuc
1840f4a2713aSLionel Sambuc /// HandleImportDirective - Implements \#import.
1841f4a2713aSLionel Sambuc ///
HandleImportDirective(SourceLocation HashLoc,Token & ImportTok)1842f4a2713aSLionel Sambuc void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1843f4a2713aSLionel Sambuc Token &ImportTok) {
1844f4a2713aSLionel Sambuc if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1845*0a6a1f1dSLionel Sambuc if (LangOpts.MSVCCompat)
1846f4a2713aSLionel Sambuc return HandleMicrosoftImportDirective(ImportTok);
1847f4a2713aSLionel Sambuc Diag(ImportTok, diag::ext_pp_import_directive);
1848f4a2713aSLionel Sambuc }
1849*0a6a1f1dSLionel Sambuc return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
1850f4a2713aSLionel Sambuc }
1851f4a2713aSLionel Sambuc
1852f4a2713aSLionel Sambuc /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1853f4a2713aSLionel Sambuc /// pseudo directive in the predefines buffer. This handles it by sucking all
1854f4a2713aSLionel Sambuc /// tokens through the preprocessor and discarding them (only keeping the side
1855f4a2713aSLionel Sambuc /// effects on the preprocessor).
HandleIncludeMacrosDirective(SourceLocation HashLoc,Token & IncludeMacrosTok)1856f4a2713aSLionel Sambuc void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1857f4a2713aSLionel Sambuc Token &IncludeMacrosTok) {
1858f4a2713aSLionel Sambuc // This directive should only occur in the predefines buffer. If not, emit an
1859f4a2713aSLionel Sambuc // error and reject it.
1860f4a2713aSLionel Sambuc SourceLocation Loc = IncludeMacrosTok.getLocation();
1861f4a2713aSLionel Sambuc if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1862f4a2713aSLionel Sambuc Diag(IncludeMacrosTok.getLocation(),
1863f4a2713aSLionel Sambuc diag::pp_include_macros_out_of_predefines);
1864f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
1865f4a2713aSLionel Sambuc return;
1866f4a2713aSLionel Sambuc }
1867f4a2713aSLionel Sambuc
1868f4a2713aSLionel Sambuc // Treat this as a normal #include for checking purposes. If this is
1869f4a2713aSLionel Sambuc // successful, it will push a new lexer onto the include stack.
1870*0a6a1f1dSLionel Sambuc HandleIncludeDirective(HashLoc, IncludeMacrosTok);
1871f4a2713aSLionel Sambuc
1872f4a2713aSLionel Sambuc Token TmpTok;
1873f4a2713aSLionel Sambuc do {
1874f4a2713aSLionel Sambuc Lex(TmpTok);
1875f4a2713aSLionel Sambuc assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1876f4a2713aSLionel Sambuc } while (TmpTok.isNot(tok::hashhash));
1877f4a2713aSLionel Sambuc }
1878f4a2713aSLionel Sambuc
1879f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1880f4a2713aSLionel Sambuc // Preprocessor Macro Directive Handling.
1881f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1882f4a2713aSLionel Sambuc
1883f4a2713aSLionel Sambuc /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1884f4a2713aSLionel Sambuc /// definition has just been read. Lex the rest of the arguments and the
1885f4a2713aSLionel Sambuc /// closing ), updating MI with what we learn. Return true if an error occurs
1886f4a2713aSLionel Sambuc /// parsing the arg list.
ReadMacroDefinitionArgList(MacroInfo * MI,Token & Tok)1887f4a2713aSLionel Sambuc bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
1888f4a2713aSLionel Sambuc SmallVector<IdentifierInfo*, 32> Arguments;
1889f4a2713aSLionel Sambuc
1890f4a2713aSLionel Sambuc while (1) {
1891f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
1892f4a2713aSLionel Sambuc switch (Tok.getKind()) {
1893f4a2713aSLionel Sambuc case tok::r_paren:
1894f4a2713aSLionel Sambuc // Found the end of the argument list.
1895f4a2713aSLionel Sambuc if (Arguments.empty()) // #define FOO()
1896f4a2713aSLionel Sambuc return false;
1897f4a2713aSLionel Sambuc // Otherwise we have #define FOO(A,)
1898f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1899f4a2713aSLionel Sambuc return true;
1900f4a2713aSLionel Sambuc case tok::ellipsis: // #define X(... -> C99 varargs
1901f4a2713aSLionel Sambuc if (!LangOpts.C99)
1902f4a2713aSLionel Sambuc Diag(Tok, LangOpts.CPlusPlus11 ?
1903f4a2713aSLionel Sambuc diag::warn_cxx98_compat_variadic_macro :
1904f4a2713aSLionel Sambuc diag::ext_variadic_macro);
1905f4a2713aSLionel Sambuc
1906f4a2713aSLionel Sambuc // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1907f4a2713aSLionel Sambuc if (LangOpts.OpenCL) {
1908f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_opencl_variadic_macros);
1909f4a2713aSLionel Sambuc return true;
1910f4a2713aSLionel Sambuc }
1911f4a2713aSLionel Sambuc
1912f4a2713aSLionel Sambuc // Lex the token after the identifier.
1913f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
1914f4a2713aSLionel Sambuc if (Tok.isNot(tok::r_paren)) {
1915f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1916f4a2713aSLionel Sambuc return true;
1917f4a2713aSLionel Sambuc }
1918f4a2713aSLionel Sambuc // Add the __VA_ARGS__ identifier as an argument.
1919f4a2713aSLionel Sambuc Arguments.push_back(Ident__VA_ARGS__);
1920f4a2713aSLionel Sambuc MI->setIsC99Varargs();
1921f4a2713aSLionel Sambuc MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1922f4a2713aSLionel Sambuc return false;
1923f4a2713aSLionel Sambuc case tok::eod: // #define X(
1924f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1925f4a2713aSLionel Sambuc return true;
1926f4a2713aSLionel Sambuc default:
1927f4a2713aSLionel Sambuc // Handle keywords and identifiers here to accept things like
1928f4a2713aSLionel Sambuc // #define Foo(for) for.
1929f4a2713aSLionel Sambuc IdentifierInfo *II = Tok.getIdentifierInfo();
1930*0a6a1f1dSLionel Sambuc if (!II) {
1931f4a2713aSLionel Sambuc // #define X(1
1932f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1933f4a2713aSLionel Sambuc return true;
1934f4a2713aSLionel Sambuc }
1935f4a2713aSLionel Sambuc
1936f4a2713aSLionel Sambuc // If this is already used as an argument, it is used multiple times (e.g.
1937f4a2713aSLionel Sambuc // #define X(A,A.
1938f4a2713aSLionel Sambuc if (std::find(Arguments.begin(), Arguments.end(), II) !=
1939f4a2713aSLionel Sambuc Arguments.end()) { // C99 6.10.3p6
1940f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
1941f4a2713aSLionel Sambuc return true;
1942f4a2713aSLionel Sambuc }
1943f4a2713aSLionel Sambuc
1944f4a2713aSLionel Sambuc // Add the argument to the macro info.
1945f4a2713aSLionel Sambuc Arguments.push_back(II);
1946f4a2713aSLionel Sambuc
1947f4a2713aSLionel Sambuc // Lex the token after the identifier.
1948f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
1949f4a2713aSLionel Sambuc
1950f4a2713aSLionel Sambuc switch (Tok.getKind()) {
1951f4a2713aSLionel Sambuc default: // #define X(A B
1952f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1953f4a2713aSLionel Sambuc return true;
1954f4a2713aSLionel Sambuc case tok::r_paren: // #define X(A)
1955f4a2713aSLionel Sambuc MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1956f4a2713aSLionel Sambuc return false;
1957f4a2713aSLionel Sambuc case tok::comma: // #define X(A,
1958f4a2713aSLionel Sambuc break;
1959f4a2713aSLionel Sambuc case tok::ellipsis: // #define X(A... -> GCC extension
1960f4a2713aSLionel Sambuc // Diagnose extension.
1961f4a2713aSLionel Sambuc Diag(Tok, diag::ext_named_variadic_macro);
1962f4a2713aSLionel Sambuc
1963f4a2713aSLionel Sambuc // Lex the token after the identifier.
1964f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
1965f4a2713aSLionel Sambuc if (Tok.isNot(tok::r_paren)) {
1966f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1967f4a2713aSLionel Sambuc return true;
1968f4a2713aSLionel Sambuc }
1969f4a2713aSLionel Sambuc
1970f4a2713aSLionel Sambuc MI->setIsGNUVarargs();
1971f4a2713aSLionel Sambuc MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1972f4a2713aSLionel Sambuc return false;
1973f4a2713aSLionel Sambuc }
1974f4a2713aSLionel Sambuc }
1975f4a2713aSLionel Sambuc }
1976f4a2713aSLionel Sambuc }
1977f4a2713aSLionel Sambuc
isConfigurationPattern(Token & MacroName,MacroInfo * MI,const LangOptions & LOptions)1978*0a6a1f1dSLionel Sambuc static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
1979*0a6a1f1dSLionel Sambuc const LangOptions &LOptions) {
1980*0a6a1f1dSLionel Sambuc if (MI->getNumTokens() == 1) {
1981*0a6a1f1dSLionel Sambuc const Token &Value = MI->getReplacementToken(0);
1982*0a6a1f1dSLionel Sambuc
1983*0a6a1f1dSLionel Sambuc // Macro that is identity, like '#define inline inline' is a valid pattern.
1984*0a6a1f1dSLionel Sambuc if (MacroName.getKind() == Value.getKind())
1985*0a6a1f1dSLionel Sambuc return true;
1986*0a6a1f1dSLionel Sambuc
1987*0a6a1f1dSLionel Sambuc // Macro that maps a keyword to the same keyword decorated with leading/
1988*0a6a1f1dSLionel Sambuc // trailing underscores is a valid pattern:
1989*0a6a1f1dSLionel Sambuc // #define inline __inline
1990*0a6a1f1dSLionel Sambuc // #define inline __inline__
1991*0a6a1f1dSLionel Sambuc // #define inline _inline (in MS compatibility mode)
1992*0a6a1f1dSLionel Sambuc StringRef MacroText = MacroName.getIdentifierInfo()->getName();
1993*0a6a1f1dSLionel Sambuc if (IdentifierInfo *II = Value.getIdentifierInfo()) {
1994*0a6a1f1dSLionel Sambuc if (!II->isKeyword(LOptions))
1995*0a6a1f1dSLionel Sambuc return false;
1996*0a6a1f1dSLionel Sambuc StringRef ValueText = II->getName();
1997*0a6a1f1dSLionel Sambuc StringRef TrimmedValue = ValueText;
1998*0a6a1f1dSLionel Sambuc if (!ValueText.startswith("__")) {
1999*0a6a1f1dSLionel Sambuc if (ValueText.startswith("_"))
2000*0a6a1f1dSLionel Sambuc TrimmedValue = TrimmedValue.drop_front(1);
2001*0a6a1f1dSLionel Sambuc else
2002*0a6a1f1dSLionel Sambuc return false;
2003*0a6a1f1dSLionel Sambuc } else {
2004*0a6a1f1dSLionel Sambuc TrimmedValue = TrimmedValue.drop_front(2);
2005*0a6a1f1dSLionel Sambuc if (TrimmedValue.endswith("__"))
2006*0a6a1f1dSLionel Sambuc TrimmedValue = TrimmedValue.drop_back(2);
2007*0a6a1f1dSLionel Sambuc }
2008*0a6a1f1dSLionel Sambuc return TrimmedValue.equals(MacroText);
2009*0a6a1f1dSLionel Sambuc } else {
2010*0a6a1f1dSLionel Sambuc return false;
2011*0a6a1f1dSLionel Sambuc }
2012*0a6a1f1dSLionel Sambuc }
2013*0a6a1f1dSLionel Sambuc
2014*0a6a1f1dSLionel Sambuc // #define inline
2015*0a6a1f1dSLionel Sambuc if ((MacroName.is(tok::kw_extern) || MacroName.is(tok::kw_inline) ||
2016*0a6a1f1dSLionel Sambuc MacroName.is(tok::kw_static) || MacroName.is(tok::kw_const)) &&
2017*0a6a1f1dSLionel Sambuc MI->getNumTokens() == 0) {
2018*0a6a1f1dSLionel Sambuc return true;
2019*0a6a1f1dSLionel Sambuc }
2020*0a6a1f1dSLionel Sambuc
2021*0a6a1f1dSLionel Sambuc return false;
2022*0a6a1f1dSLionel Sambuc }
2023*0a6a1f1dSLionel Sambuc
2024f4a2713aSLionel Sambuc /// HandleDefineDirective - Implements \#define. This consumes the entire macro
2025f4a2713aSLionel Sambuc /// line then lets the caller lex the next real token.
HandleDefineDirective(Token & DefineTok,bool ImmediatelyAfterHeaderGuard)2026f4a2713aSLionel Sambuc void Preprocessor::HandleDefineDirective(Token &DefineTok,
2027f4a2713aSLionel Sambuc bool ImmediatelyAfterHeaderGuard) {
2028f4a2713aSLionel Sambuc ++NumDefined;
2029f4a2713aSLionel Sambuc
2030f4a2713aSLionel Sambuc Token MacroNameTok;
2031*0a6a1f1dSLionel Sambuc bool MacroShadowsKeyword;
2032*0a6a1f1dSLionel Sambuc ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2033f4a2713aSLionel Sambuc
2034f4a2713aSLionel Sambuc // Error reading macro name? If so, diagnostic already issued.
2035f4a2713aSLionel Sambuc if (MacroNameTok.is(tok::eod))
2036f4a2713aSLionel Sambuc return;
2037f4a2713aSLionel Sambuc
2038f4a2713aSLionel Sambuc Token LastTok = MacroNameTok;
2039f4a2713aSLionel Sambuc
2040f4a2713aSLionel Sambuc // If we are supposed to keep comments in #defines, reenable comment saving
2041f4a2713aSLionel Sambuc // mode.
2042f4a2713aSLionel Sambuc if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2043f4a2713aSLionel Sambuc
2044f4a2713aSLionel Sambuc // Create the new macro.
2045f4a2713aSLionel Sambuc MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
2046f4a2713aSLionel Sambuc
2047f4a2713aSLionel Sambuc Token Tok;
2048f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2049f4a2713aSLionel Sambuc
2050f4a2713aSLionel Sambuc // If this is a function-like macro definition, parse the argument list,
2051f4a2713aSLionel Sambuc // marking each of the identifiers as being used as macro arguments. Also,
2052f4a2713aSLionel Sambuc // check other constraints on the first token of the macro body.
2053f4a2713aSLionel Sambuc if (Tok.is(tok::eod)) {
2054f4a2713aSLionel Sambuc if (ImmediatelyAfterHeaderGuard) {
2055f4a2713aSLionel Sambuc // Save this macro information since it may part of a header guard.
2056f4a2713aSLionel Sambuc CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2057f4a2713aSLionel Sambuc MacroNameTok.getLocation());
2058f4a2713aSLionel Sambuc }
2059f4a2713aSLionel Sambuc // If there is no body to this macro, we have no special handling here.
2060f4a2713aSLionel Sambuc } else if (Tok.hasLeadingSpace()) {
2061f4a2713aSLionel Sambuc // This is a normal token with leading space. Clear the leading space
2062f4a2713aSLionel Sambuc // marker on the first token to get proper expansion.
2063f4a2713aSLionel Sambuc Tok.clearFlag(Token::LeadingSpace);
2064f4a2713aSLionel Sambuc } else if (Tok.is(tok::l_paren)) {
2065f4a2713aSLionel Sambuc // This is a function-like macro definition. Read the argument list.
2066f4a2713aSLionel Sambuc MI->setIsFunctionLike();
2067f4a2713aSLionel Sambuc if (ReadMacroDefinitionArgList(MI, LastTok)) {
2068f4a2713aSLionel Sambuc // Throw away the rest of the line.
2069f4a2713aSLionel Sambuc if (CurPPLexer->ParsingPreprocessorDirective)
2070f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
2071f4a2713aSLionel Sambuc return;
2072f4a2713aSLionel Sambuc }
2073f4a2713aSLionel Sambuc
2074f4a2713aSLionel Sambuc // If this is a definition of a variadic C99 function-like macro, not using
2075f4a2713aSLionel Sambuc // the GNU named varargs extension, enabled __VA_ARGS__.
2076f4a2713aSLionel Sambuc
2077f4a2713aSLionel Sambuc // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2078f4a2713aSLionel Sambuc // This gets unpoisoned where it is allowed.
2079f4a2713aSLionel Sambuc assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2080f4a2713aSLionel Sambuc if (MI->isC99Varargs())
2081f4a2713aSLionel Sambuc Ident__VA_ARGS__->setIsPoisoned(false);
2082f4a2713aSLionel Sambuc
2083f4a2713aSLionel Sambuc // Read the first token after the arg list for down below.
2084f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2085f4a2713aSLionel Sambuc } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
2086f4a2713aSLionel Sambuc // C99 requires whitespace between the macro definition and the body. Emit
2087f4a2713aSLionel Sambuc // a diagnostic for something like "#define X+".
2088f4a2713aSLionel Sambuc Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2089f4a2713aSLionel Sambuc } else {
2090f4a2713aSLionel Sambuc // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2091f4a2713aSLionel Sambuc // first character of a replacement list is not a character required by
2092f4a2713aSLionel Sambuc // subclause 5.2.1, then there shall be white-space separation between the
2093f4a2713aSLionel Sambuc // identifier and the replacement list.". 5.2.1 lists this set:
2094f4a2713aSLionel Sambuc // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2095f4a2713aSLionel Sambuc // is irrelevant here.
2096f4a2713aSLionel Sambuc bool isInvalid = false;
2097f4a2713aSLionel Sambuc if (Tok.is(tok::at)) // @ is not in the list above.
2098f4a2713aSLionel Sambuc isInvalid = true;
2099f4a2713aSLionel Sambuc else if (Tok.is(tok::unknown)) {
2100f4a2713aSLionel Sambuc // If we have an unknown token, it is something strange like "`". Since
2101f4a2713aSLionel Sambuc // all of valid characters would have lexed into a single character
2102f4a2713aSLionel Sambuc // token of some sort, we know this is not a valid case.
2103f4a2713aSLionel Sambuc isInvalid = true;
2104f4a2713aSLionel Sambuc }
2105f4a2713aSLionel Sambuc if (isInvalid)
2106f4a2713aSLionel Sambuc Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2107f4a2713aSLionel Sambuc else
2108f4a2713aSLionel Sambuc Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
2109f4a2713aSLionel Sambuc }
2110f4a2713aSLionel Sambuc
2111f4a2713aSLionel Sambuc if (!Tok.is(tok::eod))
2112f4a2713aSLionel Sambuc LastTok = Tok;
2113f4a2713aSLionel Sambuc
2114f4a2713aSLionel Sambuc // Read the rest of the macro body.
2115f4a2713aSLionel Sambuc if (MI->isObjectLike()) {
2116f4a2713aSLionel Sambuc // Object-like macros are very simple, just read their body.
2117f4a2713aSLionel Sambuc while (Tok.isNot(tok::eod)) {
2118f4a2713aSLionel Sambuc LastTok = Tok;
2119f4a2713aSLionel Sambuc MI->AddTokenToBody(Tok);
2120f4a2713aSLionel Sambuc // Get the next token of the macro.
2121f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2122f4a2713aSLionel Sambuc }
2123f4a2713aSLionel Sambuc
2124f4a2713aSLionel Sambuc } else {
2125f4a2713aSLionel Sambuc // Otherwise, read the body of a function-like macro. While we are at it,
2126f4a2713aSLionel Sambuc // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2127f4a2713aSLionel Sambuc // parameters in function-like macro expansions.
2128f4a2713aSLionel Sambuc while (Tok.isNot(tok::eod)) {
2129f4a2713aSLionel Sambuc LastTok = Tok;
2130f4a2713aSLionel Sambuc
2131f4a2713aSLionel Sambuc if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
2132f4a2713aSLionel Sambuc MI->AddTokenToBody(Tok);
2133f4a2713aSLionel Sambuc
2134f4a2713aSLionel Sambuc // Get the next token of the macro.
2135f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2136f4a2713aSLionel Sambuc continue;
2137f4a2713aSLionel Sambuc }
2138f4a2713aSLionel Sambuc
2139f4a2713aSLionel Sambuc // If we're in -traditional mode, then we should ignore stringification
2140f4a2713aSLionel Sambuc // and token pasting. Mark the tokens as unknown so as not to confuse
2141f4a2713aSLionel Sambuc // things.
2142f4a2713aSLionel Sambuc if (getLangOpts().TraditionalCPP) {
2143f4a2713aSLionel Sambuc Tok.setKind(tok::unknown);
2144f4a2713aSLionel Sambuc MI->AddTokenToBody(Tok);
2145f4a2713aSLionel Sambuc
2146f4a2713aSLionel Sambuc // Get the next token of the macro.
2147f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2148f4a2713aSLionel Sambuc continue;
2149f4a2713aSLionel Sambuc }
2150f4a2713aSLionel Sambuc
2151f4a2713aSLionel Sambuc if (Tok.is(tok::hashhash)) {
2152f4a2713aSLionel Sambuc
2153f4a2713aSLionel Sambuc // If we see token pasting, check if it looks like the gcc comma
2154f4a2713aSLionel Sambuc // pasting extension. We'll use this information to suppress
2155f4a2713aSLionel Sambuc // diagnostics later on.
2156f4a2713aSLionel Sambuc
2157f4a2713aSLionel Sambuc // Get the next token of the macro.
2158f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2159f4a2713aSLionel Sambuc
2160f4a2713aSLionel Sambuc if (Tok.is(tok::eod)) {
2161f4a2713aSLionel Sambuc MI->AddTokenToBody(LastTok);
2162f4a2713aSLionel Sambuc break;
2163f4a2713aSLionel Sambuc }
2164f4a2713aSLionel Sambuc
2165f4a2713aSLionel Sambuc unsigned NumTokens = MI->getNumTokens();
2166f4a2713aSLionel Sambuc if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2167f4a2713aSLionel Sambuc MI->getReplacementToken(NumTokens-1).is(tok::comma))
2168f4a2713aSLionel Sambuc MI->setHasCommaPasting();
2169f4a2713aSLionel Sambuc
2170f4a2713aSLionel Sambuc // Things look ok, add the '##' token to the macro.
2171f4a2713aSLionel Sambuc MI->AddTokenToBody(LastTok);
2172f4a2713aSLionel Sambuc continue;
2173f4a2713aSLionel Sambuc }
2174f4a2713aSLionel Sambuc
2175f4a2713aSLionel Sambuc // Get the next token of the macro.
2176f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2177f4a2713aSLionel Sambuc
2178f4a2713aSLionel Sambuc // Check for a valid macro arg identifier.
2179*0a6a1f1dSLionel Sambuc if (Tok.getIdentifierInfo() == nullptr ||
2180f4a2713aSLionel Sambuc MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2181f4a2713aSLionel Sambuc
2182f4a2713aSLionel Sambuc // If this is assembler-with-cpp mode, we accept random gibberish after
2183f4a2713aSLionel Sambuc // the '#' because '#' is often a comment character. However, change
2184f4a2713aSLionel Sambuc // the kind of the token to tok::unknown so that the preprocessor isn't
2185f4a2713aSLionel Sambuc // confused.
2186f4a2713aSLionel Sambuc if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
2187f4a2713aSLionel Sambuc LastTok.setKind(tok::unknown);
2188f4a2713aSLionel Sambuc MI->AddTokenToBody(LastTok);
2189f4a2713aSLionel Sambuc continue;
2190f4a2713aSLionel Sambuc } else {
2191f4a2713aSLionel Sambuc Diag(Tok, diag::err_pp_stringize_not_parameter);
2192f4a2713aSLionel Sambuc
2193f4a2713aSLionel Sambuc // Disable __VA_ARGS__ again.
2194f4a2713aSLionel Sambuc Ident__VA_ARGS__->setIsPoisoned(true);
2195f4a2713aSLionel Sambuc return;
2196f4a2713aSLionel Sambuc }
2197f4a2713aSLionel Sambuc }
2198f4a2713aSLionel Sambuc
2199f4a2713aSLionel Sambuc // Things look ok, add the '#' and param name tokens to the macro.
2200f4a2713aSLionel Sambuc MI->AddTokenToBody(LastTok);
2201f4a2713aSLionel Sambuc MI->AddTokenToBody(Tok);
2202f4a2713aSLionel Sambuc LastTok = Tok;
2203f4a2713aSLionel Sambuc
2204f4a2713aSLionel Sambuc // Get the next token of the macro.
2205f4a2713aSLionel Sambuc LexUnexpandedToken(Tok);
2206f4a2713aSLionel Sambuc }
2207f4a2713aSLionel Sambuc }
2208f4a2713aSLionel Sambuc
2209*0a6a1f1dSLionel Sambuc if (MacroShadowsKeyword &&
2210*0a6a1f1dSLionel Sambuc !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2211*0a6a1f1dSLionel Sambuc Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2212*0a6a1f1dSLionel Sambuc }
2213f4a2713aSLionel Sambuc
2214f4a2713aSLionel Sambuc // Disable __VA_ARGS__ again.
2215f4a2713aSLionel Sambuc Ident__VA_ARGS__->setIsPoisoned(true);
2216f4a2713aSLionel Sambuc
2217f4a2713aSLionel Sambuc // Check that there is no paste (##) operator at the beginning or end of the
2218f4a2713aSLionel Sambuc // replacement list.
2219f4a2713aSLionel Sambuc unsigned NumTokens = MI->getNumTokens();
2220f4a2713aSLionel Sambuc if (NumTokens != 0) {
2221f4a2713aSLionel Sambuc if (MI->getReplacementToken(0).is(tok::hashhash)) {
2222f4a2713aSLionel Sambuc Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2223f4a2713aSLionel Sambuc return;
2224f4a2713aSLionel Sambuc }
2225f4a2713aSLionel Sambuc if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2226f4a2713aSLionel Sambuc Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2227f4a2713aSLionel Sambuc return;
2228f4a2713aSLionel Sambuc }
2229f4a2713aSLionel Sambuc }
2230f4a2713aSLionel Sambuc
2231f4a2713aSLionel Sambuc MI->setDefinitionEndLoc(LastTok.getLocation());
2232f4a2713aSLionel Sambuc
2233f4a2713aSLionel Sambuc // Finally, if this identifier already had a macro defined for it, verify that
2234f4a2713aSLionel Sambuc // the macro bodies are identical, and issue diagnostics if they are not.
2235f4a2713aSLionel Sambuc if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
2236f4a2713aSLionel Sambuc // It is very common for system headers to have tons of macro redefinitions
2237f4a2713aSLionel Sambuc // and for warnings to be disabled in system headers. If this is the case,
2238f4a2713aSLionel Sambuc // then don't bother calling MacroInfo::isIdenticalTo.
2239f4a2713aSLionel Sambuc if (!getDiagnostics().getSuppressSystemWarnings() ||
2240f4a2713aSLionel Sambuc !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
2241f4a2713aSLionel Sambuc if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
2242f4a2713aSLionel Sambuc Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2243f4a2713aSLionel Sambuc
2244f4a2713aSLionel Sambuc // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2245f4a2713aSLionel Sambuc // C++ [cpp.predefined]p4, but allow it as an extension.
2246f4a2713aSLionel Sambuc if (OtherMI->isBuiltinMacro())
2247f4a2713aSLionel Sambuc Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
2248f4a2713aSLionel Sambuc // Macros must be identical. This means all tokens and whitespace
2249f4a2713aSLionel Sambuc // separation must be the same. C99 6.10.3p2.
2250f4a2713aSLionel Sambuc else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
2251f4a2713aSLionel Sambuc !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
2252f4a2713aSLionel Sambuc Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2253f4a2713aSLionel Sambuc << MacroNameTok.getIdentifierInfo();
2254f4a2713aSLionel Sambuc Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2255f4a2713aSLionel Sambuc }
2256f4a2713aSLionel Sambuc }
2257f4a2713aSLionel Sambuc if (OtherMI->isWarnIfUnused())
2258f4a2713aSLionel Sambuc WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
2259f4a2713aSLionel Sambuc }
2260f4a2713aSLionel Sambuc
2261f4a2713aSLionel Sambuc DefMacroDirective *MD =
2262f4a2713aSLionel Sambuc appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
2263f4a2713aSLionel Sambuc
2264f4a2713aSLionel Sambuc assert(!MI->isUsed());
2265f4a2713aSLionel Sambuc // If we need warning for not using the macro, add its location in the
2266f4a2713aSLionel Sambuc // warn-because-unused-macro set. If it gets used it will be removed from set.
2267f4a2713aSLionel Sambuc if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
2268*0a6a1f1dSLionel Sambuc !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
2269f4a2713aSLionel Sambuc MI->setIsWarnIfUnused(true);
2270f4a2713aSLionel Sambuc WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2271f4a2713aSLionel Sambuc }
2272f4a2713aSLionel Sambuc
2273f4a2713aSLionel Sambuc // If the callbacks want to know, tell them about the macro definition.
2274f4a2713aSLionel Sambuc if (Callbacks)
2275f4a2713aSLionel Sambuc Callbacks->MacroDefined(MacroNameTok, MD);
2276f4a2713aSLionel Sambuc }
2277f4a2713aSLionel Sambuc
2278f4a2713aSLionel Sambuc /// HandleUndefDirective - Implements \#undef.
2279f4a2713aSLionel Sambuc ///
HandleUndefDirective(Token & UndefTok)2280f4a2713aSLionel Sambuc void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2281f4a2713aSLionel Sambuc ++NumUndefined;
2282f4a2713aSLionel Sambuc
2283f4a2713aSLionel Sambuc Token MacroNameTok;
2284*0a6a1f1dSLionel Sambuc ReadMacroName(MacroNameTok, MU_Undef);
2285f4a2713aSLionel Sambuc
2286f4a2713aSLionel Sambuc // Error reading macro name? If so, diagnostic already issued.
2287f4a2713aSLionel Sambuc if (MacroNameTok.is(tok::eod))
2288f4a2713aSLionel Sambuc return;
2289f4a2713aSLionel Sambuc
2290f4a2713aSLionel Sambuc // Check to see if this is the last token on the #undef line.
2291f4a2713aSLionel Sambuc CheckEndOfDirective("undef");
2292f4a2713aSLionel Sambuc
2293f4a2713aSLionel Sambuc // Okay, we finally have a valid identifier to undef.
2294f4a2713aSLionel Sambuc MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
2295*0a6a1f1dSLionel Sambuc const MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
2296f4a2713aSLionel Sambuc
2297f4a2713aSLionel Sambuc // If the callbacks want to know, tell them about the macro #undef.
2298f4a2713aSLionel Sambuc // Note: no matter if the macro was defined or not.
2299f4a2713aSLionel Sambuc if (Callbacks)
2300f4a2713aSLionel Sambuc Callbacks->MacroUndefined(MacroNameTok, MD);
2301f4a2713aSLionel Sambuc
2302f4a2713aSLionel Sambuc // If the macro is not defined, this is a noop undef, just return.
2303*0a6a1f1dSLionel Sambuc if (!MI)
2304*0a6a1f1dSLionel Sambuc return;
2305f4a2713aSLionel Sambuc
2306f4a2713aSLionel Sambuc if (!MI->isUsed() && MI->isWarnIfUnused())
2307f4a2713aSLionel Sambuc Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2308f4a2713aSLionel Sambuc
2309f4a2713aSLionel Sambuc if (MI->isWarnIfUnused())
2310f4a2713aSLionel Sambuc WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2311f4a2713aSLionel Sambuc
2312f4a2713aSLionel Sambuc appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2313f4a2713aSLionel Sambuc AllocateUndefMacroDirective(MacroNameTok.getLocation()));
2314f4a2713aSLionel Sambuc }
2315f4a2713aSLionel Sambuc
2316f4a2713aSLionel Sambuc
2317f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
2318f4a2713aSLionel Sambuc // Preprocessor Conditional Directive Handling.
2319f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
2320f4a2713aSLionel Sambuc
2321f4a2713aSLionel Sambuc /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2322f4a2713aSLionel Sambuc /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2323f4a2713aSLionel Sambuc /// true if any tokens have been returned or pp-directives activated before this
2324f4a2713aSLionel Sambuc /// \#ifndef has been lexed.
2325f4a2713aSLionel Sambuc ///
HandleIfdefDirective(Token & Result,bool isIfndef,bool ReadAnyTokensBeforeDirective)2326f4a2713aSLionel Sambuc void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2327f4a2713aSLionel Sambuc bool ReadAnyTokensBeforeDirective) {
2328f4a2713aSLionel Sambuc ++NumIf;
2329f4a2713aSLionel Sambuc Token DirectiveTok = Result;
2330f4a2713aSLionel Sambuc
2331f4a2713aSLionel Sambuc Token MacroNameTok;
2332f4a2713aSLionel Sambuc ReadMacroName(MacroNameTok);
2333f4a2713aSLionel Sambuc
2334f4a2713aSLionel Sambuc // Error reading macro name? If so, diagnostic already issued.
2335f4a2713aSLionel Sambuc if (MacroNameTok.is(tok::eod)) {
2336f4a2713aSLionel Sambuc // Skip code until we get to #endif. This helps with recovery by not
2337f4a2713aSLionel Sambuc // emitting an error when the #endif is reached.
2338f4a2713aSLionel Sambuc SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2339f4a2713aSLionel Sambuc /*Foundnonskip*/false, /*FoundElse*/false);
2340f4a2713aSLionel Sambuc return;
2341f4a2713aSLionel Sambuc }
2342f4a2713aSLionel Sambuc
2343f4a2713aSLionel Sambuc // Check to see if this is the last token on the #if[n]def line.
2344f4a2713aSLionel Sambuc CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
2345f4a2713aSLionel Sambuc
2346f4a2713aSLionel Sambuc IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2347f4a2713aSLionel Sambuc MacroDirective *MD = getMacroDirective(MII);
2348*0a6a1f1dSLionel Sambuc MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
2349f4a2713aSLionel Sambuc
2350f4a2713aSLionel Sambuc if (CurPPLexer->getConditionalStackDepth() == 0) {
2351f4a2713aSLionel Sambuc // If the start of a top-level #ifdef and if the macro is not defined,
2352f4a2713aSLionel Sambuc // inform MIOpt that this might be the start of a proper include guard.
2353f4a2713aSLionel Sambuc // Otherwise it is some other form of unknown conditional which we can't
2354f4a2713aSLionel Sambuc // handle.
2355*0a6a1f1dSLionel Sambuc if (!ReadAnyTokensBeforeDirective && !MI) {
2356f4a2713aSLionel Sambuc assert(isIfndef && "#ifdef shouldn't reach here");
2357f4a2713aSLionel Sambuc CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
2358f4a2713aSLionel Sambuc } else
2359f4a2713aSLionel Sambuc CurPPLexer->MIOpt.EnterTopLevelConditional();
2360f4a2713aSLionel Sambuc }
2361f4a2713aSLionel Sambuc
2362f4a2713aSLionel Sambuc // If there is a macro, process it.
2363f4a2713aSLionel Sambuc if (MI) // Mark it used.
2364f4a2713aSLionel Sambuc markMacroAsUsed(MI);
2365f4a2713aSLionel Sambuc
2366f4a2713aSLionel Sambuc if (Callbacks) {
2367f4a2713aSLionel Sambuc if (isIfndef)
2368f4a2713aSLionel Sambuc Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
2369f4a2713aSLionel Sambuc else
2370f4a2713aSLionel Sambuc Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
2371f4a2713aSLionel Sambuc }
2372f4a2713aSLionel Sambuc
2373f4a2713aSLionel Sambuc // Should we include the stuff contained by this directive?
2374f4a2713aSLionel Sambuc if (!MI == isIfndef) {
2375f4a2713aSLionel Sambuc // Yes, remember that we are inside a conditional, then lex the next token.
2376f4a2713aSLionel Sambuc CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2377f4a2713aSLionel Sambuc /*wasskip*/false, /*foundnonskip*/true,
2378f4a2713aSLionel Sambuc /*foundelse*/false);
2379f4a2713aSLionel Sambuc } else {
2380f4a2713aSLionel Sambuc // No, skip the contents of this block.
2381f4a2713aSLionel Sambuc SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2382f4a2713aSLionel Sambuc /*Foundnonskip*/false,
2383f4a2713aSLionel Sambuc /*FoundElse*/false);
2384f4a2713aSLionel Sambuc }
2385f4a2713aSLionel Sambuc }
2386f4a2713aSLionel Sambuc
2387f4a2713aSLionel Sambuc /// HandleIfDirective - Implements the \#if directive.
2388f4a2713aSLionel Sambuc ///
HandleIfDirective(Token & IfToken,bool ReadAnyTokensBeforeDirective)2389f4a2713aSLionel Sambuc void Preprocessor::HandleIfDirective(Token &IfToken,
2390f4a2713aSLionel Sambuc bool ReadAnyTokensBeforeDirective) {
2391f4a2713aSLionel Sambuc ++NumIf;
2392f4a2713aSLionel Sambuc
2393f4a2713aSLionel Sambuc // Parse and evaluate the conditional expression.
2394*0a6a1f1dSLionel Sambuc IdentifierInfo *IfNDefMacro = nullptr;
2395f4a2713aSLionel Sambuc const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2396f4a2713aSLionel Sambuc const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2397f4a2713aSLionel Sambuc const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
2398f4a2713aSLionel Sambuc
2399f4a2713aSLionel Sambuc // If this condition is equivalent to #ifndef X, and if this is the first
2400f4a2713aSLionel Sambuc // directive seen, handle it for the multiple-include optimization.
2401f4a2713aSLionel Sambuc if (CurPPLexer->getConditionalStackDepth() == 0) {
2402f4a2713aSLionel Sambuc if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
2403f4a2713aSLionel Sambuc // FIXME: Pass in the location of the macro name, not the 'if' token.
2404f4a2713aSLionel Sambuc CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
2405f4a2713aSLionel Sambuc else
2406f4a2713aSLionel Sambuc CurPPLexer->MIOpt.EnterTopLevelConditional();
2407f4a2713aSLionel Sambuc }
2408f4a2713aSLionel Sambuc
2409f4a2713aSLionel Sambuc if (Callbacks)
2410f4a2713aSLionel Sambuc Callbacks->If(IfToken.getLocation(),
2411f4a2713aSLionel Sambuc SourceRange(ConditionalBegin, ConditionalEnd),
2412*0a6a1f1dSLionel Sambuc (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
2413f4a2713aSLionel Sambuc
2414f4a2713aSLionel Sambuc // Should we include the stuff contained by this directive?
2415f4a2713aSLionel Sambuc if (ConditionalTrue) {
2416f4a2713aSLionel Sambuc // Yes, remember that we are inside a conditional, then lex the next token.
2417f4a2713aSLionel Sambuc CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2418f4a2713aSLionel Sambuc /*foundnonskip*/true, /*foundelse*/false);
2419f4a2713aSLionel Sambuc } else {
2420f4a2713aSLionel Sambuc // No, skip the contents of this block.
2421f4a2713aSLionel Sambuc SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2422f4a2713aSLionel Sambuc /*FoundElse*/false);
2423f4a2713aSLionel Sambuc }
2424f4a2713aSLionel Sambuc }
2425f4a2713aSLionel Sambuc
2426f4a2713aSLionel Sambuc /// HandleEndifDirective - Implements the \#endif directive.
2427f4a2713aSLionel Sambuc ///
HandleEndifDirective(Token & EndifToken)2428f4a2713aSLionel Sambuc void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2429f4a2713aSLionel Sambuc ++NumEndif;
2430f4a2713aSLionel Sambuc
2431f4a2713aSLionel Sambuc // Check that this is the whole directive.
2432f4a2713aSLionel Sambuc CheckEndOfDirective("endif");
2433f4a2713aSLionel Sambuc
2434f4a2713aSLionel Sambuc PPConditionalInfo CondInfo;
2435f4a2713aSLionel Sambuc if (CurPPLexer->popConditionalLevel(CondInfo)) {
2436f4a2713aSLionel Sambuc // No conditionals on the stack: this is an #endif without an #if.
2437f4a2713aSLionel Sambuc Diag(EndifToken, diag::err_pp_endif_without_if);
2438f4a2713aSLionel Sambuc return;
2439f4a2713aSLionel Sambuc }
2440f4a2713aSLionel Sambuc
2441f4a2713aSLionel Sambuc // If this the end of a top-level #endif, inform MIOpt.
2442f4a2713aSLionel Sambuc if (CurPPLexer->getConditionalStackDepth() == 0)
2443f4a2713aSLionel Sambuc CurPPLexer->MIOpt.ExitTopLevelConditional();
2444f4a2713aSLionel Sambuc
2445f4a2713aSLionel Sambuc assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
2446f4a2713aSLionel Sambuc "This code should only be reachable in the non-skipping case!");
2447f4a2713aSLionel Sambuc
2448f4a2713aSLionel Sambuc if (Callbacks)
2449f4a2713aSLionel Sambuc Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
2450f4a2713aSLionel Sambuc }
2451f4a2713aSLionel Sambuc
2452f4a2713aSLionel Sambuc /// HandleElseDirective - Implements the \#else directive.
2453f4a2713aSLionel Sambuc ///
HandleElseDirective(Token & Result)2454f4a2713aSLionel Sambuc void Preprocessor::HandleElseDirective(Token &Result) {
2455f4a2713aSLionel Sambuc ++NumElse;
2456f4a2713aSLionel Sambuc
2457f4a2713aSLionel Sambuc // #else directive in a non-skipping conditional... start skipping.
2458f4a2713aSLionel Sambuc CheckEndOfDirective("else");
2459f4a2713aSLionel Sambuc
2460f4a2713aSLionel Sambuc PPConditionalInfo CI;
2461f4a2713aSLionel Sambuc if (CurPPLexer->popConditionalLevel(CI)) {
2462f4a2713aSLionel Sambuc Diag(Result, diag::pp_err_else_without_if);
2463f4a2713aSLionel Sambuc return;
2464f4a2713aSLionel Sambuc }
2465f4a2713aSLionel Sambuc
2466f4a2713aSLionel Sambuc // If this is a top-level #else, inform the MIOpt.
2467f4a2713aSLionel Sambuc if (CurPPLexer->getConditionalStackDepth() == 0)
2468f4a2713aSLionel Sambuc CurPPLexer->MIOpt.EnterTopLevelConditional();
2469f4a2713aSLionel Sambuc
2470f4a2713aSLionel Sambuc // If this is a #else with a #else before it, report the error.
2471f4a2713aSLionel Sambuc if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2472f4a2713aSLionel Sambuc
2473f4a2713aSLionel Sambuc if (Callbacks)
2474f4a2713aSLionel Sambuc Callbacks->Else(Result.getLocation(), CI.IfLoc);
2475f4a2713aSLionel Sambuc
2476f4a2713aSLionel Sambuc // Finally, skip the rest of the contents of this block.
2477f4a2713aSLionel Sambuc SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2478f4a2713aSLionel Sambuc /*FoundElse*/true, Result.getLocation());
2479f4a2713aSLionel Sambuc }
2480f4a2713aSLionel Sambuc
2481f4a2713aSLionel Sambuc /// HandleElifDirective - Implements the \#elif directive.
2482f4a2713aSLionel Sambuc ///
HandleElifDirective(Token & ElifToken)2483f4a2713aSLionel Sambuc void Preprocessor::HandleElifDirective(Token &ElifToken) {
2484f4a2713aSLionel Sambuc ++NumElse;
2485f4a2713aSLionel Sambuc
2486f4a2713aSLionel Sambuc // #elif directive in a non-skipping conditional... start skipping.
2487f4a2713aSLionel Sambuc // We don't care what the condition is, because we will always skip it (since
2488f4a2713aSLionel Sambuc // the block immediately before it was included).
2489f4a2713aSLionel Sambuc const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2490f4a2713aSLionel Sambuc DiscardUntilEndOfDirective();
2491f4a2713aSLionel Sambuc const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
2492f4a2713aSLionel Sambuc
2493f4a2713aSLionel Sambuc PPConditionalInfo CI;
2494f4a2713aSLionel Sambuc if (CurPPLexer->popConditionalLevel(CI)) {
2495f4a2713aSLionel Sambuc Diag(ElifToken, diag::pp_err_elif_without_if);
2496f4a2713aSLionel Sambuc return;
2497f4a2713aSLionel Sambuc }
2498f4a2713aSLionel Sambuc
2499f4a2713aSLionel Sambuc // If this is a top-level #elif, inform the MIOpt.
2500f4a2713aSLionel Sambuc if (CurPPLexer->getConditionalStackDepth() == 0)
2501f4a2713aSLionel Sambuc CurPPLexer->MIOpt.EnterTopLevelConditional();
2502f4a2713aSLionel Sambuc
2503f4a2713aSLionel Sambuc // If this is a #elif with a #else before it, report the error.
2504f4a2713aSLionel Sambuc if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2505f4a2713aSLionel Sambuc
2506f4a2713aSLionel Sambuc if (Callbacks)
2507f4a2713aSLionel Sambuc Callbacks->Elif(ElifToken.getLocation(),
2508f4a2713aSLionel Sambuc SourceRange(ConditionalBegin, ConditionalEnd),
2509*0a6a1f1dSLionel Sambuc PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
2510f4a2713aSLionel Sambuc
2511f4a2713aSLionel Sambuc // Finally, skip the rest of the contents of this block.
2512f4a2713aSLionel Sambuc SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2513f4a2713aSLionel Sambuc /*FoundElse*/CI.FoundElse,
2514f4a2713aSLionel Sambuc ElifToken.getLocation());
2515f4a2713aSLionel Sambuc }
2516