blob: 4ab293b9b72469f22d9c6adb7947425d74076ec7 [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattner141e71f2008-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 Lattner359cc442009-01-26 05:29:08 +000015#include "clang/Lex/LiteralSupport.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/SourceManager.h"
Chris Lattner359cc442009-01-26 05:29:08 +000020#include "llvm/ADT/APInt.h"
Chris Lattner141e71f2008-03-09 01:54:53 +000021using namespace clang;
22
23//===----------------------------------------------------------------------===//
24// Utility Methods for Preprocessor Directive Handling.
25//===----------------------------------------------------------------------===//
26
Ted Kremenek0ea76722008-12-15 19:56:42 +000027MacroInfo* Preprocessor::AllocateMacroInfo(SourceLocation L) {
28 MacroInfo *MI;
29
30 if (!MICache.empty()) {
31 MI = MICache.back();
32 MICache.pop_back();
33 }
34 else MI = (MacroInfo*) BP.Allocate<MacroInfo>();
35 new (MI) MacroInfo(L);
36 return MI;
37}
38
Chris Lattner141e71f2008-03-09 01:54:53 +000039/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
40/// current line until the tok::eom token is found.
41void Preprocessor::DiscardUntilEndOfDirective() {
42 Token Tmp;
43 do {
44 LexUnexpandedToken(Tmp);
45 } while (Tmp.isNot(tok::eom));
46}
47
Chris Lattner141e71f2008-03-09 01:54:53 +000048/// ReadMacroName - Lex and validate a macro name, which occurs after a
49/// #define or #undef. This sets the token kind to eom and discards the rest
50/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
51/// this is due to a a #define, 2 if #undef directive, 0 if it is something
52/// else (e.g. #ifdef).
53void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
54 // Read the token, don't allow macro expansion on it.
55 LexUnexpandedToken(MacroNameTok);
56
57 // Missing macro name?
Chris Lattner3692b092008-11-18 07:59:24 +000058 if (MacroNameTok.is(tok::eom)) {
59 Diag(MacroNameTok, diag::err_pp_missing_macro_name);
60 return;
61 }
Chris Lattner141e71f2008-03-09 01:54:53 +000062
63 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
64 if (II == 0) {
65 std::string Spelling = getSpelling(MacroNameTok);
Chris Lattner9485d232008-12-13 20:12:40 +000066 const IdentifierInfo &Info = Identifiers.get(Spelling);
67 if (Info.isCPlusPlusOperatorKeyword())
Chris Lattner141e71f2008-03-09 01:54:53 +000068 // C++ 2.5p2: Alternative tokens behave the same as its primary token
69 // except for their spellings.
Chris Lattner56b05c82008-11-18 08:02:48 +000070 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
Chris Lattner141e71f2008-03-09 01:54:53 +000071 else
72 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
73 // Fall through on error.
74 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
75 // Error if defining "defined": C99 6.10.8.4.
76 Diag(MacroNameTok, diag::err_defined_macro_name);
77 } else if (isDefineUndef && II->hasMacroDefinition() &&
78 getMacroInfo(II)->isBuiltinMacro()) {
79 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
80 if (isDefineUndef == 1)
81 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
82 else
83 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
84 } else {
85 // Okay, we got a good identifier node. Return it.
86 return;
87 }
88
89 // Invalid macro name, read and discard the rest of the line. Then set the
90 // token kind to tok::eom.
91 MacroNameTok.setKind(tok::eom);
92 return DiscardUntilEndOfDirective();
93}
94
95/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
96/// not, emit a diagnostic and consume up until the eom.
97void Preprocessor::CheckEndOfDirective(const char *DirType) {
98 Token Tmp;
99 // Lex unexpanded tokens: macros might expand to zero tokens, causing us to
100 // miss diagnosing invalid lines.
101 LexUnexpandedToken(Tmp);
102
103 // There should be no tokens after the directive, but we allow them as an
104 // extension.
105 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
106 LexUnexpandedToken(Tmp);
107
108 if (Tmp.isNot(tok::eom)) {
Chris Lattner56b05c82008-11-18 08:02:48 +0000109 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType;
Chris Lattner141e71f2008-03-09 01:54:53 +0000110 DiscardUntilEndOfDirective();
111 }
112}
113
114
115
116/// SkipExcludedConditionalBlock - We just read a #if or related directive and
117/// decided that the subsequent tokens are in the #if'd out portion of the
118/// file. Lex the rest of the file, until we see an #endif. If
119/// FoundNonSkipPortion is true, then we have already emitted code for part of
120/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
121/// is true, then #else directives are ok, if not, then we have already seen one
122/// so a #else directive is a duplicate. When this returns, the caller can lex
123/// the first valid token.
124void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
125 bool FoundNonSkipPortion,
126 bool FoundElse) {
127 ++NumSkipped;
Ted Kremenekf6452c52008-11-18 01:04:47 +0000128 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattner141e71f2008-03-09 01:54:53 +0000129
Ted Kremenek60e45d42008-11-18 00:34:22 +0000130 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +0000131 FoundNonSkipPortion, FoundElse);
132
Ted Kremenek268ee702008-12-12 18:34:08 +0000133 if (CurPTHLexer) {
134 PTHSkipExcludedConditionalBlock();
135 return;
136 }
137
Chris Lattner141e71f2008-03-09 01:54:53 +0000138 // Enter raw mode to disable identifier lookup (and thus macro expansion),
139 // disabling warnings, etc.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000140 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000141 Token Tok;
142 while (1) {
Ted Kremenekf6452c52008-11-18 01:04:47 +0000143 if (CurLexer)
144 CurLexer->Lex(Tok);
145 else
146 CurPTHLexer->Lex(Tok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000147
148 // If this is the end of the buffer, we have an error.
149 if (Tok.is(tok::eof)) {
150 // Emit errors for each unterminated conditional on the stack, including
151 // the current one.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000152 while (!CurPPLexer->ConditionalStack.empty()) {
153 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
Chris Lattner141e71f2008-03-09 01:54:53 +0000154 diag::err_pp_unterminated_conditional);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000155 CurPPLexer->ConditionalStack.pop_back();
Chris Lattner141e71f2008-03-09 01:54:53 +0000156 }
157
158 // Just return and let the caller lex after this #include.
159 break;
160 }
161
162 // If this token is not a preprocessor directive, just skip it.
163 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
164 continue;
165
166 // We just parsed a # character at the start of a line, so we're in
167 // directive mode. Tell the lexer this so any newlines we see will be
168 // converted into an EOM token (this terminates the macro).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000169 CurPPLexer->ParsingPreprocessorDirective = true;
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000170 if (CurLexer) CurLexer->SetCommentRetentionState(false);
Chris Lattner141e71f2008-03-09 01:54:53 +0000171
172
173 // Read the next token, the directive flavor.
174 LexUnexpandedToken(Tok);
175
176 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
177 // something bogus), skip it.
178 if (Tok.isNot(tok::identifier)) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000179 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000180 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000181 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000182 continue;
183 }
184
185 // If the first letter isn't i or e, it isn't intesting to us. We know that
186 // this is safe in the face of spelling differences, because there is no way
187 // to spell an i/e in a strange way that is another letter. Skipping this
188 // allows us to avoid looking up the identifier info for #define/#undef and
189 // other common directives.
190 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
191 char FirstChar = RawCharData[0];
192 if (FirstChar >= 'a' && FirstChar <= 'z' &&
193 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000194 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000195 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000196 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000197 continue;
198 }
199
200 // Get the identifier name without trigraphs or embedded newlines. Note
201 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
202 // when skipping.
203 // TODO: could do this with zero copies in the no-clean case by using
204 // strncmp below.
205 char Directive[20];
206 unsigned IdLen;
207 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
208 IdLen = Tok.getLength();
209 memcpy(Directive, RawCharData, IdLen);
210 Directive[IdLen] = 0;
211 } else {
212 std::string DirectiveStr = getSpelling(Tok);
213 IdLen = DirectiveStr.size();
214 if (IdLen >= 20) {
Ted Kremenek60e45d42008-11-18 00:34:22 +0000215 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000216 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000217 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000218 continue;
219 }
220 memcpy(Directive, &DirectiveStr[0], IdLen);
221 Directive[IdLen] = 0;
222 }
223
224 if (FirstChar == 'i' && Directive[1] == 'f') {
225 if ((IdLen == 2) || // "if"
226 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
227 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
228 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
229 // bother parsing the condition.
230 DiscardUntilEndOfDirective();
Ted Kremenek60e45d42008-11-18 00:34:22 +0000231 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattner141e71f2008-03-09 01:54:53 +0000232 /*foundnonskip*/false,
233 /*fnddelse*/false);
234 }
235 } else if (FirstChar == 'e') {
236 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
237 CheckEndOfDirective("#endif");
238 PPConditionalInfo CondInfo;
239 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000240 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Chris Lattner141e71f2008-03-09 01:54:53 +0000241 InCond = InCond; // Silence warning in no-asserts mode.
242 assert(!InCond && "Can't be skipping if not in a conditional!");
243
244 // If we popped the outermost skipping block, we're done skipping!
245 if (!CondInfo.WasSkipping)
246 break;
247 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
248 // #else directive in a skipping conditional. If not in some other
249 // skipping conditional, and if #else hasn't already been seen, enter it
250 // as a non-skipping conditional.
251 CheckEndOfDirective("#else");
Ted Kremenek60e45d42008-11-18 00:34:22 +0000252 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000253
254 // If this is a #else with a #else before it, report the error.
255 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
256
257 // Note that we've seen a #else in this conditional.
258 CondInfo.FoundElse = true;
259
260 // If the conditional is at the top level, and the #if block wasn't
261 // entered, enter the #else block now.
262 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
263 CondInfo.FoundNonSkip = true;
264 break;
265 }
266 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Ted Kremenek60e45d42008-11-18 00:34:22 +0000267 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattner141e71f2008-03-09 01:54:53 +0000268
269 bool ShouldEnter;
270 // If this is in a skipping block or if we're already handled this #if
271 // block, don't bother parsing the condition.
272 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
273 DiscardUntilEndOfDirective();
274 ShouldEnter = false;
275 } else {
276 // Restore the value of LexingRawMode so that identifiers are
277 // looked up, etc, inside the #elif expression.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000278 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
279 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000280 IdentifierInfo *IfNDefMacro = 0;
281 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek60e45d42008-11-18 00:34:22 +0000282 CurPPLexer->LexingRawMode = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000283 }
284
285 // If this is a #elif with a #else before it, report the error.
286 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
287
288 // If this condition is true, enter it!
289 if (ShouldEnter) {
290 CondInfo.FoundNonSkip = true;
291 break;
292 }
293 }
294 }
295
Ted Kremenek60e45d42008-11-18 00:34:22 +0000296 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000297 // Restore comment saving mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +0000298 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
Chris Lattner141e71f2008-03-09 01:54:53 +0000299 }
300
301 // Finally, if we are out of the conditional (saw an #endif or ran off the end
302 // of the file, just stop skipping and return to lexing whatever came after
303 // the #if block.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000304 CurPPLexer->LexingRawMode = false;
Chris Lattner141e71f2008-03-09 01:54:53 +0000305}
306
Ted Kremenek268ee702008-12-12 18:34:08 +0000307void Preprocessor::PTHSkipExcludedConditionalBlock() {
308
309 while(1) {
310 assert(CurPTHLexer);
311 assert(CurPTHLexer->LexingRawMode == false);
312
313 // Skip to the next '#else', '#elif', or #endif.
314 if (CurPTHLexer->SkipBlock()) {
315 // We have reached an #endif. Both the '#' and 'endif' tokens
316 // have been consumed by the PTHLexer. Just pop off the condition level.
317 PPConditionalInfo CondInfo;
318 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
319 InCond = InCond; // Silence warning in no-asserts mode.
320 assert(!InCond && "Can't be skipping if not in a conditional!");
321 break;
322 }
323
324 // We have reached a '#else' or '#elif'. Lex the next token to get
325 // the directive flavor.
326 Token Tok;
327 LexUnexpandedToken(Tok);
328
329 // We can actually look up the IdentifierInfo here since we aren't in
330 // raw mode.
331 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
332
333 if (K == tok::pp_else) {
334 // #else: Enter the else condition. We aren't in a nested condition
335 // since we skip those. We're always in the one matching the last
336 // blocked we skipped.
337 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
338 // Note that we've seen a #else in this conditional.
339 CondInfo.FoundElse = true;
340
341 // If the #if block wasn't entered then enter the #else block now.
342 if (!CondInfo.FoundNonSkip) {
343 CondInfo.FoundNonSkip = true;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000344
345 // Consume the eom token.
346 CurPTHLexer->ParsingPreprocessorDirective = true;
347 LexUnexpandedToken(Tok);
348 assert(Tok.is(tok::eom));
349 CurPTHLexer->ParsingPreprocessorDirective = false;
350
Ted Kremenek268ee702008-12-12 18:34:08 +0000351 break;
352 }
353
354 // Otherwise skip this block.
355 continue;
356 }
357
358 assert(K == tok::pp_elif);
359 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
360
361 // If this is a #elif with a #else before it, report the error.
362 if (CondInfo.FoundElse)
363 Diag(Tok, diag::pp_err_elif_after_else);
364
365 // If this is in a skipping block or if we're already handled this #if
366 // block, don't bother parsing the condition. We just skip this block.
367 if (CondInfo.FoundNonSkip)
368 continue;
369
370 // Evaluate the condition of the #elif.
371 IdentifierInfo *IfNDefMacro = 0;
372 CurPTHLexer->ParsingPreprocessorDirective = true;
373 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
374 CurPTHLexer->ParsingPreprocessorDirective = false;
375
376 // If this condition is true, enter it!
377 if (ShouldEnter) {
378 CondInfo.FoundNonSkip = true;
379 break;
380 }
381
382 // Otherwise, skip this block and go to the next one.
383 continue;
384 }
385}
386
Chris Lattner10725092008-03-09 04:17:44 +0000387/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
388/// return null on failure. isAngled indicates whether the file reference is
389/// for system #include's or not (i.e. using <> instead of "").
390const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
391 const char *FilenameEnd,
392 bool isAngled,
393 const DirectoryLookup *FromDir,
394 const DirectoryLookup *&CurDir) {
395 // If the header lookup mechanism may be relative to the current file, pass in
396 // info about where the current file is.
397 const FileEntry *CurFileEnt = 0;
398 if (!FromDir) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000399 FileID FID = getCurrentFileLexer()->getFileID();
400 CurFileEnt = SourceMgr.getFileEntryForID(FID);
Chris Lattner10725092008-03-09 04:17:44 +0000401 }
402
403 // Do a standard file entry lookup.
404 CurDir = CurDirLookup;
405 const FileEntry *FE =
406 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
407 isAngled, FromDir, CurDir, CurFileEnt);
408 if (FE) return FE;
409
410 // Otherwise, see if this is a subframework header. If so, this is relative
411 // to one of the headers on the #include stack. Walk the list of the current
412 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek81d24e12008-11-20 16:19:53 +0000413 if (IsFileLexer()) {
Ted Kremenek41938c82008-11-19 21:57:25 +0000414 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000415 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
416 CurFileEnt)))
417 return FE;
418 }
419
420 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
421 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +0000422 if (IsFileLexer(ISEntry)) {
Chris Lattner10725092008-03-09 04:17:44 +0000423 if ((CurFileEnt =
Ted Kremenek41938c82008-11-19 21:57:25 +0000424 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
Chris Lattner10725092008-03-09 04:17:44 +0000425 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
426 FilenameEnd, CurFileEnt)))
427 return FE;
428 }
429 }
430
431 // Otherwise, we really couldn't find the file.
432 return 0;
433}
434
Chris Lattner141e71f2008-03-09 01:54:53 +0000435
436//===----------------------------------------------------------------------===//
437// Preprocessor Directive Handling.
438//===----------------------------------------------------------------------===//
439
440/// HandleDirective - This callback is invoked when the lexer sees a # token
441/// at the start of a line. This consumes the directive, modifies the
442/// lexer/preprocessor state, and advances the lexer(s) so that the next token
443/// read is the correct one.
444void Preprocessor::HandleDirective(Token &Result) {
445 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
446
447 // We just parsed a # character at the start of a line, so we're in directive
448 // mode. Tell the lexer this so any newlines we see will be converted into an
449 // EOM token (which terminates the directive).
Ted Kremenek60e45d42008-11-18 00:34:22 +0000450 CurPPLexer->ParsingPreprocessorDirective = true;
Chris Lattner141e71f2008-03-09 01:54:53 +0000451
452 ++NumDirectives;
453
454 // We are about to read a token. For the multiple-include optimization FA to
455 // work, we have to remember if we had read any tokens *before* this
456 // pp-directive.
Ted Kremenek60e45d42008-11-18 00:34:22 +0000457 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Chris Lattner141e71f2008-03-09 01:54:53 +0000458
459 // Read the next token, the directive flavor. This isn't expanded due to
460 // C99 6.10.3p8.
461 LexUnexpandedToken(Result);
462
463 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
464 // #define A(x) #x
465 // A(abc
466 // #warning blah
467 // def)
468 // If so, the user is relying on non-portable behavior, emit a diagnostic.
469 if (InMacroArgs)
470 Diag(Result, diag::ext_embedded_directive);
471
472TryAgain:
473 switch (Result.getKind()) {
474 case tok::eom:
475 return; // null directive.
476 case tok::comment:
477 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
478 LexUnexpandedToken(Result);
479 goto TryAgain;
480
481 case tok::numeric_constant:
482 // FIXME: implement # 7 line numbers!
Chris Lattner359cc442009-01-26 05:29:08 +0000483 return DiscardUntilEndOfDirective();
Chris Lattner141e71f2008-03-09 01:54:53 +0000484 default:
485 IdentifierInfo *II = Result.getIdentifierInfo();
486 if (II == 0) break; // Not an identifier.
487
488 // Ask what the preprocessor keyword ID is.
489 switch (II->getPPKeywordID()) {
490 default: break;
491 // C99 6.10.1 - Conditional Inclusion.
492 case tok::pp_if:
493 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
494 case tok::pp_ifdef:
495 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
496 case tok::pp_ifndef:
497 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
498 case tok::pp_elif:
499 return HandleElifDirective(Result);
500 case tok::pp_else:
501 return HandleElseDirective(Result);
502 case tok::pp_endif:
503 return HandleEndifDirective(Result);
504
505 // C99 6.10.2 - Source File Inclusion.
506 case tok::pp_include:
507 return HandleIncludeDirective(Result); // Handle #include.
508
509 // C99 6.10.3 - Macro Replacement.
510 case tok::pp_define:
511 return HandleDefineDirective(Result);
512 case tok::pp_undef:
513 return HandleUndefDirective(Result);
514
515 // C99 6.10.4 - Line Control.
516 case tok::pp_line:
Chris Lattner359cc442009-01-26 05:29:08 +0000517 return HandleLineDirective(Result);
Chris Lattner141e71f2008-03-09 01:54:53 +0000518
519 // C99 6.10.5 - Error Directive.
520 case tok::pp_error:
521 return HandleUserDiagnosticDirective(Result, false);
522
523 // C99 6.10.6 - Pragma Directive.
524 case tok::pp_pragma:
525 return HandlePragmaDirective();
526
527 // GNU Extensions.
528 case tok::pp_import:
529 return HandleImportDirective(Result);
530 case tok::pp_include_next:
531 return HandleIncludeNextDirective(Result);
532
533 case tok::pp_warning:
534 Diag(Result, diag::ext_pp_warning_directive);
535 return HandleUserDiagnosticDirective(Result, true);
536 case tok::pp_ident:
537 return HandleIdentSCCSDirective(Result);
538 case tok::pp_sccs:
539 return HandleIdentSCCSDirective(Result);
540 case tok::pp_assert:
541 //isExtension = true; // FIXME: implement #assert
542 break;
543 case tok::pp_unassert:
544 //isExtension = true; // FIXME: implement #unassert
545 break;
546 }
547 break;
548 }
549
550 // If we reached here, the preprocessing token is not valid!
551 Diag(Result, diag::err_pp_invalid_directive);
552
553 // Read the rest of the PP line.
554 DiscardUntilEndOfDirective();
555
556 // Okay, we're done parsing the directive.
557}
558
Chris Lattner359cc442009-01-26 05:29:08 +0000559/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
560/// acceptable forms are:
561/// # line digit-sequence
562/// # line digit-sequence "s-char-sequence"
563void Preprocessor::HandleLineDirective(Token &Tok) {
564 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
565 // expanded.
566 Token DigitTok;
567 Lex(DigitTok);
568
569 // Verify that we get a number.
570 if (DigitTok.isNot(tok::numeric_constant)) {
571 Diag(DigitTok, diag::err_pp_line_requires_integer);
572 if (DigitTok.isNot(tok::eom))
573 DiscardUntilEndOfDirective();
574 return;
575 }
576
577 // Validate the number and convert it to an unsigned.
578 llvm::SmallString<64> IntegerBuffer;
579 IntegerBuffer.resize(DigitTok.getLength());
580 const char *DigitTokBegin = &IntegerBuffer[0];
581 unsigned ActualLength = getSpelling(DigitTok, DigitTokBegin);
582 NumericLiteralParser Literal(DigitTokBegin, DigitTokBegin+ActualLength,
583 DigitTok.getLocation(), *this);
584 if (Literal.hadError)
585 return DiscardUntilEndOfDirective(); // a diagnostic was already reported.
586
587 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
588 Diag(DigitTok, diag::err_pp_line_requires_integer);
589 return;
590 }
591
592 // Parse the integer literal into Result.
593 llvm::APInt Val(32, 0);
594 if (Literal.GetIntegerValue(Val)) {
595 // Overflow parsing integer literal.
596 Diag(DigitTok, diag::err_pp_line_requires_integer);
597 return DiscardUntilEndOfDirective();
598 }
599
600 // Enforce C99 6.10.4p3: The digit sequence shall not specify zero, nor a
601 // number greater than 2147483647.
602 unsigned LineNo = Val.getZExtValue();
603 if (LineNo == 0) {
604 Diag(DigitTok, diag::err_pp_line_requires_integer);
605 return DiscardUntilEndOfDirective();
606 }
607
608 // C90 requires that the line # be less than 32767, and C99 ups the limit.
609 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
610 if (LineNo >= LineLimit)
611 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
612
613 Token StrTok;
614 Lex(StrTok);
615
616 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a
617 // string followed by eom.
618 if (StrTok.is(tok::eom))
619 ; // ok
620 else if (StrTok.isNot(tok::string_literal)) {
621 Diag(StrTok, diag::err_pp_line_invalid_filename);
622 DiscardUntilEndOfDirective();
623 return;
624 } else {
625 // Verify that there is nothing after the string, other than EOM.
626 CheckEndOfDirective("#line");
627 }
628
629 // FIXME: do something with the #line info.
630}
631
632
Chris Lattner141e71f2008-03-09 01:54:53 +0000633void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
634 bool isWarning) {
Chris Lattner359cc442009-01-26 05:29:08 +0000635 if (!CurLexer)
636 return CurPTHLexer->DiscardToEndOfLine();
637
Chris Lattner141e71f2008-03-09 01:54:53 +0000638 // Read the rest of the line raw. We do this because we don't want macros
639 // to be expanded and we don't require that the tokens be valid preprocessing
640 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
641 // collapse multiple consequtive white space between tokens, but this isn't
642 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000643 std::string Message = CurLexer->ReadToEndOfLine();
644 if (isWarning)
645 Diag(Tok, diag::pp_hash_warning) << Message;
646 else
647 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000648}
649
650/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
651///
652void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
653 // Yes, this directive is an extension.
654 Diag(Tok, diag::ext_pp_ident_directive);
655
656 // Read the string argument.
657 Token StrTok;
658 Lex(StrTok);
659
660 // If the token kind isn't a string, it's a malformed directive.
661 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000662 StrTok.isNot(tok::wide_string_literal)) {
663 Diag(StrTok, diag::err_pp_malformed_ident);
664 return;
665 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000666
667 // Verify that there is nothing after the string, other than EOM.
668 CheckEndOfDirective("#ident");
669
670 if (Callbacks)
671 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
672}
673
674//===----------------------------------------------------------------------===//
675// Preprocessor Include Directive Handling.
676//===----------------------------------------------------------------------===//
677
678/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
679/// checked and spelled filename, e.g. as an operand of #include. This returns
680/// true if the input filename was in <>'s or false if it were in ""'s. The
681/// caller is expected to provide a buffer that is large enough to hold the
682/// spelling of the filename, but is also expected to handle the case when
683/// this method decides to use a different buffer.
684bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
685 const char *&BufStart,
686 const char *&BufEnd) {
687 // Get the text form of the filename.
688 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
689
690 // Make sure the filename is <x> or "x".
691 bool isAngled;
692 if (BufStart[0] == '<') {
693 if (BufEnd[-1] != '>') {
694 Diag(Loc, diag::err_pp_expects_filename);
695 BufStart = 0;
696 return true;
697 }
698 isAngled = true;
699 } else if (BufStart[0] == '"') {
700 if (BufEnd[-1] != '"') {
701 Diag(Loc, diag::err_pp_expects_filename);
702 BufStart = 0;
703 return true;
704 }
705 isAngled = false;
706 } else {
707 Diag(Loc, diag::err_pp_expects_filename);
708 BufStart = 0;
709 return true;
710 }
711
712 // Diagnose #include "" as invalid.
713 if (BufEnd-BufStart <= 2) {
714 Diag(Loc, diag::err_pp_empty_filename);
715 BufStart = 0;
716 return "";
717 }
718
719 // Skip the brackets.
720 ++BufStart;
721 --BufEnd;
722 return isAngled;
723}
724
725/// ConcatenateIncludeName - Handle cases where the #include name is expanded
726/// from a macro as multiple tokens, which need to be glued together. This
727/// occurs for code like:
728/// #define FOO <a/b.h>
729/// #include FOO
730/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
731///
732/// This code concatenates and consumes tokens up to the '>' token. It returns
733/// false if the > was found, otherwise it returns true if it finds and consumes
734/// the EOM marker.
735static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
736 Preprocessor &PP) {
737 Token CurTok;
738
739 PP.Lex(CurTok);
740 while (CurTok.isNot(tok::eom)) {
741 // Append the spelling of this token to the buffer. If there was a space
742 // before it, add it now.
743 if (CurTok.hasLeadingSpace())
744 FilenameBuffer.push_back(' ');
745
746 // Get the spelling of the token, directly into FilenameBuffer if possible.
747 unsigned PreAppendSize = FilenameBuffer.size();
748 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
749
750 const char *BufPtr = &FilenameBuffer[PreAppendSize];
751 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
752
753 // If the token was spelled somewhere else, copy it into FilenameBuffer.
754 if (BufPtr != &FilenameBuffer[PreAppendSize])
755 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
756
757 // Resize FilenameBuffer to the correct size.
758 if (CurTok.getLength() != ActualLen)
759 FilenameBuffer.resize(PreAppendSize+ActualLen);
760
761 // If we found the '>' marker, return success.
762 if (CurTok.is(tok::greater))
763 return false;
764
765 PP.Lex(CurTok);
766 }
767
768 // If we hit the eom marker, emit an error and return true so that the caller
769 // knows the EOM has been read.
770 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
771 return true;
772}
773
774/// HandleIncludeDirective - The "#include" tokens have just been read, read the
775/// file to be included from the lexer, then include it! This is a common
776/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +0000777/// #import. LookupFrom is set when this is a #include_next directive, it
778/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +0000779void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
780 const DirectoryLookup *LookupFrom,
781 bool isImport) {
782
783 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +0000784 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000785
786 // Reserve a buffer to get the spelling.
787 llvm::SmallVector<char, 128> FilenameBuffer;
788 const char *FilenameStart, *FilenameEnd;
789
790 switch (FilenameTok.getKind()) {
791 case tok::eom:
792 // If the token kind is EOM, the error has already been diagnosed.
793 return;
794
795 case tok::angle_string_literal:
796 case tok::string_literal: {
797 FilenameBuffer.resize(FilenameTok.getLength());
798 FilenameStart = &FilenameBuffer[0];
799 unsigned Len = getSpelling(FilenameTok, FilenameStart);
800 FilenameEnd = FilenameStart+Len;
801 break;
802 }
803
804 case tok::less:
805 // This could be a <foo/bar.h> file coming from a macro expansion. In this
806 // case, glue the tokens together into FilenameBuffer and interpret those.
807 FilenameBuffer.push_back('<');
808 if (ConcatenateIncludeName(FilenameBuffer, *this))
809 return; // Found <eom> but no ">"? Diagnostic already emitted.
810 FilenameStart = &FilenameBuffer[0];
811 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
812 break;
813 default:
814 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
815 DiscardUntilEndOfDirective();
816 return;
817 }
818
819 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
820 FilenameStart, FilenameEnd);
821 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
822 // error.
823 if (FilenameStart == 0) {
824 DiscardUntilEndOfDirective();
825 return;
826 }
827
828 // Verify that there is nothing after the filename, other than EOM. Use the
829 // preprocessor to lex this in case lexing the filename entered a macro.
830 CheckEndOfDirective("#include");
831
832 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +0000833 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
834 Diag(FilenameTok, diag::err_pp_include_too_deep);
835 return;
836 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000837
838 // Search include directories.
839 const DirectoryLookup *CurDir;
840 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
841 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +0000842 if (File == 0) {
843 Diag(FilenameTok, diag::err_pp_file_not_found)
844 << std::string(FilenameStart, FilenameEnd);
845 return;
846 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000847
Chris Lattner72181832008-09-26 20:12:23 +0000848 // Ask HeaderInfo if we should enter this #include file. If not, #including
849 // this file will have no effect.
850 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +0000851 return;
Chris Lattner72181832008-09-26 20:12:23 +0000852
853 // The #included file will be considered to be a system header if either it is
854 // in a system include directory, or if the #includer is a system include
855 // header.
Chris Lattner9d728512008-10-27 01:19:25 +0000856 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000857 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +0000858 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Chris Lattner72181832008-09-26 20:12:23 +0000859
Chris Lattner141e71f2008-03-09 01:54:53 +0000860 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000861 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
862 FileCharacter);
863 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +0000864 Diag(FilenameTok, diag::err_pp_file_not_found)
865 << std::string(FilenameStart, FilenameEnd);
866 return;
867 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000868
869 // Finally, if all is good, enter the new file!
Chris Lattner2b2453a2009-01-17 06:22:33 +0000870 EnterSourceFile(FID, CurDir);
Chris Lattner141e71f2008-03-09 01:54:53 +0000871}
872
873/// HandleIncludeNextDirective - Implements #include_next.
874///
875void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
876 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
877
878 // #include_next is like #include, except that we start searching after
879 // the current found directory. If we can't do this, issue a
880 // diagnostic.
881 const DirectoryLookup *Lookup = CurDirLookup;
882 if (isInPrimaryFile()) {
883 Lookup = 0;
884 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
885 } else if (Lookup == 0) {
886 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
887 } else {
888 // Start looking up in the next directory.
889 ++Lookup;
890 }
891
892 return HandleIncludeDirective(IncludeNextTok, Lookup);
893}
894
895/// HandleImportDirective - Implements #import.
896///
897void Preprocessor::HandleImportDirective(Token &ImportTok) {
898 Diag(ImportTok, diag::ext_pp_import_directive);
899
900 return HandleIncludeDirective(ImportTok, 0, true);
901}
902
903//===----------------------------------------------------------------------===//
904// Preprocessor Macro Directive Handling.
905//===----------------------------------------------------------------------===//
906
907/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
908/// definition has just been read. Lex the rest of the arguments and the
909/// closing ), updating MI with what we learn. Return true if an error occurs
910/// parsing the arg list.
911bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
912 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
913
914 Token Tok;
915 while (1) {
916 LexUnexpandedToken(Tok);
917 switch (Tok.getKind()) {
918 case tok::r_paren:
919 // Found the end of the argument list.
920 if (Arguments.empty()) { // #define FOO()
921 MI->setArgumentList(Arguments.begin(), Arguments.end());
922 return false;
923 }
924 // Otherwise we have #define FOO(A,)
925 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
926 return true;
927 case tok::ellipsis: // #define X(... -> C99 varargs
928 // Warn if use of C99 feature in non-C99 mode.
929 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
930
931 // Lex the token after the identifier.
932 LexUnexpandedToken(Tok);
933 if (Tok.isNot(tok::r_paren)) {
934 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
935 return true;
936 }
937 // Add the __VA_ARGS__ identifier as an argument.
938 Arguments.push_back(Ident__VA_ARGS__);
939 MI->setIsC99Varargs();
940 MI->setArgumentList(Arguments.begin(), Arguments.end());
941 return false;
942 case tok::eom: // #define X(
943 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
944 return true;
945 default:
946 // Handle keywords and identifiers here to accept things like
947 // #define Foo(for) for.
948 IdentifierInfo *II = Tok.getIdentifierInfo();
949 if (II == 0) {
950 // #define X(1
951 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
952 return true;
953 }
954
955 // If this is already used as an argument, it is used multiple times (e.g.
956 // #define X(A,A.
957 if (std::find(Arguments.begin(), Arguments.end(), II) !=
958 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +0000959 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +0000960 return true;
961 }
962
963 // Add the argument to the macro info.
964 Arguments.push_back(II);
965
966 // Lex the token after the identifier.
967 LexUnexpandedToken(Tok);
968
969 switch (Tok.getKind()) {
970 default: // #define X(A B
971 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
972 return true;
973 case tok::r_paren: // #define X(A)
974 MI->setArgumentList(Arguments.begin(), Arguments.end());
975 return false;
976 case tok::comma: // #define X(A,
977 break;
978 case tok::ellipsis: // #define X(A... -> GCC extension
979 // Diagnose extension.
980 Diag(Tok, diag::ext_named_variadic_macro);
981
982 // Lex the token after the identifier.
983 LexUnexpandedToken(Tok);
984 if (Tok.isNot(tok::r_paren)) {
985 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
986 return true;
987 }
988
989 MI->setIsGNUVarargs();
990 MI->setArgumentList(Arguments.begin(), Arguments.end());
991 return false;
992 }
993 }
994 }
995}
996
997/// HandleDefineDirective - Implements #define. This consumes the entire macro
998/// line then lets the caller lex the next real token.
999void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1000 ++NumDefined;
1001
1002 Token MacroNameTok;
1003 ReadMacroName(MacroNameTok, 1);
1004
1005 // Error reading macro name? If so, diagnostic already issued.
1006 if (MacroNameTok.is(tok::eom))
1007 return;
1008
1009 // If we are supposed to keep comments in #defines, reenable comment saving
1010 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001011 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +00001012
1013 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001014 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001015
1016 Token Tok;
1017 LexUnexpandedToken(Tok);
1018
1019 // If this is a function-like macro definition, parse the argument list,
1020 // marking each of the identifiers as being used as macro arguments. Also,
1021 // check other constraints on the first token of the macro body.
1022 if (Tok.is(tok::eom)) {
1023 // If there is no body to this macro, we have no special handling here.
1024 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
1025 // This is a function-like macro definition. Read the argument list.
1026 MI->setIsFunctionLike();
1027 if (ReadMacroDefinitionArgList(MI)) {
1028 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001029 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001030 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001031 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001032 DiscardUntilEndOfDirective();
1033 return;
1034 }
1035
1036 // Read the first token after the arg list for down below.
1037 LexUnexpandedToken(Tok);
1038 } else if (!Tok.hasLeadingSpace()) {
1039 // C99 requires whitespace between the macro definition and the body. Emit
1040 // a diagnostic for something like "#define X+".
1041 if (Features.C99) {
1042 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1043 } else {
1044 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1045 // one in some cases!
1046 }
1047 } else {
1048 // This is a normal token with leading space. Clear the leading space
1049 // marker on the first token to get proper expansion.
1050 Tok.clearFlag(Token::LeadingSpace);
1051 }
1052
1053 // If this is a definition of a variadic C99 function-like macro, not using
1054 // the GNU named varargs extension, enabled __VA_ARGS__.
1055
1056 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1057 // This gets unpoisoned where it is allowed.
1058 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1059 if (MI->isC99Varargs())
1060 Ident__VA_ARGS__->setIsPoisoned(false);
1061
1062 // Read the rest of the macro body.
1063 if (MI->isObjectLike()) {
1064 // Object-like macros are very simple, just read their body.
1065 while (Tok.isNot(tok::eom)) {
Chris Lattner9bd0d592009-01-26 04:06:48 +00001066 // If this token has a virtual location, resolve it down to its spelling
1067 // location. This is not strictly needed, but avoids extra resolutions
1068 // for macros that are expanded frequently.
1069 if (!Tok.getLocation().isFileID())
1070 Tok.setLocation(SourceMgr.getSpellingLoc(Tok.getLocation()));
1071
Chris Lattner141e71f2008-03-09 01:54:53 +00001072 MI->AddTokenToBody(Tok);
1073 // Get the next token of the macro.
1074 LexUnexpandedToken(Tok);
1075 }
1076
1077 } else {
1078 // Otherwise, read the body of a function-like macro. This has to validate
1079 // the # (stringize) operator.
1080 while (Tok.isNot(tok::eom)) {
Chris Lattner9bd0d592009-01-26 04:06:48 +00001081 // If this token has a virtual location, resolve it down to its spelling
1082 // location. This is not strictly needed, but avoids extra resolutions
1083 // for macros that are expanded frequently.
1084 if (!Tok.getLocation().isFileID())
1085 Tok.setLocation(SourceMgr.getSpellingLoc(Tok.getLocation()));
1086
Chris Lattner141e71f2008-03-09 01:54:53 +00001087 MI->AddTokenToBody(Tok);
1088
1089 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1090 // parameters in function-like macro expansions.
1091 if (Tok.isNot(tok::hash)) {
1092 // Get the next token of the macro.
1093 LexUnexpandedToken(Tok);
1094 continue;
1095 }
1096
1097 // Get the next token of the macro.
1098 LexUnexpandedToken(Tok);
1099
1100 // Not a macro arg identifier?
1101 if (!Tok.getIdentifierInfo() ||
1102 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1103 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001104 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001105
1106 // Disable __VA_ARGS__ again.
1107 Ident__VA_ARGS__->setIsPoisoned(true);
1108 return;
1109 }
1110
1111 // Things look ok, add the param name token to the macro.
1112 MI->AddTokenToBody(Tok);
1113
1114 // Get the next token of the macro.
1115 LexUnexpandedToken(Tok);
1116 }
1117 }
1118
1119
1120 // Disable __VA_ARGS__ again.
1121 Ident__VA_ARGS__->setIsPoisoned(true);
1122
1123 // Check that there is no paste (##) operator at the begining or end of the
1124 // replacement list.
1125 unsigned NumTokens = MI->getNumTokens();
1126 if (NumTokens != 0) {
1127 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1128 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001129 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001130 return;
1131 }
1132 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1133 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001134 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001135 return;
1136 }
1137 }
1138
1139 // If this is the primary source file, remember that this macro hasn't been
1140 // used yet.
1141 if (isInPrimaryFile())
1142 MI->setIsUsed(false);
1143
1144 // Finally, if this identifier already had a macro defined for it, verify that
1145 // the macro bodies are identical and free the old definition.
1146 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001147 // It is very common for system headers to have tons of macro redefinitions
1148 // and for warnings to be disabled in system headers. If this is the case,
1149 // then don't bother calling MacroInfo::isIdenticalTo.
1150 if (!Diags.getSuppressSystemWarnings() ||
1151 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1152 if (!OtherMI->isUsed())
1153 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001154
Chris Lattner41c3ae12009-01-16 19:50:11 +00001155 // Macros must be identical. This means all tokes and whitespace
1156 // separation must be the same. C99 6.10.3.2.
1157 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1158 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1159 << MacroNameTok.getIdentifierInfo();
1160 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1161 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001162 }
Chris Lattner41c3ae12009-01-16 19:50:11 +00001163
Ted Kremenek0ea76722008-12-15 19:56:42 +00001164 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001165 }
1166
1167 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1168}
1169
1170/// HandleUndefDirective - Implements #undef.
1171///
1172void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1173 ++NumUndefined;
1174
1175 Token MacroNameTok;
1176 ReadMacroName(MacroNameTok, 2);
1177
1178 // Error reading macro name? If so, diagnostic already issued.
1179 if (MacroNameTok.is(tok::eom))
1180 return;
1181
1182 // Check to see if this is the last token on the #undef line.
1183 CheckEndOfDirective("#undef");
1184
1185 // Okay, we finally have a valid identifier to undef.
1186 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1187
1188 // If the macro is not defined, this is a noop undef, just return.
1189 if (MI == 0) return;
1190
1191 if (!MI->isUsed())
1192 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1193
1194 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001195 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001196 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1197}
1198
1199
1200//===----------------------------------------------------------------------===//
1201// Preprocessor Conditional Directive Handling.
1202//===----------------------------------------------------------------------===//
1203
1204/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1205/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1206/// if any tokens have been returned or pp-directives activated before this
1207/// #ifndef has been lexed.
1208///
1209void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1210 bool ReadAnyTokensBeforeDirective) {
1211 ++NumIf;
1212 Token DirectiveTok = Result;
1213
1214 Token MacroNameTok;
1215 ReadMacroName(MacroNameTok);
1216
1217 // Error reading macro name? If so, diagnostic already issued.
1218 if (MacroNameTok.is(tok::eom)) {
1219 // Skip code until we get to #endif. This helps with recovery by not
1220 // emitting an error when the #endif is reached.
1221 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1222 /*Foundnonskip*/false, /*FoundElse*/false);
1223 return;
1224 }
1225
1226 // Check to see if this is the last token on the #if[n]def line.
1227 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1228
Ted Kremenek60e45d42008-11-18 00:34:22 +00001229 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001230 // If the start of a top-level #ifdef, inform MIOpt.
1231 if (!ReadAnyTokensBeforeDirective) {
1232 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001233 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001234 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001235 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001236 }
1237
1238 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1239 MacroInfo *MI = getMacroInfo(MII);
1240
1241 // If there is a macro, process it.
1242 if (MI) // Mark it used.
1243 MI->setIsUsed(true);
1244
1245 // Should we include the stuff contained by this directive?
1246 if (!MI == isIfndef) {
1247 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001248 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001249 /*foundnonskip*/true, /*foundelse*/false);
1250 } else {
1251 // No, skip the contents of this block and return the first token after it.
1252 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1253 /*Foundnonskip*/false,
1254 /*FoundElse*/false);
1255 }
1256}
1257
1258/// HandleIfDirective - Implements the #if directive.
1259///
1260void Preprocessor::HandleIfDirective(Token &IfToken,
1261 bool ReadAnyTokensBeforeDirective) {
1262 ++NumIf;
1263
1264 // Parse and evaluation the conditional expression.
1265 IdentifierInfo *IfNDefMacro = 0;
1266 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1267
Nuno Lopes0049db62008-06-01 18:31:24 +00001268
1269 // If this condition is equivalent to #ifndef X, and if this is the first
1270 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001271 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001272 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001273 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001274 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001275 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001276 }
1277
Chris Lattner141e71f2008-03-09 01:54:53 +00001278 // Should we include the stuff contained by this directive?
1279 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001280 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001281 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001282 /*foundnonskip*/true, /*foundelse*/false);
1283 } else {
1284 // No, skip the contents of this block and return the first token after it.
1285 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1286 /*FoundElse*/false);
1287 }
1288}
1289
1290/// HandleEndifDirective - Implements the #endif directive.
1291///
1292void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1293 ++NumEndif;
1294
1295 // Check that this is the whole directive.
1296 CheckEndOfDirective("#endif");
1297
1298 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001299 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001300 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001301 Diag(EndifToken, diag::err_pp_endif_without_if);
1302 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001303 }
1304
1305 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001306 if (CurPPLexer->getConditionalStackDepth() == 0)
1307 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001308
Ted Kremenek60e45d42008-11-18 00:34:22 +00001309 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001310 "This code should only be reachable in the non-skipping case!");
1311}
1312
1313
1314void Preprocessor::HandleElseDirective(Token &Result) {
1315 ++NumElse;
1316
1317 // #else directive in a non-skipping conditional... start skipping.
1318 CheckEndOfDirective("#else");
1319
1320 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001321 if (CurPPLexer->popConditionalLevel(CI)) {
1322 Diag(Result, diag::pp_err_else_without_if);
1323 return;
1324 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001325
1326 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001327 if (CurPPLexer->getConditionalStackDepth() == 0)
1328 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001329
1330 // If this is a #else with a #else before it, report the error.
1331 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1332
1333 // Finally, skip the rest of the contents of this block and return the first
1334 // token after it.
1335 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1336 /*FoundElse*/true);
1337}
1338
1339void Preprocessor::HandleElifDirective(Token &ElifToken) {
1340 ++NumElse;
1341
1342 // #elif directive in a non-skipping conditional... start skipping.
1343 // We don't care what the condition is, because we will always skip it (since
1344 // the block immediately before it was included).
1345 DiscardUntilEndOfDirective();
1346
1347 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001348 if (CurPPLexer->popConditionalLevel(CI)) {
1349 Diag(ElifToken, diag::pp_err_elif_without_if);
1350 return;
1351 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001352
1353 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001354 if (CurPPLexer->getConditionalStackDepth() == 0)
1355 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001356
1357 // If this is a #elif with a #else before it, report the error.
1358 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1359
1360 // Finally, skip the rest of the contents of this block and return the first
1361 // token after it.
1362 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1363 /*FoundElse*/CI.FoundElse);
1364}
1365