blob: f316c67b3c3d4276700f29b8194d17e958816fdb [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
279//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000280// Source File Location Methods.
281//===----------------------------------------------------------------------===//
282
283
284/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
285/// return null on failure. isAngled indicates whether the file reference is
286/// for system #include's or not (i.e. using <> instead of "").
287const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000288 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000289 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000290 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000291 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000292 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000293
294 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000295 // FIXME: Portability. This should be a sys::Path interface, this doesn't
296 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000297 if (Filename[0] == '/') {
298 // If this was an #include_next "/absolute/file", fail.
299 if (FromDir) return 0;
300
301 // Otherwise, just return the file.
302 return FileMgr.getFile(Filename);
303 }
304
305 // Step #0, unless disabled, check to see if the file is in the #includer's
306 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000307 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000308 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
309 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000310 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000311 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000312 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000313 if (const FileEntry *FE =
314 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000315 if (CurDirLookup)
316 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000317 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000318 CurDir = 0;
319
320 // This file is a system header or C++ unfriendly if the old file is.
321 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000322 return FE;
323 }
324 }
325 }
326
327 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000328 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000329
330 // If this is a #include_next request, start searching after the directory the
331 // file was found in.
332 if (FromDir)
333 i = FromDir-&SearchDirs[0];
334
335 // Check each directory in sequence to see if it contains this file.
336 for (; i != SearchDirs.size(); ++i) {
337 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000338 // FIXME: Portability. Adding file to dir should be in sys::Path.
339 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
340 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000341 CurDir = &SearchDirs[i];
342
343 // This file is a system header or C++ unfriendly if the dir is.
344 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000345 return FE;
346 }
347 }
348
349 // Otherwise, didn't find it.
350 return 0;
351}
352
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000353/// isInPrimaryFile - Return true if we're in the top-level file, not in a
354/// #include.
355bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000356 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000357 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000358
Chris Lattner13044d92006-07-03 05:16:44 +0000359 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000360 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000361 if (IncludeMacroStack[i].TheLexer &&
362 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
363 return IncludeMacroStack[i].TheLexer->isMainFile();
364 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000365}
366
367/// getCurrentLexer - Return the current file lexer being lexed from. Note
368/// that this ignores any potentially active macro expansions and _Pragma
369/// expansions going on at the time.
370Lexer *Preprocessor::getCurrentFileLexer() const {
371 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
372
373 // Look for a stacked lexer.
374 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000375 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000376 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
377 return L;
378 }
379 return 0;
380}
381
382
Chris Lattner22eb9722006-06-18 05:43:12 +0000383/// EnterSourceFile - Add a source file to the top of the include stack and
384/// start lexing tokens from it instead of the current buffer. Return true
385/// on failure.
386void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000387 const DirectoryLookup *CurDir,
388 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000389 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000390 ++NumEnteredSourceFiles;
391
Chris Lattner69772b02006-07-02 20:34:39 +0000392 if (MaxIncludeStackDepth < IncludeMacroStack.size())
393 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000394
Chris Lattner22eb9722006-06-18 05:43:12 +0000395 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000396 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000397 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000398 EnterSourceFileWithLexer(TheLexer, CurDir);
399}
Chris Lattner22eb9722006-06-18 05:43:12 +0000400
Chris Lattner69772b02006-07-02 20:34:39 +0000401/// EnterSourceFile - Add a source file to the top of the include stack and
402/// start lexing tokens from it instead of the current buffer.
403void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
404 const DirectoryLookup *CurDir) {
405
406 // Add the current lexer to the include stack.
407 if (CurLexer || CurMacroExpander)
408 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
409 CurMacroExpander));
410
411 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000412 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000413 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000414
415 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000416 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000417 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
418
419 // Get the file entry for the current file.
420 if (const FileEntry *FE =
421 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
422 FileType = getFileInfo(FE).DirInfo;
423
Chris Lattner1840e492006-07-02 22:30:01 +0000424 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000425 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000426 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000427}
428
Chris Lattner69772b02006-07-02 20:34:39 +0000429
430
Chris Lattner22eb9722006-06-18 05:43:12 +0000431/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000432/// tokens from it instead of the current buffer.
Chris Lattner78186052006-07-09 00:45:31 +0000433void Preprocessor::EnterMacro(LexerToken &Tok, MacroFormalArgs *Formals) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000434 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000435 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000436 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
437 CurMacroExpander));
438 CurLexer = 0;
439 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000440
Chris Lattner22eb9722006-06-18 05:43:12 +0000441 // Mark the macro as currently disabled, so that it is not recursively
442 // expanded.
443 MI.DisableMacro();
Chris Lattner78186052006-07-09 00:45:31 +0000444 CurMacroExpander = new MacroExpander(Tok, Formals, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000445}
446
Chris Lattner22eb9722006-06-18 05:43:12 +0000447//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000448// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000449//===----------------------------------------------------------------------===//
450
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000451/// RegisterBuiltinMacro - Register the specified identifier in the identifier
452/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000453IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000454 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000455 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000456
457 // Mark it as being a macro that is builtin.
458 MacroInfo *MI = new MacroInfo(SourceLocation());
459 MI->setIsBuiltinMacro();
460 Id->setMacroInfo(MI);
461 return Id;
462}
463
464
Chris Lattner677757a2006-06-28 05:26:32 +0000465/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
466/// identifier table.
467void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000468 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000469 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000470 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
471 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000472 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000473
474 // GCC Extensions.
475 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
476 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000477 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000478}
479
Chris Lattnerc2395832006-07-09 00:57:04 +0000480/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
481/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000482static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
483 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000484 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
485
486 // If the token isn't an identifier, it's always literally expanded.
487 if (II == 0) return true;
488
489 // If the identifier is a macro, and if that macro is enabled, it may be
490 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000491 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
492 // Fast expanding "#define X X" is ok, because X would be disabled.
493 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000494 return false;
495
496 // If this is an object-like macro invocation, it is safe to trivially expand
497 // it.
498 if (MI->isObjectLike()) return true;
499
500 // If this is a function-like macro invocation, it's safe to trivially expand
501 // as long as the identifier is not a macro argument.
502 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
503 I != E; ++I)
504 if (*I == II)
505 return false; // Identifier is a macro argument.
506 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000507}
508
Chris Lattnerc2395832006-07-09 00:57:04 +0000509
Chris Lattnerafe603f2006-07-11 04:02:46 +0000510/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
511/// lexed is a '('. If so, consume the token and return true, if not, this
512/// method should have no observable side-effect on the lexed tokens.
513bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000514 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000515 unsigned Val;
516 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000517 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000518 else
519 Val = CurMacroExpander->isNextTokenLParen();
520
521 if (Val == 2) {
522 // If we ran off the end of the lexer or macro expander, walk the include
523 // stack, looking for whatever will return the next token.
524 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
525 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
526 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000527 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000528 else
529 Val = Entry.TheMacroExpander->isNextTokenLParen();
530 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000531 }
532
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000533 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
534 // have found something that isn't a '(' or we found the end of the
535 // translation unit. In either case, return false.
536 if (Val != 1)
537 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000538
539 LexerToken Tok;
540 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000541 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
542 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000543}
Chris Lattner677757a2006-06-28 05:26:32 +0000544
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000545/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
546/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000547bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000548 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000549
550 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
551 if (MI->isBuiltinMacro()) {
552 ExpandBuiltinMacro(Identifier);
553 return false;
554 }
555
556 /// FormalArgs - If this is a function-like macro expansion, this contains,
557 /// for each macro argument, the list of tokens that were provided to the
558 /// invocation.
559 MacroFormalArgs *FormalArgs = 0;
560
561 // If this is a function-like macro, read the arguments.
562 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000563 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
564 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000565 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000566 return true;
567
Chris Lattner78186052006-07-09 00:45:31 +0000568 // Remember that we are now parsing the arguments to a macro invocation.
569 // Preprocessor directives used inside macro arguments are not portable, and
570 // this enables the warning.
571 InMacroFormalArgs = true;
572 FormalArgs = ReadFunctionLikeMacroFormalArgs(Identifier, MI);
573
574 // Finished parsing args.
575 InMacroFormalArgs = false;
576
577 // If there was an error parsing the arguments, bail out.
578 if (FormalArgs == 0) return false;
579
580 ++NumFnMacroExpanded;
581 } else {
582 ++NumMacroExpanded;
583 }
Chris Lattner13044d92006-07-03 05:16:44 +0000584
585 // Notice that this macro has been used.
586 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000587
588 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589
590 // If this macro expands to no tokens, don't bother to push it onto the
591 // expansion stack, only to take it right back off.
592 if (MI->getNumTokens() == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000593 // No need for formal arg info.
594 delete FormalArgs;
595
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000596 // Ignore this macro use, just return the next token in the current
597 // buffer.
598 bool HadLeadingSpace = Identifier.hasLeadingSpace();
599 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
600
601 Lex(Identifier);
602
603 // If the identifier isn't on some OTHER line, inherit the leading
604 // whitespace/first-on-a-line property of this token. This handles
605 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
606 // empty.
607 if (!Identifier.isAtStartOfLine()) {
608 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
609 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
610 }
611 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000612 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000613
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000614 } else if (MI->getNumTokens() == 1 &&
615 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000616 // Otherwise, if this macro expands into a single trivially-expanded
617 // token: expand it now. This handles common cases like
618 // "#define VAL 42".
619
620 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
621 // identifier to the expanded token.
622 bool isAtStartOfLine = Identifier.isAtStartOfLine();
623 bool hasLeadingSpace = Identifier.hasLeadingSpace();
624
625 // Remember where the token is instantiated.
626 SourceLocation InstantiateLoc = Identifier.getLocation();
627
628 // Replace the result token.
629 Identifier = MI->getReplacementToken(0);
630
631 // Restore the StartOfLine/LeadingSpace markers.
632 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
633 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
634
635 // Update the tokens location to include both its logical and physical
636 // locations.
637 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000638 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000639 Identifier.SetLocation(Loc);
640
641 // Since this is not an identifier token, it can't be macro expanded, so
642 // we're done.
643 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000644 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000645 }
646
Chris Lattner78186052006-07-09 00:45:31 +0000647 // Start expanding the macro.
648 EnterMacro(Identifier, FormalArgs);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000649
650 // Now that the macro is at the top of the include stack, ask the
651 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000652 Lex(Identifier);
653 return false;
654}
655
656/// ReadFunctionLikeMacroFormalArgs - After reading "MACRO(", this method is
657/// invoked to read all of the formal arguments specified for the macro
658/// invocation. This returns null on error.
659MacroFormalArgs *Preprocessor::
660ReadFunctionLikeMacroFormalArgs(LexerToken &MacroName, MacroInfo *MI) {
661 // Use an auto_ptr here so that the MacroFormalArgs object is deleted on
662 // all error paths.
663 std::auto_ptr<MacroFormalArgs> Args(new MacroFormalArgs(MI));
664
665 // The number of fixed arguments to parse.
666 unsigned NumFixedArgsLeft = MI->getNumArgs();
667 bool isVariadic = MI->isVariadic();
668
669 // If this is a C99-style varargs macro invocation, add an extra expected
670 // argument, which will catch all of the varargs formals in one argument.
671 if (MI->isC99Varargs())
672 ++NumFixedArgsLeft;
673
674 // Outer loop, while there are more arguments, keep reading them.
675 LexerToken Tok;
676 Tok.SetKind(tok::comma);
677 --NumFixedArgsLeft; // Start reading the first arg.
678
679 while (Tok.getKind() == tok::comma) {
680 // ArgTokens - Build up a list of tokens that make up this argument.
681 std::vector<LexerToken> ArgTokens;
682 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
683 unsigned NumParens = 0;
684
685 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000686 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
687 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000688 LexUnexpandedToken(Tok);
689
690 if (Tok.getKind() == tok::eof) {
691 Diag(MacroName, diag::err_unterm_macro_invoc);
692 // Do not lose the EOF. Return it to the client.
693 MacroName = Tok;
694 return 0;
695 } else if (Tok.getKind() == tok::r_paren) {
696 // If we found the ) token, the macro arg list is done.
697 if (NumParens-- == 0)
698 break;
699 } else if (Tok.getKind() == tok::l_paren) {
700 ++NumParens;
701 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
702 // Comma ends this argument if there are more fixed arguments expected.
703 if (NumFixedArgsLeft)
704 break;
705
706 // If this is not a variadic macro, too many formals were specified.
707 if (!isVariadic) {
708 // Emit the diagnostic at the macro name in case there is a missing ).
709 // Emitting it at the , could be far away from the macro name.
710 Diag(MacroName, diag::err_too_many_formals_in_macro_invoc);
711 return 0;
712 }
713 // Otherwise, continue to add the tokens to this variable argument.
714 }
715
716 ArgTokens.push_back(Tok);
717 }
718
Chris Lattnera12dd152006-07-11 04:09:02 +0000719 // Empty arguments are standard in C99 and supported as an extension in
720 // other modes.
721 if (ArgTokens.empty() && !Features.C99)
722 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000723
Chris Lattner78186052006-07-09 00:45:31 +0000724 // Remember the tokens that make up this argument. This destroys ArgTokens.
725 Args->addArgument(ArgTokens);
726 --NumFixedArgsLeft;
727 };
728
729 // Okay, we either found the r_paren. Check to see if we parsed too few
730 // arguments.
731 unsigned NumFormals = Args->getNumArguments();
732 unsigned MinArgsExpected = MI->getNumArgs();
733
734 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000735 // don't require this). GNU-style varargs already include the 'rest' name in
736 // the count.
737 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000738
739 if (NumFormals < MinArgsExpected) {
740 // There are several cases where too few arguments is ok, handle them now.
741 if (NumFormals+1 == MinArgsExpected && MI->isVariadic()) {
742 // Varargs where the named vararg parameter is missing: ok as extension.
743 // #define A(x, ...)
744 // A("blah")
745 Diag(Tok, diag::ext_missing_varargs_arg);
746 } else if (MI->getNumArgs() == 1) {
747 // #define A(x)
748 // A()
Chris Lattnerafe603f2006-07-11 04:02:46 +0000749 // is ok because it is an empty argument. Add it explicitly.
Chris Lattner78186052006-07-09 00:45:31 +0000750 std::vector<LexerToken> ArgTokens;
751 Args->addArgument(ArgTokens);
Chris Lattnera12dd152006-07-11 04:09:02 +0000752
753 // Empty arguments are standard in C99 and supported as an extension in
754 // other modes.
755 if (ArgTokens.empty() && !Features.C99)
756 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000757 } else {
758 // Otherwise, emit the error.
759 Diag(Tok, diag::err_too_few_formals_in_macro_invoc);
760 return 0;
761 }
762 }
763
764 return Args.release();
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000765}
766
Chris Lattnerc673f902006-06-30 06:10:41 +0000767/// ComputeDATE_TIME - Compute the current time, enter it into the specified
768/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
769/// the identifier tokens inserted.
770static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
771 ScratchBuffer *ScratchBuf) {
772 time_t TT = time(0);
773 struct tm *TM = localtime(&TT);
774
775 static const char * const Months[] = {
776 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
777 };
778
779 char TmpBuffer[100];
780 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
781 TM->tm_year+1900);
782 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
783
784 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
785 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
786}
787
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000788/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
789/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000790void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000791 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000792 IdentifierInfo *II = Tok.getIdentifierInfo();
793 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000794
795 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
796 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000797 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000798 return Handle_Pragma(Tok);
799
Chris Lattner78186052006-07-09 00:45:31 +0000800 ++NumBuiltinMacroExpanded;
801
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000802 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000803
804 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000805 Tok.SetIdentifierInfo(0);
806 Tok.ClearFlag(LexerToken::NeedsCleaning);
807
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000808 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000809 // __LINE__ expands to a simple numeric value.
810 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
811 unsigned Length = strlen(TmpBuffer);
812 Tok.SetKind(tok::numeric_constant);
813 Tok.SetLength(Length);
814 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000815 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000816 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000817 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000818 Diag(Tok, diag::ext_pp_base_file);
819 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
820 while (NextLoc.getFileID() != 0) {
821 Loc = NextLoc;
822 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
823 }
824 }
825
Chris Lattner0766e592006-07-03 01:07:01 +0000826 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
827 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000828 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000829 Tok.SetKind(tok::string_literal);
830 Tok.SetLength(FN.size());
831 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000832 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000833 if (!DATELoc.isValid())
834 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
835 Tok.SetKind(tok::string_literal);
836 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
837 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000838 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000839 if (!TIMELoc.isValid())
840 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
841 Tok.SetKind(tok::string_literal);
842 Tok.SetLength(strlen("\"hh:mm:ss\""));
843 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000844 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000845 Diag(Tok, diag::ext_pp_include_level);
846
847 // Compute the include depth of this token.
848 unsigned Depth = 0;
849 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
850 for (; Loc.getFileID() != 0; ++Depth)
851 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
852
853 // __INCLUDE_LEVEL__ expands to a simple numeric value.
854 sprintf(TmpBuffer, "%u", Depth);
855 unsigned Length = strlen(TmpBuffer);
856 Tok.SetKind(tok::numeric_constant);
857 Tok.SetLength(Length);
858 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000859 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000860 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
861 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
862 Diag(Tok, diag::ext_pp_timestamp);
863
864 // Get the file that we are lexing out of. If we're currently lexing from
865 // a macro, dig into the include stack.
866 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000867 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000868
869 if (TheLexer)
870 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
871
872 // If this file is older than the file it depends on, emit a diagnostic.
873 const char *Result;
874 if (CurFile) {
875 time_t TT = CurFile->getModificationTime();
876 struct tm *TM = localtime(&TT);
877 Result = asctime(TM);
878 } else {
879 Result = "??? ??? ?? ??:??:?? ????\n";
880 }
881 TmpBuffer[0] = '"';
882 strcpy(TmpBuffer+1, Result);
883 unsigned Len = strlen(TmpBuffer);
884 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
885 Tok.SetKind(tok::string_literal);
886 Tok.SetLength(Len);
887 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000888 } else {
889 assert(0 && "Unknown identifier!");
890 }
891}
Chris Lattner677757a2006-06-28 05:26:32 +0000892
Chris Lattner13044d92006-07-03 05:16:44 +0000893namespace {
894struct UnusedIdentifierReporter : public IdentifierVisitor {
895 Preprocessor &PP;
896 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
897
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000898 void VisitIdentifier(IdentifierInfo &II) const {
899 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
900 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000901 }
902};
903}
904
Chris Lattner677757a2006-06-28 05:26:32 +0000905//===----------------------------------------------------------------------===//
906// Lexer Event Handling.
907//===----------------------------------------------------------------------===//
908
Chris Lattnercefc7682006-07-08 08:28:12 +0000909/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
910/// identifier information for the token and install it into the token.
911IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
912 const char *BufPtr) {
913 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
914 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
915
916 // Look up this token, see if it is a macro, or if it is a language keyword.
917 IdentifierInfo *II;
918 if (BufPtr && !Identifier.needsCleaning()) {
919 // No cleaning needed, just use the characters from the lexed buffer.
920 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
921 } else {
922 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
923 const char *TmpBuf = (char*)alloca(Identifier.getLength());
924 unsigned Size = getSpelling(Identifier, TmpBuf);
925 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
926 }
927 Identifier.SetIdentifierInfo(II);
928 return II;
929}
930
931
Chris Lattner677757a2006-06-28 05:26:32 +0000932/// HandleIdentifier - This callback is invoked when the lexer reads an
933/// identifier. This callback looks up the identifier in the map and/or
934/// potentially macro expands it or turns it into a named token (like 'for').
935void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
936 if (Identifier.getIdentifierInfo() == 0) {
937 // If we are skipping tokens (because we are in a #if 0 block), there will
938 // be no identifier info, just return the token.
939 assert(isSkipping() && "Token isn't an identifier?");
940 return;
941 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000942 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000943
944 // If this identifier was poisoned, and if it was not produced from a macro
945 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000946 if (II.isPoisoned() && CurLexer) {
947 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
948 Diag(Identifier, diag::err_pp_used_poisoned_id);
949 else
950 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
951 }
Chris Lattner677757a2006-06-28 05:26:32 +0000952
Chris Lattner78186052006-07-09 00:45:31 +0000953 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000954 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000955 if (MI->isEnabled() && !DisableMacroExpansion)
Chris Lattner78186052006-07-09 00:45:31 +0000956 if (!HandleMacroExpandedIdentifier(Identifier, MI))
957 return;
Chris Lattner677757a2006-06-28 05:26:32 +0000958
959 // Change the kind of this identifier to the appropriate token kind, e.g.
960 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000961 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000962
963 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000964 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000965}
966
Chris Lattner22eb9722006-06-18 05:43:12 +0000967/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
968/// the current file. This either returns the EOF token or pops a level off
969/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000970void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000971 assert(!CurMacroExpander &&
972 "Ending a file when currently in a macro!");
973
974 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
975 // this is an error condition. Just return the EOF token up to
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000976 // SkipExcludedConditionalBlock. The code that enabled skipping will issue
977 // errors for the unterminated #if's on the conditional stack if it is
978 // interested.
Chris Lattner22eb9722006-06-18 05:43:12 +0000979 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000980 Result.StartToken();
981 CurLexer->BufferPtr = CurLexer->BufferEnd;
982 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000983 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000984 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000985 }
986
Chris Lattner371ac8a2006-07-04 07:11:10 +0000987 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000988 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000989 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000990 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000991 // Okay, this has a controlling macro, remember in PerFileInfo.
992 if (const FileEntry *FE =
993 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
994 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +0000995 }
996 }
997
Chris Lattner22eb9722006-06-18 05:43:12 +0000998 // If this is a #include'd file, pop it off the include stack and continue
999 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001000 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001001 // We're done with the #included file.
1002 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +00001003 CurLexer = IncludeMacroStack.back().TheLexer;
1004 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
1005 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
1006 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +00001007
1008 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001009 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001010 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1011
1012 // Get the file entry for the current file.
1013 if (const FileEntry *FE =
1014 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1015 FileType = getFileInfo(FE).DirInfo;
1016
Chris Lattner0c885f52006-06-21 06:50:18 +00001017 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001018 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001019 }
Chris Lattner0c885f52006-06-21 06:50:18 +00001020
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 return Lex(Result);
1022 }
1023
Chris Lattnerd01e2912006-06-18 16:22:51 +00001024 Result.StartToken();
1025 CurLexer->BufferPtr = CurLexer->BufferEnd;
1026 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001027 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001028
1029 // We're done with the #included file.
1030 delete CurLexer;
1031 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001032
Chris Lattner03f83482006-07-10 06:16:26 +00001033 // This is the end of the top-level file. If the diag::pp_macro_not_used
1034 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1035 // have not been used.
1036 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1037 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +00001038}
1039
1040/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnerafe603f2006-07-11 04:02:46 +00001041/// the current macro expansion.
Chris Lattnercb283342006-06-18 06:48:37 +00001042void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001043 assert(CurMacroExpander && !CurLexer &&
1044 "Ending a macro when currently in a #include file!");
1045
1046 // Mark macro not ignored now that it is no longer being expanded.
1047 CurMacroExpander->getMacro().EnableMacro();
1048 delete CurMacroExpander;
1049
Chris Lattner69772b02006-07-02 20:34:39 +00001050 // Handle this like a #include file being popped off the stack.
1051 CurMacroExpander = 0;
1052 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001053}
1054
1055
1056//===----------------------------------------------------------------------===//
1057// Utility Methods for Preprocessor Directive Handling.
1058//===----------------------------------------------------------------------===//
1059
1060/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1061/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001062void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001063 LexerToken Tmp;
1064 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001065 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001067}
1068
1069/// ReadMacroName - Lex and validate a macro name, which occurs after a
1070/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001071/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1072/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001073/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001074void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001075 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001076 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001077
1078 // Missing macro name?
1079 if (MacroNameTok.getKind() == tok::eom)
1080 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1081
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001082 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1083 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001084 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001085 // Fall through on error.
1086 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001087 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001088
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001089 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1090 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001091 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001092 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001093 } else if (isDefineUndef && II->getMacroInfo() &&
1094 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001095 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001096 if (isDefineUndef == 1)
1097 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1098 else
1099 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 } else {
1101 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001102 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 }
1104
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 // Invalid macro name, read and discard the rest of the line. Then set the
1106 // token kind to tok::eom.
1107 MacroNameTok.SetKind(tok::eom);
1108 return DiscardUntilEndOfDirective();
1109}
1110
1111/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1112/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001113void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001115 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 // There should be no tokens after the directive, but we allow them as an
1117 // extension.
1118 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001119 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1120 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001121 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001122}
1123
1124
1125
1126/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1127/// decided that the subsequent tokens are in the #if'd out portion of the
1128/// file. Lex the rest of the file, until we see an #endif. If
1129/// FoundNonSkipPortion is true, then we have already emitted code for part of
1130/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1131/// is true, then #else directives are ok, if not, then we have already seen one
1132/// so a #else directive is a duplicate. When this returns, the caller can lex
1133/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001134void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 bool FoundNonSkipPortion,
1136 bool FoundElse) {
1137 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001138 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001139 "Lexing a macro, not a file?");
1140
1141 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1142 FoundNonSkipPortion, FoundElse);
1143
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001144 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1145 // disabling warnings, etc.
1146 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001147 LexerToken Tok;
1148 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001149 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001150
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001151 // If this is the end of the buffer, we have an error.
1152 if (Tok.getKind() == tok::eof) {
1153 // Emit errors for each unterminated conditional on the stack, including
1154 // the current one.
1155 while (!CurLexer->ConditionalStack.empty()) {
1156 Diag(CurLexer->ConditionalStack.back().IfLoc,
1157 diag::err_pp_unterminated_conditional);
1158 CurLexer->ConditionalStack.pop_back();
1159 }
1160
1161 // Just return and let the caller lex after this #include.
1162 break;
1163 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001164
1165 // If this token is not a preprocessor directive, just skip it.
1166 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1167 continue;
1168
1169 // We just parsed a # character at the start of a line, so we're in
1170 // directive mode. Tell the lexer this so any newlines we see will be
1171 // converted into an EOM token (this terminates the macro).
1172 CurLexer->ParsingPreprocessorDirective = true;
1173
1174 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001175 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001176
1177 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1178 // something bogus), skip it.
1179 if (Tok.getKind() != tok::identifier) {
1180 CurLexer->ParsingPreprocessorDirective = false;
1181 continue;
1182 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001183
Chris Lattner22eb9722006-06-18 05:43:12 +00001184 // If the first letter isn't i or e, it isn't intesting to us. We know that
1185 // this is safe in the face of spelling differences, because there is no way
1186 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001187 // allows us to avoid looking up the identifier info for #define/#undef and
1188 // other common directives.
1189 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1190 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001191 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1192 FirstChar != 'i' && FirstChar != 'e') {
1193 CurLexer->ParsingPreprocessorDirective = false;
1194 continue;
1195 }
1196
Chris Lattnere60165f2006-06-22 06:36:29 +00001197 // Get the identifier name without trigraphs or embedded newlines. Note
1198 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1199 // when skipping.
1200 // TODO: could do this with zero copies in the no-clean case by using
1201 // strncmp below.
1202 char Directive[20];
1203 unsigned IdLen;
1204 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1205 IdLen = Tok.getLength();
1206 memcpy(Directive, RawCharData, IdLen);
1207 Directive[IdLen] = 0;
1208 } else {
1209 std::string DirectiveStr = getSpelling(Tok);
1210 IdLen = DirectiveStr.size();
1211 if (IdLen >= 20) {
1212 CurLexer->ParsingPreprocessorDirective = false;
1213 continue;
1214 }
1215 memcpy(Directive, &DirectiveStr[0], IdLen);
1216 Directive[IdLen] = 0;
1217 }
1218
Chris Lattner22eb9722006-06-18 05:43:12 +00001219 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001220 if ((IdLen == 2) || // "if"
1221 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1222 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001223 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1224 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001225 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001226 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001227 /*foundnonskip*/false,
1228 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001229 }
1230 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001231 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001232 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001233 PPConditionalInfo CondInfo;
1234 CondInfo.WasSkipping = true; // Silence bogus warning.
1235 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1236 assert(!InCond && "Can't be skipping if not in a conditional!");
1237
1238 // If we popped the outermost skipping block, we're done skipping!
1239 if (!CondInfo.WasSkipping)
1240 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001241 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001242 // #else directive in a skipping conditional. If not in some other
1243 // skipping conditional, and if #else hasn't already been seen, enter it
1244 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001245 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001246 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1247
1248 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001249 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001250
1251 // Note that we've seen a #else in this conditional.
1252 CondInfo.FoundElse = true;
1253
1254 // If the conditional is at the top level, and the #if block wasn't
1255 // entered, enter the #else block now.
1256 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1257 CondInfo.FoundNonSkip = true;
1258 break;
1259 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001260 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001261 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1262
1263 bool ShouldEnter;
1264 // If this is in a skipping block or if we're already handled this #if
1265 // block, don't bother parsing the condition.
1266 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001267 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001268 ShouldEnter = false;
1269 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001270 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001271 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001272 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1273 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001274 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001275 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001276 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 }
1278
1279 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001280 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001281
1282 // If this condition is true, enter it!
1283 if (ShouldEnter) {
1284 CondInfo.FoundNonSkip = true;
1285 break;
1286 }
1287 }
1288 }
1289
1290 CurLexer->ParsingPreprocessorDirective = false;
1291 }
1292
1293 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1294 // of the file, just stop skipping and return to lexing whatever came after
1295 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001296 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001297}
1298
1299//===----------------------------------------------------------------------===//
1300// Preprocessor Directive Handling.
1301//===----------------------------------------------------------------------===//
1302
1303/// HandleDirective - This callback is invoked when the lexer sees a # token
1304/// at the start of a line. This consumes the directive, modifies the
1305/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1306/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001307void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001308 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001309
1310 // We just parsed a # character at the start of a line, so we're in directive
1311 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001312 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001313 CurLexer->ParsingPreprocessorDirective = true;
1314
1315 ++NumDirectives;
1316
Chris Lattner371ac8a2006-07-04 07:11:10 +00001317 // We are about to read a token. For the multiple-include optimization FA to
1318 // work, we have to remember if we had read any tokens *before* this
1319 // pp-directive.
1320 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1321
Chris Lattner78186052006-07-09 00:45:31 +00001322 // Read the next token, the directive flavor. This isn't expanded due to
1323 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001324 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001325
Chris Lattner78186052006-07-09 00:45:31 +00001326 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1327 // #define A(x) #x
1328 // A(abc
1329 // #warning blah
1330 // def)
1331 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1332 if (InMacroFormalArgs)
1333 Diag(Result, diag::ext_embedded_directive);
1334
Chris Lattner22eb9722006-06-18 05:43:12 +00001335 switch (Result.getKind()) {
1336 default: break;
1337 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001338 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001339
1340#if 0
1341 case tok::numeric_constant:
1342 // FIXME: implement # 7 line numbers!
1343 break;
1344#endif
1345 case tok::kw_else:
1346 return HandleElseDirective(Result);
1347 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001348 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001349 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001350 // Get the identifier name without trigraphs or embedded newlines.
1351 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001353 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001354 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001355 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001356 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001357 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001358 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001359 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1360 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 break;
1362 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001363 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001364 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001365 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001366 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001367 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001368 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001369 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001370 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001371 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001372 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 break;
1374 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001375 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001376 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001377 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001378 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001379 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001381 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001382 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001383 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1384 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001385 break;
1386 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001387 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1388 return HandleIncludeDirective(Result); // Handle #include.
1389 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001390 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001391 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001392 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 break;
1394 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001395 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001396 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001397 }
1398 break;
1399 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001400 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1401 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 break;
1403 }
1404 break;
1405 }
1406
1407 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001408 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001409
1410 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001411 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001412
1413 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001414}
1415
Chris Lattner01d66cc2006-07-03 22:16:27 +00001416void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 bool isWarning) {
1418 // Read the rest of the line raw. We do this because we don't want macros
1419 // to be expanded and we don't require that the tokens be valid preprocessing
1420 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1421 // collapse multiple consequtive white space between tokens, but this isn't
1422 // specified by the standard.
1423 std::string Message = CurLexer->ReadToEndOfLine();
1424
1425 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001426 return Diag(Tok, DiagID, Message);
1427}
1428
1429/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1430///
1431void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001432 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001433 Diag(Tok, diag::ext_pp_ident_directive);
1434
Chris Lattner371ac8a2006-07-04 07:11:10 +00001435 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001436 LexerToken StrTok;
1437 Lex(StrTok);
1438
1439 // If the token kind isn't a string, it's a malformed directive.
1440 if (StrTok.getKind() != tok::string_literal)
1441 return Diag(StrTok, diag::err_pp_malformed_ident);
1442
1443 // Verify that there is nothing after the string, other than EOM.
1444 CheckEndOfDirective("#ident");
1445
1446 if (IdentHandler)
1447 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001448}
1449
Chris Lattnerb8761832006-06-24 21:31:03 +00001450//===----------------------------------------------------------------------===//
1451// Preprocessor Include Directive Handling.
1452//===----------------------------------------------------------------------===//
1453
Chris Lattner22eb9722006-06-18 05:43:12 +00001454/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1455/// file to be included from the lexer, then include it! This is a common
1456/// routine with functionality shared between #include, #include_next and
1457/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001458void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001459 const DirectoryLookup *LookupFrom,
1460 bool isImport) {
1461 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001462
Chris Lattner22eb9722006-06-18 05:43:12 +00001463 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001464 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001465
1466 // If the token kind is EOM, the error has already been diagnosed.
1467 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001468 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001469
1470 // Verify that there is nothing after the filename, other than EOM. Use the
1471 // preprocessor to lex this in case lexing the filename entered a macro.
1472 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001473
1474 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001475 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001476 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1477
Chris Lattner269c2322006-06-25 06:23:00 +00001478 // Find out whether the filename is <x> or "x".
1479 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001480
1481 // Remove the quotes.
1482 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1483
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001485 const DirectoryLookup *CurDir;
1486 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 if (File == 0)
1488 return Diag(FilenameTok, diag::err_pp_file_not_found);
1489
1490 // Get information about this file.
1491 PerFileInfo &FileInfo = getFileInfo(File);
1492
1493 // If this is a #import directive, check that we have not already imported
1494 // this header.
1495 if (isImport) {
1496 // If this has already been imported, don't import it again.
1497 FileInfo.isImport = true;
1498
1499 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001500 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001501 } else {
1502 // Otherwise, if this is a #include of a file that was previously #import'd
1503 // or if this is the second #include of a #pragma once file, ignore it.
1504 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001505 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 }
Chris Lattner3665f162006-07-04 07:26:10 +00001507
1508 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1509 // if the macro that guards it is defined, we know the #include has no effect.
1510 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1511 ++NumMultiIncludeFileOptzn;
1512 return;
1513 }
1514
Chris Lattner22eb9722006-06-18 05:43:12 +00001515
1516 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001517 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001518 if (FileID == 0)
1519 return Diag(FilenameTok, diag::err_pp_file_not_found);
1520
1521 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001522 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001523
1524 // Increment the number of times this file has been included.
1525 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001526}
1527
1528/// HandleIncludeNextDirective - Implements #include_next.
1529///
Chris Lattnercb283342006-06-18 06:48:37 +00001530void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1531 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001532
1533 // #include_next is like #include, except that we start searching after
1534 // the current found directory. If we can't do this, issue a
1535 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001536 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001537 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001538 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001539 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001540 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001541 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001542 } else {
1543 // Start looking up in the next directory.
1544 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001545 }
1546
1547 return HandleIncludeDirective(IncludeNextTok, Lookup);
1548}
1549
1550/// HandleImportDirective - Implements #import.
1551///
Chris Lattnercb283342006-06-18 06:48:37 +00001552void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1553 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001554
1555 return HandleIncludeDirective(ImportTok, 0, true);
1556}
1557
Chris Lattnerb8761832006-06-24 21:31:03 +00001558//===----------------------------------------------------------------------===//
1559// Preprocessor Macro Directive Handling.
1560//===----------------------------------------------------------------------===//
1561
Chris Lattnercefc7682006-07-08 08:28:12 +00001562/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1563/// definition has just been read. Lex the rest of the arguments and the
1564/// closing ), updating MI with what we learn. Return true if an error occurs
1565/// parsing the arg list.
1566bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1567 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001568 while (1) {
1569 LexUnexpandedToken(Tok);
1570 switch (Tok.getKind()) {
1571 case tok::r_paren:
1572 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001573 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001574 // Otherwise we have #define FOO(A,)
1575 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1576 return true;
1577 case tok::ellipsis: // #define X(... -> C99 varargs
1578 // Warn if use of C99 feature in non-C99 mode.
1579 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1580
1581 // Lex the token after the identifier.
1582 LexUnexpandedToken(Tok);
1583 if (Tok.getKind() != tok::r_paren) {
1584 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1585 return true;
1586 }
1587 MI->setIsC99Varargs();
1588 return false;
1589 case tok::eom: // #define X(
1590 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1591 return true;
1592 default: // #define X(1
1593 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1594 return true;
1595 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001596 IdentifierInfo *II = Tok.getIdentifierInfo();
1597
1598 // If this is already used as an argument, it is used multiple times (e.g.
1599 // #define X(A,A.
1600 if (II->isMacroArg()) { // C99 6.10.3p6
1601 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1602 return true;
1603 }
1604
1605 // Add the argument to the macro info.
1606 MI->addArgument(II);
1607 // Remember it is an argument now.
1608 II->setIsMacroArg(true);
Chris Lattnercefc7682006-07-08 08:28:12 +00001609
1610 // Lex the token after the identifier.
1611 LexUnexpandedToken(Tok);
1612
1613 switch (Tok.getKind()) {
1614 default: // #define X(A B
1615 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1616 return true;
1617 case tok::r_paren: // #define X(A)
1618 return false;
1619 case tok::comma: // #define X(A,
1620 break;
1621 case tok::ellipsis: // #define X(A... -> GCC extension
1622 // Diagnose extension.
1623 Diag(Tok, diag::ext_named_variadic_macro);
1624
1625 // Lex the token after the identifier.
1626 LexUnexpandedToken(Tok);
1627 if (Tok.getKind() != tok::r_paren) {
1628 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1629 return true;
1630 }
1631
1632 MI->setIsGNUVarargs();
1633 return false;
1634 }
1635 }
1636 }
1637}
1638
Chris Lattner22eb9722006-06-18 05:43:12 +00001639/// HandleDefineDirective - Implements #define. This consumes the entire macro
1640/// line then lets the caller lex the next real token.
1641///
Chris Lattnercb283342006-06-18 06:48:37 +00001642void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001643 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001644
Chris Lattner22eb9722006-06-18 05:43:12 +00001645 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001646 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001647
1648 // Error reading macro name? If so, diagnostic already issued.
1649 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001650 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001651
Chris Lattner50b497e2006-06-18 16:32:35 +00001652 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001653
1654 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001655 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001656
Chris Lattner78186052006-07-09 00:45:31 +00001657 // FIXME: Enable __VA_ARGS__.
1658
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001659 // If this is a function-like macro definition, parse the argument list,
1660 // marking each of the identifiers as being used as macro arguments. Also,
1661 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001662 if (Tok.getKind() == tok::eom) {
1663 // If there is no body to this macro, we have no special handling here.
1664 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001665 // This is a function-like macro definition. Read the argument list.
1666 MI->setIsFunctionLike();
1667 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001668 // Clear the "isMacroArg" flags from all the macro arguments parsed.
1669 MI->SetIdentifierIsMacroArgFlags(false);
1670 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001671 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001672 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001673 if (CurLexer->ParsingPreprocessorDirective)
1674 DiscardUntilEndOfDirective();
1675 return;
1676 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001677
Chris Lattner815a1f92006-07-08 20:48:04 +00001678 // Read the first token after the arg list for down below.
1679 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001680 } else if (!Tok.hasLeadingSpace()) {
1681 // C99 requires whitespace between the macro definition and the body. Emit
1682 // a diagnostic for something like "#define X+".
1683 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001684 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001685 } else {
1686 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1687 // one in some cases!
1688 }
1689 } else {
1690 // This is a normal token with leading space. Clear the leading space
1691 // marker on the first token to get proper expansion.
1692 Tok.ClearFlag(LexerToken::LeadingSpace);
1693 }
1694
1695 // Read the rest of the macro body.
1696 while (Tok.getKind() != tok::eom) {
1697 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001698
1699 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001700 // parameters in function-like macro expansions.
1701 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001702 // Get the next token of the macro.
1703 LexUnexpandedToken(Tok);
1704 continue;
1705 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001706
Chris Lattner815a1f92006-07-08 20:48:04 +00001707 // Get the next token of the macro.
1708 LexUnexpandedToken(Tok);
1709
1710 // Not a macro arg identifier?
1711 if (!Tok.getIdentifierInfo() || !Tok.getIdentifierInfo()->isMacroArg()) {
1712 Diag(Tok, diag::err_pp_stringize_not_parameter);
1713 // Clear the "isMacroArg" flags from all the macro arguments.
1714 MI->SetIdentifierIsMacroArgFlags(false);
1715 delete MI;
1716 return;
1717 }
1718
1719 // Things look ok, add the param name token to the macro.
1720 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001721
Chris Lattner22eb9722006-06-18 05:43:12 +00001722 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001723 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001724 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001725
Chris Lattner78186052006-07-09 00:45:31 +00001726 // Clear the "isMacroArg" flags from all the macro arguments.
1727 MI->SetIdentifierIsMacroArgFlags(false);
1728
Chris Lattnerbff18d52006-07-06 04:49:18 +00001729 // Check that there is no paste (##) operator at the begining or end of the
1730 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001731 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001732 if (NumTokens != 0) {
1733 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001734 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001735 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001736 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001737 }
1738 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001739 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001740 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001741 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001742 }
1743 }
1744
Chris Lattner13044d92006-07-03 05:16:44 +00001745 // If this is the primary source file, remember that this macro hasn't been
1746 // used yet.
1747 if (isInPrimaryFile())
1748 MI->setIsUsed(false);
1749
Chris Lattner22eb9722006-06-18 05:43:12 +00001750 // Finally, if this identifier already had a macro defined for it, verify that
1751 // the macro bodies are identical and free the old definition.
1752 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001753 if (!OtherMI->isUsed())
1754 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1755
Chris Lattner22eb9722006-06-18 05:43:12 +00001756 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001757 // must be the same. C99 6.10.3.2.
1758 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001759 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1760 MacroNameTok.getIdentifierInfo()->getName());
1761 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1762 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001763 delete OtherMI;
1764 }
1765
1766 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001767}
1768
1769
1770/// HandleUndefDirective - Implements #undef.
1771///
Chris Lattnercb283342006-06-18 06:48:37 +00001772void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001773 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001774
Chris Lattner22eb9722006-06-18 05:43:12 +00001775 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001776 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001777
1778 // Error reading macro name? If so, diagnostic already issued.
1779 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001780 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001781
1782 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001783 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001784
1785 // Okay, we finally have a valid identifier to undef.
1786 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1787
1788 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001789 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001790
Chris Lattner13044d92006-07-03 05:16:44 +00001791 if (!MI->isUsed())
1792 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001793
1794 // Free macro definition.
1795 delete MI;
1796 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001797}
1798
1799
Chris Lattnerb8761832006-06-24 21:31:03 +00001800//===----------------------------------------------------------------------===//
1801// Preprocessor Conditional Directive Handling.
1802//===----------------------------------------------------------------------===//
1803
Chris Lattner22eb9722006-06-18 05:43:12 +00001804/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001805/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1806/// if any tokens have been returned or pp-directives activated before this
1807/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001808///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001809void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1810 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001811 ++NumIf;
1812 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001813
Chris Lattner22eb9722006-06-18 05:43:12 +00001814 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001815 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001816
1817 // Error reading macro name? If so, diagnostic already issued.
1818 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001819 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001820
1821 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001822 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1823
1824 // If the start of a top-level #ifdef, inform MIOpt.
1825 if (!ReadAnyTokensBeforeDirective &&
1826 CurLexer->getConditionalStackDepth() == 0) {
1827 assert(isIfndef && "#ifdef shouldn't reach here");
1828 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1829 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001830
Chris Lattnera78a97e2006-07-03 05:42:18 +00001831 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1832
1833 // If there is a macro, mark it used.
1834 if (MI) MI->setIsUsed(true);
1835
Chris Lattner22eb9722006-06-18 05:43:12 +00001836 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001837 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001838 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001839 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001840 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001841 } else {
1842 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001843 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001844 /*Foundnonskip*/false,
1845 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001846 }
1847}
1848
1849/// HandleIfDirective - Implements the #if directive.
1850///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001851void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1852 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001853 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001854
Chris Lattner371ac8a2006-07-04 07:11:10 +00001855 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001856 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001857 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001858
1859 // Should we include the stuff contained by this directive?
1860 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001861 // If this condition is equivalent to #ifndef X, and if this is the first
1862 // directive seen, handle it for the multiple-include optimization.
1863 if (!ReadAnyTokensBeforeDirective &&
1864 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1865 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1866
Chris Lattner22eb9722006-06-18 05:43:12 +00001867 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001868 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001869 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001870 } else {
1871 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001872 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001873 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001874 }
1875}
1876
1877/// HandleEndifDirective - Implements the #endif directive.
1878///
Chris Lattnercb283342006-06-18 06:48:37 +00001879void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001880 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001881
Chris Lattner22eb9722006-06-18 05:43:12 +00001882 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001883 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001884
1885 PPConditionalInfo CondInfo;
1886 if (CurLexer->popConditionalLevel(CondInfo)) {
1887 // No conditionals on the stack: this is an #endif without an #if.
1888 return Diag(EndifToken, diag::err_pp_endif_without_if);
1889 }
1890
Chris Lattner371ac8a2006-07-04 07:11:10 +00001891 // If this the end of a top-level #endif, inform MIOpt.
1892 if (CurLexer->getConditionalStackDepth() == 0)
1893 CurLexer->MIOpt.ExitTopLevelConditional();
1894
Chris Lattner22eb9722006-06-18 05:43:12 +00001895 assert(!CondInfo.WasSkipping && !isSkipping() &&
1896 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001897}
1898
1899
Chris Lattnercb283342006-06-18 06:48:37 +00001900void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001901 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001902
Chris Lattner22eb9722006-06-18 05:43:12 +00001903 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001904 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001905
1906 PPConditionalInfo CI;
1907 if (CurLexer->popConditionalLevel(CI))
1908 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001909
1910 // If this is a top-level #else, inform the MIOpt.
1911 if (CurLexer->getConditionalStackDepth() == 0)
1912 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001913
1914 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001915 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001916
1917 // Finally, skip the rest of the contents of this block and return the first
1918 // token after it.
1919 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1920 /*FoundElse*/true);
1921}
1922
Chris Lattnercb283342006-06-18 06:48:37 +00001923void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001924 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001925
Chris Lattner22eb9722006-06-18 05:43:12 +00001926 // #elif directive in a non-skipping conditional... start skipping.
1927 // We don't care what the condition is, because we will always skip it (since
1928 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001929 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001930
1931 PPConditionalInfo CI;
1932 if (CurLexer->popConditionalLevel(CI))
1933 return Diag(ElifToken, diag::pp_err_elif_without_if);
1934
Chris Lattner371ac8a2006-07-04 07:11:10 +00001935 // If this is a top-level #elif, inform the MIOpt.
1936 if (CurLexer->getConditionalStackDepth() == 0)
1937 CurLexer->MIOpt.FoundTopLevelElse();
1938
Chris Lattner22eb9722006-06-18 05:43:12 +00001939 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001940 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001941
1942 // Finally, skip the rest of the contents of this block and return the first
1943 // token after it.
1944 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1945 /*FoundElse*/CI.FoundElse);
1946}
Chris Lattnerb8761832006-06-24 21:31:03 +00001947