blob: 589eec3fcce74f0b81ea93a3a6cdade924c47c04 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15//
16// ERROR : __VA_ARGS__ can only appear in the expansion of a C99 variadic macro
17//
18// Options to support:
19// -H - Print the name of each header file used.
20// -C -CC - Do not discard comments for cpp.
21// -P - Do not emit #line directives.
22// -d[MDNI] - Dump various things.
23// -fworking-directory - #line's with preprocessor's working dir.
24// -fpreprocessed
25// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
26// -W*
27// -w
28//
29// Messages to emit:
30// "Multiple include guards may be useful for:\n"
31//
32// TODO: Implement the include guard optimization.
33//
34//===----------------------------------------------------------------------===//
35
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Basic/Diagnostic.h"
39#include "clang/Basic/FileManager.h"
40#include "clang/Basic/SourceManager.h"
41#include <iostream>
42using namespace llvm;
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46
47Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
48 FileManager &FM, SourceManager &SM)
49 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
50 SystemDirIdx(0), NoCurDirSearch(false),
51 CurLexer(0), CurNextDirLookup(0), CurMacroExpander(0) {
52 // Clear stats.
53 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
54 NumIf = NumElse = NumEndif = 0;
55 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
56 MaxIncludeStackDepth = MaxMacroStackDepth = 0;
57 NumSkipped = 0;
58
59 // Macro expansion is enabled.
60 DisableMacroExpansion = false;
61 SkippingContents = false;
62}
63
64Preprocessor::~Preprocessor() {
65 // Free any active lexers.
66 delete CurLexer;
67
68 while (!IncludeStack.empty()) {
69 delete IncludeStack.back().TheLexer;
70 IncludeStack.pop_back();
71 }
72}
73
74/// getFileInfo - Return the PerFileInfo structure for the specified
75/// FileEntry.
76Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
77 if (FE->getUID() >= FileInfo.size())
78 FileInfo.resize(FE->getUID()+1);
79 return FileInfo[FE->getUID()];
80}
81
82
83/// AddKeywords - Add all keywords to the symbol table.
84///
85void Preprocessor::AddKeywords() {
86 enum {
87 C90Shift = 0,
88 EXTC90 = 1 << C90Shift,
89 NOTC90 = 2 << C90Shift,
90 C99Shift = 2,
91 EXTC99 = 1 << C99Shift,
92 NOTC99 = 2 << C99Shift,
93 CPPShift = 4,
94 EXTCPP = 1 << CPPShift,
95 NOTCPP = 2 << CPPShift,
96 Mask = 3
97 };
98
99 // Add keywords and tokens for the current language.
100#define KEYWORD(NAME, FLAGS) \
101 AddKeyword(#NAME+1, tok::kw##NAME, \
102 (FLAGS >> C90Shift) & Mask, \
103 (FLAGS >> C99Shift) & Mask, \
104 (FLAGS >> CPPShift) & Mask);
105#define ALIAS(NAME, TOK) \
106 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
107#include "clang/Basic/TokenKinds.def"
108}
109
110/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
111/// the specified LexerToken's location, translating the token's start
112/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000113void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000114 const std::string &Msg) {
115 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
116 // warnings or extensions.
117 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000118 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000119
Chris Lattnercb283342006-06-18 06:48:37 +0000120 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000121}
Chris Lattnercb283342006-06-18 06:48:37 +0000122void Preprocessor::Diag(const LexerToken &Tok, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000123 const std::string &Msg) {
124 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
125 // warnings or extensions.
126 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000127 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000128
Chris Lattnercb283342006-06-18 06:48:37 +0000129 Diag(Tok.getSourceLocation(), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000130}
131
132void Preprocessor::PrintStats() {
133 std::cerr << "\n*** Preprocessor Stats:\n";
134 std::cerr << FileInfo.size() << " files tracked.\n";
135 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
136 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
137 NumOnceOnlyFiles += FileInfo[i].isImport;
138 if (MaxNumIncludes < FileInfo[i].NumIncludes)
139 MaxNumIncludes = FileInfo[i].NumIncludes;
140 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
141 }
142 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
143 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
144 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
145
146 std::cerr << NumDirectives << " directives found:\n";
147 std::cerr << " " << NumDefined << " #define.\n";
148 std::cerr << " " << NumUndefined << " #undef.\n";
149 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
150 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
151 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
152 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
153 std::cerr << " " << NumElse << " #else/#elif.\n";
154 std::cerr << " " << NumEndif << " #endif.\n";
155 std::cerr << " " << NumPragma << " #pragma.\n";
156 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
157
158 std::cerr << NumMacroExpanded << " macros expanded, "
159 << NumFastMacroExpanded << " on the fast path.\n";
160 if (MaxMacroStackDepth > 1)
161 std::cerr << " " << MaxMacroStackDepth << " max macroexpand stack depth\n";
162}
163
164//===----------------------------------------------------------------------===//
165// Source File Location Methods.
166//===----------------------------------------------------------------------===//
167
168
169/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
170/// return null on failure. isAngled indicates whether the file reference is
171/// for system #include's or not (i.e. using <> instead of "").
172const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
173 bool isSystem,
174 const DirectoryLookup *FromDir,
175 const DirectoryLookup *&NextDir) {
176 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
177 NextDir = 0;
178
179 // If 'Filename' is absolute, check to see if it exists and no searching.
180 // FIXME: this should be a sys::Path interface, this doesn't handle things
181 // like C:\foo.txt right, nor win32 \\network\device\blah.
182 if (Filename[0] == '/') {
183 // If this was an #include_next "/absolute/file", fail.
184 if (FromDir) return 0;
185
186 // Otherwise, just return the file.
187 return FileMgr.getFile(Filename);
188 }
189
190 // Step #0, unless disabled, check to see if the file is in the #includer's
191 // directory. This search is not done for <> headers.
192 if (!isSystem && !FromDir && !NoCurDirSearch) {
193 const FileEntry *CurFE =
194 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
195 if (CurFE) {
196 if (const FileEntry *FE =
197 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
198 if (CurNextDirLookup)
199 NextDir = CurNextDirLookup;
200 else
201 NextDir = &SearchDirs[0];
202 return FE;
203 }
204 }
205 }
206
207 // If this is a system #include, ignore the user #include locs.
208 unsigned i = isSystem ? SystemDirIdx : 0;
209
210 // If this is a #include_next request, start searching after the directory the
211 // file was found in.
212 if (FromDir)
213 i = FromDir-&SearchDirs[0];
214
215 // Check each directory in sequence to see if it contains this file.
216 for (; i != SearchDirs.size(); ++i) {
217 // Concatenate the requested file onto the directory.
218 // FIXME: should be in sys::Path.
219 if (const FileEntry *FE =
220 FileMgr.getFile(SearchDirs[i].getDir()->getName()+"/"+Filename)) {
221 NextDir = &SearchDirs[i+1];
222 return FE;
223 }
224 }
225
226 // Otherwise, didn't find it.
227 return 0;
228}
229
230/// EnterSourceFile - Add a source file to the top of the include stack and
231/// start lexing tokens from it instead of the current buffer. Return true
232/// on failure.
233void Preprocessor::EnterSourceFile(unsigned FileID,
234 const DirectoryLookup *NextDir) {
235 ++NumEnteredSourceFiles;
236
237 // Add the current lexer to the include stack.
238 if (CurLexer) {
239 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurNextDirLookup));
240 } else {
241 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
242 }
243
244 if (MaxIncludeStackDepth < IncludeStack.size())
245 MaxIncludeStackDepth = IncludeStack.size();
246
247 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
248
249 CurLexer = new Lexer(Buffer, FileID, *this);
250 CurNextDirLookup = NextDir;
251}
252
253/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000254/// tokens from it instead of the current buffer.
255void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000256 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
257 MacroInfo &MI = *Identifier->getMacroInfo();
258 SourceLocation ExpandLoc = Tok.getSourceLocation();
259 unsigned MacroID = SourceMgr.getMacroID(Identifier, ExpandLoc);
260 if (CurLexer) {
261 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurNextDirLookup));
262 CurLexer = 0;
263 CurNextDirLookup = 0;
264 } else if (CurMacroExpander) {
265 MacroStack.push_back(CurMacroExpander);
266 }
267
268 if (MaxMacroStackDepth < MacroStack.size())
269 MaxMacroStackDepth = MacroStack.size();
270
271 // TODO: Figure out arguments.
272
273 // Mark the macro as currently disabled, so that it is not recursively
274 // expanded.
275 MI.DisableMacro();
276
277 CurMacroExpander = new MacroExpander(MI, MacroID, *this,
278 Tok.isAtStartOfLine(),
279 Tok.hasLeadingSpace());
Chris Lattner22eb9722006-06-18 05:43:12 +0000280}
281
282
283//===----------------------------------------------------------------------===//
284// Lexer Event Handling.
285//===----------------------------------------------------------------------===//
286
287/// HandleIdentifier - This callback is invoked when the lexer reads an
288/// identifier. This callback looks up the identifier in the map and/or
289/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnercb283342006-06-18 06:48:37 +0000290void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000291 if (Identifier.getIdentifierInfo() == 0) {
292 // If we are skipping tokens (because we are in a #if 0 block), there will
293 // be no identifier info, just return the token.
294 assert(isSkipping() && "Token isn't an identifier?");
Chris Lattnercb283342006-06-18 06:48:37 +0000295 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000296 }
297 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
298
299 // FIXME: Check for poisoning in ITI?
300
301 if (MacroInfo *MI = ITI.getMacroInfo()) {
302 if (MI->isEnabled() && !DisableMacroExpansion) {
303 ++NumMacroExpanded;
304 // If we started lexing a macro, enter the macro expansion body.
305 // FIXME: Read/Validate the argument list here!
306
307 // If this macro expands to no tokens, don't bother to push it onto the
308 // expansion stack, only to take it right back off.
309 if (MI->getNumTokens() == 0) {
310 // Ignore this macro use, just return the next token in the current
311 // buffer.
312 bool HadLeadingSpace = Identifier.hasLeadingSpace();
313 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
314
Chris Lattnercb283342006-06-18 06:48:37 +0000315 Lex(Identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000316
317 // If the identifier isn't on some OTHER line, inherit the leading
318 // whitespace/first-on-a-line property of this token. This handles
319 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
320 // empty.
321 if (!Identifier.isAtStartOfLine()) {
322 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
323 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
324 }
325 ++NumFastMacroExpanded;
Chris Lattnercb283342006-06-18 06:48:37 +0000326 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000327
328 } else if (MI->getNumTokens() == 1 &&
329 // Don't handle identifiers, which might need recursive
330 // expansion.
331 MI->getReplacementToken(0).getIdentifierInfo() == 0) {
332 // FIXME: Function-style macros only if no arguments?
333
334 // Otherwise, if this macro expands into a single trivially-expanded
335 // token: expand it now. This handles common cases like
336 // "#define VAL 42".
337
338 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
339 // identifier to the expanded token.
340 bool isAtStartOfLine = Identifier.isAtStartOfLine();
341 bool hasLeadingSpace = Identifier.hasLeadingSpace();
342
343 // Replace the result token.
344 Identifier = MI->getReplacementToken(0);
345
346 // Restore the StartOfLine/LeadingSpace markers.
347 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
348 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
349
350 // FIXME: Get correct macro expansion stack location info!
351
352 // Since this is not an identifier token, it can't be macro expanded, so
353 // we're done.
354 ++NumFastMacroExpanded;
Chris Lattnercb283342006-06-18 06:48:37 +0000355 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000356 }
357
358 // Start expanding the macro (FIXME, pass arguments).
Chris Lattnercb283342006-06-18 06:48:37 +0000359 EnterMacro(Identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000360
361 // Now that the macro is at the top of the include stack, ask the
362 // preprocessor to read the next token from it.
363 return Lex(Identifier);
364 }
365 }
366
367 // Change the kind of this identifier to the appropriate token kind, e.g.
368 // turning "for" into a keyword.
369 Identifier.SetKind(ITI.getTokenID());
370
371 // If this is an extension token, diagnose its use.
Chris Lattnercb283342006-06-18 06:48:37 +0000372 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner22eb9722006-06-18 05:43:12 +0000373}
374
375/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
376/// the current file. This either returns the EOF token or pops a level off
377/// the include stack and keeps going.
Chris Lattnercb283342006-06-18 06:48:37 +0000378void Preprocessor::HandleEndOfFile(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000379 assert(!CurMacroExpander &&
380 "Ending a file when currently in a macro!");
381
382 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
383 // this is an error condition. Just return the EOF token up to
384 // SkipExcludedConditionalBlock. The Lexer will have already have issued
385 // errors for the unterminated #if's on the conditional stack.
386 if (isSkipping()) {
387 Result.StartToken(CurLexer);
388 Result.SetKind(tok::eof);
389 Result.SetStart(CurLexer->BufferEnd);
390 Result.SetEnd(CurLexer->BufferEnd);
Chris Lattnercb283342006-06-18 06:48:37 +0000391 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000392 }
393
394 // If this is a #include'd file, pop it off the include stack and continue
395 // lexing the #includer file.
396 if (!IncludeStack.empty()) {
397 // We're done with the #included file.
398 delete CurLexer;
399 CurLexer = IncludeStack.back().TheLexer;
400 CurNextDirLookup = IncludeStack.back().TheDirLookup;
401 IncludeStack.pop_back();
402 return Lex(Result);
403 }
404
405 Result.StartToken(CurLexer);
406 Result.SetKind(tok::eof);
407 Result.SetStart(CurLexer->BufferEnd);
408 Result.SetEnd(CurLexer->BufferEnd);
409
410 // We're done with the #included file.
411 delete CurLexer;
412 CurLexer = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000413}
414
415/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000416/// the current macro line.
417void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000418 assert(CurMacroExpander && !CurLexer &&
419 "Ending a macro when currently in a #include file!");
420
421 // Mark macro not ignored now that it is no longer being expanded.
422 CurMacroExpander->getMacro().EnableMacro();
423 delete CurMacroExpander;
424
425 if (!MacroStack.empty()) {
426 // In a nested macro invocation, continue lexing from the macro.
427 CurMacroExpander = MacroStack.back();
428 MacroStack.pop_back();
429 return Lex(Result);
430 } else {
431 CurMacroExpander = 0;
432 // Handle this like a #include file being popped off the stack.
433 return HandleEndOfFile(Result);
434 }
435}
436
437
438//===----------------------------------------------------------------------===//
439// Utility Methods for Preprocessor Directive Handling.
440//===----------------------------------------------------------------------===//
441
442/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
443/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000444void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000445 LexerToken Tmp;
446 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000447 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000448 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000449}
450
451/// ReadMacroName - Lex and validate a macro name, which occurs after a
452/// #define or #undef. This sets the token kind to eom and discards the rest
453/// of the macro line if the macro name is invalid.
Chris Lattnercb283342006-06-18 06:48:37 +0000454void Preprocessor::ReadMacroName(LexerToken &MacroNameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000455 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000456 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000457
458 // Missing macro name?
459 if (MacroNameTok.getKind() == tok::eom)
460 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
461
462 if (MacroNameTok.getIdentifierInfo() == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000463 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000464 // Fall through on error.
465 } else if (0) {
466 // FIXME: Error if defining a C++ named operator.
467
468 } else if (0) {
469 // FIXME: Error if defining "defined", "__DATE__", and other predef macros
470 // in C99 6.10.8.4.
471 } else {
472 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000473 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000474 }
475
476
477 // Invalid macro name, read and discard the rest of the line. Then set the
478 // token kind to tok::eom.
479 MacroNameTok.SetKind(tok::eom);
480 return DiscardUntilEndOfDirective();
481}
482
483/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
484/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000485void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000486 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000487 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000488 // There should be no tokens after the directive, but we allow them as an
489 // extension.
490 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000491 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
492 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000493 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000494}
495
496
497
498/// SkipExcludedConditionalBlock - We just read a #if or related directive and
499/// decided that the subsequent tokens are in the #if'd out portion of the
500/// file. Lex the rest of the file, until we see an #endif. If
501/// FoundNonSkipPortion is true, then we have already emitted code for part of
502/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
503/// is true, then #else directives are ok, if not, then we have already seen one
504/// so a #else directive is a duplicate. When this returns, the caller can lex
505/// the first valid token.
Chris Lattnercb283342006-06-18 06:48:37 +0000506void Preprocessor::SkipExcludedConditionalBlock(const char *IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000507 bool FoundNonSkipPortion,
508 bool FoundElse) {
509 ++NumSkipped;
510 assert(MacroStack.empty() && CurMacroExpander == 0 && CurLexer &&
511 "Lexing a macro, not a file?");
512
513 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
514 FoundNonSkipPortion, FoundElse);
515
516 // Know that we are going to be skipping tokens. Set this flag to indicate
517 // this, which has a couple of effects:
518 // 1. If EOF of the current lexer is found, the include stack isn't popped.
519 // 2. Identifier information is not looked up for identifier tokens. As an
520 // effect of this, implicit macro expansion is naturally disabled.
521 // 3. "#" tokens at the start of a line are treated as normal tokens, not
522 // implicitly transformed by the lexer.
523 // 4. All notes, warnings, and extension messages are disabled.
524 //
525 SkippingContents = true;
526 LexerToken Tok;
527 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000528 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000529
530 // If this is the end of the buffer, we have an error. The lexer will have
531 // already handled this error condition, so just return and let the caller
532 // lex after this #include.
533 if (Tok.getKind() == tok::eof) break;
534
535 // If this token is not a preprocessor directive, just skip it.
536 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
537 continue;
538
539 // We just parsed a # character at the start of a line, so we're in
540 // directive mode. Tell the lexer this so any newlines we see will be
541 // converted into an EOM token (this terminates the macro).
542 CurLexer->ParsingPreprocessorDirective = true;
543
544 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000545 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000546
547 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
548 // something bogus), skip it.
549 if (Tok.getKind() != tok::identifier) {
550 CurLexer->ParsingPreprocessorDirective = false;
551 continue;
552 }
553
554 // If the first letter isn't i or e, it isn't intesting to us. We know that
555 // this is safe in the face of spelling differences, because there is no way
556 // to spell an i/e in a strange way that is another letter. Skipping this
557 // allows us to avoid computing the spelling for #define/#undef and other
558 // common directives.
559 char FirstChar = Tok.getStart()[0];
560 if (FirstChar >= 'a' && FirstChar <= 'z' &&
561 FirstChar != 'i' && FirstChar != 'e') {
562 CurLexer->ParsingPreprocessorDirective = false;
563 continue;
564 }
565
566 // Strip out trigraphs and embedded newlines.
567 std::string Directive = Lexer::getSpelling(Tok, Features);
568 FirstChar = Directive[0];
569 if (FirstChar == 'i' && Directive[1] == 'f') {
570 if (Directive == "if" || Directive == "ifdef" || Directive == "ifndef") {
571 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
572 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000573 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000574 CurLexer->pushConditionalLevel(Tok.getStart(), /*wasskipping*/true,
575 /*foundnonskip*/false,/*fnddelse*/false);
576 }
577 } else if (FirstChar == 'e') {
578 if (Directive == "endif") {
Chris Lattnercb283342006-06-18 06:48:37 +0000579 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000580 PPConditionalInfo CondInfo;
581 CondInfo.WasSkipping = true; // Silence bogus warning.
582 bool InCond = CurLexer->popConditionalLevel(CondInfo);
583 assert(!InCond && "Can't be skipping if not in a conditional!");
584
585 // If we popped the outermost skipping block, we're done skipping!
586 if (!CondInfo.WasSkipping)
587 break;
588 } else if (Directive == "else") {
589 // #else directive in a skipping conditional. If not in some other
590 // skipping conditional, and if #else hasn't already been seen, enter it
591 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000592 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000593 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
594
595 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000596 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000597
598 // Note that we've seen a #else in this conditional.
599 CondInfo.FoundElse = true;
600
601 // If the conditional is at the top level, and the #if block wasn't
602 // entered, enter the #else block now.
603 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
604 CondInfo.FoundNonSkip = true;
605 break;
606 }
607 } else if (Directive == "elif") {
608 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
609
610 bool ShouldEnter;
611 // If this is in a skipping block or if we're already handled this #if
612 // block, don't bother parsing the condition.
613 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +0000614 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000615 ShouldEnter = false;
616 } else {
617 // Evaluate the #elif condition!
618 const char *Start = CurLexer->BufferPtr;
619
620 // Restore the value of SkippingContents so that identifiers are
621 // looked up, etc, inside the #elif expression.
622 assert(SkippingContents && "We have to be skipping here!");
623 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +0000624 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +0000625 SkippingContents = true;
626 }
627
628 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000629 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000630
631 // If this condition is true, enter it!
632 if (ShouldEnter) {
633 CondInfo.FoundNonSkip = true;
634 break;
635 }
636 }
637 }
638
639 CurLexer->ParsingPreprocessorDirective = false;
640 }
641
642 // Finally, if we are out of the conditional (saw an #endif or ran off the end
643 // of the file, just stop skipping and return to lexing whatever came after
644 // the #if block.
645 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000646}
647
648//===----------------------------------------------------------------------===//
649// Preprocessor Directive Handling.
650//===----------------------------------------------------------------------===//
651
652/// HandleDirective - This callback is invoked when the lexer sees a # token
653/// at the start of a line. This consumes the directive, modifies the
654/// lexer/preprocessor state, and advances the lexer(s) so that the next token
655/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +0000656void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000657 // FIXME: TRADITIONAL: # with whitespace before it not recognized by K&R?
658
659 // We just parsed a # character at the start of a line, so we're in directive
660 // mode. Tell the lexer this so any newlines we see will be converted into an
661 // EOM token (this terminates the macro).
662 CurLexer->ParsingPreprocessorDirective = true;
663
664 ++NumDirectives;
665
666 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000667 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000668
669 switch (Result.getKind()) {
670 default: break;
671 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +0000672 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +0000673
674#if 0
675 case tok::numeric_constant:
676 // FIXME: implement # 7 line numbers!
677 break;
678#endif
679 case tok::kw_else:
680 return HandleElseDirective(Result);
681 case tok::kw_if:
682 return HandleIfDirective(Result);
683 case tok::identifier:
684 // Strip out trigraphs and embedded newlines.
685 std::string Directive = Lexer::getSpelling(Result, Features);
686 bool isExtension = false;
687 switch (Directive.size()) {
688 case 4:
689 if (Directive == "line")
690 ;
691 if (Directive == "elif")
692 return HandleElifDirective(Result);
693 if (Directive == "sccs") {
694 isExtension = true;
695 // SCCS is the same as #ident.
696 }
697 break;
698 case 5:
699 if (Directive == "endif")
700 return HandleEndifDirective(Result);
701 if (Directive == "ifdef")
702 return HandleIfdefDirective(Result, false);
703 if (Directive == "undef")
704 return HandleUndefDirective(Result);
705 if (Directive == "error")
706 return HandleUserDiagnosticDirective(Result, false);
707 if (Directive == "ident")
708 isExtension = true;
709 break;
710 case 6:
711 if (Directive == "define")
712 return HandleDefineDirective(Result);
713 if (Directive == "ifndef")
714 return HandleIfdefDirective(Result, true);
715 if (Directive == "import")
716 return HandleImportDirective(Result);
717 if (Directive == "pragma") {
718 // FIXME: implement #pragma
719 ++NumPragma;
720#if 1
721 // Read the rest of the PP line.
722 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000723 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000724 } while (Result.getKind() != tok::eom);
725
Chris Lattnercb283342006-06-18 06:48:37 +0000726 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000727#endif
728 } else if (Directive == "assert") {
729 isExtension = true;
730 }
731 break;
732 case 7:
733 if (Directive == "include") // Handle #include.
734 return HandleIncludeDirective(Result);
Chris Lattnercb283342006-06-18 06:48:37 +0000735 if (Directive == "warning") {
736 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +0000737 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +0000738 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000739 break;
740 case 8:
741 if (Directive == "unassert") {
742 isExtension = true;
743 }
744 break;
745 case 12:
746 if (Directive == "include_next") // Handle #include_next.
747 return HandleIncludeNextDirective(Result);
748 break;
749 }
750 break;
751 }
752
753 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +0000754 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +0000755
756 // Read the rest of the PP line.
757 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000758 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000759 } while (Result.getKind() != tok::eom);
760
761 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +0000762}
763
Chris Lattnercb283342006-06-18 06:48:37 +0000764void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +0000765 bool isWarning) {
766 // Read the rest of the line raw. We do this because we don't want macros
767 // to be expanded and we don't require that the tokens be valid preprocessing
768 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
769 // collapse multiple consequtive white space between tokens, but this isn't
770 // specified by the standard.
771 std::string Message = CurLexer->ReadToEndOfLine();
772
773 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
774 return Diag(Result, DiagID, Message);
775}
776
777/// HandleIncludeDirective - The "#include" tokens have just been read, read the
778/// file to be included from the lexer, then include it! This is a common
779/// routine with functionality shared between #include, #include_next and
780/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +0000781void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +0000782 const DirectoryLookup *LookupFrom,
783 bool isImport) {
784 ++NumIncluded;
785 LexerToken FilenameTok;
Chris Lattnercb283342006-06-18 06:48:37 +0000786 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000787
788 // If the token kind is EOM, the error has already been diagnosed.
789 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +0000790 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000791
792 // Check that we don't have infinite #include recursion.
793 if (IncludeStack.size() == MaxAllowedIncludeStackDepth-1)
794 return Diag(FilenameTok, diag::err_pp_include_too_deep);
795
796 // Get the text form of the filename.
797 std::string Filename = CurLexer->getSpelling(FilenameTok);
798 assert(!Filename.empty() && "Can't have tokens with empty spellings!");
799
800 // Make sure the filename is <x> or "x".
801 bool isAngled;
802 if (Filename[0] == '<') {
803 isAngled = true;
804 if (Filename[Filename.size()-1] != '>')
805 return Diag(FilenameTok, diag::err_pp_expects_filename);
806 } else if (Filename[0] == '"') {
807 isAngled = false;
808 if (Filename[Filename.size()-1] != '"')
809 return Diag(FilenameTok, diag::err_pp_expects_filename);
810 } else {
811 return Diag(FilenameTok, diag::err_pp_expects_filename);
812 }
813
814 // Remove the quotes.
815 Filename = std::string(Filename.begin()+1, Filename.end()-1);
816
817 // Diagnose #include "" as invalid.
818 if (Filename.empty())
819 return Diag(FilenameTok, diag::err_pp_empty_filename);
820
821 // Search include directories.
822 const DirectoryLookup *NextDir;
823 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, NextDir);
824 if (File == 0)
825 return Diag(FilenameTok, diag::err_pp_file_not_found);
826
827 // Get information about this file.
828 PerFileInfo &FileInfo = getFileInfo(File);
829
830 // If this is a #import directive, check that we have not already imported
831 // this header.
832 if (isImport) {
833 // If this has already been imported, don't import it again.
834 FileInfo.isImport = true;
835
836 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +0000837 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000838 } else {
839 // Otherwise, if this is a #include of a file that was previously #import'd
840 // or if this is the second #include of a #pragma once file, ignore it.
841 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +0000842 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000843 }
844
845 // Look up the file, create a File ID for it.
846 unsigned FileID =
847 SourceMgr.createFileID(File, FilenameTok.getSourceLocation());
848 if (FileID == 0)
849 return Diag(FilenameTok, diag::err_pp_file_not_found);
850
851 // Finally, if all is good, enter the new file!
852 EnterSourceFile(FileID, NextDir);
853
854 // Increment the number of times this file has been included.
855 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +0000856}
857
858/// HandleIncludeNextDirective - Implements #include_next.
859///
Chris Lattnercb283342006-06-18 06:48:37 +0000860void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
861 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +0000862
863 // #include_next is like #include, except that we start searching after
864 // the current found directory. If we can't do this, issue a
865 // diagnostic.
866 const DirectoryLookup *Lookup = CurNextDirLookup;
867 if (IncludeStack.empty()) {
868 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +0000869 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +0000870 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000871 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattner22eb9722006-06-18 05:43:12 +0000872 }
873
874 return HandleIncludeDirective(IncludeNextTok, Lookup);
875}
876
877/// HandleImportDirective - Implements #import.
878///
Chris Lattnercb283342006-06-18 06:48:37 +0000879void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
880 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +0000881
882 return HandleIncludeDirective(ImportTok, 0, true);
883}
884
885/// HandleDefineDirective - Implements #define. This consumes the entire macro
886/// line then lets the caller lex the next real token.
887///
Chris Lattnercb283342006-06-18 06:48:37 +0000888void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000889 ++NumDefined;
890 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +0000891 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000892
893 // Error reading macro name? If so, diagnostic already issued.
894 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +0000895 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000896
897 MacroInfo *MI = new MacroInfo(MacroNameTok.getSourceLocation());
898
899 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +0000900 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000901
902 if (Tok.getKind() == tok::eom) {
903 // If there is no body to this macro, we have no special handling here.
904 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
905 // This is a function-like macro definition.
906 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000907 return DiscardUntilEndOfDirective();
908
909 } else if (!Tok.hasLeadingSpace()) {
910 // C99 requires whitespace between the macro definition and the body. Emit
911 // a diagnostic for something like "#define X+".
912 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +0000913 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +0000914 } else {
915 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
916 // one in some cases!
917 }
918 } else {
919 // This is a normal token with leading space. Clear the leading space
920 // marker on the first token to get proper expansion.
921 Tok.ClearFlag(LexerToken::LeadingSpace);
922 }
923
924 // Read the rest of the macro body.
925 while (Tok.getKind() != tok::eom) {
926 MI->AddTokenToBody(Tok);
927
928 // FIXME: See create_iso_definition.
929
930 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +0000931 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000932 }
933
934 // Finally, if this identifier already had a macro defined for it, verify that
935 // the macro bodies are identical and free the old definition.
936 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
937 // FIXME: Verify the definition is the same.
938 // Macros must be identical. This means all tokes and whitespace separation
939 // must be the same.
940 delete OtherMI;
941 }
942
943 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +0000944}
945
946
947/// HandleUndefDirective - Implements #undef.
948///
Chris Lattnercb283342006-06-18 06:48:37 +0000949void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000950 ++NumUndefined;
951 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +0000952 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000953
954 // Error reading macro name? If so, diagnostic already issued.
955 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +0000956 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000957
958 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +0000959 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +0000960
961 // Okay, we finally have a valid identifier to undef.
962 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
963
964 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +0000965 if (MI == 0) return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000966
967#if 0 // FIXME: implement warn_unused_macros.
968 if (CPP_OPTION (pfile, warn_unused_macros))
969 _cpp_warn_if_unused_macro (pfile, node, NULL);
970#endif
971
972 // Free macro definition.
973 delete MI;
974 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +0000975}
976
977
978/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
979/// true when this is a #ifndef directive.
980///
Chris Lattnercb283342006-06-18 06:48:37 +0000981void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000982 ++NumIf;
983 LexerToken DirectiveTok = Result;
984
985 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +0000986 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000987
988 // Error reading macro name? If so, diagnostic already issued.
989 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +0000990 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000991
992 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +0000993 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +0000994
995 // Should we include the stuff contained by this directive?
996 if (!MacroNameTok.getIdentifierInfo()->getMacroInfo() == isIfndef) {
997 // Yes, remember that we are inside a conditional, then lex the next token.
998 CurLexer->pushConditionalLevel(DirectiveTok.getStart(), /*wasskip*/false,
999 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001000 } else {
1001 // No, skip the contents of this block and return the first token after it.
Chris Lattnercb283342006-06-18 06:48:37 +00001002 SkipExcludedConditionalBlock(DirectiveTok.getStart(),
1003 /*Foundnonskip*/false,
1004 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001005 }
1006}
1007
1008/// HandleIfDirective - Implements the #if directive.
1009///
Chris Lattnercb283342006-06-18 06:48:37 +00001010void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001011 ++NumIf;
1012 const char *Start = CurLexer->BufferPtr;
1013
Chris Lattner7966aaf2006-06-18 06:50:36 +00001014 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001015
1016 // Should we include the stuff contained by this directive?
1017 if (ConditionalTrue) {
1018 // Yes, remember that we are inside a conditional, then lex the next token.
1019 CurLexer->pushConditionalLevel(IfToken.getStart(), /*wasskip*/false,
1020 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 } else {
1022 // No, skip the contents of this block and return the first token after it.
Chris Lattnercb283342006-06-18 06:48:37 +00001023 SkipExcludedConditionalBlock(IfToken.getStart(),
1024 /*Foundnonskip*/false,
1025 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001026 }
1027}
1028
1029/// HandleEndifDirective - Implements the #endif directive.
1030///
Chris Lattnercb283342006-06-18 06:48:37 +00001031void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001032 ++NumEndif;
1033 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001034 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001035
1036 PPConditionalInfo CondInfo;
1037 if (CurLexer->popConditionalLevel(CondInfo)) {
1038 // No conditionals on the stack: this is an #endif without an #if.
1039 return Diag(EndifToken, diag::err_pp_endif_without_if);
1040 }
1041
1042 assert(!CondInfo.WasSkipping && !isSkipping() &&
1043 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001044}
1045
1046
Chris Lattnercb283342006-06-18 06:48:37 +00001047void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001048 ++NumElse;
1049 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001050 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001051
1052 PPConditionalInfo CI;
1053 if (CurLexer->popConditionalLevel(CI))
1054 return Diag(Result, diag::pp_err_else_without_if);
1055
1056 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001057 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001058
1059 // Finally, skip the rest of the contents of this block and return the first
1060 // token after it.
1061 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1062 /*FoundElse*/true);
1063}
1064
Chris Lattnercb283342006-06-18 06:48:37 +00001065void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 ++NumElse;
1067 // #elif directive in a non-skipping conditional... start skipping.
1068 // We don't care what the condition is, because we will always skip it (since
1069 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001070 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001071
1072 PPConditionalInfo CI;
1073 if (CurLexer->popConditionalLevel(CI))
1074 return Diag(ElifToken, diag::pp_err_elif_without_if);
1075
1076 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001077 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001078
1079 // Finally, skip the rest of the contents of this block and return the first
1080 // token after it.
1081 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1082 /*FoundElse*/CI.FoundElse);
1083}