blob: be70ceccfa5693e52fc47dcc16eb6ef3d81d3038 [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 Gregorc7d65762010-09-09 22:45:38 +000020#include "clang/Lex/Pragma.h"
Chris Lattner710bb872009-11-30 04:18:44 +000021#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000023#include "llvm/ADT/APInt.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000024using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Utility Methods for Preprocessor Directive Handling.
28//===----------------------------------------------------------------------===//
29
Chris Lattnerc0a585d2010-08-17 15:55:45 +000030MacroInfo *Preprocessor::AllocateMacroInfo() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000031 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000032
Ted Kremenekc8456f82010-10-19 22:15:20 +000033 if (MICache) {
34 MIChain = MICache;
35 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000036 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 else {
38 MIChain = BP.Allocate<MacroInfoChain>();
39 }
40
41 MIChain->Next = MIChainHead;
42 MIChain->Prev = 0;
43 if (MIChainHead)
44 MIChainHead->Prev = MIChain;
45 MIChainHead = MIChain;
46
47 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000048}
49
50MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
51 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000052 new (MI) MacroInfo(L);
53 return MI;
54}
55
Chris Lattnerc0a585d2010-08-17 15:55:45 +000056MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
57 MacroInfo *MI = AllocateMacroInfo();
58 new (MI) MacroInfo(MacroToClone, BP);
59 return MI;
60}
61
Chris Lattner666f7a42009-02-20 22:19:20 +000062/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
63/// be reused for allocating new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +000064void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +000065 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
66 if (MacroInfoChain *Prev = MIChain->Prev) {
67 MacroInfoChain *Next = MIChain->Next;
68 Prev->Next = Next;
69 if (Next)
70 Next->Prev = Prev;
71 }
72 else {
73 assert(MIChainHead == MIChain);
74 MIChainHead = MIChain->Next;
75 MIChainHead->Prev = 0;
76 }
77 MIChain->Next = MICache;
78 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +000079
Ted Kremenekc8456f82010-10-19 22:15:20 +000080 MI->Destroy();
81}
Chris Lattner666f7a42009-02-20 22:19:20 +000082
Chris Lattnerf64b3522008-03-09 01:54:53 +000083/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000084/// current line until the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000085void Preprocessor::DiscardUntilEndOfDirective() {
86 Token Tmp;
87 do {
88 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000089 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000090 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000091}
92
Chris Lattnerf64b3522008-03-09 01:54:53 +000093/// ReadMacroName - Lex and validate a macro name, which occurs after a
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000094/// #define or #undef. This sets the token kind to eod and discards the rest
Chris Lattnerf64b3522008-03-09 01:54:53 +000095/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
96/// this is due to a a #define, 2 if #undef directive, 0 if it is something
97/// else (e.g. #ifdef).
98void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
99 // Read the token, don't allow macro expansion on it.
100 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000101
Douglas Gregor12785102010-08-24 20:21:13 +0000102 if (MacroNameTok.is(tok::code_completion)) {
103 if (CodeComplete)
104 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000105 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000106 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000107 }
108
Chris Lattnerf64b3522008-03-09 01:54:53 +0000109 // Missing macro name?
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000110 if (MacroNameTok.is(tok::eod)) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000111 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
112 return;
113 }
Mike Stump11289f42009-09-09 15:08:12 +0000114
Chris Lattnerf64b3522008-03-09 01:54:53 +0000115 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
116 if (II == 0) {
Douglas Gregordc970f02010-03-16 22:30:13 +0000117 bool Invalid = false;
118 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
119 if (Invalid)
120 return;
121
Chris Lattner77c76ae2008-12-13 20:12:40 +0000122 const IdentifierInfo &Info = Identifiers.get(Spelling);
123 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattnerf64b3522008-03-09 01:54:53 +0000124 // C++ 2.5p2: Alternative tokens behave the same as its primary token
125 // except for their spellings.
Chris Lattner97b8e842008-11-18 08:02:48 +0000126 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000127 else
128 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
129 // Fall through on error.
130 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
131 // Error if defining "defined": C99 6.10.8.4.
132 Diag(MacroNameTok, diag::err_defined_macro_name);
133 } else if (isDefineUndef && II->hasMacroDefinition() &&
134 getMacroInfo(II)->isBuiltinMacro()) {
135 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
136 if (isDefineUndef == 1)
137 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
138 else
139 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
140 } else {
141 // Okay, we got a good identifier node. Return it.
142 return;
143 }
Mike Stump11289f42009-09-09 15:08:12 +0000144
Chris Lattnerf64b3522008-03-09 01:54:53 +0000145 // Invalid macro name, read and discard the rest of the line. Then set the
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000146 // token kind to tok::eod.
147 MacroNameTok.setKind(tok::eod);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000148 return DiscardUntilEndOfDirective();
149}
150
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000151/// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
152/// not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000153/// true, then we consider macros that expand to zero tokens as being ok.
154void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000155 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000156 // Lex unexpanded tokens for most directives: macros might expand to zero
157 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
158 // #line) allow empty macros.
159 if (EnableMacros)
160 Lex(Tmp);
161 else
162 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000163
Chris Lattnerf64b3522008-03-09 01:54:53 +0000164 // There should be no tokens after the directive, but we allow them as an
165 // extension.
166 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
167 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000169 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000170 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000171 // or if this is a macro-style preprocessing directive, because it is more
172 // trouble than it is worth to insert /**/ and check that there is no /**/
173 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000174 FixItHint Hint;
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000175 if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
176 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000177 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
178 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000179 DiscardUntilEndOfDirective();
180 }
181}
182
183
184
185/// SkipExcludedConditionalBlock - We just read a #if or related directive and
186/// decided that the subsequent tokens are in the #if'd out portion of the
187/// file. Lex the rest of the file, until we see an #endif. If
188/// FoundNonSkipPortion is true, then we have already emitted code for part of
189/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
190/// is true, then #else directives are ok, if not, then we have already seen one
191/// so a #else directive is a duplicate. When this returns, the caller can lex
192/// the first valid token.
193void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
194 bool FoundNonSkipPortion,
195 bool FoundElse) {
196 ++NumSkipped;
Ted Kremenek6b732912008-11-18 01:04:47 +0000197 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000198
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000199 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000200 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000201
Ted Kremenek56572ab2008-12-12 18:34:08 +0000202 if (CurPTHLexer) {
203 PTHSkipExcludedConditionalBlock();
204 return;
205 }
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattnerf64b3522008-03-09 01:54:53 +0000207 // Enter raw mode to disable identifier lookup (and thus macro expansion),
208 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000209 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 Token Tok;
211 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000212 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000213
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000214 if (Tok.is(tok::code_completion)) {
215 if (CodeComplete)
216 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000217 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000218 continue;
219 }
220
Chris Lattnerf64b3522008-03-09 01:54:53 +0000221 // If this is the end of the buffer, we have an error.
222 if (Tok.is(tok::eof)) {
223 // Emit errors for each unterminated conditional on the stack, including
224 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000225 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000226 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000227 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
228 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000229 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000230 }
231
Chris Lattnerf64b3522008-03-09 01:54:53 +0000232 // Just return and let the caller lex after this #include.
233 break;
234 }
Mike Stump11289f42009-09-09 15:08:12 +0000235
Chris Lattnerf64b3522008-03-09 01:54:53 +0000236 // If this token is not a preprocessor directive, just skip it.
237 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
238 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattnerf64b3522008-03-09 01:54:53 +0000240 // We just parsed a # character at the start of a line, so we're in
241 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000242 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000243 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenek59e003e2008-11-18 00:43:07 +0000244 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000245
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattnerf64b3522008-03-09 01:54:53 +0000247 // Read the next token, the directive flavor.
248 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattnerf64b3522008-03-09 01:54:53 +0000250 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
251 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000252 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000253 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000254 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000255 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000256 continue;
257 }
258
259 // If the first letter isn't i or e, it isn't intesting to us. We know that
260 // this is safe in the face of spelling differences, because there is no way
261 // to spell an i/e in a strange way that is another letter. Skipping this
262 // allows us to avoid looking up the identifier info for #define/#undef and
263 // other common directives.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000264 const char *RawCharData = Tok.getRawIdentifierData();
265
Chris Lattnerf64b3522008-03-09 01:54:53 +0000266 char FirstChar = RawCharData[0];
Mike Stump11289f42009-09-09 15:08:12 +0000267 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000268 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000269 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000270 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000271 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000272 continue;
273 }
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattnerf64b3522008-03-09 01:54:53 +0000275 // Get the identifier name without trigraphs or embedded newlines. Note
276 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
277 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000278 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000279 StringRef Directive;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000281 Directive = StringRef(RawCharData, Tok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +0000282 } else {
283 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000284 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000286 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000287 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000288 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000289 continue;
290 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000291 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000292 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000293 }
Mike Stump11289f42009-09-09 15:08:12 +0000294
Benjamin Kramer144884642009-12-31 13:32:38 +0000295 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000296 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000297 if (Sub.empty() || // "if"
298 Sub == "def" || // "ifdef"
299 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
301 // bother parsing the condition.
302 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000303 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000304 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000305 /*foundelse*/false);
306
307 if (Callbacks)
308 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000309 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000310 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000311 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000312 if (Sub == "ndif") { // "endif"
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000313 CheckEndOfDirective("endif");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 PPConditionalInfo CondInfo;
315 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000316 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000317 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000318 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 // If we popped the outermost skipping block, we're done skipping!
321 if (!CondInfo.WasSkipping)
322 break;
Benjamin Kramer144884642009-12-31 13:32:38 +0000323 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 // #else directive in a skipping conditional. If not in some other
325 // skipping conditional, and if #else hasn't already been seen, enter it
326 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000327 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 // If this is a #else with a #else before it, report the error.
330 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 // Note that we've seen a #else in this conditional.
333 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000334
Chandler Carruth540960f2011-01-03 17:40:17 +0000335 if (Callbacks)
336 Callbacks->Else();
337
Chris Lattnerf64b3522008-03-09 01:54:53 +0000338 // If the conditional is at the top level, and the #if block wasn't
339 // entered, enter the #else block now.
340 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
341 CondInfo.FoundNonSkip = true;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000342 CheckEndOfDirective("else");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000343 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000344 } else {
345 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000346 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000347 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000348 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349
350 bool ShouldEnter;
Chandler Carruth540960f2011-01-03 17:40:17 +0000351 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 // If this is in a skipping block or if we're already handled this #if
353 // block, don't bother parsing the condition.
354 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
355 DiscardUntilEndOfDirective();
356 ShouldEnter = false;
357 } else {
358 // Restore the value of LexingRawMode so that identifiers are
359 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000360 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
361 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 IdentifierInfo *IfNDefMacro = 0;
363 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000364 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365 }
Chandler Carruth540960f2011-01-03 17:40:17 +0000366 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattnerf64b3522008-03-09 01:54:53 +0000368 // If this is a #elif with a #else before it, report the error.
369 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chandler Carruth540960f2011-01-03 17:40:17 +0000371 if (Callbacks)
372 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
373
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374 // If this condition is true, enter it!
375 if (ShouldEnter) {
376 CondInfo.FoundNonSkip = true;
377 break;
378 }
379 }
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000382 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 // Restore comment saving mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +0000384 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 }
386
387 // Finally, if we are out of the conditional (saw an #endif or ran off the end
388 // of the file, just stop skipping and return to lexing whatever came after
389 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000390 CurPPLexer->LexingRawMode = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000391}
392
Ted Kremenek56572ab2008-12-12 18:34:08 +0000393void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000394
395 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000396 assert(CurPTHLexer);
397 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000398
Ted Kremenek56572ab2008-12-12 18:34:08 +0000399 // Skip to the next '#else', '#elif', or #endif.
400 if (CurPTHLexer->SkipBlock()) {
401 // We have reached an #endif. Both the '#' and 'endif' tokens
402 // have been consumed by the PTHLexer. Just pop off the condition level.
403 PPConditionalInfo CondInfo;
404 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000405 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000406 assert(!InCond && "Can't be skipping if not in a conditional!");
407 break;
408 }
Mike Stump11289f42009-09-09 15:08:12 +0000409
Ted Kremenek56572ab2008-12-12 18:34:08 +0000410 // We have reached a '#else' or '#elif'. Lex the next token to get
411 // the directive flavor.
412 Token Tok;
413 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000414
Ted Kremenek56572ab2008-12-12 18:34:08 +0000415 // We can actually look up the IdentifierInfo here since we aren't in
416 // raw mode.
417 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
418
419 if (K == tok::pp_else) {
420 // #else: Enter the else condition. We aren't in a nested condition
421 // since we skip those. We're always in the one matching the last
422 // blocked we skipped.
423 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
424 // Note that we've seen a #else in this conditional.
425 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000426
Ted Kremenek56572ab2008-12-12 18:34:08 +0000427 // If the #if block wasn't entered then enter the #else block now.
428 if (!CondInfo.FoundNonSkip) {
429 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000430
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000431 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000432 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000433 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000434 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000435
Ted Kremenek56572ab2008-12-12 18:34:08 +0000436 break;
437 }
Mike Stump11289f42009-09-09 15:08:12 +0000438
Ted Kremenek56572ab2008-12-12 18:34:08 +0000439 // Otherwise skip this block.
440 continue;
441 }
Mike Stump11289f42009-09-09 15:08:12 +0000442
Ted Kremenek56572ab2008-12-12 18:34:08 +0000443 assert(K == tok::pp_elif);
444 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
445
446 // If this is a #elif with a #else before it, report the error.
447 if (CondInfo.FoundElse)
448 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000449
Ted Kremenek56572ab2008-12-12 18:34:08 +0000450 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000451 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000452 if (CondInfo.FoundNonSkip)
453 continue;
454
455 // Evaluate the condition of the #elif.
456 IdentifierInfo *IfNDefMacro = 0;
457 CurPTHLexer->ParsingPreprocessorDirective = true;
458 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
459 CurPTHLexer->ParsingPreprocessorDirective = false;
460
461 // If this condition is true, enter it!
462 if (ShouldEnter) {
463 CondInfo.FoundNonSkip = true;
464 break;
465 }
466
467 // Otherwise, skip this block and go to the next one.
468 continue;
469 }
470}
471
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000472/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
473/// return null on failure. isAngled indicates whether the file reference is
474/// for system #include's or not (i.e. using <> instead of "").
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000475const FileEntry *Preprocessor::LookupFile(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000477 bool isAngled,
478 const DirectoryLookup *FromDir,
479 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 SmallVectorImpl<char> *SearchPath,
481 SmallVectorImpl<char> *RelativePath) {
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000482 // If the header lookup mechanism may be relative to the current file, pass in
483 // info about where the current file is.
Douglas Gregor618e64a2010-08-08 07:49:23 +0000484 const FileEntry *CurFileEnt = 0;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000485 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000486 FileID FID = getCurrentFileLexer()->getFileID();
Douglas Gregor618e64a2010-08-08 07:49:23 +0000487 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000488
Chris Lattner022923a2009-02-04 19:45:07 +0000489 // If there is no file entry associated with this file, it must be the
490 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000491 // it won't be scanned for preprocessor directives. If we have the
492 // predefines buffer, resolve #include references (which come from the
493 // -include command line argument) as if they came from the main file, this
494 // affects file lookup etc.
495 if (CurFileEnt == 0) {
Chris Lattner022923a2009-02-04 19:45:07 +0000496 FID = SourceMgr.getMainFileID();
497 CurFileEnt = SourceMgr.getFileEntryForID(FID);
498 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000501 // Do a standard file entry lookup.
502 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000503 const FileEntry *FE = HeaderInfo.LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000504 Filename, isAngled, FromDir, CurDir, CurFileEnt,
505 SearchPath, RelativePath);
Chris Lattnerfde85352010-01-22 00:14:44 +0000506 if (FE) return FE;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000508 // Otherwise, see if this is a subframework header. If so, this is relative
509 // to one of the headers on the #include stack. Walk the list of the current
510 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000511 if (IsFileLexer()) {
Ted Kremenek45245212008-11-19 21:57:25 +0000512 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000513 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000514 SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000515 return FE;
516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000518 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
519 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000520 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000521 if ((CurFileEnt =
Ted Kremenek45245212008-11-19 21:57:25 +0000522 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000523 if ((FE = HeaderInfo.LookupSubframeworkHeader(
524 Filename, CurFileEnt, SearchPath, RelativePath)))
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000525 return FE;
526 }
527 }
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000529 // Otherwise, we really couldn't find the file.
530 return 0;
531}
532
Chris Lattnerf64b3522008-03-09 01:54:53 +0000533
534//===----------------------------------------------------------------------===//
535// Preprocessor Directive Handling.
536//===----------------------------------------------------------------------===//
537
538/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000539/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000540/// lexer/preprocessor state, and advances the lexer(s) so that the next token
541/// read is the correct one.
542void Preprocessor::HandleDirective(Token &Result) {
543 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000544
Chris Lattnerf64b3522008-03-09 01:54:53 +0000545 // We just parsed a # character at the start of a line, so we're in directive
546 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000547 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000548 CurPPLexer->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattnerf64b3522008-03-09 01:54:53 +0000550 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000551
Chris Lattnerf64b3522008-03-09 01:54:53 +0000552 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000553 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000554 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000555 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattner2d17ab72009-03-18 21:00:25 +0000557 // Save the '#' token in case we need to return it later.
558 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattnerf64b3522008-03-09 01:54:53 +0000560 // Read the next token, the directive flavor. This isn't expanded due to
561 // C99 6.10.3p8.
562 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattnerf64b3522008-03-09 01:54:53 +0000564 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
565 // #define A(x) #x
566 // A(abc
567 // #warning blah
568 // def)
569 // If so, the user is relying on non-portable behavior, emit a diagnostic.
570 if (InMacroArgs)
571 Diag(Result, diag::ext_embedded_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Chris Lattnerf64b3522008-03-09 01:54:53 +0000573TryAgain:
574 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000575 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000576 return; // null directive.
577 case tok::comment:
578 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
579 LexUnexpandedToken(Result);
580 goto TryAgain;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000581 case tok::code_completion:
582 if (CodeComplete)
583 CodeComplete->CodeCompleteDirective(
584 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000585 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000586 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000587 case tok::numeric_constant: // # 7 GNU line marker directive.
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000588 if (getLangOptions().AsmPreprocessor)
589 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000590 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000591 default:
592 IdentifierInfo *II = Result.getIdentifierInfo();
593 if (II == 0) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chris Lattnerf64b3522008-03-09 01:54:53 +0000595 // Ask what the preprocessor keyword ID is.
596 switch (II->getPPKeywordID()) {
597 default: break;
598 // C99 6.10.1 - Conditional Inclusion.
599 case tok::pp_if:
600 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
601 case tok::pp_ifdef:
602 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
603 case tok::pp_ifndef:
604 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
605 case tok::pp_elif:
606 return HandleElifDirective(Result);
607 case tok::pp_else:
608 return HandleElseDirective(Result);
609 case tok::pp_endif:
610 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000611
Chris Lattnerf64b3522008-03-09 01:54:53 +0000612 // C99 6.10.2 - Source File Inclusion.
613 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000614 // Handle #include.
615 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000616 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000617 // Handle -imacros.
618 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattnerf64b3522008-03-09 01:54:53 +0000620 // C99 6.10.3 - Macro Replacement.
621 case tok::pp_define:
622 return HandleDefineDirective(Result);
623 case tok::pp_undef:
624 return HandleUndefDirective(Result);
625
626 // C99 6.10.4 - Line Control.
627 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000628 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000629
Chris Lattnerf64b3522008-03-09 01:54:53 +0000630 // C99 6.10.5 - Error Directive.
631 case tok::pp_error:
632 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattnerf64b3522008-03-09 01:54:53 +0000634 // C99 6.10.6 - Pragma Directive.
635 case tok::pp_pragma:
Douglas Gregorc7d65762010-09-09 22:45:38 +0000636 return HandlePragmaDirective(PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000637
Chris Lattnerf64b3522008-03-09 01:54:53 +0000638 // GNU Extensions.
639 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000640 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000641 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000642 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000643
Chris Lattnerf64b3522008-03-09 01:54:53 +0000644 case tok::pp_warning:
645 Diag(Result, diag::ext_pp_warning_directive);
646 return HandleUserDiagnosticDirective(Result, true);
647 case tok::pp_ident:
648 return HandleIdentSCCSDirective(Result);
649 case tok::pp_sccs:
650 return HandleIdentSCCSDirective(Result);
651 case tok::pp_assert:
652 //isExtension = true; // FIXME: implement #assert
653 break;
654 case tok::pp_unassert:
655 //isExtension = true; // FIXME: implement #unassert
656 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000657
658 case tok::pp___export_macro__:
659 return HandleMacroExportDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000660 }
661 break;
662 }
Mike Stump11289f42009-09-09 15:08:12 +0000663
Chris Lattner2d17ab72009-03-18 21:00:25 +0000664 // If this is a .S file, treat unknown # directives as non-preprocessor
665 // directives. This is important because # may be a comment or introduce
666 // various pseudo-ops. Just return the # token and push back the following
667 // token to be lexed next time.
668 if (getLangOptions().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000669 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000670 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000671 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000672 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000673
674 // If the second token is a hashhash token, then we need to translate it to
675 // unknown so the token lexer doesn't try to perform token pasting.
676 if (Result.is(tok::hashhash))
677 Toks[1].setKind(tok::unknown);
678
Chris Lattner2d17ab72009-03-18 21:00:25 +0000679 // Enter this token stream so that we re-lex the tokens. Make sure to
680 // enable macro expansion, in case the token after the # is an identifier
681 // that is expanded.
682 EnterTokenStream(Toks, 2, false, true);
683 return;
684 }
Mike Stump11289f42009-09-09 15:08:12 +0000685
Chris Lattnerf64b3522008-03-09 01:54:53 +0000686 // If we reached here, the preprocessing token is not valid!
687 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000688
Chris Lattnerf64b3522008-03-09 01:54:53 +0000689 // Read the rest of the PP line.
690 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattnerf64b3522008-03-09 01:54:53 +0000692 // Okay, we're done parsing the directive.
693}
694
Chris Lattner76e68962009-01-26 06:19:46 +0000695/// GetLineValue - Convert a numeric token into an unsigned value, emitting
696/// Diagnostic DiagID if it is invalid, and returning the value in Val.
697static bool GetLineValue(Token &DigitTok, unsigned &Val,
698 unsigned DiagID, Preprocessor &PP) {
699 if (DigitTok.isNot(tok::numeric_constant)) {
700 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000701
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000702 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000703 PP.DiscardUntilEndOfDirective();
704 return true;
705 }
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner76e68962009-01-26 06:19:46 +0000707 llvm::SmallString<64> IntegerBuffer;
708 IntegerBuffer.resize(DigitTok.getLength());
709 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000710 bool Invalid = false;
711 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
712 if (Invalid)
713 return true;
714
Chris Lattnerd66f1722009-04-18 18:35:15 +0000715 // Verify that we have a simple digit-sequence, and compute the value. This
716 // is always a simple digit string computed in decimal, so we do this manually
717 // here.
718 Val = 0;
719 for (unsigned i = 0; i != ActualLength; ++i) {
720 if (!isdigit(DigitTokBegin[i])) {
721 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
722 diag::err_pp_line_digit_sequence);
723 PP.DiscardUntilEndOfDirective();
724 return true;
725 }
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattnerd66f1722009-04-18 18:35:15 +0000727 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
728 if (NextVal < Val) { // overflow.
729 PP.Diag(DigitTok, DiagID);
730 PP.DiscardUntilEndOfDirective();
731 return true;
732 }
733 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000734 }
Mike Stump11289f42009-09-09 15:08:12 +0000735
736 // Reject 0, this is needed both by #line numbers and flags.
Chris Lattner76e68962009-01-26 06:19:46 +0000737 if (Val == 0) {
738 PP.Diag(DigitTok, DiagID);
739 PP.DiscardUntilEndOfDirective();
740 return true;
741 }
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattnerd66f1722009-04-18 18:35:15 +0000743 if (DigitTokBegin[0] == '0')
744 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattner76e68962009-01-26 06:19:46 +0000746 return false;
747}
748
Mike Stump11289f42009-09-09 15:08:12 +0000749/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
Chris Lattner100c65e2009-01-26 05:29:08 +0000750/// acceptable forms are:
751/// # line digit-sequence
752/// # line digit-sequence "s-char-sequence"
753void Preprocessor::HandleLineDirective(Token &Tok) {
754 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
755 // expanded.
756 Token DigitTok;
757 Lex(DigitTok);
758
Chris Lattner100c65e2009-01-26 05:29:08 +0000759 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000760 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000761 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000762 return;
Chris Lattner100c65e2009-01-26 05:29:08 +0000763
Chris Lattner76e68962009-01-26 06:19:46 +0000764 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
765 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Chris Lattner100c65e2009-01-26 05:29:08 +0000766 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
767 if (LineNo >= LineLimit)
768 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Mike Stump11289f42009-09-09 15:08:12 +0000769
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000770 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000771 Token StrTok;
772 Lex(StrTok);
773
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000774 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
775 // string followed by eod.
776 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000777 ; // ok
778 else if (StrTok.isNot(tok::string_literal)) {
779 Diag(StrTok, diag::err_pp_line_invalid_filename);
780 DiscardUntilEndOfDirective();
781 return;
782 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000783 // Parse and validate the string, converting it into a unique ID.
784 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000785 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000786 if (Literal.hadError)
787 return DiscardUntilEndOfDirective();
788 if (Literal.Pascal) {
789 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
790 return DiscardUntilEndOfDirective();
791 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000792 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000793
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000794 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000795 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
796 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000799 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000800
Chris Lattner839150e2009-03-27 17:13:49 +0000801 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000802 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
803 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000804 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000805}
806
Chris Lattner76e68962009-01-26 06:19:46 +0000807/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
808/// marker directive.
809static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
810 bool &IsSystemHeader, bool &IsExternCHeader,
811 Preprocessor &PP) {
812 unsigned FlagVal;
813 Token FlagTok;
814 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000815 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000816 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
817 return true;
818
819 if (FlagVal == 1) {
820 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000821
Chris Lattner76e68962009-01-26 06:19:46 +0000822 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000823 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000824 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
825 return true;
826 } else if (FlagVal == 2) {
827 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chris Lattner1c967782009-02-04 06:25:26 +0000829 SourceManager &SM = PP.getSourceManager();
830 // If we are leaving the current presumed file, check to make sure the
831 // presumed include stack isn't empty!
832 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000833 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +0000834 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000835 if (PLoc.isInvalid())
836 return true;
837
Chris Lattner1c967782009-02-04 06:25:26 +0000838 // If there is no include loc (main file) or if the include loc is in a
839 // different physical file, then we aren't in a "1" line marker flag region.
840 SourceLocation IncLoc = PLoc.getIncludeLoc();
841 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000842 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +0000843 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
844 PP.DiscardUntilEndOfDirective();
845 return true;
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattner76e68962009-01-26 06:19:46 +0000848 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000849 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000850 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
851 return true;
852 }
853
854 // We must have 3 if there are still flags.
855 if (FlagVal != 3) {
856 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000857 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000858 return true;
859 }
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner76e68962009-01-26 06:19:46 +0000861 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattner76e68962009-01-26 06:19:46 +0000863 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000864 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000865 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +0000866 return true;
867
868 // We must have 4 if there is yet another flag.
869 if (FlagVal != 4) {
870 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000871 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000872 return true;
873 }
Mike Stump11289f42009-09-09 15:08:12 +0000874
Chris Lattner76e68962009-01-26 06:19:46 +0000875 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +0000876
Chris Lattner76e68962009-01-26 06:19:46 +0000877 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000878 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000879
880 // There are no more valid flags here.
881 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000882 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000883 return true;
884}
885
886/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
887/// one of the following forms:
888///
889/// # 42
Mike Stump11289f42009-09-09 15:08:12 +0000890/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +0000891/// # 42 "file" ('1' | '2')? '3' '4'?
892///
893void Preprocessor::HandleDigitDirective(Token &DigitTok) {
894 // Validate the number and convert it to an unsigned. GNU does not have a
895 // line # limit other than it fit in 32-bits.
896 unsigned LineNo;
897 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
898 *this))
899 return;
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattner76e68962009-01-26 06:19:46 +0000901 Token StrTok;
902 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner76e68962009-01-26 06:19:46 +0000904 bool IsFileEntry = false, IsFileExit = false;
905 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000906 int FilenameID = -1;
907
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000908 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
909 // string followed by eod.
910 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000911 ; // ok
912 else if (StrTok.isNot(tok::string_literal)) {
913 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000914 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +0000915 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000916 // Parse and validate the string, converting it into a unique ID.
917 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000918 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000919 if (Literal.hadError)
920 return DiscardUntilEndOfDirective();
921 if (Literal.Pascal) {
922 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
923 return DiscardUntilEndOfDirective();
924 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000925 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000926
Chris Lattner76e68962009-01-26 06:19:46 +0000927 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +0000928 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000929 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +0000930 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000931 }
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000933 // Create a line note with this information.
934 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +0000935 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000936 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner839150e2009-03-27 17:13:49 +0000938 // If the preprocessor has callbacks installed, notify them of the #line
939 // change. This is used so that the line marker comes out in -E mode for
940 // example.
941 if (Callbacks) {
942 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
943 if (IsFileEntry)
944 Reason = PPCallbacks::EnterFile;
945 else if (IsFileExit)
946 Reason = PPCallbacks::ExitFile;
947 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
948 if (IsExternCHeader)
949 FileKind = SrcMgr::C_ExternCSystem;
950 else if (IsSystemHeader)
951 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +0000952
Chris Lattnerc745cec2010-04-14 04:28:50 +0000953 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +0000954 }
Chris Lattner76e68962009-01-26 06:19:46 +0000955}
956
957
Chris Lattner38d7fd22009-01-26 05:30:54 +0000958/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
959///
Mike Stump11289f42009-09-09 15:08:12 +0000960void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000961 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +0000962 // PTH doesn't emit #warning or #error directives.
963 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +0000964 return CurPTHLexer->DiscardToEndOfLine();
965
Chris Lattnerf64b3522008-03-09 01:54:53 +0000966 // Read the rest of the line raw. We do this because we don't want macros
967 // to be expanded and we don't require that the tokens be valid preprocessing
968 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
969 // collapse multiple consequtive white space between tokens, but this isn't
970 // specified by the standard.
Chris Lattner100c65e2009-01-26 05:29:08 +0000971 std::string Message = CurLexer->ReadToEndOfLine();
972 if (isWarning)
973 Diag(Tok, diag::pp_hash_warning) << Message;
974 else
975 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000976}
977
978/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
979///
980void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
981 // Yes, this directive is an extension.
982 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000983
Chris Lattnerf64b3522008-03-09 01:54:53 +0000984 // Read the string argument.
985 Token StrTok;
986 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000987
Chris Lattnerf64b3522008-03-09 01:54:53 +0000988 // If the token kind isn't a string, it's a malformed directive.
989 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +0000990 StrTok.isNot(tok::wide_string_literal)) {
991 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000992 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +0000993 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000994 return;
995 }
Mike Stump11289f42009-09-09 15:08:12 +0000996
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000997 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000998 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000999
Douglas Gregordc970f02010-03-16 22:30:13 +00001000 if (Callbacks) {
1001 bool Invalid = false;
1002 std::string Str = getSpelling(StrTok, &Invalid);
1003 if (!Invalid)
1004 Callbacks->Ident(Tok.getLocation(), Str);
1005 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001006}
1007
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001008/// \brief Handle a #__export_macro__ directive.
1009void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1010 Token MacroNameTok;
1011 ReadMacroName(MacroNameTok, 2);
1012
1013 // Error reading macro name? If so, diagnostic already issued.
1014 if (MacroNameTok.is(tok::eod))
1015 return;
1016
1017 // Check to see if this is the last token on the #__export_macro__ line.
1018 CheckEndOfDirective("__export_macro__");
1019
1020 // Okay, we finally have a valid identifier to undef.
1021 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1022
1023 // If the macro is not defined, this is an error.
1024 if (MI == 0) {
1025 Diag(MacroNameTok, diag::err_pp_export_non_macro)
1026 << MacroNameTok.getIdentifierInfo();
1027 return;
1028 }
1029
1030 // Note that this macro has now been exported.
1031 MI->setExportLocation(MacroNameTok.getLocation());
1032
1033 // If this macro definition came from a PCH file, mark it
1034 // as having changed since serialization.
1035 if (MI->isFromAST())
1036 MI->setChangedAfterLoad();
1037}
1038
Chris Lattnerf64b3522008-03-09 01:54:53 +00001039//===----------------------------------------------------------------------===//
1040// Preprocessor Include Directive Handling.
1041//===----------------------------------------------------------------------===//
1042
1043/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1044/// checked and spelled filename, e.g. as an operand of #include. This returns
1045/// true if the input filename was in <>'s or false if it were in ""'s. The
1046/// caller is expected to provide a buffer that is large enough to hold the
1047/// spelling of the filename, but is also expected to handle the case when
1048/// this method decides to use a different buffer.
1049bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001050 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001051 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001052 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001053
Chris Lattnerf64b3522008-03-09 01:54:53 +00001054 // Make sure the filename is <x> or "x".
1055 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001056 if (Buffer[0] == '<') {
1057 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001058 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001059 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001060 return true;
1061 }
1062 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001063 } else if (Buffer[0] == '"') {
1064 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001065 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001066 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001067 return true;
1068 }
1069 isAngled = false;
1070 } else {
1071 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001073 return true;
1074 }
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chris Lattnerf64b3522008-03-09 01:54:53 +00001076 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001077 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001078 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001079 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001080 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Chris Lattnerf64b3522008-03-09 01:54:53 +00001083 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001084 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001085 return isAngled;
1086}
1087
1088/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1089/// from a macro as multiple tokens, which need to be glued together. This
1090/// occurs for code like:
1091/// #define FOO <a/b.h>
1092/// #include FOO
1093/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1094///
1095/// This code concatenates and consumes tokens up to the '>' token. It returns
1096/// false if the > was found, otherwise it returns true if it finds and consumes
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001097/// the EOD marker.
John Thompsonb5353522009-10-30 13:49:06 +00001098bool Preprocessor::ConcatenateIncludeName(
Douglas Gregor796d76a2010-10-20 22:00:55 +00001099 llvm::SmallString<128> &FilenameBuffer,
1100 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001101 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001102
John Thompsonb5353522009-10-30 13:49:06 +00001103 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001104 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001105 End = CurTok.getLocation();
1106
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001107 // FIXME: Provide code completion for #includes.
1108 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001109 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001110 Lex(CurTok);
1111 continue;
1112 }
1113
Chris Lattnerf64b3522008-03-09 01:54:53 +00001114 // Append the spelling of this token to the buffer. If there was a space
1115 // before it, add it now.
1116 if (CurTok.hasLeadingSpace())
1117 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001118
Chris Lattnerf64b3522008-03-09 01:54:53 +00001119 // Get the spelling of the token, directly into FilenameBuffer if possible.
1120 unsigned PreAppendSize = FilenameBuffer.size();
1121 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001122
Chris Lattnerf64b3522008-03-09 01:54:53 +00001123 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001124 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattnerf64b3522008-03-09 01:54:53 +00001126 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1127 if (BufPtr != &FilenameBuffer[PreAppendSize])
1128 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001129
Chris Lattnerf64b3522008-03-09 01:54:53 +00001130 // Resize FilenameBuffer to the correct size.
1131 if (CurTok.getLength() != ActualLen)
1132 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattnerf64b3522008-03-09 01:54:53 +00001134 // If we found the '>' marker, return success.
1135 if (CurTok.is(tok::greater))
1136 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001137
John Thompsonb5353522009-10-30 13:49:06 +00001138 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001139 }
1140
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001141 // If we hit the eod marker, emit an error and return true so that the caller
1142 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001143 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001144 return true;
1145}
1146
1147/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1148/// file to be included from the lexer, then include it! This is a common
1149/// routine with functionality shared between #include, #include_next and
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001150/// #import. LookupFrom is set when this is a #include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001151/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001152void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1153 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001154 const DirectoryLookup *LookupFrom,
1155 bool isImport) {
1156
1157 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001158 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001159
Chris Lattnerf64b3522008-03-09 01:54:53 +00001160 // Reserve a buffer to get the spelling.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001161 llvm::SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001162 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001163 SourceLocation End;
1164
Chris Lattnerf64b3522008-03-09 01:54:53 +00001165 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001166 case tok::eod:
1167 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001168 return;
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattnerf64b3522008-03-09 01:54:53 +00001170 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001171 case tok::string_literal:
1172 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001173 End = FilenameTok.getLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001174 break;
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattnerf64b3522008-03-09 01:54:53 +00001176 case tok::less:
1177 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1178 // case, glue the tokens together into FilenameBuffer and interpret those.
1179 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001180 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001181 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001182 Filename = FilenameBuffer.str();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001183 break;
1184 default:
1185 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1186 DiscardUntilEndOfDirective();
1187 return;
1188 }
Mike Stump11289f42009-09-09 15:08:12 +00001189
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001190 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001191 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001192 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1193 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001194 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001195 DiscardUntilEndOfDirective();
1196 return;
1197 }
Mike Stump11289f42009-09-09 15:08:12 +00001198
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001199 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001200 // we allow macros that expand to nothing after the filename, because this
1201 // falls into the category of "#include pp-tokens new-line" specified in
1202 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001203 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001204
1205 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001206 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1207 Diag(FilenameTok, diag::err_pp_include_too_deep);
1208 return;
1209 }
Mike Stump11289f42009-09-09 15:08:12 +00001210
Chris Lattnerf64b3522008-03-09 01:54:53 +00001211 // Search include directories.
1212 const DirectoryLookup *CurDir;
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001213 llvm::SmallString<1024> SearchPath;
1214 llvm::SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001215 // We get the raw path only if we have 'Callbacks' to which we later pass
1216 // the path.
1217 const FileEntry *File = LookupFile(
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001218 Filename, isAngled, LookupFrom, CurDir,
1219 Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001220
Douglas Gregor796d76a2010-10-20 22:00:55 +00001221 // Notify the callback object that we've seen an inclusion directive.
1222 if (Callbacks)
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001223 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001224 End, SearchPath, RelativePath);
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001225
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001226 if (File == 0) {
Eli Friedman3781a362011-08-30 23:07:51 +00001227 if (!SuppressIncludeNotFoundError)
1228 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001229 return;
1230 }
1231
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001232 // The #included file will be considered to be a system header if either it is
1233 // in a system include directory, or if the #includer is a system include
1234 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001235 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001236 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001237 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001238
Chris Lattner72286d62010-04-19 20:44:31 +00001239 // Ask HeaderInfo if we should enter this #include file. If not, #including
1240 // this file will have no effect.
1241 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001242 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001243 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001244 return;
1245 }
1246
Chris Lattnerf64b3522008-03-09 01:54:53 +00001247 // Look up the file, create a File ID for it.
Chris Lattnerd32480d2009-01-17 06:22:33 +00001248 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1249 FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001250 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001251
1252 // Finally, if all is good, enter the new file!
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001253 EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254}
1255
1256/// HandleIncludeNextDirective - Implements #include_next.
1257///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001258void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1259 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001260 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattnerf64b3522008-03-09 01:54:53 +00001262 // #include_next is like #include, except that we start searching after
1263 // the current found directory. If we can't do this, issue a
1264 // diagnostic.
1265 const DirectoryLookup *Lookup = CurDirLookup;
1266 if (isInPrimaryFile()) {
1267 Lookup = 0;
1268 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1269 } else if (Lookup == 0) {
1270 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1271 } else {
1272 // Start looking up in the next directory.
1273 ++Lookup;
1274 }
Mike Stump11289f42009-09-09 15:08:12 +00001275
Douglas Gregor796d76a2010-10-20 22:00:55 +00001276 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001277}
1278
1279/// HandleImportDirective - Implements #import.
1280///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001281void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1282 Token &ImportTok) {
Chris Lattnerd4a96732009-03-06 04:28:03 +00001283 if (!Features.ObjC1) // #import is standard for ObjC.
1284 Diag(ImportTok, diag::ext_pp_import_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001285
Douglas Gregor796d76a2010-10-20 22:00:55 +00001286 return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001287}
1288
Chris Lattner58a1eb02009-04-08 18:46:40 +00001289/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1290/// pseudo directive in the predefines buffer. This handles it by sucking all
1291/// tokens through the preprocessor and discarding them (only keeping the side
1292/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001293void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1294 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001295 // This directive should only occur in the predefines buffer. If not, emit an
1296 // error and reject it.
1297 SourceLocation Loc = IncludeMacrosTok.getLocation();
1298 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1299 Diag(IncludeMacrosTok.getLocation(),
1300 diag::pp_include_macros_out_of_predefines);
1301 DiscardUntilEndOfDirective();
1302 return;
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Chris Lattnere01d82b2009-04-08 20:53:24 +00001305 // Treat this as a normal #include for checking purposes. If this is
1306 // successful, it will push a new lexer onto the include stack.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001307 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattnere01d82b2009-04-08 20:53:24 +00001309 Token TmpTok;
1310 do {
1311 Lex(TmpTok);
1312 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1313 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001314}
1315
Chris Lattnerf64b3522008-03-09 01:54:53 +00001316//===----------------------------------------------------------------------===//
1317// Preprocessor Macro Directive Handling.
1318//===----------------------------------------------------------------------===//
1319
1320/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1321/// definition has just been read. Lex the rest of the arguments and the
1322/// closing ), updating MI with what we learn. Return true if an error occurs
1323/// parsing the arg list.
1324bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001325 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001326
Chris Lattnerf64b3522008-03-09 01:54:53 +00001327 Token Tok;
1328 while (1) {
1329 LexUnexpandedToken(Tok);
1330 switch (Tok.getKind()) {
1331 case tok::r_paren:
1332 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001333 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001334 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001335 // Otherwise we have #define FOO(A,)
1336 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1337 return true;
1338 case tok::ellipsis: // #define X(... -> C99 varargs
Eli Friedman4acfbcd2011-08-22 18:48:28 +00001339 if (!Features.C99 && !Features.CPlusPlus0x)
1340 Diag(Tok, diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001341
1342 // Lex the token after the identifier.
1343 LexUnexpandedToken(Tok);
1344 if (Tok.isNot(tok::r_paren)) {
1345 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1346 return true;
1347 }
1348 // Add the __VA_ARGS__ identifier as an argument.
1349 Arguments.push_back(Ident__VA_ARGS__);
1350 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001351 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001352 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001353 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1355 return true;
1356 default:
1357 // Handle keywords and identifiers here to accept things like
1358 // #define Foo(for) for.
1359 IdentifierInfo *II = Tok.getIdentifierInfo();
1360 if (II == 0) {
1361 // #define X(1
1362 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1363 return true;
1364 }
1365
1366 // If this is already used as an argument, it is used multiple times (e.g.
1367 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001368 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001369 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001370 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001371 return true;
1372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
Chris Lattnerf64b3522008-03-09 01:54:53 +00001374 // Add the argument to the macro info.
1375 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattnerf64b3522008-03-09 01:54:53 +00001377 // Lex the token after the identifier.
1378 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001379
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380 switch (Tok.getKind()) {
1381 default: // #define X(A B
1382 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1383 return true;
1384 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001385 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001386 return false;
1387 case tok::comma: // #define X(A,
1388 break;
1389 case tok::ellipsis: // #define X(A... -> GCC extension
1390 // Diagnose extension.
1391 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattnerf64b3522008-03-09 01:54:53 +00001393 // Lex the token after the identifier.
1394 LexUnexpandedToken(Tok);
1395 if (Tok.isNot(tok::r_paren)) {
1396 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1397 return true;
1398 }
Mike Stump11289f42009-09-09 15:08:12 +00001399
Chris Lattnerf64b3522008-03-09 01:54:53 +00001400 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001401 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001402 return false;
1403 }
1404 }
1405 }
1406}
1407
1408/// HandleDefineDirective - Implements #define. This consumes the entire macro
1409/// line then lets the caller lex the next real token.
1410void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1411 ++NumDefined;
1412
1413 Token MacroNameTok;
1414 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattnerf64b3522008-03-09 01:54:53 +00001416 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001417 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001418 return;
1419
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001420 Token LastTok = MacroNameTok;
1421
Chris Lattnerf64b3522008-03-09 01:54:53 +00001422 // If we are supposed to keep comments in #defines, reenable comment saving
1423 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001424 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Chris Lattnerf64b3522008-03-09 01:54:53 +00001426 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001427 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001428
Chris Lattnerf64b3522008-03-09 01:54:53 +00001429 Token Tok;
1430 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001431
Chris Lattnerf64b3522008-03-09 01:54:53 +00001432 // If this is a function-like macro definition, parse the argument list,
1433 // marking each of the identifiers as being used as macro arguments. Also,
1434 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001435 if (Tok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001436 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001437 } else if (Tok.hasLeadingSpace()) {
1438 // This is a normal token with leading space. Clear the leading space
1439 // marker on the first token to get proper expansion.
1440 Tok.clearFlag(Token::LeadingSpace);
1441 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001442 // This is a function-like macro definition. Read the argument list.
1443 MI->setIsFunctionLike();
1444 if (ReadMacroDefinitionArgList(MI)) {
1445 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001446 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001447 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001448 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001449 DiscardUntilEndOfDirective();
1450 return;
1451 }
1452
Chris Lattner249c38b2009-04-19 18:26:34 +00001453 // If this is a definition of a variadic C99 function-like macro, not using
1454 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001455
Chris Lattner249c38b2009-04-19 18:26:34 +00001456 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1457 // This gets unpoisoned where it is allowed.
1458 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1459 if (MI->isC99Varargs())
1460 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Chris Lattnerf64b3522008-03-09 01:54:53 +00001462 // Read the first token after the arg list for down below.
1463 LexUnexpandedToken(Tok);
Chris Lattner2425bcb2009-04-18 02:23:25 +00001464 } else if (Features.C99) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001465 // C99 requires whitespace between the macro definition and the body. Emit
1466 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001467 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001468 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001469 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1470 // first character of a replacement list is not a character required by
1471 // subclause 5.2.1, then there shall be white-space separation between the
1472 // identifier and the replacement list.". 5.2.1 lists this set:
1473 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1474 // is irrelevant here.
1475 bool isInvalid = false;
1476 if (Tok.is(tok::at)) // @ is not in the list above.
1477 isInvalid = true;
1478 else if (Tok.is(tok::unknown)) {
1479 // If we have an unknown token, it is something strange like "`". Since
1480 // all of valid characters would have lexed into a single character
1481 // token of some sort, we know this is not a valid case.
1482 isInvalid = true;
1483 }
1484 if (isInvalid)
1485 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1486 else
1487 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001488 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001489
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001490 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001491 LastTok = Tok;
1492
Chris Lattnerf64b3522008-03-09 01:54:53 +00001493 // Read the rest of the macro body.
1494 if (MI->isObjectLike()) {
1495 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001496 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001497 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001498 MI->AddTokenToBody(Tok);
1499 // Get the next token of the macro.
1500 LexUnexpandedToken(Tok);
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502
Chris Lattnerf64b3522008-03-09 01:54:53 +00001503 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001504 // Otherwise, read the body of a function-like macro. While we are at it,
1505 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1506 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001507 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001508 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001509
Chris Lattnerf64b3522008-03-09 01:54:53 +00001510 if (Tok.isNot(tok::hash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001511 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001512
Chris Lattnerf64b3522008-03-09 01:54:53 +00001513 // Get the next token of the macro.
1514 LexUnexpandedToken(Tok);
1515 continue;
1516 }
Mike Stump11289f42009-09-09 15:08:12 +00001517
Chris Lattnerf64b3522008-03-09 01:54:53 +00001518 // Get the next token of the macro.
1519 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001520
Chris Lattner83bd8282009-05-25 17:16:10 +00001521 // Check for a valid macro arg identifier.
1522 if (Tok.getIdentifierInfo() == 0 ||
1523 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1524
1525 // If this is assembler-with-cpp mode, we accept random gibberish after
1526 // the '#' because '#' is often a comment character. However, change
1527 // the kind of the token to tok::unknown so that the preprocessor isn't
1528 // confused.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001529 if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001530 LastTok.setKind(tok::unknown);
1531 } else {
1532 Diag(Tok, diag::err_pp_stringize_not_parameter);
1533 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001534
Chris Lattner83bd8282009-05-25 17:16:10 +00001535 // Disable __VA_ARGS__ again.
1536 Ident__VA_ARGS__->setIsPoisoned(true);
1537 return;
1538 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001539 }
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattner83bd8282009-05-25 17:16:10 +00001541 // Things look ok, add the '#' and param name tokens to the macro.
1542 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001543 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00001544 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00001545
Chris Lattnerf64b3522008-03-09 01:54:53 +00001546 // Get the next token of the macro.
1547 LexUnexpandedToken(Tok);
1548 }
1549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
1551
Chris Lattnerf64b3522008-03-09 01:54:53 +00001552 // Disable __VA_ARGS__ again.
1553 Ident__VA_ARGS__->setIsPoisoned(true);
1554
Chris Lattner57540c52011-04-15 05:22:18 +00001555 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00001556 // replacement list.
1557 unsigned NumTokens = MI->getNumTokens();
1558 if (NumTokens != 0) {
1559 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1560 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001561 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001562 return;
1563 }
1564 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1565 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001566 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001567 return;
1568 }
1569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001571 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnerf64b3522008-03-09 01:54:53 +00001573 // Finally, if this identifier already had a macro defined for it, verify that
1574 // the macro bodies are identical and free the old definition.
1575 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00001576 // It is very common for system headers to have tons of macro redefinitions
1577 // and for warnings to be disabled in system headers. If this is the case,
1578 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00001579 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00001580 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001581 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00001582 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001583
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001584 // Macros must be identical. This means all tokens and whitespace
Chris Lattner5244f342009-01-16 19:50:11 +00001585 // separation must be the same. C99 6.10.3.2.
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001586 if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Eli Friedman04831922010-08-22 01:00:03 +00001587 !MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattner5244f342009-01-16 19:50:11 +00001588 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1589 << MacroNameTok.getIdentifierInfo();
1590 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1591 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001592 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00001593 if (OtherMI->isWarnIfUnused())
1594 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001595 ReleaseMacroInfo(OtherMI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001596 }
Mike Stump11289f42009-09-09 15:08:12 +00001597
Chris Lattnerf64b3522008-03-09 01:54:53 +00001598 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00001599
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001600 assert(!MI->isUsed());
1601 // If we need warning for not using the macro, add its location in the
1602 // warn-because-unused-macro set. If it gets used it will be removed from set.
1603 if (isInPrimaryFile() && // don't warn for include'd macros.
1604 Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1605 MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1606 MI->setIsWarnIfUnused(true);
1607 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1608 }
1609
Chris Lattner928e9092009-04-12 01:39:54 +00001610 // If the callbacks want to know, tell them about the macro definition.
1611 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001612 Callbacks->MacroDefined(MacroNameTok, MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001613}
1614
1615/// HandleUndefDirective - Implements #undef.
1616///
1617void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1618 ++NumUndefined;
1619
1620 Token MacroNameTok;
1621 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001622
Chris Lattnerf64b3522008-03-09 01:54:53 +00001623 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001624 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001625 return;
Mike Stump11289f42009-09-09 15:08:12 +00001626
Chris Lattnerf64b3522008-03-09 01:54:53 +00001627 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001628 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00001629
Chris Lattnerf64b3522008-03-09 01:54:53 +00001630 // Okay, we finally have a valid identifier to undef.
1631 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Mike Stump11289f42009-09-09 15:08:12 +00001632
Chris Lattnerf64b3522008-03-09 01:54:53 +00001633 // If the macro is not defined, this is a noop undef, just return.
1634 if (MI == 0) return;
1635
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00001636 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00001637 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001638
1639 // If the callbacks want to know, tell them about the macro #undef.
1640 if (Callbacks)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001641 Callbacks->MacroUndefined(MacroNameTok, MI);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00001642
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001643 if (MI->isWarnIfUnused())
1644 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1645
Chris Lattnerf64b3522008-03-09 01:54:53 +00001646 // Free macro definition.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001647 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001648 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1649}
1650
1651
1652//===----------------------------------------------------------------------===//
1653// Preprocessor Conditional Directive Handling.
1654//===----------------------------------------------------------------------===//
1655
1656/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1657/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1658/// if any tokens have been returned or pp-directives activated before this
1659/// #ifndef has been lexed.
1660///
1661void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1662 bool ReadAnyTokensBeforeDirective) {
1663 ++NumIf;
1664 Token DirectiveTok = Result;
1665
1666 Token MacroNameTok;
1667 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001668
Chris Lattnerf64b3522008-03-09 01:54:53 +00001669 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001670 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001671 // Skip code until we get to #endif. This helps with recovery by not
1672 // emitting an error when the #endif is reached.
1673 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1674 /*Foundnonskip*/false, /*FoundElse*/false);
1675 return;
1676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Chris Lattnerf64b3522008-03-09 01:54:53 +00001678 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001679 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001680
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001681 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1682 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001683
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001684 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001685 // If the start of a top-level #ifdef and if the macro is not defined,
1686 // inform MIOpt that this might be the start of a proper include guard.
1687 // Otherwise it is some other form of unknown conditional which we can't
1688 // handle.
1689 if (!ReadAnyTokensBeforeDirective && MI == 0) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001690 assert(isIfndef && "#ifdef shouldn't reach here");
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001691 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001692 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001693 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001694 }
1695
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696 // If there is a macro, process it.
1697 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001698 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattnerf64b3522008-03-09 01:54:53 +00001700 // Should we include the stuff contained by this directive?
1701 if (!MI == isIfndef) {
1702 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00001703 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1704 /*wasskip*/false, /*foundnonskip*/true,
1705 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001706 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001707 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001709 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001710 /*FoundElse*/false);
1711 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001712
1713 if (Callbacks) {
1714 if (isIfndef)
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001715 Callbacks->Ifndef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001716 else
Craig Silverstein1a9ca212010-11-19 21:33:15 +00001717 Callbacks->Ifdef(MacroNameTok);
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001718 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001719}
1720
1721/// HandleIfDirective - Implements the #if directive.
1722///
1723void Preprocessor::HandleIfDirective(Token &IfToken,
1724 bool ReadAnyTokensBeforeDirective) {
1725 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00001726
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001727 // Parse and evaluate the conditional expression.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001728 IdentifierInfo *IfNDefMacro = 0;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001729 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1730 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1731 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00001732
1733 // If this condition is equivalent to #ifndef X, and if this is the first
1734 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001735 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00001736 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001737 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes363212b2008-06-01 18:31:24 +00001738 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001739 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00001740 }
1741
Chris Lattnerf64b3522008-03-09 01:54:53 +00001742 // Should we include the stuff contained by this directive?
1743 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001744 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001745 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001746 /*foundnonskip*/true, /*foundelse*/false);
1747 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001748 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00001749 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001750 /*FoundElse*/false);
1751 }
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001752
1753 if (Callbacks)
1754 Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001755}
1756
1757/// HandleEndifDirective - Implements the #endif directive.
1758///
1759void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1760 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00001761
Chris Lattnerf64b3522008-03-09 01:54:53 +00001762 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001763 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00001764
Chris Lattnerf64b3522008-03-09 01:54:53 +00001765 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001766 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001767 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00001768 Diag(EndifToken, diag::err_pp_endif_without_if);
1769 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
Chris Lattnerf64b3522008-03-09 01:54:53 +00001772 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001773 if (CurPPLexer->getConditionalStackDepth() == 0)
1774 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001775
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001776 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00001777 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001778
1779 if (Callbacks)
1780 Callbacks->Endif();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001781}
1782
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001783/// HandleElseDirective - Implements the #else directive.
1784///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001785void Preprocessor::HandleElseDirective(Token &Result) {
1786 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001787
Chris Lattnerf64b3522008-03-09 01:54:53 +00001788 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001789 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00001790
Chris Lattnerf64b3522008-03-09 01:54:53 +00001791 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001792 if (CurPPLexer->popConditionalLevel(CI)) {
1793 Diag(Result, diag::pp_err_else_without_if);
1794 return;
1795 }
Mike Stump11289f42009-09-09 15:08:12 +00001796
Chris Lattnerf64b3522008-03-09 01:54:53 +00001797 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001798 if (CurPPLexer->getConditionalStackDepth() == 0)
1799 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001800
1801 // If this is a #else with a #else before it, report the error.
1802 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00001803
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001804 // Finally, skip the rest of the contents of this block.
1805 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1806 /*FoundElse*/true);
1807
1808 if (Callbacks)
1809 Callbacks->Else();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001810}
1811
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001812/// HandleElifDirective - Implements the #elif directive.
1813///
Chris Lattnerf64b3522008-03-09 01:54:53 +00001814void Preprocessor::HandleElifDirective(Token &ElifToken) {
1815 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00001816
Chris Lattnerf64b3522008-03-09 01:54:53 +00001817 // #elif directive in a non-skipping conditional... start skipping.
1818 // We don't care what the condition is, because we will always skip it (since
1819 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001820 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001821 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001822 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001823
1824 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00001825 if (CurPPLexer->popConditionalLevel(CI)) {
1826 Diag(ElifToken, diag::pp_err_elif_without_if);
1827 return;
1828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
Chris Lattnerf64b3522008-03-09 01:54:53 +00001830 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001831 if (CurPPLexer->getConditionalStackDepth() == 0)
1832 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00001833
Chris Lattnerf64b3522008-03-09 01:54:53 +00001834 // If this is a #elif with a #else before it, report the error.
1835 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1836
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00001837 // Finally, skip the rest of the contents of this block.
1838 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1839 /*FoundElse*/CI.FoundElse);
1840
1841 if (Callbacks)
1842 Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
Chris Lattnerf64b3522008-03-09 01:54:53 +00001843}