blob: 71f315d03d8a705c6f950e762e3c08efdfe18853 [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;
Chris Lattner510ab612006-07-20 04:47:30 +000054 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 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 Lattneree8760b2006-07-15 07:42:55 +000060 InMacroArgs = 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) {
Chris Lattnercb283342006-06-18 06:48:37 +0000136 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000137}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000138
139void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
140 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
141 << getSpelling(Tok) << "'";
142
143 if (!DumpFlags) return;
144 std::cerr << "\t";
145 if (Tok.isAtStartOfLine())
146 std::cerr << " [StartOfLine]";
147 if (Tok.hasLeadingSpace())
148 std::cerr << " [LeadingSpace]";
149 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000150 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000151 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
152 << "']";
153 }
154}
155
156void Preprocessor::DumpMacro(const MacroInfo &MI) const {
157 std::cerr << "MACRO: ";
158 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
159 DumpToken(MI.getReplacementToken(i));
160 std::cerr << " ";
161 }
162 std::cerr << "\n";
163}
164
Chris Lattner22eb9722006-06-18 05:43:12 +0000165void Preprocessor::PrintStats() {
166 std::cerr << "\n*** Preprocessor Stats:\n";
167 std::cerr << FileInfo.size() << " files tracked.\n";
168 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
169 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
170 NumOnceOnlyFiles += FileInfo[i].isImport;
171 if (MaxNumIncludes < FileInfo[i].NumIncludes)
172 MaxNumIncludes = FileInfo[i].NumIncludes;
173 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
174 }
175 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
176 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
177 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
178
179 std::cerr << NumDirectives << " directives found:\n";
180 std::cerr << " " << NumDefined << " #define.\n";
181 std::cerr << " " << NumUndefined << " #undef.\n";
182 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000183 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
184 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000185 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
186 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
187 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
188 std::cerr << " " << NumElse << " #else/#elif.\n";
189 std::cerr << " " << NumEndif << " #endif.\n";
190 std::cerr << " " << NumPragma << " #pragma.\n";
191 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
192
Chris Lattner78186052006-07-09 00:45:31 +0000193 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
194 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000195 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000196 std::cerr << (NumFastTokenPaste+NumTokenPaste)
197 << " token paste (##) operations performed, "
198 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000199}
200
201//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000202// Token Spelling
203//===----------------------------------------------------------------------===//
204
205
206/// getSpelling() - Return the 'spelling' of this token. The spelling of a
207/// token are the characters used to represent the token in the source file
208/// after trigraph expansion and escaped-newline folding. In particular, this
209/// wants to get the true, uncanonicalized, spelling of things like digraphs
210/// UCNs, etc.
211std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
212 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
213
214 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000215 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000216 if (!Tok.needsCleaning())
217 return std::string(TokStart, TokStart+Tok.getLength());
218
Chris Lattnerd01e2912006-06-18 16:22:51 +0000219 std::string Result;
220 Result.reserve(Tok.getLength());
221
Chris Lattneref9eae12006-07-04 22:33:12 +0000222 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
224 Ptr != End; ) {
225 unsigned CharSize;
226 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
227 Ptr += CharSize;
228 }
229 assert(Result.size() != unsigned(Tok.getLength()) &&
230 "NeedsCleaning flag set on something that didn't need cleaning!");
231 return Result;
232}
233
234/// getSpelling - This method is used to get the spelling of a token into a
235/// preallocated buffer, instead of as an std::string. The caller is required
236/// to allocate enough space for the token, which is guaranteed to be at least
237/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000238///
239/// Note that this method may do two possible things: it may either fill in
240/// the buffer specified with characters, or it may *change the input pointer*
241/// to point to a constant buffer with the data already in it (avoiding a
242/// copy). The caller is not allowed to modify the returned buffer pointer
243/// if an internal buffer is returned.
244unsigned Preprocessor::getSpelling(const LexerToken &Tok,
245 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000246 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
247
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000248 // If this token is an identifier, just return the string from the identifier
249 // table, which is very quick.
250 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
251 Buffer = II->getName();
252 return Tok.getLength();
253 }
254
255 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000256 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000257
258 // If this token contains nothing interesting, return it directly.
259 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000260 Buffer = TokStart;
261 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000262 }
263 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000264 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000265 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
266 Ptr != End; ) {
267 unsigned CharSize;
268 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
269 Ptr += CharSize;
270 }
271 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
272 "NeedsCleaning flag set on something that didn't need cleaning!");
273
274 return OutBuf-Buffer;
275}
276
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000277
278/// CreateString - Plop the specified string into a scratch buffer and return a
279/// location for it. If specified, the source location provides a source
280/// location for the token.
281SourceLocation Preprocessor::
282CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
283 if (SLoc.isValid())
284 return ScratchBuf->getToken(Buf, Len, SLoc);
285 return ScratchBuf->getToken(Buf, Len);
286}
287
288
Chris Lattnerd01e2912006-06-18 16:22:51 +0000289//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000290// Source File Location Methods.
291//===----------------------------------------------------------------------===//
292
293
294/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
295/// return null on failure. isAngled indicates whether the file reference is
296/// for system #include's or not (i.e. using <> instead of "").
297const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000298 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000299 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000300 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000301 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000302 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000303
304 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000305 // FIXME: Portability. This should be a sys::Path interface, this doesn't
306 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000307 if (Filename[0] == '/') {
308 // If this was an #include_next "/absolute/file", fail.
309 if (FromDir) return 0;
310
311 // Otherwise, just return the file.
312 return FileMgr.getFile(Filename);
313 }
314
315 // Step #0, unless disabled, check to see if the file is in the #includer's
316 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000317 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000318 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
319 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000320 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000321 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000322 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000323 if (const FileEntry *FE =
324 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000325 if (CurDirLookup)
326 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000327 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000328 CurDir = 0;
329
330 // This file is a system header or C++ unfriendly if the old file is.
331 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000332 return FE;
333 }
334 }
335 }
336
337 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000338 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000339
340 // If this is a #include_next request, start searching after the directory the
341 // file was found in.
342 if (FromDir)
343 i = FromDir-&SearchDirs[0];
344
345 // Check each directory in sequence to see if it contains this file.
346 for (; i != SearchDirs.size(); ++i) {
347 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000348 // FIXME: Portability. Adding file to dir should be in sys::Path.
349 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
350 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000351 CurDir = &SearchDirs[i];
352
353 // This file is a system header or C++ unfriendly if the dir is.
354 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000355 return FE;
356 }
357 }
358
359 // Otherwise, didn't find it.
360 return 0;
361}
362
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000363/// isInPrimaryFile - Return true if we're in the top-level file, not in a
364/// #include.
365bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000366 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000367 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368
Chris Lattner13044d92006-07-03 05:16:44 +0000369 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000370 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000371 if (IncludeMacroStack[i].TheLexer &&
372 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
373 return IncludeMacroStack[i].TheLexer->isMainFile();
374 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000375}
376
377/// getCurrentLexer - Return the current file lexer being lexed from. Note
378/// that this ignores any potentially active macro expansions and _Pragma
379/// expansions going on at the time.
380Lexer *Preprocessor::getCurrentFileLexer() const {
381 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
382
383 // Look for a stacked lexer.
384 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000385 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000386 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
387 return L;
388 }
389 return 0;
390}
391
392
Chris Lattner22eb9722006-06-18 05:43:12 +0000393/// EnterSourceFile - Add a source file to the top of the include stack and
394/// start lexing tokens from it instead of the current buffer. Return true
395/// on failure.
396void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000397 const DirectoryLookup *CurDir,
398 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000399 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000400 ++NumEnteredSourceFiles;
401
Chris Lattner69772b02006-07-02 20:34:39 +0000402 if (MaxIncludeStackDepth < IncludeMacroStack.size())
403 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000404
Chris Lattner22eb9722006-06-18 05:43:12 +0000405 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000406 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000407 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000408 EnterSourceFileWithLexer(TheLexer, CurDir);
409}
Chris Lattner22eb9722006-06-18 05:43:12 +0000410
Chris Lattner69772b02006-07-02 20:34:39 +0000411/// EnterSourceFile - Add a source file to the top of the include stack and
412/// start lexing tokens from it instead of the current buffer.
413void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
414 const DirectoryLookup *CurDir) {
415
416 // Add the current lexer to the include stack.
417 if (CurLexer || CurMacroExpander)
418 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
419 CurMacroExpander));
420
421 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000422 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000423 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000424
425 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000426 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000427 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
428
429 // Get the file entry for the current file.
430 if (const FileEntry *FE =
431 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
432 FileType = getFileInfo(FE).DirInfo;
433
Chris Lattner1840e492006-07-02 22:30:01 +0000434 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000435 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000436 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000437}
438
Chris Lattner69772b02006-07-02 20:34:39 +0000439
440
Chris Lattner22eb9722006-06-18 05:43:12 +0000441/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000442/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000443void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000444 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000445 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000446 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
447 CurMacroExpander));
448 CurLexer = 0;
449 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000450
Chris Lattneree8760b2006-07-15 07:42:55 +0000451 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000452}
453
Chris Lattner7667d0d2006-07-16 18:16:58 +0000454/// EnterTokenStream - Add a "macro" context to the top of the include stack,
455/// which will cause the lexer to start returning the specified tokens. Note
456/// that these tokens will be re-macro-expanded when/if expansion is enabled.
457/// This method assumes that the specified stream of tokens has a permanent
458/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000459void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000460 // Save our current state.
461 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
462 CurMacroExpander));
463 CurLexer = 0;
464 CurDirLookup = 0;
465
466 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000467 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000468}
469
470/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
471/// lexer stack. This should only be used in situations where the current
472/// state of the top-of-stack lexer is known.
473void Preprocessor::RemoveTopOfLexerStack() {
474 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
475 delete CurLexer;
476 delete CurMacroExpander;
477 CurLexer = IncludeMacroStack.back().TheLexer;
478 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
479 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
480 IncludeMacroStack.pop_back();
481}
482
Chris Lattner22eb9722006-06-18 05:43:12 +0000483//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000484// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000485//===----------------------------------------------------------------------===//
486
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000487/// RegisterBuiltinMacro - Register the specified identifier in the identifier
488/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000489IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000490 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000491 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000492
493 // Mark it as being a macro that is builtin.
494 MacroInfo *MI = new MacroInfo(SourceLocation());
495 MI->setIsBuiltinMacro();
496 Id->setMacroInfo(MI);
497 return Id;
498}
499
500
Chris Lattner677757a2006-06-28 05:26:32 +0000501/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
502/// identifier table.
503void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000504 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000505 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000506 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
507 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000508 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000509
510 // GCC Extensions.
511 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
512 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000513 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000514}
515
Chris Lattnerc2395832006-07-09 00:57:04 +0000516/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
517/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000518static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
519 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000520 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
521
522 // If the token isn't an identifier, it's always literally expanded.
523 if (II == 0) return true;
524
525 // If the identifier is a macro, and if that macro is enabled, it may be
526 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000527 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
528 // Fast expanding "#define X X" is ok, because X would be disabled.
529 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000530 return false;
531
532 // If this is an object-like macro invocation, it is safe to trivially expand
533 // it.
534 if (MI->isObjectLike()) return true;
535
536 // If this is a function-like macro invocation, it's safe to trivially expand
537 // as long as the identifier is not a macro argument.
538 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
539 I != E; ++I)
540 if (*I == II)
541 return false; // Identifier is a macro argument.
542 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000543}
544
Chris Lattnerc2395832006-07-09 00:57:04 +0000545
Chris Lattnerafe603f2006-07-11 04:02:46 +0000546/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
547/// lexed is a '('. If so, consume the token and return true, if not, this
548/// method should have no observable side-effect on the lexed tokens.
549bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000550 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000551 unsigned Val;
552 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000553 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000554 else
555 Val = CurMacroExpander->isNextTokenLParen();
556
557 if (Val == 2) {
558 // If we ran off the end of the lexer or macro expander, walk the include
559 // stack, looking for whatever will return the next token.
560 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
561 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
562 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000563 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000564 else
565 Val = Entry.TheMacroExpander->isNextTokenLParen();
566 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000567 }
568
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000569 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
570 // have found something that isn't a '(' or we found the end of the
571 // translation unit. In either case, return false.
572 if (Val != 1)
573 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000574
575 LexerToken Tok;
576 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000577 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
578 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000579}
Chris Lattner677757a2006-06-28 05:26:32 +0000580
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000581/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
582/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000583bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000584 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000585
586 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
587 if (MI->isBuiltinMacro()) {
588 ExpandBuiltinMacro(Identifier);
589 return false;
590 }
591
Chris Lattneree8760b2006-07-15 07:42:55 +0000592 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000593 /// for each macro argument, the list of tokens that were provided to the
594 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000595 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000596
597 // If this is a function-like macro, read the arguments.
598 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000599 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
600 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000601 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000602 return true;
603
Chris Lattner78186052006-07-09 00:45:31 +0000604 // Remember that we are now parsing the arguments to a macro invocation.
605 // Preprocessor directives used inside macro arguments are not portable, and
606 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000607 InMacroArgs = true;
608 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000609
610 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000611 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000612
613 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000614 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000615
616 ++NumFnMacroExpanded;
617 } else {
618 ++NumMacroExpanded;
619 }
Chris Lattner13044d92006-07-03 05:16:44 +0000620
621 // Notice that this macro has been used.
622 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000623
624 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000625
626 // If this macro expands to no tokens, don't bother to push it onto the
627 // expansion stack, only to take it right back off.
628 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000629 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000630 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000631
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000632 // Ignore this macro use, just return the next token in the current
633 // buffer.
634 bool HadLeadingSpace = Identifier.hasLeadingSpace();
635 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
636
637 Lex(Identifier);
638
639 // If the identifier isn't on some OTHER line, inherit the leading
640 // whitespace/first-on-a-line property of this token. This handles
641 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
642 // empty.
643 if (!Identifier.isAtStartOfLine()) {
644 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
645 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
646 }
647 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000648 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000649
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000650 } else if (MI->getNumTokens() == 1 &&
651 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000652 // Otherwise, if this macro expands into a single trivially-expanded
653 // token: expand it now. This handles common cases like
654 // "#define VAL 42".
655
656 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
657 // identifier to the expanded token.
658 bool isAtStartOfLine = Identifier.isAtStartOfLine();
659 bool hasLeadingSpace = Identifier.hasLeadingSpace();
660
661 // Remember where the token is instantiated.
662 SourceLocation InstantiateLoc = Identifier.getLocation();
663
664 // Replace the result token.
665 Identifier = MI->getReplacementToken(0);
666
667 // Restore the StartOfLine/LeadingSpace markers.
668 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
669 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
670
671 // Update the tokens location to include both its logical and physical
672 // locations.
673 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000674 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000675 Identifier.SetLocation(Loc);
676
677 // Since this is not an identifier token, it can't be macro expanded, so
678 // we're done.
679 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000680 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000681 }
682
Chris Lattner78186052006-07-09 00:45:31 +0000683 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000684 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000685
686 // Now that the macro is at the top of the include stack, ask the
687 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000688 Lex(Identifier);
689 return false;
690}
691
Chris Lattneree8760b2006-07-15 07:42:55 +0000692/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000693/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000694/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000695MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
696 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000697 // The number of fixed arguments to parse.
698 unsigned NumFixedArgsLeft = MI->getNumArgs();
699 bool isVariadic = MI->isVariadic();
700
701 // If this is a C99-style varargs macro invocation, add an extra expected
Chris Lattner2ada5d32006-07-15 07:51:24 +0000702 // argument, which will catch all of the vararg args in one argument.
Chris Lattner78186052006-07-09 00:45:31 +0000703 if (MI->isC99Varargs())
704 ++NumFixedArgsLeft;
705
706 // Outer loop, while there are more arguments, keep reading them.
707 LexerToken Tok;
708 Tok.SetKind(tok::comma);
709 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000710
711 // ArgTokens - Build up a list of tokens that make up each argument. Each
712 // argument is separated by an EOF token.
713 std::vector<LexerToken> ArgTokens;
714
715 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000716 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000717 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
718 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000719
Chris Lattner78186052006-07-09 00:45:31 +0000720 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000721 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
722 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000723 LexUnexpandedToken(Tok);
724
725 if (Tok.getKind() == tok::eof) {
726 Diag(MacroName, diag::err_unterm_macro_invoc);
727 // Do not lose the EOF. Return it to the client.
728 MacroName = Tok;
729 return 0;
730 } else if (Tok.getKind() == tok::r_paren) {
731 // If we found the ) token, the macro arg list is done.
732 if (NumParens-- == 0)
733 break;
734 } else if (Tok.getKind() == tok::l_paren) {
735 ++NumParens;
736 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
737 // Comma ends this argument if there are more fixed arguments expected.
738 if (NumFixedArgsLeft)
739 break;
740
Chris Lattner2ada5d32006-07-15 07:51:24 +0000741 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000742 if (!isVariadic) {
743 // Emit the diagnostic at the macro name in case there is a missing ).
744 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000745 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000746 return 0;
747 }
748 // Otherwise, continue to add the tokens to this variable argument.
749 }
750
751 ArgTokens.push_back(Tok);
752 }
753
Chris Lattnera12dd152006-07-11 04:09:02 +0000754 // Empty arguments are standard in C99 and supported as an extension in
755 // other modes.
756 if (ArgTokens.empty() && !Features.C99)
757 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000758
Chris Lattner36b6e812006-07-21 06:38:30 +0000759 // Add a marker EOF token to the end of the token list for this argument.
760 LexerToken EOFTok;
761 EOFTok.StartToken();
762 EOFTok.SetKind(tok::eof);
763 EOFTok.SetLocation(Tok.getLocation());
764 EOFTok.SetLength(0);
765 ArgTokens.push_back(EOFTok);
766 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000767 --NumFixedArgsLeft;
768 };
769
770 // Okay, we either found the r_paren. Check to see if we parsed too few
771 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000772 unsigned MinArgsExpected = MI->getNumArgs();
773
774 // C99 expects us to pass at least one vararg arg (but as an extension, we
Chris Lattnerc2395832006-07-09 00:57:04 +0000775 // don't require this). GNU-style varargs already include the 'rest' name in
776 // the count.
777 MinArgsExpected += MI->isC99Varargs();
Chris Lattner78186052006-07-09 00:45:31 +0000778
Chris Lattner2ada5d32006-07-15 07:51:24 +0000779 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000780 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000781 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000782 // Varargs where the named vararg parameter is missing: ok as extension.
783 // #define A(x, ...)
784 // A("blah")
785 Diag(Tok, diag::ext_missing_varargs_arg);
786 } else if (MI->getNumArgs() == 1) {
787 // #define A(x)
788 // A()
Chris Lattnerafe603f2006-07-11 04:02:46 +0000789 // is ok because it is an empty argument. Add it explicitly.
Chris Lattner36b6e812006-07-21 06:38:30 +0000790
791
792 // Add a marker EOF token to the end of the token list for this argument.
793 SourceLocation EndLoc = Tok.getLocation();
794 Tok.StartToken();
795 Tok.SetKind(tok::eof);
796 Tok.SetLocation(EndLoc);
797 Tok.SetLength(0);
798 ArgTokens.push_back(Tok);
Chris Lattnera12dd152006-07-11 04:09:02 +0000799
800 // Empty arguments are standard in C99 and supported as an extension in
801 // other modes.
802 if (ArgTokens.empty() && !Features.C99)
803 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000804 } else {
805 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000806 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000807 return 0;
808 }
809 }
810
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000811 return MacroArgs::create(MI, ArgTokens);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000812}
813
Chris Lattnerc673f902006-06-30 06:10:41 +0000814/// ComputeDATE_TIME - Compute the current time, enter it into the specified
815/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
816/// the identifier tokens inserted.
817static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000818 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000819 time_t TT = time(0);
820 struct tm *TM = localtime(&TT);
821
822 static const char * const Months[] = {
823 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
824 };
825
826 char TmpBuffer[100];
827 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
828 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000829 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000830
831 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000832 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000833}
834
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000835/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
836/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000837void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000838 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000839 IdentifierInfo *II = Tok.getIdentifierInfo();
840 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000841
842 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
843 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000844 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000845 return Handle_Pragma(Tok);
846
Chris Lattner78186052006-07-09 00:45:31 +0000847 ++NumBuiltinMacroExpanded;
848
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000849 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000850
851 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000852 Tok.SetIdentifierInfo(0);
853 Tok.ClearFlag(LexerToken::NeedsCleaning);
854
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000855 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000856 // __LINE__ expands to a simple numeric value.
857 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
858 unsigned Length = strlen(TmpBuffer);
859 Tok.SetKind(tok::numeric_constant);
860 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000861 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000862 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000863 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000864 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000865 Diag(Tok, diag::ext_pp_base_file);
866 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
867 while (NextLoc.getFileID() != 0) {
868 Loc = NextLoc;
869 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
870 }
871 }
872
Chris Lattner0766e592006-07-03 01:07:01 +0000873 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
874 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000875 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000876 Tok.SetKind(tok::string_literal);
877 Tok.SetLength(FN.size());
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000878 Tok.SetLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000879 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000880 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000881 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000882 Tok.SetKind(tok::string_literal);
883 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
884 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000885 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000886 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000887 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattnerc673f902006-06-30 06:10:41 +0000888 Tok.SetKind(tok::string_literal);
889 Tok.SetLength(strlen("\"hh:mm:ss\""));
890 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000891 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000892 Diag(Tok, diag::ext_pp_include_level);
893
894 // Compute the include depth of this token.
895 unsigned Depth = 0;
896 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
897 for (; Loc.getFileID() != 0; ++Depth)
898 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
899
900 // __INCLUDE_LEVEL__ expands to a simple numeric value.
901 sprintf(TmpBuffer, "%u", Depth);
902 unsigned Length = strlen(TmpBuffer);
903 Tok.SetKind(tok::numeric_constant);
904 Tok.SetLength(Length);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000905 Tok.SetLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000906 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000907 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
908 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
909 Diag(Tok, diag::ext_pp_timestamp);
910
911 // Get the file that we are lexing out of. If we're currently lexing from
912 // a macro, dig into the include stack.
913 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000914 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000915
916 if (TheLexer)
917 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
918
919 // If this file is older than the file it depends on, emit a diagnostic.
920 const char *Result;
921 if (CurFile) {
922 time_t TT = CurFile->getModificationTime();
923 struct tm *TM = localtime(&TT);
924 Result = asctime(TM);
925 } else {
926 Result = "??? ??? ?? ??:??:?? ????\n";
927 }
928 TmpBuffer[0] = '"';
929 strcpy(TmpBuffer+1, Result);
930 unsigned Len = strlen(TmpBuffer);
931 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
932 Tok.SetKind(tok::string_literal);
933 Tok.SetLength(Len);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000934 Tok.SetLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000935 } else {
936 assert(0 && "Unknown identifier!");
937 }
938}
Chris Lattner677757a2006-06-28 05:26:32 +0000939
Chris Lattner13044d92006-07-03 05:16:44 +0000940namespace {
941struct UnusedIdentifierReporter : public IdentifierVisitor {
942 Preprocessor &PP;
943 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
944
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000945 void VisitIdentifier(IdentifierInfo &II) const {
946 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
947 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000948 }
949};
950}
951
Chris Lattner677757a2006-06-28 05:26:32 +0000952//===----------------------------------------------------------------------===//
953// Lexer Event Handling.
954//===----------------------------------------------------------------------===//
955
Chris Lattnercefc7682006-07-08 08:28:12 +0000956/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
957/// identifier information for the token and install it into the token.
958IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
959 const char *BufPtr) {
960 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
961 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
962
963 // Look up this token, see if it is a macro, or if it is a language keyword.
964 IdentifierInfo *II;
965 if (BufPtr && !Identifier.needsCleaning()) {
966 // No cleaning needed, just use the characters from the lexed buffer.
967 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
968 } else {
969 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
970 const char *TmpBuf = (char*)alloca(Identifier.getLength());
971 unsigned Size = getSpelling(Identifier, TmpBuf);
972 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
973 }
974 Identifier.SetIdentifierInfo(II);
975 return II;
976}
977
978
Chris Lattner677757a2006-06-28 05:26:32 +0000979/// HandleIdentifier - This callback is invoked when the lexer reads an
980/// identifier. This callback looks up the identifier in the map and/or
981/// potentially macro expands it or turns it into a named token (like 'for').
982void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000983 assert(Identifier.getIdentifierInfo() &&
984 "Can't handle identifiers without identifier info!");
985
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000986 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000987
988 // If this identifier was poisoned, and if it was not produced from a macro
989 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000990 if (II.isPoisoned() && CurLexer) {
991 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
992 Diag(Identifier, diag::err_pp_used_poisoned_id);
993 else
994 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
995 }
Chris Lattner677757a2006-06-28 05:26:32 +0000996
Chris Lattner78186052006-07-09 00:45:31 +0000997 // If this is a macro to be expanded, do it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000998 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000999 if (MI->isEnabled() && !DisableMacroExpansion)
Chris Lattner78186052006-07-09 00:45:31 +00001000 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1001 return;
Chris Lattner677757a2006-06-28 05:26:32 +00001002
1003 // Change the kind of this identifier to the appropriate token kind, e.g.
1004 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001005 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001006
1007 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001008 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001009}
1010
Chris Lattner22eb9722006-06-18 05:43:12 +00001011/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1012/// the current file. This either returns the EOF token or pops a level off
1013/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001014bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001015 assert(!CurMacroExpander &&
1016 "Ending a file when currently in a macro!");
1017
Chris Lattner371ac8a2006-07-04 07:11:10 +00001018 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001019 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001020 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001021 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001022 // Okay, this has a controlling macro, remember in PerFileInfo.
1023 if (const FileEntry *FE =
1024 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1025 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001026 }
1027 }
1028
Chris Lattner22eb9722006-06-18 05:43:12 +00001029 // If this is a #include'd file, pop it off the include stack and continue
1030 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001031 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001032 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001033 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001034
1035 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +00001036 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001037 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1038
1039 // Get the file entry for the current file.
1040 if (const FileEntry *FE =
1041 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1042 FileType = getFileInfo(FE).DirInfo;
1043
Chris Lattner0c885f52006-06-21 06:50:18 +00001044 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +00001045 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001046 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001047
1048 // Client should lex another token.
1049 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001050 }
1051
Chris Lattnerd01e2912006-06-18 16:22:51 +00001052 Result.StartToken();
1053 CurLexer->BufferPtr = CurLexer->BufferEnd;
1054 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +00001055 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001056
1057 // We're done with the #included file.
1058 delete CurLexer;
1059 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001060
Chris Lattner03f83482006-07-10 06:16:26 +00001061 // This is the end of the top-level file. If the diag::pp_macro_not_used
1062 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1063 // have not been used.
1064 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1065 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001066
1067 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001068}
1069
1070/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001071/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001072bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001073 assert(CurMacroExpander && !CurLexer &&
1074 "Ending a macro when currently in a #include file!");
1075
Chris Lattner22eb9722006-06-18 05:43:12 +00001076 delete CurMacroExpander;
1077
Chris Lattner69772b02006-07-02 20:34:39 +00001078 // Handle this like a #include file being popped off the stack.
1079 CurMacroExpander = 0;
1080 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001081}
1082
1083
1084//===----------------------------------------------------------------------===//
1085// Utility Methods for Preprocessor Directive Handling.
1086//===----------------------------------------------------------------------===//
1087
1088/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1089/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001090void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 LexerToken Tmp;
1092 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001093 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001095}
1096
1097/// ReadMacroName - Lex and validate a macro name, which occurs after a
1098/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001099/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1100/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001101/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001102void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001104 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001105
1106 // Missing macro name?
1107 if (MacroNameTok.getKind() == tok::eom)
1108 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1109
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001110 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1111 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001112 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001113 // Fall through on error.
1114 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001115 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001116
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001117 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1118 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001119 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001120 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001121 } else if (isDefineUndef && II->getMacroInfo() &&
1122 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001123 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001124 if (isDefineUndef == 1)
1125 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1126 else
1127 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001128 } else {
1129 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001130 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 }
1132
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 // Invalid macro name, read and discard the rest of the line. Then set the
1134 // token kind to tok::eom.
1135 MacroNameTok.SetKind(tok::eom);
1136 return DiscardUntilEndOfDirective();
1137}
1138
1139/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1140/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001141void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001142 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001143 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001144 // There should be no tokens after the directive, but we allow them as an
1145 // extension.
1146 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001147 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1148 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001149 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001150}
1151
1152
1153
1154/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1155/// decided that the subsequent tokens are in the #if'd out portion of the
1156/// file. Lex the rest of the file, until we see an #endif. If
1157/// FoundNonSkipPortion is true, then we have already emitted code for part of
1158/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1159/// is true, then #else directives are ok, if not, then we have already seen one
1160/// so a #else directive is a duplicate. When this returns, the caller can lex
1161/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001162void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001163 bool FoundNonSkipPortion,
1164 bool FoundElse) {
1165 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001166 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001167 "Lexing a macro, not a file?");
1168
1169 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1170 FoundNonSkipPortion, FoundElse);
1171
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001172 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1173 // disabling warnings, etc.
1174 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001175 LexerToken Tok;
1176 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001177 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001178
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001179 // If this is the end of the buffer, we have an error.
1180 if (Tok.getKind() == tok::eof) {
1181 // Emit errors for each unterminated conditional on the stack, including
1182 // the current one.
1183 while (!CurLexer->ConditionalStack.empty()) {
1184 Diag(CurLexer->ConditionalStack.back().IfLoc,
1185 diag::err_pp_unterminated_conditional);
1186 CurLexer->ConditionalStack.pop_back();
1187 }
1188
1189 // Just return and let the caller lex after this #include.
1190 break;
1191 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001192
1193 // If this token is not a preprocessor directive, just skip it.
1194 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1195 continue;
1196
1197 // We just parsed a # character at the start of a line, so we're in
1198 // directive mode. Tell the lexer this so any newlines we see will be
1199 // converted into an EOM token (this terminates the macro).
1200 CurLexer->ParsingPreprocessorDirective = true;
1201
1202 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001203 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001204
1205 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1206 // something bogus), skip it.
1207 if (Tok.getKind() != tok::identifier) {
1208 CurLexer->ParsingPreprocessorDirective = false;
1209 continue;
1210 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001211
Chris Lattner22eb9722006-06-18 05:43:12 +00001212 // If the first letter isn't i or e, it isn't intesting to us. We know that
1213 // this is safe in the face of spelling differences, because there is no way
1214 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001215 // allows us to avoid looking up the identifier info for #define/#undef and
1216 // other common directives.
1217 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1218 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001219 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1220 FirstChar != 'i' && FirstChar != 'e') {
1221 CurLexer->ParsingPreprocessorDirective = false;
1222 continue;
1223 }
1224
Chris Lattnere60165f2006-06-22 06:36:29 +00001225 // Get the identifier name without trigraphs or embedded newlines. Note
1226 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1227 // when skipping.
1228 // TODO: could do this with zero copies in the no-clean case by using
1229 // strncmp below.
1230 char Directive[20];
1231 unsigned IdLen;
1232 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1233 IdLen = Tok.getLength();
1234 memcpy(Directive, RawCharData, IdLen);
1235 Directive[IdLen] = 0;
1236 } else {
1237 std::string DirectiveStr = getSpelling(Tok);
1238 IdLen = DirectiveStr.size();
1239 if (IdLen >= 20) {
1240 CurLexer->ParsingPreprocessorDirective = false;
1241 continue;
1242 }
1243 memcpy(Directive, &DirectiveStr[0], IdLen);
1244 Directive[IdLen] = 0;
1245 }
1246
Chris Lattner22eb9722006-06-18 05:43:12 +00001247 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001248 if ((IdLen == 2) || // "if"
1249 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1250 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1252 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001253 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001254 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001255 /*foundnonskip*/false,
1256 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 }
1258 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001259 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001260 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001261 PPConditionalInfo CondInfo;
1262 CondInfo.WasSkipping = true; // Silence bogus warning.
1263 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1264 assert(!InCond && "Can't be skipping if not in a conditional!");
1265
1266 // If we popped the outermost skipping block, we're done skipping!
1267 if (!CondInfo.WasSkipping)
1268 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001269 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001270 // #else directive in a skipping conditional. If not in some other
1271 // skipping conditional, and if #else hasn't already been seen, enter it
1272 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001273 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001274 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1275
1276 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001277 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001278
1279 // Note that we've seen a #else in this conditional.
1280 CondInfo.FoundElse = true;
1281
1282 // If the conditional is at the top level, and the #if block wasn't
1283 // entered, enter the #else block now.
1284 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1285 CondInfo.FoundNonSkip = true;
1286 break;
1287 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001288 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1290
1291 bool ShouldEnter;
1292 // If this is in a skipping block or if we're already handled this #if
1293 // block, don't bother parsing the condition.
1294 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001295 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 ShouldEnter = false;
1297 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001298 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001299 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001300 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1301 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001302 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001303 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001304 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001305 }
1306
1307 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001308 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001309
1310 // If this condition is true, enter it!
1311 if (ShouldEnter) {
1312 CondInfo.FoundNonSkip = true;
1313 break;
1314 }
1315 }
1316 }
1317
1318 CurLexer->ParsingPreprocessorDirective = false;
1319 }
1320
1321 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1322 // of the file, just stop skipping and return to lexing whatever came after
1323 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001324 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001325}
1326
1327//===----------------------------------------------------------------------===//
1328// Preprocessor Directive Handling.
1329//===----------------------------------------------------------------------===//
1330
1331/// HandleDirective - This callback is invoked when the lexer sees a # token
1332/// at the start of a line. This consumes the directive, modifies the
1333/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1334/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001335void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001336 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001337
1338 // We just parsed a # character at the start of a line, so we're in directive
1339 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001340 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 CurLexer->ParsingPreprocessorDirective = true;
1342
1343 ++NumDirectives;
1344
Chris Lattner371ac8a2006-07-04 07:11:10 +00001345 // We are about to read a token. For the multiple-include optimization FA to
1346 // work, we have to remember if we had read any tokens *before* this
1347 // pp-directive.
1348 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1349
Chris Lattner78186052006-07-09 00:45:31 +00001350 // Read the next token, the directive flavor. This isn't expanded due to
1351 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001352 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001353
Chris Lattner78186052006-07-09 00:45:31 +00001354 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1355 // #define A(x) #x
1356 // A(abc
1357 // #warning blah
1358 // def)
1359 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001360 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001361 Diag(Result, diag::ext_embedded_directive);
1362
Chris Lattner22eb9722006-06-18 05:43:12 +00001363 switch (Result.getKind()) {
1364 default: break;
1365 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001366 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001367
1368#if 0
1369 case tok::numeric_constant:
1370 // FIXME: implement # 7 line numbers!
1371 break;
1372#endif
1373 case tok::kw_else:
1374 return HandleElseDirective(Result);
1375 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001376 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001378 // Get the identifier name without trigraphs or embedded newlines.
1379 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001381 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001382 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001383 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001384 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001385 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001386 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001387 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1388 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001389 break;
1390 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001391 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001392 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001393 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001394 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001395 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001397 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001398 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001399 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001400 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001401 break;
1402 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001403 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001405 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001406 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001407 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001408 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001409 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001410 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001411 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1412 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001413 break;
1414 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001415 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1416 return HandleIncludeDirective(Result); // Handle #include.
1417 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001418 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001419 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001420 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001421 break;
1422 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001423 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001424 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 }
1426 break;
1427 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001428 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1429 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001430 break;
1431 }
1432 break;
1433 }
1434
1435 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001436 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001437
1438 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001439 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001440
1441 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001442}
1443
Chris Lattner01d66cc2006-07-03 22:16:27 +00001444void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001445 bool isWarning) {
1446 // Read the rest of the line raw. We do this because we don't want macros
1447 // to be expanded and we don't require that the tokens be valid preprocessing
1448 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1449 // collapse multiple consequtive white space between tokens, but this isn't
1450 // specified by the standard.
1451 std::string Message = CurLexer->ReadToEndOfLine();
1452
1453 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001454 return Diag(Tok, DiagID, Message);
1455}
1456
1457/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1458///
1459void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001460 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001461 Diag(Tok, diag::ext_pp_ident_directive);
1462
Chris Lattner371ac8a2006-07-04 07:11:10 +00001463 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001464 LexerToken StrTok;
1465 Lex(StrTok);
1466
1467 // If the token kind isn't a string, it's a malformed directive.
1468 if (StrTok.getKind() != tok::string_literal)
1469 return Diag(StrTok, diag::err_pp_malformed_ident);
1470
1471 // Verify that there is nothing after the string, other than EOM.
1472 CheckEndOfDirective("#ident");
1473
1474 if (IdentHandler)
1475 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001476}
1477
Chris Lattnerb8761832006-06-24 21:31:03 +00001478//===----------------------------------------------------------------------===//
1479// Preprocessor Include Directive Handling.
1480//===----------------------------------------------------------------------===//
1481
Chris Lattner22eb9722006-06-18 05:43:12 +00001482/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1483/// file to be included from the lexer, then include it! This is a common
1484/// routine with functionality shared between #include, #include_next and
1485/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001486void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 const DirectoryLookup *LookupFrom,
1488 bool isImport) {
1489 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001490
Chris Lattner22eb9722006-06-18 05:43:12 +00001491 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001492 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001493
1494 // If the token kind is EOM, the error has already been diagnosed.
1495 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001496 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001497
1498 // Verify that there is nothing after the filename, other than EOM. Use the
1499 // preprocessor to lex this in case lexing the filename entered a macro.
1500 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001501
1502 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001503 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001504 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1505
Chris Lattner269c2322006-06-25 06:23:00 +00001506 // Find out whether the filename is <x> or "x".
1507 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001508
1509 // Remove the quotes.
1510 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1511
Chris Lattner22eb9722006-06-18 05:43:12 +00001512 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001513 const DirectoryLookup *CurDir;
1514 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001515 if (File == 0)
1516 return Diag(FilenameTok, diag::err_pp_file_not_found);
1517
1518 // Get information about this file.
1519 PerFileInfo &FileInfo = getFileInfo(File);
1520
1521 // If this is a #import directive, check that we have not already imported
1522 // this header.
1523 if (isImport) {
1524 // If this has already been imported, don't import it again.
1525 FileInfo.isImport = true;
1526
1527 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001528 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001529 } else {
1530 // Otherwise, if this is a #include of a file that was previously #import'd
1531 // or if this is the second #include of a #pragma once file, ignore it.
1532 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001533 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001534 }
Chris Lattner3665f162006-07-04 07:26:10 +00001535
1536 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1537 // if the macro that guards it is defined, we know the #include has no effect.
1538 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1539 ++NumMultiIncludeFileOptzn;
1540 return;
1541 }
1542
Chris Lattner22eb9722006-06-18 05:43:12 +00001543
1544 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001545 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 if (FileID == 0)
1547 return Diag(FilenameTok, diag::err_pp_file_not_found);
1548
1549 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001550 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001551
1552 // Increment the number of times this file has been included.
1553 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001554}
1555
1556/// HandleIncludeNextDirective - Implements #include_next.
1557///
Chris Lattnercb283342006-06-18 06:48:37 +00001558void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1559 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001560
1561 // #include_next is like #include, except that we start searching after
1562 // the current found directory. If we can't do this, issue a
1563 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001564 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001565 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001566 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001567 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001568 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001569 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001570 } else {
1571 // Start looking up in the next directory.
1572 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 }
1574
1575 return HandleIncludeDirective(IncludeNextTok, Lookup);
1576}
1577
1578/// HandleImportDirective - Implements #import.
1579///
Chris Lattnercb283342006-06-18 06:48:37 +00001580void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1581 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001582
1583 return HandleIncludeDirective(ImportTok, 0, true);
1584}
1585
Chris Lattnerb8761832006-06-24 21:31:03 +00001586//===----------------------------------------------------------------------===//
1587// Preprocessor Macro Directive Handling.
1588//===----------------------------------------------------------------------===//
1589
Chris Lattnercefc7682006-07-08 08:28:12 +00001590/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1591/// definition has just been read. Lex the rest of the arguments and the
1592/// closing ), updating MI with what we learn. Return true if an error occurs
1593/// parsing the arg list.
1594bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1595 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001596 while (1) {
1597 LexUnexpandedToken(Tok);
1598 switch (Tok.getKind()) {
1599 case tok::r_paren:
1600 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001601 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001602 // Otherwise we have #define FOO(A,)
1603 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1604 return true;
1605 case tok::ellipsis: // #define X(... -> C99 varargs
1606 // Warn if use of C99 feature in non-C99 mode.
1607 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1608
1609 // Lex the token after the identifier.
1610 LexUnexpandedToken(Tok);
1611 if (Tok.getKind() != tok::r_paren) {
1612 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1613 return true;
1614 }
1615 MI->setIsC99Varargs();
1616 return false;
1617 case tok::eom: // #define X(
1618 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1619 return true;
1620 default: // #define X(1
1621 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1622 return true;
1623 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001624 IdentifierInfo *II = Tok.getIdentifierInfo();
1625
1626 // If this is already used as an argument, it is used multiple times (e.g.
1627 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001628 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001629 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1630 return true;
1631 }
1632
1633 // Add the argument to the macro info.
1634 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001635
1636 // Lex the token after the identifier.
1637 LexUnexpandedToken(Tok);
1638
1639 switch (Tok.getKind()) {
1640 default: // #define X(A B
1641 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1642 return true;
1643 case tok::r_paren: // #define X(A)
1644 return false;
1645 case tok::comma: // #define X(A,
1646 break;
1647 case tok::ellipsis: // #define X(A... -> GCC extension
1648 // Diagnose extension.
1649 Diag(Tok, diag::ext_named_variadic_macro);
1650
1651 // Lex the token after the identifier.
1652 LexUnexpandedToken(Tok);
1653 if (Tok.getKind() != tok::r_paren) {
1654 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1655 return true;
1656 }
1657
1658 MI->setIsGNUVarargs();
1659 return false;
1660 }
1661 }
1662 }
1663}
1664
Chris Lattner22eb9722006-06-18 05:43:12 +00001665/// HandleDefineDirective - Implements #define. This consumes the entire macro
1666/// line then lets the caller lex the next real token.
1667///
Chris Lattnercb283342006-06-18 06:48:37 +00001668void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001669 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001670
Chris Lattner22eb9722006-06-18 05:43:12 +00001671 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001672 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001673
1674 // Error reading macro name? If so, diagnostic already issued.
1675 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001676 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001677
Chris Lattner50b497e2006-06-18 16:32:35 +00001678 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001679
1680 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001681 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001682
Chris Lattner78186052006-07-09 00:45:31 +00001683 // FIXME: Enable __VA_ARGS__.
1684
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001685 // If this is a function-like macro definition, parse the argument list,
1686 // marking each of the identifiers as being used as macro arguments. Also,
1687 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001688 if (Tok.getKind() == tok::eom) {
1689 // If there is no body to this macro, we have no special handling here.
1690 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001691 // This is a function-like macro definition. Read the argument list.
1692 MI->setIsFunctionLike();
1693 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001694 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001695 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001696 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001697 if (CurLexer->ParsingPreprocessorDirective)
1698 DiscardUntilEndOfDirective();
1699 return;
1700 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001701
Chris Lattner815a1f92006-07-08 20:48:04 +00001702 // Read the first token after the arg list for down below.
1703 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001704 } else if (!Tok.hasLeadingSpace()) {
1705 // C99 requires whitespace between the macro definition and the body. Emit
1706 // a diagnostic for something like "#define X+".
1707 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001708 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001709 } else {
1710 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1711 // one in some cases!
1712 }
1713 } else {
1714 // This is a normal token with leading space. Clear the leading space
1715 // marker on the first token to get proper expansion.
1716 Tok.ClearFlag(LexerToken::LeadingSpace);
1717 }
1718
1719 // Read the rest of the macro body.
1720 while (Tok.getKind() != tok::eom) {
1721 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001722
1723 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001724 // parameters in function-like macro expansions.
1725 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001726 // Get the next token of the macro.
1727 LexUnexpandedToken(Tok);
1728 continue;
1729 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001730
Chris Lattner815a1f92006-07-08 20:48:04 +00001731 // Get the next token of the macro.
1732 LexUnexpandedToken(Tok);
1733
1734 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001735 if (!Tok.getIdentifierInfo() ||
1736 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001737 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001738 delete MI;
1739 return;
1740 }
1741
1742 // Things look ok, add the param name token to the macro.
1743 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001744
Chris Lattner22eb9722006-06-18 05:43:12 +00001745 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001746 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001747 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001748
Chris Lattnerbff18d52006-07-06 04:49:18 +00001749 // Check that there is no paste (##) operator at the begining or end of the
1750 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001751 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001752 if (NumTokens != 0) {
1753 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001754 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001755 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001756 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001757 }
1758 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001759 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001760 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001761 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001762 }
1763 }
1764
Chris Lattner13044d92006-07-03 05:16:44 +00001765 // If this is the primary source file, remember that this macro hasn't been
1766 // used yet.
1767 if (isInPrimaryFile())
1768 MI->setIsUsed(false);
1769
Chris Lattner22eb9722006-06-18 05:43:12 +00001770 // Finally, if this identifier already had a macro defined for it, verify that
1771 // the macro bodies are identical and free the old definition.
1772 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001773 if (!OtherMI->isUsed())
1774 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1775
Chris Lattner22eb9722006-06-18 05:43:12 +00001776 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001777 // must be the same. C99 6.10.3.2.
1778 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001779 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1780 MacroNameTok.getIdentifierInfo()->getName());
1781 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1782 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001783 delete OtherMI;
1784 }
1785
1786 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001787}
1788
1789
1790/// HandleUndefDirective - Implements #undef.
1791///
Chris Lattnercb283342006-06-18 06:48:37 +00001792void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001793 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001794
Chris Lattner22eb9722006-06-18 05:43:12 +00001795 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001796 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001797
1798 // Error reading macro name? If so, diagnostic already issued.
1799 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001800 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001801
1802 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001803 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001804
1805 // Okay, we finally have a valid identifier to undef.
1806 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1807
1808 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001809 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001810
Chris Lattner13044d92006-07-03 05:16:44 +00001811 if (!MI->isUsed())
1812 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001813
1814 // Free macro definition.
1815 delete MI;
1816 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001817}
1818
1819
Chris Lattnerb8761832006-06-24 21:31:03 +00001820//===----------------------------------------------------------------------===//
1821// Preprocessor Conditional Directive Handling.
1822//===----------------------------------------------------------------------===//
1823
Chris Lattner22eb9722006-06-18 05:43:12 +00001824/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001825/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1826/// if any tokens have been returned or pp-directives activated before this
1827/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001828///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001829void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1830 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001831 ++NumIf;
1832 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001833
Chris Lattner22eb9722006-06-18 05:43:12 +00001834 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001835 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001836
1837 // Error reading macro name? If so, diagnostic already issued.
1838 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001839 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001840
1841 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001842 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1843
1844 // If the start of a top-level #ifdef, inform MIOpt.
1845 if (!ReadAnyTokensBeforeDirective &&
1846 CurLexer->getConditionalStackDepth() == 0) {
1847 assert(isIfndef && "#ifdef shouldn't reach here");
1848 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1849 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001850
Chris Lattnera78a97e2006-07-03 05:42:18 +00001851 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1852
1853 // If there is a macro, mark it used.
1854 if (MI) MI->setIsUsed(true);
1855
Chris Lattner22eb9722006-06-18 05:43:12 +00001856 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001857 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001859 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001860 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001861 } else {
1862 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001863 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001864 /*Foundnonskip*/false,
1865 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001866 }
1867}
1868
1869/// HandleIfDirective - Implements the #if directive.
1870///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001871void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1872 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001873 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001874
Chris Lattner371ac8a2006-07-04 07:11:10 +00001875 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001876 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001877 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001878
1879 // Should we include the stuff contained by this directive?
1880 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001881 // If this condition is equivalent to #ifndef X, and if this is the first
1882 // directive seen, handle it for the multiple-include optimization.
1883 if (!ReadAnyTokensBeforeDirective &&
1884 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1885 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1886
Chris Lattner22eb9722006-06-18 05:43:12 +00001887 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001888 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001890 } else {
1891 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001892 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001893 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001894 }
1895}
1896
1897/// HandleEndifDirective - Implements the #endif directive.
1898///
Chris Lattnercb283342006-06-18 06:48:37 +00001899void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001900 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001901
Chris Lattner22eb9722006-06-18 05:43:12 +00001902 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001903 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001904
1905 PPConditionalInfo CondInfo;
1906 if (CurLexer->popConditionalLevel(CondInfo)) {
1907 // No conditionals on the stack: this is an #endif without an #if.
1908 return Diag(EndifToken, diag::err_pp_endif_without_if);
1909 }
1910
Chris Lattner371ac8a2006-07-04 07:11:10 +00001911 // If this the end of a top-level #endif, inform MIOpt.
1912 if (CurLexer->getConditionalStackDepth() == 0)
1913 CurLexer->MIOpt.ExitTopLevelConditional();
1914
Chris Lattner538d7f32006-07-20 04:31:52 +00001915 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001917}
1918
1919
Chris Lattnercb283342006-06-18 06:48:37 +00001920void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001921 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001922
Chris Lattner22eb9722006-06-18 05:43:12 +00001923 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001924 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001925
1926 PPConditionalInfo CI;
1927 if (CurLexer->popConditionalLevel(CI))
1928 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001929
1930 // If this is a top-level #else, inform the MIOpt.
1931 if (CurLexer->getConditionalStackDepth() == 0)
1932 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001933
1934 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001935 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001936
1937 // Finally, skip the rest of the contents of this block and return the first
1938 // token after it.
1939 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1940 /*FoundElse*/true);
1941}
1942
Chris Lattnercb283342006-06-18 06:48:37 +00001943void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001944 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001945
Chris Lattner22eb9722006-06-18 05:43:12 +00001946 // #elif directive in a non-skipping conditional... start skipping.
1947 // We don't care what the condition is, because we will always skip it (since
1948 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001949 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001950
1951 PPConditionalInfo CI;
1952 if (CurLexer->popConditionalLevel(CI))
1953 return Diag(ElifToken, diag::pp_err_elif_without_if);
1954
Chris Lattner371ac8a2006-07-04 07:11:10 +00001955 // If this is a top-level #elif, inform the MIOpt.
1956 if (CurLexer->getConditionalStackDepth() == 0)
1957 CurLexer->MIOpt.FoundTopLevelElse();
1958
Chris Lattner22eb9722006-06-18 05:43:12 +00001959 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001960 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001961
1962 // Finally, skip the rest of the contents of this block and return the first
1963 // token after it.
1964 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1965 /*FoundElse*/CI.FoundElse);
1966}
Chris Lattnerb8761832006-06-24 21:31:03 +00001967