blob: 04d92b8a29111efc66c574705301fd1c7977acd7 [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//===----------------------------------------------------------------------===//
9//
10// This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000019#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor97eec242011-09-15 22:00:41 +000020#include "clang/Lex/ModuleLoader.h"
Douglas Gregorc7d65762010-09-09 22:45:38 +000021#include "clang/Lex/Pragma.h"
Chris Lattner710bb872009-11-30 04:18:44 +000022#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000024#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000026using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// Utility Methods for Preprocessor Directive Handling.
30//===----------------------------------------------------------------------===//
31
Chris Lattnerc0a585d2010-08-17 15:55:45 +000032MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000033 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000034
Ted Kremenekc8456f82010-10-19 22:15:20 +000035 if (MICache) {
36 MIChain = MICache;
37 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000038 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000039 else {
40 MIChain = BP.Allocate<MacroInfoChain>();
41 }
42
43 MIChain->Next = MIChainHead;
44 MIChain->Prev = 0;
45 if (MIChainHead)
46 MIChainHead->Prev = MIChain;
47 MIChainHead = MIChain;
48
49 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000050}
51
52MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
53 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000054 new (MI) MacroInfo(L);
55 return MI;
56}
57
Chris Lattnerc0a585d2010-08-17 15:55:45 +000058MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
59 MacroInfo *MI = AllocateMacroInfo();
60 new (MI) MacroInfo(MacroToClone, BP);
61 return MI;
62}
63
Chris Lattner666f7a42009-02-20 22:19:20 +000064/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
65/// be reused for allocating new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000066void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000067 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
68 if (MacroInfoChain *Prev = MIChain->Prev) {
69 MacroInfoChain *Next = MIChain->Next;
70 Prev->Next = Next;
71 if (Next)
72 Next->Prev = Prev;
73 }
74 else {
75 assert(MIChainHead == MIChain);
76 MIChainHead = MIChain->Next;
77 MIChainHead->Prev = 0;
78 }
79 MIChain->Next = MICache;
80 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000081
Ted Kremenekc8456f82010-10-19 22:15:20 +000082 MI->Destroy();
83}
Chris Lattner666f7a42009-02-20 22:19:20 +000084
Chris Lattnerf64b3522008-03-09 01:54:53 +000085/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000086/// current line until the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000087void Preprocessor::DiscardUntilEndOfDirective() {
88 Token Tmp;
89 do {
90 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000091 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000092 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000093}
94
Chris Lattnerf64b3522008-03-09 01:54:53 +000095/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000096/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattnerf64b3522008-03-09 01:54:53 +000097/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
98/// this is due to a a #define, 2 if #undef directive, 0 if it is something
99/// else (e.g. #ifdef).
100void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
101 // Read the token, don't allow macro expansion on it.
102 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000103
Douglas Gregor12785102010-08-24 20:21:13 +0000104 if (MacroNameTok.is(tok::code_completion)) {
105 if (CodeComplete)
106 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000107 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000108 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000109 }
110
Chris Lattnerf64b3522008-03-09 01:54:53 +0000111 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000112 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000113 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
114 return;
115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattnerf64b3522008-03-09 01:54:53 +0000117 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
118 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000119 bool Invalid = false;
120 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
121 if (Invalid)
122 return;
123
Chris Lattner77c76ae2008-12-13 20:12:40 +0000124 const IdentifierInfo &Info = Identifiers.get(Spelling);
125 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000126 // C++ 2.5p2: Alternative tokens behave the same as its primary token
127 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000128 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000129 else
130 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
131 // Fall through on error.
132 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
133 // Error if defining "defined": C99 6.10.8.4.
134 Diag(MacroNameTok, diag::err_defined_macro_name);
135 } else if (isDefineUndef && II->hasMacroDefinition() &&
136 getMacroInfo(II)->isBuiltinMacro()) {
137 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
138 if (isDefineUndef == 1)
139 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
140 else
141 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
142 } else {
143 // Okay, we got a good identifier node. Return it.
144 return;
145 }
Mike Stump11289f42009-09-09 15:08:12 +0000146
Chris Lattnerf64b3522008-03-09 01:54:53 +0000147 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000148 // token kind to tok::eod.
149 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000150 return DiscardUntilEndOfDirective();
151}
152
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000153/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
154/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000155/// true, then we consider macros that expand to zero tokens as being ok.
156void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000157 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000158 // Lex unexpanded tokens for most directives: macros might expand to zero
159 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
160 // #line) allow empty macros.
161 if (EnableMacros)
162 Lex(Tmp);
163 else
164 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000165
Chris Lattnerf64b3522008-03-09 01:54:53 +0000166 // There should be no tokens after the directive, but we allow them as an
167 // extension.
168 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
169 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000170
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000171 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000172 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000173 // or if this is a macro-style preprocessing directive, because it is more
174 // trouble than it is worth to insert /**/ and check that there is no /**/
175 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000176 FixItHint Hint;
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000177 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
178 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000179 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
180 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000181 DiscardUntilEndOfDirective();
182 }
183}
184
185
186
187/// SkipExcludedConditionalBlock - We just read a #if or related directive and
188/// decided that the subsequent tokens are in the #if'd out portion of the
189/// file. Lex the rest of the file, until we see an #endif. If
190/// FoundNonSkipPortion is true, then we have already emitted code for part of
191/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
192/// is true, then #else directives are ok, if not, then we have already seen one
193/// so a #else directive is a duplicate. When this returns, the caller can lex
194/// the first valid token.
195void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
196 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000197 bool FoundElse,
198 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000199 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000200 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000201
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000202 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000203 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000204
Ted Kremenek56572ab2008-12-12 18:34:08 +0000205 if (CurPTHLexer) {
206 PTHSkipExcludedConditionalBlock();
207 return;
208 }
Mike Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 // Enter raw mode to disable identifier lookup (and thus macro expansion),
211 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000212 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000213 Token Tok;
214 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000215 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000216
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000217 if (Tok.is(tok::code_completion)) {
218 if (CodeComplete)
219 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000220 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000221 continue;
222 }
223
Chris Lattnerf64b3522008-03-09 01:54:53 +0000224 // If this is the end of the buffer, we have an error.
225 if (Tok.is(tok::eof)) {
226 // Emit errors for each unterminated conditional on the stack, including
227 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000228 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000229 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000230 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
231 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000232 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000233 }
234
Chris Lattnerf64b3522008-03-09 01:54:53 +0000235 // Just return and let the caller lex after this #include.
236 break;
237 }
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattnerf64b3522008-03-09 01:54:53 +0000239 // If this token is not a preprocessor directive, just skip it.
240 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
241 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattnerf64b3522008-03-09 01:54:53 +0000243 // We just parsed a # character at the start of a line, so we're in
244 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000245 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000246 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000247 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattnerf64b3522008-03-09 01:54:53 +0000250 // Read the next token, the directive flavor.
251 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000252
Chris Lattnerf64b3522008-03-09 01:54:53 +0000253 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
254 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000255 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000256 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000257 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000258 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000259 continue;
260 }
261
262 // If the first letter isn't i or e, it isn't intesting to us. We know that
263 // this is safe in the face of spelling differences, because there is no way
264 // to spell an i/e in a strange way that is another letter. Skipping this
265 // allows us to avoid looking up the identifier info for #define/#undef and
266 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000267 const char *RawCharData = Tok.getRawIdentifierData();
268
Chris Lattnerf64b3522008-03-09 01:54:53 +0000269 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000270 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000271 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000272 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000273 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000274 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000275 continue;
276 }
Mike Stump11289f42009-09-09 15:08:12 +0000277
Chris Lattnerf64b3522008-03-09 01:54:53 +0000278 // Get the identifier name without trigraphs or embedded newlines. Note
279 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
280 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000281 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000283 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000284 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 } else {
286 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000287 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000289 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000290 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000291 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292 continue;
293 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000294 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000296 }
Mike Stump11289f42009-09-09 15:08:12 +0000297
Benjamin Kramer144884642009-12-31 13:32:38 +0000298 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000299 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000300 if (Sub.empty() || // "if"
301 Sub == "def" || // "ifdef"
302 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
304 // bother parsing the condition.
305 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000306 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000307 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000308 /*foundelse*/false);
309
310 if (Callbacks)
311 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000312 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000313 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000314 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000315 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000316 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000317 PPConditionalInfo CondInfo;
318 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000319 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000320 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000321 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 // If we popped the outermost skipping block, we're done skipping!
324 if (!CondInfo.WasSkipping)
325 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000326 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000327 // #else directive in a skipping conditional. If not in some other
328 // skipping conditional, and if #else hasn't already been seen, enter it
329 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000330 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 // If this is a #else with a #else before it, report the error.
333 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000334
Chris Lattnerf64b3522008-03-09 01:54:53 +0000335 // Note that we've seen a #else in this conditional.
336 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000337
Chandler Carruth540960f2011-01-03 17:40:17 +0000338 if (Callbacks)
339 Callbacks->Else();
340
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 // If the conditional is at the top level, and the #if block wasn't
342 // entered, enter the #else block now.
343 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
344 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000345 CheckEndOfDirective("else");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000346 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000347 } else {
348 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000350 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000351 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352
353 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000354 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000355 // If this is in a skipping block or if we're already handled this #if
356 // block, don't bother parsing the condition.
357 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
358 DiscardUntilEndOfDirective();
359 ShouldEnter = false;
360 } else {
361 // Restore the value of LexingRawMode so that identifiers are
362 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000363 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
364 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365 IdentifierInfo *IfNDefMacro = 0;
366 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000367 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000368 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000369 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattnerf64b3522008-03-09 01:54:53 +0000371 // If this is a #elif with a #else before it, report the error.
372 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chandler Carruth540960f2011-01-03 17:40:17 +0000374 if (Callbacks)
375 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
376
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 // If this condition is true, enter it!
378 if (ShouldEnter) {
379 CondInfo.FoundNonSkip = true;
380 break;
381 }
382 }
383 }
Mike Stump11289f42009-09-09 15:08:12 +0000384
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000385 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000387 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000388 }
389
390 // Finally, if we are out of the conditional (saw an #endif or ran off the end
391 // of the file, just stop skipping and return to lexing whatever came after
392 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000393 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000394
395 if (Callbacks) {
396 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
397 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
398 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000399}
400
Ted Kremenek56572ab2008-12-12 18:34:08 +0000401void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000402
403 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000404 assert(CurPTHLexer);
405 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000406
Ted Kremenek56572ab2008-12-12 18:34:08 +0000407 // Skip to the next '#else', '#elif', or #endif.
408 if (CurPTHLexer->SkipBlock()) {
409 // We have reached an #endif. Both the '#' and 'endif' tokens
410 // have been consumed by the PTHLexer. Just pop off the condition level.
411 PPConditionalInfo CondInfo;
412 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000413 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000414 assert(!InCond && "Can't be skipping if not in a conditional!");
415 break;
416 }
Mike Stump11289f42009-09-09 15:08:12 +0000417
Ted Kremenek56572ab2008-12-12 18:34:08 +0000418 // We have reached a '#else' or '#elif'. Lex the next token to get
419 // the directive flavor.
420 Token Tok;
421 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000422
Ted Kremenek56572ab2008-12-12 18:34:08 +0000423 // We can actually look up the IdentifierInfo here since we aren't in
424 // raw mode.
425 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
426
427 if (K == tok::pp_else) {
428 // #else: Enter the else condition. We aren't in a nested condition
429 // since we skip those. We're always in the one matching the last
430 // blocked we skipped.
431 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
432 // Note that we've seen a #else in this conditional.
433 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000434
Ted Kremenek56572ab2008-12-12 18:34:08 +0000435 // If the #if block wasn't entered then enter the #else block now.
436 if (!CondInfo.FoundNonSkip) {
437 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000438
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000439 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000440 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000441 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000442 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000443
Ted Kremenek56572ab2008-12-12 18:34:08 +0000444 break;
445 }
Mike Stump11289f42009-09-09 15:08:12 +0000446
Ted Kremenek56572ab2008-12-12 18:34:08 +0000447 // Otherwise skip this block.
448 continue;
449 }
Mike Stump11289f42009-09-09 15:08:12 +0000450
Ted Kremenek56572ab2008-12-12 18:34:08 +0000451 assert(K == tok::pp_elif);
452 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
453
454 // If this is a #elif with a #else before it, report the error.
455 if (CondInfo.FoundElse)
456 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000457
Ted Kremenek56572ab2008-12-12 18:34:08 +0000458 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000459 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000460 if (CondInfo.FoundNonSkip)
461 continue;
462
463 // Evaluate the condition of the #elif.
464 IdentifierInfo *IfNDefMacro = 0;
465 CurPTHLexer->ParsingPreprocessorDirective = true;
466 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
467 CurPTHLexer->ParsingPreprocessorDirective = false;
468
469 // If this condition is true, enter it!
470 if (ShouldEnter) {
471 CondInfo.FoundNonSkip = true;
472 break;
473 }
474
475 // Otherwise, skip this block and go to the next one.
476 continue;
477 }
478}
479
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000480/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
481/// return null on failure. isAngled indicates whether the file reference is
482/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000483const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000484 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000485 bool isAngled,
486 const DirectoryLookup *FromDir,
487 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000489 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000490 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000491 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000492 // If the header lookup mechanism may be relative to the current file, pass in
493 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000494 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000495 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000496 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000497 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattner022923a2009-02-04 19:45:07 +0000499 // If there is no file entry associated with this file, it must be the
500 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000501 // it won't be scanned for preprocessor directives. If we have the
502 // predefines buffer, resolve #include references (which come from the
503 // -include command line argument) as if they came from the main file, this
504 // affects file lookup etc.
505 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000506 FID = SourceMgr.getMainFileID();
507 CurFileEnt = SourceMgr.getFileEntryForID(FID);
508 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000509 }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000511 // Do a standard file entry lookup.
512 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000513 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000514 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000515 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000516 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000518 // Otherwise, see if this is a subframework header. If so, this is relative
519 // to one of the headers on the #include stack. Walk the list of the current
520 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000521 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000522 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000523 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000524 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000525 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000526 return FE;
527 }
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000529 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
530 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000531 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000532 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000533 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000534 if ((FE = HeaderInfo.LookupSubframeworkHeader(
535 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000536 return FE;
537 }
538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000540 // Otherwise, we really couldn't find the file.
541 return 0;
542}
543
Chris Lattnerf64b3522008-03-09 01:54:53 +0000544
545//===----------------------------------------------------------------------===//
546// Preprocessor Directive Handling.
547//===----------------------------------------------------------------------===//
548
549/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000550/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000551/// lexer/preprocessor state, and advances the lexer(s) so that the next token
552/// read is the correct one.
553void Preprocessor::HandleDirective(Token &Result) {
554 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000555
Chris Lattnerf64b3522008-03-09 01:54:53 +0000556 // We just parsed a # character at the start of a line, so we're in directive
557 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000558 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000559 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000560
Chris Lattnerf64b3522008-03-09 01:54:53 +0000561 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000562
Chris Lattnerf64b3522008-03-09 01:54:53 +0000563 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000564 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000565 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000566 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattner2d17ab72009-03-18 21:00:25 +0000568 // Save the '#' token in case we need to return it later.
569 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000570
Chris Lattnerf64b3522008-03-09 01:54:53 +0000571 // Read the next token, the directive flavor. This isn't expanded due to
572 // C99 6.10.3p8.
573 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000574
Chris Lattnerf64b3522008-03-09 01:54:53 +0000575 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
576 // #define A(x) #x
577 // A(abc
578 // #warning blah
579 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000580 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
581 // not support this for #include-like directives, since that can result in
582 // terrible diagnostics, and does not work in GCC.
583 if (InMacroArgs) {
584 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
585 switch (II->getPPKeywordID()) {
586 case tok::pp_include:
587 case tok::pp_import:
588 case tok::pp_include_next:
589 case tok::pp___include_macros:
590 Diag(Result, diag::err_embedded_include) << II->getName();
591 DiscardUntilEndOfDirective();
592 return;
593 default:
594 break;
595 }
596 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000597 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000598 }
Mike Stump11289f42009-09-09 15:08:12 +0000599
Chris Lattnerf64b3522008-03-09 01:54:53 +0000600TryAgain:
601 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000602 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000603 return; // null directive.
604 case tok::comment:
605 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
606 LexUnexpandedToken(Result);
607 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000608 case tok::code_completion:
609 if (CodeComplete)
610 CodeComplete->CodeCompleteDirective(
611 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000612 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000613 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000614 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000615 if (getLangOptions().AsmPreprocessor)
616 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000617 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000618 default:
619 IdentifierInfo *II = Result.getIdentifierInfo();
620 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000621
Chris Lattnerf64b3522008-03-09 01:54:53 +0000622 // Ask what the preprocessor keyword ID is.
623 switch (II->getPPKeywordID()) {
624 default: break;
625 // C99 6.10.1 - Conditional Inclusion.
626 case tok::pp_if:
627 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
628 case tok::pp_ifdef:
629 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
630 case tok::pp_ifndef:
631 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
632 case tok::pp_elif:
633 return HandleElifDirective(Result);
634 case tok::pp_else:
635 return HandleElseDirective(Result);
636 case tok::pp_endif:
637 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000638
Chris Lattnerf64b3522008-03-09 01:54:53 +0000639 // C99 6.10.2 - Source File Inclusion.
640 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000641 // Handle #include.
642 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000643 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000644 // Handle -imacros.
645 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattnerf64b3522008-03-09 01:54:53 +0000647 // C99 6.10.3 - Macro Replacement.
648 case tok::pp_define:
649 return HandleDefineDirective(Result);
650 case tok::pp_undef:
651 return HandleUndefDirective(Result);
652
653 // C99 6.10.4 - Line Control.
654 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000655 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000656
Chris Lattnerf64b3522008-03-09 01:54:53 +0000657 // C99 6.10.5 - Error Directive.
658 case tok::pp_error:
659 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000660
Chris Lattnerf64b3522008-03-09 01:54:53 +0000661 // C99 6.10.6 - Pragma Directive.
662 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000663 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000664
Chris Lattnerf64b3522008-03-09 01:54:53 +0000665 // GNU Extensions.
666 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000667 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000668 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000669 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000670
Chris Lattnerf64b3522008-03-09 01:54:53 +0000671 case tok::pp_warning:
672 Diag(Result, diag::ext_pp_warning_directive);
673 return HandleUserDiagnosticDirective(Result, true);
674 case tok::pp_ident:
675 return HandleIdentSCCSDirective(Result);
676 case tok::pp_sccs:
677 return HandleIdentSCCSDirective(Result);
678 case tok::pp_assert:
679 //isExtension = true; // FIXME: implement #assert
680 break;
681 case tok::pp_unassert:
682 //isExtension = true; // FIXME: implement #unassert
683 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000684
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000685 case tok::pp_public:
686 if (getLangOptions().Modules)
687 return HandleMacroPublicDirective(Result);
688 break;
689
690 case tok::pp_private:
691 if (getLangOptions().Modules)
692 return HandleMacroPrivateDirective(Result);
693 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000694 }
695 break;
696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner2d17ab72009-03-18 21:00:25 +0000698 // If this is a .S file, treat unknown # directives as non-preprocessor
699 // directives. This is important because # may be a comment or introduce
700 // various pseudo-ops. Just return the # token and push back the following
701 // token to be lexed next time.
702 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000703 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000704 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000705 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000706 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000707
708 // If the second token is a hashhash token, then we need to translate it to
709 // unknown so the token lexer doesn't try to perform token pasting.
710 if (Result.is(tok::hashhash))
711 Toks[1].setKind(tok::unknown);
712
Chris Lattner2d17ab72009-03-18 21:00:25 +0000713 // Enter this token stream so that we re-lex the tokens. Make sure to
714 // enable macro expansion, in case the token after the # is an identifier
715 // that is expanded.
716 EnterTokenStream(Toks, 2, false, true);
717 return;
718 }
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattnerf64b3522008-03-09 01:54:53 +0000720 // If we reached here, the preprocessing token is not valid!
721 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000722
Chris Lattnerf64b3522008-03-09 01:54:53 +0000723 // Read the rest of the PP line.
724 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000725
Chris Lattnerf64b3522008-03-09 01:54:53 +0000726 // Okay, we're done parsing the directive.
727}
728
Chris Lattner76e68962009-01-26 06:19:46 +0000729/// GetLineValue - Convert a numeric token into an unsigned value, emitting
730/// Diagnostic DiagID if it is invalid, and returning the value in Val.
731static bool GetLineValue(Token &DigitTok, unsigned &Val,
732 unsigned DiagID, Preprocessor &PP) {
733 if (DigitTok.isNot(tok::numeric_constant)) {
734 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000735
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000736 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000737 PP.DiscardUntilEndOfDirective();
738 return true;
739 }
Mike Stump11289f42009-09-09 15:08:12 +0000740
Chris Lattner76e68962009-01-26 06:19:46 +0000741 llvm::SmallString<64> IntegerBuffer;
742 IntegerBuffer.resize(DigitTok.getLength());
743 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000744 bool Invalid = false;
745 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
746 if (Invalid)
747 return true;
748
Chris Lattnerd66f1722009-04-18 18:35:15 +0000749 // Verify that we have a simple digit-sequence, and compute the value. This
750 // is always a simple digit string computed in decimal, so we do this manually
751 // here.
752 Val = 0;
753 for (unsigned i = 0; i != ActualLength; ++i) {
754 if (!isdigit(DigitTokBegin[i])) {
755 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
756 diag::err_pp_line_digit_sequence);
757 PP.DiscardUntilEndOfDirective();
758 return true;
759 }
Mike Stump11289f42009-09-09 15:08:12 +0000760
Chris Lattnerd66f1722009-04-18 18:35:15 +0000761 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
762 if (NextVal < Val) { // overflow.
763 PP.Diag(DigitTok, DiagID);
764 PP.DiscardUntilEndOfDirective();
765 return true;
766 }
767 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
770 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000771 if (Val == 0) {
772 PP.Diag(DigitTok, DiagID);
773 PP.DiscardUntilEndOfDirective();
774 return true;
775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Chris Lattnerd66f1722009-04-18 18:35:15 +0000777 if (DigitTokBegin[0] == '0')
778 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattner76e68962009-01-26 06:19:46 +0000780 return false;
781}
782
Mike Stump11289f42009-09-09 15:08:12 +0000783/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000784/// acceptable forms are:
785/// # line digit-sequence
786/// # line digit-sequence "s-char-sequence"
787void Preprocessor::HandleLineDirective(Token &Tok) {
788 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
789 // expanded.
790 Token DigitTok;
791 Lex(DigitTok);
792
Chris Lattner100c65e2009-01-26 05:29:08 +0000793 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000794 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000795 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000796 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000797
Chris Lattner76e68962009-01-26 06:19:46 +0000798 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
799 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000800 unsigned LineLimit = 32768U;
801 if (Features.C99 || Features.CPlusPlus0x)
802 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000803 if (LineNo >= LineLimit)
804 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smithacd4d3d2011-10-15 01:18:56 +0000805 else if (Features.CPlusPlus0x && LineNo >= 32768U)
806 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000807
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000808 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000809 Token StrTok;
810 Lex(StrTok);
811
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000812 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
813 // string followed by eod.
814 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000815 ; // ok
816 else if (StrTok.isNot(tok::string_literal)) {
817 Diag(StrTok, diag::err_pp_line_invalid_filename);
818 DiscardUntilEndOfDirective();
819 return;
820 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000821 // Parse and validate the string, converting it into a unique ID.
822 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000823 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000824 if (Literal.hadError)
825 return DiscardUntilEndOfDirective();
826 if (Literal.Pascal) {
827 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
828 return DiscardUntilEndOfDirective();
829 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000830 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000831
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000832 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000833 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
834 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000835 }
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000837 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattner839150e2009-03-27 17:13:49 +0000839 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000840 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
841 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000842 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000843}
844
Chris Lattner76e68962009-01-26 06:19:46 +0000845/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
846/// marker directive.
847static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
848 bool &IsSystemHeader, bool &IsExternCHeader,
849 Preprocessor &PP) {
850 unsigned FlagVal;
851 Token FlagTok;
852 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000853 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000854 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
855 return true;
856
857 if (FlagVal == 1) {
858 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Chris Lattner76e68962009-01-26 06:19:46 +0000860 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000861 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000862 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
863 return true;
864 } else if (FlagVal == 2) {
865 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattner1c967782009-02-04 06:25:26 +0000867 SourceManager &SM = PP.getSourceManager();
868 // If we are leaving the current presumed file, check to make sure the
869 // presumed include stack isn't empty!
870 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000871 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000872 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000873 if (PLoc.isInvalid())
874 return true;
875
Chris Lattner1c967782009-02-04 06:25:26 +0000876 // If there is no include loc (main file) or if the include loc is in a
877 // different physical file, then we aren't in a "1" line marker flag region.
878 SourceLocation IncLoc = PLoc.getIncludeLoc();
879 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000880 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000881 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
882 PP.DiscardUntilEndOfDirective();
883 return true;
884 }
Mike Stump11289f42009-09-09 15:08:12 +0000885
Chris Lattner76e68962009-01-26 06:19:46 +0000886 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000887 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000888 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
889 return true;
890 }
891
892 // We must have 3 if there are still flags.
893 if (FlagVal != 3) {
894 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000895 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000896 return true;
897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Chris Lattner76e68962009-01-26 06:19:46 +0000899 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattner76e68962009-01-26 06:19:46 +0000901 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000902 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000903 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000904 return true;
905
906 // We must have 4 if there is yet another flag.
907 if (FlagVal != 4) {
908 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000909 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000910 return true;
911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattner76e68962009-01-26 06:19:46 +0000913 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000914
Chris Lattner76e68962009-01-26 06:19:46 +0000915 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000916 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000917
918 // There are no more valid flags here.
919 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000920 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000921 return true;
922}
923
924/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
925/// one of the following forms:
926///
927/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000928/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000929/// # 42 "file" ('1' | '2')? '3' '4'?
930///
931void Preprocessor::HandleDigitDirective(Token &DigitTok) {
932 // Validate the number and convert it to an unsigned. GNU does not have a
933 // line # limit other than it fit in 32-bits.
934 unsigned LineNo;
935 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
936 *this))
937 return;
Mike Stump11289f42009-09-09 15:08:12 +0000938
Chris Lattner76e68962009-01-26 06:19:46 +0000939 Token StrTok;
940 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner76e68962009-01-26 06:19:46 +0000942 bool IsFileEntry = false, IsFileExit = false;
943 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000944 int FilenameID = -1;
945
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000946 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
947 // string followed by eod.
948 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000949 ; // ok
950 else if (StrTok.isNot(tok::string_literal)) {
951 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000952 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000953 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000954 // Parse and validate the string, converting it into a unique ID.
955 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000956 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000957 if (Literal.hadError)
958 return DiscardUntilEndOfDirective();
959 if (Literal.Pascal) {
960 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
961 return DiscardUntilEndOfDirective();
962 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000963 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000964
Chris Lattner76e68962009-01-26 06:19:46 +0000965 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000966 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000967 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000968 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000969 }
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000971 // Create a line note with this information.
972 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000973 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000974 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Chris Lattner839150e2009-03-27 17:13:49 +0000976 // If the preprocessor has callbacks installed, notify them of the #line
977 // change. This is used so that the line marker comes out in -E mode for
978 // example.
979 if (Callbacks) {
980 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
981 if (IsFileEntry)
982 Reason = PPCallbacks::EnterFile;
983 else if (IsFileExit)
984 Reason = PPCallbacks::ExitFile;
985 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
986 if (IsExternCHeader)
987 FileKind = SrcMgr::C_ExternCSystem;
988 else if (IsSystemHeader)
989 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000990
Chris Lattnerc745cec2010-04-14 04:28:50 +0000991 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000992 }
Chris Lattner76e68962009-01-26 06:19:46 +0000993}
994
995
Chris Lattner38d7fd22009-01-26 05:30:54 +0000996/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
997///
Mike Stump11289f42009-09-09 15:08:12 +0000998void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000999 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001000 // PTH doesn't emit #warning or #error directives.
1001 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001002 return CurPTHLexer->DiscardToEndOfLine();
1003
Chris Lattnerf64b3522008-03-09 01:54:53 +00001004 // Read the rest of the line raw. We do this because we don't want macros
1005 // to be expanded and we don't require that the tokens be valid preprocessing
1006 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1007 // collapse multiple consequtive white space between tokens, but this isn't
1008 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +00001009 std::string Message = CurLexer->ReadToEndOfLine();
1010 if (isWarning)
1011 Diag(Tok, diag::pp_hash_warning) << Message;
1012 else
1013 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001014}
1015
1016/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1017///
1018void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1019 // Yes, this directive is an extension.
1020 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001021
Chris Lattnerf64b3522008-03-09 01:54:53 +00001022 // Read the string argument.
1023 Token StrTok;
1024 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001025
Chris Lattnerf64b3522008-03-09 01:54:53 +00001026 // If the token kind isn't a string, it's a malformed directive.
1027 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001028 StrTok.isNot(tok::wide_string_literal)) {
1029 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001030 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001031 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001032 return;
1033 }
Mike Stump11289f42009-09-09 15:08:12 +00001034
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001035 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001036 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001037
Douglas Gregordc970f02010-03-16 22:30:13 +00001038 if (Callbacks) {
1039 bool Invalid = false;
1040 std::string Str = getSpelling(StrTok, &Invalid);
1041 if (!Invalid)
1042 Callbacks->Ident(Tok.getLocation(), Str);
1043 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001044}
1045
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001046/// \brief Handle a #public directive.
1047void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001048 Token MacroNameTok;
1049 ReadMacroName(MacroNameTok, 2);
1050
1051 // Error reading macro name? If so, diagnostic already issued.
1052 if (MacroNameTok.is(tok::eod))
1053 return;
1054
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001055 // Check to see if this is the last token on the #public line.
1056 CheckEndOfDirective("public");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001057
1058 // Okay, we finally have a valid identifier to undef.
1059 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1060
1061 // If the macro is not defined, this is an error.
1062 if (MI == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001063 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001064 << MacroNameTok.getIdentifierInfo();
1065 return;
1066 }
1067
1068 // Note that this macro has now been exported.
Douglas Gregorebf00492011-10-17 15:32:29 +00001069 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1070
1071 // If this macro definition came from a PCH file, mark it
1072 // as having changed since serialization.
1073 if (MI->isFromAST())
1074 MI->setChangedAfterLoad();
1075}
1076
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001077/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001078void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1079 Token MacroNameTok;
1080 ReadMacroName(MacroNameTok, 2);
1081
1082 // Error reading macro name? If so, diagnostic already issued.
1083 if (MacroNameTok.is(tok::eod))
1084 return;
1085
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001086 // Check to see if this is the last token on the #private line.
1087 CheckEndOfDirective("private");
Douglas Gregorebf00492011-10-17 15:32:29 +00001088
1089 // Okay, we finally have a valid identifier to undef.
1090 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1091
1092 // If the macro is not defined, this is an error.
1093 if (MI == 0) {
1094 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1095 << MacroNameTok.getIdentifierInfo();
1096 return;
1097 }
1098
1099 // Note that this macro has now been marked private.
1100 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001101
1102 // If this macro definition came from a PCH file, mark it
1103 // as having changed since serialization.
1104 if (MI->isFromAST())
1105 MI->setChangedAfterLoad();
1106}
1107
Chris Lattnerf64b3522008-03-09 01:54:53 +00001108//===----------------------------------------------------------------------===//
1109// Preprocessor Include Directive Handling.
1110//===----------------------------------------------------------------------===//
1111
1112/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1113/// checked and spelled filename, e.g. as an operand of #include. This returns
1114/// true if the input filename was in <>'s or false if it were in ""'s. The
1115/// caller is expected to provide a buffer that is large enough to hold the
1116/// spelling of the filename, but is also expected to handle the case when
1117/// this method decides to use a different buffer.
1118bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001119 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001120 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001121 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001122
Chris Lattnerf64b3522008-03-09 01:54:53 +00001123 // Make sure the filename is <x> or "x".
1124 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001125 if (Buffer[0] == '<') {
1126 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001127 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001128 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001129 return true;
1130 }
1131 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001132 } else if (Buffer[0] == '"') {
1133 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001134 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001135 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001136 return true;
1137 }
1138 isAngled = false;
1139 } else {
1140 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001141 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001142 return true;
1143 }
Mike Stump11289f42009-09-09 15:08:12 +00001144
Chris Lattnerf64b3522008-03-09 01:54:53 +00001145 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001146 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001147 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001148 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001149 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001150 }
Mike Stump11289f42009-09-09 15:08:12 +00001151
Chris Lattnerf64b3522008-03-09 01:54:53 +00001152 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001153 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001154 return isAngled;
1155}
1156
1157/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1158/// from a macro as multiple tokens, which need to be glued together. This
1159/// occurs for code like:
1160/// #define FOO <a/b.h>
1161/// #include FOO
1162/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1163///
1164/// This code concatenates and consumes tokens up to the '>' token. It returns
1165/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001166/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001167bool Preprocessor::ConcatenateIncludeName(
Douglas Gregor796d76a2010-10-20 22:00:55 +00001168 llvm::SmallString<128> &FilenameBuffer,
1169 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001170 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001171
John Thompsonb5353522009-10-30 13:49:06 +00001172 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001173 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001174 End = CurTok.getLocation();
1175
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001176 // FIXME: Provide code completion for #includes.
1177 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001178 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001179 Lex(CurTok);
1180 continue;
1181 }
1182
Chris Lattnerf64b3522008-03-09 01:54:53 +00001183 // Append the spelling of this token to the buffer. If there was a space
1184 // before it, add it now.
1185 if (CurTok.hasLeadingSpace())
1186 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001187
Chris Lattnerf64b3522008-03-09 01:54:53 +00001188 // Get the spelling of the token, directly into FilenameBuffer if possible.
1189 unsigned PreAppendSize = FilenameBuffer.size();
1190 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001191
Chris Lattnerf64b3522008-03-09 01:54:53 +00001192 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001193 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattnerf64b3522008-03-09 01:54:53 +00001195 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1196 if (BufPtr != &FilenameBuffer[PreAppendSize])
1197 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001198
Chris Lattnerf64b3522008-03-09 01:54:53 +00001199 // Resize FilenameBuffer to the correct size.
1200 if (CurTok.getLength() != ActualLen)
1201 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001202
Chris Lattnerf64b3522008-03-09 01:54:53 +00001203 // If we found the '>' marker, return success.
1204 if (CurTok.is(tok::greater))
1205 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001206
John Thompsonb5353522009-10-30 13:49:06 +00001207 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001208 }
1209
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001210 // If we hit the eod marker, emit an error and return true so that the caller
1211 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001212 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001213 return true;
1214}
1215
1216/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1217/// file to be included from the lexer, then include it! This is a common
1218/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001219/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001220/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001221void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1222 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001223 const DirectoryLookup *LookupFrom,
1224 bool isImport) {
1225
1226 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001227 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001228
Chris Lattnerf64b3522008-03-09 01:54:53 +00001229 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001230 llvm::SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001231 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001232 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001233 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001234
Chris Lattnerf64b3522008-03-09 01:54:53 +00001235 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001236 case tok::eod:
1237 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001238 return;
Mike Stump11289f42009-09-09 15:08:12 +00001239
Chris Lattnerf64b3522008-03-09 01:54:53 +00001240 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001241 case tok::string_literal:
1242 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001243 End = FilenameTok.getLocation();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001244 CharEnd = End.getLocWithOffset(Filename.size());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001245 break;
Mike Stump11289f42009-09-09 15:08:12 +00001246
Chris Lattnerf64b3522008-03-09 01:54:53 +00001247 case tok::less:
1248 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1249 // case, glue the tokens together into FilenameBuffer and interpret those.
1250 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001251 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001252 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001253 Filename = FilenameBuffer.str();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001254 CharEnd = getLocForEndOfToken(End);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001255 break;
1256 default:
1257 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1258 DiscardUntilEndOfDirective();
1259 return;
1260 }
Mike Stump11289f42009-09-09 15:08:12 +00001261
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001262 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001263 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001264 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1265 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001266 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001267 DiscardUntilEndOfDirective();
1268 return;
1269 }
Mike Stump11289f42009-09-09 15:08:12 +00001270
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001271 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001272 // we allow macros that expand to nothing after the filename, because this
1273 // falls into the category of "#include pp-tokens new-line" specified in
1274 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001275 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001276
1277 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001278 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1279 Diag(FilenameTok, diag::err_pp_include_too_deep);
1280 return;
1281 }
Mike Stump11289f42009-09-09 15:08:12 +00001282
John McCall32f5fe12011-09-30 05:12:12 +00001283 // Complain about attempts to #include files in an audit pragma.
1284 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1285 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1286 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1287
1288 // Immediately leave the pragma.
1289 PragmaARCCFCodeAuditedLoc = SourceLocation();
1290 }
1291
Chris Lattnerf64b3522008-03-09 01:54:53 +00001292 // Search include directories.
1293 const DirectoryLookup *CurDir;
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001294 llvm::SmallString<1024> SearchPath;
1295 llvm::SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001296 // We get the raw path only if we have 'Callbacks' to which we later pass
1297 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001298 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001299 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001300 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001301 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
Douglas Gregorad01b312012-01-03 17:07:34 +00001302 getLangOptions().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001303
Douglas Gregor11729f02011-11-30 18:12:06 +00001304 if (Callbacks) {
1305 if (!File) {
1306 // Give the clients a chance to recover.
1307 llvm::SmallString<128> RecoveryPath;
1308 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1309 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1310 // Add the recovery path to the list of search paths.
1311 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1312 HeaderInfo.AddSearchPath(DL, isAngled);
1313
1314 // Try the lookup again, skipping the cache.
1315 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
Douglas Gregorad01b312012-01-03 17:07:34 +00001316 getLangOptions().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001317 /*SkipCache*/true);
1318 }
1319 }
1320 }
1321
1322 // Notify the callback object that we've seen an inclusion directive.
1323 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1324 End, SearchPath, RelativePath);
1325 }
1326
1327 if (File == 0) {
1328 if (!SuppressIncludeNotFoundError)
1329 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1330 return;
1331 }
1332
Douglas Gregor97eec242011-09-15 22:00:41 +00001333 // If we are supposed to import a module rather than including the header,
1334 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001335 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001336 // Compute the module access path corresponding to this module.
1337 // FIXME: Should we have a second loadModule() overload to avoid this
1338 // extra lookup step?
1339 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001340 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001341 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1342 FilenameTok.getLocation()));
1343 std::reverse(Path.begin(), Path.end());
1344
Douglas Gregor41e115a2011-11-30 18:02:36 +00001345 // Warn that we're replacing the include/import with a module import.
1346 llvm::SmallString<128> PathString;
1347 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1348 if (I)
1349 PathString += '.';
1350 PathString += Path[I].first->getName();
1351 }
1352 int IncludeKind = 0;
1353
1354 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1355 case tok::pp_include:
1356 IncludeKind = 0;
1357 break;
1358
1359 case tok::pp_import:
1360 IncludeKind = 1;
1361 break;
1362
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001363 case tok::pp_include_next:
1364 IncludeKind = 2;
1365 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001366
1367 case tok::pp___include_macros:
1368 IncludeKind = 3;
1369 break;
1370
1371 default:
1372 llvm_unreachable("unknown include directive kind");
1373 break;
1374 }
1375
Douglas Gregor2537a362011-12-08 17:01:29 +00001376 // Determine whether we are actually building the module that this
1377 // include directive maps to.
1378 bool BuildingImportedModule
1379 = Path[0].first->getName() == getLangOptions().CurrentModule;
1380
1381 if (!BuildingImportedModule) {
1382 // If we're not building the imported module, warn that we're going
1383 // to automatically turn this inclusion directive into a module import.
1384 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1385 /*IsTokenRange=*/false);
1386 Diag(HashLoc, diag::warn_auto_module_import)
1387 << IncludeKind << PathString
1388 << FixItHint::CreateReplacement(ReplaceRange,
1389 "__import_module__ " + PathString.str().str() + ";");
1390 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001391
Douglas Gregor71944202011-11-30 00:36:36 +00001392 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001393 // If this was an #__include_macros directive, only make macros visible.
1394 Module::NameVisibilityKind Visibility
1395 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor98a52db2011-12-20 00:28:52 +00001396 Module *Imported
1397 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1398 /*IsIncludeDirective=*/true);
Douglas Gregor2537a362011-12-08 17:01:29 +00001399
1400 // If this header isn't part of the module we're building, we're done.
Douglas Gregor98a52db2011-12-20 00:28:52 +00001401 if (!BuildingImportedModule && Imported)
Douglas Gregor2537a362011-12-08 17:01:29 +00001402 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001403 }
1404
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001405 // The #included file will be considered to be a system header if either it is
1406 // in a system include directory, or if the #includer is a system include
1407 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001408 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001409 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001410 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001411
Chris Lattner72286d62010-04-19 20:44:31 +00001412 // Ask HeaderInfo if we should enter this #include file. If not, #including
1413 // this file will have no effect.
1414 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001415 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001416 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001417 return;
1418 }
1419
Chris Lattnerf64b3522008-03-09 01:54:53 +00001420 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001421 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1422 FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001423 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001424
1425 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001426 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001427}
1428
1429/// HandleIncludeNextDirective - Implements #include_next.
1430///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001431void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1432 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001433 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001434
Chris Lattnerf64b3522008-03-09 01:54:53 +00001435 // #include_next is like #include, except that we start searching after
1436 // the current found directory. If we can't do this, issue a
1437 // diagnostic.
1438 const DirectoryLookup *Lookup = CurDirLookup;
1439 if (isInPrimaryFile()) {
1440 Lookup = 0;
1441 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1442 } else if (Lookup == 0) {
1443 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1444 } else {
1445 // Start looking up in the next directory.
1446 ++Lookup;
1447 }
Mike Stump11289f42009-09-09 15:08:12 +00001448
Douglas Gregor796d76a2010-10-20 22:00:55 +00001449 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001450}
1451
1452/// HandleImportDirective - Implements #import.
1453///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001454void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1455 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001456 if (!Features.ObjC1) // #import is standard for ObjC.
1457 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001458
Douglas Gregor796d76a2010-10-20 22:00:55 +00001459 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001460}
1461
Chris Lattner58a1eb02009-04-08 18:46:40 +00001462/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1463/// pseudo directive in the predefines buffer. This handles it by sucking all
1464/// tokens through the preprocessor and discarding them (only keeping the side
1465/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001466void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1467 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001468 // This directive should only occur in the predefines buffer. If not, emit an
1469 // error and reject it.
1470 SourceLocation Loc = IncludeMacrosTok.getLocation();
1471 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1472 Diag(IncludeMacrosTok.getLocation(),
1473 diag::pp_include_macros_out_of_predefines);
1474 DiscardUntilEndOfDirective();
1475 return;
1476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Chris Lattnere01d82b2009-04-08 20:53:24 +00001478 // Treat this as a normal #include for checking purposes. If this is
1479 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001480 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001481
Chris Lattnere01d82b2009-04-08 20:53:24 +00001482 Token TmpTok;
1483 do {
1484 Lex(TmpTok);
1485 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1486 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001487}
1488
Chris Lattnerf64b3522008-03-09 01:54:53 +00001489//===----------------------------------------------------------------------===//
1490// Preprocessor Macro Directive Handling.
1491//===----------------------------------------------------------------------===//
1492
1493/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1494/// definition has just been read. Lex the rest of the arguments and the
1495/// closing ), updating MI with what we learn. Return true if an error occurs
1496/// parsing the arg list.
1497bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001498 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001499
Chris Lattnerf64b3522008-03-09 01:54:53 +00001500 Token Tok;
1501 while (1) {
1502 LexUnexpandedToken(Tok);
1503 switch (Tok.getKind()) {
1504 case tok::r_paren:
1505 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001506 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001507 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001508 // Otherwise we have #define FOO(A,)
1509 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1510 return true;
1511 case tok::ellipsis: // #define X(... -> C99 varargs
Richard Smithacd4d3d2011-10-15 01:18:56 +00001512 if (!Features.C99)
1513 Diag(Tok, Features.CPlusPlus0x ?
1514 diag::warn_cxx98_compat_variadic_macro :
1515 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001516
1517 // Lex the token after the identifier.
1518 LexUnexpandedToken(Tok);
1519 if (Tok.isNot(tok::r_paren)) {
1520 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1521 return true;
1522 }
1523 // Add the __VA_ARGS__ identifier as an argument.
1524 Arguments.push_back(Ident__VA_ARGS__);
1525 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001526 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001528 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001529 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1530 return true;
1531 default:
1532 // Handle keywords and identifiers here to accept things like
1533 // #define Foo(for) for.
1534 IdentifierInfo *II = Tok.getIdentifierInfo();
1535 if (II == 0) {
1536 // #define X(1
1537 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1538 return true;
1539 }
1540
1541 // If this is already used as an argument, it is used multiple times (e.g.
1542 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001543 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001544 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001545 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001546 return true;
1547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
Chris Lattnerf64b3522008-03-09 01:54:53 +00001549 // Add the argument to the macro info.
1550 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001551
Chris Lattnerf64b3522008-03-09 01:54:53 +00001552 // Lex the token after the identifier.
1553 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001554
Chris Lattnerf64b3522008-03-09 01:54:53 +00001555 switch (Tok.getKind()) {
1556 default: // #define X(A B
1557 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1558 return true;
1559 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001560 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001561 return false;
1562 case tok::comma: // #define X(A,
1563 break;
1564 case tok::ellipsis: // #define X(A... -> GCC extension
1565 // Diagnose extension.
1566 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001567
Chris Lattnerf64b3522008-03-09 01:54:53 +00001568 // Lex the token after the identifier.
1569 LexUnexpandedToken(Tok);
1570 if (Tok.isNot(tok::r_paren)) {
1571 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1572 return true;
1573 }
Mike Stump11289f42009-09-09 15:08:12 +00001574
Chris Lattnerf64b3522008-03-09 01:54:53 +00001575 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001576 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001577 return false;
1578 }
1579 }
1580 }
1581}
1582
1583/// HandleDefineDirective - Implements #define. This consumes the entire macro
1584/// line then lets the caller lex the next real token.
1585void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1586 ++NumDefined;
1587
1588 Token MacroNameTok;
1589 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001590
Chris Lattnerf64b3522008-03-09 01:54:53 +00001591 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001592 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001593 return;
1594
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001595 Token LastTok = MacroNameTok;
1596
Chris Lattnerf64b3522008-03-09 01:54:53 +00001597 // If we are supposed to keep comments in #defines, reenable comment saving
1598 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001599 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001600
Chris Lattnerf64b3522008-03-09 01:54:53 +00001601 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001602 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001603
Chris Lattnerf64b3522008-03-09 01:54:53 +00001604 Token Tok;
1605 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001606
Chris Lattnerf64b3522008-03-09 01:54:53 +00001607 // If this is a function-like macro definition, parse the argument list,
1608 // marking each of the identifiers as being used as macro arguments. Also,
1609 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001610 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001611 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001612 } else if (Tok.hasLeadingSpace()) {
1613 // This is a normal token with leading space. Clear the leading space
1614 // marker on the first token to get proper expansion.
1615 Tok.clearFlag(Token::LeadingSpace);
1616 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001617 // This is a function-like macro definition. Read the argument list.
1618 MI->setIsFunctionLike();
1619 if (ReadMacroDefinitionArgList(MI)) {
1620 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001621 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001622 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001623 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001624 DiscardUntilEndOfDirective();
1625 return;
1626 }
1627
Chris Lattner249c38b2009-04-19 18:26:34 +00001628 // If this is a definition of a variadic C99 function-like macro, not using
1629 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001630
Chris Lattner249c38b2009-04-19 18:26:34 +00001631 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1632 // This gets unpoisoned where it is allowed.
1633 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1634 if (MI->isC99Varargs())
1635 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001636
Chris Lattnerf64b3522008-03-09 01:54:53 +00001637 // Read the first token after the arg list for down below.
1638 LexUnexpandedToken(Tok);
Eli Friedman192e0342011-10-10 23:35:28 +00001639 } else if (Features.C99 || Features.CPlusPlus0x) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001640 // C99 requires whitespace between the macro definition and the body. Emit
1641 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001642 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001643 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001644 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1645 // first character of a replacement list is not a character required by
1646 // subclause 5.2.1, then there shall be white-space separation between the
1647 // identifier and the replacement list.". 5.2.1 lists this set:
1648 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1649 // is irrelevant here.
1650 bool isInvalid = false;
1651 if (Tok.is(tok::at)) // @ is not in the list above.
1652 isInvalid = true;
1653 else if (Tok.is(tok::unknown)) {
1654 // If we have an unknown token, it is something strange like "`". Since
1655 // all of valid characters would have lexed into a single character
1656 // token of some sort, we know this is not a valid case.
1657 isInvalid = true;
1658 }
1659 if (isInvalid)
1660 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1661 else
1662 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001663 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001664
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001665 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001666 LastTok = Tok;
1667
Chris Lattnerf64b3522008-03-09 01:54:53 +00001668 // Read the rest of the macro body.
1669 if (MI->isObjectLike()) {
1670 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001671 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001672 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001673 MI->AddTokenToBody(Tok);
1674 // Get the next token of the macro.
1675 LexUnexpandedToken(Tok);
1676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Chris Lattnerf64b3522008-03-09 01:54:53 +00001678 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001679 // Otherwise, read the body of a function-like macro. While we are at it,
1680 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1681 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001682 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001683 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684
Chris Lattnerf64b3522008-03-09 01:54:53 +00001685 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001686 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001687
Chris Lattnerf64b3522008-03-09 01:54:53 +00001688 // Get the next token of the macro.
1689 LexUnexpandedToken(Tok);
1690 continue;
1691 }
Mike Stump11289f42009-09-09 15:08:12 +00001692
Chris Lattnerf64b3522008-03-09 01:54:53 +00001693 // Get the next token of the macro.
1694 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001695
Chris Lattner83bd8282009-05-25 17:16:10 +00001696 // Check for a valid macro arg identifier.
1697 if (Tok.getIdentifierInfo() == 0 ||
1698 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1699
1700 // If this is assembler-with-cpp mode, we accept random gibberish after
1701 // the '#' because '#' is often a comment character. However, change
1702 // the kind of the token to tok::unknown so that the preprocessor isn't
1703 // confused.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001704 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001705 LastTok.setKind(tok::unknown);
1706 } else {
1707 Diag(Tok, diag::err_pp_stringize_not_parameter);
1708 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Chris Lattner83bd8282009-05-25 17:16:10 +00001710 // Disable __VA_ARGS__ again.
1711 Ident__VA_ARGS__->setIsPoisoned(true);
1712 return;
1713 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Chris Lattner83bd8282009-05-25 17:16:10 +00001716 // Things look ok, add the '#' and param name tokens to the macro.
1717 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001719 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001720
Chris Lattnerf64b3522008-03-09 01:54:53 +00001721 // Get the next token of the macro.
1722 LexUnexpandedToken(Tok);
1723 }
1724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725
1726
Chris Lattnerf64b3522008-03-09 01:54:53 +00001727 // Disable __VA_ARGS__ again.
1728 Ident__VA_ARGS__->setIsPoisoned(true);
1729
Chris Lattner57540c52011-04-15 05:22:18 +00001730 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001731 // replacement list.
1732 unsigned NumTokens = MI->getNumTokens();
1733 if (NumTokens != 0) {
1734 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1735 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001736 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001737 return;
1738 }
1739 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1740 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001741 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001742 return;
1743 }
1744 }
Mike Stump11289f42009-09-09 15:08:12 +00001745
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001746 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001747
Chris Lattnerf64b3522008-03-09 01:54:53 +00001748 // Finally, if this identifier already had a macro defined for it, verify that
1749 // the macro bodies are identical and free the old definition.
1750 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001751 // It is very common for system headers to have tons of macro redefinitions
1752 // and for warnings to be disabled in system headers. If this is the case,
1753 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001754 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001755 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001756 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001757 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001758
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001759 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001760 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001761 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001762 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001763 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1764 << MacroNameTok.getIdentifierInfo();
1765 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1766 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001767 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001768 if (OtherMI->isWarnIfUnused())
1769 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001770 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001771 }
Mike Stump11289f42009-09-09 15:08:12 +00001772
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001775 assert(!MI->isUsed());
1776 // If we need warning for not using the macro, add its location in the
1777 // warn-because-unused-macro set. If it gets used it will be removed from set.
1778 if (isInPrimaryFile() && // don't warn for include'd macros.
1779 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001780 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001781 MI->setIsWarnIfUnused(true);
1782 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1783 }
1784
Chris Lattner928e9092009-04-12 01:39:54 +00001785 // If the callbacks want to know, tell them about the macro definition.
1786 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001787 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001788}
1789
1790/// HandleUndefDirective - Implements #undef.
1791///
1792void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1793 ++NumUndefined;
1794
1795 Token MacroNameTok;
1796 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001797
Chris Lattnerf64b3522008-03-09 01:54:53 +00001798 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001799 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001800 return;
Mike Stump11289f42009-09-09 15:08:12 +00001801
Chris Lattnerf64b3522008-03-09 01:54:53 +00001802 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001803 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001804
Chris Lattnerf64b3522008-03-09 01:54:53 +00001805 // Okay, we finally have a valid identifier to undef.
1806 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001807
Chris Lattnerf64b3522008-03-09 01:54:53 +00001808 // If the macro is not defined, this is a noop undef, just return.
1809 if (MI == 0) return;
1810
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001811 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001812 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001813
1814 // If the callbacks want to know, tell them about the macro #undef.
1815 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001816 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001817
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001818 if (MI->isWarnIfUnused())
1819 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1820
Chris Lattnerf64b3522008-03-09 01:54:53 +00001821 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001822 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001823 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1824}
1825
1826
1827//===----------------------------------------------------------------------===//
1828// Preprocessor Conditional Directive Handling.
1829//===----------------------------------------------------------------------===//
1830
1831/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1832/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1833/// if any tokens have been returned or pp-directives activated before this
1834/// #ifndef has been lexed.
1835///
1836void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1837 bool ReadAnyTokensBeforeDirective) {
1838 ++NumIf;
1839 Token DirectiveTok = Result;
1840
1841 Token MacroNameTok;
1842 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattnerf64b3522008-03-09 01:54:53 +00001844 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001845 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 // Skip code until we get to #endif. This helps with recovery by not
1847 // emitting an error when the #endif is reached.
1848 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1849 /*Foundnonskip*/false, /*FoundElse*/false);
1850 return;
1851 }
Mike Stump11289f42009-09-09 15:08:12 +00001852
Chris Lattnerf64b3522008-03-09 01:54:53 +00001853 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001854 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001855
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001856 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1857 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001858
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001859 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001860 // If the start of a top-level #ifdef and if the macro is not defined,
1861 // inform MIOpt that this might be the start of a proper include guard.
1862 // Otherwise it is some other form of unknown conditional which we can't
1863 // handle.
1864 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001865 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001866 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001867 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001868 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001869 }
1870
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871 // If there is a macro, process it.
1872 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001873 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattnerf64b3522008-03-09 01:54:53 +00001875 // Should we include the stuff contained by this directive?
1876 if (!MI == isIfndef) {
1877 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001878 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1879 /*wasskip*/false, /*foundnonskip*/true,
1880 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001881 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001882 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001883 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001884 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001885 /*FoundElse*/false);
1886 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001887
1888 if (Callbacks) {
1889 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001890 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001891 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001892 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001893 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001894}
1895
1896/// HandleIfDirective - Implements the #if directive.
1897///
1898void Preprocessor::HandleIfDirective(Token &IfToken,
1899 bool ReadAnyTokensBeforeDirective) {
1900 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001901
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001902 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001903 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001904 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1905 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1906 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001907
1908 // If this condition is equivalent to #ifndef X, and if this is the first
1909 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001910 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001911 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001912 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001913 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001914 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001915 }
1916
Chris Lattnerf64b3522008-03-09 01:54:53 +00001917 // Should we include the stuff contained by this directive?
1918 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001919 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001920 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001921 /*foundnonskip*/true, /*foundelse*/false);
1922 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001923 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001924 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001925 /*FoundElse*/false);
1926 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001927
1928 if (Callbacks)
1929 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001930}
1931
1932/// HandleEndifDirective - Implements the #endif directive.
1933///
1934void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1935 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001936
Chris Lattnerf64b3522008-03-09 01:54:53 +00001937 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001938 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001939
Chris Lattnerf64b3522008-03-09 01:54:53 +00001940 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001941 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001942 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001943 Diag(EndifToken, diag::err_pp_endif_without_if);
1944 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001945 }
Mike Stump11289f42009-09-09 15:08:12 +00001946
Chris Lattnerf64b3522008-03-09 01:54:53 +00001947 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001948 if (CurPPLexer->getConditionalStackDepth() == 0)
1949 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001950
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001951 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001952 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001953
1954 if (Callbacks)
1955 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001956}
1957
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001958/// HandleElseDirective - Implements the #else directive.
1959///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001960void Preprocessor::HandleElseDirective(Token &Result) {
1961 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001962
Chris Lattnerf64b3522008-03-09 01:54:53 +00001963 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001964 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001965
Chris Lattnerf64b3522008-03-09 01:54:53 +00001966 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001967 if (CurPPLexer->popConditionalLevel(CI)) {
1968 Diag(Result, diag::pp_err_else_without_if);
1969 return;
1970 }
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattnerf64b3522008-03-09 01:54:53 +00001972 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001973 if (CurPPLexer->getConditionalStackDepth() == 0)
1974 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001975
1976 // If this is a #else with a #else before it, report the error.
1977 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001978
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001979 // Finally, skip the rest of the contents of this block.
1980 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00001981 /*FoundElse*/true, Result.getLocation());
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001982
1983 if (Callbacks)
1984 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001985}
1986
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001987/// HandleElifDirective - Implements the #elif directive.
1988///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001989void Preprocessor::HandleElifDirective(Token &ElifToken) {
1990 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattnerf64b3522008-03-09 01:54:53 +00001992 // #elif directive in a non-skipping conditional... start skipping.
1993 // We don't care what the condition is, because we will always skip it (since
1994 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001995 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001996 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001997 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001998
1999 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002000 if (CurPPLexer->popConditionalLevel(CI)) {
2001 Diag(ElifToken, diag::pp_err_elif_without_if);
2002 return;
2003 }
Mike Stump11289f42009-09-09 15:08:12 +00002004
Chris Lattnerf64b3522008-03-09 01:54:53 +00002005 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002006 if (CurPPLexer->getConditionalStackDepth() == 0)
2007 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002008
Chris Lattnerf64b3522008-03-09 01:54:53 +00002009 // If this is a #elif with a #else before it, report the error.
2010 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2011
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002012 // Finally, skip the rest of the contents of this block.
2013 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002014 /*FoundElse*/CI.FoundElse,
2015 ElifToken.getLocation());
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002016
2017 if (Callbacks)
2018 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002019}