blob: ea9e6ad3186f63f052499f6efcfb610b1b6391c7 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15//
16// ERROR : __VA_ARGS__ can only appear in the expansion of a C99 variadic macro
17//
18// Options to support:
19// -H - Print the name of each header file used.
20// -C -CC - Do not discard comments for cpp.
Chris Lattner22eb9722006-06-18 05:43:12 +000021// -d[MDNI] - Dump various things.
22// -fworking-directory - #line's with preprocessor's working dir.
23// -fpreprocessed
24// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
25// -W*
26// -w
27//
28// Messages to emit:
29// "Multiple include guards may be useful for:\n"
30//
31// TODO: Implement the include guard optimization.
32//
33//===----------------------------------------------------------------------===//
34
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000037#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000038#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Basic/Diagnostic.h"
40#include "clang/Basic/FileManager.h"
41#include "clang/Basic/SourceManager.h"
42#include <iostream>
43using namespace llvm;
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47
48Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
49 FileManager &FM, SourceManager &SM)
50 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
51 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000052 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000053 ScratchBuf = new ScratchBuffer(SourceMgr);
54
Chris Lattner22eb9722006-06-18 05:43:12 +000055 // Clear stats.
56 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
57 NumIf = NumElse = NumEndif = 0;
58 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
Chris Lattner69772b02006-07-02 20:34:39 +000059 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
Chris Lattner22eb9722006-06-18 05:43:12 +000062 // Macro expansion is enabled.
63 DisableMacroExpansion = false;
64 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000065
66 // There is no file-change handler yet.
67 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000068 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000069
70 // Initialize the pragma handlers.
71 PragmaHandlers = new PragmaNamespace(0);
72 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000073
74 // Initialize builtin macros like __LINE__ and friends.
75 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000076}
77
78Preprocessor::~Preprocessor() {
79 // Free any active lexers.
80 delete CurLexer;
81
Chris Lattner69772b02006-07-02 20:34:39 +000082 while (!IncludeMacroStack.empty()) {
83 delete IncludeMacroStack.back().TheLexer;
84 delete IncludeMacroStack.back().TheMacroExpander;
85 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000086 }
Chris Lattnerb8761832006-06-24 21:31:03 +000087
88 // Release pragma information.
89 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000090
91 // Delete the scratch buffer info.
92 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000093}
94
95/// getFileInfo - Return the PerFileInfo structure for the specified
96/// FileEntry.
97Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
98 if (FE->getUID() >= FileInfo.size())
99 FileInfo.resize(FE->getUID()+1);
100 return FileInfo[FE->getUID()];
101}
102
103
104/// AddKeywords - Add all keywords to the symbol table.
105///
106void Preprocessor::AddKeywords() {
107 enum {
108 C90Shift = 0,
109 EXTC90 = 1 << C90Shift,
110 NOTC90 = 2 << C90Shift,
111 C99Shift = 2,
112 EXTC99 = 1 << C99Shift,
113 NOTC99 = 2 << C99Shift,
114 CPPShift = 4,
115 EXTCPP = 1 << CPPShift,
116 NOTCPP = 2 << CPPShift,
117 Mask = 3
118 };
119
120 // Add keywords and tokens for the current language.
121#define KEYWORD(NAME, FLAGS) \
122 AddKeyword(#NAME+1, tok::kw##NAME, \
123 (FLAGS >> C90Shift) & Mask, \
124 (FLAGS >> C99Shift) & Mask, \
125 (FLAGS >> CPPShift) & Mask);
126#define ALIAS(NAME, TOK) \
127 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
128#include "clang/Basic/TokenKinds.def"
129}
130
131/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
132/// the specified LexerToken's location, translating the token's start
133/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000134void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000135 const std::string &Msg) {
136 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
137 // warnings or extensions.
138 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000139 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000140
Chris Lattnercb283342006-06-18 06:48:37 +0000141 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000142}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143
144void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
145 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
146 << getSpelling(Tok) << "'";
147
148 if (!DumpFlags) return;
149 std::cerr << "\t";
150 if (Tok.isAtStartOfLine())
151 std::cerr << " [StartOfLine]";
152 if (Tok.hasLeadingSpace())
153 std::cerr << " [LeadingSpace]";
154 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000155 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000156 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
157 << "']";
158 }
159}
160
161void Preprocessor::DumpMacro(const MacroInfo &MI) const {
162 std::cerr << "MACRO: ";
163 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
164 DumpToken(MI.getReplacementToken(i));
165 std::cerr << " ";
166 }
167 std::cerr << "\n";
168}
169
Chris Lattner22eb9722006-06-18 05:43:12 +0000170void Preprocessor::PrintStats() {
171 std::cerr << "\n*** Preprocessor Stats:\n";
172 std::cerr << FileInfo.size() << " files tracked.\n";
173 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
174 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
175 NumOnceOnlyFiles += FileInfo[i].isImport;
176 if (MaxNumIncludes < FileInfo[i].NumIncludes)
177 MaxNumIncludes = FileInfo[i].NumIncludes;
178 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
179 }
180 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
181 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
182 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
183
184 std::cerr << NumDirectives << " directives found:\n";
185 std::cerr << " " << NumDefined << " #define.\n";
186 std::cerr << " " << NumUndefined << " #undef.\n";
187 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
188 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
189 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
190 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
191 std::cerr << " " << NumElse << " #else/#elif.\n";
192 std::cerr << " " << NumEndif << " #endif.\n";
193 std::cerr << " " << NumPragma << " #pragma.\n";
194 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
195
196 std::cerr << NumMacroExpanded << " macros expanded, "
197 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000198}
199
200//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000201// Token Spelling
202//===----------------------------------------------------------------------===//
203
204
205/// getSpelling() - Return the 'spelling' of this token. The spelling of a
206/// token are the characters used to represent the token in the source file
207/// after trigraph expansion and escaped-newline folding. In particular, this
208/// wants to get the true, uncanonicalized, spelling of things like digraphs
209/// UCNs, etc.
210std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
211 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
212
213 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000214 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 assert(TokStart && "Token has invalid location!");
216 if (!Tok.needsCleaning())
217 return std::string(TokStart, TokStart+Tok.getLength());
218
219 // Otherwise, hard case, relex the characters into the string.
220 std::string Result;
221 Result.reserve(Tok.getLength());
222
223 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.
238unsigned Preprocessor::getSpelling(const LexerToken &Tok, char *Buffer) const {
239 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
240
Chris Lattner50b497e2006-06-18 16:32:35 +0000241 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000242 assert(TokStart && "Token has invalid location!");
243
244 // If this token contains nothing interesting, return it directly.
245 if (!Tok.needsCleaning()) {
246 unsigned Size = Tok.getLength();
247 memcpy(Buffer, TokStart, Size);
248 return Size;
249 }
250 // Otherwise, hard case, relex the characters into the string.
251 std::string Result;
252 Result.reserve(Tok.getLength());
253
254 char *OutBuf = Buffer;
255 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
256 Ptr != End; ) {
257 unsigned CharSize;
258 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
259 Ptr += CharSize;
260 }
261 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
262 "NeedsCleaning flag set on something that didn't need cleaning!");
263
264 return OutBuf-Buffer;
265}
266
267//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000268// Source File Location Methods.
269//===----------------------------------------------------------------------===//
270
271
272/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
273/// return null on failure. isAngled indicates whether the file reference is
274/// for system #include's or not (i.e. using <> instead of "").
275const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000276 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000277 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000278 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000279 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000280 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000281
282 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000283 // FIXME: Portability. This should be a sys::Path interface, this doesn't
284 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000285 if (Filename[0] == '/') {
286 // If this was an #include_next "/absolute/file", fail.
287 if (FromDir) return 0;
288
289 // Otherwise, just return the file.
290 return FileMgr.getFile(Filename);
291 }
292
293 // Step #0, unless disabled, check to see if the file is in the #includer's
294 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000295 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000296 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
297 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000298 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000299 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000300 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000301 if (const FileEntry *FE =
302 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000303 if (CurDirLookup)
304 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000305 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000306 CurDir = 0;
307
308 // This file is a system header or C++ unfriendly if the old file is.
309 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000310 return FE;
311 }
312 }
313 }
314
315 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000316 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000317
318 // If this is a #include_next request, start searching after the directory the
319 // file was found in.
320 if (FromDir)
321 i = FromDir-&SearchDirs[0];
322
323 // Check each directory in sequence to see if it contains this file.
324 for (; i != SearchDirs.size(); ++i) {
325 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000326 // FIXME: Portability. Adding file to dir should be in sys::Path.
327 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
328 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000329 CurDir = &SearchDirs[i];
330
331 // This file is a system header or C++ unfriendly if the dir is.
332 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000333 return FE;
334 }
335 }
336
337 // Otherwise, didn't find it.
338 return 0;
339}
340
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000341/// isInPrimaryFile - Return true if we're in the top-level file, not in a
342/// #include.
343bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000344 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000345 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000346
Chris Lattner13044d92006-07-03 05:16:44 +0000347 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000348 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000349 if (IncludeMacroStack[i].TheLexer &&
350 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
351 return IncludeMacroStack[i].TheLexer->isMainFile();
352 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000353}
354
355/// getCurrentLexer - Return the current file lexer being lexed from. Note
356/// that this ignores any potentially active macro expansions and _Pragma
357/// expansions going on at the time.
358Lexer *Preprocessor::getCurrentFileLexer() const {
359 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
360
361 // Look for a stacked lexer.
362 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000363 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000364 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
365 return L;
366 }
367 return 0;
368}
369
370
Chris Lattner22eb9722006-06-18 05:43:12 +0000371/// EnterSourceFile - Add a source file to the top of the include stack and
372/// start lexing tokens from it instead of the current buffer. Return true
373/// on failure.
374void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000375 const DirectoryLookup *CurDir,
376 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000377 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000378 ++NumEnteredSourceFiles;
379
Chris Lattner69772b02006-07-02 20:34:39 +0000380 if (MaxIncludeStackDepth < IncludeMacroStack.size())
381 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000382
Chris Lattner22eb9722006-06-18 05:43:12 +0000383 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000384 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000385 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000386 EnterSourceFileWithLexer(TheLexer, CurDir);
387}
Chris Lattner22eb9722006-06-18 05:43:12 +0000388
Chris Lattner69772b02006-07-02 20:34:39 +0000389/// EnterSourceFile - Add a source file to the top of the include stack and
390/// start lexing tokens from it instead of the current buffer.
391void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
392 const DirectoryLookup *CurDir) {
393
394 // Add the current lexer to the include stack.
395 if (CurLexer || CurMacroExpander)
396 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
397 CurMacroExpander));
398
399 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000400 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000401 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000402
403 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000404 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000405 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
406
407 // Get the file entry for the current file.
408 if (const FileEntry *FE =
409 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
410 FileType = getFileInfo(FE).DirInfo;
411
Chris Lattner1840e492006-07-02 22:30:01 +0000412 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000413 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000414 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000415}
416
Chris Lattner69772b02006-07-02 20:34:39 +0000417
418
Chris Lattner22eb9722006-06-18 05:43:12 +0000419/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000420/// tokens from it instead of the current buffer.
421void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000422 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
423 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000424 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
425 CurMacroExpander));
426 CurLexer = 0;
427 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000428
429 // TODO: Figure out arguments.
430
431 // Mark the macro as currently disabled, so that it is not recursively
432 // expanded.
433 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000434 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000435}
436
Chris Lattner22eb9722006-06-18 05:43:12 +0000437//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000438// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000439//===----------------------------------------------------------------------===//
440
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000441/// RegisterBuiltinMacro - Register the specified identifier in the identifier
442/// table and mark it as a builtin macro to be expanded.
443IdentifierTokenInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
444 // Get the identifier.
445 IdentifierTokenInfo *Id = getIdentifierInfo(Name);
446
447 // Mark it as being a macro that is builtin.
448 MacroInfo *MI = new MacroInfo(SourceLocation());
449 MI->setIsBuiltinMacro();
450 Id->setMacroInfo(MI);
451 return Id;
452}
453
454
Chris Lattner677757a2006-06-28 05:26:32 +0000455/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
456/// identifier table.
457void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000458 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000459 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000460 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
461 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000462 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000463
464 // GCC Extensions.
465 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
466 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000467 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000468
Chris Lattner69772b02006-07-02 20:34:39 +0000469 // FIXME: implement them all:
Chris Lattnerc1283b92006-07-01 23:16:30 +0000470//Pseudo #defines.
471 // __STDC__ 1 if !stdc_0_in_system_headers and "std"
472 // __STDC_VERSION__
473 // __STDC_HOSTED__
474 // __OBJC__
Chris Lattner22eb9722006-06-18 05:43:12 +0000475}
476
Chris Lattner677757a2006-06-28 05:26:32 +0000477
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000478/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
479/// expanded as a macro, handle it and return the next token as 'Identifier'.
480void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
481 MacroInfo *MI) {
482 ++NumMacroExpanded;
Chris Lattner13044d92006-07-03 05:16:44 +0000483
484 // Notice that this macro has been used.
485 MI->setIsUsed(true);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000486
487 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
488 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000489 return ExpandBuiltinMacro(Identifier);
490
491 // If we started lexing a macro, enter the macro expansion body.
492 // FIXME: Read/Validate the argument list here!
493
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000494
495 // If this macro expands to no tokens, don't bother to push it onto the
496 // expansion stack, only to take it right back off.
497 if (MI->getNumTokens() == 0) {
498 // Ignore this macro use, just return the next token in the current
499 // buffer.
500 bool HadLeadingSpace = Identifier.hasLeadingSpace();
501 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
502
503 Lex(Identifier);
504
505 // If the identifier isn't on some OTHER line, inherit the leading
506 // whitespace/first-on-a-line property of this token. This handles
507 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
508 // empty.
509 if (!Identifier.isAtStartOfLine()) {
510 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
511 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
512 }
513 ++NumFastMacroExpanded;
514 return;
515
516 } else if (MI->getNumTokens() == 1 &&
517 // Don't handle identifiers if they need recursive expansion.
518 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
519 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
520 // FIXME: Function-style macros only if no arguments?
521
522 // Otherwise, if this macro expands into a single trivially-expanded
523 // token: expand it now. This handles common cases like
524 // "#define VAL 42".
525
526 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
527 // identifier to the expanded token.
528 bool isAtStartOfLine = Identifier.isAtStartOfLine();
529 bool hasLeadingSpace = Identifier.hasLeadingSpace();
530
531 // Remember where the token is instantiated.
532 SourceLocation InstantiateLoc = Identifier.getLocation();
533
534 // Replace the result token.
535 Identifier = MI->getReplacementToken(0);
536
537 // Restore the StartOfLine/LeadingSpace markers.
538 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
539 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
540
541 // Update the tokens location to include both its logical and physical
542 // locations.
543 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000544 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000545 Identifier.SetLocation(Loc);
546
547 // Since this is not an identifier token, it can't be macro expanded, so
548 // we're done.
549 ++NumFastMacroExpanded;
550 return;
551 }
552
553 // Start expanding the macro (FIXME, pass arguments).
554 EnterMacro(Identifier);
555
556 // Now that the macro is at the top of the include stack, ask the
557 // preprocessor to read the next token from it.
558 return Lex(Identifier);
559}
560
Chris Lattnerc673f902006-06-30 06:10:41 +0000561/// ComputeDATE_TIME - Compute the current time, enter it into the specified
562/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
563/// the identifier tokens inserted.
564static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
565 ScratchBuffer *ScratchBuf) {
566 time_t TT = time(0);
567 struct tm *TM = localtime(&TT);
568
569 static const char * const Months[] = {
570 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
571 };
572
573 char TmpBuffer[100];
574 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
575 TM->tm_year+1900);
576 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
577
578 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
579 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
580}
581
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000582/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
583/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000584void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000585 // Figure out which token this is.
586 IdentifierTokenInfo *ITI = Tok.getIdentifierInfo();
587 assert(ITI && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000588
589 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
590 // lex the token after it.
591 if (ITI == Ident_Pragma)
592 return Handle_Pragma(Tok);
593
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000594 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000595
596 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000597 Tok.SetIdentifierInfo(0);
598 Tok.ClearFlag(LexerToken::NeedsCleaning);
599
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000600 if (ITI == Ident__LINE__) {
601 // __LINE__ expands to a simple numeric value.
602 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
603 unsigned Length = strlen(TmpBuffer);
604 Tok.SetKind(tok::numeric_constant);
605 Tok.SetLength(Length);
606 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000607 } else if (ITI == Ident__FILE__ || ITI == Ident__BASE_FILE__) {
608 SourceLocation Loc = Tok.getLocation();
609 if (ITI == Ident__BASE_FILE__) {
610 Diag(Tok, diag::ext_pp_base_file);
611 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
612 while (NextLoc.getFileID() != 0) {
613 Loc = NextLoc;
614 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
615 }
616 }
617
Chris Lattner0766e592006-07-03 01:07:01 +0000618 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
619 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000620 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000621 Tok.SetKind(tok::string_literal);
622 Tok.SetLength(FN.size());
623 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000624 } else if (ITI == Ident__DATE__) {
625 if (!DATELoc.isValid())
626 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
627 Tok.SetKind(tok::string_literal);
628 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
629 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000630 } else if (ITI == Ident__TIME__) {
631 if (!TIMELoc.isValid())
632 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
633 Tok.SetKind(tok::string_literal);
634 Tok.SetLength(strlen("\"hh:mm:ss\""));
635 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000636 } else if (ITI == Ident__INCLUDE_LEVEL__) {
637 Diag(Tok, diag::ext_pp_include_level);
638
639 // Compute the include depth of this token.
640 unsigned Depth = 0;
641 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
642 for (; Loc.getFileID() != 0; ++Depth)
643 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
644
645 // __INCLUDE_LEVEL__ expands to a simple numeric value.
646 sprintf(TmpBuffer, "%u", Depth);
647 unsigned Length = strlen(TmpBuffer);
648 Tok.SetKind(tok::numeric_constant);
649 Tok.SetLength(Length);
650 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattner847e0e42006-07-01 23:49:16 +0000651 } else if (ITI == Ident__TIMESTAMP__) {
652 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
653 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
654 Diag(Tok, diag::ext_pp_timestamp);
655
656 // Get the file that we are lexing out of. If we're currently lexing from
657 // a macro, dig into the include stack.
658 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000659 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000660
661 if (TheLexer)
662 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
663
664 // If this file is older than the file it depends on, emit a diagnostic.
665 const char *Result;
666 if (CurFile) {
667 time_t TT = CurFile->getModificationTime();
668 struct tm *TM = localtime(&TT);
669 Result = asctime(TM);
670 } else {
671 Result = "??? ??? ?? ??:??:?? ????\n";
672 }
673 TmpBuffer[0] = '"';
674 strcpy(TmpBuffer+1, Result);
675 unsigned Len = strlen(TmpBuffer);
676 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
677 Tok.SetKind(tok::string_literal);
678 Tok.SetLength(Len);
679 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000680 } else {
681 assert(0 && "Unknown identifier!");
682 }
683}
Chris Lattner677757a2006-06-28 05:26:32 +0000684
Chris Lattner13044d92006-07-03 05:16:44 +0000685namespace {
686struct UnusedIdentifierReporter : public IdentifierVisitor {
687 Preprocessor &PP;
688 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
689
690 void VisitIdentifier(IdentifierTokenInfo &ITI) const {
691 if (ITI.getMacroInfo() && !ITI.getMacroInfo()->isUsed())
692 PP.Diag(ITI.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
693 }
694};
695}
696
Chris Lattner677757a2006-06-28 05:26:32 +0000697//===----------------------------------------------------------------------===//
698// Lexer Event Handling.
699//===----------------------------------------------------------------------===//
700
701/// HandleIdentifier - This callback is invoked when the lexer reads an
702/// identifier. This callback looks up the identifier in the map and/or
703/// potentially macro expands it or turns it into a named token (like 'for').
704void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
705 if (Identifier.getIdentifierInfo() == 0) {
706 // If we are skipping tokens (because we are in a #if 0 block), there will
707 // be no identifier info, just return the token.
708 assert(isSkipping() && "Token isn't an identifier?");
709 return;
710 }
711 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
712
713 // If this identifier was poisoned, and if it was not produced from a macro
714 // expansion, emit an error.
715 if (ITI.isPoisoned() && CurLexer)
716 Diag(Identifier, diag::err_pp_used_poisoned_id);
717
718 if (MacroInfo *MI = ITI.getMacroInfo())
719 if (MI->isEnabled() && !DisableMacroExpansion)
720 return HandleMacroExpandedIdentifier(Identifier, MI);
721
722 // Change the kind of this identifier to the appropriate token kind, e.g.
723 // turning "for" into a keyword.
724 Identifier.SetKind(ITI.getTokenID());
725
726 // If this is an extension token, diagnose its use.
727 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
728}
729
Chris Lattner22eb9722006-06-18 05:43:12 +0000730/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
731/// the current file. This either returns the EOF token or pops a level off
732/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000733void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000734 assert(!CurMacroExpander &&
735 "Ending a file when currently in a macro!");
736
737 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
738 // this is an error condition. Just return the EOF token up to
739 // SkipExcludedConditionalBlock. The Lexer will have already have issued
740 // errors for the unterminated #if's on the conditional stack.
741 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000742 Result.StartToken();
743 CurLexer->BufferPtr = CurLexer->BufferEnd;
744 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000745 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000746 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000747 }
748
749 // If this is a #include'd file, pop it off the include stack and continue
750 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000751 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000752 // We're done with the #included file.
753 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000754 CurLexer = IncludeMacroStack.back().TheLexer;
755 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
756 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
757 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000758
759 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000760 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000761 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
762
763 // Get the file entry for the current file.
764 if (const FileEntry *FE =
765 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
766 FileType = getFileInfo(FE).DirInfo;
767
Chris Lattner0c885f52006-06-21 06:50:18 +0000768 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000769 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000770 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000771
Chris Lattner22eb9722006-06-18 05:43:12 +0000772 return Lex(Result);
773 }
774
Chris Lattnerd01e2912006-06-18 16:22:51 +0000775 Result.StartToken();
776 CurLexer->BufferPtr = CurLexer->BufferEnd;
777 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000778 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000779
780 // We're done with the #included file.
781 delete CurLexer;
782 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000783
784 // This is the end of the top-level file.
785 IdentifierInfo.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +0000786}
787
788/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000789/// the current macro line.
790void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000791 assert(CurMacroExpander && !CurLexer &&
792 "Ending a macro when currently in a #include file!");
793
794 // Mark macro not ignored now that it is no longer being expanded.
795 CurMacroExpander->getMacro().EnableMacro();
796 delete CurMacroExpander;
797
Chris Lattner69772b02006-07-02 20:34:39 +0000798 // Handle this like a #include file being popped off the stack.
799 CurMacroExpander = 0;
800 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000801}
802
803
804//===----------------------------------------------------------------------===//
805// Utility Methods for Preprocessor Directive Handling.
806//===----------------------------------------------------------------------===//
807
808/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
809/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000810void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000811 LexerToken Tmp;
812 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000813 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000814 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000815}
816
817/// ReadMacroName - Lex and validate a macro name, which occurs after a
818/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattner44f8a662006-07-03 01:27:27 +0000819/// of the macro line if the macro name is invalid. isDefineUndef is true if
820/// this is due to a a #define or #undef directive, false if it is something
821/// else (e.g. #ifdef).
822void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, bool isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000823 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000824 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000825
826 // Missing macro name?
827 if (MacroNameTok.getKind() == tok::eom)
828 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
829
Chris Lattneraaf09112006-07-03 01:17:59 +0000830 IdentifierTokenInfo *ITI = MacroNameTok.getIdentifierInfo();
831 if (ITI == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000832 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000833 // Fall through on error.
834 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000835 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000836
Chris Lattner44f8a662006-07-03 01:27:27 +0000837 } else if (isDefineUndef && ITI->getName()[0] == 'd' && // defined
Chris Lattneraaf09112006-07-03 01:17:59 +0000838 !strcmp(ITI->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000839 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +0000840 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner44f8a662006-07-03 01:27:27 +0000841 } else if (isDefineUndef && ITI->getMacroInfo() &&
842 ITI->getMacroInfo()->isBuiltinMacro()) {
843 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
844 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +0000845 } else {
846 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000847 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000848 }
849
Chris Lattner22eb9722006-06-18 05:43:12 +0000850 // Invalid macro name, read and discard the rest of the line. Then set the
851 // token kind to tok::eom.
852 MacroNameTok.SetKind(tok::eom);
853 return DiscardUntilEndOfDirective();
854}
855
856/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
857/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000858void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000859 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000860 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000861 // There should be no tokens after the directive, but we allow them as an
862 // extension.
863 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000864 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
865 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000866 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000867}
868
869
870
871/// SkipExcludedConditionalBlock - We just read a #if or related directive and
872/// decided that the subsequent tokens are in the #if'd out portion of the
873/// file. Lex the rest of the file, until we see an #endif. If
874/// FoundNonSkipPortion is true, then we have already emitted code for part of
875/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
876/// is true, then #else directives are ok, if not, then we have already seen one
877/// so a #else directive is a duplicate. When this returns, the caller can lex
878/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000879void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000880 bool FoundNonSkipPortion,
881 bool FoundElse) {
882 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000883 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000884 "Lexing a macro, not a file?");
885
886 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
887 FoundNonSkipPortion, FoundElse);
888
889 // Know that we are going to be skipping tokens. Set this flag to indicate
890 // this, which has a couple of effects:
891 // 1. If EOF of the current lexer is found, the include stack isn't popped.
892 // 2. Identifier information is not looked up for identifier tokens. As an
893 // effect of this, implicit macro expansion is naturally disabled.
894 // 3. "#" tokens at the start of a line are treated as normal tokens, not
895 // implicitly transformed by the lexer.
896 // 4. All notes, warnings, and extension messages are disabled.
897 //
898 SkippingContents = true;
899 LexerToken Tok;
900 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000901 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000902
903 // If this is the end of the buffer, we have an error. The lexer will have
904 // already handled this error condition, so just return and let the caller
905 // lex after this #include.
906 if (Tok.getKind() == tok::eof) break;
907
908 // If this token is not a preprocessor directive, just skip it.
909 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
910 continue;
911
912 // We just parsed a # character at the start of a line, so we're in
913 // directive mode. Tell the lexer this so any newlines we see will be
914 // converted into an EOM token (this terminates the macro).
915 CurLexer->ParsingPreprocessorDirective = true;
916
917 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000918 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000919
920 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
921 // something bogus), skip it.
922 if (Tok.getKind() != tok::identifier) {
923 CurLexer->ParsingPreprocessorDirective = false;
924 continue;
925 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000926
Chris Lattner22eb9722006-06-18 05:43:12 +0000927 // If the first letter isn't i or e, it isn't intesting to us. We know that
928 // this is safe in the face of spelling differences, because there is no way
929 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000930 // allows us to avoid looking up the identifier info for #define/#undef and
931 // other common directives.
932 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
933 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000934 if (FirstChar >= 'a' && FirstChar <= 'z' &&
935 FirstChar != 'i' && FirstChar != 'e') {
936 CurLexer->ParsingPreprocessorDirective = false;
937 continue;
938 }
939
Chris Lattnere60165f2006-06-22 06:36:29 +0000940 // Get the identifier name without trigraphs or embedded newlines. Note
941 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
942 // when skipping.
943 // TODO: could do this with zero copies in the no-clean case by using
944 // strncmp below.
945 char Directive[20];
946 unsigned IdLen;
947 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
948 IdLen = Tok.getLength();
949 memcpy(Directive, RawCharData, IdLen);
950 Directive[IdLen] = 0;
951 } else {
952 std::string DirectiveStr = getSpelling(Tok);
953 IdLen = DirectiveStr.size();
954 if (IdLen >= 20) {
955 CurLexer->ParsingPreprocessorDirective = false;
956 continue;
957 }
958 memcpy(Directive, &DirectiveStr[0], IdLen);
959 Directive[IdLen] = 0;
960 }
961
Chris Lattner22eb9722006-06-18 05:43:12 +0000962 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000963 if ((IdLen == 2) || // "if"
964 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
965 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000966 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
967 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000968 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000969 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000970 /*foundnonskip*/false,
971 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000972 }
973 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000974 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000975 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000976 PPConditionalInfo CondInfo;
977 CondInfo.WasSkipping = true; // Silence bogus warning.
978 bool InCond = CurLexer->popConditionalLevel(CondInfo);
979 assert(!InCond && "Can't be skipping if not in a conditional!");
980
981 // If we popped the outermost skipping block, we're done skipping!
982 if (!CondInfo.WasSkipping)
983 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000984 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000985 // #else directive in a skipping conditional. If not in some other
986 // skipping conditional, and if #else hasn't already been seen, enter it
987 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000988 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000989 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
990
991 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000992 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000993
994 // Note that we've seen a #else in this conditional.
995 CondInfo.FoundElse = true;
996
997 // If the conditional is at the top level, and the #if block wasn't
998 // entered, enter the #else block now.
999 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1000 CondInfo.FoundNonSkip = true;
1001 break;
1002 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001003 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001004 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1005
1006 bool ShouldEnter;
1007 // If this is in a skipping block or if we're already handled this #if
1008 // block, don't bother parsing the condition.
1009 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001010 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001011 ShouldEnter = false;
1012 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001013 // Restore the value of SkippingContents so that identifiers are
1014 // looked up, etc, inside the #elif expression.
1015 assert(SkippingContents && "We have to be skipping here!");
1016 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001017 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001018 SkippingContents = true;
1019 }
1020
1021 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001022 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001023
1024 // If this condition is true, enter it!
1025 if (ShouldEnter) {
1026 CondInfo.FoundNonSkip = true;
1027 break;
1028 }
1029 }
1030 }
1031
1032 CurLexer->ParsingPreprocessorDirective = false;
1033 }
1034
1035 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1036 // of the file, just stop skipping and return to lexing whatever came after
1037 // the #if block.
1038 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001039}
1040
1041//===----------------------------------------------------------------------===//
1042// Preprocessor Directive Handling.
1043//===----------------------------------------------------------------------===//
1044
1045/// HandleDirective - This callback is invoked when the lexer sees a # token
1046/// at the start of a line. This consumes the directive, modifies the
1047/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1048/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001049void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001050 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001051
1052 // We just parsed a # character at the start of a line, so we're in directive
1053 // mode. Tell the lexer this so any newlines we see will be converted into an
1054 // EOM token (this terminates the macro).
1055 CurLexer->ParsingPreprocessorDirective = true;
1056
1057 ++NumDirectives;
1058
1059 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001060 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001061
1062 switch (Result.getKind()) {
1063 default: break;
1064 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001065 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001066
1067#if 0
1068 case tok::numeric_constant:
1069 // FIXME: implement # 7 line numbers!
1070 break;
1071#endif
1072 case tok::kw_else:
1073 return HandleElseDirective(Result);
1074 case tok::kw_if:
1075 return HandleIfDirective(Result);
1076 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001077 // Get the identifier name without trigraphs or embedded newlines.
1078 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001079 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001080 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001081 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001082 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001083 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001084 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001085 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001086 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1087 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001088 break;
1089 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001090 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001092 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001093 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001094 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001095 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001096 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001098 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001099 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 break;
1101 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001102 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001104 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +00001106 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001108 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001109 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001110 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1111 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 break;
1113 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001114 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1115 return HandleIncludeDirective(Result); // Handle #include.
1116 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001117 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001118 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001119 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001120 break;
1121 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001122 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001123 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001124 }
1125 break;
1126 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001127 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1128 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 break;
1130 }
1131 break;
1132 }
1133
1134 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001135 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001136
1137 // Read the rest of the PP line.
1138 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001139 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001140 } while (Result.getKind() != tok::eom);
1141
1142 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001143}
1144
Chris Lattner01d66cc2006-07-03 22:16:27 +00001145void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 bool isWarning) {
1147 // Read the rest of the line raw. We do this because we don't want macros
1148 // to be expanded and we don't require that the tokens be valid preprocessing
1149 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1150 // collapse multiple consequtive white space between tokens, but this isn't
1151 // specified by the standard.
1152 std::string Message = CurLexer->ReadToEndOfLine();
1153
1154 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001155 return Diag(Tok, DiagID, Message);
1156}
1157
1158/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1159///
1160void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
1161 Diag(Tok, diag::ext_pp_ident_directive);
1162
1163 LexerToken StrTok;
1164 Lex(StrTok);
1165
1166 // If the token kind isn't a string, it's a malformed directive.
1167 if (StrTok.getKind() != tok::string_literal)
1168 return Diag(StrTok, diag::err_pp_malformed_ident);
1169
1170 // Verify that there is nothing after the string, other than EOM.
1171 CheckEndOfDirective("#ident");
1172
1173 if (IdentHandler)
1174 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001175}
1176
Chris Lattnerb8761832006-06-24 21:31:03 +00001177//===----------------------------------------------------------------------===//
1178// Preprocessor Include Directive Handling.
1179//===----------------------------------------------------------------------===//
1180
Chris Lattner22eb9722006-06-18 05:43:12 +00001181/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1182/// file to be included from the lexer, then include it! This is a common
1183/// routine with functionality shared between #include, #include_next and
1184/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001185void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001186 const DirectoryLookup *LookupFrom,
1187 bool isImport) {
1188 ++NumIncluded;
1189 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001190 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001191
1192 // If the token kind is EOM, the error has already been diagnosed.
1193 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001194 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001195
1196 // Verify that there is nothing after the filename, other than EOM. Use the
1197 // preprocessor to lex this in case lexing the filename entered a macro.
1198 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001199
1200 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001201 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001202 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1203
Chris Lattner269c2322006-06-25 06:23:00 +00001204 // Find out whether the filename is <x> or "x".
1205 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001206
1207 // Remove the quotes.
1208 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1209
Chris Lattner22eb9722006-06-18 05:43:12 +00001210 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001211 const DirectoryLookup *CurDir;
1212 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001213 if (File == 0)
1214 return Diag(FilenameTok, diag::err_pp_file_not_found);
1215
1216 // Get information about this file.
1217 PerFileInfo &FileInfo = getFileInfo(File);
1218
1219 // If this is a #import directive, check that we have not already imported
1220 // this header.
1221 if (isImport) {
1222 // If this has already been imported, don't import it again.
1223 FileInfo.isImport = true;
1224
1225 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001226 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001227 } else {
1228 // Otherwise, if this is a #include of a file that was previously #import'd
1229 // or if this is the second #include of a #pragma once file, ignore it.
1230 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001231 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001232 }
1233
1234 // Look up the file, create a File ID for it.
1235 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +00001236 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001237 if (FileID == 0)
1238 return Diag(FilenameTok, diag::err_pp_file_not_found);
1239
1240 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001241 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001242
1243 // Increment the number of times this file has been included.
1244 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001245}
1246
1247/// HandleIncludeNextDirective - Implements #include_next.
1248///
Chris Lattnercb283342006-06-18 06:48:37 +00001249void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1250 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001251
1252 // #include_next is like #include, except that we start searching after
1253 // the current found directory. If we can't do this, issue a
1254 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001255 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001256 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001258 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001259 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001260 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001261 } else {
1262 // Start looking up in the next directory.
1263 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001264 }
1265
1266 return HandleIncludeDirective(IncludeNextTok, Lookup);
1267}
1268
1269/// HandleImportDirective - Implements #import.
1270///
Chris Lattnercb283342006-06-18 06:48:37 +00001271void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1272 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001273
1274 return HandleIncludeDirective(ImportTok, 0, true);
1275}
1276
Chris Lattnerb8761832006-06-24 21:31:03 +00001277//===----------------------------------------------------------------------===//
1278// Preprocessor Macro Directive Handling.
1279//===----------------------------------------------------------------------===//
1280
Chris Lattner22eb9722006-06-18 05:43:12 +00001281/// HandleDefineDirective - Implements #define. This consumes the entire macro
1282/// line then lets the caller lex the next real token.
1283///
Chris Lattnercb283342006-06-18 06:48:37 +00001284void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001285 ++NumDefined;
1286 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001287 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001288
1289 // Error reading macro name? If so, diagnostic already issued.
1290 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001291 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001292
Chris Lattner50b497e2006-06-18 16:32:35 +00001293 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001294
1295 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001296 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001297
1298 if (Tok.getKind() == tok::eom) {
1299 // If there is no body to this macro, we have no special handling here.
1300 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1301 // This is a function-like macro definition.
1302 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001303 return DiscardUntilEndOfDirective();
1304
1305 } else if (!Tok.hasLeadingSpace()) {
1306 // C99 requires whitespace between the macro definition and the body. Emit
1307 // a diagnostic for something like "#define X+".
1308 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001309 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 } else {
1311 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1312 // one in some cases!
1313 }
1314 } else {
1315 // This is a normal token with leading space. Clear the leading space
1316 // marker on the first token to get proper expansion.
1317 Tok.ClearFlag(LexerToken::LeadingSpace);
1318 }
1319
1320 // Read the rest of the macro body.
1321 while (Tok.getKind() != tok::eom) {
1322 MI->AddTokenToBody(Tok);
1323
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001324 // FIXME: Read macro body. See create_iso_definition.
Chris Lattner22eb9722006-06-18 05:43:12 +00001325
1326 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001327 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 }
1329
Chris Lattner13044d92006-07-03 05:16:44 +00001330 // If this is the primary source file, remember that this macro hasn't been
1331 // used yet.
1332 if (isInPrimaryFile())
1333 MI->setIsUsed(false);
1334
Chris Lattner22eb9722006-06-18 05:43:12 +00001335 // Finally, if this identifier already had a macro defined for it, verify that
1336 // the macro bodies are identical and free the old definition.
1337 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001338 if (!OtherMI->isUsed())
1339 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1340
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 // FIXME: Verify the definition is the same.
1342 // Macros must be identical. This means all tokes and whitespace separation
1343 // must be the same.
1344 delete OtherMI;
1345 }
1346
1347 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001348}
1349
1350
1351/// HandleUndefDirective - Implements #undef.
1352///
Chris Lattnercb283342006-06-18 06:48:37 +00001353void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001354 ++NumUndefined;
1355 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001356 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001357
1358 // Error reading macro name? If so, diagnostic already issued.
1359 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001360 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001361
1362 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001363 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001364
1365 // Okay, we finally have a valid identifier to undef.
1366 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1367
1368 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001369 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001370
Chris Lattner13044d92006-07-03 05:16:44 +00001371 if (!MI->isUsed())
1372 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001373
1374 // Free macro definition.
1375 delete MI;
1376 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001377}
1378
1379
Chris Lattnerb8761832006-06-24 21:31:03 +00001380//===----------------------------------------------------------------------===//
1381// Preprocessor Conditional Directive Handling.
1382//===----------------------------------------------------------------------===//
1383
Chris Lattner22eb9722006-06-18 05:43:12 +00001384/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1385/// true when this is a #ifndef directive.
1386///
Chris Lattnercb283342006-06-18 06:48:37 +00001387void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001388 ++NumIf;
1389 LexerToken DirectiveTok = Result;
1390
1391 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001392 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001393
1394 // Error reading macro name? If so, diagnostic already issued.
1395 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001396 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001397
1398 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001399 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001400
Chris Lattnera78a97e2006-07-03 05:42:18 +00001401 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1402
1403 // If there is a macro, mark it used.
1404 if (MI) MI->setIsUsed(true);
1405
Chris Lattner22eb9722006-06-18 05:43:12 +00001406 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001407 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001408 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001409 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001410 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001411 } else {
1412 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001413 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001414 /*Foundnonskip*/false,
1415 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001416 }
1417}
1418
1419/// HandleIfDirective - Implements the #if directive.
1420///
Chris Lattnercb283342006-06-18 06:48:37 +00001421void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001422 ++NumIf;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001423 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001424
1425 // Should we include the stuff contained by this directive?
1426 if (ConditionalTrue) {
1427 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001428 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001429 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001430 } else {
1431 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001432 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001433 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001434 }
1435}
1436
1437/// HandleEndifDirective - Implements the #endif directive.
1438///
Chris Lattnercb283342006-06-18 06:48:37 +00001439void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001440 ++NumEndif;
1441 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001442 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001443
1444 PPConditionalInfo CondInfo;
1445 if (CurLexer->popConditionalLevel(CondInfo)) {
1446 // No conditionals on the stack: this is an #endif without an #if.
1447 return Diag(EndifToken, diag::err_pp_endif_without_if);
1448 }
1449
1450 assert(!CondInfo.WasSkipping && !isSkipping() &&
1451 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001452}
1453
1454
Chris Lattnercb283342006-06-18 06:48:37 +00001455void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001456 ++NumElse;
1457 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001458 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001459
1460 PPConditionalInfo CI;
1461 if (CurLexer->popConditionalLevel(CI))
1462 return Diag(Result, diag::pp_err_else_without_if);
1463
1464 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001465 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001466
1467 // Finally, skip the rest of the contents of this block and return the first
1468 // token after it.
1469 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1470 /*FoundElse*/true);
1471}
1472
Chris Lattnercb283342006-06-18 06:48:37 +00001473void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001474 ++NumElse;
1475 // #elif directive in a non-skipping conditional... start skipping.
1476 // We don't care what the condition is, because we will always skip it (since
1477 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001478 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001479
1480 PPConditionalInfo CI;
1481 if (CurLexer->popConditionalLevel(CI))
1482 return Diag(ElifToken, diag::pp_err_elif_without_if);
1483
1484 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001485 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001486
1487 // Finally, skip the rest of the contents of this block and return the first
1488 // token after it.
1489 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1490 /*FoundElse*/CI.FoundElse);
1491}
Chris Lattnerb8761832006-06-24 21:31:03 +00001492