blob: ce4a7ffb8cfd45249812623d4ee23cf7e9ca066d [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//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
16// -C -CC - Do not discard comments for cpp.
Chris Lattner22eb9722006-06-18 05:43:12 +000017// -d[MDNI] - Dump various things.
18// -fworking-directory - #line's with preprocessor's working dir.
19// -fpreprocessed
20// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
21// -W*
22// -w
23//
24// Messages to emit:
25// "Multiple include guards may be useful for:\n"
26//
Chris Lattner22eb9722006-06-18 05:43:12 +000027//===----------------------------------------------------------------------===//
28
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000031#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000032#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include "clang/Basic/Diagnostic.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
36#include <iostream>
37using namespace llvm;
38using namespace clang;
39
40//===----------------------------------------------------------------------===//
41
42Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
43 FileManager &FM, SourceManager &SM)
44 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
45 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000046 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000047 ScratchBuf = new ScratchBuffer(SourceMgr);
48
Chris Lattner22eb9722006-06-18 05:43:12 +000049 // Clear stats.
50 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
51 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000052 NumEnteredSourceFiles = 0;
53 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
54 NumFastMacroExpanded = 0;
Chris Lattner3665f162006-07-04 07:26:10 +000055 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000057
Chris Lattner22eb9722006-06-18 05:43:12 +000058 // Macro expansion is enabled.
59 DisableMacroExpansion = false;
Chris Lattner78186052006-07-09 00:45:31 +000060 InMacroFormalArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
62 // There is no file-change handler yet.
63 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000064 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000065
Chris Lattner8ff71992006-07-06 05:17:39 +000066 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
67 // This gets unpoisoned where it is allowed.
68 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
69
Chris Lattnerb8761832006-06-24 21:31:03 +000070 // 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
Chris Lattner78186052006-07-09 00:45:31 +0000198 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
199 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000200 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000201}
202
203//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000204// Token Spelling
205//===----------------------------------------------------------------------===//
206
207
208/// getSpelling() - Return the 'spelling' of this token. The spelling of a
209/// token are the characters used to represent the token in the source file
210/// after trigraph expansion and escaped-newline folding. In particular, this
211/// wants to get the true, uncanonicalized, spelling of things like digraphs
212/// UCNs, etc.
213std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
214 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
215
216 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000217 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 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 Lattnerd3a15f72006-07-04 23:01:03 +0000250 // If this token is an identifier, just return the string from the identifier
251 // table, which is very quick.
252 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
253 Buffer = II->getName();
254 return Tok.getLength();
255 }
256
257 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000258 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000259
260 // If this token contains nothing interesting, return it directly.
261 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000262 Buffer = TokStart;
263 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000264 }
265 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000266 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000267 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
268 Ptr != End; ) {
269 unsigned CharSize;
270 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
271 Ptr += CharSize;
272 }
273 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
274 "NeedsCleaning flag set on something that didn't need cleaning!");
275
276 return OutBuf-Buffer;
277}
278
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000279
280/// CreateString - Plop the specified string into a scratch buffer and return a
281/// location for it. If specified, the source location provides a source
282/// location for the token.
283SourceLocation Preprocessor::
284CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
285 if (SLoc.isValid())
286 return ScratchBuf->getToken(Buf, Len, SLoc);
287 return ScratchBuf->getToken(Buf, Len);
288}
289
290
Chris Lattnerd01e2912006-06-18 16:22:51 +0000291//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000292// Source File Location Methods.
293//===----------------------------------------------------------------------===//
294
295
296/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
297/// return null on failure. isAngled indicates whether the file reference is
298/// for system #include's or not (i.e. using <> instead of "").
299const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000300 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000301 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000302 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000303 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000304 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000305
306 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000307 // FIXME: Portability. This should be a sys::Path interface, this doesn't
308 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000309 if (Filename[0] == '/') {
310 // If this was an #include_next "/absolute/file", fail.
311 if (FromDir) return 0;
312
313 // Otherwise, just return the file.
314 return FileMgr.getFile(Filename);
315 }
316
317 // Step #0, unless disabled, check to see if the file is in the #includer's
318 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000319 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000320 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
321 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000322 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000323 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000324 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000325 if (const FileEntry *FE =
326 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000327 if (CurDirLookup)
328 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000329 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000330 CurDir = 0;
331
332 // This file is a system header or C++ unfriendly if the old file is.
333 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000334 return FE;
335 }
336 }
337 }
338
339 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000340 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000341
342 // If this is a #include_next request, start searching after the directory the
343 // file was found in.
344 if (FromDir)
345 i = FromDir-&SearchDirs[0];
346
347 // Check each directory in sequence to see if it contains this file.
348 for (; i != SearchDirs.size(); ++i) {
349 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000350 // FIXME: Portability. Adding file to dir should be in sys::Path.
351 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
352 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000353 CurDir = &SearchDirs[i];
354
355 // This file is a system header or C++ unfriendly if the dir is.
356 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000357 return FE;
358 }
359 }
360
361 // Otherwise, didn't find it.
362 return 0;
363}
364
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000365/// isInPrimaryFile - Return true if we're in the top-level file, not in a
366/// #include.
367bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000369 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000370
Chris Lattner13044d92006-07-03 05:16:44 +0000371 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000372 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000373 if (IncludeMacroStack[i].TheLexer &&
374 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
375 return IncludeMacroStack[i].TheLexer->isMainFile();
376 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000377}
378
379/// getCurrentLexer - Return the current file lexer being lexed from. Note
380/// that this ignores any potentially active macro expansions and _Pragma
381/// expansions going on at the time.
382Lexer *Preprocessor::getCurrentFileLexer() const {
383 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
384
385 // Look for a stacked lexer.
386 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000387 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000388 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
389 return L;
390 }
391 return 0;
392}
393
394
Chris Lattner22eb9722006-06-18 05:43:12 +0000395/// EnterSourceFile - Add a source file to the top of the include stack and
396/// start lexing tokens from it instead of the current buffer. Return true
397/// on failure.
398void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000399 const DirectoryLookup *CurDir,
400 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000401 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000402 ++NumEnteredSourceFiles;
403
Chris Lattner69772b02006-07-02 20:34:39 +0000404 if (MaxIncludeStackDepth < IncludeMacroStack.size())
405 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000406
Chris Lattner22eb9722006-06-18 05:43:12 +0000407 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000408 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000409 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000410 EnterSourceFileWithLexer(TheLexer, CurDir);
411}
Chris Lattner22eb9722006-06-18 05:43:12 +0000412
Chris Lattner69772b02006-07-02 20:34:39 +0000413/// EnterSourceFile - Add a source file to the top of the include stack and
414/// start lexing tokens from it instead of the current buffer.
415void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
416 const DirectoryLookup *CurDir) {
417
418 // Add the current lexer to the include stack.
419 if (CurLexer || CurMacroExpander)
420 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
421 CurMacroExpander));
422
423 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000424 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000425 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000426
427 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000428 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000429 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
430
431 // Get the file entry for the current file.
432 if (const FileEntry *FE =
433 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
434 FileType = getFileInfo(FE).DirInfo;
435
Chris Lattner1840e492006-07-02 22:30:01 +0000436 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000437 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000438 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000439}
440
Chris Lattner69772b02006-07-02 20:34:39 +0000441
442
Chris Lattner22eb9722006-06-18 05:43:12 +0000443/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000444/// tokens from it instead of the current buffer.
Chris Lattner78186052006-07-09 00:45:31 +0000445void Preprocessor::EnterMacro(LexerToken &Tok, MacroFormalArgs *Formals) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000446 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000447 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000448 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
449 CurMacroExpander));
450 CurLexer = 0;
451 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000452
Chris Lattner22eb9722006-06-18 05:43:12 +0000453 // Mark the macro as currently disabled, so that it is not recursively
454 // expanded.
455 MI.DisableMacro();
Chris Lattner78186052006-07-09 00:45:31 +0000456 CurMacroExpander = new MacroExpander(Tok, Formals, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000457}
458
Chris Lattner22eb9722006-06-18 05:43:12 +0000459//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000460// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000461//===----------------------------------------------------------------------===//
462
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000463/// RegisterBuiltinMacro - Register the specified identifier in the identifier
464/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000465IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000466 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000467 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000468
469 // Mark it as being a macro that is builtin.
470 MacroInfo *MI = new MacroInfo(SourceLocation());
471 MI->setIsBuiltinMacro();
472 Id->setMacroInfo(MI);
473 return Id;
474}
475
476
Chris Lattner677757a2006-06-28 05:26:32 +0000477/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
478/// identifier table.
479void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000480 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000481 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000482 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
483 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000484 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000485
486 // GCC Extensions.
487 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
488 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000489 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000490}
491
Chris Lattnerc2395832006-07-09 00:57:04 +0000492/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
493/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000494static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
495 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000496 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
497
498 // If the token isn't an identifier, it's always literally expanded.
499 if (II == 0) return true;
500
501 // If the identifier is a macro, and if that macro is enabled, it may be
502 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000503 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
504 // Fast expanding "#define X X" is ok, because X would be disabled.
505 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000506 return false;
507
508 // If this is an object-like macro invocation, it is safe to trivially expand
509 // it.
510 if (MI->isObjectLike()) return true;
511
512 // If this is a function-like macro invocation, it's safe to trivially expand
513 // as long as the identifier is not a macro argument.
514 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
515 I != E; ++I)
516 if (*I == II)
517 return false; // Identifier is a macro argument.
518 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000519}
520
Chris Lattnerc2395832006-07-09 00:57:04 +0000521
Chris Lattnerafe603f2006-07-11 04:02:46 +0000522/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
523/// lexed is a '('. If so, consume the token and return true, if not, this
524/// method should have no observable side-effect on the lexed tokens.
525bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000526 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000527 unsigned Val;
528 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000529 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000530 else
531 Val = CurMacroExpander->isNextTokenLParen();
532
533 if (Val == 2) {
534 // If we ran off the end of the lexer or macro expander, walk the include
535 // stack, looking for whatever will return the next token.
536 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
537 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
538 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000539 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000540 else
541 Val = Entry.TheMacroExpander->isNextTokenLParen();
542 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000543 }
544
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000545 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
546 // have found something that isn't a '(' or we found the end of the
547 // translation unit. In either case, return false.
548 if (Val != 1)
549 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000550
551 LexerToken Tok;
552 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000553 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
554 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000555}
Chris Lattner677757a2006-06-28 05:26:32 +0000556
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000557/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
558/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000559bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000560 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000561
562 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
563 if (MI->isBuiltinMacro()) {
564 ExpandBuiltinMacro(Identifier);
565 return false;
566 }
567
568 /// FormalArgs - If this is a function-like macro expansion, this contains,
569 /// for each macro argument, the list of tokens that were provided to the
570 /// invocation.
571 MacroFormalArgs *FormalArgs = 0;
572
573 // If this is a function-like macro, read the arguments.
574 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000575 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
576 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000577 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000578 return true;
579
Chris Lattner78186052006-07-09 00:45:31 +0000580 // Remember that we are now parsing the arguments to a macro invocation.
581 // Preprocessor directives used inside macro arguments are not portable, and
582 // this enables the warning.
583 InMacroFormalArgs = true;
584 FormalArgs = ReadFunctionLikeMacroFormalArgs(Identifier, MI);
585
586 // Finished parsing args.
587 InMacroFormalArgs = false;
588
589 // If there was an error parsing the arguments, bail out.
590 if (FormalArgs == 0) return false;
591
592 ++NumFnMacroExpanded;
593 } else {
594 ++NumMacroExpanded;
595 }
Chris Lattner13044d92006-07-03 05:16:44 +0000596
597 // Notice that this macro has been used.
598 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000599
600 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000601
602 // If this macro expands to no tokens, don't bother to push it onto the
603 // expansion stack, only to take it right back off.
604 if (MI->getNumTokens() == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000605 // No need for formal arg info.
606 delete FormalArgs;
607
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000608 // Ignore this macro use, just return the next token in the current
609 // buffer.
610 bool HadLeadingSpace = Identifier.hasLeadingSpace();
611 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
612
613 Lex(Identifier);
614
615 // If the identifier isn't on some OTHER line, inherit the leading
616 // whitespace/first-on-a-line property of this token. This handles
617 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
618 // empty.
619 if (!Identifier.isAtStartOfLine()) {
620 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
621 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
622 }
623 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000624 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000625
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000626 } else if (MI->getNumTokens() == 1 &&
627 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000628 // Otherwise, if this macro expands into a single trivially-expanded
629 // token: expand it now. This handles common cases like
630 // "#define VAL 42".
631
632 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
633 // identifier to the expanded token.
634 bool isAtStartOfLine = Identifier.isAtStartOfLine();
635 bool hasLeadingSpace = Identifier.hasLeadingSpace();
636
637 // Remember where the token is instantiated.
638 SourceLocation InstantiateLoc = Identifier.getLocation();
639
640 // Replace the result token.
641 Identifier = MI->getReplacementToken(0);
642
643 // Restore the StartOfLine/LeadingSpace markers.
644 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
645 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
646
647 // Update the tokens location to include both its logical and physical
648 // locations.
649 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000650 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000651 Identifier.SetLocation(Loc);
652
653 // Since this is not an identifier token, it can't be macro expanded, so
654 // we're done.
655 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000656 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000657 }
658
Chris Lattner78186052006-07-09 00:45:31 +0000659 // Start expanding the macro.
660 EnterMacro(Identifier, FormalArgs);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000661
662 // Now that the macro is at the top of the include stack, ask the
663 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000664 Lex(Identifier);
665 return false;
666}
667
668/// ReadFunctionLikeMacroFormalArgs - After reading "MACRO(", this method is
669/// invoked to read all of the formal arguments specified for the macro
670/// invocation. This returns null on error.
671MacroFormalArgs *Preprocessor::
672ReadFunctionLikeMacroFormalArgs(LexerToken &MacroName, MacroInfo *MI) {
673 // Use an auto_ptr here so that the MacroFormalArgs object is deleted on
674 // all error paths.
675 std::auto_ptr<MacroFormalArgs> Args(new MacroFormalArgs(MI));
676
677 // The number of fixed arguments to parse.
678 unsigned NumFixedArgsLeft = MI->getNumArgs();
679 bool isVariadic = MI->isVariadic();
680
681 // If this is a C99-style varargs macro invocation, add an extra expected
682 // argument, which will catch all of the varargs formals in one argument.
683 if (MI->isC99Varargs())
684 ++NumFixedArgsLeft;
685
686 // Outer loop, while there are more arguments, keep reading them.
687 LexerToken Tok;
688 Tok.SetKind(tok::comma);
689 --NumFixedArgsLeft; // Start reading the first arg.
690
691 while (Tok.getKind() == tok::comma) {
692 // ArgTokens - Build up a list of tokens that make up this argument.
693 std::vector<LexerToken> ArgTokens;
694 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
695 unsigned NumParens = 0;
696
697 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000698 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
699 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000700 LexUnexpandedToken(Tok);
701
702 if (Tok.getKind() == tok::eof) {
703 Diag(MacroName, diag::err_unterm_macro_invoc);
704 // Do not lose the EOF. Return it to the client.
705 MacroName = Tok;
706 return 0;
707 } else if (Tok.getKind() == tok::r_paren) {
708 // If we found the ) token, the macro arg list is done.
709 if (NumParens-- == 0)
710 break;
711 } else if (Tok.getKind() == tok::l_paren) {
712 ++NumParens;
713 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
714 // Comma ends this argument if there are more fixed arguments expected.
715 if (NumFixedArgsLeft)
716 break;
717
718 // If this is not a variadic macro, too many formals were specified.
719 if (!isVariadic) {
720 // Emit the diagnostic at the macro name in case there is a missing ).
721 // Emitting it at the , could be far away from the macro name.
722 Diag(MacroName, diag::err_too_many_formals_in_macro_invoc);
723 return 0;
724 }
725 // Otherwise, continue to add the tokens to this variable argument.
726 }
727
728 ArgTokens.push_back(Tok);
729 }
730
Chris Lattnera12dd152006-07-11 04:09:02 +0000731 // Empty arguments are standard in C99 and supported as an extension in
732 // other modes.
733 if (ArgTokens.empty() && !Features.C99)
734 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000735
Chris Lattner78186052006-07-09 00:45:31 +0000736 // Remember the tokens that make up this argument. This destroys ArgTokens.
737 Args->addArgument(ArgTokens);
738 --NumFixedArgsLeft;
739 };
740
741 // Okay, we either found the r_paren. Check to see if we parsed too few
742 // arguments.
743 unsigned NumFormals = Args->getNumArguments();
744 unsigned MinArgsExpected = MI->getNumArgs();
745
746 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000747 // don't require this). GNU-style varargs already include the 'rest' name in
748 // the count.
749 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000750
751 if (NumFormals < MinArgsExpected) {
752 // There are several cases where too few arguments is ok, handle them now.
753 if (NumFormals+1 == MinArgsExpected && MI->isVariadic()) {
754 // Varargs where the named vararg parameter is missing: ok as extension.
755 // #define A(x, ...)
756 // A("blah")
757 Diag(Tok, diag::ext_missing_varargs_arg);
758 } else if (MI->getNumArgs() == 1) {
759 // #define A(x)
760 // A()
Chris Lattnerafe603f2006-07-11 04:02:46 +0000761 // is ok because it is an empty argument. Add it explicitly.
Chris Lattner78186052006-07-09 00:45:31 +0000762 std::vector<LexerToken> ArgTokens;
763 Args->addArgument(ArgTokens);
Chris Lattnera12dd152006-07-11 04:09:02 +0000764
765 // Empty arguments are standard in C99 and supported as an extension in
766 // other modes.
767 if (ArgTokens.empty() && !Features.C99)
768 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000769 } else {
770 // Otherwise, emit the error.
771 Diag(Tok, diag::err_too_few_formals_in_macro_invoc);
772 return 0;
773 }
774 }
775
776 return Args.release();
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000777}
778
Chris Lattnerc673f902006-06-30 06:10:41 +0000779/// ComputeDATE_TIME - Compute the current time, enter it into the specified
780/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
781/// the identifier tokens inserted.
782static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000783 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000784 time_t TT = time(0);
785 struct tm *TM = localtime(&TT);
786
787 static const char * const Months[] = {
788 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
789 };
790
791 char TmpBuffer[100];
792 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
793 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000794 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000795
796 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000797 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000798}
799
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000800/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
801/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000802void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000803 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000804 IdentifierInfo *II = Tok.getIdentifierInfo();
805 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000806
807 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
808 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000809 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000810 return Handle_Pragma(Tok);
811
Chris Lattner78186052006-07-09 00:45:31 +0000812 ++NumBuiltinMacroExpanded;
813
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000814 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000815
816 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000817 Tok.SetIdentifierInfo(0);
818 Tok.ClearFlag(LexerToken::NeedsCleaning);
819
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000820 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000821 // __LINE__ expands to a simple numeric value.
822 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
823 unsigned Length = strlen(TmpBuffer);
824 Tok.SetKind(tok::numeric_constant);
825 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000826 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000827 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000828 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000829 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000830 Diag(Tok, diag::ext_pp_base_file);
831 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
832 while (NextLoc.getFileID() != 0) {
833 Loc = NextLoc;
834 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
835 }
836 }
837
Chris Lattner0766e592006-07-03 01:07:01 +0000838 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
839 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000840 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000841 Tok.SetKind(tok::string_literal);
842 Tok.SetLength(FN.size());
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000843 Tok.SetLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000844 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000845 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000846 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000847 Tok.SetKind(tok::string_literal);
848 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
849 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000850 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000851 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000852 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000853 Tok.SetKind(tok::string_literal);
854 Tok.SetLength(strlen("\"hh:mm:ss\""));
855 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000856 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000857 Diag(Tok, diag::ext_pp_include_level);
858
859 // Compute the include depth of this token.
860 unsigned Depth = 0;
861 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
862 for (; Loc.getFileID() != 0; ++Depth)
863 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
864
865 // __INCLUDE_LEVEL__ expands to a simple numeric value.
866 sprintf(TmpBuffer, "%u", Depth);
867 unsigned Length = strlen(TmpBuffer);
868 Tok.SetKind(tok::numeric_constant);
869 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000870 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000871 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000872 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
873 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
874 Diag(Tok, diag::ext_pp_timestamp);
875
876 // Get the file that we are lexing out of. If we're currently lexing from
877 // a macro, dig into the include stack.
878 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000879 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000880
881 if (TheLexer)
882 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
883
884 // If this file is older than the file it depends on, emit a diagnostic.
885 const char *Result;
886 if (CurFile) {
887 time_t TT = CurFile->getModificationTime();
888 struct tm *TM = localtime(&TT);
889 Result = asctime(TM);
890 } else {
891 Result = "??? ??? ?? ??:??:?? ????\n";
892 }
893 TmpBuffer[0] = '"';
894 strcpy(TmpBuffer+1, Result);
895 unsigned Len = strlen(TmpBuffer);
896 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
897 Tok.SetKind(tok::string_literal);
898 Tok.SetLength(Len);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000899 Tok.SetLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000900 } else {
901 assert(0 && "Unknown identifier!");
902 }
903}
Chris Lattner677757a2006-06-28 05:26:32 +0000904
Chris Lattner13044d92006-07-03 05:16:44 +0000905namespace {
906struct UnusedIdentifierReporter : public IdentifierVisitor {
907 Preprocessor &PP;
908 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
909
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000910 void VisitIdentifier(IdentifierInfo &II) const {
911 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
912 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000913 }
914};
915}
916
Chris Lattner677757a2006-06-28 05:26:32 +0000917//===----------------------------------------------------------------------===//
918// Lexer Event Handling.
919//===----------------------------------------------------------------------===//
920
Chris Lattnercefc7682006-07-08 08:28:12 +0000921/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
922/// identifier information for the token and install it into the token.
923IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
924 const char *BufPtr) {
925 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
926 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
927
928 // Look up this token, see if it is a macro, or if it is a language keyword.
929 IdentifierInfo *II;
930 if (BufPtr && !Identifier.needsCleaning()) {
931 // No cleaning needed, just use the characters from the lexed buffer.
932 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
933 } else {
934 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
935 const char *TmpBuf = (char*)alloca(Identifier.getLength());
936 unsigned Size = getSpelling(Identifier, TmpBuf);
937 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
938 }
939 Identifier.SetIdentifierInfo(II);
940 return II;
941}
942
943
Chris Lattner677757a2006-06-28 05:26:32 +0000944/// HandleIdentifier - This callback is invoked when the lexer reads an
945/// identifier. This callback looks up the identifier in the map and/or
946/// potentially macro expands it or turns it into a named token (like 'for').
947void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
948 if (Identifier.getIdentifierInfo() == 0) {
949 // If we are skipping tokens (because we are in a #if 0 block), there will
950 // be no identifier info, just return the token.
951 assert(isSkipping() && "Token isn't an identifier?");
952 return;
953 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000954 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000955
956 // If this identifier was poisoned, and if it was not produced from a macro
957 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000958 if (II.isPoisoned() && CurLexer) {
959 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
960 Diag(Identifier, diag::err_pp_used_poisoned_id);
961 else
962 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
963 }
Chris Lattner677757a2006-06-28 05:26:32 +0000964
Chris Lattner78186052006-07-09 00:45:31 +0000965 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000966 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000967 if (MI->isEnabled() && !DisableMacroExpansion)
Chris Lattner78186052006-07-09 00:45:31 +0000968 if (!HandleMacroExpandedIdentifier(Identifier, MI))
969 return;
Chris Lattner677757a2006-06-28 05:26:32 +0000970
971 // Change the kind of this identifier to the appropriate token kind, e.g.
972 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000973 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000974
975 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000976 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000977}
978
Chris Lattner22eb9722006-06-18 05:43:12 +0000979/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
980/// the current file. This either returns the EOF token or pops a level off
981/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000982void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000983 assert(!CurMacroExpander &&
984 "Ending a file when currently in a macro!");
985
986 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
987 // this is an error condition. Just return the EOF token up to
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000988 // SkipExcludedConditionalBlock. The code that enabled skipping will issue
989 // errors for the unterminated #if's on the conditional stack if it is
990 // interested.
Chris Lattner22eb9722006-06-18 05:43:12 +0000991 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000992 Result.StartToken();
993 CurLexer->BufferPtr = CurLexer->BufferEnd;
994 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000995 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000996 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000997 }
998
Chris Lattner371ac8a2006-07-04 07:11:10 +0000999 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001000 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001001 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001002 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001003 // Okay, this has a controlling macro, remember in PerFileInfo.
1004 if (const FileEntry *FE =
1005 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1006 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001007 }
1008 }
1009
Chris Lattner22eb9722006-06-18 05:43:12 +00001010 // If this is a #include'd file, pop it off the include stack and continue
1011 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001012 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001013 // We're done with the #included file.
1014 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +00001015 CurLexer = IncludeMacroStack.back().TheLexer;
1016 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
1017 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
1018 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +00001019
1020 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001021 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001022 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1023
1024 // Get the file entry for the current file.
1025 if (const FileEntry *FE =
1026 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1027 FileType = getFileInfo(FE).DirInfo;
1028
Chris Lattner0c885f52006-06-21 06:50:18 +00001029 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001030 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001031 }
Chris Lattner0c885f52006-06-21 06:50:18 +00001032
Chris Lattner22eb9722006-06-18 05:43:12 +00001033 return Lex(Result);
1034 }
1035
Chris Lattnerd01e2912006-06-18 16:22:51 +00001036 Result.StartToken();
1037 CurLexer->BufferPtr = CurLexer->BufferEnd;
1038 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001040
1041 // We're done with the #included file.
1042 delete CurLexer;
1043 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001044
Chris Lattner03f83482006-07-10 06:16:26 +00001045 // This is the end of the top-level file. If the diag::pp_macro_not_used
1046 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1047 // have not been used.
1048 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1049 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +00001050}
1051
1052/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnerafe603f2006-07-11 04:02:46 +00001053/// the current macro expansion.
Chris Lattnercb283342006-06-18 06:48:37 +00001054void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001055 assert(CurMacroExpander && !CurLexer &&
1056 "Ending a macro when currently in a #include file!");
1057
1058 // Mark macro not ignored now that it is no longer being expanded.
1059 CurMacroExpander->getMacro().EnableMacro();
1060 delete CurMacroExpander;
1061
Chris Lattner69772b02006-07-02 20:34:39 +00001062 // Handle this like a #include file being popped off the stack.
1063 CurMacroExpander = 0;
1064 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001065}
1066
1067
1068//===----------------------------------------------------------------------===//
1069// Utility Methods for Preprocessor Directive Handling.
1070//===----------------------------------------------------------------------===//
1071
1072/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1073/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001074void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001075 LexerToken Tmp;
1076 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001077 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001078 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001079}
1080
1081/// ReadMacroName - Lex and validate a macro name, which occurs after a
1082/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001083/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1084/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001085/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001086void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001087 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001088 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001089
1090 // Missing macro name?
1091 if (MacroNameTok.getKind() == tok::eom)
1092 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1093
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001094 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1095 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001096 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 // Fall through on error.
1098 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001099 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001100
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001101 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1102 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001103 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001104 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001105 } else if (isDefineUndef && II->getMacroInfo() &&
1106 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001107 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001108 if (isDefineUndef == 1)
1109 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1110 else
1111 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 } else {
1113 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001114 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 }
1116
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 // Invalid macro name, read and discard the rest of the line. Then set the
1118 // token kind to tok::eom.
1119 MacroNameTok.SetKind(tok::eom);
1120 return DiscardUntilEndOfDirective();
1121}
1122
1123/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1124/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001125void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001126 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001127 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001128 // There should be no tokens after the directive, but we allow them as an
1129 // extension.
1130 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001131 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1132 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001134}
1135
1136
1137
1138/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1139/// decided that the subsequent tokens are in the #if'd out portion of the
1140/// file. Lex the rest of the file, until we see an #endif. If
1141/// FoundNonSkipPortion is true, then we have already emitted code for part of
1142/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1143/// is true, then #else directives are ok, if not, then we have already seen one
1144/// so a #else directive is a duplicate. When this returns, the caller can lex
1145/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001146void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001147 bool FoundNonSkipPortion,
1148 bool FoundElse) {
1149 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001150 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 "Lexing a macro, not a file?");
1152
1153 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1154 FoundNonSkipPortion, FoundElse);
1155
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001156 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1157 // disabling warnings, etc.
1158 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001159 LexerToken Tok;
1160 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001161 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001162
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001163 // If this is the end of the buffer, we have an error.
1164 if (Tok.getKind() == tok::eof) {
1165 // Emit errors for each unterminated conditional on the stack, including
1166 // the current one.
1167 while (!CurLexer->ConditionalStack.empty()) {
1168 Diag(CurLexer->ConditionalStack.back().IfLoc,
1169 diag::err_pp_unterminated_conditional);
1170 CurLexer->ConditionalStack.pop_back();
1171 }
1172
1173 // Just return and let the caller lex after this #include.
1174 break;
1175 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001176
1177 // If this token is not a preprocessor directive, just skip it.
1178 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1179 continue;
1180
1181 // We just parsed a # character at the start of a line, so we're in
1182 // directive mode. Tell the lexer this so any newlines we see will be
1183 // converted into an EOM token (this terminates the macro).
1184 CurLexer->ParsingPreprocessorDirective = true;
1185
1186 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001187 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001188
1189 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1190 // something bogus), skip it.
1191 if (Tok.getKind() != tok::identifier) {
1192 CurLexer->ParsingPreprocessorDirective = false;
1193 continue;
1194 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001195
Chris Lattner22eb9722006-06-18 05:43:12 +00001196 // If the first letter isn't i or e, it isn't intesting to us. We know that
1197 // this is safe in the face of spelling differences, because there is no way
1198 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001199 // allows us to avoid looking up the identifier info for #define/#undef and
1200 // other common directives.
1201 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1202 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001203 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1204 FirstChar != 'i' && FirstChar != 'e') {
1205 CurLexer->ParsingPreprocessorDirective = false;
1206 continue;
1207 }
1208
Chris Lattnere60165f2006-06-22 06:36:29 +00001209 // Get the identifier name without trigraphs or embedded newlines. Note
1210 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1211 // when skipping.
1212 // TODO: could do this with zero copies in the no-clean case by using
1213 // strncmp below.
1214 char Directive[20];
1215 unsigned IdLen;
1216 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1217 IdLen = Tok.getLength();
1218 memcpy(Directive, RawCharData, IdLen);
1219 Directive[IdLen] = 0;
1220 } else {
1221 std::string DirectiveStr = getSpelling(Tok);
1222 IdLen = DirectiveStr.size();
1223 if (IdLen >= 20) {
1224 CurLexer->ParsingPreprocessorDirective = false;
1225 continue;
1226 }
1227 memcpy(Directive, &DirectiveStr[0], IdLen);
1228 Directive[IdLen] = 0;
1229 }
1230
Chris Lattner22eb9722006-06-18 05:43:12 +00001231 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001232 if ((IdLen == 2) || // "if"
1233 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1234 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001235 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1236 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001237 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001238 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001239 /*foundnonskip*/false,
1240 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001241 }
1242 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001243 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001244 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 PPConditionalInfo CondInfo;
1246 CondInfo.WasSkipping = true; // Silence bogus warning.
1247 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1248 assert(!InCond && "Can't be skipping if not in a conditional!");
1249
1250 // If we popped the outermost skipping block, we're done skipping!
1251 if (!CondInfo.WasSkipping)
1252 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001253 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001254 // #else directive in a skipping conditional. If not in some other
1255 // skipping conditional, and if #else hasn't already been seen, enter it
1256 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001257 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001258 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1259
1260 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001261 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001262
1263 // Note that we've seen a #else in this conditional.
1264 CondInfo.FoundElse = true;
1265
1266 // If the conditional is at the top level, and the #if block wasn't
1267 // entered, enter the #else block now.
1268 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1269 CondInfo.FoundNonSkip = true;
1270 break;
1271 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001272 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001273 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1274
1275 bool ShouldEnter;
1276 // If this is in a skipping block or if we're already handled this #if
1277 // block, don't bother parsing the condition.
1278 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001279 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001280 ShouldEnter = false;
1281 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001282 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001283 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001284 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1285 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001286 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001287 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001288 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 }
1290
1291 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001292 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001293
1294 // If this condition is true, enter it!
1295 if (ShouldEnter) {
1296 CondInfo.FoundNonSkip = true;
1297 break;
1298 }
1299 }
1300 }
1301
1302 CurLexer->ParsingPreprocessorDirective = false;
1303 }
1304
1305 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1306 // of the file, just stop skipping and return to lexing whatever came after
1307 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001308 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001309}
1310
1311//===----------------------------------------------------------------------===//
1312// Preprocessor Directive Handling.
1313//===----------------------------------------------------------------------===//
1314
1315/// HandleDirective - This callback is invoked when the lexer sees a # token
1316/// at the start of a line. This consumes the directive, modifies the
1317/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1318/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001319void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001320 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001321
1322 // We just parsed a # character at the start of a line, so we're in directive
1323 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001324 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001325 CurLexer->ParsingPreprocessorDirective = true;
1326
1327 ++NumDirectives;
1328
Chris Lattner371ac8a2006-07-04 07:11:10 +00001329 // We are about to read a token. For the multiple-include optimization FA to
1330 // work, we have to remember if we had read any tokens *before* this
1331 // pp-directive.
1332 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1333
Chris Lattner78186052006-07-09 00:45:31 +00001334 // Read the next token, the directive flavor. This isn't expanded due to
1335 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001336 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001337
Chris Lattner78186052006-07-09 00:45:31 +00001338 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1339 // #define A(x) #x
1340 // A(abc
1341 // #warning blah
1342 // def)
1343 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1344 if (InMacroFormalArgs)
1345 Diag(Result, diag::ext_embedded_directive);
1346
Chris Lattner22eb9722006-06-18 05:43:12 +00001347 switch (Result.getKind()) {
1348 default: break;
1349 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001350 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001351
1352#if 0
1353 case tok::numeric_constant:
1354 // FIXME: implement # 7 line numbers!
1355 break;
1356#endif
1357 case tok::kw_else:
1358 return HandleElseDirective(Result);
1359 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001360 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001362 // Get the identifier name without trigraphs or embedded newlines.
1363 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001364 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001365 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001366 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001367 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001368 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001369 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001370 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001371 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1372 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 break;
1374 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001375 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001376 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001377 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001378 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001379 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001381 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001382 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001383 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001384 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001385 break;
1386 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001387 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001388 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001389 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001390 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001391 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001392 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001393 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001394 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001395 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1396 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001397 break;
1398 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001399 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1400 return HandleIncludeDirective(Result); // Handle #include.
1401 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001402 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001403 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001404 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001405 break;
1406 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001407 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001408 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001409 }
1410 break;
1411 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001412 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1413 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001414 break;
1415 }
1416 break;
1417 }
1418
1419 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001420 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001421
1422 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001423 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001424
1425 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001426}
1427
Chris Lattner01d66cc2006-07-03 22:16:27 +00001428void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001429 bool isWarning) {
1430 // Read the rest of the line raw. We do this because we don't want macros
1431 // to be expanded and we don't require that the tokens be valid preprocessing
1432 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1433 // collapse multiple consequtive white space between tokens, but this isn't
1434 // specified by the standard.
1435 std::string Message = CurLexer->ReadToEndOfLine();
1436
1437 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001438 return Diag(Tok, DiagID, Message);
1439}
1440
1441/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1442///
1443void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001444 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001445 Diag(Tok, diag::ext_pp_ident_directive);
1446
Chris Lattner371ac8a2006-07-04 07:11:10 +00001447 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001448 LexerToken StrTok;
1449 Lex(StrTok);
1450
1451 // If the token kind isn't a string, it's a malformed directive.
1452 if (StrTok.getKind() != tok::string_literal)
1453 return Diag(StrTok, diag::err_pp_malformed_ident);
1454
1455 // Verify that there is nothing after the string, other than EOM.
1456 CheckEndOfDirective("#ident");
1457
1458 if (IdentHandler)
1459 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001460}
1461
Chris Lattnerb8761832006-06-24 21:31:03 +00001462//===----------------------------------------------------------------------===//
1463// Preprocessor Include Directive Handling.
1464//===----------------------------------------------------------------------===//
1465
Chris Lattner22eb9722006-06-18 05:43:12 +00001466/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1467/// file to be included from the lexer, then include it! This is a common
1468/// routine with functionality shared between #include, #include_next and
1469/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001470void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001471 const DirectoryLookup *LookupFrom,
1472 bool isImport) {
1473 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001474
Chris Lattner22eb9722006-06-18 05:43:12 +00001475 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001476 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001477
1478 // If the token kind is EOM, the error has already been diagnosed.
1479 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001480 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001481
1482 // Verify that there is nothing after the filename, other than EOM. Use the
1483 // preprocessor to lex this in case lexing the filename entered a macro.
1484 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001485
1486 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001487 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001488 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1489
Chris Lattner269c2322006-06-25 06:23:00 +00001490 // Find out whether the filename is <x> or "x".
1491 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001492
1493 // Remove the quotes.
1494 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1495
Chris Lattner22eb9722006-06-18 05:43:12 +00001496 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001497 const DirectoryLookup *CurDir;
1498 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001499 if (File == 0)
1500 return Diag(FilenameTok, diag::err_pp_file_not_found);
1501
1502 // Get information about this file.
1503 PerFileInfo &FileInfo = getFileInfo(File);
1504
1505 // If this is a #import directive, check that we have not already imported
1506 // this header.
1507 if (isImport) {
1508 // If this has already been imported, don't import it again.
1509 FileInfo.isImport = true;
1510
1511 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001512 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001513 } else {
1514 // Otherwise, if this is a #include of a file that was previously #import'd
1515 // or if this is the second #include of a #pragma once file, ignore it.
1516 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001517 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001518 }
Chris Lattner3665f162006-07-04 07:26:10 +00001519
1520 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1521 // if the macro that guards it is defined, we know the #include has no effect.
1522 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1523 ++NumMultiIncludeFileOptzn;
1524 return;
1525 }
1526
Chris Lattner22eb9722006-06-18 05:43:12 +00001527
1528 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001529 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 if (FileID == 0)
1531 return Diag(FilenameTok, diag::err_pp_file_not_found);
1532
1533 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001534 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001535
1536 // Increment the number of times this file has been included.
1537 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001538}
1539
1540/// HandleIncludeNextDirective - Implements #include_next.
1541///
Chris Lattnercb283342006-06-18 06:48:37 +00001542void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1543 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001544
1545 // #include_next is like #include, except that we start searching after
1546 // the current found directory. If we can't do this, issue a
1547 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001548 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001549 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001550 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001551 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001552 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001553 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001554 } else {
1555 // Start looking up in the next directory.
1556 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001557 }
1558
1559 return HandleIncludeDirective(IncludeNextTok, Lookup);
1560}
1561
1562/// HandleImportDirective - Implements #import.
1563///
Chris Lattnercb283342006-06-18 06:48:37 +00001564void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1565 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001566
1567 return HandleIncludeDirective(ImportTok, 0, true);
1568}
1569
Chris Lattnerb8761832006-06-24 21:31:03 +00001570//===----------------------------------------------------------------------===//
1571// Preprocessor Macro Directive Handling.
1572//===----------------------------------------------------------------------===//
1573
Chris Lattnercefc7682006-07-08 08:28:12 +00001574/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1575/// definition has just been read. Lex the rest of the arguments and the
1576/// closing ), updating MI with what we learn. Return true if an error occurs
1577/// parsing the arg list.
1578bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1579 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001580 while (1) {
1581 LexUnexpandedToken(Tok);
1582 switch (Tok.getKind()) {
1583 case tok::r_paren:
1584 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001585 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001586 // Otherwise we have #define FOO(A,)
1587 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1588 return true;
1589 case tok::ellipsis: // #define X(... -> C99 varargs
1590 // Warn if use of C99 feature in non-C99 mode.
1591 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1592
1593 // Lex the token after the identifier.
1594 LexUnexpandedToken(Tok);
1595 if (Tok.getKind() != tok::r_paren) {
1596 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1597 return true;
1598 }
1599 MI->setIsC99Varargs();
1600 return false;
1601 case tok::eom: // #define X(
1602 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1603 return true;
1604 default: // #define X(1
1605 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1606 return true;
1607 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001608 IdentifierInfo *II = Tok.getIdentifierInfo();
1609
1610 // If this is already used as an argument, it is used multiple times (e.g.
1611 // #define X(A,A.
1612 if (II->isMacroArg()) { // C99 6.10.3p6
1613 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1614 return true;
1615 }
1616
1617 // Add the argument to the macro info.
1618 MI->addArgument(II);
1619 // Remember it is an argument now.
1620 II->setIsMacroArg(true);
Chris Lattnercefc7682006-07-08 08:28:12 +00001621
1622 // Lex the token after the identifier.
1623 LexUnexpandedToken(Tok);
1624
1625 switch (Tok.getKind()) {
1626 default: // #define X(A B
1627 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1628 return true;
1629 case tok::r_paren: // #define X(A)
1630 return false;
1631 case tok::comma: // #define X(A,
1632 break;
1633 case tok::ellipsis: // #define X(A... -> GCC extension
1634 // Diagnose extension.
1635 Diag(Tok, diag::ext_named_variadic_macro);
1636
1637 // Lex the token after the identifier.
1638 LexUnexpandedToken(Tok);
1639 if (Tok.getKind() != tok::r_paren) {
1640 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1641 return true;
1642 }
1643
1644 MI->setIsGNUVarargs();
1645 return false;
1646 }
1647 }
1648 }
1649}
1650
Chris Lattner22eb9722006-06-18 05:43:12 +00001651/// HandleDefineDirective - Implements #define. This consumes the entire macro
1652/// line then lets the caller lex the next real token.
1653///
Chris Lattnercb283342006-06-18 06:48:37 +00001654void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001655 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001656
Chris Lattner22eb9722006-06-18 05:43:12 +00001657 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001658 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001659
1660 // Error reading macro name? If so, diagnostic already issued.
1661 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001662 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001663
Chris Lattner50b497e2006-06-18 16:32:35 +00001664 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001665
1666 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001667 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001668
Chris Lattner78186052006-07-09 00:45:31 +00001669 // FIXME: Enable __VA_ARGS__.
1670
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001671 // If this is a function-like macro definition, parse the argument list,
1672 // marking each of the identifiers as being used as macro arguments. Also,
1673 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001674 if (Tok.getKind() == tok::eom) {
1675 // If there is no body to this macro, we have no special handling here.
1676 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001677 // This is a function-like macro definition. Read the argument list.
1678 MI->setIsFunctionLike();
1679 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001680 // Clear the "isMacroArg" flags from all the macro arguments parsed.
1681 MI->SetIdentifierIsMacroArgFlags(false);
1682 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001683 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001684 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001685 if (CurLexer->ParsingPreprocessorDirective)
1686 DiscardUntilEndOfDirective();
1687 return;
1688 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001689
Chris Lattner815a1f92006-07-08 20:48:04 +00001690 // Read the first token after the arg list for down below.
1691 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001692 } else if (!Tok.hasLeadingSpace()) {
1693 // C99 requires whitespace between the macro definition and the body. Emit
1694 // a diagnostic for something like "#define X+".
1695 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001696 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001697 } else {
1698 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1699 // one in some cases!
1700 }
1701 } else {
1702 // This is a normal token with leading space. Clear the leading space
1703 // marker on the first token to get proper expansion.
1704 Tok.ClearFlag(LexerToken::LeadingSpace);
1705 }
1706
1707 // Read the rest of the macro body.
1708 while (Tok.getKind() != tok::eom) {
1709 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001710
1711 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001712 // parameters in function-like macro expansions.
1713 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001714 // Get the next token of the macro.
1715 LexUnexpandedToken(Tok);
1716 continue;
1717 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001718
Chris Lattner815a1f92006-07-08 20:48:04 +00001719 // Get the next token of the macro.
1720 LexUnexpandedToken(Tok);
1721
1722 // Not a macro arg identifier?
1723 if (!Tok.getIdentifierInfo() || !Tok.getIdentifierInfo()->isMacroArg()) {
1724 Diag(Tok, diag::err_pp_stringize_not_parameter);
1725 // Clear the "isMacroArg" flags from all the macro arguments.
1726 MI->SetIdentifierIsMacroArgFlags(false);
1727 delete MI;
1728 return;
1729 }
1730
1731 // Things look ok, add the param name token to the macro.
1732 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001733
Chris Lattner22eb9722006-06-18 05:43:12 +00001734 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001735 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001737
Chris Lattner78186052006-07-09 00:45:31 +00001738 // Clear the "isMacroArg" flags from all the macro arguments.
1739 MI->SetIdentifierIsMacroArgFlags(false);
1740
Chris Lattnerbff18d52006-07-06 04:49:18 +00001741 // Check that there is no paste (##) operator at the begining or end of the
1742 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001743 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001744 if (NumTokens != 0) {
1745 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001746 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001747 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001748 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001749 }
1750 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001751 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001752 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001753 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001754 }
1755 }
1756
Chris Lattner13044d92006-07-03 05:16:44 +00001757 // If this is the primary source file, remember that this macro hasn't been
1758 // used yet.
1759 if (isInPrimaryFile())
1760 MI->setIsUsed(false);
1761
Chris Lattner22eb9722006-06-18 05:43:12 +00001762 // Finally, if this identifier already had a macro defined for it, verify that
1763 // the macro bodies are identical and free the old definition.
1764 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001765 if (!OtherMI->isUsed())
1766 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1767
Chris Lattner22eb9722006-06-18 05:43:12 +00001768 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001769 // must be the same. C99 6.10.3.2.
1770 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001771 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1772 MacroNameTok.getIdentifierInfo()->getName());
1773 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1774 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001775 delete OtherMI;
1776 }
1777
1778 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001779}
1780
1781
1782/// HandleUndefDirective - Implements #undef.
1783///
Chris Lattnercb283342006-06-18 06:48:37 +00001784void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001785 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001786
Chris Lattner22eb9722006-06-18 05:43:12 +00001787 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001788 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001789
1790 // Error reading macro name? If so, diagnostic already issued.
1791 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001792 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001793
1794 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001795 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001796
1797 // Okay, we finally have a valid identifier to undef.
1798 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1799
1800 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001801 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001802
Chris Lattner13044d92006-07-03 05:16:44 +00001803 if (!MI->isUsed())
1804 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001805
1806 // Free macro definition.
1807 delete MI;
1808 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001809}
1810
1811
Chris Lattnerb8761832006-06-24 21:31:03 +00001812//===----------------------------------------------------------------------===//
1813// Preprocessor Conditional Directive Handling.
1814//===----------------------------------------------------------------------===//
1815
Chris Lattner22eb9722006-06-18 05:43:12 +00001816/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001817/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1818/// if any tokens have been returned or pp-directives activated before this
1819/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001820///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001821void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1822 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001823 ++NumIf;
1824 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001825
Chris Lattner22eb9722006-06-18 05:43:12 +00001826 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001827 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001828
1829 // Error reading macro name? If so, diagnostic already issued.
1830 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001831 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001832
1833 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001834 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1835
1836 // If the start of a top-level #ifdef, inform MIOpt.
1837 if (!ReadAnyTokensBeforeDirective &&
1838 CurLexer->getConditionalStackDepth() == 0) {
1839 assert(isIfndef && "#ifdef shouldn't reach here");
1840 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1841 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001842
Chris Lattnera78a97e2006-07-03 05:42:18 +00001843 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1844
1845 // If there is a macro, mark it used.
1846 if (MI) MI->setIsUsed(true);
1847
Chris Lattner22eb9722006-06-18 05:43:12 +00001848 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001849 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001850 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001851 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001852 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001853 } else {
1854 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001855 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001856 /*Foundnonskip*/false,
1857 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 }
1859}
1860
1861/// HandleIfDirective - Implements the #if directive.
1862///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001863void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1864 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001865 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001866
Chris Lattner371ac8a2006-07-04 07:11:10 +00001867 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001868 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001869 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001870
1871 // Should we include the stuff contained by this directive?
1872 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001873 // If this condition is equivalent to #ifndef X, and if this is the first
1874 // directive seen, handle it for the multiple-include optimization.
1875 if (!ReadAnyTokensBeforeDirective &&
1876 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1877 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1878
Chris Lattner22eb9722006-06-18 05:43:12 +00001879 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001880 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001881 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001882 } else {
1883 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001884 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001885 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001886 }
1887}
1888
1889/// HandleEndifDirective - Implements the #endif directive.
1890///
Chris Lattnercb283342006-06-18 06:48:37 +00001891void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001893
Chris Lattner22eb9722006-06-18 05:43:12 +00001894 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001895 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001896
1897 PPConditionalInfo CondInfo;
1898 if (CurLexer->popConditionalLevel(CondInfo)) {
1899 // No conditionals on the stack: this is an #endif without an #if.
1900 return Diag(EndifToken, diag::err_pp_endif_without_if);
1901 }
1902
Chris Lattner371ac8a2006-07-04 07:11:10 +00001903 // If this the end of a top-level #endif, inform MIOpt.
1904 if (CurLexer->getConditionalStackDepth() == 0)
1905 CurLexer->MIOpt.ExitTopLevelConditional();
1906
Chris Lattner22eb9722006-06-18 05:43:12 +00001907 assert(!CondInfo.WasSkipping && !isSkipping() &&
1908 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001909}
1910
1911
Chris Lattnercb283342006-06-18 06:48:37 +00001912void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001913 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001914
Chris Lattner22eb9722006-06-18 05:43:12 +00001915 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001916 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001917
1918 PPConditionalInfo CI;
1919 if (CurLexer->popConditionalLevel(CI))
1920 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001921
1922 // If this is a top-level #else, inform the MIOpt.
1923 if (CurLexer->getConditionalStackDepth() == 0)
1924 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001925
1926 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001927 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001928
1929 // Finally, skip the rest of the contents of this block and return the first
1930 // token after it.
1931 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1932 /*FoundElse*/true);
1933}
1934
Chris Lattnercb283342006-06-18 06:48:37 +00001935void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001936 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001937
Chris Lattner22eb9722006-06-18 05:43:12 +00001938 // #elif directive in a non-skipping conditional... start skipping.
1939 // We don't care what the condition is, because we will always skip it (since
1940 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001941 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001942
1943 PPConditionalInfo CI;
1944 if (CurLexer->popConditionalLevel(CI))
1945 return Diag(ElifToken, diag::pp_err_elif_without_if);
1946
Chris Lattner371ac8a2006-07-04 07:11:10 +00001947 // If this is a top-level #elif, inform the MIOpt.
1948 if (CurLexer->getConditionalStackDepth() == 0)
1949 CurLexer->MIOpt.FoundTopLevelElse();
1950
Chris Lattner22eb9722006-06-18 05:43:12 +00001951 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001952 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001953
1954 // Finally, skip the rest of the contents of this block and return the first
1955 // token after it.
1956 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1957 /*FoundElse*/CI.FoundElse);
1958}
Chris Lattnerb8761832006-06-24 21:31:03 +00001959