blob: a952b2ef1b90676f1643d1d56879e9f19718a66c [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
Daniel Jasper07e6c402013-08-05 20:26:17 +000020#include "clang/Lex/HeaderSearchOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/ModuleLoader.h"
25#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000026#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000027#include "llvm/Support/ErrorHandling.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000028#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000029using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Utility Methods for Preprocessor Directive Handling.
33//===----------------------------------------------------------------------===//
34
Chris Lattnerc0a585d2010-08-17 15:55:45 +000035MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000036 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000037
Ted Kremenekc8456f82010-10-19 22:15:20 +000038 if (MICache) {
39 MIChain = MICache;
40 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000041 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000042 else {
43 MIChain = BP.Allocate<MacroInfoChain>();
44 }
45
46 MIChain->Next = MIChainHead;
47 MIChain->Prev = 0;
48 if (MIChainHead)
49 MIChainHead->Prev = MIChain;
50 MIChainHead = MIChain;
51
52 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000053}
54
55MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
56 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000057 new (MI) MacroInfo(L);
58 return MI;
59}
60
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000061MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
62 unsigned SubModuleID) {
63 LLVM_STATIC_ASSERT(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
64 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000065 DeserializedMacroInfoChain *MIChain =
66 BP.Allocate<DeserializedMacroInfoChain>();
67 MIChain->Next = DeserialMIChainHead;
68 DeserialMIChainHead = MIChain;
69
70 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000071 new (MI) MacroInfo(L);
72 MI->FromASTFile = true;
73 MI->setOwningModuleID(SubModuleID);
74 return MI;
75}
76
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000077DefMacroDirective *
78Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
79 bool isImported) {
80 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>();
81 new (MD) DefMacroDirective(MI, Loc, isImported);
82 return MD;
83}
84
85UndefMacroDirective *
86Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
87 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>();
88 new (MD) UndefMacroDirective(UndefLoc);
89 return MD;
90}
91
92VisibilityMacroDirective *
93Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
94 bool isPublic) {
95 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>();
96 new (MD) VisibilityMacroDirective(Loc, isPublic);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000097 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000098}
99
James Dennettf6333ac2012-06-22 05:46:07 +0000100/// \brief Release the specified MacroInfo to be reused for allocating
101/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +0000102void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +0000103 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
104 if (MacroInfoChain *Prev = MIChain->Prev) {
105 MacroInfoChain *Next = MIChain->Next;
106 Prev->Next = Next;
107 if (Next)
108 Next->Prev = Prev;
109 }
110 else {
111 assert(MIChainHead == MIChain);
112 MIChainHead = MIChain->Next;
113 MIChainHead->Prev = 0;
114 }
115 MIChain->Next = MICache;
116 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +0000117
Ted Kremenekc8456f82010-10-19 22:15:20 +0000118 MI->Destroy();
119}
Chris Lattner666f7a42009-02-20 22:19:20 +0000120
James Dennettf6333ac2012-06-22 05:46:07 +0000121/// \brief Read and discard all tokens remaining on the current line until
122/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000123void Preprocessor::DiscardUntilEndOfDirective() {
124 Token Tmp;
125 do {
126 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000127 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000128 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000129}
130
James Dennettf6333ac2012-06-22 05:46:07 +0000131/// \brief Lex and validate a macro name, which occurs after a
132/// \#define or \#undef.
133///
134/// This sets the token kind to eod and discards the rest
135/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
136/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
137/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000138void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
139 // Read the token, don't allow macro expansion on it.
140 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Douglas Gregor12785102010-08-24 20:21:13 +0000142 if (MacroNameTok.is(tok::code_completion)) {
143 if (CodeComplete)
144 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000145 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000146 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000147 }
148
Chris Lattnerf64b3522008-03-09 01:54:53 +0000149 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000150 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000151 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
152 return;
153 }
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattnerf64b3522008-03-09 01:54:53 +0000155 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
156 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000157 bool Invalid = false;
158 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
159 if (Invalid)
160 return;
Nico Weber2e686202012-02-29 22:54:43 +0000161
Chris Lattner77c76ae2008-12-13 20:12:40 +0000162 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000163
164 // Allow #defining |and| and friends in microsoft mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000165 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000166 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
167 return;
168 }
169
Chris Lattner77c76ae2008-12-13 20:12:40 +0000170 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000171 // C++ 2.5p2: Alternative tokens behave the same as its primary token
172 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000173 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000174 else
175 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
176 // Fall through on error.
177 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Richard Smith7b242542013-03-06 00:46:00 +0000178 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000179 Diag(MacroNameTok, diag::err_defined_macro_name);
Richard Smith7b242542013-03-06 00:46:00 +0000180 } else if (isDefineUndef == 2 && II->hasMacroDefinition() &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000181 getMacroInfo(II)->isBuiltinMacro()) {
Richard Smith7b242542013-03-06 00:46:00 +0000182 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
183 // and C++ [cpp.predefined]p4], but allow it as an extension.
184 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
185 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000186 } else {
187 // Okay, we got a good identifier node. Return it.
188 return;
189 }
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattnerf64b3522008-03-09 01:54:53 +0000191 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000192 // token kind to tok::eod.
193 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000194 return DiscardUntilEndOfDirective();
195}
196
James Dennettf6333ac2012-06-22 05:46:07 +0000197/// \brief Ensure that the next token is a tok::eod token.
198///
199/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000200/// true, then we consider macros that expand to zero tokens as being ok.
201void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000202 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000203 // Lex unexpanded tokens for most directives: macros might expand to zero
204 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
205 // #line) allow empty macros.
206 if (EnableMacros)
207 Lex(Tmp);
208 else
209 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattnerf64b3522008-03-09 01:54:53 +0000211 // There should be no tokens after the directive, but we allow them as an
212 // extension.
213 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
214 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000215
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000216 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000217 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000218 // or if this is a macro-style preprocessing directive, because it is more
219 // trouble than it is worth to insert /**/ and check that there is no /**/
220 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000221 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000222 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000223 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000224 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
225 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000226 DiscardUntilEndOfDirective();
227 }
228}
229
230
231
James Dennettf6333ac2012-06-22 05:46:07 +0000232/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
233/// decided that the subsequent tokens are in the \#if'd out portion of the
234/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000235/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000236/// this \#if directive, so \#else/\#elif blocks should never be entered.
237/// If ElseOk is true, then \#else directives are ok, if not, then we have
238/// already seen one so a \#else directive is a duplicate. When this returns,
239/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000240void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
241 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000242 bool FoundElse,
243 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000244 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000245 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000247 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000249
Ted Kremenek56572ab2008-12-12 18:34:08 +0000250 if (CurPTHLexer) {
251 PTHSkipExcludedConditionalBlock();
252 return;
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255 // Enter raw mode to disable identifier lookup (and thus macro expansion),
256 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000257 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000258 Token Tok;
259 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000260 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000262 if (Tok.is(tok::code_completion)) {
263 if (CodeComplete)
264 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000265 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000266 continue;
267 }
268
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 // If this is the end of the buffer, we have an error.
270 if (Tok.is(tok::eof)) {
271 // Emit errors for each unterminated conditional on the stack, including
272 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000273 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000274 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000275 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
276 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000277 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000278 }
279
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 // Just return and let the caller lex after this #include.
281 break;
282 }
Mike Stump11289f42009-09-09 15:08:12 +0000283
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 // If this token is not a preprocessor directive, just skip it.
285 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
286 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 // We just parsed a # character at the start of a line, so we're in
289 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000290 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000291 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000292 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000293
Mike Stump11289f42009-09-09 15:08:12 +0000294
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 // Read the next token, the directive flavor.
296 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000297
Chris Lattnerf64b3522008-03-09 01:54:53 +0000298 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
299 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000300 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000301 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000303 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000304 continue;
305 }
306
307 // If the first letter isn't i or e, it isn't intesting to us. We know that
308 // this is safe in the face of spelling differences, because there is no way
309 // to spell an i/e in a strange way that is another letter. Skipping this
310 // allows us to avoid looking up the identifier info for #define/#undef and
311 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000312 const char *RawCharData = Tok.getRawIdentifierData();
313
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000315 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000317 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000318 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000319 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 continue;
321 }
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 // Get the identifier name without trigraphs or embedded newlines. Note
324 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
325 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000326 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000327 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000329 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 } else {
331 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000332 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000334 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000335 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000336 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337 continue;
338 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000339 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 }
Mike Stump11289f42009-09-09 15:08:12 +0000342
Benjamin Kramer144884642009-12-31 13:32:38 +0000343 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000344 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000345 if (Sub.empty() || // "if"
346 Sub == "def" || // "ifdef"
347 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
349 // bother parsing the condition.
350 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000351 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000353 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000355 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000356 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000357 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 PPConditionalInfo CondInfo;
359 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000360 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000361 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000363
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000365 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000366 // Restore the value of LexingRawMode so that trailing comments
367 // are handled correctly, if we've reached the outermost block.
368 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000369 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000370 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000371 if (Callbacks)
372 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000373 break;
Richard Smithd0124572012-06-21 00:35:03 +0000374 } else {
375 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000376 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000377 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000378 // #else directive in a skipping conditional. If not in some other
379 // skipping conditional, and if #else hasn't already been seen, enter it
380 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000381 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 // If this is a #else with a #else before it, report the error.
384 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 // Note that we've seen a #else in this conditional.
387 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Chris Lattnerf64b3522008-03-09 01:54:53 +0000389 // If the conditional is at the top level, and the #if block wasn't
390 // entered, enter the #else block now.
391 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
392 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000393 // Restore the value of LexingRawMode so that trailing comments
394 // are handled correctly.
395 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000396 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000397 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000398 if (Callbacks)
399 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000400 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000401 } else {
402 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000403 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000404 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000405 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406
407 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000408 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // If this is in a skipping block or if we're already handled this #if
410 // block, don't bother parsing the condition.
411 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
412 DiscardUntilEndOfDirective();
413 ShouldEnter = false;
414 } else {
415 // Restore the value of LexingRawMode so that identifiers are
416 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000417 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
418 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000419 IdentifierInfo *IfNDefMacro = 0;
420 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000421 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000422 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000423 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattnerf64b3522008-03-09 01:54:53 +0000425 // If this is a #elif with a #else before it, report the error.
426 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000427
Chris Lattnerf64b3522008-03-09 01:54:53 +0000428 // If this condition is true, enter it!
429 if (ShouldEnter) {
430 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000431 if (Callbacks)
432 Callbacks->Elif(Tok.getLocation(),
433 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompsonb1028562013-07-18 00:00:36 +0000434 ShouldEnter, CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000435 break;
436 }
437 }
438 }
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000440 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000441 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000442 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000443 }
444
445 // Finally, if we are out of the conditional (saw an #endif or ran off the end
446 // of the file, just stop skipping and return to lexing whatever came after
447 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000448 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000449
450 if (Callbacks) {
451 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
452 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
453 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454}
455
Ted Kremenek56572ab2008-12-12 18:34:08 +0000456void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000457
458 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000459 assert(CurPTHLexer);
460 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000461
Ted Kremenek56572ab2008-12-12 18:34:08 +0000462 // Skip to the next '#else', '#elif', or #endif.
463 if (CurPTHLexer->SkipBlock()) {
464 // We have reached an #endif. Both the '#' and 'endif' tokens
465 // have been consumed by the PTHLexer. Just pop off the condition level.
466 PPConditionalInfo CondInfo;
467 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000468 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000469 assert(!InCond && "Can't be skipping if not in a conditional!");
470 break;
471 }
Mike Stump11289f42009-09-09 15:08:12 +0000472
Ted Kremenek56572ab2008-12-12 18:34:08 +0000473 // We have reached a '#else' or '#elif'. Lex the next token to get
474 // the directive flavor.
475 Token Tok;
476 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000477
Ted Kremenek56572ab2008-12-12 18:34:08 +0000478 // We can actually look up the IdentifierInfo here since we aren't in
479 // raw mode.
480 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
481
482 if (K == tok::pp_else) {
483 // #else: Enter the else condition. We aren't in a nested condition
484 // since we skip those. We're always in the one matching the last
485 // blocked we skipped.
486 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
487 // Note that we've seen a #else in this conditional.
488 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Ted Kremenek56572ab2008-12-12 18:34:08 +0000490 // If the #if block wasn't entered then enter the #else block now.
491 if (!CondInfo.FoundNonSkip) {
492 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000494 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000495 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000496 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000497 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Ted Kremenek56572ab2008-12-12 18:34:08 +0000499 break;
500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Ted Kremenek56572ab2008-12-12 18:34:08 +0000502 // Otherwise skip this block.
503 continue;
504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Ted Kremenek56572ab2008-12-12 18:34:08 +0000506 assert(K == tok::pp_elif);
507 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
508
509 // If this is a #elif with a #else before it, report the error.
510 if (CondInfo.FoundElse)
511 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000512
Ted Kremenek56572ab2008-12-12 18:34:08 +0000513 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000514 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000515 if (CondInfo.FoundNonSkip)
516 continue;
517
518 // Evaluate the condition of the #elif.
519 IdentifierInfo *IfNDefMacro = 0;
520 CurPTHLexer->ParsingPreprocessorDirective = true;
521 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
522 CurPTHLexer->ParsingPreprocessorDirective = false;
523
524 // If this condition is true, enter it!
525 if (ShouldEnter) {
526 CondInfo.FoundNonSkip = true;
527 break;
528 }
529
530 // Otherwise, skip this block and go to the next one.
531 continue;
532 }
533}
534
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000535Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) {
536 ModuleMap &ModMap = HeaderInfo.getModuleMap();
537 if (SourceMgr.isInMainFile(FilenameLoc)) {
538 if (Module *CurMod = getCurrentModule())
539 return CurMod; // Compiling a module.
540 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
541 }
542 // Try to determine the module of the include directive.
543 FileID IDOfIncl = SourceMgr.getFileID(FilenameLoc);
544 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
545 // The include comes from a file.
546 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
547 } else {
548 // The include does not come from a file,
549 // so it is probably a module compilation.
550 return getCurrentModule();
551 }
552}
553
554bool Preprocessor::violatesPrivateInclude(
555 Module *RequestingModule,
556 const FileEntry *IncFileEnt,
557 ModuleMap::ModuleHeaderRole Role,
558 Module *RequestedModule) {
559 #ifndef NDEBUG
560 // Check for consistency between the module header role
561 // as obtained from the lookup and as obtained from the module.
562 // This check is not cheap, so enable it only for debugging.
563 SmallVectorImpl<const FileEntry *> &PvtHdrs
564 = RequestedModule->PrivateHeaders;
565 SmallVectorImpl<const FileEntry *>::iterator Look
566 = std::find(PvtHdrs.begin(), PvtHdrs.end(), IncFileEnt);
567 bool IsPrivate = Look != PvtHdrs.end();
568 assert((IsPrivate && Role == ModuleMap::PrivateHeader)
569 || (!IsPrivate && Role != ModuleMap::PrivateHeader));
570 #endif
571 return Role == ModuleMap::PrivateHeader &&
572 RequestedModule->getTopLevelModule() != RequestingModule;
573}
574
575bool Preprocessor::violatesUseDeclarations(
576 Module *RequestingModule,
577 Module *RequestedModule) {
578 ModuleMap &ModMap = HeaderInfo.getModuleMap();
579 ModMap.resolveUses(RequestingModule, /*Complain=*/false);
580 const SmallVectorImpl<Module *> &AllowedUses = RequestingModule->DirectUses;
581 SmallVectorImpl<Module *>::const_iterator Declared =
582 std::find(AllowedUses.begin(), AllowedUses.end(), RequestedModule);
583 return Declared == AllowedUses.end();
584}
585
Daniel Jasper97da9172013-10-22 08:09:47 +0000586void Preprocessor::verifyModuleInclude(SourceLocation FilenameLoc,
587 StringRef Filename,
588 const FileEntry *IncFileEnt) {
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000589 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Daniel Jasper97da9172013-10-22 08:09:47 +0000590 if (RequestingModule)
591 HeaderInfo.getModuleMap().resolveUses(RequestingModule, /*Complain=*/false);
592 ModuleMap::KnownHeader RequestedModule =
593 HeaderInfo.getModuleMap().findModuleForHeader(IncFileEnt,
594 RequestingModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000595
Daniel Jasper97da9172013-10-22 08:09:47 +0000596 if (RequestingModule == RequestedModule.getModule())
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000597 return; // No faults wihin a module, or between files both not in modules.
598
599 if (RequestingModule != HeaderInfo.getModuleMap().SourceModule)
600 return; // No errors for indirect modules.
601 // This may be a bit of a problem for modules with no source files.
602
Daniel Jasper97da9172013-10-22 08:09:47 +0000603 if (RequestedModule && violatesPrivateInclude(RequestingModule, IncFileEnt,
604 RequestedModule.getRole(),
605 RequestedModule.getModule()))
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000606 Diag(FilenameLoc, diag::error_use_of_private_header_outside_module)
607 << Filename;
608
609 // FIXME: Add support for FixIts in module map files and offer adding the
610 // required use declaration.
611 if (RequestingModule && getLangOpts().ModulesDeclUse &&
Daniel Jasper97da9172013-10-22 08:09:47 +0000612 violatesUseDeclarations(RequestingModule, RequestedModule.getModule()))
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000613 Diag(FilenameLoc, diag::error_undeclared_use_of_module)
614 << Filename;
615}
616
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000617const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000618 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000620 bool isAngled,
621 const DirectoryLookup *FromDir,
622 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000623 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000624 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000625 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000626 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000627 // If the header lookup mechanism may be relative to the current file, pass in
628 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000629 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000630 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000631 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000632 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattner022923a2009-02-04 19:45:07 +0000634 // If there is no file entry associated with this file, it must be the
635 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000636 // it won't be scanned for preprocessor directives. If we have the
637 // predefines buffer, resolve #include references (which come from the
638 // -include command line argument) as if they came from the main file, this
639 // affects file lookup etc.
640 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000641 FID = SourceMgr.getMainFileID();
642 CurFileEnt = SourceMgr.getFileEntryForID(FID);
643 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000644 }
Mike Stump11289f42009-09-09 15:08:12 +0000645
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000646 // Do a standard file entry lookup.
647 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000648 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000649 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000650 SearchPath, RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000651 if (FE) {
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000652 if (SuggestedModule)
Daniel Jasper97da9172013-10-22 08:09:47 +0000653 verifyModuleInclude(FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000654 return FE;
655 }
Mike Stump11289f42009-09-09 15:08:12 +0000656
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000657 // Otherwise, see if this is a subframework header. If so, this is relative
658 // to one of the headers on the #include stack. Walk the list of the current
659 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000660 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000661 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000662 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000663 SearchPath, RelativePath,
664 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000665 return FE;
666 }
Mike Stump11289f42009-09-09 15:08:12 +0000667
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000668 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
669 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000670 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000671 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000672 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000673 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000674 Filename, CurFileEnt, SearchPath, RelativePath,
675 SuggestedModule)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000676 return FE;
677 }
678 }
Mike Stump11289f42009-09-09 15:08:12 +0000679
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000680 // Otherwise, we really couldn't find the file.
681 return 0;
682}
683
Chris Lattnerf64b3522008-03-09 01:54:53 +0000684
685//===----------------------------------------------------------------------===//
686// Preprocessor Directive Handling.
687//===----------------------------------------------------------------------===//
688
David Blaikied5321242012-06-06 18:52:13 +0000689class Preprocessor::ResetMacroExpansionHelper {
690public:
691 ResetMacroExpansionHelper(Preprocessor *pp)
692 : PP(pp), save(pp->DisableMacroExpansion) {
693 if (pp->MacroExpansionInDirectivesOverride)
694 pp->DisableMacroExpansion = false;
695 }
696 ~ResetMacroExpansionHelper() {
697 PP->DisableMacroExpansion = save;
698 }
699private:
700 Preprocessor *PP;
701 bool save;
702};
703
Chris Lattnerf64b3522008-03-09 01:54:53 +0000704/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000705/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000706/// lexer/preprocessor state, and advances the lexer(s) so that the next token
707/// read is the correct one.
708void Preprocessor::HandleDirective(Token &Result) {
709 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattnerf64b3522008-03-09 01:54:53 +0000711 // We just parsed a # character at the start of a line, so we're in directive
712 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000713 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000714 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000715 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000716
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000717 bool ImmediatelyAfterTopLevelIfndef =
718 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
719 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
720
Chris Lattnerf64b3522008-03-09 01:54:53 +0000721 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000722
Chris Lattnerf64b3522008-03-09 01:54:53 +0000723 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000724 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000725 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000726 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chris Lattner2d17ab72009-03-18 21:00:25 +0000728 // Save the '#' token in case we need to return it later.
729 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattnerf64b3522008-03-09 01:54:53 +0000731 // Read the next token, the directive flavor. This isn't expanded due to
732 // C99 6.10.3p8.
733 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattnerf64b3522008-03-09 01:54:53 +0000735 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
736 // #define A(x) #x
737 // A(abc
738 // #warning blah
739 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000740 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
741 // not support this for #include-like directives, since that can result in
742 // terrible diagnostics, and does not work in GCC.
743 if (InMacroArgs) {
744 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
745 switch (II->getPPKeywordID()) {
746 case tok::pp_include:
747 case tok::pp_import:
748 case tok::pp_include_next:
749 case tok::pp___include_macros:
750 Diag(Result, diag::err_embedded_include) << II->getName();
751 DiscardUntilEndOfDirective();
752 return;
753 default:
754 break;
755 }
756 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000757 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000758 }
Mike Stump11289f42009-09-09 15:08:12 +0000759
David Blaikied5321242012-06-06 18:52:13 +0000760 // Temporarily enable macro expansion if set so
761 // and reset to previous state when returning from this function.
762 ResetMacroExpansionHelper helper(this);
763
Chris Lattnerf64b3522008-03-09 01:54:53 +0000764 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000765 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000766 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000767 case tok::code_completion:
768 if (CodeComplete)
769 CodeComplete->CodeCompleteDirective(
770 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000771 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000772 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000773 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000774 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000775 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000776 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000777 default:
778 IdentifierInfo *II = Result.getIdentifierInfo();
779 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattnerf64b3522008-03-09 01:54:53 +0000781 // Ask what the preprocessor keyword ID is.
782 switch (II->getPPKeywordID()) {
783 default: break;
784 // C99 6.10.1 - Conditional Inclusion.
785 case tok::pp_if:
786 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
787 case tok::pp_ifdef:
788 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
789 case tok::pp_ifndef:
790 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
791 case tok::pp_elif:
792 return HandleElifDirective(Result);
793 case tok::pp_else:
794 return HandleElseDirective(Result);
795 case tok::pp_endif:
796 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattnerf64b3522008-03-09 01:54:53 +0000798 // C99 6.10.2 - Source File Inclusion.
799 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000800 // Handle #include.
801 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000802 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000803 // Handle -imacros.
804 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattnerf64b3522008-03-09 01:54:53 +0000806 // C99 6.10.3 - Macro Replacement.
807 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000808 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000809 case tok::pp_undef:
810 return HandleUndefDirective(Result);
811
812 // C99 6.10.4 - Line Control.
813 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000814 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattnerf64b3522008-03-09 01:54:53 +0000816 // C99 6.10.5 - Error Directive.
817 case tok::pp_error:
818 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000819
Chris Lattnerf64b3522008-03-09 01:54:53 +0000820 // C99 6.10.6 - Pragma Directive.
821 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000822 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000823
Chris Lattnerf64b3522008-03-09 01:54:53 +0000824 // GNU Extensions.
825 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000826 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000827 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000828 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000829
Chris Lattnerf64b3522008-03-09 01:54:53 +0000830 case tok::pp_warning:
831 Diag(Result, diag::ext_pp_warning_directive);
832 return HandleUserDiagnosticDirective(Result, true);
833 case tok::pp_ident:
834 return HandleIdentSCCSDirective(Result);
835 case tok::pp_sccs:
836 return HandleIdentSCCSDirective(Result);
837 case tok::pp_assert:
838 //isExtension = true; // FIXME: implement #assert
839 break;
840 case tok::pp_unassert:
841 //isExtension = true; // FIXME: implement #unassert
842 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000843
Douglas Gregor663b48f2012-01-03 19:48:16 +0000844 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000845 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000846 return HandleMacroPublicDirective(Result);
847 break;
848
Douglas Gregor663b48f2012-01-03 19:48:16 +0000849 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000850 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000851 return HandleMacroPrivateDirective(Result);
852 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000853 }
854 break;
855 }
Mike Stump11289f42009-09-09 15:08:12 +0000856
Chris Lattner2d17ab72009-03-18 21:00:25 +0000857 // If this is a .S file, treat unknown # directives as non-preprocessor
858 // directives. This is important because # may be a comment or introduce
859 // various pseudo-ops. Just return the # token and push back the following
860 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000862 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000863 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000864 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000865 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000866
867 // If the second token is a hashhash token, then we need to translate it to
868 // unknown so the token lexer doesn't try to perform token pasting.
869 if (Result.is(tok::hashhash))
870 Toks[1].setKind(tok::unknown);
871
Chris Lattner2d17ab72009-03-18 21:00:25 +0000872 // Enter this token stream so that we re-lex the tokens. Make sure to
873 // enable macro expansion, in case the token after the # is an identifier
874 // that is expanded.
875 EnterTokenStream(Toks, 2, false, true);
876 return;
877 }
Mike Stump11289f42009-09-09 15:08:12 +0000878
Chris Lattnerf64b3522008-03-09 01:54:53 +0000879 // If we reached here, the preprocessing token is not valid!
880 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000881
Chris Lattnerf64b3522008-03-09 01:54:53 +0000882 // Read the rest of the PP line.
883 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattnerf64b3522008-03-09 01:54:53 +0000885 // Okay, we're done parsing the directive.
886}
887
Chris Lattner76e68962009-01-26 06:19:46 +0000888/// GetLineValue - Convert a numeric token into an unsigned value, emitting
889/// Diagnostic DiagID if it is invalid, and returning the value in Val.
890static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000891 unsigned DiagID, Preprocessor &PP,
892 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000893 if (DigitTok.isNot(tok::numeric_constant)) {
894 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000895
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000896 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000897 PP.DiscardUntilEndOfDirective();
898 return true;
899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000901 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000902 IntegerBuffer.resize(DigitTok.getLength());
903 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000904 bool Invalid = false;
905 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
906 if (Invalid)
907 return true;
908
Chris Lattnerd66f1722009-04-18 18:35:15 +0000909 // Verify that we have a simple digit-sequence, and compute the value. This
910 // is always a simple digit string computed in decimal, so we do this manually
911 // here.
912 Val = 0;
913 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000914 // C++1y [lex.fcon]p1:
915 // Optional separating single quotes in a digit-sequence are ignored
916 if (DigitTokBegin[i] == '\'')
917 continue;
918
Jordan Rosea7d03842013-02-08 22:30:41 +0000919 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000920 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000921 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000922 PP.DiscardUntilEndOfDirective();
923 return true;
924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Chris Lattnerd66f1722009-04-18 18:35:15 +0000926 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
927 if (NextVal < Val) { // overflow.
928 PP.Diag(DigitTok, DiagID);
929 PP.DiscardUntilEndOfDirective();
930 return true;
931 }
932 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000933 }
Mike Stump11289f42009-09-09 15:08:12 +0000934
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000935 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000936 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
937 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000938
Chris Lattner76e68962009-01-26 06:19:46 +0000939 return false;
940}
941
James Dennettf6333ac2012-06-22 05:46:07 +0000942/// \brief Handle a \#line directive: C99 6.10.4.
943///
944/// The two acceptable forms are:
945/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000946/// # line digit-sequence
947/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000948/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000949void Preprocessor::HandleLineDirective(Token &Tok) {
950 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
951 // expanded.
952 Token DigitTok;
953 Lex(DigitTok);
954
Chris Lattner100c65e2009-01-26 05:29:08 +0000955 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000956 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000957 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000958 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000959
960 if (LineNo == 0)
961 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000962
Chris Lattner76e68962009-01-26 06:19:46 +0000963 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
964 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000965 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000966 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000967 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000968 if (LineNo >= LineLimit)
969 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000970 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000971 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000973 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000974 Token StrTok;
975 Lex(StrTok);
976
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000977 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
978 // string followed by eod.
979 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000980 ; // ok
981 else if (StrTok.isNot(tok::string_literal)) {
982 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000983 return DiscardUntilEndOfDirective();
984 } else if (StrTok.hasUDSuffix()) {
985 Diag(StrTok, diag::err_invalid_string_udl);
986 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000987 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000988 // Parse and validate the string, converting it into a unique ID.
989 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000990 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000991 if (Literal.hadError)
992 return DiscardUntilEndOfDirective();
993 if (Literal.Pascal) {
994 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
995 return DiscardUntilEndOfDirective();
996 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000997 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000998
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000999 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001000 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1001 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001002 }
Mike Stump11289f42009-09-09 15:08:12 +00001003
Chris Lattner1eaa70a2009-02-03 21:52:55 +00001004 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +00001005
Chris Lattner839150e2009-03-27 17:13:49 +00001006 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001007 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1008 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +00001009 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +00001010}
1011
Chris Lattner76e68962009-01-26 06:19:46 +00001012/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1013/// marker directive.
1014static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1015 bool &IsSystemHeader, bool &IsExternCHeader,
1016 Preprocessor &PP) {
1017 unsigned FlagVal;
1018 Token FlagTok;
1019 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001020 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001021 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1022 return true;
1023
1024 if (FlagVal == 1) {
1025 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001026
Chris Lattner76e68962009-01-26 06:19:46 +00001027 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001028 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001029 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1030 return true;
1031 } else if (FlagVal == 2) {
1032 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattner1c967782009-02-04 06:25:26 +00001034 SourceManager &SM = PP.getSourceManager();
1035 // If we are leaving the current presumed file, check to make sure the
1036 // presumed include stack isn't empty!
1037 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001038 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001039 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001040 if (PLoc.isInvalid())
1041 return true;
1042
Chris Lattner1c967782009-02-04 06:25:26 +00001043 // If there is no include loc (main file) or if the include loc is in a
1044 // different physical file, then we aren't in a "1" line marker flag region.
1045 SourceLocation IncLoc = PLoc.getIncludeLoc();
1046 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001047 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001048 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1049 PP.DiscardUntilEndOfDirective();
1050 return true;
1051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chris Lattner76e68962009-01-26 06:19:46 +00001053 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001054 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001055 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1056 return true;
1057 }
1058
1059 // We must have 3 if there are still flags.
1060 if (FlagVal != 3) {
1061 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001062 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001063 return true;
1064 }
Mike Stump11289f42009-09-09 15:08:12 +00001065
Chris Lattner76e68962009-01-26 06:19:46 +00001066 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Chris Lattner76e68962009-01-26 06:19:46 +00001068 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001069 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001070 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001071 return true;
1072
1073 // We must have 4 if there is yet another flag.
1074 if (FlagVal != 4) {
1075 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001076 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001077 return true;
1078 }
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattner76e68962009-01-26 06:19:46 +00001080 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001081
Chris Lattner76e68962009-01-26 06:19:46 +00001082 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001083 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001084
1085 // There are no more valid flags here.
1086 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001087 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001088 return true;
1089}
1090
1091/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1092/// one of the following forms:
1093///
1094/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001095/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001096/// # 42 "file" ('1' | '2')? '3' '4'?
1097///
1098void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1099 // Validate the number and convert it to an unsigned. GNU does not have a
1100 // line # limit other than it fit in 32-bits.
1101 unsigned LineNo;
1102 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001103 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001104 return;
Mike Stump11289f42009-09-09 15:08:12 +00001105
Chris Lattner76e68962009-01-26 06:19:46 +00001106 Token StrTok;
1107 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001108
Chris Lattner76e68962009-01-26 06:19:46 +00001109 bool IsFileEntry = false, IsFileExit = false;
1110 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001111 int FilenameID = -1;
1112
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001113 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1114 // string followed by eod.
1115 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001116 ; // ok
1117 else if (StrTok.isNot(tok::string_literal)) {
1118 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001119 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001120 } else if (StrTok.hasUDSuffix()) {
1121 Diag(StrTok, diag::err_invalid_string_udl);
1122 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001123 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001124 // Parse and validate the string, converting it into a unique ID.
1125 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001126 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001127 if (Literal.hadError)
1128 return DiscardUntilEndOfDirective();
1129 if (Literal.Pascal) {
1130 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1131 return DiscardUntilEndOfDirective();
1132 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001133 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001134
Chris Lattner76e68962009-01-26 06:19:46 +00001135 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001136 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001137 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001138 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001139 }
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001141 // Create a line note with this information.
1142 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001143 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001144 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Chris Lattner839150e2009-03-27 17:13:49 +00001146 // If the preprocessor has callbacks installed, notify them of the #line
1147 // change. This is used so that the line marker comes out in -E mode for
1148 // example.
1149 if (Callbacks) {
1150 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1151 if (IsFileEntry)
1152 Reason = PPCallbacks::EnterFile;
1153 else if (IsFileExit)
1154 Reason = PPCallbacks::ExitFile;
1155 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1156 if (IsExternCHeader)
1157 FileKind = SrcMgr::C_ExternCSystem;
1158 else if (IsSystemHeader)
1159 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001160
Chris Lattnerc745cec2010-04-14 04:28:50 +00001161 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001162 }
Chris Lattner76e68962009-01-26 06:19:46 +00001163}
1164
1165
Chris Lattner38d7fd22009-01-26 05:30:54 +00001166/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1167///
Mike Stump11289f42009-09-09 15:08:12 +00001168void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001169 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001170 // PTH doesn't emit #warning or #error directives.
1171 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001172 return CurPTHLexer->DiscardToEndOfLine();
1173
Chris Lattnerf64b3522008-03-09 01:54:53 +00001174 // Read the rest of the line raw. We do this because we don't want macros
1175 // to be expanded and we don't require that the tokens be valid preprocessing
1176 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1177 // collapse multiple consequtive white space between tokens, but this isn't
1178 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001179 SmallString<128> Message;
1180 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001181
1182 // Find the first non-whitespace character, so that we can make the
1183 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001184 StringRef Msg = Message.str().ltrim(" ");
1185
Chris Lattner100c65e2009-01-26 05:29:08 +00001186 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001187 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001188 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001189 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001190}
1191
1192/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1193///
1194void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1195 // Yes, this directive is an extension.
1196 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001197
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 // Read the string argument.
1199 Token StrTok;
1200 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001201
Chris Lattnerf64b3522008-03-09 01:54:53 +00001202 // If the token kind isn't a string, it's a malformed directive.
1203 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001204 StrTok.isNot(tok::wide_string_literal)) {
1205 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001206 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001207 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001208 return;
1209 }
Mike Stump11289f42009-09-09 15:08:12 +00001210
Richard Smithd67aea22012-03-06 03:21:47 +00001211 if (StrTok.hasUDSuffix()) {
1212 Diag(StrTok, diag::err_invalid_string_udl);
1213 return DiscardUntilEndOfDirective();
1214 }
1215
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001216 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001217 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001218
Douglas Gregordc970f02010-03-16 22:30:13 +00001219 if (Callbacks) {
1220 bool Invalid = false;
1221 std::string Str = getSpelling(StrTok, &Invalid);
1222 if (!Invalid)
1223 Callbacks->Ident(Tok.getLocation(), Str);
1224 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001225}
1226
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001227/// \brief Handle a #public directive.
1228void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001229 Token MacroNameTok;
1230 ReadMacroName(MacroNameTok, 2);
1231
1232 // Error reading macro name? If so, diagnostic already issued.
1233 if (MacroNameTok.is(tok::eod))
1234 return;
1235
Douglas Gregor663b48f2012-01-03 19:48:16 +00001236 // Check to see if this is the last token on the #__public_macro line.
1237 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001238
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001239 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001240 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001241 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001242
1243 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001244 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001245 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001246 return;
1247 }
1248
1249 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001250 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1251 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001252}
1253
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001254/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001255void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1256 Token MacroNameTok;
1257 ReadMacroName(MacroNameTok, 2);
1258
1259 // Error reading macro name? If so, diagnostic already issued.
1260 if (MacroNameTok.is(tok::eod))
1261 return;
1262
Douglas Gregor663b48f2012-01-03 19:48:16 +00001263 // Check to see if this is the last token on the #__private_macro line.
1264 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001265
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001266 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001267 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001268 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001269
1270 // If the macro is not defined, this is an error.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00001271 if (MD == 0) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001272 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001273 return;
1274 }
1275
1276 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001277 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1278 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001279}
1280
Chris Lattnerf64b3522008-03-09 01:54:53 +00001281//===----------------------------------------------------------------------===//
1282// Preprocessor Include Directive Handling.
1283//===----------------------------------------------------------------------===//
1284
1285/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001286/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001287/// true if the input filename was in <>'s or false if it were in ""'s. The
1288/// caller is expected to provide a buffer that is large enough to hold the
1289/// spelling of the filename, but is also expected to handle the case when
1290/// this method decides to use a different buffer.
1291bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001292 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001293 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001294 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattnerf64b3522008-03-09 01:54:53 +00001296 // Make sure the filename is <x> or "x".
1297 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001298 if (Buffer[0] == '<') {
1299 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001300 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001301 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001302 return true;
1303 }
1304 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001305 } else if (Buffer[0] == '"') {
1306 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001307 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001308 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001309 return true;
1310 }
1311 isAngled = false;
1312 } else {
1313 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001314 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001315 return true;
1316 }
Mike Stump11289f42009-09-09 15:08:12 +00001317
Chris Lattnerf64b3522008-03-09 01:54:53 +00001318 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001319 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001320 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001321 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001322 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattnerf64b3522008-03-09 01:54:53 +00001325 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001326 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001327 return isAngled;
1328}
1329
James Dennettf6333ac2012-06-22 05:46:07 +00001330/// \brief Handle cases where the \#include name is expanded from a macro
1331/// as multiple tokens, which need to be glued together.
1332///
1333/// This occurs for code like:
1334/// \code
1335/// \#define FOO <a/b.h>
1336/// \#include FOO
1337/// \endcode
Chris Lattnerf64b3522008-03-09 01:54:53 +00001338/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1339///
1340/// This code concatenates and consumes tokens up to the '>' token. It returns
1341/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001342/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001343bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001344 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001345 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001346 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001347
John Thompsonb5353522009-10-30 13:49:06 +00001348 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001349 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001350 End = CurTok.getLocation();
1351
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001352 // FIXME: Provide code completion for #includes.
1353 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001354 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001355 Lex(CurTok);
1356 continue;
1357 }
1358
Chris Lattnerf64b3522008-03-09 01:54:53 +00001359 // Append the spelling of this token to the buffer. If there was a space
1360 // before it, add it now.
1361 if (CurTok.hasLeadingSpace())
1362 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001363
Chris Lattnerf64b3522008-03-09 01:54:53 +00001364 // Get the spelling of the token, directly into FilenameBuffer if possible.
1365 unsigned PreAppendSize = FilenameBuffer.size();
1366 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattnerf64b3522008-03-09 01:54:53 +00001368 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001369 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattnerf64b3522008-03-09 01:54:53 +00001371 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1372 if (BufPtr != &FilenameBuffer[PreAppendSize])
1373 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattnerf64b3522008-03-09 01:54:53 +00001375 // Resize FilenameBuffer to the correct size.
1376 if (CurTok.getLength() != ActualLen)
1377 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattnerf64b3522008-03-09 01:54:53 +00001379 // If we found the '>' marker, return success.
1380 if (CurTok.is(tok::greater))
1381 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001382
John Thompsonb5353522009-10-30 13:49:06 +00001383 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001384 }
1385
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001386 // If we hit the eod marker, emit an error and return true so that the caller
1387 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001388 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001389 return true;
1390}
1391
James Dennettf6333ac2012-06-22 05:46:07 +00001392/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1393/// the file to be included from the lexer, then include it! This is a common
1394/// routine with functionality shared between \#include, \#include_next and
1395/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001396/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001397void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1398 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001399 const DirectoryLookup *LookupFrom,
1400 bool isImport) {
1401
1402 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001403 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Chris Lattnerf64b3522008-03-09 01:54:53 +00001405 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001406 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001407 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001408 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001409 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001410
Chris Lattnerf64b3522008-03-09 01:54:53 +00001411 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001412 case tok::eod:
1413 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001414 return;
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattnerf64b3522008-03-09 01:54:53 +00001416 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001417 case tok::string_literal:
1418 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001419 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001420 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001421 break;
Mike Stump11289f42009-09-09 15:08:12 +00001422
Chris Lattnerf64b3522008-03-09 01:54:53 +00001423 case tok::less:
1424 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1425 // case, glue the tokens together into FilenameBuffer and interpret those.
1426 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001427 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001428 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001429 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001430 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001431 break;
1432 default:
1433 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1434 DiscardUntilEndOfDirective();
1435 return;
1436 }
Mike Stump11289f42009-09-09 15:08:12 +00001437
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001438 CharSourceRange FilenameRange
1439 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001440 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001441 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001442 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001443 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1444 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001445 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001446 DiscardUntilEndOfDirective();
1447 return;
1448 }
Mike Stump11289f42009-09-09 15:08:12 +00001449
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001450 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001451 // we allow macros that expand to nothing after the filename, because this
1452 // falls into the category of "#include pp-tokens new-line" specified in
1453 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001454 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001455
1456 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001457 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1458 Diag(FilenameTok, diag::err_pp_include_too_deep);
1459 return;
1460 }
Mike Stump11289f42009-09-09 15:08:12 +00001461
John McCall32f5fe12011-09-30 05:12:12 +00001462 // Complain about attempts to #include files in an audit pragma.
1463 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1464 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1465 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1466
1467 // Immediately leave the pragma.
1468 PragmaARCCFCodeAuditedLoc = SourceLocation();
1469 }
1470
Aaron Ballman611306e2012-03-02 22:51:54 +00001471 if (HeaderInfo.HasIncludeAliasMap()) {
1472 // Map the filename with the brackets still attached. If the name doesn't
1473 // map to anything, fall back on the filename we've already gotten the
1474 // spelling for.
1475 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1476 if (!NewName.empty())
1477 Filename = NewName;
1478 }
1479
Chris Lattnerf64b3522008-03-09 01:54:53 +00001480 // Search include directories.
1481 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001482 SmallString<1024> SearchPath;
1483 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001484 // We get the raw path only if we have 'Callbacks' to which we later pass
1485 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001486 ModuleMap::KnownHeader SuggestedModule;
1487 SourceLocation FilenameLoc = FilenameTok.getLocation();
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001488 const FileEntry *File = LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001489 FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001490 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001491 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001492
Douglas Gregor11729f02011-11-30 18:12:06 +00001493 if (Callbacks) {
1494 if (!File) {
1495 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001496 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001497 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1498 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1499 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001500 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001501 HeaderInfo.AddSearchPath(DL, isAngled);
1502
1503 // Try the lookup again, skipping the cache.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001504 File = LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001505 0, 0, HeaderInfo.getHeaderSearchOpts().ModuleMaps
1506 ? &SuggestedModule
1507 : 0,
1508 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001509 }
1510 }
1511 }
1512
Daniel Jasper07e6c402013-08-05 20:26:17 +00001513 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001514 // Notify the callback object that we've seen an inclusion directive.
1515 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1516 FilenameRange, File,
1517 SearchPath, RelativePath,
1518 /*ImportedModule=*/0);
1519 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001520 }
1521
1522 if (File == 0) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001523 if (!SuppressIncludeNotFoundError) {
1524 // If the file could not be located and it was included via angle
1525 // brackets, we can attempt a lookup as though it were a quoted path to
1526 // provide the user with a possible fixit.
1527 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001528 File = LookupFile(
1529 FilenameLoc, Filename, false, LookupFrom, CurDir,
1530 Callbacks ? &SearchPath : 0, Callbacks ? &RelativePath : 0,
1531 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001532 if (File) {
1533 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1534 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1535 Filename <<
1536 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1537 }
1538 }
1539 // If the file is still not found, just go with the vanilla diagnostic
1540 if (!File)
1541 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1542 }
1543 if (!File)
1544 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001545 }
1546
Douglas Gregor97eec242011-09-15 22:00:41 +00001547 // If we are supposed to import a module rather than including the header,
1548 // do so now.
Daniel Jasper07e6c402013-08-05 20:26:17 +00001549 if (SuggestedModule && getLangOpts().Modules) {
Douglas Gregor71944202011-11-30 00:36:36 +00001550 // Compute the module access path corresponding to this module.
1551 // FIXME: Should we have a second loadModule() overload to avoid this
1552 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001553 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001554 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001555 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1556 FilenameTok.getLocation()));
1557 std::reverse(Path.begin(), Path.end());
1558
Douglas Gregor41e115a2011-11-30 18:02:36 +00001559 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001560 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001561 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1562 if (I)
1563 PathString += '.';
1564 PathString += Path[I].first->getName();
1565 }
1566 int IncludeKind = 0;
1567
1568 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1569 case tok::pp_include:
1570 IncludeKind = 0;
1571 break;
1572
1573 case tok::pp_import:
1574 IncludeKind = 1;
1575 break;
1576
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001577 case tok::pp_include_next:
1578 IncludeKind = 2;
1579 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001580
1581 case tok::pp___include_macros:
1582 IncludeKind = 3;
1583 break;
1584
1585 default:
1586 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001587 }
1588
Douglas Gregor2537a362011-12-08 17:01:29 +00001589 // Determine whether we are actually building the module that this
1590 // include directive maps to.
1591 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 = Path[0].first->getName() == getLangOpts().CurrentModule;
Douglas Gregor2537a362011-12-08 17:01:29 +00001593
David Blaikiebbafb8a2012-03-11 07:00:24 +00001594 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001595 // If we're not building the imported module, warn that we're going
1596 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001597 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001598 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1599 /*IsTokenRange=*/false);
1600 Diag(HashLoc, diag::warn_auto_module_import)
1601 << IncludeKind << PathString
1602 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001603 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001604 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001605
Douglas Gregor71944202011-11-30 00:36:36 +00001606 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001607 // If this was an #__include_macros directive, only make macros visible.
1608 Module::NameVisibilityKind Visibility
1609 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001610 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001611 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1612 /*IsIncludeDirective=*/true);
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001613 assert((Imported == 0 || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001614 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001615
1616 if (!Imported && hadModuleLoaderFatalFailure()) {
1617 // With a fatal failure in the module loader, we abort parsing.
1618 Token &Result = IncludeTok;
1619 if (CurLexer) {
1620 Result.startToken();
1621 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1622 CurLexer->cutOffLexing();
1623 } else {
1624 assert(CurPTHLexer && "#include but no current lexer set!");
1625 CurPTHLexer->getEOF(Result);
1626 }
1627 return;
1628 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001629
1630 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001631 if (!BuildingImportedModule && Imported) {
1632 if (Callbacks) {
1633 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1634 FilenameRange, File,
1635 SearchPath, RelativePath, Imported);
1636 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001637 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001638 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001639
1640 // If we failed to find a submodule that we expected to find, we can
1641 // continue. Otherwise, there's an error in the included file, so we
1642 // don't want to include it.
1643 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1644 return;
1645 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001646 }
1647
1648 if (Callbacks && SuggestedModule) {
1649 // We didn't notify the callback object that we've seen an inclusion
1650 // directive before. Now that we are parsing the include normally and not
1651 // turning it to a module import, notify the callback object.
1652 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1653 FilenameRange, File,
1654 SearchPath, RelativePath,
1655 /*ImportedModule=*/0);
Douglas Gregor97eec242011-09-15 22:00:41 +00001656 }
1657
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001658 // The #included file will be considered to be a system header if either it is
1659 // in a system include directory, or if the #includer is a system include
1660 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001661 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001662 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001663 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001664
Chris Lattner72286d62010-04-19 20:44:31 +00001665 // Ask HeaderInfo if we should enter this #include file. If not, #including
1666 // this file will have no effect.
1667 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001668 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001669 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001670 return;
1671 }
1672
Chris Lattnerf64b3522008-03-09 01:54:53 +00001673 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001674 SourceLocation IncludePos = End;
1675 // If the filename string was the result of macro expansions, set the include
1676 // position on the file where it will be included and after the expansions.
1677 if (IncludePos.isMacroID())
1678 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1679 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001680 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681
1682 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001683 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684}
1685
James Dennettf6333ac2012-06-22 05:46:07 +00001686/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001688void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1689 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001690 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 // #include_next is like #include, except that we start searching after
1693 // the current found directory. If we can't do this, issue a
1694 // diagnostic.
1695 const DirectoryLookup *Lookup = CurDirLookup;
1696 if (isInPrimaryFile()) {
1697 Lookup = 0;
1698 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1699 } else if (Lookup == 0) {
1700 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1701 } else {
1702 // Start looking up in the next directory.
1703 ++Lookup;
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Douglas Gregor796d76a2010-10-20 22:00:55 +00001706 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001707}
1708
James Dennettf6333ac2012-06-22 05:46:07 +00001709/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001710void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1711 // The Microsoft #import directive takes a type library and generates header
1712 // files from it, and includes those. This is beyond the scope of what clang
1713 // does, so we ignore it and error out. However, #import can optionally have
1714 // trailing attributes that span multiple lines. We're going to eat those
1715 // so we can continue processing from there.
1716 Diag(Tok, diag::err_pp_import_directive_ms );
1717
1718 // Read tokens until we get to the end of the directive. Note that the
1719 // directive can be split over multiple lines using the backslash character.
1720 DiscardUntilEndOfDirective();
1721}
1722
James Dennettf6333ac2012-06-22 05:46:07 +00001723/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001724///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001725void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1726 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001727 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
1728 if (LangOpts.MicrosoftMode)
1729 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001730 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001731 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001732 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001733}
1734
Chris Lattner58a1eb02009-04-08 18:46:40 +00001735/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1736/// pseudo directive in the predefines buffer. This handles it by sucking all
1737/// tokens through the preprocessor and discarding them (only keeping the side
1738/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001739void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1740 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001741 // This directive should only occur in the predefines buffer. If not, emit an
1742 // error and reject it.
1743 SourceLocation Loc = IncludeMacrosTok.getLocation();
1744 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1745 Diag(IncludeMacrosTok.getLocation(),
1746 diag::pp_include_macros_out_of_predefines);
1747 DiscardUntilEndOfDirective();
1748 return;
1749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
Chris Lattnere01d82b2009-04-08 20:53:24 +00001751 // Treat this as a normal #include for checking purposes. If this is
1752 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001753 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001754
Chris Lattnere01d82b2009-04-08 20:53:24 +00001755 Token TmpTok;
1756 do {
1757 Lex(TmpTok);
1758 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1759 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001760}
1761
Chris Lattnerf64b3522008-03-09 01:54:53 +00001762//===----------------------------------------------------------------------===//
1763// Preprocessor Macro Directive Handling.
1764//===----------------------------------------------------------------------===//
1765
1766/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1767/// definition has just been read. Lex the rest of the arguments and the
1768/// closing ), updating MI with what we learn. Return true if an error occurs
1769/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001770bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001771 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001772
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 while (1) {
1774 LexUnexpandedToken(Tok);
1775 switch (Tok.getKind()) {
1776 case tok::r_paren:
1777 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001778 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001779 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001780 // Otherwise we have #define FOO(A,)
1781 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1782 return true;
1783 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001784 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001785 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001786 diag::warn_cxx98_compat_variadic_macro :
1787 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001788
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001789 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1790 if (LangOpts.OpenCL) {
1791 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1792 return true;
1793 }
1794
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795 // Lex the token after the identifier.
1796 LexUnexpandedToken(Tok);
1797 if (Tok.isNot(tok::r_paren)) {
1798 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1799 return true;
1800 }
1801 // Add the __VA_ARGS__ identifier as an argument.
1802 Arguments.push_back(Ident__VA_ARGS__);
1803 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001804 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001805 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001806 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001807 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1808 return true;
1809 default:
1810 // Handle keywords and identifiers here to accept things like
1811 // #define Foo(for) for.
1812 IdentifierInfo *II = Tok.getIdentifierInfo();
1813 if (II == 0) {
1814 // #define X(1
1815 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1816 return true;
1817 }
1818
1819 // If this is already used as an argument, it is used multiple times (e.g.
1820 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001821 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001822 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001823 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001824 return true;
1825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Chris Lattnerf64b3522008-03-09 01:54:53 +00001827 // Add the argument to the macro info.
1828 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Chris Lattnerf64b3522008-03-09 01:54:53 +00001830 // Lex the token after the identifier.
1831 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001832
Chris Lattnerf64b3522008-03-09 01:54:53 +00001833 switch (Tok.getKind()) {
1834 default: // #define X(A B
1835 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1836 return true;
1837 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001838 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001839 return false;
1840 case tok::comma: // #define X(A,
1841 break;
1842 case tok::ellipsis: // #define X(A... -> GCC extension
1843 // Diagnose extension.
1844 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 // Lex the token after the identifier.
1847 LexUnexpandedToken(Tok);
1848 if (Tok.isNot(tok::r_paren)) {
1849 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1850 return true;
1851 }
Mike Stump11289f42009-09-09 15:08:12 +00001852
Chris Lattnerf64b3522008-03-09 01:54:53 +00001853 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001854 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001855 return false;
1856 }
1857 }
1858 }
1859}
1860
James Dennettf6333ac2012-06-22 05:46:07 +00001861/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001862/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001863void Preprocessor::HandleDefineDirective(Token &DefineTok,
1864 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001865 ++NumDefined;
1866
1867 Token MacroNameTok;
1868 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001869
Chris Lattnerf64b3522008-03-09 01:54:53 +00001870 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001871 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001872 return;
1873
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001874 Token LastTok = MacroNameTok;
1875
Chris Lattnerf64b3522008-03-09 01:54:53 +00001876 // If we are supposed to keep comments in #defines, reenable comment saving
1877 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001878 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001879
Chris Lattnerf64b3522008-03-09 01:54:53 +00001880 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001881 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001882
Chris Lattnerf64b3522008-03-09 01:54:53 +00001883 Token Tok;
1884 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001885
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886 // If this is a function-like macro definition, parse the argument list,
1887 // marking each of the identifiers as being used as macro arguments. Also,
1888 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001889 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001890 if (ImmediatelyAfterHeaderGuard) {
1891 // Save this macro information since it may part of a header guard.
1892 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1893 MacroNameTok.getLocation());
1894 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001895 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001896 } else if (Tok.hasLeadingSpace()) {
1897 // This is a normal token with leading space. Clear the leading space
1898 // marker on the first token to get proper expansion.
1899 Tok.clearFlag(Token::LeadingSpace);
1900 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001901 // This is a function-like macro definition. Read the argument list.
1902 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001903 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001904 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001905 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001906 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001907 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001908 DiscardUntilEndOfDirective();
1909 return;
1910 }
1911
Chris Lattner249c38b2009-04-19 18:26:34 +00001912 // If this is a definition of a variadic C99 function-like macro, not using
1913 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001914
Chris Lattner249c38b2009-04-19 18:26:34 +00001915 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1916 // This gets unpoisoned where it is allowed.
1917 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1918 if (MI->isC99Varargs())
1919 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001920
Chris Lattnerf64b3522008-03-09 01:54:53 +00001921 // Read the first token after the arg list for down below.
1922 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001923 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001924 // C99 requires whitespace between the macro definition and the body. Emit
1925 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001926 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001927 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001928 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1929 // first character of a replacement list is not a character required by
1930 // subclause 5.2.1, then there shall be white-space separation between the
1931 // identifier and the replacement list.". 5.2.1 lists this set:
1932 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1933 // is irrelevant here.
1934 bool isInvalid = false;
1935 if (Tok.is(tok::at)) // @ is not in the list above.
1936 isInvalid = true;
1937 else if (Tok.is(tok::unknown)) {
1938 // If we have an unknown token, it is something strange like "`". Since
1939 // all of valid characters would have lexed into a single character
1940 // token of some sort, we know this is not a valid case.
1941 isInvalid = true;
1942 }
1943 if (isInvalid)
1944 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1945 else
1946 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001947 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001948
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001949 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001950 LastTok = Tok;
1951
Chris Lattnerf64b3522008-03-09 01:54:53 +00001952 // Read the rest of the macro body.
1953 if (MI->isObjectLike()) {
1954 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001955 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001956 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001957 MI->AddTokenToBody(Tok);
1958 // Get the next token of the macro.
1959 LexUnexpandedToken(Tok);
1960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Chris Lattnerf64b3522008-03-09 01:54:53 +00001962 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001963 // Otherwise, read the body of a function-like macro. While we are at it,
1964 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1965 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001966 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001967 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001968
Eli Friedman14d3c792012-11-14 02:18:46 +00001969 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001970 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattnerf64b3522008-03-09 01:54:53 +00001972 // Get the next token of the macro.
1973 LexUnexpandedToken(Tok);
1974 continue;
1975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Richard Smith701a3522013-07-09 01:00:29 +00001977 // If we're in -traditional mode, then we should ignore stringification
1978 // and token pasting. Mark the tokens as unknown so as not to confuse
1979 // things.
1980 if (getLangOpts().TraditionalCPP) {
1981 Tok.setKind(tok::unknown);
1982 MI->AddTokenToBody(Tok);
1983
1984 // Get the next token of the macro.
1985 LexUnexpandedToken(Tok);
1986 continue;
1987 }
1988
Eli Friedman14d3c792012-11-14 02:18:46 +00001989 if (Tok.is(tok::hashhash)) {
1990
1991 // If we see token pasting, check if it looks like the gcc comma
1992 // pasting extension. We'll use this information to suppress
1993 // diagnostics later on.
1994
1995 // Get the next token of the macro.
1996 LexUnexpandedToken(Tok);
1997
1998 if (Tok.is(tok::eod)) {
1999 MI->AddTokenToBody(LastTok);
2000 break;
2001 }
2002
2003 unsigned NumTokens = MI->getNumTokens();
2004 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2005 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2006 MI->setHasCommaPasting();
2007
2008 // Things look ok, add the '##' and param name tokens to the macro.
2009 MI->AddTokenToBody(LastTok);
2010 MI->AddTokenToBody(Tok);
2011 LastTok = Tok;
2012
2013 // Get the next token of the macro.
2014 LexUnexpandedToken(Tok);
2015 continue;
2016 }
2017
Chris Lattnerf64b3522008-03-09 01:54:53 +00002018 // Get the next token of the macro.
2019 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattner83bd8282009-05-25 17:16:10 +00002021 // Check for a valid macro arg identifier.
2022 if (Tok.getIdentifierInfo() == 0 ||
2023 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2024
2025 // If this is assembler-with-cpp mode, we accept random gibberish after
2026 // the '#' because '#' is often a comment character. However, change
2027 // the kind of the token to tok::unknown so that the preprocessor isn't
2028 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002029 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002030 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002031 MI->AddTokenToBody(LastTok);
2032 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002033 } else {
2034 Diag(Tok, diag::err_pp_stringize_not_parameter);
2035 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Chris Lattner83bd8282009-05-25 17:16:10 +00002037 // Disable __VA_ARGS__ again.
2038 Ident__VA_ARGS__->setIsPoisoned(true);
2039 return;
2040 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
Chris Lattner83bd8282009-05-25 17:16:10 +00002043 // Things look ok, add the '#' and param name tokens to the macro.
2044 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002045 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002046 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002047
Chris Lattnerf64b3522008-03-09 01:54:53 +00002048 // Get the next token of the macro.
2049 LexUnexpandedToken(Tok);
2050 }
2051 }
Mike Stump11289f42009-09-09 15:08:12 +00002052
2053
Chris Lattnerf64b3522008-03-09 01:54:53 +00002054 // Disable __VA_ARGS__ again.
2055 Ident__VA_ARGS__->setIsPoisoned(true);
2056
Chris Lattner57540c52011-04-15 05:22:18 +00002057 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002058 // replacement list.
2059 unsigned NumTokens = MI->getNumTokens();
2060 if (NumTokens != 0) {
2061 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2062 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002063 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064 return;
2065 }
2066 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2067 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002068 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002069 return;
2070 }
2071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002073 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002074
Chris Lattnerf64b3522008-03-09 01:54:53 +00002075 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002076 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002077 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002078 // It is very common for system headers to have tons of macro redefinitions
2079 // and for warnings to be disabled in system headers. If this is the case,
2080 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002081 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002082 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002083 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002084 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002085
Richard Smith7b242542013-03-06 00:46:00 +00002086 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2087 // C++ [cpp.predefined]p4, but allow it as an extension.
2088 if (OtherMI->isBuiltinMacro())
2089 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002090 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002091 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002092 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002093 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002094 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2095 << MacroNameTok.getIdentifierInfo();
2096 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2097 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002099 if (OtherMI->isWarnIfUnused())
2100 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002103 DefMacroDirective *MD =
2104 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002105
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002106 assert(!MI->isUsed());
2107 // If we need warning for not using the macro, add its location in the
2108 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002109 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002110 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00002111 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002112 MI->setIsWarnIfUnused(true);
2113 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2114 }
2115
Chris Lattner928e9092009-04-12 01:39:54 +00002116 // If the callbacks want to know, tell them about the macro definition.
2117 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002118 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119}
2120
James Dennettf6333ac2012-06-22 05:46:07 +00002121/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002122///
2123void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2124 ++NumUndefined;
2125
2126 Token MacroNameTok;
2127 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattnerf64b3522008-03-09 01:54:53 +00002129 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002130 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002131 return;
Mike Stump11289f42009-09-09 15:08:12 +00002132
Chris Lattnerf64b3522008-03-09 01:54:53 +00002133 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002134 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002135
Chris Lattnerf64b3522008-03-09 01:54:53 +00002136 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002137 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002138 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Mike Stump11289f42009-09-09 15:08:12 +00002139
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002140 // If the callbacks want to know, tell them about the macro #undef.
2141 // Note: no matter if the macro was defined or not.
2142 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002143 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002144
Chris Lattnerf64b3522008-03-09 01:54:53 +00002145 // If the macro is not defined, this is a noop undef, just return.
2146 if (MI == 0) return;
2147
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002148 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002150
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002151 if (MI->isWarnIfUnused())
2152 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2153
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002154 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2155 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002156}
2157
2158
2159//===----------------------------------------------------------------------===//
2160// Preprocessor Conditional Directive Handling.
2161//===----------------------------------------------------------------------===//
2162
James Dennettf6333ac2012-06-22 05:46:07 +00002163/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2164/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2165/// true if any tokens have been returned or pp-directives activated before this
2166/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002167///
2168void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2169 bool ReadAnyTokensBeforeDirective) {
2170 ++NumIf;
2171 Token DirectiveTok = Result;
2172
2173 Token MacroNameTok;
2174 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002175
Chris Lattnerf64b3522008-03-09 01:54:53 +00002176 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002177 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002178 // Skip code until we get to #endif. This helps with recovery by not
2179 // emitting an error when the #endif is reached.
2180 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2181 /*Foundnonskip*/false, /*FoundElse*/false);
2182 return;
2183 }
Mike Stump11289f42009-09-09 15:08:12 +00002184
Chris Lattnerf64b3522008-03-09 01:54:53 +00002185 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002186 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002187
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002188 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002189 MacroDirective *MD = getMacroDirective(MII);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002190 MacroInfo *MI = MD ? MD->getMacroInfo() : 0;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002191
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002192 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002193 // If the start of a top-level #ifdef and if the macro is not defined,
2194 // inform MIOpt that this might be the start of a proper include guard.
2195 // Otherwise it is some other form of unknown conditional which we can't
2196 // handle.
2197 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002198 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002199 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002200 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002201 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002202 }
2203
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204 // If there is a macro, process it.
2205 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002206 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002207
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002208 if (Callbacks) {
2209 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002210 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002211 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002212 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002213 }
2214
Chris Lattnerf64b3522008-03-09 01:54:53 +00002215 // Should we include the stuff contained by this directive?
2216 if (!MI == isIfndef) {
2217 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002218 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2219 /*wasskip*/false, /*foundnonskip*/true,
2220 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002221 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002222 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002223 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002224 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002225 /*FoundElse*/false);
2226 }
2227}
2228
James Dennettf6333ac2012-06-22 05:46:07 +00002229/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002230///
2231void Preprocessor::HandleIfDirective(Token &IfToken,
2232 bool ReadAnyTokensBeforeDirective) {
2233 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002234
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002235 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002236 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002237 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2238 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2239 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002240
2241 // If this condition is equivalent to #ifndef X, and if this is the first
2242 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002243 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002244 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002245 // FIXME: Pass in the location of the macro name, not the 'if' token.
2246 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002247 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002248 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002249 }
2250
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002251 if (Callbacks)
2252 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002253 SourceRange(ConditionalBegin, ConditionalEnd),
2254 ConditionalTrue);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002255
Chris Lattnerf64b3522008-03-09 01:54:53 +00002256 // Should we include the stuff contained by this directive?
2257 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002258 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002259 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002260 /*foundnonskip*/true, /*foundelse*/false);
2261 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002262 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002263 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002264 /*FoundElse*/false);
2265 }
2266}
2267
James Dennettf6333ac2012-06-22 05:46:07 +00002268/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002269///
2270void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2271 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002272
Chris Lattnerf64b3522008-03-09 01:54:53 +00002273 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002274 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chris Lattnerf64b3522008-03-09 01:54:53 +00002276 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002277 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002278 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002279 Diag(EndifToken, diag::err_pp_endif_without_if);
2280 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattnerf64b3522008-03-09 01:54:53 +00002283 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002284 if (CurPPLexer->getConditionalStackDepth() == 0)
2285 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002286
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002287 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002288 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002289
2290 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002291 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002292}
2293
James Dennettf6333ac2012-06-22 05:46:07 +00002294/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002295///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002296void Preprocessor::HandleElseDirective(Token &Result) {
2297 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002298
Chris Lattnerf64b3522008-03-09 01:54:53 +00002299 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002300 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chris Lattnerf64b3522008-03-09 01:54:53 +00002302 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002303 if (CurPPLexer->popConditionalLevel(CI)) {
2304 Diag(Result, diag::pp_err_else_without_if);
2305 return;
2306 }
Mike Stump11289f42009-09-09 15:08:12 +00002307
Chris Lattnerf64b3522008-03-09 01:54:53 +00002308 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002309 if (CurPPLexer->getConditionalStackDepth() == 0)
2310 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002311
2312 // If this is a #else with a #else before it, report the error.
2313 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002314
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002315 if (Callbacks)
2316 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2317
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002318 // Finally, skip the rest of the contents of this block.
2319 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002320 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002321}
2322
James Dennettf6333ac2012-06-22 05:46:07 +00002323/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002324///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002325void Preprocessor::HandleElifDirective(Token &ElifToken) {
2326 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002327
Chris Lattnerf64b3522008-03-09 01:54:53 +00002328 // #elif directive in a non-skipping conditional... start skipping.
2329 // We don't care what the condition is, because we will always skip it (since
2330 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002331 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002332 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002333 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002334
2335 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002336 if (CurPPLexer->popConditionalLevel(CI)) {
2337 Diag(ElifToken, diag::pp_err_elif_without_if);
2338 return;
2339 }
Mike Stump11289f42009-09-09 15:08:12 +00002340
Chris Lattnerf64b3522008-03-09 01:54:53 +00002341 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002342 if (CurPPLexer->getConditionalStackDepth() == 0)
2343 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002344
Chris Lattnerf64b3522008-03-09 01:54:53 +00002345 // If this is a #elif with a #else before it, report the error.
2346 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002347
2348 if (Callbacks)
2349 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002350 SourceRange(ConditionalBegin, ConditionalEnd),
2351 true, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002352
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002353 // Finally, skip the rest of the contents of this block.
2354 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002355 /*FoundElse*/CI.FoundElse,
2356 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002357}