blob: 2871e30ed99032b6a8224a0cd04f1837efc4a1ab [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"
15#include "clang/Lex/HeaderSearch.h"
16#include "clang/Lex/MacroInfo.h"
17#include "clang/Lex/PPCallbacks.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/SourceManager.h"
20using namespace clang;
21
22//===----------------------------------------------------------------------===//
23// Utility Methods for Preprocessor Directive Handling.
24//===----------------------------------------------------------------------===//
25
26/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
27/// current line until the tok::eom token is found.
28void Preprocessor::DiscardUntilEndOfDirective() {
29 Token Tmp;
30 do {
31 LexUnexpandedToken(Tmp);
32 } while (Tmp.isNot(tok::eom));
33}
34
35/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
36static bool isCXXNamedOperator(const std::string &Spelling) {
37 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
38 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
39 Spelling == "or" || Spelling == "xor";
40}
41
42/// ReadMacroName - Lex and validate a macro name, which occurs after a
43/// #define or #undef. This sets the token kind to eom and discards the rest
44/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
45/// this is due to a a #define, 2 if #undef directive, 0 if it is something
46/// else (e.g. #ifdef).
47void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
48 // Read the token, don't allow macro expansion on it.
49 LexUnexpandedToken(MacroNameTok);
50
51 // Missing macro name?
52 if (MacroNameTok.is(tok::eom))
53 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
54
55 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
56 if (II == 0) {
57 std::string Spelling = getSpelling(MacroNameTok);
58 if (isCXXNamedOperator(Spelling))
59 // C++ 2.5p2: Alternative tokens behave the same as its primary token
60 // except for their spellings.
61 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
62 else
63 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
64 // Fall through on error.
65 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
66 // Error if defining "defined": C99 6.10.8.4.
67 Diag(MacroNameTok, diag::err_defined_macro_name);
68 } else if (isDefineUndef && II->hasMacroDefinition() &&
69 getMacroInfo(II)->isBuiltinMacro()) {
70 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
71 if (isDefineUndef == 1)
72 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
73 else
74 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
75 } else {
76 // Okay, we got a good identifier node. Return it.
77 return;
78 }
79
80 // Invalid macro name, read and discard the rest of the line. Then set the
81 // token kind to tok::eom.
82 MacroNameTok.setKind(tok::eom);
83 return DiscardUntilEndOfDirective();
84}
85
86/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
87/// not, emit a diagnostic and consume up until the eom.
88void Preprocessor::CheckEndOfDirective(const char *DirType) {
89 Token Tmp;
90 // Lex unexpanded tokens: macros might expand to zero tokens, causing us to
91 // miss diagnosing invalid lines.
92 LexUnexpandedToken(Tmp);
93
94 // There should be no tokens after the directive, but we allow them as an
95 // extension.
96 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
97 LexUnexpandedToken(Tmp);
98
99 if (Tmp.isNot(tok::eom)) {
100 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
101 DiscardUntilEndOfDirective();
102 }
103}
104
105
106
107/// SkipExcludedConditionalBlock - We just read a #if or related directive and
108/// decided that the subsequent tokens are in the #if'd out portion of the
109/// file. Lex the rest of the file, until we see an #endif. If
110/// FoundNonSkipPortion is true, then we have already emitted code for part of
111/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
112/// is true, then #else directives are ok, if not, then we have already seen one
113/// so a #else directive is a duplicate. When this returns, the caller can lex
114/// the first valid token.
115void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
116 bool FoundNonSkipPortion,
117 bool FoundElse) {
118 ++NumSkipped;
Chris Lattner6cfe7592008-03-09 02:26:03 +0000119 assert(CurTokenLexer == 0 && CurLexer &&
Chris Lattner141e71f2008-03-09 01:54:53 +0000120 "Lexing a macro, not a file?");
121
122 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
123 FoundNonSkipPortion, FoundElse);
124
125 // Enter raw mode to disable identifier lookup (and thus macro expansion),
126 // disabling warnings, etc.
127 CurLexer->LexingRawMode = true;
128 Token Tok;
129 while (1) {
130 CurLexer->Lex(Tok);
131
132 // If this is the end of the buffer, we have an error.
133 if (Tok.is(tok::eof)) {
134 // Emit errors for each unterminated conditional on the stack, including
135 // the current one.
136 while (!CurLexer->ConditionalStack.empty()) {
137 Diag(CurLexer->ConditionalStack.back().IfLoc,
138 diag::err_pp_unterminated_conditional);
139 CurLexer->ConditionalStack.pop_back();
140 }
141
142 // Just return and let the caller lex after this #include.
143 break;
144 }
145
146 // If this token is not a preprocessor directive, just skip it.
147 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
148 continue;
149
150 // We just parsed a # character at the start of a line, so we're in
151 // directive mode. Tell the lexer this so any newlines we see will be
152 // converted into an EOM token (this terminates the macro).
153 CurLexer->ParsingPreprocessorDirective = true;
154 CurLexer->KeepCommentMode = false;
155
156
157 // Read the next token, the directive flavor.
158 LexUnexpandedToken(Tok);
159
160 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
161 // something bogus), skip it.
162 if (Tok.isNot(tok::identifier)) {
163 CurLexer->ParsingPreprocessorDirective = false;
164 // Restore comment saving mode.
165 CurLexer->KeepCommentMode = KeepComments;
166 continue;
167 }
168
169 // If the first letter isn't i or e, it isn't intesting to us. We know that
170 // this is safe in the face of spelling differences, because there is no way
171 // to spell an i/e in a strange way that is another letter. Skipping this
172 // allows us to avoid looking up the identifier info for #define/#undef and
173 // other common directives.
174 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
175 char FirstChar = RawCharData[0];
176 if (FirstChar >= 'a' && FirstChar <= 'z' &&
177 FirstChar != 'i' && FirstChar != 'e') {
178 CurLexer->ParsingPreprocessorDirective = false;
179 // Restore comment saving mode.
180 CurLexer->KeepCommentMode = KeepComments;
181 continue;
182 }
183
184 // Get the identifier name without trigraphs or embedded newlines. Note
185 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
186 // when skipping.
187 // TODO: could do this with zero copies in the no-clean case by using
188 // strncmp below.
189 char Directive[20];
190 unsigned IdLen;
191 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
192 IdLen = Tok.getLength();
193 memcpy(Directive, RawCharData, IdLen);
194 Directive[IdLen] = 0;
195 } else {
196 std::string DirectiveStr = getSpelling(Tok);
197 IdLen = DirectiveStr.size();
198 if (IdLen >= 20) {
199 CurLexer->ParsingPreprocessorDirective = false;
200 // Restore comment saving mode.
201 CurLexer->KeepCommentMode = KeepComments;
202 continue;
203 }
204 memcpy(Directive, &DirectiveStr[0], IdLen);
205 Directive[IdLen] = 0;
206 }
207
208 if (FirstChar == 'i' && Directive[1] == 'f') {
209 if ((IdLen == 2) || // "if"
210 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
211 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
212 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
213 // bother parsing the condition.
214 DiscardUntilEndOfDirective();
215 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
216 /*foundnonskip*/false,
217 /*fnddelse*/false);
218 }
219 } else if (FirstChar == 'e') {
220 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
221 CheckEndOfDirective("#endif");
222 PPConditionalInfo CondInfo;
223 CondInfo.WasSkipping = true; // Silence bogus warning.
224 bool InCond = CurLexer->popConditionalLevel(CondInfo);
225 InCond = InCond; // Silence warning in no-asserts mode.
226 assert(!InCond && "Can't be skipping if not in a conditional!");
227
228 // If we popped the outermost skipping block, we're done skipping!
229 if (!CondInfo.WasSkipping)
230 break;
231 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
232 // #else directive in a skipping conditional. If not in some other
233 // skipping conditional, and if #else hasn't already been seen, enter it
234 // as a non-skipping conditional.
235 CheckEndOfDirective("#else");
236 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
237
238 // If this is a #else with a #else before it, report the error.
239 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
240
241 // Note that we've seen a #else in this conditional.
242 CondInfo.FoundElse = true;
243
244 // If the conditional is at the top level, and the #if block wasn't
245 // entered, enter the #else block now.
246 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
247 CondInfo.FoundNonSkip = true;
248 break;
249 }
250 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
251 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
252
253 bool ShouldEnter;
254 // If this is in a skipping block or if we're already handled this #if
255 // block, don't bother parsing the condition.
256 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
257 DiscardUntilEndOfDirective();
258 ShouldEnter = false;
259 } else {
260 // Restore the value of LexingRawMode so that identifiers are
261 // looked up, etc, inside the #elif expression.
262 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
263 CurLexer->LexingRawMode = false;
264 IdentifierInfo *IfNDefMacro = 0;
265 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
266 CurLexer->LexingRawMode = true;
267 }
268
269 // If this is a #elif with a #else before it, report the error.
270 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
271
272 // If this condition is true, enter it!
273 if (ShouldEnter) {
274 CondInfo.FoundNonSkip = true;
275 break;
276 }
277 }
278 }
279
280 CurLexer->ParsingPreprocessorDirective = false;
281 // Restore comment saving mode.
282 CurLexer->KeepCommentMode = KeepComments;
283 }
284
285 // Finally, if we are out of the conditional (saw an #endif or ran off the end
286 // of the file, just stop skipping and return to lexing whatever came after
287 // the #if block.
288 CurLexer->LexingRawMode = false;
289}
290
291
292//===----------------------------------------------------------------------===//
293// Preprocessor Directive Handling.
294//===----------------------------------------------------------------------===//
295
296/// HandleDirective - This callback is invoked when the lexer sees a # token
297/// at the start of a line. This consumes the directive, modifies the
298/// lexer/preprocessor state, and advances the lexer(s) so that the next token
299/// read is the correct one.
300void Preprocessor::HandleDirective(Token &Result) {
301 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
302
303 // We just parsed a # character at the start of a line, so we're in directive
304 // mode. Tell the lexer this so any newlines we see will be converted into an
305 // EOM token (which terminates the directive).
306 CurLexer->ParsingPreprocessorDirective = true;
307
308 ++NumDirectives;
309
310 // We are about to read a token. For the multiple-include optimization FA to
311 // work, we have to remember if we had read any tokens *before* this
312 // pp-directive.
313 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
314
315 // Read the next token, the directive flavor. This isn't expanded due to
316 // C99 6.10.3p8.
317 LexUnexpandedToken(Result);
318
319 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
320 // #define A(x) #x
321 // A(abc
322 // #warning blah
323 // def)
324 // If so, the user is relying on non-portable behavior, emit a diagnostic.
325 if (InMacroArgs)
326 Diag(Result, diag::ext_embedded_directive);
327
328TryAgain:
329 switch (Result.getKind()) {
330 case tok::eom:
331 return; // null directive.
332 case tok::comment:
333 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
334 LexUnexpandedToken(Result);
335 goto TryAgain;
336
337 case tok::numeric_constant:
338 // FIXME: implement # 7 line numbers!
339 DiscardUntilEndOfDirective();
340 return;
341 default:
342 IdentifierInfo *II = Result.getIdentifierInfo();
343 if (II == 0) break; // Not an identifier.
344
345 // Ask what the preprocessor keyword ID is.
346 switch (II->getPPKeywordID()) {
347 default: break;
348 // C99 6.10.1 - Conditional Inclusion.
349 case tok::pp_if:
350 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
351 case tok::pp_ifdef:
352 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
353 case tok::pp_ifndef:
354 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
355 case tok::pp_elif:
356 return HandleElifDirective(Result);
357 case tok::pp_else:
358 return HandleElseDirective(Result);
359 case tok::pp_endif:
360 return HandleEndifDirective(Result);
361
362 // C99 6.10.2 - Source File Inclusion.
363 case tok::pp_include:
364 return HandleIncludeDirective(Result); // Handle #include.
365
366 // C99 6.10.3 - Macro Replacement.
367 case tok::pp_define:
368 return HandleDefineDirective(Result);
369 case tok::pp_undef:
370 return HandleUndefDirective(Result);
371
372 // C99 6.10.4 - Line Control.
373 case tok::pp_line:
374 // FIXME: implement #line
375 DiscardUntilEndOfDirective();
376 return;
377
378 // C99 6.10.5 - Error Directive.
379 case tok::pp_error:
380 return HandleUserDiagnosticDirective(Result, false);
381
382 // C99 6.10.6 - Pragma Directive.
383 case tok::pp_pragma:
384 return HandlePragmaDirective();
385
386 // GNU Extensions.
387 case tok::pp_import:
388 return HandleImportDirective(Result);
389 case tok::pp_include_next:
390 return HandleIncludeNextDirective(Result);
391
392 case tok::pp_warning:
393 Diag(Result, diag::ext_pp_warning_directive);
394 return HandleUserDiagnosticDirective(Result, true);
395 case tok::pp_ident:
396 return HandleIdentSCCSDirective(Result);
397 case tok::pp_sccs:
398 return HandleIdentSCCSDirective(Result);
399 case tok::pp_assert:
400 //isExtension = true; // FIXME: implement #assert
401 break;
402 case tok::pp_unassert:
403 //isExtension = true; // FIXME: implement #unassert
404 break;
405 }
406 break;
407 }
408
409 // If we reached here, the preprocessing token is not valid!
410 Diag(Result, diag::err_pp_invalid_directive);
411
412 // Read the rest of the PP line.
413 DiscardUntilEndOfDirective();
414
415 // Okay, we're done parsing the directive.
416}
417
418void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
419 bool isWarning) {
420 // Read the rest of the line raw. We do this because we don't want macros
421 // to be expanded and we don't require that the tokens be valid preprocessing
422 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
423 // collapse multiple consequtive white space between tokens, but this isn't
424 // specified by the standard.
425 std::string Message = CurLexer->ReadToEndOfLine();
426
427 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
428 return Diag(Tok, DiagID, Message);
429}
430
431/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
432///
433void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
434 // Yes, this directive is an extension.
435 Diag(Tok, diag::ext_pp_ident_directive);
436
437 // Read the string argument.
438 Token StrTok;
439 Lex(StrTok);
440
441 // If the token kind isn't a string, it's a malformed directive.
442 if (StrTok.isNot(tok::string_literal) &&
443 StrTok.isNot(tok::wide_string_literal))
444 return Diag(StrTok, diag::err_pp_malformed_ident);
445
446 // Verify that there is nothing after the string, other than EOM.
447 CheckEndOfDirective("#ident");
448
449 if (Callbacks)
450 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
451}
452
453//===----------------------------------------------------------------------===//
454// Preprocessor Include Directive Handling.
455//===----------------------------------------------------------------------===//
456
457/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
458/// checked and spelled filename, e.g. as an operand of #include. This returns
459/// true if the input filename was in <>'s or false if it were in ""'s. The
460/// caller is expected to provide a buffer that is large enough to hold the
461/// spelling of the filename, but is also expected to handle the case when
462/// this method decides to use a different buffer.
463bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
464 const char *&BufStart,
465 const char *&BufEnd) {
466 // Get the text form of the filename.
467 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
468
469 // Make sure the filename is <x> or "x".
470 bool isAngled;
471 if (BufStart[0] == '<') {
472 if (BufEnd[-1] != '>') {
473 Diag(Loc, diag::err_pp_expects_filename);
474 BufStart = 0;
475 return true;
476 }
477 isAngled = true;
478 } else if (BufStart[0] == '"') {
479 if (BufEnd[-1] != '"') {
480 Diag(Loc, diag::err_pp_expects_filename);
481 BufStart = 0;
482 return true;
483 }
484 isAngled = false;
485 } else {
486 Diag(Loc, diag::err_pp_expects_filename);
487 BufStart = 0;
488 return true;
489 }
490
491 // Diagnose #include "" as invalid.
492 if (BufEnd-BufStart <= 2) {
493 Diag(Loc, diag::err_pp_empty_filename);
494 BufStart = 0;
495 return "";
496 }
497
498 // Skip the brackets.
499 ++BufStart;
500 --BufEnd;
501 return isAngled;
502}
503
504/// ConcatenateIncludeName - Handle cases where the #include name is expanded
505/// from a macro as multiple tokens, which need to be glued together. This
506/// occurs for code like:
507/// #define FOO <a/b.h>
508/// #include FOO
509/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
510///
511/// This code concatenates and consumes tokens up to the '>' token. It returns
512/// false if the > was found, otherwise it returns true if it finds and consumes
513/// the EOM marker.
514static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
515 Preprocessor &PP) {
516 Token CurTok;
517
518 PP.Lex(CurTok);
519 while (CurTok.isNot(tok::eom)) {
520 // Append the spelling of this token to the buffer. If there was a space
521 // before it, add it now.
522 if (CurTok.hasLeadingSpace())
523 FilenameBuffer.push_back(' ');
524
525 // Get the spelling of the token, directly into FilenameBuffer if possible.
526 unsigned PreAppendSize = FilenameBuffer.size();
527 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
528
529 const char *BufPtr = &FilenameBuffer[PreAppendSize];
530 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
531
532 // If the token was spelled somewhere else, copy it into FilenameBuffer.
533 if (BufPtr != &FilenameBuffer[PreAppendSize])
534 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
535
536 // Resize FilenameBuffer to the correct size.
537 if (CurTok.getLength() != ActualLen)
538 FilenameBuffer.resize(PreAppendSize+ActualLen);
539
540 // If we found the '>' marker, return success.
541 if (CurTok.is(tok::greater))
542 return false;
543
544 PP.Lex(CurTok);
545 }
546
547 // If we hit the eom marker, emit an error and return true so that the caller
548 // knows the EOM has been read.
549 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
550 return true;
551}
552
553/// HandleIncludeDirective - The "#include" tokens have just been read, read the
554/// file to be included from the lexer, then include it! This is a common
555/// routine with functionality shared between #include, #include_next and
556/// #import.
557void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
558 const DirectoryLookup *LookupFrom,
559 bool isImport) {
560
561 Token FilenameTok;
562 CurLexer->LexIncludeFilename(FilenameTok);
563
564 // Reserve a buffer to get the spelling.
565 llvm::SmallVector<char, 128> FilenameBuffer;
566 const char *FilenameStart, *FilenameEnd;
567
568 switch (FilenameTok.getKind()) {
569 case tok::eom:
570 // If the token kind is EOM, the error has already been diagnosed.
571 return;
572
573 case tok::angle_string_literal:
574 case tok::string_literal: {
575 FilenameBuffer.resize(FilenameTok.getLength());
576 FilenameStart = &FilenameBuffer[0];
577 unsigned Len = getSpelling(FilenameTok, FilenameStart);
578 FilenameEnd = FilenameStart+Len;
579 break;
580 }
581
582 case tok::less:
583 // This could be a <foo/bar.h> file coming from a macro expansion. In this
584 // case, glue the tokens together into FilenameBuffer and interpret those.
585 FilenameBuffer.push_back('<');
586 if (ConcatenateIncludeName(FilenameBuffer, *this))
587 return; // Found <eom> but no ">"? Diagnostic already emitted.
588 FilenameStart = &FilenameBuffer[0];
589 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
590 break;
591 default:
592 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
593 DiscardUntilEndOfDirective();
594 return;
595 }
596
597 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
598 FilenameStart, FilenameEnd);
599 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
600 // error.
601 if (FilenameStart == 0) {
602 DiscardUntilEndOfDirective();
603 return;
604 }
605
606 // Verify that there is nothing after the filename, other than EOM. Use the
607 // preprocessor to lex this in case lexing the filename entered a macro.
608 CheckEndOfDirective("#include");
609
610 // Check that we don't have infinite #include recursion.
611 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
612 return Diag(FilenameTok, diag::err_pp_include_too_deep);
613
614 // Search include directories.
615 const DirectoryLookup *CurDir;
616 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
617 isAngled, LookupFrom, CurDir);
618 if (File == 0)
619 return Diag(FilenameTok, diag::err_pp_file_not_found,
620 std::string(FilenameStart, FilenameEnd));
621
622 // Ask HeaderInfo if we should enter this #include file.
623 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
624 // If it returns true, #including this file will have no effect.
625 return;
626 }
627
628 // Look up the file, create a File ID for it.
629 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
630 if (FileID == 0)
631 return Diag(FilenameTok, diag::err_pp_file_not_found,
632 std::string(FilenameStart, FilenameEnd));
633
634 // Finally, if all is good, enter the new file!
635 EnterSourceFile(FileID, CurDir);
636}
637
638/// HandleIncludeNextDirective - Implements #include_next.
639///
640void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
641 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
642
643 // #include_next is like #include, except that we start searching after
644 // the current found directory. If we can't do this, issue a
645 // diagnostic.
646 const DirectoryLookup *Lookup = CurDirLookup;
647 if (isInPrimaryFile()) {
648 Lookup = 0;
649 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
650 } else if (Lookup == 0) {
651 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
652 } else {
653 // Start looking up in the next directory.
654 ++Lookup;
655 }
656
657 return HandleIncludeDirective(IncludeNextTok, Lookup);
658}
659
660/// HandleImportDirective - Implements #import.
661///
662void Preprocessor::HandleImportDirective(Token &ImportTok) {
663 Diag(ImportTok, diag::ext_pp_import_directive);
664
665 return HandleIncludeDirective(ImportTok, 0, true);
666}
667
668//===----------------------------------------------------------------------===//
669// Preprocessor Macro Directive Handling.
670//===----------------------------------------------------------------------===//
671
672/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
673/// definition has just been read. Lex the rest of the arguments and the
674/// closing ), updating MI with what we learn. Return true if an error occurs
675/// parsing the arg list.
676bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
677 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
678
679 Token Tok;
680 while (1) {
681 LexUnexpandedToken(Tok);
682 switch (Tok.getKind()) {
683 case tok::r_paren:
684 // Found the end of the argument list.
685 if (Arguments.empty()) { // #define FOO()
686 MI->setArgumentList(Arguments.begin(), Arguments.end());
687 return false;
688 }
689 // Otherwise we have #define FOO(A,)
690 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
691 return true;
692 case tok::ellipsis: // #define X(... -> C99 varargs
693 // Warn if use of C99 feature in non-C99 mode.
694 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
695
696 // Lex the token after the identifier.
697 LexUnexpandedToken(Tok);
698 if (Tok.isNot(tok::r_paren)) {
699 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
700 return true;
701 }
702 // Add the __VA_ARGS__ identifier as an argument.
703 Arguments.push_back(Ident__VA_ARGS__);
704 MI->setIsC99Varargs();
705 MI->setArgumentList(Arguments.begin(), Arguments.end());
706 return false;
707 case tok::eom: // #define X(
708 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
709 return true;
710 default:
711 // Handle keywords and identifiers here to accept things like
712 // #define Foo(for) for.
713 IdentifierInfo *II = Tok.getIdentifierInfo();
714 if (II == 0) {
715 // #define X(1
716 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
717 return true;
718 }
719
720 // If this is already used as an argument, it is used multiple times (e.g.
721 // #define X(A,A.
722 if (std::find(Arguments.begin(), Arguments.end(), II) !=
723 Arguments.end()) { // C99 6.10.3p6
724 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
725 return true;
726 }
727
728 // Add the argument to the macro info.
729 Arguments.push_back(II);
730
731 // Lex the token after the identifier.
732 LexUnexpandedToken(Tok);
733
734 switch (Tok.getKind()) {
735 default: // #define X(A B
736 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
737 return true;
738 case tok::r_paren: // #define X(A)
739 MI->setArgumentList(Arguments.begin(), Arguments.end());
740 return false;
741 case tok::comma: // #define X(A,
742 break;
743 case tok::ellipsis: // #define X(A... -> GCC extension
744 // Diagnose extension.
745 Diag(Tok, diag::ext_named_variadic_macro);
746
747 // Lex the token after the identifier.
748 LexUnexpandedToken(Tok);
749 if (Tok.isNot(tok::r_paren)) {
750 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
751 return true;
752 }
753
754 MI->setIsGNUVarargs();
755 MI->setArgumentList(Arguments.begin(), Arguments.end());
756 return false;
757 }
758 }
759 }
760}
761
762/// HandleDefineDirective - Implements #define. This consumes the entire macro
763/// line then lets the caller lex the next real token.
764void Preprocessor::HandleDefineDirective(Token &DefineTok) {
765 ++NumDefined;
766
767 Token MacroNameTok;
768 ReadMacroName(MacroNameTok, 1);
769
770 // Error reading macro name? If so, diagnostic already issued.
771 if (MacroNameTok.is(tok::eom))
772 return;
773
774 // If we are supposed to keep comments in #defines, reenable comment saving
775 // mode.
776 CurLexer->KeepCommentMode = KeepMacroComments;
777
778 // Create the new macro.
779 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
780
781 Token Tok;
782 LexUnexpandedToken(Tok);
783
784 // If this is a function-like macro definition, parse the argument list,
785 // marking each of the identifiers as being used as macro arguments. Also,
786 // check other constraints on the first token of the macro body.
787 if (Tok.is(tok::eom)) {
788 // If there is no body to this macro, we have no special handling here.
789 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
790 // This is a function-like macro definition. Read the argument list.
791 MI->setIsFunctionLike();
792 if (ReadMacroDefinitionArgList(MI)) {
793 // Forget about MI.
794 delete MI;
795 // Throw away the rest of the line.
796 if (CurLexer->ParsingPreprocessorDirective)
797 DiscardUntilEndOfDirective();
798 return;
799 }
800
801 // Read the first token after the arg list for down below.
802 LexUnexpandedToken(Tok);
803 } else if (!Tok.hasLeadingSpace()) {
804 // C99 requires whitespace between the macro definition and the body. Emit
805 // a diagnostic for something like "#define X+".
806 if (Features.C99) {
807 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
808 } else {
809 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
810 // one in some cases!
811 }
812 } else {
813 // This is a normal token with leading space. Clear the leading space
814 // marker on the first token to get proper expansion.
815 Tok.clearFlag(Token::LeadingSpace);
816 }
817
818 // If this is a definition of a variadic C99 function-like macro, not using
819 // the GNU named varargs extension, enabled __VA_ARGS__.
820
821 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
822 // This gets unpoisoned where it is allowed.
823 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
824 if (MI->isC99Varargs())
825 Ident__VA_ARGS__->setIsPoisoned(false);
826
827 // Read the rest of the macro body.
828 if (MI->isObjectLike()) {
829 // Object-like macros are very simple, just read their body.
830 while (Tok.isNot(tok::eom)) {
831 MI->AddTokenToBody(Tok);
832 // Get the next token of the macro.
833 LexUnexpandedToken(Tok);
834 }
835
836 } else {
837 // Otherwise, read the body of a function-like macro. This has to validate
838 // the # (stringize) operator.
839 while (Tok.isNot(tok::eom)) {
840 MI->AddTokenToBody(Tok);
841
842 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
843 // parameters in function-like macro expansions.
844 if (Tok.isNot(tok::hash)) {
845 // Get the next token of the macro.
846 LexUnexpandedToken(Tok);
847 continue;
848 }
849
850 // Get the next token of the macro.
851 LexUnexpandedToken(Tok);
852
853 // Not a macro arg identifier?
854 if (!Tok.getIdentifierInfo() ||
855 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
856 Diag(Tok, diag::err_pp_stringize_not_parameter);
857 delete MI;
858
859 // Disable __VA_ARGS__ again.
860 Ident__VA_ARGS__->setIsPoisoned(true);
861 return;
862 }
863
864 // Things look ok, add the param name token to the macro.
865 MI->AddTokenToBody(Tok);
866
867 // Get the next token of the macro.
868 LexUnexpandedToken(Tok);
869 }
870 }
871
872
873 // Disable __VA_ARGS__ again.
874 Ident__VA_ARGS__->setIsPoisoned(true);
875
876 // Check that there is no paste (##) operator at the begining or end of the
877 // replacement list.
878 unsigned NumTokens = MI->getNumTokens();
879 if (NumTokens != 0) {
880 if (MI->getReplacementToken(0).is(tok::hashhash)) {
881 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
882 delete MI;
883 return;
884 }
885 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
886 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
887 delete MI;
888 return;
889 }
890 }
891
892 // If this is the primary source file, remember that this macro hasn't been
893 // used yet.
894 if (isInPrimaryFile())
895 MI->setIsUsed(false);
896
897 // Finally, if this identifier already had a macro defined for it, verify that
898 // the macro bodies are identical and free the old definition.
899 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
900 if (!OtherMI->isUsed())
901 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
902
903 // Macros must be identical. This means all tokes and whitespace separation
904 // must be the same. C99 6.10.3.2.
905 if (!MI->isIdenticalTo(*OtherMI, *this)) {
906 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
907 MacroNameTok.getIdentifierInfo()->getName());
908 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
909 }
910 delete OtherMI;
911 }
912
913 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
914}
915
916/// HandleUndefDirective - Implements #undef.
917///
918void Preprocessor::HandleUndefDirective(Token &UndefTok) {
919 ++NumUndefined;
920
921 Token MacroNameTok;
922 ReadMacroName(MacroNameTok, 2);
923
924 // Error reading macro name? If so, diagnostic already issued.
925 if (MacroNameTok.is(tok::eom))
926 return;
927
928 // Check to see if this is the last token on the #undef line.
929 CheckEndOfDirective("#undef");
930
931 // Okay, we finally have a valid identifier to undef.
932 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
933
934 // If the macro is not defined, this is a noop undef, just return.
935 if (MI == 0) return;
936
937 if (!MI->isUsed())
938 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
939
940 // Free macro definition.
941 delete MI;
942 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
943}
944
945
946//===----------------------------------------------------------------------===//
947// Preprocessor Conditional Directive Handling.
948//===----------------------------------------------------------------------===//
949
950/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
951/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
952/// if any tokens have been returned or pp-directives activated before this
953/// #ifndef has been lexed.
954///
955void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
956 bool ReadAnyTokensBeforeDirective) {
957 ++NumIf;
958 Token DirectiveTok = Result;
959
960 Token MacroNameTok;
961 ReadMacroName(MacroNameTok);
962
963 // Error reading macro name? If so, diagnostic already issued.
964 if (MacroNameTok.is(tok::eom)) {
965 // Skip code until we get to #endif. This helps with recovery by not
966 // emitting an error when the #endif is reached.
967 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
968 /*Foundnonskip*/false, /*FoundElse*/false);
969 return;
970 }
971
972 // Check to see if this is the last token on the #if[n]def line.
973 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
974
975 if (CurLexer->getConditionalStackDepth() == 0) {
976 // If the start of a top-level #ifdef, inform MIOpt.
977 if (!ReadAnyTokensBeforeDirective) {
978 assert(isIfndef && "#ifdef shouldn't reach here");
979 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
980 } else
981 CurLexer->MIOpt.EnterTopLevelConditional();
982 }
983
984 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
985 MacroInfo *MI = getMacroInfo(MII);
986
987 // If there is a macro, process it.
988 if (MI) // Mark it used.
989 MI->setIsUsed(true);
990
991 // Should we include the stuff contained by this directive?
992 if (!MI == isIfndef) {
993 // Yes, remember that we are inside a conditional, then lex the next token.
994 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
995 /*foundnonskip*/true, /*foundelse*/false);
996 } else {
997 // No, skip the contents of this block and return the first token after it.
998 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
999 /*Foundnonskip*/false,
1000 /*FoundElse*/false);
1001 }
1002}
1003
1004/// HandleIfDirective - Implements the #if directive.
1005///
1006void Preprocessor::HandleIfDirective(Token &IfToken,
1007 bool ReadAnyTokensBeforeDirective) {
1008 ++NumIf;
1009
1010 // Parse and evaluation the conditional expression.
1011 IdentifierInfo *IfNDefMacro = 0;
1012 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1013
1014 // Should we include the stuff contained by this directive?
1015 if (ConditionalTrue) {
1016 // If this condition is equivalent to #ifndef X, and if this is the first
1017 // directive seen, handle it for the multiple-include optimization.
1018 if (CurLexer->getConditionalStackDepth() == 0) {
1019 if (!ReadAnyTokensBeforeDirective && IfNDefMacro)
1020 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1021 else
1022 CurLexer->MIOpt.EnterTopLevelConditional();
1023 }
1024
1025 // Yes, remember that we are inside a conditional, then lex the next token.
1026 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
1027 /*foundnonskip*/true, /*foundelse*/false);
1028 } else {
1029 // No, skip the contents of this block and return the first token after it.
1030 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1031 /*FoundElse*/false);
1032 }
1033}
1034
1035/// HandleEndifDirective - Implements the #endif directive.
1036///
1037void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1038 ++NumEndif;
1039
1040 // Check that this is the whole directive.
1041 CheckEndOfDirective("#endif");
1042
1043 PPConditionalInfo CondInfo;
1044 if (CurLexer->popConditionalLevel(CondInfo)) {
1045 // No conditionals on the stack: this is an #endif without an #if.
1046 return Diag(EndifToken, diag::err_pp_endif_without_if);
1047 }
1048
1049 // If this the end of a top-level #endif, inform MIOpt.
1050 if (CurLexer->getConditionalStackDepth() == 0)
1051 CurLexer->MIOpt.ExitTopLevelConditional();
1052
1053 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
1054 "This code should only be reachable in the non-skipping case!");
1055}
1056
1057
1058void Preprocessor::HandleElseDirective(Token &Result) {
1059 ++NumElse;
1060
1061 // #else directive in a non-skipping conditional... start skipping.
1062 CheckEndOfDirective("#else");
1063
1064 PPConditionalInfo CI;
1065 if (CurLexer->popConditionalLevel(CI))
1066 return Diag(Result, diag::pp_err_else_without_if);
1067
1068 // If this is a top-level #else, inform the MIOpt.
1069 if (CurLexer->getConditionalStackDepth() == 0)
1070 CurLexer->MIOpt.EnterTopLevelConditional();
1071
1072 // If this is a #else with a #else before it, report the error.
1073 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1074
1075 // Finally, skip the rest of the contents of this block and return the first
1076 // token after it.
1077 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1078 /*FoundElse*/true);
1079}
1080
1081void Preprocessor::HandleElifDirective(Token &ElifToken) {
1082 ++NumElse;
1083
1084 // #elif directive in a non-skipping conditional... start skipping.
1085 // We don't care what the condition is, because we will always skip it (since
1086 // the block immediately before it was included).
1087 DiscardUntilEndOfDirective();
1088
1089 PPConditionalInfo CI;
1090 if (CurLexer->popConditionalLevel(CI))
1091 return Diag(ElifToken, diag::pp_err_elif_without_if);
1092
1093 // If this is a top-level #elif, inform the MIOpt.
1094 if (CurLexer->getConditionalStackDepth() == 0)
1095 CurLexer->MIOpt.EnterTopLevelConditional();
1096
1097 // If this is a #elif with a #else before it, report the error.
1098 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1099
1100 // Finally, skip the rest of the contents of this block and return the first
1101 // token after it.
1102 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1103 /*FoundElse*/CI.FoundElse);
1104}
1105