blob: 281b2b8aab6c057987bb38736c8497b5bd4493ce [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.
Chris Lattner22eb9722006-06-18 05:43:12 +000021// -d[MDNI] - Dump various things.
22// -fworking-directory - #line's with preprocessor's working dir.
23// -fpreprocessed
24// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
25// -W*
26// -w
27//
28// Messages to emit:
29// "Multiple include guards may be useful for:\n"
30//
31// TODO: Implement the include guard optimization.
32//
33//===----------------------------------------------------------------------===//
34
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000037#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000038#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Basic/Diagnostic.h"
40#include "clang/Basic/FileManager.h"
41#include "clang/Basic/SourceManager.h"
42#include <iostream>
43using namespace llvm;
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47
48Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
49 FileManager &FM, SourceManager &SM)
50 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
51 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000052 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000053 ScratchBuf = new ScratchBuffer(SourceMgr);
54
Chris Lattner22eb9722006-06-18 05:43:12 +000055 // Clear stats.
56 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
57 NumIf = NumElse = NumEndif = 0;
58 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000059 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
Chris Lattner22eb9722006-06-18 05:43:12 +000062 // Macro expansion is enabled.
63 DisableMacroExpansion = false;
64 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000065
66 // There is no file-change handler yet.
67 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000068 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000069
70 // Initialize the pragma handlers.
71 PragmaHandlers = new PragmaNamespace(0);
72 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000073
74 // Initialize builtin macros like __LINE__ and friends.
75 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000076}
77
78Preprocessor::~Preprocessor() {
79 // Free any active lexers.
80 delete CurLexer;
81
Chris Lattner69772b02006-07-02 20:34:39 +000082 while (!IncludeMacroStack.empty()) {
83 delete IncludeMacroStack.back().TheLexer;
84 delete IncludeMacroStack.back().TheMacroExpander;
85 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000086 }
Chris Lattnerb8761832006-06-24 21:31:03 +000087
88 // Release pragma information.
89 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000090
91 // Delete the scratch buffer info.
92 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000093}
94
95/// getFileInfo - Return the PerFileInfo structure for the specified
96/// FileEntry.
97Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
98 if (FE->getUID() >= FileInfo.size())
99 FileInfo.resize(FE->getUID()+1);
100 return FileInfo[FE->getUID()];
101}
102
103
104/// AddKeywords - Add all keywords to the symbol table.
105///
106void Preprocessor::AddKeywords() {
107 enum {
108 C90Shift = 0,
109 EXTC90 = 1 << C90Shift,
110 NOTC90 = 2 << C90Shift,
111 C99Shift = 2,
112 EXTC99 = 1 << C99Shift,
113 NOTC99 = 2 << C99Shift,
114 CPPShift = 4,
115 EXTCPP = 1 << CPPShift,
116 NOTCPP = 2 << CPPShift,
117 Mask = 3
118 };
119
120 // Add keywords and tokens for the current language.
121#define KEYWORD(NAME, FLAGS) \
122 AddKeyword(#NAME+1, tok::kw##NAME, \
123 (FLAGS >> C90Shift) & Mask, \
124 (FLAGS >> C99Shift) & Mask, \
125 (FLAGS >> CPPShift) & Mask);
126#define ALIAS(NAME, TOK) \
127 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
128#include "clang/Basic/TokenKinds.def"
129}
130
131/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
132/// the specified LexerToken's location, translating the token's start
133/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000134void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000135 const std::string &Msg) {
136 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
137 // warnings or extensions.
138 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000139 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000140
Chris Lattnercb283342006-06-18 06:48:37 +0000141 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000142}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143
144void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
145 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
146 << getSpelling(Tok) << "'";
147
148 if (!DumpFlags) return;
149 std::cerr << "\t";
150 if (Tok.isAtStartOfLine())
151 std::cerr << " [StartOfLine]";
152 if (Tok.hasLeadingSpace())
153 std::cerr << " [LeadingSpace]";
154 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000155 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000156 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
157 << "']";
158 }
159}
160
161void Preprocessor::DumpMacro(const MacroInfo &MI) const {
162 std::cerr << "MACRO: ";
163 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
164 DumpToken(MI.getReplacementToken(i));
165 std::cerr << " ";
166 }
167 std::cerr << "\n";
168}
169
Chris Lattner22eb9722006-06-18 05:43:12 +0000170void Preprocessor::PrintStats() {
171 std::cerr << "\n*** Preprocessor Stats:\n";
172 std::cerr << FileInfo.size() << " files tracked.\n";
173 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
174 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
175 NumOnceOnlyFiles += FileInfo[i].isImport;
176 if (MaxNumIncludes < FileInfo[i].NumIncludes)
177 MaxNumIncludes = FileInfo[i].NumIncludes;
178 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
179 }
180 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
181 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
182 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
183
184 std::cerr << NumDirectives << " directives found:\n";
185 std::cerr << " " << NumDefined << " #define.\n";
186 std::cerr << " " << NumUndefined << " #undef.\n";
187 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000188 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
189 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000190 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
191 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
192 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
193 std::cerr << " " << NumElse << " #else/#elif.\n";
194 std::cerr << " " << NumEndif << " #endif.\n";
195 std::cerr << " " << NumPragma << " #pragma.\n";
196 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
197
198 std::cerr << NumMacroExpanded << " macros expanded, "
199 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000200}
201
202//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000203// Token Spelling
204//===----------------------------------------------------------------------===//
205
206
207/// getSpelling() - Return the 'spelling' of this token. The spelling of a
208/// token are the characters used to represent the token in the source file
209/// after trigraph expansion and escaped-newline folding. In particular, this
210/// wants to get the true, uncanonicalized, spelling of things like digraphs
211/// UCNs, etc.
212std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
213 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
214
215 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000216 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217 if (!Tok.needsCleaning())
218 return std::string(TokStart, TokStart+Tok.getLength());
219
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 std::string Result;
221 Result.reserve(Tok.getLength());
222
Chris Lattneref9eae12006-07-04 22:33:12 +0000223 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
225 Ptr != End; ) {
226 unsigned CharSize;
227 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
228 Ptr += CharSize;
229 }
230 assert(Result.size() != unsigned(Tok.getLength()) &&
231 "NeedsCleaning flag set on something that didn't need cleaning!");
232 return Result;
233}
234
235/// getSpelling - This method is used to get the spelling of a token into a
236/// preallocated buffer, instead of as an std::string. The caller is required
237/// to allocate enough space for the token, which is guaranteed to be at least
238/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000239///
240/// Note that this method may do two possible things: it may either fill in
241/// the buffer specified with characters, or it may *change the input pointer*
242/// to point to a constant buffer with the data already in it (avoiding a
243/// copy). The caller is not allowed to modify the returned buffer pointer
244/// if an internal buffer is returned.
245unsigned Preprocessor::getSpelling(const LexerToken &Tok,
246 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000247 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
248
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000249 // If this token is an identifier, just return the string from the identifier
250 // table, which is very quick.
251 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
252 Buffer = II->getName();
253 return Tok.getLength();
254 }
255
256 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000257 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000258
259 // If this token contains nothing interesting, return it directly.
260 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000261 Buffer = TokStart;
262 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000263 }
264 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000265 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000266 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
267 Ptr != End; ) {
268 unsigned CharSize;
269 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
270 Ptr += CharSize;
271 }
272 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
273 "NeedsCleaning flag set on something that didn't need cleaning!");
274
275 return OutBuf-Buffer;
276}
277
278//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000279// Source File Location Methods.
280//===----------------------------------------------------------------------===//
281
282
283/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
284/// return null on failure. isAngled indicates whether the file reference is
285/// for system #include's or not (i.e. using <> instead of "").
286const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000287 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000288 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000289 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000290 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000291 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000292
293 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000294 // FIXME: Portability. This should be a sys::Path interface, this doesn't
295 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000296 if (Filename[0] == '/') {
297 // If this was an #include_next "/absolute/file", fail.
298 if (FromDir) return 0;
299
300 // Otherwise, just return the file.
301 return FileMgr.getFile(Filename);
302 }
303
304 // Step #0, unless disabled, check to see if the file is in the #includer's
305 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000306 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000307 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
308 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000309 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000310 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000311 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000312 if (const FileEntry *FE =
313 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000314 if (CurDirLookup)
315 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000316 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000317 CurDir = 0;
318
319 // This file is a system header or C++ unfriendly if the old file is.
320 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000321 return FE;
322 }
323 }
324 }
325
326 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000327 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000328
329 // If this is a #include_next request, start searching after the directory the
330 // file was found in.
331 if (FromDir)
332 i = FromDir-&SearchDirs[0];
333
334 // Check each directory in sequence to see if it contains this file.
335 for (; i != SearchDirs.size(); ++i) {
336 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000337 // FIXME: Portability. Adding file to dir should be in sys::Path.
338 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
339 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000340 CurDir = &SearchDirs[i];
341
342 // This file is a system header or C++ unfriendly if the dir is.
343 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000344 return FE;
345 }
346 }
347
348 // Otherwise, didn't find it.
349 return 0;
350}
351
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000352/// isInPrimaryFile - Return true if we're in the top-level file, not in a
353/// #include.
354bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000355 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000356 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000357
Chris Lattner13044d92006-07-03 05:16:44 +0000358 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000359 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000360 if (IncludeMacroStack[i].TheLexer &&
361 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
362 return IncludeMacroStack[i].TheLexer->isMainFile();
363 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000364}
365
366/// getCurrentLexer - Return the current file lexer being lexed from. Note
367/// that this ignores any potentially active macro expansions and _Pragma
368/// expansions going on at the time.
369Lexer *Preprocessor::getCurrentFileLexer() const {
370 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
371
372 // Look for a stacked lexer.
373 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000374 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000375 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
376 return L;
377 }
378 return 0;
379}
380
381
Chris Lattner22eb9722006-06-18 05:43:12 +0000382/// EnterSourceFile - Add a source file to the top of the include stack and
383/// start lexing tokens from it instead of the current buffer. Return true
384/// on failure.
385void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000386 const DirectoryLookup *CurDir,
387 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000388 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000389 ++NumEnteredSourceFiles;
390
Chris Lattner69772b02006-07-02 20:34:39 +0000391 if (MaxIncludeStackDepth < IncludeMacroStack.size())
392 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000393
Chris Lattner22eb9722006-06-18 05:43:12 +0000394 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000395 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000396 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000397 EnterSourceFileWithLexer(TheLexer, CurDir);
398}
Chris Lattner22eb9722006-06-18 05:43:12 +0000399
Chris Lattner69772b02006-07-02 20:34:39 +0000400/// EnterSourceFile - Add a source file to the top of the include stack and
401/// start lexing tokens from it instead of the current buffer.
402void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
403 const DirectoryLookup *CurDir) {
404
405 // Add the current lexer to the include stack.
406 if (CurLexer || CurMacroExpander)
407 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
408 CurMacroExpander));
409
410 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000411 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000412 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000413
414 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000415 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000416 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
417
418 // Get the file entry for the current file.
419 if (const FileEntry *FE =
420 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
421 FileType = getFileInfo(FE).DirInfo;
422
Chris Lattner1840e492006-07-02 22:30:01 +0000423 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000424 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000425 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000426}
427
Chris Lattner69772b02006-07-02 20:34:39 +0000428
429
Chris Lattner22eb9722006-06-18 05:43:12 +0000430/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000431/// tokens from it instead of the current buffer.
432void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000433 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000434 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000435 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
436 CurMacroExpander));
437 CurLexer = 0;
438 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000439
440 // TODO: Figure out arguments.
441
442 // Mark the macro as currently disabled, so that it is not recursively
443 // expanded.
444 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000445 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000446}
447
Chris Lattner22eb9722006-06-18 05:43:12 +0000448//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000449// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000450//===----------------------------------------------------------------------===//
451
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000452/// RegisterBuiltinMacro - Register the specified identifier in the identifier
453/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000454IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000455 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000456 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000457
458 // Mark it as being a macro that is builtin.
459 MacroInfo *MI = new MacroInfo(SourceLocation());
460 MI->setIsBuiltinMacro();
461 Id->setMacroInfo(MI);
462 return Id;
463}
464
465
Chris Lattner677757a2006-06-28 05:26:32 +0000466/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
467/// identifier table.
468void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000469 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000470 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000471 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
472 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000473 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000474
475 // GCC Extensions.
476 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
477 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000478 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000479}
480
Chris Lattner677757a2006-06-28 05:26:32 +0000481
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000482/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
483/// expanded as a macro, handle it and return the next token as 'Identifier'.
484void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
485 MacroInfo *MI) {
486 ++NumMacroExpanded;
Chris Lattner13044d92006-07-03 05:16:44 +0000487
488 // Notice that this macro has been used.
489 MI->setIsUsed(true);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000490
491 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
492 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000493 return ExpandBuiltinMacro(Identifier);
494
495 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000496 // FIXME: Fn-Like Macros: Read/Validate the argument list here!
Chris Lattner69772b02006-07-02 20:34:39 +0000497
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000498
499 // If this macro expands to no tokens, don't bother to push it onto the
500 // expansion stack, only to take it right back off.
501 if (MI->getNumTokens() == 0) {
502 // Ignore this macro use, just return the next token in the current
503 // buffer.
504 bool HadLeadingSpace = Identifier.hasLeadingSpace();
505 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
506
507 Lex(Identifier);
508
509 // If the identifier isn't on some OTHER line, inherit the leading
510 // whitespace/first-on-a-line property of this token. This handles
511 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
512 // empty.
513 if (!Identifier.isAtStartOfLine()) {
514 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
515 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
516 }
517 ++NumFastMacroExpanded;
518 return;
519
520 } else if (MI->getNumTokens() == 1 &&
521 // Don't handle identifiers if they need recursive expansion.
522 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
523 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000524 // FIXME: Fn-Like Macros: Function-style macros only if no arguments?
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000525
526 // Otherwise, if this macro expands into a single trivially-expanded
527 // token: expand it now. This handles common cases like
528 // "#define VAL 42".
529
530 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
531 // identifier to the expanded token.
532 bool isAtStartOfLine = Identifier.isAtStartOfLine();
533 bool hasLeadingSpace = Identifier.hasLeadingSpace();
534
535 // Remember where the token is instantiated.
536 SourceLocation InstantiateLoc = Identifier.getLocation();
537
538 // Replace the result token.
539 Identifier = MI->getReplacementToken(0);
540
541 // Restore the StartOfLine/LeadingSpace markers.
542 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
543 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
544
545 // Update the tokens location to include both its logical and physical
546 // locations.
547 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000548 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000549 Identifier.SetLocation(Loc);
550
551 // Since this is not an identifier token, it can't be macro expanded, so
552 // we're done.
553 ++NumFastMacroExpanded;
554 return;
555 }
556
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000557 // Start expanding the macro (FIXME: Fn-Like Macros: pass arguments).
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000558 EnterMacro(Identifier);
559
560 // Now that the macro is at the top of the include stack, ask the
561 // preprocessor to read the next token from it.
562 return Lex(Identifier);
563}
564
Chris Lattnerc673f902006-06-30 06:10:41 +0000565/// ComputeDATE_TIME - Compute the current time, enter it into the specified
566/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
567/// the identifier tokens inserted.
568static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
569 ScratchBuffer *ScratchBuf) {
570 time_t TT = time(0);
571 struct tm *TM = localtime(&TT);
572
573 static const char * const Months[] = {
574 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
575 };
576
577 char TmpBuffer[100];
578 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
579 TM->tm_year+1900);
580 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
581
582 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
583 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
584}
585
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000586/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
587/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000588void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000589 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000590 IdentifierInfo *II = Tok.getIdentifierInfo();
591 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000592
593 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
594 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000595 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000596 return Handle_Pragma(Tok);
597
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000598 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000599
600 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000601 Tok.SetIdentifierInfo(0);
602 Tok.ClearFlag(LexerToken::NeedsCleaning);
603
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000604 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000605 // __LINE__ expands to a simple numeric value.
606 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
607 unsigned Length = strlen(TmpBuffer);
608 Tok.SetKind(tok::numeric_constant);
609 Tok.SetLength(Length);
610 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000611 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000612 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000613 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000614 Diag(Tok, diag::ext_pp_base_file);
615 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
616 while (NextLoc.getFileID() != 0) {
617 Loc = NextLoc;
618 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
619 }
620 }
621
Chris Lattner0766e592006-07-03 01:07:01 +0000622 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
623 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000624 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000625 Tok.SetKind(tok::string_literal);
626 Tok.SetLength(FN.size());
627 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000628 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000629 if (!DATELoc.isValid())
630 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
631 Tok.SetKind(tok::string_literal);
632 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
633 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000634 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000635 if (!TIMELoc.isValid())
636 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
637 Tok.SetKind(tok::string_literal);
638 Tok.SetLength(strlen("\"hh:mm:ss\""));
639 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000640 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000641 Diag(Tok, diag::ext_pp_include_level);
642
643 // Compute the include depth of this token.
644 unsigned Depth = 0;
645 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
646 for (; Loc.getFileID() != 0; ++Depth)
647 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
648
649 // __INCLUDE_LEVEL__ expands to a simple numeric value.
650 sprintf(TmpBuffer, "%u", Depth);
651 unsigned Length = strlen(TmpBuffer);
652 Tok.SetKind(tok::numeric_constant);
653 Tok.SetLength(Length);
654 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000655 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000656 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
657 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
658 Diag(Tok, diag::ext_pp_timestamp);
659
660 // Get the file that we are lexing out of. If we're currently lexing from
661 // a macro, dig into the include stack.
662 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000663 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000664
665 if (TheLexer)
666 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
667
668 // If this file is older than the file it depends on, emit a diagnostic.
669 const char *Result;
670 if (CurFile) {
671 time_t TT = CurFile->getModificationTime();
672 struct tm *TM = localtime(&TT);
673 Result = asctime(TM);
674 } else {
675 Result = "??? ??? ?? ??:??:?? ????\n";
676 }
677 TmpBuffer[0] = '"';
678 strcpy(TmpBuffer+1, Result);
679 unsigned Len = strlen(TmpBuffer);
680 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
681 Tok.SetKind(tok::string_literal);
682 Tok.SetLength(Len);
683 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000684 } else {
685 assert(0 && "Unknown identifier!");
686 }
687}
Chris Lattner677757a2006-06-28 05:26:32 +0000688
Chris Lattner13044d92006-07-03 05:16:44 +0000689namespace {
690struct UnusedIdentifierReporter : public IdentifierVisitor {
691 Preprocessor &PP;
692 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
693
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000694 void VisitIdentifier(IdentifierInfo &II) const {
695 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
696 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000697 }
698};
699}
700
Chris Lattner677757a2006-06-28 05:26:32 +0000701//===----------------------------------------------------------------------===//
702// Lexer Event Handling.
703//===----------------------------------------------------------------------===//
704
705/// HandleIdentifier - This callback is invoked when the lexer reads an
706/// identifier. This callback looks up the identifier in the map and/or
707/// potentially macro expands it or turns it into a named token (like 'for').
708void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
709 if (Identifier.getIdentifierInfo() == 0) {
710 // If we are skipping tokens (because we are in a #if 0 block), there will
711 // be no identifier info, just return the token.
712 assert(isSkipping() && "Token isn't an identifier?");
713 return;
714 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000715 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000716
717 // If this identifier was poisoned, and if it was not produced from a macro
718 // expansion, emit an error.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000719 if (II.isPoisoned() && CurLexer)
Chris Lattner677757a2006-06-28 05:26:32 +0000720 Diag(Identifier, diag::err_pp_used_poisoned_id);
721
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000722 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000723 if (MI->isEnabled() && !DisableMacroExpansion)
724 return HandleMacroExpandedIdentifier(Identifier, MI);
725
726 // Change the kind of this identifier to the appropriate token kind, e.g.
727 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000728 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000729
730 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000731 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000732}
733
Chris Lattner22eb9722006-06-18 05:43:12 +0000734/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
735/// the current file. This either returns the EOF token or pops a level off
736/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000737void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000738 assert(!CurMacroExpander &&
739 "Ending a file when currently in a macro!");
740
741 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
742 // this is an error condition. Just return the EOF token up to
743 // SkipExcludedConditionalBlock. The Lexer will have already have issued
744 // errors for the unterminated #if's on the conditional stack.
745 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000746 Result.StartToken();
747 CurLexer->BufferPtr = CurLexer->BufferEnd;
748 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000749 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000750 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000751 }
752
Chris Lattner371ac8a2006-07-04 07:11:10 +0000753 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000754 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000755 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000756 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000757 // Okay, this has a controlling macro, remember in PerFileInfo.
758 if (const FileEntry *FE =
759 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
760 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +0000761 }
762 }
763
Chris Lattner22eb9722006-06-18 05:43:12 +0000764 // If this is a #include'd file, pop it off the include stack and continue
765 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000766 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000767 // We're done with the #included file.
768 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000769 CurLexer = IncludeMacroStack.back().TheLexer;
770 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
771 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
772 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000773
774 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000775 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000776 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
777
778 // Get the file entry for the current file.
779 if (const FileEntry *FE =
780 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
781 FileType = getFileInfo(FE).DirInfo;
782
Chris Lattner0c885f52006-06-21 06:50:18 +0000783 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000784 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000785 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000786
Chris Lattner22eb9722006-06-18 05:43:12 +0000787 return Lex(Result);
788 }
789
Chris Lattnerd01e2912006-06-18 16:22:51 +0000790 Result.StartToken();
791 CurLexer->BufferPtr = CurLexer->BufferEnd;
792 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000793 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000794
795 // We're done with the #included file.
796 delete CurLexer;
797 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000798
799 // This is the end of the top-level file.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000800 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +0000801}
802
803/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000804/// the current macro line.
805void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000806 assert(CurMacroExpander && !CurLexer &&
807 "Ending a macro when currently in a #include file!");
808
809 // Mark macro not ignored now that it is no longer being expanded.
810 CurMacroExpander->getMacro().EnableMacro();
811 delete CurMacroExpander;
812
Chris Lattner69772b02006-07-02 20:34:39 +0000813 // Handle this like a #include file being popped off the stack.
814 CurMacroExpander = 0;
815 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000816}
817
818
819//===----------------------------------------------------------------------===//
820// Utility Methods for Preprocessor Directive Handling.
821//===----------------------------------------------------------------------===//
822
823/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
824/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000825void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000826 LexerToken Tmp;
827 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000828 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000829 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000830}
831
832/// ReadMacroName - Lex and validate a macro name, which occurs after a
833/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattner44f8a662006-07-03 01:27:27 +0000834/// of the macro line if the macro name is invalid. isDefineUndef is true if
835/// this is due to a a #define or #undef directive, false if it is something
836/// else (e.g. #ifdef).
837void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, bool isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000838 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000839 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000840
841 // Missing macro name?
842 if (MacroNameTok.getKind() == tok::eom)
843 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
844
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000845 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
846 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000847 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000848 // Fall through on error.
849 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000850 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000851
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000852 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
853 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000854 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +0000855 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000856 } else if (isDefineUndef && II->getMacroInfo() &&
857 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000858 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
859 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +0000860 } else {
861 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000862 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000863 }
864
Chris Lattner22eb9722006-06-18 05:43:12 +0000865 // Invalid macro name, read and discard the rest of the line. Then set the
866 // token kind to tok::eom.
867 MacroNameTok.SetKind(tok::eom);
868 return DiscardUntilEndOfDirective();
869}
870
871/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
872/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000873void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000874 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000875 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000876 // There should be no tokens after the directive, but we allow them as an
877 // extension.
878 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000879 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
880 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000881 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000882}
883
884
885
886/// SkipExcludedConditionalBlock - We just read a #if or related directive and
887/// decided that the subsequent tokens are in the #if'd out portion of the
888/// file. Lex the rest of the file, until we see an #endif. If
889/// FoundNonSkipPortion is true, then we have already emitted code for part of
890/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
891/// is true, then #else directives are ok, if not, then we have already seen one
892/// so a #else directive is a duplicate. When this returns, the caller can lex
893/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000894void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000895 bool FoundNonSkipPortion,
896 bool FoundElse) {
897 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000898 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000899 "Lexing a macro, not a file?");
900
901 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
902 FoundNonSkipPortion, FoundElse);
903
904 // Know that we are going to be skipping tokens. Set this flag to indicate
905 // this, which has a couple of effects:
906 // 1. If EOF of the current lexer is found, the include stack isn't popped.
907 // 2. Identifier information is not looked up for identifier tokens. As an
908 // effect of this, implicit macro expansion is naturally disabled.
909 // 3. "#" tokens at the start of a line are treated as normal tokens, not
910 // implicitly transformed by the lexer.
911 // 4. All notes, warnings, and extension messages are disabled.
912 //
913 SkippingContents = true;
914 LexerToken Tok;
915 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000916 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000917
918 // If this is the end of the buffer, we have an error. The lexer will have
919 // already handled this error condition, so just return and let the caller
920 // lex after this #include.
921 if (Tok.getKind() == tok::eof) break;
922
923 // If this token is not a preprocessor directive, just skip it.
924 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
925 continue;
926
927 // We just parsed a # character at the start of a line, so we're in
928 // directive mode. Tell the lexer this so any newlines we see will be
929 // converted into an EOM token (this terminates the macro).
930 CurLexer->ParsingPreprocessorDirective = true;
931
932 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000933 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000934
935 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
936 // something bogus), skip it.
937 if (Tok.getKind() != tok::identifier) {
938 CurLexer->ParsingPreprocessorDirective = false;
939 continue;
940 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000941
Chris Lattner22eb9722006-06-18 05:43:12 +0000942 // If the first letter isn't i or e, it isn't intesting to us. We know that
943 // this is safe in the face of spelling differences, because there is no way
944 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000945 // allows us to avoid looking up the identifier info for #define/#undef and
946 // other common directives.
947 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
948 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000949 if (FirstChar >= 'a' && FirstChar <= 'z' &&
950 FirstChar != 'i' && FirstChar != 'e') {
951 CurLexer->ParsingPreprocessorDirective = false;
952 continue;
953 }
954
Chris Lattnere60165f2006-06-22 06:36:29 +0000955 // Get the identifier name without trigraphs or embedded newlines. Note
956 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
957 // when skipping.
958 // TODO: could do this with zero copies in the no-clean case by using
959 // strncmp below.
960 char Directive[20];
961 unsigned IdLen;
962 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
963 IdLen = Tok.getLength();
964 memcpy(Directive, RawCharData, IdLen);
965 Directive[IdLen] = 0;
966 } else {
967 std::string DirectiveStr = getSpelling(Tok);
968 IdLen = DirectiveStr.size();
969 if (IdLen >= 20) {
970 CurLexer->ParsingPreprocessorDirective = false;
971 continue;
972 }
973 memcpy(Directive, &DirectiveStr[0], IdLen);
974 Directive[IdLen] = 0;
975 }
976
Chris Lattner22eb9722006-06-18 05:43:12 +0000977 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000978 if ((IdLen == 2) || // "if"
979 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
980 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000981 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
982 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000983 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000984 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000985 /*foundnonskip*/false,
986 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000987 }
988 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000989 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000990 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000991 PPConditionalInfo CondInfo;
992 CondInfo.WasSkipping = true; // Silence bogus warning.
993 bool InCond = CurLexer->popConditionalLevel(CondInfo);
994 assert(!InCond && "Can't be skipping if not in a conditional!");
995
996 // If we popped the outermost skipping block, we're done skipping!
997 if (!CondInfo.WasSkipping)
998 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000999 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001000 // #else directive in a skipping conditional. If not in some other
1001 // skipping conditional, and if #else hasn't already been seen, enter it
1002 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001003 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001004 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1005
1006 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001007 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001008
1009 // Note that we've seen a #else in this conditional.
1010 CondInfo.FoundElse = true;
1011
1012 // If the conditional is at the top level, and the #if block wasn't
1013 // entered, enter the #else block now.
1014 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1015 CondInfo.FoundNonSkip = true;
1016 break;
1017 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001018 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001019 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1020
1021 bool ShouldEnter;
1022 // If this is in a skipping block or if we're already handled this #if
1023 // block, don't bother parsing the condition.
1024 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001025 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001026 ShouldEnter = false;
1027 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001028 // Restore the value of SkippingContents so that identifiers are
1029 // looked up, etc, inside the #elif expression.
1030 assert(SkippingContents && "We have to be skipping here!");
1031 SkippingContents = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001032 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001033 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001034 SkippingContents = true;
1035 }
1036
1037 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001038 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001039
1040 // If this condition is true, enter it!
1041 if (ShouldEnter) {
1042 CondInfo.FoundNonSkip = true;
1043 break;
1044 }
1045 }
1046 }
1047
1048 CurLexer->ParsingPreprocessorDirective = false;
1049 }
1050
1051 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1052 // of the file, just stop skipping and return to lexing whatever came after
1053 // the #if block.
1054 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001055}
1056
1057//===----------------------------------------------------------------------===//
1058// Preprocessor Directive Handling.
1059//===----------------------------------------------------------------------===//
1060
1061/// HandleDirective - This callback is invoked when the lexer sees a # token
1062/// at the start of a line. This consumes the directive, modifies the
1063/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1064/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001065void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001066 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001067
1068 // We just parsed a # character at the start of a line, so we're in directive
1069 // mode. Tell the lexer this so any newlines we see will be converted into an
1070 // EOM token (this terminates the macro).
1071 CurLexer->ParsingPreprocessorDirective = true;
1072
1073 ++NumDirectives;
1074
Chris Lattner371ac8a2006-07-04 07:11:10 +00001075 // We are about to read a token. For the multiple-include optimization FA to
1076 // work, we have to remember if we had read any tokens *before* this
1077 // pp-directive.
1078 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1079
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001081 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001082
1083 switch (Result.getKind()) {
1084 default: break;
1085 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001086 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001087
1088#if 0
1089 case tok::numeric_constant:
1090 // FIXME: implement # 7 line numbers!
1091 break;
1092#endif
1093 case tok::kw_else:
1094 return HandleElseDirective(Result);
1095 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001096 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001098 // Get the identifier name without trigraphs or embedded newlines.
1099 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001101 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001102 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001103 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001104 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001105 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001107 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1108 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001109 break;
1110 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001111 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001113 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001114 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001115 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001117 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001119 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001120 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001121 break;
1122 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001123 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001124 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001125 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001126 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001127 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001128 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001129 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001130 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001131 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1132 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 break;
1134 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001135 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1136 return HandleIncludeDirective(Result); // Handle #include.
1137 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001138 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001139 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001140 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001141 break;
1142 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001143 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001144 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001145 }
1146 break;
1147 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001148 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1149 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001150 break;
1151 }
1152 break;
1153 }
1154
1155 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001156 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001157
1158 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001159 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001160
1161 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001162}
1163
Chris Lattner01d66cc2006-07-03 22:16:27 +00001164void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001165 bool isWarning) {
1166 // Read the rest of the line raw. We do this because we don't want macros
1167 // to be expanded and we don't require that the tokens be valid preprocessing
1168 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1169 // collapse multiple consequtive white space between tokens, but this isn't
1170 // specified by the standard.
1171 std::string Message = CurLexer->ReadToEndOfLine();
1172
1173 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001174 return Diag(Tok, DiagID, Message);
1175}
1176
1177/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1178///
1179void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001180 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001181 Diag(Tok, diag::ext_pp_ident_directive);
1182
Chris Lattner371ac8a2006-07-04 07:11:10 +00001183 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001184 LexerToken StrTok;
1185 Lex(StrTok);
1186
1187 // If the token kind isn't a string, it's a malformed directive.
1188 if (StrTok.getKind() != tok::string_literal)
1189 return Diag(StrTok, diag::err_pp_malformed_ident);
1190
1191 // Verify that there is nothing after the string, other than EOM.
1192 CheckEndOfDirective("#ident");
1193
1194 if (IdentHandler)
1195 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001196}
1197
Chris Lattnerb8761832006-06-24 21:31:03 +00001198//===----------------------------------------------------------------------===//
1199// Preprocessor Include Directive Handling.
1200//===----------------------------------------------------------------------===//
1201
Chris Lattner22eb9722006-06-18 05:43:12 +00001202/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1203/// file to be included from the lexer, then include it! This is a common
1204/// routine with functionality shared between #include, #include_next and
1205/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001206void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001207 const DirectoryLookup *LookupFrom,
1208 bool isImport) {
1209 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001210
Chris Lattner22eb9722006-06-18 05:43:12 +00001211 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001212 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001213
1214 // If the token kind is EOM, the error has already been diagnosed.
1215 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001216 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001217
1218 // Verify that there is nothing after the filename, other than EOM. Use the
1219 // preprocessor to lex this in case lexing the filename entered a macro.
1220 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001221
1222 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001223 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001224 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1225
Chris Lattner269c2322006-06-25 06:23:00 +00001226 // Find out whether the filename is <x> or "x".
1227 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001228
1229 // Remove the quotes.
1230 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1231
Chris Lattner22eb9722006-06-18 05:43:12 +00001232 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001233 const DirectoryLookup *CurDir;
1234 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 if (File == 0)
1236 return Diag(FilenameTok, diag::err_pp_file_not_found);
1237
1238 // Get information about this file.
1239 PerFileInfo &FileInfo = getFileInfo(File);
1240
1241 // If this is a #import directive, check that we have not already imported
1242 // this header.
1243 if (isImport) {
1244 // If this has already been imported, don't import it again.
1245 FileInfo.isImport = true;
1246
1247 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001248 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 } else {
1250 // Otherwise, if this is a #include of a file that was previously #import'd
1251 // or if this is the second #include of a #pragma once file, ignore it.
1252 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001253 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001254 }
Chris Lattner3665f162006-07-04 07:26:10 +00001255
1256 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1257 // if the macro that guards it is defined, we know the #include has no effect.
1258 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1259 ++NumMultiIncludeFileOptzn;
1260 return;
1261 }
1262
Chris Lattner22eb9722006-06-18 05:43:12 +00001263
1264 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001265 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001266 if (FileID == 0)
1267 return Diag(FilenameTok, diag::err_pp_file_not_found);
1268
1269 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001270 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001271
1272 // Increment the number of times this file has been included.
1273 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001274}
1275
1276/// HandleIncludeNextDirective - Implements #include_next.
1277///
Chris Lattnercb283342006-06-18 06:48:37 +00001278void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1279 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001280
1281 // #include_next is like #include, except that we start searching after
1282 // the current found directory. If we can't do this, issue a
1283 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001284 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001285 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001286 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001287 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001288 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001289 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001290 } else {
1291 // Start looking up in the next directory.
1292 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001293 }
1294
1295 return HandleIncludeDirective(IncludeNextTok, Lookup);
1296}
1297
1298/// HandleImportDirective - Implements #import.
1299///
Chris Lattnercb283342006-06-18 06:48:37 +00001300void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1301 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001302
1303 return HandleIncludeDirective(ImportTok, 0, true);
1304}
1305
Chris Lattnerb8761832006-06-24 21:31:03 +00001306//===----------------------------------------------------------------------===//
1307// Preprocessor Macro Directive Handling.
1308//===----------------------------------------------------------------------===//
1309
Chris Lattner22eb9722006-06-18 05:43:12 +00001310/// HandleDefineDirective - Implements #define. This consumes the entire macro
1311/// line then lets the caller lex the next real token.
1312///
Chris Lattnercb283342006-06-18 06:48:37 +00001313void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001314 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001315
Chris Lattner22eb9722006-06-18 05:43:12 +00001316 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001317 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001318
1319 // Error reading macro name? If so, diagnostic already issued.
1320 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001321 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001322
Chris Lattner50b497e2006-06-18 16:32:35 +00001323 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001324
1325 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001326 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001327
1328 if (Tok.getKind() == tok::eom) {
1329 // If there is no body to this macro, we have no special handling here.
1330 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1331 // This is a function-like macro definition.
1332 //assert(0 && "Function-like macros not implemented!");
Chris Lattnerbff18d52006-07-06 04:49:18 +00001333 delete MI;
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 return DiscardUntilEndOfDirective();
1335
1336 } else if (!Tok.hasLeadingSpace()) {
1337 // C99 requires whitespace between the macro definition and the body. Emit
1338 // a diagnostic for something like "#define X+".
1339 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001340 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 } else {
1342 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1343 // one in some cases!
1344 }
1345 } else {
1346 // This is a normal token with leading space. Clear the leading space
1347 // marker on the first token to get proper expansion.
1348 Tok.ClearFlag(LexerToken::LeadingSpace);
1349 }
1350
1351 // Read the rest of the macro body.
1352 while (Tok.getKind() != tok::eom) {
1353 MI->AddTokenToBody(Tok);
1354
Chris Lattnerbff18d52006-07-06 04:49:18 +00001355 // FIXME: Check for #'s that aren't followed by argument names.
1356 // See create_iso_definition.
1357
Chris Lattner22eb9722006-06-18 05:43:12 +00001358 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001359 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001360 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001361
1362 unsigned NumTokens = MI->getNumTokens();
1363
1364 // Check that there is no paste (##) operator at the begining or end of the
1365 // replacement list.
1366 if (NumTokens != 0) {
1367 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
1368 SourceLocation Loc = MI->getReplacementToken(0).getLocation();
1369 delete MI;
1370 return Diag(Loc, diag::err_paste_at_start);
1371 }
1372 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
1373 SourceLocation Loc = MI->getReplacementToken(NumTokens-1).getLocation();
1374 delete MI;
1375 return Diag(Loc, diag::err_paste_at_end);
1376 }
1377 }
1378
Chris Lattner22eb9722006-06-18 05:43:12 +00001379
Chris Lattner13044d92006-07-03 05:16:44 +00001380 // If this is the primary source file, remember that this macro hasn't been
1381 // used yet.
1382 if (isInPrimaryFile())
1383 MI->setIsUsed(false);
1384
Chris Lattner22eb9722006-06-18 05:43:12 +00001385 // Finally, if this identifier already had a macro defined for it, verify that
1386 // the macro bodies are identical and free the old definition.
1387 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001388 if (!OtherMI->isUsed())
1389 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1390
Chris Lattner22eb9722006-06-18 05:43:12 +00001391 // FIXME: Verify the definition is the same.
1392 // Macros must be identical. This means all tokes and whitespace separation
1393 // must be the same.
1394 delete OtherMI;
1395 }
1396
1397 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001398}
1399
1400
1401/// HandleUndefDirective - Implements #undef.
1402///
Chris Lattnercb283342006-06-18 06:48:37 +00001403void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001405
Chris Lattner22eb9722006-06-18 05:43:12 +00001406 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001407 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001408
1409 // Error reading macro name? If so, diagnostic already issued.
1410 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001411 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001412
1413 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001414 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001415
1416 // Okay, we finally have a valid identifier to undef.
1417 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1418
1419 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001420 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001421
Chris Lattner13044d92006-07-03 05:16:44 +00001422 if (!MI->isUsed())
1423 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001424
1425 // Free macro definition.
1426 delete MI;
1427 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001428}
1429
1430
Chris Lattnerb8761832006-06-24 21:31:03 +00001431//===----------------------------------------------------------------------===//
1432// Preprocessor Conditional Directive Handling.
1433//===----------------------------------------------------------------------===//
1434
Chris Lattner22eb9722006-06-18 05:43:12 +00001435/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001436/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1437/// if any tokens have been returned or pp-directives activated before this
1438/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001439///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001440void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1441 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 ++NumIf;
1443 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001444
Chris Lattner22eb9722006-06-18 05:43:12 +00001445 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001446 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001447
1448 // Error reading macro name? If so, diagnostic already issued.
1449 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001450 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001451
1452 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001453 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1454
1455 // If the start of a top-level #ifdef, inform MIOpt.
1456 if (!ReadAnyTokensBeforeDirective &&
1457 CurLexer->getConditionalStackDepth() == 0) {
1458 assert(isIfndef && "#ifdef shouldn't reach here");
1459 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1460 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001461
Chris Lattnera78a97e2006-07-03 05:42:18 +00001462 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1463
1464 // If there is a macro, mark it used.
1465 if (MI) MI->setIsUsed(true);
1466
Chris Lattner22eb9722006-06-18 05:43:12 +00001467 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001468 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001469 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001470 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001471 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001472 } else {
1473 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001474 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001475 /*Foundnonskip*/false,
1476 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001477 }
1478}
1479
1480/// HandleIfDirective - Implements the #if directive.
1481///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001482void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1483 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001485
Chris Lattner371ac8a2006-07-04 07:11:10 +00001486 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001487 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001488 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001489
1490 // Should we include the stuff contained by this directive?
1491 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001492 // If this condition is equivalent to #ifndef X, and if this is the first
1493 // directive seen, handle it for the multiple-include optimization.
1494 if (!ReadAnyTokensBeforeDirective &&
1495 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1496 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1497
Chris Lattner22eb9722006-06-18 05:43:12 +00001498 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001499 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001500 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001501 } else {
1502 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001503 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001504 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001505 }
1506}
1507
1508/// HandleEndifDirective - Implements the #endif directive.
1509///
Chris Lattnercb283342006-06-18 06:48:37 +00001510void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001511 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001512
Chris Lattner22eb9722006-06-18 05:43:12 +00001513 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001514 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001515
1516 PPConditionalInfo CondInfo;
1517 if (CurLexer->popConditionalLevel(CondInfo)) {
1518 // No conditionals on the stack: this is an #endif without an #if.
1519 return Diag(EndifToken, diag::err_pp_endif_without_if);
1520 }
1521
Chris Lattner371ac8a2006-07-04 07:11:10 +00001522 // If this the end of a top-level #endif, inform MIOpt.
1523 if (CurLexer->getConditionalStackDepth() == 0)
1524 CurLexer->MIOpt.ExitTopLevelConditional();
1525
Chris Lattner22eb9722006-06-18 05:43:12 +00001526 assert(!CondInfo.WasSkipping && !isSkipping() &&
1527 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001528}
1529
1530
Chris Lattnercb283342006-06-18 06:48:37 +00001531void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001532 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001533
Chris Lattner22eb9722006-06-18 05:43:12 +00001534 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001535 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001536
1537 PPConditionalInfo CI;
1538 if (CurLexer->popConditionalLevel(CI))
1539 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001540
1541 // If this is a top-level #else, inform the MIOpt.
1542 if (CurLexer->getConditionalStackDepth() == 0)
1543 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001544
1545 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001546 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001547
1548 // Finally, skip the rest of the contents of this block and return the first
1549 // token after it.
1550 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1551 /*FoundElse*/true);
1552}
1553
Chris Lattnercb283342006-06-18 06:48:37 +00001554void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001555 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001556
Chris Lattner22eb9722006-06-18 05:43:12 +00001557 // #elif directive in a non-skipping conditional... start skipping.
1558 // We don't care what the condition is, because we will always skip it (since
1559 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001560 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001561
1562 PPConditionalInfo CI;
1563 if (CurLexer->popConditionalLevel(CI))
1564 return Diag(ElifToken, diag::pp_err_elif_without_if);
1565
Chris Lattner371ac8a2006-07-04 07:11:10 +00001566 // If this is a top-level #elif, inform the MIOpt.
1567 if (CurLexer->getConditionalStackDepth() == 0)
1568 CurLexer->MIOpt.FoundTopLevelElse();
1569
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001571 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001572
1573 // Finally, skip the rest of the contents of this block and return the first
1574 // token after it.
1575 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1576 /*FoundElse*/CI.FoundElse);
1577}
Chris Lattnerb8761832006-06-24 21:31:03 +00001578