blob: 38256815ef93e80836c8c7ec63022462bca27ba7 [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;
Nico Weber2e686202012-02-29 22:54:43 +0000123
Chris Lattner77c76ae2008-12-13 20:12:40 +0000124 const IdentifierInfo &Info = Identifiers.get(Spelling);
Nico Weber2e686202012-02-29 22:54:43 +0000125
126 // Allow #defining |and| and friends in microsoft mode.
Nico Weber2c21c442012-03-01 00:13:46 +0000127 if (Info.isCPlusPlusOperatorKeyword() && getLangOptions().MicrosoftMode) {
Nico Weber2e686202012-02-29 22:54:43 +0000128 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
129 return;
130 }
131
Chris Lattner77c76ae2008-12-13 20:12:40 +0000132 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000133 // C++ 2.5p2: Alternative tokens behave the same as its primary token
134 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000135 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000136 else
137 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
138 // Fall through on error.
139 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
140 // Error if defining "defined": C99 6.10.8.4.
141 Diag(MacroNameTok, diag::err_defined_macro_name);
142 } else if (isDefineUndef && II->hasMacroDefinition() &&
143 getMacroInfo(II)->isBuiltinMacro()) {
144 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
145 if (isDefineUndef == 1)
146 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
147 else
148 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
149 } else {
150 // Okay, we got a good identifier node. Return it.
151 return;
152 }
Mike Stump11289f42009-09-09 15:08:12 +0000153
Chris Lattnerf64b3522008-03-09 01:54:53 +0000154 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000155 // token kind to tok::eod.
156 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000157 return DiscardUntilEndOfDirective();
158}
159
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000160/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
161/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000162/// true, then we consider macros that expand to zero tokens as being ok.
163void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000164 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000165 // Lex unexpanded tokens for most directives: macros might expand to zero
166 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
167 // #line) allow empty macros.
168 if (EnableMacros)
169 Lex(Tmp);
170 else
171 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000172
Chris Lattnerf64b3522008-03-09 01:54:53 +0000173 // There should be no tokens after the directive, but we allow them as an
174 // extension.
175 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
176 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000177
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000178 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000179 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000180 // or if this is a macro-style preprocessing directive, because it is more
181 // trouble than it is worth to insert /**/ and check that there is no /**/
182 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000183 FixItHint Hint;
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000184 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
185 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000186 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
187 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000188 DiscardUntilEndOfDirective();
189 }
190}
191
192
193
194/// SkipExcludedConditionalBlock - We just read a #if or related directive and
195/// decided that the subsequent tokens are in the #if'd out portion of the
196/// file. Lex the rest of the file, until we see an #endif. If
197/// FoundNonSkipPortion is true, then we have already emitted code for part of
198/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
199/// is true, then #else directives are ok, if not, then we have already seen one
200/// so a #else directive is a duplicate. When this returns, the caller can lex
201/// the first valid token.
202void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
203 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000204 bool FoundElse,
205 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000206 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000207 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000208
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000209 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000211
Ted Kremenek56572ab2008-12-12 18:34:08 +0000212 if (CurPTHLexer) {
213 PTHSkipExcludedConditionalBlock();
214 return;
215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattnerf64b3522008-03-09 01:54:53 +0000217 // Enter raw mode to disable identifier lookup (and thus macro expansion),
218 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000219 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000220 Token Tok;
221 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000222 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000223
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000224 if (Tok.is(tok::code_completion)) {
225 if (CodeComplete)
226 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000227 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000228 continue;
229 }
230
Chris Lattnerf64b3522008-03-09 01:54:53 +0000231 // If this is the end of the buffer, we have an error.
232 if (Tok.is(tok::eof)) {
233 // Emit errors for each unterminated conditional on the stack, including
234 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000235 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000236 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000237 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
238 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000239 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000240 }
241
Chris Lattnerf64b3522008-03-09 01:54:53 +0000242 // Just return and let the caller lex after this #include.
243 break;
244 }
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattnerf64b3522008-03-09 01:54:53 +0000246 // If this token is not a preprocessor directive, just skip it.
247 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
248 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattnerf64b3522008-03-09 01:54:53 +0000250 // We just parsed a # character at the start of a line, so we're in
251 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000252 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000253 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000254 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255
Mike Stump11289f42009-09-09 15:08:12 +0000256
Chris Lattnerf64b3522008-03-09 01:54:53 +0000257 // Read the next token, the directive flavor.
258 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000259
Chris Lattnerf64b3522008-03-09 01:54:53 +0000260 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
261 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000262 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000263 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000264 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000265 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000266 continue;
267 }
268
269 // If the first letter isn't i or e, it isn't intesting to us. We know that
270 // this is safe in the face of spelling differences, because there is no way
271 // to spell an i/e in a strange way that is another letter. Skipping this
272 // allows us to avoid looking up the identifier info for #define/#undef and
273 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000274 const char *RawCharData = Tok.getRawIdentifierData();
275
Chris Lattnerf64b3522008-03-09 01:54:53 +0000276 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000277 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000278 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000279 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000281 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000282 continue;
283 }
Mike Stump11289f42009-09-09 15:08:12 +0000284
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 // Get the identifier name without trigraphs or embedded newlines. Note
286 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
287 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000288 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000289 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000290 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000291 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292 } else {
293 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000294 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000296 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000297 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000298 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000299 continue;
300 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000301 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000302 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 }
Mike Stump11289f42009-09-09 15:08:12 +0000304
Benjamin Kramer144884642009-12-31 13:32:38 +0000305 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000307 if (Sub.empty() || // "if"
308 Sub == "def" || // "ifdef"
309 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
311 // bother parsing the condition.
312 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000313 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000315 /*foundelse*/false);
316
317 if (Callbacks)
318 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000319 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000320 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000322 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000323 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 PPConditionalInfo CondInfo;
325 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000326 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000327 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 // If we popped the outermost skipping block, we're done skipping!
331 if (!CondInfo.WasSkipping)
332 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000333 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000334 // #else directive in a skipping conditional. If not in some other
335 // skipping conditional, and if #else hasn't already been seen, enter it
336 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000337 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattnerf64b3522008-03-09 01:54:53 +0000339 // If this is a #else with a #else before it, report the error.
340 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattnerf64b3522008-03-09 01:54:53 +0000342 // Note that we've seen a #else in this conditional.
343 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000344
Chandler Carruth540960f2011-01-03 17:40:17 +0000345 if (Callbacks)
346 Callbacks->Else();
347
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 // If the conditional is at the top level, and the #if block wasn't
349 // entered, enter the #else block now.
350 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
351 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000352 CheckEndOfDirective("else");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000354 } else {
355 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000356 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000357 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000358 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000359
360 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000361 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 // If this is in a skipping block or if we're already handled this #if
363 // block, don't bother parsing the condition.
364 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
365 DiscardUntilEndOfDirective();
366 ShouldEnter = false;
367 } else {
368 // Restore the value of LexingRawMode so that identifiers are
369 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000370 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
371 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372 IdentifierInfo *IfNDefMacro = 0;
373 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000374 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000375 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000376 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000377
Chris Lattnerf64b3522008-03-09 01:54:53 +0000378 // If this is a #elif with a #else before it, report the error.
379 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chandler Carruth540960f2011-01-03 17:40:17 +0000381 if (Callbacks)
382 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
383
Chris Lattnerf64b3522008-03-09 01:54:53 +0000384 // If this condition is true, enter it!
385 if (ShouldEnter) {
386 CondInfo.FoundNonSkip = true;
387 break;
388 }
389 }
390 }
Mike Stump11289f42009-09-09 15:08:12 +0000391
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000392 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000393 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000394 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 }
396
397 // Finally, if we are out of the conditional (saw an #endif or ran off the end
398 // of the file, just stop skipping and return to lexing whatever came after
399 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000400 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000401
402 if (Callbacks) {
403 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
404 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
405 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406}
407
Ted Kremenek56572ab2008-12-12 18:34:08 +0000408void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000409
410 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000411 assert(CurPTHLexer);
412 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Ted Kremenek56572ab2008-12-12 18:34:08 +0000414 // Skip to the next '#else', '#elif', or #endif.
415 if (CurPTHLexer->SkipBlock()) {
416 // We have reached an #endif. Both the '#' and 'endif' tokens
417 // have been consumed by the PTHLexer. Just pop off the condition level.
418 PPConditionalInfo CondInfo;
419 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000420 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000421 assert(!InCond && "Can't be skipping if not in a conditional!");
422 break;
423 }
Mike Stump11289f42009-09-09 15:08:12 +0000424
Ted Kremenek56572ab2008-12-12 18:34:08 +0000425 // We have reached a '#else' or '#elif'. Lex the next token to get
426 // the directive flavor.
427 Token Tok;
428 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Ted Kremenek56572ab2008-12-12 18:34:08 +0000430 // We can actually look up the IdentifierInfo here since we aren't in
431 // raw mode.
432 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
433
434 if (K == tok::pp_else) {
435 // #else: Enter the else condition. We aren't in a nested condition
436 // since we skip those. We're always in the one matching the last
437 // blocked we skipped.
438 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
439 // Note that we've seen a #else in this conditional.
440 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000441
Ted Kremenek56572ab2008-12-12 18:34:08 +0000442 // If the #if block wasn't entered then enter the #else block now.
443 if (!CondInfo.FoundNonSkip) {
444 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000445
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000446 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000447 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000448 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000449 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000450
Ted Kremenek56572ab2008-12-12 18:34:08 +0000451 break;
452 }
Mike Stump11289f42009-09-09 15:08:12 +0000453
Ted Kremenek56572ab2008-12-12 18:34:08 +0000454 // Otherwise skip this block.
455 continue;
456 }
Mike Stump11289f42009-09-09 15:08:12 +0000457
Ted Kremenek56572ab2008-12-12 18:34:08 +0000458 assert(K == tok::pp_elif);
459 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
460
461 // If this is a #elif with a #else before it, report the error.
462 if (CondInfo.FoundElse)
463 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000464
Ted Kremenek56572ab2008-12-12 18:34:08 +0000465 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000466 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000467 if (CondInfo.FoundNonSkip)
468 continue;
469
470 // Evaluate the condition of the #elif.
471 IdentifierInfo *IfNDefMacro = 0;
472 CurPTHLexer->ParsingPreprocessorDirective = true;
473 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
474 CurPTHLexer->ParsingPreprocessorDirective = false;
475
476 // If this condition is true, enter it!
477 if (ShouldEnter) {
478 CondInfo.FoundNonSkip = true;
479 break;
480 }
481
482 // Otherwise, skip this block and go to the next one.
483 continue;
484 }
485}
486
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000487/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
488/// return null on failure. isAngled indicates whether the file reference is
489/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000490const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000491 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000492 bool isAngled,
493 const DirectoryLookup *FromDir,
494 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000496 SmallVectorImpl<char> *RelativePath,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000497 Module **SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000498 bool SkipCache) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000499 // If the header lookup mechanism may be relative to the current file, pass in
500 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000501 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000502 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000503 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000504 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000505
Chris Lattner022923a2009-02-04 19:45:07 +0000506 // If there is no file entry associated with this file, it must be the
507 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000508 // it won't be scanned for preprocessor directives. If we have the
509 // predefines buffer, resolve #include references (which come from the
510 // -include command line argument) as if they came from the main file, this
511 // affects file lookup etc.
512 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000513 FID = SourceMgr.getMainFileID();
514 CurFileEnt = SourceMgr.getFileEntryForID(FID);
515 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000518 // Do a standard file entry lookup.
519 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000520 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000521 Filename, isAngled, FromDir, CurDir, CurFileEnt,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000522 SearchPath, RelativePath, SuggestedModule, SkipCache);
Chris Lattnerfde85352010-01-22 00:14:44 +0000523 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000525 // Otherwise, see if this is a subframework header. If so, this is relative
526 // to one of the headers on the #include stack. Walk the list of the current
527 // headers on the #include stack and pass them to HeaderInfo.
Douglas Gregor97eec242011-09-15 22:00:41 +0000528 // FIXME: SuggestedModule!
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000529 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000530 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000531 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000532 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000533 return FE;
534 }
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000536 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
537 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000538 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000539 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000540 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000541 if ((FE = HeaderInfo.LookupSubframeworkHeader(
542 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000543 return FE;
544 }
545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000547 // Otherwise, we really couldn't find the file.
548 return 0;
549}
550
Chris Lattnerf64b3522008-03-09 01:54:53 +0000551
552//===----------------------------------------------------------------------===//
553// Preprocessor Directive Handling.
554//===----------------------------------------------------------------------===//
555
556/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000557/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000558/// lexer/preprocessor state, and advances the lexer(s) so that the next token
559/// read is the correct one.
560void Preprocessor::HandleDirective(Token &Result) {
561 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattnerf64b3522008-03-09 01:54:53 +0000563 // We just parsed a # character at the start of a line, so we're in directive
564 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000565 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000566 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattnerf64b3522008-03-09 01:54:53 +0000568 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000569
Chris Lattnerf64b3522008-03-09 01:54:53 +0000570 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000571 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000572 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000573 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000574
Chris Lattner2d17ab72009-03-18 21:00:25 +0000575 // Save the '#' token in case we need to return it later.
576 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000577
Chris Lattnerf64b3522008-03-09 01:54:53 +0000578 // Read the next token, the directive flavor. This isn't expanded due to
579 // C99 6.10.3p8.
580 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattnerf64b3522008-03-09 01:54:53 +0000582 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
583 // #define A(x) #x
584 // A(abc
585 // #warning blah
586 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000587 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
588 // not support this for #include-like directives, since that can result in
589 // terrible diagnostics, and does not work in GCC.
590 if (InMacroArgs) {
591 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
592 switch (II->getPPKeywordID()) {
593 case tok::pp_include:
594 case tok::pp_import:
595 case tok::pp_include_next:
596 case tok::pp___include_macros:
597 Diag(Result, diag::err_embedded_include) << II->getName();
598 DiscardUntilEndOfDirective();
599 return;
600 default:
601 break;
602 }
603 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000604 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Chris Lattnerf64b3522008-03-09 01:54:53 +0000607TryAgain:
608 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000609 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000610 return; // null directive.
611 case tok::comment:
612 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
613 LexUnexpandedToken(Result);
614 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000615 case tok::code_completion:
616 if (CodeComplete)
617 CodeComplete->CodeCompleteDirective(
618 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000619 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000620 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000621 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000622 if (getLangOptions().AsmPreprocessor)
623 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000624 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000625 default:
626 IdentifierInfo *II = Result.getIdentifierInfo();
627 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattnerf64b3522008-03-09 01:54:53 +0000629 // Ask what the preprocessor keyword ID is.
630 switch (II->getPPKeywordID()) {
631 default: break;
632 // C99 6.10.1 - Conditional Inclusion.
633 case tok::pp_if:
634 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
635 case tok::pp_ifdef:
636 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
637 case tok::pp_ifndef:
638 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
639 case tok::pp_elif:
640 return HandleElifDirective(Result);
641 case tok::pp_else:
642 return HandleElseDirective(Result);
643 case tok::pp_endif:
644 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000645
Chris Lattnerf64b3522008-03-09 01:54:53 +0000646 // C99 6.10.2 - Source File Inclusion.
647 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000648 // Handle #include.
649 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000650 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000651 // Handle -imacros.
652 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000653
Chris Lattnerf64b3522008-03-09 01:54:53 +0000654 // C99 6.10.3 - Macro Replacement.
655 case tok::pp_define:
656 return HandleDefineDirective(Result);
657 case tok::pp_undef:
658 return HandleUndefDirective(Result);
659
660 // C99 6.10.4 - Line Control.
661 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000662 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000663
Chris Lattnerf64b3522008-03-09 01:54:53 +0000664 // C99 6.10.5 - Error Directive.
665 case tok::pp_error:
666 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000667
Chris Lattnerf64b3522008-03-09 01:54:53 +0000668 // C99 6.10.6 - Pragma Directive.
669 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000670 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000671
Chris Lattnerf64b3522008-03-09 01:54:53 +0000672 // GNU Extensions.
673 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000674 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000675 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000676 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattnerf64b3522008-03-09 01:54:53 +0000678 case tok::pp_warning:
679 Diag(Result, diag::ext_pp_warning_directive);
680 return HandleUserDiagnosticDirective(Result, true);
681 case tok::pp_ident:
682 return HandleIdentSCCSDirective(Result);
683 case tok::pp_sccs:
684 return HandleIdentSCCSDirective(Result);
685 case tok::pp_assert:
686 //isExtension = true; // FIXME: implement #assert
687 break;
688 case tok::pp_unassert:
689 //isExtension = true; // FIXME: implement #unassert
690 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000691
Douglas Gregor663b48f2012-01-03 19:48:16 +0000692 case tok::pp___public_macro:
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000693 if (getLangOptions().Modules)
694 return HandleMacroPublicDirective(Result);
695 break;
696
Douglas Gregor663b48f2012-01-03 19:48:16 +0000697 case tok::pp___private_macro:
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000698 if (getLangOptions().Modules)
699 return HandleMacroPrivateDirective(Result);
700 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000701 }
702 break;
703 }
Mike Stump11289f42009-09-09 15:08:12 +0000704
Chris Lattner2d17ab72009-03-18 21:00:25 +0000705 // If this is a .S file, treat unknown # directives as non-preprocessor
706 // directives. This is important because # may be a comment or introduce
707 // various pseudo-ops. Just return the # token and push back the following
708 // token to be lexed next time.
709 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000710 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000711 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000712 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000713 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000714
715 // If the second token is a hashhash token, then we need to translate it to
716 // unknown so the token lexer doesn't try to perform token pasting.
717 if (Result.is(tok::hashhash))
718 Toks[1].setKind(tok::unknown);
719
Chris Lattner2d17ab72009-03-18 21:00:25 +0000720 // Enter this token stream so that we re-lex the tokens. Make sure to
721 // enable macro expansion, in case the token after the # is an identifier
722 // that is expanded.
723 EnterTokenStream(Toks, 2, false, true);
724 return;
725 }
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattnerf64b3522008-03-09 01:54:53 +0000727 // If we reached here, the preprocessing token is not valid!
728 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattnerf64b3522008-03-09 01:54:53 +0000730 // Read the rest of the PP line.
731 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattnerf64b3522008-03-09 01:54:53 +0000733 // Okay, we're done parsing the directive.
734}
735
Chris Lattner76e68962009-01-26 06:19:46 +0000736/// GetLineValue - Convert a numeric token into an unsigned value, emitting
737/// Diagnostic DiagID if it is invalid, and returning the value in Val.
738static bool GetLineValue(Token &DigitTok, unsigned &Val,
739 unsigned DiagID, Preprocessor &PP) {
740 if (DigitTok.isNot(tok::numeric_constant)) {
741 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000742
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000743 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000744 PP.DiscardUntilEndOfDirective();
745 return true;
746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000748 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000749 IntegerBuffer.resize(DigitTok.getLength());
750 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000751 bool Invalid = false;
752 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
753 if (Invalid)
754 return true;
755
Chris Lattnerd66f1722009-04-18 18:35:15 +0000756 // Verify that we have a simple digit-sequence, and compute the value. This
757 // is always a simple digit string computed in decimal, so we do this manually
758 // here.
759 Val = 0;
760 for (unsigned i = 0; i != ActualLength; ++i) {
761 if (!isdigit(DigitTokBegin[i])) {
762 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
763 diag::err_pp_line_digit_sequence);
764 PP.DiscardUntilEndOfDirective();
765 return true;
766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattnerd66f1722009-04-18 18:35:15 +0000768 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
769 if (NextVal < Val) { // overflow.
770 PP.Diag(DigitTok, DiagID);
771 PP.DiscardUntilEndOfDirective();
772 return true;
773 }
774 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
777 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000778 if (Val == 0) {
779 PP.Diag(DigitTok, DiagID);
780 PP.DiscardUntilEndOfDirective();
781 return true;
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattnerd66f1722009-04-18 18:35:15 +0000784 if (DigitTokBegin[0] == '0')
785 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000786
Chris Lattner76e68962009-01-26 06:19:46 +0000787 return false;
788}
789
Mike Stump11289f42009-09-09 15:08:12 +0000790/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000791/// acceptable forms are:
792/// # line digit-sequence
793/// # line digit-sequence "s-char-sequence"
794void Preprocessor::HandleLineDirective(Token &Tok) {
795 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
796 // expanded.
797 Token DigitTok;
798 Lex(DigitTok);
799
Chris Lattner100c65e2009-01-26 05:29:08 +0000800 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000801 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000802 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000803 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000804
Chris Lattner76e68962009-01-26 06:19:46 +0000805 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
806 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000807 unsigned LineLimit = 32768U;
808 if (Features.C99 || Features.CPlusPlus0x)
809 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000810 if (LineNo >= LineLimit)
811 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smithacd4d3d2011-10-15 01:18:56 +0000812 else if (Features.CPlusPlus0x && LineNo >= 32768U)
813 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000814
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000815 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000816 Token StrTok;
817 Lex(StrTok);
818
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000819 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
820 // string followed by eod.
821 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000822 ; // ok
823 else if (StrTok.isNot(tok::string_literal)) {
824 Diag(StrTok, diag::err_pp_line_invalid_filename);
825 DiscardUntilEndOfDirective();
826 return;
827 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000828 // Parse and validate the string, converting it into a unique ID.
829 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000830 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000831 if (Literal.hadError)
832 return DiscardUntilEndOfDirective();
833 if (Literal.Pascal) {
834 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
835 return DiscardUntilEndOfDirective();
836 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000837 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000838
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000839 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000840 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
841 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000842 }
Mike Stump11289f42009-09-09 15:08:12 +0000843
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000844 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattner839150e2009-03-27 17:13:49 +0000846 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000847 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
848 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000849 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000850}
851
Chris Lattner76e68962009-01-26 06:19:46 +0000852/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
853/// marker directive.
854static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
855 bool &IsSystemHeader, bool &IsExternCHeader,
856 Preprocessor &PP) {
857 unsigned FlagVal;
858 Token FlagTok;
859 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000860 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000861 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
862 return true;
863
864 if (FlagVal == 1) {
865 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattner76e68962009-01-26 06:19:46 +0000867 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000868 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000869 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
870 return true;
871 } else if (FlagVal == 2) {
872 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Chris Lattner1c967782009-02-04 06:25:26 +0000874 SourceManager &SM = PP.getSourceManager();
875 // If we are leaving the current presumed file, check to make sure the
876 // presumed include stack isn't empty!
877 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000878 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000879 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000880 if (PLoc.isInvalid())
881 return true;
882
Chris Lattner1c967782009-02-04 06:25:26 +0000883 // If there is no include loc (main file) or if the include loc is in a
884 // different physical file, then we aren't in a "1" line marker flag region.
885 SourceLocation IncLoc = PLoc.getIncludeLoc();
886 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000887 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000888 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
889 PP.DiscardUntilEndOfDirective();
890 return true;
891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
Chris Lattner76e68962009-01-26 06:19:46 +0000893 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000894 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000895 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
896 return true;
897 }
898
899 // We must have 3 if there are still flags.
900 if (FlagVal != 3) {
901 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000902 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000903 return true;
904 }
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattner76e68962009-01-26 06:19:46 +0000906 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Chris Lattner76e68962009-01-26 06:19:46 +0000908 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000909 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000910 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000911 return true;
912
913 // We must have 4 if there is yet another flag.
914 if (FlagVal != 4) {
915 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000916 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000917 return true;
918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
Chris Lattner76e68962009-01-26 06:19:46 +0000920 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000921
Chris Lattner76e68962009-01-26 06:19:46 +0000922 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000923 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000924
925 // There are no more valid flags here.
926 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000927 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000928 return true;
929}
930
931/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
932/// one of the following forms:
933///
934/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000935/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000936/// # 42 "file" ('1' | '2')? '3' '4'?
937///
938void Preprocessor::HandleDigitDirective(Token &DigitTok) {
939 // Validate the number and convert it to an unsigned. GNU does not have a
940 // line # limit other than it fit in 32-bits.
941 unsigned LineNo;
942 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
943 *this))
944 return;
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattner76e68962009-01-26 06:19:46 +0000946 Token StrTok;
947 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattner76e68962009-01-26 06:19:46 +0000949 bool IsFileEntry = false, IsFileExit = false;
950 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000951 int FilenameID = -1;
952
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000953 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
954 // string followed by eod.
955 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000956 ; // ok
957 else if (StrTok.isNot(tok::string_literal)) {
958 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000959 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000960 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000961 // Parse and validate the string, converting it into a unique ID.
962 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000963 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000964 if (Literal.hadError)
965 return DiscardUntilEndOfDirective();
966 if (Literal.Pascal) {
967 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
968 return DiscardUntilEndOfDirective();
969 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000970 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattner76e68962009-01-26 06:19:46 +0000972 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000973 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000974 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000975 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000976 }
Mike Stump11289f42009-09-09 15:08:12 +0000977
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000978 // Create a line note with this information.
979 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000980 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000981 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000982
Chris Lattner839150e2009-03-27 17:13:49 +0000983 // If the preprocessor has callbacks installed, notify them of the #line
984 // change. This is used so that the line marker comes out in -E mode for
985 // example.
986 if (Callbacks) {
987 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
988 if (IsFileEntry)
989 Reason = PPCallbacks::EnterFile;
990 else if (IsFileExit)
991 Reason = PPCallbacks::ExitFile;
992 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
993 if (IsExternCHeader)
994 FileKind = SrcMgr::C_ExternCSystem;
995 else if (IsSystemHeader)
996 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattnerc745cec2010-04-14 04:28:50 +0000998 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000999 }
Chris Lattner76e68962009-01-26 06:19:46 +00001000}
1001
1002
Chris Lattner38d7fd22009-01-26 05:30:54 +00001003/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1004///
Mike Stump11289f42009-09-09 15:08:12 +00001005void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001006 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001007 // PTH doesn't emit #warning or #error directives.
1008 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001009 return CurPTHLexer->DiscardToEndOfLine();
1010
Chris Lattnerf64b3522008-03-09 01:54:53 +00001011 // Read the rest of the line raw. We do this because we don't want macros
1012 // to be expanded and we don't require that the tokens be valid preprocessing
1013 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1014 // collapse multiple consequtive white space between tokens, but this isn't
1015 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +00001016 std::string Message = CurLexer->ReadToEndOfLine();
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001017
1018 // Find the first non-whitespace character, so that we can make the
1019 // diagnostic more succinct.
1020 StringRef Msg(Message);
1021 size_t i = Msg.find_first_not_of(' ');
1022 if (i < Msg.size())
1023 Msg = Msg.substr(i);
1024
Chris Lattner100c65e2009-01-26 05:29:08 +00001025 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001026 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001027 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001028 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001029}
1030
1031/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1032///
1033void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1034 // Yes, this directive is an extension.
1035 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001036
Chris Lattnerf64b3522008-03-09 01:54:53 +00001037 // Read the string argument.
1038 Token StrTok;
1039 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattnerf64b3522008-03-09 01:54:53 +00001041 // If the token kind isn't a string, it's a malformed directive.
1042 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001043 StrTok.isNot(tok::wide_string_literal)) {
1044 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001045 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001046 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001047 return;
1048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001050 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001051 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001052
Douglas Gregordc970f02010-03-16 22:30:13 +00001053 if (Callbacks) {
1054 bool Invalid = false;
1055 std::string Str = getSpelling(StrTok, &Invalid);
1056 if (!Invalid)
1057 Callbacks->Ident(Tok.getLocation(), Str);
1058 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001059}
1060
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001061/// \brief Handle a #public directive.
1062void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001063 Token MacroNameTok;
1064 ReadMacroName(MacroNameTok, 2);
1065
1066 // Error reading macro name? If so, diagnostic already issued.
1067 if (MacroNameTok.is(tok::eod))
1068 return;
1069
Douglas Gregor663b48f2012-01-03 19:48:16 +00001070 // Check to see if this is the last token on the #__public_macro line.
1071 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001072
1073 // Okay, we finally have a valid identifier to undef.
1074 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1075
1076 // If the macro is not defined, this is an error.
1077 if (MI == 0) {
Douglas Gregorebf00492011-10-17 15:32:29 +00001078 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001079 << MacroNameTok.getIdentifierInfo();
1080 return;
1081 }
1082
1083 // Note that this macro has now been exported.
Douglas Gregorebf00492011-10-17 15:32:29 +00001084 MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
1085
1086 // If this macro definition came from a PCH file, mark it
1087 // as having changed since serialization.
1088 if (MI->isFromAST())
1089 MI->setChangedAfterLoad();
1090}
1091
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001092/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001093void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1094 Token MacroNameTok;
1095 ReadMacroName(MacroNameTok, 2);
1096
1097 // Error reading macro name? If so, diagnostic already issued.
1098 if (MacroNameTok.is(tok::eod))
1099 return;
1100
Douglas Gregor663b48f2012-01-03 19:48:16 +00001101 // Check to see if this is the last token on the #__private_macro line.
1102 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001103
1104 // Okay, we finally have a valid identifier to undef.
1105 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1106
1107 // If the macro is not defined, this is an error.
1108 if (MI == 0) {
1109 Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
1110 << MacroNameTok.getIdentifierInfo();
1111 return;
1112 }
1113
1114 // Note that this macro has now been marked private.
1115 MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001116
1117 // If this macro definition came from a PCH file, mark it
1118 // as having changed since serialization.
1119 if (MI->isFromAST())
1120 MI->setChangedAfterLoad();
1121}
1122
Chris Lattnerf64b3522008-03-09 01:54:53 +00001123//===----------------------------------------------------------------------===//
1124// Preprocessor Include Directive Handling.
1125//===----------------------------------------------------------------------===//
1126
1127/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1128/// checked and spelled filename, e.g. as an operand of #include. This returns
1129/// true if the input filename was in <>'s or false if it were in ""'s. The
1130/// caller is expected to provide a buffer that is large enough to hold the
1131/// spelling of the filename, but is also expected to handle the case when
1132/// this method decides to use a different buffer.
1133bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001134 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001135 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001136 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001137
Chris Lattnerf64b3522008-03-09 01:54:53 +00001138 // Make sure the filename is <x> or "x".
1139 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001140 if (Buffer[0] == '<') {
1141 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001142 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001143 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001144 return true;
1145 }
1146 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001147 } else if (Buffer[0] == '"') {
1148 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001149 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001150 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001151 return true;
1152 }
1153 isAngled = false;
1154 } else {
1155 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001156 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001157 return true;
1158 }
Mike Stump11289f42009-09-09 15:08:12 +00001159
Chris Lattnerf64b3522008-03-09 01:54:53 +00001160 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001161 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001162 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001163 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001164 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001165 }
Mike Stump11289f42009-09-09 15:08:12 +00001166
Chris Lattnerf64b3522008-03-09 01:54:53 +00001167 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001168 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001169 return isAngled;
1170}
1171
1172/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1173/// from a macro as multiple tokens, which need to be glued together. This
1174/// occurs for code like:
1175/// #define FOO <a/b.h>
1176/// #include FOO
1177/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1178///
1179/// This code concatenates and consumes tokens up to the '>' token. It returns
1180/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001181/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001182bool Preprocessor::ConcatenateIncludeName(
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001183 SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001184 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001185 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001186
John Thompsonb5353522009-10-30 13:49:06 +00001187 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001188 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001189 End = CurTok.getLocation();
1190
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001191 // FIXME: Provide code completion for #includes.
1192 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001193 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001194 Lex(CurTok);
1195 continue;
1196 }
1197
Chris Lattnerf64b3522008-03-09 01:54:53 +00001198 // Append the spelling of this token to the buffer. If there was a space
1199 // before it, add it now.
1200 if (CurTok.hasLeadingSpace())
1201 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001202
Chris Lattnerf64b3522008-03-09 01:54:53 +00001203 // Get the spelling of the token, directly into FilenameBuffer if possible.
1204 unsigned PreAppendSize = FilenameBuffer.size();
1205 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattnerf64b3522008-03-09 01:54:53 +00001207 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001208 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattnerf64b3522008-03-09 01:54:53 +00001210 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1211 if (BufPtr != &FilenameBuffer[PreAppendSize])
1212 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214 // Resize FilenameBuffer to the correct size.
1215 if (CurTok.getLength() != ActualLen)
1216 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattnerf64b3522008-03-09 01:54:53 +00001218 // If we found the '>' marker, return success.
1219 if (CurTok.is(tok::greater))
1220 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001221
John Thompsonb5353522009-10-30 13:49:06 +00001222 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001223 }
1224
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001225 // If we hit the eod marker, emit an error and return true so that the caller
1226 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001227 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001228 return true;
1229}
1230
1231/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1232/// file to be included from the lexer, then include it! This is a common
1233/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001234/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001235/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001236void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1237 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001238 const DirectoryLookup *LookupFrom,
1239 bool isImport) {
1240
1241 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001242 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001243
Chris Lattnerf64b3522008-03-09 01:54:53 +00001244 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001245 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001246 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001247 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001248 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001249
Chris Lattnerf64b3522008-03-09 01:54:53 +00001250 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001251 case tok::eod:
1252 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001253 return;
Mike Stump11289f42009-09-09 15:08:12 +00001254
Chris Lattnerf64b3522008-03-09 01:54:53 +00001255 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001256 case tok::string_literal:
1257 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001258 End = FilenameTok.getLocation();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001259 CharEnd = End.getLocWithOffset(Filename.size());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001260 break;
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattnerf64b3522008-03-09 01:54:53 +00001262 case tok::less:
1263 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1264 // case, glue the tokens together into FilenameBuffer and interpret those.
1265 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001266 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001267 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001268 Filename = FilenameBuffer.str();
Douglas Gregor41e115a2011-11-30 18:02:36 +00001269 CharEnd = getLocForEndOfToken(End);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270 break;
1271 default:
1272 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1273 DiscardUntilEndOfDirective();
1274 return;
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Aaron Ballman611306e2012-03-02 22:51:54 +00001277 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001278 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001279 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001280 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1281 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001282 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001283 DiscardUntilEndOfDirective();
1284 return;
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001287 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001288 // we allow macros that expand to nothing after the filename, because this
1289 // falls into the category of "#include pp-tokens new-line" specified in
1290 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001291 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001292
1293 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001294 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1295 Diag(FilenameTok, diag::err_pp_include_too_deep);
1296 return;
1297 }
Mike Stump11289f42009-09-09 15:08:12 +00001298
John McCall32f5fe12011-09-30 05:12:12 +00001299 // Complain about attempts to #include files in an audit pragma.
1300 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1301 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1302 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1303
1304 // Immediately leave the pragma.
1305 PragmaARCCFCodeAuditedLoc = SourceLocation();
1306 }
1307
Aaron Ballman611306e2012-03-02 22:51:54 +00001308 if (HeaderInfo.HasIncludeAliasMap()) {
1309 // Map the filename with the brackets still attached. If the name doesn't
1310 // map to anything, fall back on the filename we've already gotten the
1311 // spelling for.
1312 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1313 if (!NewName.empty())
1314 Filename = NewName;
1315 }
1316
Chris Lattnerf64b3522008-03-09 01:54:53 +00001317 // Search include directories.
1318 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001319 SmallString<1024> SearchPath;
1320 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001321 // We get the raw path only if we have 'Callbacks' to which we later pass
1322 // the path.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001323 Module *SuggestedModule = 0;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001324 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001325 Filename, isAngled, LookupFrom, CurDir,
Douglas Gregor97eec242011-09-15 22:00:41 +00001326 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
Douglas Gregorad01b312012-01-03 17:07:34 +00001327 getLangOptions().Modules? &SuggestedModule : 0);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001328
Douglas Gregor11729f02011-11-30 18:12:06 +00001329 if (Callbacks) {
1330 if (!File) {
1331 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001332 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001333 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1334 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1335 // Add the recovery path to the list of search paths.
1336 DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
1337 HeaderInfo.AddSearchPath(DL, isAngled);
1338
1339 // Try the lookup again, skipping the cache.
1340 File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
Douglas Gregorad01b312012-01-03 17:07:34 +00001341 getLangOptions().Modules? &SuggestedModule : 0,
Douglas Gregor11729f02011-11-30 18:12:06 +00001342 /*SkipCache*/true);
1343 }
1344 }
1345 }
1346
1347 // Notify the callback object that we've seen an inclusion directive.
1348 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1349 End, SearchPath, RelativePath);
1350 }
1351
1352 if (File == 0) {
1353 if (!SuppressIncludeNotFoundError)
1354 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1355 return;
1356 }
1357
Douglas Gregor97eec242011-09-15 22:00:41 +00001358 // If we are supposed to import a module rather than including the header,
1359 // do so now.
Douglas Gregorc04f6442011-11-17 22:44:56 +00001360 if (SuggestedModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001361 // Compute the module access path corresponding to this module.
1362 // FIXME: Should we have a second loadModule() overload to avoid this
1363 // extra lookup step?
1364 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Douglas Gregorde3ef502011-11-30 23:21:26 +00001365 for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001366 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1367 FilenameTok.getLocation()));
1368 std::reverse(Path.begin(), Path.end());
1369
Douglas Gregor41e115a2011-11-30 18:02:36 +00001370 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001371 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001372 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1373 if (I)
1374 PathString += '.';
1375 PathString += Path[I].first->getName();
1376 }
1377 int IncludeKind = 0;
1378
1379 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1380 case tok::pp_include:
1381 IncludeKind = 0;
1382 break;
1383
1384 case tok::pp_import:
1385 IncludeKind = 1;
1386 break;
1387
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001388 case tok::pp_include_next:
1389 IncludeKind = 2;
1390 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001391
1392 case tok::pp___include_macros:
1393 IncludeKind = 3;
1394 break;
1395
1396 default:
1397 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001398 }
1399
Douglas Gregor2537a362011-12-08 17:01:29 +00001400 // Determine whether we are actually building the module that this
1401 // include directive maps to.
1402 bool BuildingImportedModule
1403 = Path[0].first->getName() == getLangOptions().CurrentModule;
1404
Douglas Gregorda82e702012-01-03 19:32:59 +00001405 if (!BuildingImportedModule && getLangOptions().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001406 // If we're not building the imported module, warn that we're going
1407 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001408 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001409 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1410 /*IsTokenRange=*/false);
1411 Diag(HashLoc, diag::warn_auto_module_import)
1412 << IncludeKind << PathString
1413 << FixItHint::CreateReplacement(ReplaceRange,
Ted Kremenekc1e4dd02012-03-01 22:07:04 +00001414 "@__experimental_modules_import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001415 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001416
Douglas Gregor71944202011-11-30 00:36:36 +00001417 // Load the module.
Douglas Gregorff2be532011-12-01 17:11:21 +00001418 // If this was an #__include_macros directive, only make macros visible.
1419 Module::NameVisibilityKind Visibility
1420 = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Douglas Gregor98a52db2011-12-20 00:28:52 +00001421 Module *Imported
1422 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1423 /*IsIncludeDirective=*/true);
Douglas Gregor2537a362011-12-08 17:01:29 +00001424
1425 // If this header isn't part of the module we're building, we're done.
Douglas Gregor98a52db2011-12-20 00:28:52 +00001426 if (!BuildingImportedModule && Imported)
Douglas Gregor2537a362011-12-08 17:01:29 +00001427 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001428 }
1429
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001430 // The #included file will be considered to be a system header if either it is
1431 // in a system include directory, or if the #includer is a system include
1432 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001433 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001434 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001435 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001436
Chris Lattner72286d62010-04-19 20:44:31 +00001437 // Ask HeaderInfo if we should enter this #include file. If not, #including
1438 // this file will have no effect.
1439 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001440 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001441 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001442 return;
1443 }
1444
Chris Lattnerf64b3522008-03-09 01:54:53 +00001445 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001446 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1447 FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001448 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001449
1450 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001451 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001452}
1453
1454/// HandleIncludeNextDirective - Implements #include_next.
1455///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001456void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1457 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001458 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattnerf64b3522008-03-09 01:54:53 +00001460 // #include_next is like #include, except that we start searching after
1461 // the current found directory. If we can't do this, issue a
1462 // diagnostic.
1463 const DirectoryLookup *Lookup = CurDirLookup;
1464 if (isInPrimaryFile()) {
1465 Lookup = 0;
1466 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1467 } else if (Lookup == 0) {
1468 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1469 } else {
1470 // Start looking up in the next directory.
1471 ++Lookup;
1472 }
Mike Stump11289f42009-09-09 15:08:12 +00001473
Douglas Gregor796d76a2010-10-20 22:00:55 +00001474 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001475}
1476
1477/// HandleImportDirective - Implements #import.
1478///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001479void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1480 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001481 if (!Features.ObjC1) // #import is standard for ObjC.
1482 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001483
Douglas Gregor796d76a2010-10-20 22:00:55 +00001484 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001485}
1486
Chris Lattner58a1eb02009-04-08 18:46:40 +00001487/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1488/// pseudo directive in the predefines buffer. This handles it by sucking all
1489/// tokens through the preprocessor and discarding them (only keeping the side
1490/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001491void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1492 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001493 // This directive should only occur in the predefines buffer. If not, emit an
1494 // error and reject it.
1495 SourceLocation Loc = IncludeMacrosTok.getLocation();
1496 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1497 Diag(IncludeMacrosTok.getLocation(),
1498 diag::pp_include_macros_out_of_predefines);
1499 DiscardUntilEndOfDirective();
1500 return;
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502
Chris Lattnere01d82b2009-04-08 20:53:24 +00001503 // Treat this as a normal #include for checking purposes. If this is
1504 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001505 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001506
Chris Lattnere01d82b2009-04-08 20:53:24 +00001507 Token TmpTok;
1508 do {
1509 Lex(TmpTok);
1510 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1511 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001512}
1513
Chris Lattnerf64b3522008-03-09 01:54:53 +00001514//===----------------------------------------------------------------------===//
1515// Preprocessor Macro Directive Handling.
1516//===----------------------------------------------------------------------===//
1517
1518/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1519/// definition has just been read. Lex the rest of the arguments and the
1520/// closing ), updating MI with what we learn. Return true if an error occurs
1521/// parsing the arg list.
1522bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001523 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001524
Chris Lattnerf64b3522008-03-09 01:54:53 +00001525 Token Tok;
1526 while (1) {
1527 LexUnexpandedToken(Tok);
1528 switch (Tok.getKind()) {
1529 case tok::r_paren:
1530 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001531 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001532 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001533 // Otherwise we have #define FOO(A,)
1534 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1535 return true;
1536 case tok::ellipsis: // #define X(... -> C99 varargs
Richard Smithacd4d3d2011-10-15 01:18:56 +00001537 if (!Features.C99)
1538 Diag(Tok, Features.CPlusPlus0x ?
1539 diag::warn_cxx98_compat_variadic_macro :
1540 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001541
1542 // Lex the token after the identifier.
1543 LexUnexpandedToken(Tok);
1544 if (Tok.isNot(tok::r_paren)) {
1545 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1546 return true;
1547 }
1548 // Add the __VA_ARGS__ identifier as an argument.
1549 Arguments.push_back(Ident__VA_ARGS__);
1550 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001551 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001552 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001553 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001554 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1555 return true;
1556 default:
1557 // Handle keywords and identifiers here to accept things like
1558 // #define Foo(for) for.
1559 IdentifierInfo *II = Tok.getIdentifierInfo();
1560 if (II == 0) {
1561 // #define X(1
1562 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1563 return true;
1564 }
1565
1566 // If this is already used as an argument, it is used multiple times (e.g.
1567 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001568 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001569 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001570 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001571 return true;
1572 }
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattnerf64b3522008-03-09 01:54:53 +00001574 // Add the argument to the macro info.
1575 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Chris Lattnerf64b3522008-03-09 01:54:53 +00001577 // Lex the token after the identifier.
1578 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001579
Chris Lattnerf64b3522008-03-09 01:54:53 +00001580 switch (Tok.getKind()) {
1581 default: // #define X(A B
1582 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1583 return true;
1584 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001585 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001586 return false;
1587 case tok::comma: // #define X(A,
1588 break;
1589 case tok::ellipsis: // #define X(A... -> GCC extension
1590 // Diagnose extension.
1591 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Chris Lattnerf64b3522008-03-09 01:54:53 +00001593 // Lex the token after the identifier.
1594 LexUnexpandedToken(Tok);
1595 if (Tok.isNot(tok::r_paren)) {
1596 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1597 return true;
1598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattnerf64b3522008-03-09 01:54:53 +00001600 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001601 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001602 return false;
1603 }
1604 }
1605 }
1606}
1607
1608/// HandleDefineDirective - Implements #define. This consumes the entire macro
1609/// line then lets the caller lex the next real token.
1610void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1611 ++NumDefined;
1612
1613 Token MacroNameTok;
1614 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001615
Chris Lattnerf64b3522008-03-09 01:54:53 +00001616 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001617 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001618 return;
1619
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001620 Token LastTok = MacroNameTok;
1621
Chris Lattnerf64b3522008-03-09 01:54:53 +00001622 // If we are supposed to keep comments in #defines, reenable comment saving
1623 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001624 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001625
Chris Lattnerf64b3522008-03-09 01:54:53 +00001626 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001627 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001628
Chris Lattnerf64b3522008-03-09 01:54:53 +00001629 Token Tok;
1630 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattnerf64b3522008-03-09 01:54:53 +00001632 // If this is a function-like macro definition, parse the argument list,
1633 // marking each of the identifiers as being used as macro arguments. Also,
1634 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001635 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001636 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001637 } else if (Tok.hasLeadingSpace()) {
1638 // This is a normal token with leading space. Clear the leading space
1639 // marker on the first token to get proper expansion.
1640 Tok.clearFlag(Token::LeadingSpace);
1641 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001642 // This is a function-like macro definition. Read the argument list.
1643 MI->setIsFunctionLike();
1644 if (ReadMacroDefinitionArgList(MI)) {
1645 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001646 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001647 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001648 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001649 DiscardUntilEndOfDirective();
1650 return;
1651 }
1652
Chris Lattner249c38b2009-04-19 18:26:34 +00001653 // If this is a definition of a variadic C99 function-like macro, not using
1654 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001655
Chris Lattner249c38b2009-04-19 18:26:34 +00001656 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1657 // This gets unpoisoned where it is allowed.
1658 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1659 if (MI->isC99Varargs())
1660 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001661
Chris Lattnerf64b3522008-03-09 01:54:53 +00001662 // Read the first token after the arg list for down below.
1663 LexUnexpandedToken(Tok);
Eli Friedman192e0342011-10-10 23:35:28 +00001664 } else if (Features.C99 || Features.CPlusPlus0x) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001665 // C99 requires whitespace between the macro definition and the body. Emit
1666 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001667 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001668 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001669 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1670 // first character of a replacement list is not a character required by
1671 // subclause 5.2.1, then there shall be white-space separation between the
1672 // identifier and the replacement list.". 5.2.1 lists this set:
1673 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1674 // is irrelevant here.
1675 bool isInvalid = false;
1676 if (Tok.is(tok::at)) // @ is not in the list above.
1677 isInvalid = true;
1678 else if (Tok.is(tok::unknown)) {
1679 // If we have an unknown token, it is something strange like "`". Since
1680 // all of valid characters would have lexed into a single character
1681 // token of some sort, we know this is not a valid case.
1682 isInvalid = true;
1683 }
1684 if (isInvalid)
1685 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1686 else
1687 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001688 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001689
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001690 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001691 LastTok = Tok;
1692
Chris Lattnerf64b3522008-03-09 01:54:53 +00001693 // Read the rest of the macro body.
1694 if (MI->isObjectLike()) {
1695 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001696 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001697 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001698 MI->AddTokenToBody(Tok);
1699 // Get the next token of the macro.
1700 LexUnexpandedToken(Tok);
1701 }
Mike Stump11289f42009-09-09 15:08:12 +00001702
Chris Lattnerf64b3522008-03-09 01:54:53 +00001703 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001704 // Otherwise, read the body of a function-like macro. While we are at it,
1705 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1706 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001707 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001708 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001709
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001711 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001712
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 // Get the next token of the macro.
1714 LexUnexpandedToken(Tok);
1715 continue;
1716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
Chris Lattnerf64b3522008-03-09 01:54:53 +00001718 // Get the next token of the macro.
1719 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001720
Chris Lattner83bd8282009-05-25 17:16:10 +00001721 // Check for a valid macro arg identifier.
1722 if (Tok.getIdentifierInfo() == 0 ||
1723 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1724
1725 // If this is assembler-with-cpp mode, we accept random gibberish after
1726 // the '#' because '#' is often a comment character. However, change
1727 // the kind of the token to tok::unknown so that the preprocessor isn't
1728 // confused.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001729 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001730 LastTok.setKind(tok::unknown);
1731 } else {
1732 Diag(Tok, diag::err_pp_stringize_not_parameter);
1733 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001734
Chris Lattner83bd8282009-05-25 17:16:10 +00001735 // Disable __VA_ARGS__ again.
1736 Ident__VA_ARGS__->setIsPoisoned(true);
1737 return;
1738 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001739 }
Mike Stump11289f42009-09-09 15:08:12 +00001740
Chris Lattner83bd8282009-05-25 17:16:10 +00001741 // Things look ok, add the '#' and param name tokens to the macro.
1742 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001743 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001744 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Chris Lattnerf64b3522008-03-09 01:54:53 +00001746 // Get the next token of the macro.
1747 LexUnexpandedToken(Tok);
1748 }
1749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
1751
Chris Lattnerf64b3522008-03-09 01:54:53 +00001752 // Disable __VA_ARGS__ again.
1753 Ident__VA_ARGS__->setIsPoisoned(true);
1754
Chris Lattner57540c52011-04-15 05:22:18 +00001755 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001756 // replacement list.
1757 unsigned NumTokens = MI->getNumTokens();
1758 if (NumTokens != 0) {
1759 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1760 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001761 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001762 return;
1763 }
1764 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1765 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001766 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001767 return;
1768 }
1769 }
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001771 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001772
Chris Lattnerf64b3522008-03-09 01:54:53 +00001773 // Finally, if this identifier already had a macro defined for it, verify that
1774 // the macro bodies are identical and free the old definition.
1775 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001776 // It is very common for system headers to have tons of macro redefinitions
1777 // and for warnings to be disabled in system headers. If this is the case,
1778 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001779 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001780 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001781 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001782 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001783
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001784 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001785 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001786 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001787 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001788 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1789 << MacroNameTok.getIdentifierInfo();
1790 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1791 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001792 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001793 if (OtherMI->isWarnIfUnused())
1794 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001795 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001796 }
Mike Stump11289f42009-09-09 15:08:12 +00001797
Chris Lattnerf64b3522008-03-09 01:54:53 +00001798 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001799
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001800 assert(!MI->isUsed());
1801 // If we need warning for not using the macro, add its location in the
1802 // warn-because-unused-macro set. If it gets used it will be removed from set.
1803 if (isInPrimaryFile() && // don't warn for include'd macros.
1804 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
David Blaikie9c902b52011-09-25 23:23:43 +00001805 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001806 MI->setIsWarnIfUnused(true);
1807 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1808 }
1809
Chris Lattner928e9092009-04-12 01:39:54 +00001810 // If the callbacks want to know, tell them about the macro definition.
1811 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001812 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001813}
1814
1815/// HandleUndefDirective - Implements #undef.
1816///
1817void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1818 ++NumUndefined;
1819
1820 Token MacroNameTok;
1821 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001822
Chris Lattnerf64b3522008-03-09 01:54:53 +00001823 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001824 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001825 return;
Mike Stump11289f42009-09-09 15:08:12 +00001826
Chris Lattnerf64b3522008-03-09 01:54:53 +00001827 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001828 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001829
Chris Lattnerf64b3522008-03-09 01:54:53 +00001830 // Okay, we finally have a valid identifier to undef.
1831 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001832
Chris Lattnerf64b3522008-03-09 01:54:53 +00001833 // If the macro is not defined, this is a noop undef, just return.
1834 if (MI == 0) return;
1835
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001836 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001837 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001838
1839 // If the callbacks want to know, tell them about the macro #undef.
1840 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001841 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001842
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001843 if (MI->isWarnIfUnused())
1844 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1845
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001847 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001848 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1849}
1850
1851
1852//===----------------------------------------------------------------------===//
1853// Preprocessor Conditional Directive Handling.
1854//===----------------------------------------------------------------------===//
1855
1856/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1857/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1858/// if any tokens have been returned or pp-directives activated before this
1859/// #ifndef has been lexed.
1860///
1861void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1862 bool ReadAnyTokensBeforeDirective) {
1863 ++NumIf;
1864 Token DirectiveTok = Result;
1865
1866 Token MacroNameTok;
1867 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001868
Chris Lattnerf64b3522008-03-09 01:54:53 +00001869 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001870 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871 // Skip code until we get to #endif. This helps with recovery by not
1872 // emitting an error when the #endif is reached.
1873 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1874 /*Foundnonskip*/false, /*FoundElse*/false);
1875 return;
1876 }
Mike Stump11289f42009-09-09 15:08:12 +00001877
Chris Lattnerf64b3522008-03-09 01:54:53 +00001878 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001879 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001880
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001881 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1882 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001883
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001884 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001885 // If the start of a top-level #ifdef and if the macro is not defined,
1886 // inform MIOpt that this might be the start of a proper include guard.
1887 // Otherwise it is some other form of unknown conditional which we can't
1888 // handle.
1889 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001890 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001891 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001892 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001893 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001894 }
1895
Chris Lattnerf64b3522008-03-09 01:54:53 +00001896 // If there is a macro, process it.
1897 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001898 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Chris Lattnerf64b3522008-03-09 01:54:53 +00001900 // Should we include the stuff contained by this directive?
1901 if (!MI == isIfndef) {
1902 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001903 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1904 /*wasskip*/false, /*foundnonskip*/true,
1905 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001906 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001907 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001908 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001909 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001910 /*FoundElse*/false);
1911 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001912
1913 if (Callbacks) {
1914 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001915 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001916 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001917 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001918 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001919}
1920
1921/// HandleIfDirective - Implements the #if directive.
1922///
1923void Preprocessor::HandleIfDirective(Token &IfToken,
1924 bool ReadAnyTokensBeforeDirective) {
1925 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001926
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001927 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001928 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001929 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1930 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1931 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001932
1933 // If this condition is equivalent to #ifndef X, and if this is the first
1934 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001935 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001936 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001937 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001938 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001939 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001940 }
1941
Chris Lattnerf64b3522008-03-09 01:54:53 +00001942 // Should we include the stuff contained by this directive?
1943 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001944 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001945 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001946 /*foundnonskip*/true, /*foundelse*/false);
1947 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001948 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001949 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001950 /*FoundElse*/false);
1951 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001952
1953 if (Callbacks)
1954 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001955}
1956
1957/// HandleEndifDirective - Implements the #endif directive.
1958///
1959void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1960 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001961
Chris Lattnerf64b3522008-03-09 01:54:53 +00001962 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001963 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001964
Chris Lattnerf64b3522008-03-09 01:54:53 +00001965 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001966 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001967 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001968 Diag(EndifToken, diag::err_pp_endif_without_if);
1969 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001970 }
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattnerf64b3522008-03-09 01:54:53 +00001972 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001973 if (CurPPLexer->getConditionalStackDepth() == 0)
1974 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001975
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001976 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001977 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001978
1979 if (Callbacks)
1980 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001981}
1982
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001983/// HandleElseDirective - Implements the #else directive.
1984///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001985void Preprocessor::HandleElseDirective(Token &Result) {
1986 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001987
Chris Lattnerf64b3522008-03-09 01:54:53 +00001988 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001989 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001990
Chris Lattnerf64b3522008-03-09 01:54:53 +00001991 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001992 if (CurPPLexer->popConditionalLevel(CI)) {
1993 Diag(Result, diag::pp_err_else_without_if);
1994 return;
1995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Chris Lattnerf64b3522008-03-09 01:54:53 +00001997 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001998 if (CurPPLexer->getConditionalStackDepth() == 0)
1999 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002000
2001 // If this is a #else with a #else before it, report the error.
2002 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002003
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002004 // Finally, skip the rest of the contents of this block.
2005 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002006 /*FoundElse*/true, Result.getLocation());
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002007
2008 if (Callbacks)
2009 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002010}
2011
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002012/// HandleElifDirective - Implements the #elif directive.
2013///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002014void Preprocessor::HandleElifDirective(Token &ElifToken) {
2015 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002016
Chris Lattnerf64b3522008-03-09 01:54:53 +00002017 // #elif directive in a non-skipping conditional... start skipping.
2018 // We don't care what the condition is, because we will always skip it (since
2019 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002020 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002021 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002022 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002023
2024 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002025 if (CurPPLexer->popConditionalLevel(CI)) {
2026 Diag(ElifToken, diag::pp_err_elif_without_if);
2027 return;
2028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Chris Lattnerf64b3522008-03-09 01:54:53 +00002030 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002031 if (CurPPLexer->getConditionalStackDepth() == 0)
2032 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002033
Chris Lattnerf64b3522008-03-09 01:54:53 +00002034 // If this is a #elif with a #else before it, report the error.
2035 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2036
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002037 // Finally, skip the rest of the contents of this block.
2038 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002039 /*FoundElse*/CI.FoundElse,
2040 ElifToken.getLocation());
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002041
2042 if (Callbacks)
2043 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002044}