blob: 1c8f7f1f3a333e435091460954173180279a0323 [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
Chris Lattner099dd052009-01-26 05:30:54 +0000632/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
633///
Chris Lattner141e71f2008-03-09 01:54:53 +0000634void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
635 bool isWarning) {
Chris Lattner099dd052009-01-26 05:30:54 +0000636 // PTH doesn't emit #warning or #error directives.
637 if (CurPTHLexer)
Chris Lattner359cc442009-01-26 05:29:08 +0000638 return CurPTHLexer->DiscardToEndOfLine();
639
Chris Lattner141e71f2008-03-09 01:54:53 +0000640 // Read the rest of the line raw. We do this because we don't want macros
641 // to be expanded and we don't require that the tokens be valid preprocessing
642 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
643 // collapse multiple consequtive white space between tokens, but this isn't
644 // specified by the standard.
Chris Lattner359cc442009-01-26 05:29:08 +0000645 std::string Message = CurLexer->ReadToEndOfLine();
646 if (isWarning)
647 Diag(Tok, diag::pp_hash_warning) << Message;
648 else
649 Diag(Tok, diag::err_pp_hash_error) << Message;
Chris Lattner141e71f2008-03-09 01:54:53 +0000650}
651
652/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
653///
654void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
655 // Yes, this directive is an extension.
656 Diag(Tok, diag::ext_pp_ident_directive);
657
658 // Read the string argument.
659 Token StrTok;
660 Lex(StrTok);
661
662 // If the token kind isn't a string, it's a malformed directive.
663 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner3692b092008-11-18 07:59:24 +0000664 StrTok.isNot(tok::wide_string_literal)) {
665 Diag(StrTok, diag::err_pp_malformed_ident);
Chris Lattner099dd052009-01-26 05:30:54 +0000666 if (StrTok.isNot(tok::eom))
667 DiscardUntilEndOfDirective();
Chris Lattner3692b092008-11-18 07:59:24 +0000668 return;
669 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000670
671 // Verify that there is nothing after the string, other than EOM.
672 CheckEndOfDirective("#ident");
673
674 if (Callbacks)
675 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
676}
677
678//===----------------------------------------------------------------------===//
679// Preprocessor Include Directive Handling.
680//===----------------------------------------------------------------------===//
681
682/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
683/// checked and spelled filename, e.g. as an operand of #include. This returns
684/// true if the input filename was in <>'s or false if it were in ""'s. The
685/// caller is expected to provide a buffer that is large enough to hold the
686/// spelling of the filename, but is also expected to handle the case when
687/// this method decides to use a different buffer.
688bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
689 const char *&BufStart,
690 const char *&BufEnd) {
691 // Get the text form of the filename.
692 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
693
694 // Make sure the filename is <x> or "x".
695 bool isAngled;
696 if (BufStart[0] == '<') {
697 if (BufEnd[-1] != '>') {
698 Diag(Loc, diag::err_pp_expects_filename);
699 BufStart = 0;
700 return true;
701 }
702 isAngled = true;
703 } else if (BufStart[0] == '"') {
704 if (BufEnd[-1] != '"') {
705 Diag(Loc, diag::err_pp_expects_filename);
706 BufStart = 0;
707 return true;
708 }
709 isAngled = false;
710 } else {
711 Diag(Loc, diag::err_pp_expects_filename);
712 BufStart = 0;
713 return true;
714 }
715
716 // Diagnose #include "" as invalid.
717 if (BufEnd-BufStart <= 2) {
718 Diag(Loc, diag::err_pp_empty_filename);
719 BufStart = 0;
720 return "";
721 }
722
723 // Skip the brackets.
724 ++BufStart;
725 --BufEnd;
726 return isAngled;
727}
728
729/// ConcatenateIncludeName - Handle cases where the #include name is expanded
730/// from a macro as multiple tokens, which need to be glued together. This
731/// occurs for code like:
732/// #define FOO <a/b.h>
733/// #include FOO
734/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
735///
736/// This code concatenates and consumes tokens up to the '>' token. It returns
737/// false if the > was found, otherwise it returns true if it finds and consumes
738/// the EOM marker.
739static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
740 Preprocessor &PP) {
741 Token CurTok;
742
743 PP.Lex(CurTok);
744 while (CurTok.isNot(tok::eom)) {
745 // Append the spelling of this token to the buffer. If there was a space
746 // before it, add it now.
747 if (CurTok.hasLeadingSpace())
748 FilenameBuffer.push_back(' ');
749
750 // Get the spelling of the token, directly into FilenameBuffer if possible.
751 unsigned PreAppendSize = FilenameBuffer.size();
752 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
753
754 const char *BufPtr = &FilenameBuffer[PreAppendSize];
755 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
756
757 // If the token was spelled somewhere else, copy it into FilenameBuffer.
758 if (BufPtr != &FilenameBuffer[PreAppendSize])
759 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
760
761 // Resize FilenameBuffer to the correct size.
762 if (CurTok.getLength() != ActualLen)
763 FilenameBuffer.resize(PreAppendSize+ActualLen);
764
765 // If we found the '>' marker, return success.
766 if (CurTok.is(tok::greater))
767 return false;
768
769 PP.Lex(CurTok);
770 }
771
772 // If we hit the eom marker, emit an error and return true so that the caller
773 // knows the EOM has been read.
774 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
775 return true;
776}
777
778/// HandleIncludeDirective - The "#include" tokens have just been read, read the
779/// file to be included from the lexer, then include it! This is a common
780/// routine with functionality shared between #include, #include_next and
Chris Lattner72181832008-09-26 20:12:23 +0000781/// #import. LookupFrom is set when this is a #include_next directive, it
782/// specifies the file to start searching from.
Chris Lattner141e71f2008-03-09 01:54:53 +0000783void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
784 const DirectoryLookup *LookupFrom,
785 bool isImport) {
786
787 Token FilenameTok;
Ted Kremenek60e45d42008-11-18 00:34:22 +0000788 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattner141e71f2008-03-09 01:54:53 +0000789
790 // Reserve a buffer to get the spelling.
791 llvm::SmallVector<char, 128> FilenameBuffer;
792 const char *FilenameStart, *FilenameEnd;
793
794 switch (FilenameTok.getKind()) {
795 case tok::eom:
796 // If the token kind is EOM, the error has already been diagnosed.
797 return;
798
799 case tok::angle_string_literal:
800 case tok::string_literal: {
801 FilenameBuffer.resize(FilenameTok.getLength());
802 FilenameStart = &FilenameBuffer[0];
803 unsigned Len = getSpelling(FilenameTok, FilenameStart);
804 FilenameEnd = FilenameStart+Len;
805 break;
806 }
807
808 case tok::less:
809 // This could be a <foo/bar.h> file coming from a macro expansion. In this
810 // case, glue the tokens together into FilenameBuffer and interpret those.
811 FilenameBuffer.push_back('<');
812 if (ConcatenateIncludeName(FilenameBuffer, *this))
813 return; // Found <eom> but no ">"? Diagnostic already emitted.
814 FilenameStart = &FilenameBuffer[0];
815 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
816 break;
817 default:
818 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
819 DiscardUntilEndOfDirective();
820 return;
821 }
822
823 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
824 FilenameStart, FilenameEnd);
825 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
826 // error.
827 if (FilenameStart == 0) {
828 DiscardUntilEndOfDirective();
829 return;
830 }
831
832 // Verify that there is nothing after the filename, other than EOM. Use the
833 // preprocessor to lex this in case lexing the filename entered a macro.
834 CheckEndOfDirective("#include");
835
836 // Check that we don't have infinite #include recursion.
Chris Lattner3692b092008-11-18 07:59:24 +0000837 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
838 Diag(FilenameTok, diag::err_pp_include_too_deep);
839 return;
840 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000841
842 // Search include directories.
843 const DirectoryLookup *CurDir;
844 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
845 isAngled, LookupFrom, CurDir);
Chris Lattner3692b092008-11-18 07:59:24 +0000846 if (File == 0) {
847 Diag(FilenameTok, diag::err_pp_file_not_found)
848 << std::string(FilenameStart, FilenameEnd);
849 return;
850 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000851
Chris Lattner72181832008-09-26 20:12:23 +0000852 // Ask HeaderInfo if we should enter this #include file. If not, #including
853 // this file will have no effect.
854 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport))
Chris Lattner141e71f2008-03-09 01:54:53 +0000855 return;
Chris Lattner72181832008-09-26 20:12:23 +0000856
857 // The #included file will be considered to be a system header if either it is
858 // in a system include directory, or if the #includer is a system include
859 // header.
Chris Lattner9d728512008-10-27 01:19:25 +0000860 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000861 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattner693faa62009-01-19 07:59:15 +0000862 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Chris Lattner72181832008-09-26 20:12:23 +0000863
Chris Lattner141e71f2008-03-09 01:54:53 +0000864 // Look up the file, create a File ID for it.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000865 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
866 FileCharacter);
867 if (FID.isInvalid()) {
Chris Lattner56b05c82008-11-18 08:02:48 +0000868 Diag(FilenameTok, diag::err_pp_file_not_found)
869 << std::string(FilenameStart, FilenameEnd);
870 return;
871 }
Chris Lattner141e71f2008-03-09 01:54:53 +0000872
873 // Finally, if all is good, enter the new file!
Chris Lattner2b2453a2009-01-17 06:22:33 +0000874 EnterSourceFile(FID, CurDir);
Chris Lattner141e71f2008-03-09 01:54:53 +0000875}
876
877/// HandleIncludeNextDirective - Implements #include_next.
878///
879void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
880 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
881
882 // #include_next is like #include, except that we start searching after
883 // the current found directory. If we can't do this, issue a
884 // diagnostic.
885 const DirectoryLookup *Lookup = CurDirLookup;
886 if (isInPrimaryFile()) {
887 Lookup = 0;
888 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
889 } else if (Lookup == 0) {
890 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
891 } else {
892 // Start looking up in the next directory.
893 ++Lookup;
894 }
895
896 return HandleIncludeDirective(IncludeNextTok, Lookup);
897}
898
899/// HandleImportDirective - Implements #import.
900///
901void Preprocessor::HandleImportDirective(Token &ImportTok) {
902 Diag(ImportTok, diag::ext_pp_import_directive);
903
904 return HandleIncludeDirective(ImportTok, 0, true);
905}
906
907//===----------------------------------------------------------------------===//
908// Preprocessor Macro Directive Handling.
909//===----------------------------------------------------------------------===//
910
911/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
912/// definition has just been read. Lex the rest of the arguments and the
913/// closing ), updating MI with what we learn. Return true if an error occurs
914/// parsing the arg list.
915bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
916 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
917
918 Token Tok;
919 while (1) {
920 LexUnexpandedToken(Tok);
921 switch (Tok.getKind()) {
922 case tok::r_paren:
923 // Found the end of the argument list.
924 if (Arguments.empty()) { // #define FOO()
925 MI->setArgumentList(Arguments.begin(), Arguments.end());
926 return false;
927 }
928 // Otherwise we have #define FOO(A,)
929 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
930 return true;
931 case tok::ellipsis: // #define X(... -> C99 varargs
932 // Warn if use of C99 feature in non-C99 mode.
933 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
934
935 // Lex the token after the identifier.
936 LexUnexpandedToken(Tok);
937 if (Tok.isNot(tok::r_paren)) {
938 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
939 return true;
940 }
941 // Add the __VA_ARGS__ identifier as an argument.
942 Arguments.push_back(Ident__VA_ARGS__);
943 MI->setIsC99Varargs();
944 MI->setArgumentList(Arguments.begin(), Arguments.end());
945 return false;
946 case tok::eom: // #define X(
947 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
948 return true;
949 default:
950 // Handle keywords and identifiers here to accept things like
951 // #define Foo(for) for.
952 IdentifierInfo *II = Tok.getIdentifierInfo();
953 if (II == 0) {
954 // #define X(1
955 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
956 return true;
957 }
958
959 // If this is already used as an argument, it is used multiple times (e.g.
960 // #define X(A,A.
961 if (std::find(Arguments.begin(), Arguments.end(), II) !=
962 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6cf3ed72008-11-19 07:33:58 +0000963 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattner141e71f2008-03-09 01:54:53 +0000964 return true;
965 }
966
967 // Add the argument to the macro info.
968 Arguments.push_back(II);
969
970 // Lex the token after the identifier.
971 LexUnexpandedToken(Tok);
972
973 switch (Tok.getKind()) {
974 default: // #define X(A B
975 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
976 return true;
977 case tok::r_paren: // #define X(A)
978 MI->setArgumentList(Arguments.begin(), Arguments.end());
979 return false;
980 case tok::comma: // #define X(A,
981 break;
982 case tok::ellipsis: // #define X(A... -> GCC extension
983 // Diagnose extension.
984 Diag(Tok, diag::ext_named_variadic_macro);
985
986 // Lex the token after the identifier.
987 LexUnexpandedToken(Tok);
988 if (Tok.isNot(tok::r_paren)) {
989 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
990 return true;
991 }
992
993 MI->setIsGNUVarargs();
994 MI->setArgumentList(Arguments.begin(), Arguments.end());
995 return false;
996 }
997 }
998 }
999}
1000
1001/// HandleDefineDirective - Implements #define. This consumes the entire macro
1002/// line then lets the caller lex the next real token.
1003void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1004 ++NumDefined;
1005
1006 Token MacroNameTok;
1007 ReadMacroName(MacroNameTok, 1);
1008
1009 // Error reading macro name? If so, diagnostic already issued.
1010 if (MacroNameTok.is(tok::eom))
1011 return;
1012
1013 // If we are supposed to keep comments in #defines, reenable comment saving
1014 // mode.
Ted Kremenekac6b06d2008-11-18 00:43:07 +00001015 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Chris Lattner141e71f2008-03-09 01:54:53 +00001016
1017 // Create the new macro.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001018 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Chris Lattner141e71f2008-03-09 01:54:53 +00001019
1020 Token Tok;
1021 LexUnexpandedToken(Tok);
1022
1023 // If this is a function-like macro definition, parse the argument list,
1024 // marking each of the identifiers as being used as macro arguments. Also,
1025 // check other constraints on the first token of the macro body.
1026 if (Tok.is(tok::eom)) {
1027 // If there is no body to this macro, we have no special handling here.
1028 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
1029 // This is a function-like macro definition. Read the argument list.
1030 MI->setIsFunctionLike();
1031 if (ReadMacroDefinitionArgList(MI)) {
1032 // Forget about MI.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001033 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001034 // Throw away the rest of the line.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001035 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattner141e71f2008-03-09 01:54:53 +00001036 DiscardUntilEndOfDirective();
1037 return;
1038 }
1039
1040 // Read the first token after the arg list for down below.
1041 LexUnexpandedToken(Tok);
1042 } else if (!Tok.hasLeadingSpace()) {
1043 // C99 requires whitespace between the macro definition and the body. Emit
1044 // a diagnostic for something like "#define X+".
1045 if (Features.C99) {
1046 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1047 } else {
1048 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1049 // one in some cases!
1050 }
1051 } else {
1052 // This is a normal token with leading space. Clear the leading space
1053 // marker on the first token to get proper expansion.
1054 Tok.clearFlag(Token::LeadingSpace);
1055 }
1056
1057 // If this is a definition of a variadic C99 function-like macro, not using
1058 // the GNU named varargs extension, enabled __VA_ARGS__.
1059
1060 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1061 // This gets unpoisoned where it is allowed.
1062 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1063 if (MI->isC99Varargs())
1064 Ident__VA_ARGS__->setIsPoisoned(false);
1065
1066 // Read the rest of the macro body.
1067 if (MI->isObjectLike()) {
1068 // Object-like macros are very simple, just read their body.
1069 while (Tok.isNot(tok::eom)) {
Chris Lattner9bd0d592009-01-26 04:06:48 +00001070 // If this token has a virtual location, resolve it down to its spelling
1071 // location. This is not strictly needed, but avoids extra resolutions
1072 // for macros that are expanded frequently.
1073 if (!Tok.getLocation().isFileID())
1074 Tok.setLocation(SourceMgr.getSpellingLoc(Tok.getLocation()));
1075
Chris Lattner141e71f2008-03-09 01:54:53 +00001076 MI->AddTokenToBody(Tok);
1077 // Get the next token of the macro.
1078 LexUnexpandedToken(Tok);
1079 }
1080
1081 } else {
1082 // Otherwise, read the body of a function-like macro. This has to validate
1083 // the # (stringize) operator.
1084 while (Tok.isNot(tok::eom)) {
Chris Lattner9bd0d592009-01-26 04:06:48 +00001085 // If this token has a virtual location, resolve it down to its spelling
1086 // location. This is not strictly needed, but avoids extra resolutions
1087 // for macros that are expanded frequently.
1088 if (!Tok.getLocation().isFileID())
1089 Tok.setLocation(SourceMgr.getSpellingLoc(Tok.getLocation()));
1090
Chris Lattner141e71f2008-03-09 01:54:53 +00001091 MI->AddTokenToBody(Tok);
1092
1093 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1094 // parameters in function-like macro expansions.
1095 if (Tok.isNot(tok::hash)) {
1096 // Get the next token of the macro.
1097 LexUnexpandedToken(Tok);
1098 continue;
1099 }
1100
1101 // Get the next token of the macro.
1102 LexUnexpandedToken(Tok);
1103
1104 // Not a macro arg identifier?
1105 if (!Tok.getIdentifierInfo() ||
1106 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1107 Diag(Tok, diag::err_pp_stringize_not_parameter);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001108 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001109
1110 // Disable __VA_ARGS__ again.
1111 Ident__VA_ARGS__->setIsPoisoned(true);
1112 return;
1113 }
1114
1115 // Things look ok, add the param name token to the macro.
1116 MI->AddTokenToBody(Tok);
1117
1118 // Get the next token of the macro.
1119 LexUnexpandedToken(Tok);
1120 }
1121 }
1122
1123
1124 // Disable __VA_ARGS__ again.
1125 Ident__VA_ARGS__->setIsPoisoned(true);
1126
1127 // Check that there is no paste (##) operator at the begining or end of the
1128 // replacement list.
1129 unsigned NumTokens = MI->getNumTokens();
1130 if (NumTokens != 0) {
1131 if (MI->getReplacementToken(0).is(tok::hashhash)) {
1132 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001133 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001134 return;
1135 }
1136 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1137 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek0ea76722008-12-15 19:56:42 +00001138 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001139 return;
1140 }
1141 }
1142
1143 // If this is the primary source file, remember that this macro hasn't been
1144 // used yet.
1145 if (isInPrimaryFile())
1146 MI->setIsUsed(false);
1147
1148 // Finally, if this identifier already had a macro defined for it, verify that
1149 // the macro bodies are identical and free the old definition.
1150 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner41c3ae12009-01-16 19:50:11 +00001151 // It is very common for system headers to have tons of macro redefinitions
1152 // and for warnings to be disabled in system headers. If this is the case,
1153 // then don't bother calling MacroInfo::isIdenticalTo.
1154 if (!Diags.getSuppressSystemWarnings() ||
1155 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1156 if (!OtherMI->isUsed())
1157 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner141e71f2008-03-09 01:54:53 +00001158
Chris Lattner41c3ae12009-01-16 19:50:11 +00001159 // Macros must be identical. This means all tokes and whitespace
1160 // separation must be the same. C99 6.10.3.2.
1161 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1162 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1163 << MacroNameTok.getIdentifierInfo();
1164 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1165 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001166 }
Chris Lattner41c3ae12009-01-16 19:50:11 +00001167
Ted Kremenek0ea76722008-12-15 19:56:42 +00001168 ReleaseMacroInfo(OtherMI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001169 }
1170
1171 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1172}
1173
1174/// HandleUndefDirective - Implements #undef.
1175///
1176void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1177 ++NumUndefined;
1178
1179 Token MacroNameTok;
1180 ReadMacroName(MacroNameTok, 2);
1181
1182 // Error reading macro name? If so, diagnostic already issued.
1183 if (MacroNameTok.is(tok::eom))
1184 return;
1185
1186 // Check to see if this is the last token on the #undef line.
1187 CheckEndOfDirective("#undef");
1188
1189 // Okay, we finally have a valid identifier to undef.
1190 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1191
1192 // If the macro is not defined, this is a noop undef, just return.
1193 if (MI == 0) return;
1194
1195 if (!MI->isUsed())
1196 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1197
1198 // Free macro definition.
Ted Kremenek0ea76722008-12-15 19:56:42 +00001199 ReleaseMacroInfo(MI);
Chris Lattner141e71f2008-03-09 01:54:53 +00001200 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1201}
1202
1203
1204//===----------------------------------------------------------------------===//
1205// Preprocessor Conditional Directive Handling.
1206//===----------------------------------------------------------------------===//
1207
1208/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1209/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1210/// if any tokens have been returned or pp-directives activated before this
1211/// #ifndef has been lexed.
1212///
1213void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1214 bool ReadAnyTokensBeforeDirective) {
1215 ++NumIf;
1216 Token DirectiveTok = Result;
1217
1218 Token MacroNameTok;
1219 ReadMacroName(MacroNameTok);
1220
1221 // Error reading macro name? If so, diagnostic already issued.
1222 if (MacroNameTok.is(tok::eom)) {
1223 // Skip code until we get to #endif. This helps with recovery by not
1224 // emitting an error when the #endif is reached.
1225 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1226 /*Foundnonskip*/false, /*FoundElse*/false);
1227 return;
1228 }
1229
1230 // Check to see if this is the last token on the #if[n]def line.
1231 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1232
Ted Kremenek60e45d42008-11-18 00:34:22 +00001233 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001234 // If the start of a top-level #ifdef, inform MIOpt.
1235 if (!ReadAnyTokensBeforeDirective) {
1236 assert(isIfndef && "#ifdef shouldn't reach here");
Ted Kremenek60e45d42008-11-18 00:34:22 +00001237 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
Chris Lattner141e71f2008-03-09 01:54:53 +00001238 } else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001239 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001240 }
1241
1242 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1243 MacroInfo *MI = getMacroInfo(MII);
1244
1245 // If there is a macro, process it.
1246 if (MI) // Mark it used.
1247 MI->setIsUsed(true);
1248
1249 // Should we include the stuff contained by this directive?
1250 if (!MI == isIfndef) {
1251 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001252 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001253 /*foundnonskip*/true, /*foundelse*/false);
1254 } else {
1255 // No, skip the contents of this block and return the first token after it.
1256 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1257 /*Foundnonskip*/false,
1258 /*FoundElse*/false);
1259 }
1260}
1261
1262/// HandleIfDirective - Implements the #if directive.
1263///
1264void Preprocessor::HandleIfDirective(Token &IfToken,
1265 bool ReadAnyTokensBeforeDirective) {
1266 ++NumIf;
1267
1268 // Parse and evaluation the conditional expression.
1269 IdentifierInfo *IfNDefMacro = 0;
1270 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1271
Nuno Lopes0049db62008-06-01 18:31:24 +00001272
1273 // If this condition is equivalent to #ifndef X, and if this is the first
1274 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001275 if (CurPPLexer->getConditionalStackDepth() == 0) {
Nuno Lopes0049db62008-06-01 18:31:24 +00001276 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
Ted Kremenek60e45d42008-11-18 00:34:22 +00001277 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
Nuno Lopes0049db62008-06-01 18:31:24 +00001278 else
Ted Kremenek60e45d42008-11-18 00:34:22 +00001279 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes0049db62008-06-01 18:31:24 +00001280 }
1281
Chris Lattner141e71f2008-03-09 01:54:53 +00001282 // Should we include the stuff contained by this directive?
1283 if (ConditionalTrue) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001284 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001285 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner141e71f2008-03-09 01:54:53 +00001286 /*foundnonskip*/true, /*foundelse*/false);
1287 } else {
1288 // No, skip the contents of this block and return the first token after it.
1289 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1290 /*FoundElse*/false);
1291 }
1292}
1293
1294/// HandleEndifDirective - Implements the #endif directive.
1295///
1296void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1297 ++NumEndif;
1298
1299 // Check that this is the whole directive.
1300 CheckEndOfDirective("#endif");
1301
1302 PPConditionalInfo CondInfo;
Ted Kremenek60e45d42008-11-18 00:34:22 +00001303 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattner141e71f2008-03-09 01:54:53 +00001304 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner3692b092008-11-18 07:59:24 +00001305 Diag(EndifToken, diag::err_pp_endif_without_if);
1306 return;
Chris Lattner141e71f2008-03-09 01:54:53 +00001307 }
1308
1309 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001310 if (CurPPLexer->getConditionalStackDepth() == 0)
1311 CurPPLexer->MIOpt.ExitTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001312
Ted Kremenek60e45d42008-11-18 00:34:22 +00001313 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattner141e71f2008-03-09 01:54:53 +00001314 "This code should only be reachable in the non-skipping case!");
1315}
1316
1317
1318void Preprocessor::HandleElseDirective(Token &Result) {
1319 ++NumElse;
1320
1321 // #else directive in a non-skipping conditional... start skipping.
1322 CheckEndOfDirective("#else");
1323
1324 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001325 if (CurPPLexer->popConditionalLevel(CI)) {
1326 Diag(Result, diag::pp_err_else_without_if);
1327 return;
1328 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001329
1330 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001331 if (CurPPLexer->getConditionalStackDepth() == 0)
1332 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001333
1334 // If this is a #else with a #else before it, report the error.
1335 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1336
1337 // Finally, skip the rest of the contents of this block and return the first
1338 // token after it.
1339 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1340 /*FoundElse*/true);
1341}
1342
1343void Preprocessor::HandleElifDirective(Token &ElifToken) {
1344 ++NumElse;
1345
1346 // #elif directive in a non-skipping conditional... start skipping.
1347 // We don't care what the condition is, because we will always skip it (since
1348 // the block immediately before it was included).
1349 DiscardUntilEndOfDirective();
1350
1351 PPConditionalInfo CI;
Chris Lattner3692b092008-11-18 07:59:24 +00001352 if (CurPPLexer->popConditionalLevel(CI)) {
1353 Diag(ElifToken, diag::pp_err_elif_without_if);
1354 return;
1355 }
Chris Lattner141e71f2008-03-09 01:54:53 +00001356
1357 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek60e45d42008-11-18 00:34:22 +00001358 if (CurPPLexer->getConditionalStackDepth() == 0)
1359 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattner141e71f2008-03-09 01:54:53 +00001360
1361 // If this is a #elif with a #else before it, report the error.
1362 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1363
1364 // Finally, skip the rest of the contents of this block and return the first
1365 // token after it.
1366 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1367 /*FoundElse*/CI.FoundElse);
1368}
1369