blob: b161263423d10cbb59b7c7cde2683d6cd4e7ff41 [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 assert(TokStart && "Token has invalid location!");
218 if (!Tok.needsCleaning())
219 return std::string(TokStart, TokStart+Tok.getLength());
220
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 std::string Result;
222 Result.reserve(Tok.getLength());
223
Chris Lattneref9eae12006-07-04 22:33:12 +0000224 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
226 Ptr != End; ) {
227 unsigned CharSize;
228 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
229 Ptr += CharSize;
230 }
231 assert(Result.size() != unsigned(Tok.getLength()) &&
232 "NeedsCleaning flag set on something that didn't need cleaning!");
233 return Result;
234}
235
236/// getSpelling - This method is used to get the spelling of a token into a
237/// preallocated buffer, instead of as an std::string. The caller is required
238/// to allocate enough space for the token, which is guaranteed to be at least
239/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000240///
241/// Note that this method may do two possible things: it may either fill in
242/// the buffer specified with characters, or it may *change the input pointer*
243/// to point to a constant buffer with the data already in it (avoiding a
244/// copy). The caller is not allowed to modify the returned buffer pointer
245/// if an internal buffer is returned.
246unsigned Preprocessor::getSpelling(const LexerToken &Tok,
247 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
249
Chris Lattner50b497e2006-06-18 16:32:35 +0000250 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251 assert(TokStart && "Token has invalid location!");
252
253 // If this token contains nothing interesting, return it directly.
254 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000255 Buffer = TokStart;
256 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000257 }
258 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000259 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000260 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
261 Ptr != End; ) {
262 unsigned CharSize;
263 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
264 Ptr += CharSize;
265 }
266 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
267 "NeedsCleaning flag set on something that didn't need cleaning!");
268
269 return OutBuf-Buffer;
270}
271
272//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000273// Source File Location Methods.
274//===----------------------------------------------------------------------===//
275
276
277/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
278/// return null on failure. isAngled indicates whether the file reference is
279/// for system #include's or not (i.e. using <> instead of "").
280const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000281 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000282 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000283 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000284 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000285 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000286
287 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000288 // FIXME: Portability. This should be a sys::Path interface, this doesn't
289 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000290 if (Filename[0] == '/') {
291 // If this was an #include_next "/absolute/file", fail.
292 if (FromDir) return 0;
293
294 // Otherwise, just return the file.
295 return FileMgr.getFile(Filename);
296 }
297
298 // Step #0, unless disabled, check to see if the file is in the #includer's
299 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000300 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000301 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
302 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000303 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000304 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000305 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000306 if (const FileEntry *FE =
307 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000308 if (CurDirLookup)
309 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000310 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000311 CurDir = 0;
312
313 // This file is a system header or C++ unfriendly if the old file is.
314 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000315 return FE;
316 }
317 }
318 }
319
320 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000321 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000322
323 // If this is a #include_next request, start searching after the directory the
324 // file was found in.
325 if (FromDir)
326 i = FromDir-&SearchDirs[0];
327
328 // Check each directory in sequence to see if it contains this file.
329 for (; i != SearchDirs.size(); ++i) {
330 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000331 // FIXME: Portability. Adding file to dir should be in sys::Path.
332 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
333 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000334 CurDir = &SearchDirs[i];
335
336 // This file is a system header or C++ unfriendly if the dir is.
337 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000338 return FE;
339 }
340 }
341
342 // Otherwise, didn't find it.
343 return 0;
344}
345
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000346/// isInPrimaryFile - Return true if we're in the top-level file, not in a
347/// #include.
348bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000349 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000350 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000351
Chris Lattner13044d92006-07-03 05:16:44 +0000352 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000353 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000354 if (IncludeMacroStack[i].TheLexer &&
355 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
356 return IncludeMacroStack[i].TheLexer->isMainFile();
357 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000358}
359
360/// getCurrentLexer - Return the current file lexer being lexed from. Note
361/// that this ignores any potentially active macro expansions and _Pragma
362/// expansions going on at the time.
363Lexer *Preprocessor::getCurrentFileLexer() const {
364 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
365
366 // Look for a stacked lexer.
367 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000368 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000369 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
370 return L;
371 }
372 return 0;
373}
374
375
Chris Lattner22eb9722006-06-18 05:43:12 +0000376/// EnterSourceFile - Add a source file to the top of the include stack and
377/// start lexing tokens from it instead of the current buffer. Return true
378/// on failure.
379void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000380 const DirectoryLookup *CurDir,
381 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000382 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000383 ++NumEnteredSourceFiles;
384
Chris Lattner69772b02006-07-02 20:34:39 +0000385 if (MaxIncludeStackDepth < IncludeMacroStack.size())
386 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000387
Chris Lattner22eb9722006-06-18 05:43:12 +0000388 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000389 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000390 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000391 EnterSourceFileWithLexer(TheLexer, CurDir);
392}
Chris Lattner22eb9722006-06-18 05:43:12 +0000393
Chris Lattner69772b02006-07-02 20:34:39 +0000394/// EnterSourceFile - Add a source file to the top of the include stack and
395/// start lexing tokens from it instead of the current buffer.
396void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
397 const DirectoryLookup *CurDir) {
398
399 // Add the current lexer to the include stack.
400 if (CurLexer || CurMacroExpander)
401 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
402 CurMacroExpander));
403
404 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000405 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000406 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000407
408 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000409 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000410 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
411
412 // Get the file entry for the current file.
413 if (const FileEntry *FE =
414 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
415 FileType = getFileInfo(FE).DirInfo;
416
Chris Lattner1840e492006-07-02 22:30:01 +0000417 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000418 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000419 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000420}
421
Chris Lattner69772b02006-07-02 20:34:39 +0000422
423
Chris Lattner22eb9722006-06-18 05:43:12 +0000424/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000425/// tokens from it instead of the current buffer.
426void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000427 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000428 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000429 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
430 CurMacroExpander));
431 CurLexer = 0;
432 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000433
434 // TODO: Figure out arguments.
435
436 // Mark the macro as currently disabled, so that it is not recursively
437 // expanded.
438 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000439 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000440}
441
Chris Lattner22eb9722006-06-18 05:43:12 +0000442//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000443// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000444//===----------------------------------------------------------------------===//
445
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000446/// RegisterBuiltinMacro - Register the specified identifier in the identifier
447/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000448IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000449 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000450 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000451
452 // Mark it as being a macro that is builtin.
453 MacroInfo *MI = new MacroInfo(SourceLocation());
454 MI->setIsBuiltinMacro();
455 Id->setMacroInfo(MI);
456 return Id;
457}
458
459
Chris Lattner677757a2006-06-28 05:26:32 +0000460/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
461/// identifier table.
462void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000463 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000464 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000465 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
466 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000467 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000468
469 // GCC Extensions.
470 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
471 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000472 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000473}
474
Chris Lattner677757a2006-06-28 05:26:32 +0000475
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000476/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
477/// expanded as a macro, handle it and return the next token as 'Identifier'.
478void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
479 MacroInfo *MI) {
480 ++NumMacroExpanded;
Chris Lattner13044d92006-07-03 05:16:44 +0000481
482 // Notice that this macro has been used.
483 MI->setIsUsed(true);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000484
485 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
486 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000487 return ExpandBuiltinMacro(Identifier);
488
489 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000490 // FIXME: Fn-Like Macros: Read/Validate the argument list here!
Chris Lattner69772b02006-07-02 20:34:39 +0000491
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000492
493 // If this macro expands to no tokens, don't bother to push it onto the
494 // expansion stack, only to take it right back off.
495 if (MI->getNumTokens() == 0) {
496 // Ignore this macro use, just return the next token in the current
497 // buffer.
498 bool HadLeadingSpace = Identifier.hasLeadingSpace();
499 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
500
501 Lex(Identifier);
502
503 // If the identifier isn't on some OTHER line, inherit the leading
504 // whitespace/first-on-a-line property of this token. This handles
505 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
506 // empty.
507 if (!Identifier.isAtStartOfLine()) {
508 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
509 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
510 }
511 ++NumFastMacroExpanded;
512 return;
513
514 } else if (MI->getNumTokens() == 1 &&
515 // Don't handle identifiers if they need recursive expansion.
516 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
517 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000518 // FIXME: Fn-Like Macros: Function-style macros only if no arguments?
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000519
520 // Otherwise, if this macro expands into a single trivially-expanded
521 // token: expand it now. This handles common cases like
522 // "#define VAL 42".
523
524 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
525 // identifier to the expanded token.
526 bool isAtStartOfLine = Identifier.isAtStartOfLine();
527 bool hasLeadingSpace = Identifier.hasLeadingSpace();
528
529 // Remember where the token is instantiated.
530 SourceLocation InstantiateLoc = Identifier.getLocation();
531
532 // Replace the result token.
533 Identifier = MI->getReplacementToken(0);
534
535 // Restore the StartOfLine/LeadingSpace markers.
536 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
537 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
538
539 // Update the tokens location to include both its logical and physical
540 // locations.
541 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000542 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000543 Identifier.SetLocation(Loc);
544
545 // Since this is not an identifier token, it can't be macro expanded, so
546 // we're done.
547 ++NumFastMacroExpanded;
548 return;
549 }
550
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000551 // Start expanding the macro (FIXME: Fn-Like Macros: pass arguments).
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000552 EnterMacro(Identifier);
553
554 // Now that the macro is at the top of the include stack, ask the
555 // preprocessor to read the next token from it.
556 return Lex(Identifier);
557}
558
Chris Lattnerc673f902006-06-30 06:10:41 +0000559/// ComputeDATE_TIME - Compute the current time, enter it into the specified
560/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
561/// the identifier tokens inserted.
562static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
563 ScratchBuffer *ScratchBuf) {
564 time_t TT = time(0);
565 struct tm *TM = localtime(&TT);
566
567 static const char * const Months[] = {
568 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
569 };
570
571 char TmpBuffer[100];
572 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
573 TM->tm_year+1900);
574 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
575
576 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
577 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
578}
579
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000580/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
581/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000582void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000583 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000584 IdentifierInfo *II = Tok.getIdentifierInfo();
585 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000586
587 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
588 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000589 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000590 return Handle_Pragma(Tok);
591
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000592 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000593
594 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000595 Tok.SetIdentifierInfo(0);
596 Tok.ClearFlag(LexerToken::NeedsCleaning);
597
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000598 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000599 // __LINE__ expands to a simple numeric value.
600 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
601 unsigned Length = strlen(TmpBuffer);
602 Tok.SetKind(tok::numeric_constant);
603 Tok.SetLength(Length);
604 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000605 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000606 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000607 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000608 Diag(Tok, diag::ext_pp_base_file);
609 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
610 while (NextLoc.getFileID() != 0) {
611 Loc = NextLoc;
612 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
613 }
614 }
615
Chris Lattner0766e592006-07-03 01:07:01 +0000616 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
617 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000618 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000619 Tok.SetKind(tok::string_literal);
620 Tok.SetLength(FN.size());
621 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000622 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000623 if (!DATELoc.isValid())
624 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
625 Tok.SetKind(tok::string_literal);
626 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
627 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000628 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000629 if (!TIMELoc.isValid())
630 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
631 Tok.SetKind(tok::string_literal);
632 Tok.SetLength(strlen("\"hh:mm:ss\""));
633 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000634 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000635 Diag(Tok, diag::ext_pp_include_level);
636
637 // Compute the include depth of this token.
638 unsigned Depth = 0;
639 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
640 for (; Loc.getFileID() != 0; ++Depth)
641 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
642
643 // __INCLUDE_LEVEL__ expands to a simple numeric value.
644 sprintf(TmpBuffer, "%u", Depth);
645 unsigned Length = strlen(TmpBuffer);
646 Tok.SetKind(tok::numeric_constant);
647 Tok.SetLength(Length);
648 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000649 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000650 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
651 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
652 Diag(Tok, diag::ext_pp_timestamp);
653
654 // Get the file that we are lexing out of. If we're currently lexing from
655 // a macro, dig into the include stack.
656 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000657 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000658
659 if (TheLexer)
660 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
661
662 // If this file is older than the file it depends on, emit a diagnostic.
663 const char *Result;
664 if (CurFile) {
665 time_t TT = CurFile->getModificationTime();
666 struct tm *TM = localtime(&TT);
667 Result = asctime(TM);
668 } else {
669 Result = "??? ??? ?? ??:??:?? ????\n";
670 }
671 TmpBuffer[0] = '"';
672 strcpy(TmpBuffer+1, Result);
673 unsigned Len = strlen(TmpBuffer);
674 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
675 Tok.SetKind(tok::string_literal);
676 Tok.SetLength(Len);
677 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000678 } else {
679 assert(0 && "Unknown identifier!");
680 }
681}
Chris Lattner677757a2006-06-28 05:26:32 +0000682
Chris Lattner13044d92006-07-03 05:16:44 +0000683namespace {
684struct UnusedIdentifierReporter : public IdentifierVisitor {
685 Preprocessor &PP;
686 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
687
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000688 void VisitIdentifier(IdentifierInfo &II) const {
689 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
690 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000691 }
692};
693}
694
Chris Lattner677757a2006-06-28 05:26:32 +0000695//===----------------------------------------------------------------------===//
696// Lexer Event Handling.
697//===----------------------------------------------------------------------===//
698
699/// HandleIdentifier - This callback is invoked when the lexer reads an
700/// identifier. This callback looks up the identifier in the map and/or
701/// potentially macro expands it or turns it into a named token (like 'for').
702void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
703 if (Identifier.getIdentifierInfo() == 0) {
704 // If we are skipping tokens (because we are in a #if 0 block), there will
705 // be no identifier info, just return the token.
706 assert(isSkipping() && "Token isn't an identifier?");
707 return;
708 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000709 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000710
711 // If this identifier was poisoned, and if it was not produced from a macro
712 // expansion, emit an error.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000713 if (II.isPoisoned() && CurLexer)
Chris Lattner677757a2006-06-28 05:26:32 +0000714 Diag(Identifier, diag::err_pp_used_poisoned_id);
715
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000716 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000717 if (MI->isEnabled() && !DisableMacroExpansion)
718 return HandleMacroExpandedIdentifier(Identifier, MI);
719
720 // Change the kind of this identifier to the appropriate token kind, e.g.
721 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000722 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000723
724 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000725 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000726}
727
Chris Lattner22eb9722006-06-18 05:43:12 +0000728/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
729/// the current file. This either returns the EOF token or pops a level off
730/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000731void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000732 assert(!CurMacroExpander &&
733 "Ending a file when currently in a macro!");
734
735 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
736 // this is an error condition. Just return the EOF token up to
737 // SkipExcludedConditionalBlock. The Lexer will have already have issued
738 // errors for the unterminated #if's on the conditional stack.
739 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000740 Result.StartToken();
741 CurLexer->BufferPtr = CurLexer->BufferEnd;
742 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000743 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000744 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000745 }
746
Chris Lattner371ac8a2006-07-04 07:11:10 +0000747 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000748 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000749 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000750 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000751 // Okay, this has a controlling macro, remember in PerFileInfo.
752 if (const FileEntry *FE =
753 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
754 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +0000755 }
756 }
757
Chris Lattner22eb9722006-06-18 05:43:12 +0000758 // If this is a #include'd file, pop it off the include stack and continue
759 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000760 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000761 // We're done with the #included file.
762 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000763 CurLexer = IncludeMacroStack.back().TheLexer;
764 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
765 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
766 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000767
768 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000769 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000770 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
771
772 // Get the file entry for the current file.
773 if (const FileEntry *FE =
774 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
775 FileType = getFileInfo(FE).DirInfo;
776
Chris Lattner0c885f52006-06-21 06:50:18 +0000777 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000778 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000779 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000780
Chris Lattner22eb9722006-06-18 05:43:12 +0000781 return Lex(Result);
782 }
783
Chris Lattnerd01e2912006-06-18 16:22:51 +0000784 Result.StartToken();
785 CurLexer->BufferPtr = CurLexer->BufferEnd;
786 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000787 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000788
789 // We're done with the #included file.
790 delete CurLexer;
791 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000792
793 // This is the end of the top-level file.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000794 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +0000795}
796
797/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000798/// the current macro line.
799void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000800 assert(CurMacroExpander && !CurLexer &&
801 "Ending a macro when currently in a #include file!");
802
803 // Mark macro not ignored now that it is no longer being expanded.
804 CurMacroExpander->getMacro().EnableMacro();
805 delete CurMacroExpander;
806
Chris Lattner69772b02006-07-02 20:34:39 +0000807 // Handle this like a #include file being popped off the stack.
808 CurMacroExpander = 0;
809 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000810}
811
812
813//===----------------------------------------------------------------------===//
814// Utility Methods for Preprocessor Directive Handling.
815//===----------------------------------------------------------------------===//
816
817/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
818/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000819void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000820 LexerToken Tmp;
821 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000822 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000823 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000824}
825
826/// ReadMacroName - Lex and validate a macro name, which occurs after a
827/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattner44f8a662006-07-03 01:27:27 +0000828/// of the macro line if the macro name is invalid. isDefineUndef is true if
829/// this is due to a a #define or #undef directive, false if it is something
830/// else (e.g. #ifdef).
831void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, bool isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000832 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000833 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000834
835 // Missing macro name?
836 if (MacroNameTok.getKind() == tok::eom)
837 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
838
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000839 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
840 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000841 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000842 // Fall through on error.
843 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000844 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000845
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000846 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
847 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000848 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +0000849 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000850 } else if (isDefineUndef && II->getMacroInfo() &&
851 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000852 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
853 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +0000854 } else {
855 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000856 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000857 }
858
Chris Lattner22eb9722006-06-18 05:43:12 +0000859 // Invalid macro name, read and discard the rest of the line. Then set the
860 // token kind to tok::eom.
861 MacroNameTok.SetKind(tok::eom);
862 return DiscardUntilEndOfDirective();
863}
864
865/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
866/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000867void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000868 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000869 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000870 // There should be no tokens after the directive, but we allow them as an
871 // extension.
872 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000873 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
874 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000875 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000876}
877
878
879
880/// SkipExcludedConditionalBlock - We just read a #if or related directive and
881/// decided that the subsequent tokens are in the #if'd out portion of the
882/// file. Lex the rest of the file, until we see an #endif. If
883/// FoundNonSkipPortion is true, then we have already emitted code for part of
884/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
885/// is true, then #else directives are ok, if not, then we have already seen one
886/// so a #else directive is a duplicate. When this returns, the caller can lex
887/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000888void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000889 bool FoundNonSkipPortion,
890 bool FoundElse) {
891 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000892 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000893 "Lexing a macro, not a file?");
894
895 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
896 FoundNonSkipPortion, FoundElse);
897
898 // Know that we are going to be skipping tokens. Set this flag to indicate
899 // this, which has a couple of effects:
900 // 1. If EOF of the current lexer is found, the include stack isn't popped.
901 // 2. Identifier information is not looked up for identifier tokens. As an
902 // effect of this, implicit macro expansion is naturally disabled.
903 // 3. "#" tokens at the start of a line are treated as normal tokens, not
904 // implicitly transformed by the lexer.
905 // 4. All notes, warnings, and extension messages are disabled.
906 //
907 SkippingContents = true;
908 LexerToken Tok;
909 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000910 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000911
912 // If this is the end of the buffer, we have an error. The lexer will have
913 // already handled this error condition, so just return and let the caller
914 // lex after this #include.
915 if (Tok.getKind() == tok::eof) break;
916
917 // If this token is not a preprocessor directive, just skip it.
918 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
919 continue;
920
921 // We just parsed a # character at the start of a line, so we're in
922 // directive mode. Tell the lexer this so any newlines we see will be
923 // converted into an EOM token (this terminates the macro).
924 CurLexer->ParsingPreprocessorDirective = true;
925
926 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000927 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000928
929 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
930 // something bogus), skip it.
931 if (Tok.getKind() != tok::identifier) {
932 CurLexer->ParsingPreprocessorDirective = false;
933 continue;
934 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000935
Chris Lattner22eb9722006-06-18 05:43:12 +0000936 // If the first letter isn't i or e, it isn't intesting to us. We know that
937 // this is safe in the face of spelling differences, because there is no way
938 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000939 // allows us to avoid looking up the identifier info for #define/#undef and
940 // other common directives.
941 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
942 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000943 if (FirstChar >= 'a' && FirstChar <= 'z' &&
944 FirstChar != 'i' && FirstChar != 'e') {
945 CurLexer->ParsingPreprocessorDirective = false;
946 continue;
947 }
948
Chris Lattnere60165f2006-06-22 06:36:29 +0000949 // Get the identifier name without trigraphs or embedded newlines. Note
950 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
951 // when skipping.
952 // TODO: could do this with zero copies in the no-clean case by using
953 // strncmp below.
954 char Directive[20];
955 unsigned IdLen;
956 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
957 IdLen = Tok.getLength();
958 memcpy(Directive, RawCharData, IdLen);
959 Directive[IdLen] = 0;
960 } else {
961 std::string DirectiveStr = getSpelling(Tok);
962 IdLen = DirectiveStr.size();
963 if (IdLen >= 20) {
964 CurLexer->ParsingPreprocessorDirective = false;
965 continue;
966 }
967 memcpy(Directive, &DirectiveStr[0], IdLen);
968 Directive[IdLen] = 0;
969 }
970
Chris Lattner22eb9722006-06-18 05:43:12 +0000971 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000972 if ((IdLen == 2) || // "if"
973 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
974 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000975 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
976 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000977 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000978 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000979 /*foundnonskip*/false,
980 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000981 }
982 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000983 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000984 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000985 PPConditionalInfo CondInfo;
986 CondInfo.WasSkipping = true; // Silence bogus warning.
987 bool InCond = CurLexer->popConditionalLevel(CondInfo);
988 assert(!InCond && "Can't be skipping if not in a conditional!");
989
990 // If we popped the outermost skipping block, we're done skipping!
991 if (!CondInfo.WasSkipping)
992 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000993 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000994 // #else directive in a skipping conditional. If not in some other
995 // skipping conditional, and if #else hasn't already been seen, enter it
996 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000997 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000998 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
999
1000 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001001 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001002
1003 // Note that we've seen a #else in this conditional.
1004 CondInfo.FoundElse = true;
1005
1006 // If the conditional is at the top level, and the #if block wasn't
1007 // entered, enter the #else block now.
1008 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1009 CondInfo.FoundNonSkip = true;
1010 break;
1011 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001012 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001013 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1014
1015 bool ShouldEnter;
1016 // If this is in a skipping block or if we're already handled this #if
1017 // block, don't bother parsing the condition.
1018 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001019 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001020 ShouldEnter = false;
1021 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001022 // Restore the value of SkippingContents so that identifiers are
1023 // looked up, etc, inside the #elif expression.
1024 assert(SkippingContents && "We have to be skipping here!");
1025 SkippingContents = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001026 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001027 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001028 SkippingContents = true;
1029 }
1030
1031 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001032 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001033
1034 // If this condition is true, enter it!
1035 if (ShouldEnter) {
1036 CondInfo.FoundNonSkip = true;
1037 break;
1038 }
1039 }
1040 }
1041
1042 CurLexer->ParsingPreprocessorDirective = false;
1043 }
1044
1045 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1046 // of the file, just stop skipping and return to lexing whatever came after
1047 // the #if block.
1048 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001049}
1050
1051//===----------------------------------------------------------------------===//
1052// Preprocessor Directive Handling.
1053//===----------------------------------------------------------------------===//
1054
1055/// HandleDirective - This callback is invoked when the lexer sees a # token
1056/// at the start of a line. This consumes the directive, modifies the
1057/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1058/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001059void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001060 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001061
1062 // We just parsed a # character at the start of a line, so we're in directive
1063 // mode. Tell the lexer this so any newlines we see will be converted into an
1064 // EOM token (this terminates the macro).
1065 CurLexer->ParsingPreprocessorDirective = true;
1066
1067 ++NumDirectives;
1068
Chris Lattner371ac8a2006-07-04 07:11:10 +00001069 // We are about to read a token. For the multiple-include optimization FA to
1070 // work, we have to remember if we had read any tokens *before* this
1071 // pp-directive.
1072 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1073
Chris Lattner22eb9722006-06-18 05:43:12 +00001074 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001075 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001076
1077 switch (Result.getKind()) {
1078 default: break;
1079 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001080 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001081
1082#if 0
1083 case tok::numeric_constant:
1084 // FIXME: implement # 7 line numbers!
1085 break;
1086#endif
1087 case tok::kw_else:
1088 return HandleElseDirective(Result);
1089 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001090 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001092 // Get the identifier name without trigraphs or embedded newlines.
1093 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001095 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001096 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001097 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001098 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001099 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001101 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1102 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 break;
1104 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001105 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001107 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001108 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001109 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001110 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001111 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001113 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001114 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 break;
1116 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001117 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001119 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001120 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001121 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001122 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001123 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001124 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001125 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1126 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001127 break;
1128 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001129 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1130 return HandleIncludeDirective(Result); // Handle #include.
1131 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001132 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001133 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001134 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 break;
1136 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001137 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001138 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001139 }
1140 break;
1141 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001142 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1143 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001144 break;
1145 }
1146 break;
1147 }
1148
1149 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001150 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001151
1152 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001153 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001154
1155 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001156}
1157
Chris Lattner01d66cc2006-07-03 22:16:27 +00001158void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001159 bool isWarning) {
1160 // Read the rest of the line raw. We do this because we don't want macros
1161 // to be expanded and we don't require that the tokens be valid preprocessing
1162 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1163 // collapse multiple consequtive white space between tokens, but this isn't
1164 // specified by the standard.
1165 std::string Message = CurLexer->ReadToEndOfLine();
1166
1167 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001168 return Diag(Tok, DiagID, Message);
1169}
1170
1171/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1172///
1173void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001174 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001175 Diag(Tok, diag::ext_pp_ident_directive);
1176
Chris Lattner371ac8a2006-07-04 07:11:10 +00001177 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001178 LexerToken StrTok;
1179 Lex(StrTok);
1180
1181 // If the token kind isn't a string, it's a malformed directive.
1182 if (StrTok.getKind() != tok::string_literal)
1183 return Diag(StrTok, diag::err_pp_malformed_ident);
1184
1185 // Verify that there is nothing after the string, other than EOM.
1186 CheckEndOfDirective("#ident");
1187
1188 if (IdentHandler)
1189 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001190}
1191
Chris Lattnerb8761832006-06-24 21:31:03 +00001192//===----------------------------------------------------------------------===//
1193// Preprocessor Include Directive Handling.
1194//===----------------------------------------------------------------------===//
1195
Chris Lattner22eb9722006-06-18 05:43:12 +00001196/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1197/// file to be included from the lexer, then include it! This is a common
1198/// routine with functionality shared between #include, #include_next and
1199/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001200void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001201 const DirectoryLookup *LookupFrom,
1202 bool isImport) {
1203 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001204
Chris Lattner22eb9722006-06-18 05:43:12 +00001205 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001206 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001207
1208 // If the token kind is EOM, the error has already been diagnosed.
1209 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001210 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001211
1212 // Verify that there is nothing after the filename, other than EOM. Use the
1213 // preprocessor to lex this in case lexing the filename entered a macro.
1214 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001215
1216 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001217 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001218 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1219
Chris Lattner269c2322006-06-25 06:23:00 +00001220 // Find out whether the filename is <x> or "x".
1221 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001222
1223 // Remove the quotes.
1224 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1225
Chris Lattner22eb9722006-06-18 05:43:12 +00001226 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001227 const DirectoryLookup *CurDir;
1228 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001229 if (File == 0)
1230 return Diag(FilenameTok, diag::err_pp_file_not_found);
1231
1232 // Get information about this file.
1233 PerFileInfo &FileInfo = getFileInfo(File);
1234
1235 // If this is a #import directive, check that we have not already imported
1236 // this header.
1237 if (isImport) {
1238 // If this has already been imported, don't import it again.
1239 FileInfo.isImport = true;
1240
1241 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001242 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001243 } else {
1244 // Otherwise, if this is a #include of a file that was previously #import'd
1245 // or if this is the second #include of a #pragma once file, ignore it.
1246 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001247 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001248 }
Chris Lattner3665f162006-07-04 07:26:10 +00001249
1250 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1251 // if the macro that guards it is defined, we know the #include has no effect.
1252 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1253 ++NumMultiIncludeFileOptzn;
1254 return;
1255 }
1256
Chris Lattner22eb9722006-06-18 05:43:12 +00001257
1258 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001259 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001260 if (FileID == 0)
1261 return Diag(FilenameTok, diag::err_pp_file_not_found);
1262
1263 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001264 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001265
1266 // Increment the number of times this file has been included.
1267 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001268}
1269
1270/// HandleIncludeNextDirective - Implements #include_next.
1271///
Chris Lattnercb283342006-06-18 06:48:37 +00001272void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1273 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001274
1275 // #include_next is like #include, except that we start searching after
1276 // the current found directory. If we can't do this, issue a
1277 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001278 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001279 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001280 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001281 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001282 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001283 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001284 } else {
1285 // Start looking up in the next directory.
1286 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 }
1288
1289 return HandleIncludeDirective(IncludeNextTok, Lookup);
1290}
1291
1292/// HandleImportDirective - Implements #import.
1293///
Chris Lattnercb283342006-06-18 06:48:37 +00001294void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1295 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001296
1297 return HandleIncludeDirective(ImportTok, 0, true);
1298}
1299
Chris Lattnerb8761832006-06-24 21:31:03 +00001300//===----------------------------------------------------------------------===//
1301// Preprocessor Macro Directive Handling.
1302//===----------------------------------------------------------------------===//
1303
Chris Lattner22eb9722006-06-18 05:43:12 +00001304/// HandleDefineDirective - Implements #define. This consumes the entire macro
1305/// line then lets the caller lex the next real token.
1306///
Chris Lattnercb283342006-06-18 06:48:37 +00001307void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001308 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001309
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001311 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001312
1313 // Error reading macro name? If so, diagnostic already issued.
1314 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001315 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001316
Chris Lattner50b497e2006-06-18 16:32:35 +00001317 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001318
1319 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001320 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001321
1322 if (Tok.getKind() == tok::eom) {
1323 // If there is no body to this macro, we have no special handling here.
1324 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1325 // This is a function-like macro definition.
1326 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 return DiscardUntilEndOfDirective();
1328
1329 } else if (!Tok.hasLeadingSpace()) {
1330 // C99 requires whitespace between the macro definition and the body. Emit
1331 // a diagnostic for something like "#define X+".
1332 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001333 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 } else {
1335 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1336 // one in some cases!
1337 }
1338 } else {
1339 // This is a normal token with leading space. Clear the leading space
1340 // marker on the first token to get proper expansion.
1341 Tok.ClearFlag(LexerToken::LeadingSpace);
1342 }
1343
1344 // Read the rest of the macro body.
1345 while (Tok.getKind() != tok::eom) {
1346 MI->AddTokenToBody(Tok);
1347
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001348 // FIXME: Read macro body. See create_iso_definition.
Chris Lattner22eb9722006-06-18 05:43:12 +00001349
1350 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001351 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 }
1353
Chris Lattner13044d92006-07-03 05:16:44 +00001354 // If this is the primary source file, remember that this macro hasn't been
1355 // used yet.
1356 if (isInPrimaryFile())
1357 MI->setIsUsed(false);
1358
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 // Finally, if this identifier already had a macro defined for it, verify that
1360 // the macro bodies are identical and free the old definition.
1361 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001362 if (!OtherMI->isUsed())
1363 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1364
Chris Lattner22eb9722006-06-18 05:43:12 +00001365 // FIXME: Verify the definition is the same.
1366 // Macros must be identical. This means all tokes and whitespace separation
1367 // must be the same.
1368 delete OtherMI;
1369 }
1370
1371 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001372}
1373
1374
1375/// HandleUndefDirective - Implements #undef.
1376///
Chris Lattnercb283342006-06-18 06:48:37 +00001377void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001378 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001379
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001381 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001382
1383 // Error reading macro name? If so, diagnostic already issued.
1384 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001385 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001386
1387 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001388 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001389
1390 // Okay, we finally have a valid identifier to undef.
1391 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1392
1393 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001394 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001395
Chris Lattner13044d92006-07-03 05:16:44 +00001396 if (!MI->isUsed())
1397 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001398
1399 // Free macro definition.
1400 delete MI;
1401 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001402}
1403
1404
Chris Lattnerb8761832006-06-24 21:31:03 +00001405//===----------------------------------------------------------------------===//
1406// Preprocessor Conditional Directive Handling.
1407//===----------------------------------------------------------------------===//
1408
Chris Lattner22eb9722006-06-18 05:43:12 +00001409/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001410/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1411/// if any tokens have been returned or pp-directives activated before this
1412/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001413///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001414void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1415 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 ++NumIf;
1417 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001418
Chris Lattner22eb9722006-06-18 05:43:12 +00001419 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001420 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001421
1422 // Error reading macro name? If so, diagnostic already issued.
1423 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001424 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001425
1426 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001427 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1428
1429 // If the start of a top-level #ifdef, inform MIOpt.
1430 if (!ReadAnyTokensBeforeDirective &&
1431 CurLexer->getConditionalStackDepth() == 0) {
1432 assert(isIfndef && "#ifdef shouldn't reach here");
1433 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1434 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001435
Chris Lattnera78a97e2006-07-03 05:42:18 +00001436 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1437
1438 // If there is a macro, mark it used.
1439 if (MI) MI->setIsUsed(true);
1440
Chris Lattner22eb9722006-06-18 05:43:12 +00001441 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001442 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001443 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001444 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001445 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001446 } else {
1447 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001448 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001449 /*Foundnonskip*/false,
1450 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001451 }
1452}
1453
1454/// HandleIfDirective - Implements the #if directive.
1455///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001456void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1457 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001458 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001459
Chris Lattner371ac8a2006-07-04 07:11:10 +00001460 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001461 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001462 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001463
1464 // Should we include the stuff contained by this directive?
1465 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001466 // If this condition is equivalent to #ifndef X, and if this is the first
1467 // directive seen, handle it for the multiple-include optimization.
1468 if (!ReadAnyTokensBeforeDirective &&
1469 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1470 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1471
Chris Lattner22eb9722006-06-18 05:43:12 +00001472 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001473 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001474 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001475 } else {
1476 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001477 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001478 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001479 }
1480}
1481
1482/// HandleEndifDirective - Implements the #endif directive.
1483///
Chris Lattnercb283342006-06-18 06:48:37 +00001484void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001485 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001486
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001488 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001489
1490 PPConditionalInfo CondInfo;
1491 if (CurLexer->popConditionalLevel(CondInfo)) {
1492 // No conditionals on the stack: this is an #endif without an #if.
1493 return Diag(EndifToken, diag::err_pp_endif_without_if);
1494 }
1495
Chris Lattner371ac8a2006-07-04 07:11:10 +00001496 // If this the end of a top-level #endif, inform MIOpt.
1497 if (CurLexer->getConditionalStackDepth() == 0)
1498 CurLexer->MIOpt.ExitTopLevelConditional();
1499
Chris Lattner22eb9722006-06-18 05:43:12 +00001500 assert(!CondInfo.WasSkipping && !isSkipping() &&
1501 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001502}
1503
1504
Chris Lattnercb283342006-06-18 06:48:37 +00001505void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001507
Chris Lattner22eb9722006-06-18 05:43:12 +00001508 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001509 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001510
1511 PPConditionalInfo CI;
1512 if (CurLexer->popConditionalLevel(CI))
1513 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001514
1515 // If this is a top-level #else, inform the MIOpt.
1516 if (CurLexer->getConditionalStackDepth() == 0)
1517 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001518
1519 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001520 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001521
1522 // Finally, skip the rest of the contents of this block and return the first
1523 // token after it.
1524 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1525 /*FoundElse*/true);
1526}
1527
Chris Lattnercb283342006-06-18 06:48:37 +00001528void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001529 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001530
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 // #elif directive in a non-skipping conditional... start skipping.
1532 // We don't care what the condition is, because we will always skip it (since
1533 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001534 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001535
1536 PPConditionalInfo CI;
1537 if (CurLexer->popConditionalLevel(CI))
1538 return Diag(ElifToken, diag::pp_err_elif_without_if);
1539
Chris Lattner371ac8a2006-07-04 07:11:10 +00001540 // If this is a top-level #elif, inform the MIOpt.
1541 if (CurLexer->getConditionalStackDepth() == 0)
1542 CurLexer->MIOpt.FoundTopLevelElse();
1543
Chris Lattner22eb9722006-06-18 05:43:12 +00001544 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001545 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001546
1547 // Finally, skip the rest of the contents of this block and return the first
1548 // token after it.
1549 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1550 /*FoundElse*/CI.FoundElse);
1551}
Chris Lattnerb8761832006-06-24 21:31:03 +00001552