blob: 08717fee72703b34647ef494f87c6f223d89b0b0 [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 Lattnerb8761832006-06-24 21:31:03 +000068
69 // Initialize the pragma handlers.
70 PragmaHandlers = new PragmaNamespace(0);
71 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000072
73 // Initialize builtin macros like __LINE__ and friends.
74 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000075}
76
77Preprocessor::~Preprocessor() {
78 // Free any active lexers.
79 delete CurLexer;
80
Chris Lattner69772b02006-07-02 20:34:39 +000081 while (!IncludeMacroStack.empty()) {
82 delete IncludeMacroStack.back().TheLexer;
83 delete IncludeMacroStack.back().TheMacroExpander;
84 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000085 }
Chris Lattnerb8761832006-06-24 21:31:03 +000086
87 // Release pragma information.
88 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000089
90 // Delete the scratch buffer info.
91 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000092}
93
94/// getFileInfo - Return the PerFileInfo structure for the specified
95/// FileEntry.
96Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
97 if (FE->getUID() >= FileInfo.size())
98 FileInfo.resize(FE->getUID()+1);
99 return FileInfo[FE->getUID()];
100}
101
102
103/// AddKeywords - Add all keywords to the symbol table.
104///
105void Preprocessor::AddKeywords() {
106 enum {
107 C90Shift = 0,
108 EXTC90 = 1 << C90Shift,
109 NOTC90 = 2 << C90Shift,
110 C99Shift = 2,
111 EXTC99 = 1 << C99Shift,
112 NOTC99 = 2 << C99Shift,
113 CPPShift = 4,
114 EXTCPP = 1 << CPPShift,
115 NOTCPP = 2 << CPPShift,
116 Mask = 3
117 };
118
119 // Add keywords and tokens for the current language.
120#define KEYWORD(NAME, FLAGS) \
121 AddKeyword(#NAME+1, tok::kw##NAME, \
122 (FLAGS >> C90Shift) & Mask, \
123 (FLAGS >> C99Shift) & Mask, \
124 (FLAGS >> CPPShift) & Mask);
125#define ALIAS(NAME, TOK) \
126 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
127#include "clang/Basic/TokenKinds.def"
128}
129
130/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
131/// the specified LexerToken's location, translating the token's start
132/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000133void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000134 const std::string &Msg) {
135 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
136 // warnings or extensions.
137 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000138 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000139
Chris Lattnercb283342006-06-18 06:48:37 +0000140 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000141}
Chris Lattnercb283342006-06-18 06:48:37 +0000142void Preprocessor::Diag(const LexerToken &Tok, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000143 const std::string &Msg) {
144 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
145 // warnings or extensions.
146 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000147 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000148
Chris Lattner50b497e2006-06-18 16:32:35 +0000149 Diag(Tok.getLocation(), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000150}
151
Chris Lattnerd01e2912006-06-18 16:22:51 +0000152
153void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
154 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
155 << getSpelling(Tok) << "'";
156
157 if (!DumpFlags) return;
158 std::cerr << "\t";
159 if (Tok.isAtStartOfLine())
160 std::cerr << " [StartOfLine]";
161 if (Tok.hasLeadingSpace())
162 std::cerr << " [LeadingSpace]";
163 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000164 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000165 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
166 << "']";
167 }
168}
169
170void Preprocessor::DumpMacro(const MacroInfo &MI) const {
171 std::cerr << "MACRO: ";
172 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
173 DumpToken(MI.getReplacementToken(i));
174 std::cerr << " ";
175 }
176 std::cerr << "\n";
177}
178
Chris Lattner22eb9722006-06-18 05:43:12 +0000179void Preprocessor::PrintStats() {
180 std::cerr << "\n*** Preprocessor Stats:\n";
181 std::cerr << FileInfo.size() << " files tracked.\n";
182 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
183 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
184 NumOnceOnlyFiles += FileInfo[i].isImport;
185 if (MaxNumIncludes < FileInfo[i].NumIncludes)
186 MaxNumIncludes = FileInfo[i].NumIncludes;
187 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
188 }
189 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
190 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
191 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
192
193 std::cerr << NumDirectives << " directives found:\n";
194 std::cerr << " " << NumDefined << " #define.\n";
195 std::cerr << " " << NumUndefined << " #undef.\n";
196 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
197 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
198 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
199 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
200 std::cerr << " " << NumElse << " #else/#elif.\n";
201 std::cerr << " " << NumEndif << " #endif.\n";
202 std::cerr << " " << NumPragma << " #pragma.\n";
203 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
204
205 std::cerr << NumMacroExpanded << " macros expanded, "
206 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000207}
208
209//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000210// Token Spelling
211//===----------------------------------------------------------------------===//
212
213
214/// getSpelling() - Return the 'spelling' of this token. The spelling of a
215/// token are the characters used to represent the token in the source file
216/// after trigraph expansion and escaped-newline folding. In particular, this
217/// wants to get the true, uncanonicalized, spelling of things like digraphs
218/// UCNs, etc.
219std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
220 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
221
222 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000223 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 assert(TokStart && "Token has invalid location!");
225 if (!Tok.needsCleaning())
226 return std::string(TokStart, TokStart+Tok.getLength());
227
228 // Otherwise, hard case, relex the characters into the string.
229 std::string Result;
230 Result.reserve(Tok.getLength());
231
232 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
233 Ptr != End; ) {
234 unsigned CharSize;
235 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
236 Ptr += CharSize;
237 }
238 assert(Result.size() != unsigned(Tok.getLength()) &&
239 "NeedsCleaning flag set on something that didn't need cleaning!");
240 return Result;
241}
242
243/// getSpelling - This method is used to get the spelling of a token into a
244/// preallocated buffer, instead of as an std::string. The caller is required
245/// to allocate enough space for the token, which is guaranteed to be at least
246/// Tok.getLength() bytes long. The actual length of the token is returned.
247unsigned Preprocessor::getSpelling(const LexerToken &Tok, char *Buffer) const {
248 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
249
Chris Lattner50b497e2006-06-18 16:32:35 +0000250 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251 assert(TokStart && "Token has invalid location!");
252
253 // If this token contains nothing interesting, return it directly.
254 if (!Tok.needsCleaning()) {
255 unsigned Size = Tok.getLength();
256 memcpy(Buffer, TokStart, Size);
257 return Size;
258 }
259 // Otherwise, hard case, relex the characters into the string.
260 std::string Result;
261 Result.reserve(Tok.getLength());
262
263 char *OutBuf = Buffer;
264 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
265 Ptr != End; ) {
266 unsigned CharSize;
267 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
268 Ptr += CharSize;
269 }
270 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
271 "NeedsCleaning flag set on something that didn't need cleaning!");
272
273 return OutBuf-Buffer;
274}
275
276//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000277// Source File Location Methods.
278//===----------------------------------------------------------------------===//
279
280
281/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
282/// return null on failure. isAngled indicates whether the file reference is
283/// for system #include's or not (i.e. using <> instead of "").
284const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000285 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000286 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000287 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000288 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000289 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000290
291 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000292 // FIXME: Portability. This should be a sys::Path interface, this doesn't
293 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000294 if (Filename[0] == '/') {
295 // If this was an #include_next "/absolute/file", fail.
296 if (FromDir) return 0;
297
298 // Otherwise, just return the file.
299 return FileMgr.getFile(Filename);
300 }
301
302 // Step #0, unless disabled, check to see if the file is in the #includer's
303 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000304 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000305 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
306 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000307 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000308 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000309 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000310 if (const FileEntry *FE =
311 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000312 if (CurDirLookup)
313 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000314 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000315 CurDir = 0;
316
317 // This file is a system header or C++ unfriendly if the old file is.
318 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000319 return FE;
320 }
321 }
322 }
323
324 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000325 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000326
327 // If this is a #include_next request, start searching after the directory the
328 // file was found in.
329 if (FromDir)
330 i = FromDir-&SearchDirs[0];
331
332 // Check each directory in sequence to see if it contains this file.
333 for (; i != SearchDirs.size(); ++i) {
334 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000335 // FIXME: Portability. Adding file to dir should be in sys::Path.
336 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
337 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000338 CurDir = &SearchDirs[i];
339
340 // This file is a system header or C++ unfriendly if the dir is.
341 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000342 return FE;
343 }
344 }
345
346 // Otherwise, didn't find it.
347 return 0;
348}
349
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000350/// isInPrimaryFile - Return true if we're in the top-level file, not in a
351/// #include.
352bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000353 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000354 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000355
Chris Lattner13044d92006-07-03 05:16:44 +0000356 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000357 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000358 if (IncludeMacroStack[i].TheLexer &&
359 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
360 return IncludeMacroStack[i].TheLexer->isMainFile();
361 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000362}
363
364/// getCurrentLexer - Return the current file lexer being lexed from. Note
365/// that this ignores any potentially active macro expansions and _Pragma
366/// expansions going on at the time.
367Lexer *Preprocessor::getCurrentFileLexer() const {
368 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
369
370 // Look for a stacked lexer.
371 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000372 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000373 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
374 return L;
375 }
376 return 0;
377}
378
379
Chris Lattner22eb9722006-06-18 05:43:12 +0000380/// EnterSourceFile - Add a source file to the top of the include stack and
381/// start lexing tokens from it instead of the current buffer. Return true
382/// on failure.
383void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000384 const DirectoryLookup *CurDir,
385 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000386 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000387 ++NumEnteredSourceFiles;
388
Chris Lattner69772b02006-07-02 20:34:39 +0000389 if (MaxIncludeStackDepth < IncludeMacroStack.size())
390 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000391
Chris Lattner22eb9722006-06-18 05:43:12 +0000392 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000393 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000394 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000395 EnterSourceFileWithLexer(TheLexer, CurDir);
396}
Chris Lattner22eb9722006-06-18 05:43:12 +0000397
Chris Lattner69772b02006-07-02 20:34:39 +0000398/// EnterSourceFile - Add a source file to the top of the include stack and
399/// start lexing tokens from it instead of the current buffer.
400void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
401 const DirectoryLookup *CurDir) {
402
403 // Add the current lexer to the include stack.
404 if (CurLexer || CurMacroExpander)
405 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
406 CurMacroExpander));
407
408 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000409 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000410 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000411
412 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000413 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000414 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
415
416 // Get the file entry for the current file.
417 if (const FileEntry *FE =
418 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
419 FileType = getFileInfo(FE).DirInfo;
420
Chris Lattner1840e492006-07-02 22:30:01 +0000421 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000422 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000423 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000424}
425
Chris Lattner69772b02006-07-02 20:34:39 +0000426
427
Chris Lattner22eb9722006-06-18 05:43:12 +0000428/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000429/// tokens from it instead of the current buffer.
430void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000431 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
432 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000433 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
434 CurMacroExpander));
435 CurLexer = 0;
436 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000437
438 // TODO: Figure out arguments.
439
440 // Mark the macro as currently disabled, so that it is not recursively
441 // expanded.
442 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000443 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000444}
445
Chris Lattner22eb9722006-06-18 05:43:12 +0000446//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000447// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000448//===----------------------------------------------------------------------===//
449
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000450/// RegisterBuiltinMacro - Register the specified identifier in the identifier
451/// table and mark it as a builtin macro to be expanded.
452IdentifierTokenInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
453 // Get the identifier.
454 IdentifierTokenInfo *Id = getIdentifierInfo(Name);
455
456 // Mark it as being a macro that is builtin.
457 MacroInfo *MI = new MacroInfo(SourceLocation());
458 MI->setIsBuiltinMacro();
459 Id->setMacroInfo(MI);
460 return Id;
461}
462
463
Chris Lattner677757a2006-06-28 05:26:32 +0000464/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
465/// identifier table.
466void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000467 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000468 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000469 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
470 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000471 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000472
473 // GCC Extensions.
474 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
475 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000476 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000477
Chris Lattner69772b02006-07-02 20:34:39 +0000478 // FIXME: implement them all:
Chris Lattnerc1283b92006-07-01 23:16:30 +0000479//Pseudo #defines.
480 // __STDC__ 1 if !stdc_0_in_system_headers and "std"
481 // __STDC_VERSION__
482 // __STDC_HOSTED__
483 // __OBJC__
Chris Lattner22eb9722006-06-18 05:43:12 +0000484}
485
Chris Lattner677757a2006-06-28 05:26:32 +0000486
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000487/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
488/// expanded as a macro, handle it and return the next token as 'Identifier'.
489void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
490 MacroInfo *MI) {
491 ++NumMacroExpanded;
Chris Lattner13044d92006-07-03 05:16:44 +0000492
493 // Notice that this macro has been used.
494 MI->setIsUsed(true);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000495
496 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
497 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000498 return ExpandBuiltinMacro(Identifier);
499
500 // If we started lexing a macro, enter the macro expansion body.
501 // FIXME: Read/Validate the argument list here!
502
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000503
504 // If this macro expands to no tokens, don't bother to push it onto the
505 // expansion stack, only to take it right back off.
506 if (MI->getNumTokens() == 0) {
507 // Ignore this macro use, just return the next token in the current
508 // buffer.
509 bool HadLeadingSpace = Identifier.hasLeadingSpace();
510 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
511
512 Lex(Identifier);
513
514 // If the identifier isn't on some OTHER line, inherit the leading
515 // whitespace/first-on-a-line property of this token. This handles
516 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
517 // empty.
518 if (!Identifier.isAtStartOfLine()) {
519 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
520 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
521 }
522 ++NumFastMacroExpanded;
523 return;
524
525 } else if (MI->getNumTokens() == 1 &&
526 // Don't handle identifiers if they need recursive expansion.
527 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
528 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
529 // FIXME: Function-style macros only if no arguments?
530
531 // Otherwise, if this macro expands into a single trivially-expanded
532 // token: expand it now. This handles common cases like
533 // "#define VAL 42".
534
535 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
536 // identifier to the expanded token.
537 bool isAtStartOfLine = Identifier.isAtStartOfLine();
538 bool hasLeadingSpace = Identifier.hasLeadingSpace();
539
540 // Remember where the token is instantiated.
541 SourceLocation InstantiateLoc = Identifier.getLocation();
542
543 // Replace the result token.
544 Identifier = MI->getReplacementToken(0);
545
546 // Restore the StartOfLine/LeadingSpace markers.
547 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
548 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
549
550 // Update the tokens location to include both its logical and physical
551 // locations.
552 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000553 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000554 Identifier.SetLocation(Loc);
555
556 // Since this is not an identifier token, it can't be macro expanded, so
557 // we're done.
558 ++NumFastMacroExpanded;
559 return;
560 }
561
562 // Start expanding the macro (FIXME, pass arguments).
563 EnterMacro(Identifier);
564
565 // Now that the macro is at the top of the include stack, ask the
566 // preprocessor to read the next token from it.
567 return Lex(Identifier);
568}
569
Chris Lattnerc673f902006-06-30 06:10:41 +0000570/// ComputeDATE_TIME - Compute the current time, enter it into the specified
571/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
572/// the identifier tokens inserted.
573static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
574 ScratchBuffer *ScratchBuf) {
575 time_t TT = time(0);
576 struct tm *TM = localtime(&TT);
577
578 static const char * const Months[] = {
579 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
580 };
581
582 char TmpBuffer[100];
583 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
584 TM->tm_year+1900);
585 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
586
587 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
588 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
589}
590
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000591/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
592/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000593void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000594 // Figure out which token this is.
595 IdentifierTokenInfo *ITI = Tok.getIdentifierInfo();
596 assert(ITI && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000597
598 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
599 // lex the token after it.
600 if (ITI == Ident_Pragma)
601 return Handle_Pragma(Tok);
602
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000603 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000604
605 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000606 Tok.SetIdentifierInfo(0);
607 Tok.ClearFlag(LexerToken::NeedsCleaning);
608
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000609 if (ITI == Ident__LINE__) {
610 // __LINE__ expands to a simple numeric value.
611 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
612 unsigned Length = strlen(TmpBuffer);
613 Tok.SetKind(tok::numeric_constant);
614 Tok.SetLength(Length);
615 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000616 } else if (ITI == Ident__FILE__ || ITI == Ident__BASE_FILE__) {
617 SourceLocation Loc = Tok.getLocation();
618 if (ITI == Ident__BASE_FILE__) {
619 Diag(Tok, diag::ext_pp_base_file);
620 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
621 while (NextLoc.getFileID() != 0) {
622 Loc = NextLoc;
623 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
624 }
625 }
626
Chris Lattner0766e592006-07-03 01:07:01 +0000627 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
628 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000629 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000630 Tok.SetKind(tok::string_literal);
631 Tok.SetLength(FN.size());
632 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000633 } else if (ITI == Ident__DATE__) {
634 if (!DATELoc.isValid())
635 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
636 Tok.SetKind(tok::string_literal);
637 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
638 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000639 } else if (ITI == Ident__TIME__) {
640 if (!TIMELoc.isValid())
641 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
642 Tok.SetKind(tok::string_literal);
643 Tok.SetLength(strlen("\"hh:mm:ss\""));
644 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000645 } else if (ITI == Ident__INCLUDE_LEVEL__) {
646 Diag(Tok, diag::ext_pp_include_level);
647
648 // Compute the include depth of this token.
649 unsigned Depth = 0;
650 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
651 for (; Loc.getFileID() != 0; ++Depth)
652 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
653
654 // __INCLUDE_LEVEL__ expands to a simple numeric value.
655 sprintf(TmpBuffer, "%u", Depth);
656 unsigned Length = strlen(TmpBuffer);
657 Tok.SetKind(tok::numeric_constant);
658 Tok.SetLength(Length);
659 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattner847e0e42006-07-01 23:49:16 +0000660 } else if (ITI == Ident__TIMESTAMP__) {
661 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
662 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
663 Diag(Tok, diag::ext_pp_timestamp);
664
665 // Get the file that we are lexing out of. If we're currently lexing from
666 // a macro, dig into the include stack.
667 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000668 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000669
670 if (TheLexer)
671 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
672
673 // If this file is older than the file it depends on, emit a diagnostic.
674 const char *Result;
675 if (CurFile) {
676 time_t TT = CurFile->getModificationTime();
677 struct tm *TM = localtime(&TT);
678 Result = asctime(TM);
679 } else {
680 Result = "??? ??? ?? ??:??:?? ????\n";
681 }
682 TmpBuffer[0] = '"';
683 strcpy(TmpBuffer+1, Result);
684 unsigned Len = strlen(TmpBuffer);
685 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
686 Tok.SetKind(tok::string_literal);
687 Tok.SetLength(Len);
688 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000689 } else {
690 assert(0 && "Unknown identifier!");
691 }
692}
Chris Lattner677757a2006-06-28 05:26:32 +0000693
Chris Lattner13044d92006-07-03 05:16:44 +0000694namespace {
695struct UnusedIdentifierReporter : public IdentifierVisitor {
696 Preprocessor &PP;
697 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
698
699 void VisitIdentifier(IdentifierTokenInfo &ITI) const {
700 if (ITI.getMacroInfo() && !ITI.getMacroInfo()->isUsed())
701 PP.Diag(ITI.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
702 }
703};
704}
705
Chris Lattner677757a2006-06-28 05:26:32 +0000706//===----------------------------------------------------------------------===//
707// Lexer Event Handling.
708//===----------------------------------------------------------------------===//
709
710/// HandleIdentifier - This callback is invoked when the lexer reads an
711/// identifier. This callback looks up the identifier in the map and/or
712/// potentially macro expands it or turns it into a named token (like 'for').
713void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
714 if (Identifier.getIdentifierInfo() == 0) {
715 // If we are skipping tokens (because we are in a #if 0 block), there will
716 // be no identifier info, just return the token.
717 assert(isSkipping() && "Token isn't an identifier?");
718 return;
719 }
720 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
721
722 // If this identifier was poisoned, and if it was not produced from a macro
723 // expansion, emit an error.
724 if (ITI.isPoisoned() && CurLexer)
725 Diag(Identifier, diag::err_pp_used_poisoned_id);
726
727 if (MacroInfo *MI = ITI.getMacroInfo())
728 if (MI->isEnabled() && !DisableMacroExpansion)
729 return HandleMacroExpandedIdentifier(Identifier, MI);
730
731 // Change the kind of this identifier to the appropriate token kind, e.g.
732 // turning "for" into a keyword.
733 Identifier.SetKind(ITI.getTokenID());
734
735 // If this is an extension token, diagnose its use.
736 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
737}
738
Chris Lattner22eb9722006-06-18 05:43:12 +0000739/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
740/// the current file. This either returns the EOF token or pops a level off
741/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000742void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000743 assert(!CurMacroExpander &&
744 "Ending a file when currently in a macro!");
745
746 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
747 // this is an error condition. Just return the EOF token up to
748 // SkipExcludedConditionalBlock. The Lexer will have already have issued
749 // errors for the unterminated #if's on the conditional stack.
750 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000751 Result.StartToken();
752 CurLexer->BufferPtr = CurLexer->BufferEnd;
753 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000754 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000755 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000756 }
757
758 // If this is a #include'd file, pop it off the include stack and continue
759 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000760 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000761 // We're done with the #included file.
762 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000763 CurLexer = IncludeMacroStack.back().TheLexer;
764 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
765 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
766 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000767
768 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000769 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000770 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
771
772 // Get the file entry for the current file.
773 if (const FileEntry *FE =
774 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
775 FileType = getFileInfo(FE).DirInfo;
776
Chris Lattner0c885f52006-06-21 06:50:18 +0000777 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000778 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000779 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000780
Chris Lattner22eb9722006-06-18 05:43:12 +0000781 return Lex(Result);
782 }
783
Chris Lattnerd01e2912006-06-18 16:22:51 +0000784 Result.StartToken();
785 CurLexer->BufferPtr = CurLexer->BufferEnd;
786 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000787 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000788
789 // We're done with the #included file.
790 delete CurLexer;
791 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000792
793 // This is the end of the top-level file.
794 IdentifierInfo.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +0000795}
796
797/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000798/// the current macro line.
799void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000800 assert(CurMacroExpander && !CurLexer &&
801 "Ending a macro when currently in a #include file!");
802
803 // Mark macro not ignored now that it is no longer being expanded.
804 CurMacroExpander->getMacro().EnableMacro();
805 delete CurMacroExpander;
806
Chris Lattner69772b02006-07-02 20:34:39 +0000807 // Handle this like a #include file being popped off the stack.
808 CurMacroExpander = 0;
809 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000810}
811
812
813//===----------------------------------------------------------------------===//
814// Utility Methods for Preprocessor Directive Handling.
815//===----------------------------------------------------------------------===//
816
817/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
818/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000819void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000820 LexerToken Tmp;
821 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000822 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000823 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000824}
825
826/// ReadMacroName - Lex and validate a macro name, which occurs after a
827/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattner44f8a662006-07-03 01:27:27 +0000828/// of the macro line if the macro name is invalid. isDefineUndef is true if
829/// this is due to a a #define or #undef directive, false if it is something
830/// else (e.g. #ifdef).
831void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, bool isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000832 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000833 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000834
835 // Missing macro name?
836 if (MacroNameTok.getKind() == tok::eom)
837 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
838
Chris Lattneraaf09112006-07-03 01:17:59 +0000839 IdentifierTokenInfo *ITI = MacroNameTok.getIdentifierInfo();
840 if (ITI == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000841 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000842 // Fall through on error.
843 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000844 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000845
Chris Lattner44f8a662006-07-03 01:27:27 +0000846 } else if (isDefineUndef && ITI->getName()[0] == 'd' && // defined
Chris Lattneraaf09112006-07-03 01:17:59 +0000847 !strcmp(ITI->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000848 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +0000849 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner44f8a662006-07-03 01:27:27 +0000850 } else if (isDefineUndef && ITI->getMacroInfo() &&
851 ITI->getMacroInfo()->isBuiltinMacro()) {
852 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
853 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +0000854 } else {
855 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000856 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000857 }
858
Chris Lattner22eb9722006-06-18 05:43:12 +0000859 // Invalid macro name, read and discard the rest of the line. Then set the
860 // token kind to tok::eom.
861 MacroNameTok.SetKind(tok::eom);
862 return DiscardUntilEndOfDirective();
863}
864
865/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
866/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000867void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000868 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000869 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000870 // There should be no tokens after the directive, but we allow them as an
871 // extension.
872 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000873 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
874 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000875 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000876}
877
878
879
880/// SkipExcludedConditionalBlock - We just read a #if or related directive and
881/// decided that the subsequent tokens are in the #if'd out portion of the
882/// file. Lex the rest of the file, until we see an #endif. If
883/// FoundNonSkipPortion is true, then we have already emitted code for part of
884/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
885/// is true, then #else directives are ok, if not, then we have already seen one
886/// so a #else directive is a duplicate. When this returns, the caller can lex
887/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000888void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000889 bool FoundNonSkipPortion,
890 bool FoundElse) {
891 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000892 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000893 "Lexing a macro, not a file?");
894
895 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
896 FoundNonSkipPortion, FoundElse);
897
898 // Know that we are going to be skipping tokens. Set this flag to indicate
899 // this, which has a couple of effects:
900 // 1. If EOF of the current lexer is found, the include stack isn't popped.
901 // 2. Identifier information is not looked up for identifier tokens. As an
902 // effect of this, implicit macro expansion is naturally disabled.
903 // 3. "#" tokens at the start of a line are treated as normal tokens, not
904 // implicitly transformed by the lexer.
905 // 4. All notes, warnings, and extension messages are disabled.
906 //
907 SkippingContents = true;
908 LexerToken Tok;
909 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000910 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000911
912 // If this is the end of the buffer, we have an error. The lexer will have
913 // already handled this error condition, so just return and let the caller
914 // lex after this #include.
915 if (Tok.getKind() == tok::eof) break;
916
917 // If this token is not a preprocessor directive, just skip it.
918 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
919 continue;
920
921 // We just parsed a # character at the start of a line, so we're in
922 // directive mode. Tell the lexer this so any newlines we see will be
923 // converted into an EOM token (this terminates the macro).
924 CurLexer->ParsingPreprocessorDirective = true;
925
926 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000927 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000928
929 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
930 // something bogus), skip it.
931 if (Tok.getKind() != tok::identifier) {
932 CurLexer->ParsingPreprocessorDirective = false;
933 continue;
934 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000935
Chris Lattner22eb9722006-06-18 05:43:12 +0000936 // If the first letter isn't i or e, it isn't intesting to us. We know that
937 // this is safe in the face of spelling differences, because there is no way
938 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000939 // allows us to avoid looking up the identifier info for #define/#undef and
940 // other common directives.
941 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
942 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000943 if (FirstChar >= 'a' && FirstChar <= 'z' &&
944 FirstChar != 'i' && FirstChar != 'e') {
945 CurLexer->ParsingPreprocessorDirective = false;
946 continue;
947 }
948
Chris Lattnere60165f2006-06-22 06:36:29 +0000949 // Get the identifier name without trigraphs or embedded newlines. Note
950 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
951 // when skipping.
952 // TODO: could do this with zero copies in the no-clean case by using
953 // strncmp below.
954 char Directive[20];
955 unsigned IdLen;
956 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
957 IdLen = Tok.getLength();
958 memcpy(Directive, RawCharData, IdLen);
959 Directive[IdLen] = 0;
960 } else {
961 std::string DirectiveStr = getSpelling(Tok);
962 IdLen = DirectiveStr.size();
963 if (IdLen >= 20) {
964 CurLexer->ParsingPreprocessorDirective = false;
965 continue;
966 }
967 memcpy(Directive, &DirectiveStr[0], IdLen);
968 Directive[IdLen] = 0;
969 }
970
Chris Lattner22eb9722006-06-18 05:43:12 +0000971 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000972 if ((IdLen == 2) || // "if"
973 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
974 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000975 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
976 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000977 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000978 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000979 /*foundnonskip*/false,
980 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000981 }
982 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000983 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000984 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000985 PPConditionalInfo CondInfo;
986 CondInfo.WasSkipping = true; // Silence bogus warning.
987 bool InCond = CurLexer->popConditionalLevel(CondInfo);
988 assert(!InCond && "Can't be skipping if not in a conditional!");
989
990 // If we popped the outermost skipping block, we're done skipping!
991 if (!CondInfo.WasSkipping)
992 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000993 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000994 // #else directive in a skipping conditional. If not in some other
995 // skipping conditional, and if #else hasn't already been seen, enter it
996 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000997 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000998 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
999
1000 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001001 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001002
1003 // Note that we've seen a #else in this conditional.
1004 CondInfo.FoundElse = true;
1005
1006 // If the conditional is at the top level, and the #if block wasn't
1007 // entered, enter the #else block now.
1008 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1009 CondInfo.FoundNonSkip = true;
1010 break;
1011 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001012 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001013 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1014
1015 bool ShouldEnter;
1016 // If this is in a skipping block or if we're already handled this #if
1017 // block, don't bother parsing the condition.
1018 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001019 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001020 ShouldEnter = false;
1021 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001022 // Restore the value of SkippingContents so that identifiers are
1023 // looked up, etc, inside the #elif expression.
1024 assert(SkippingContents && "We have to be skipping here!");
1025 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001026 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001027 SkippingContents = true;
1028 }
1029
1030 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001031 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001032
1033 // If this condition is true, enter it!
1034 if (ShouldEnter) {
1035 CondInfo.FoundNonSkip = true;
1036 break;
1037 }
1038 }
1039 }
1040
1041 CurLexer->ParsingPreprocessorDirective = false;
1042 }
1043
1044 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1045 // of the file, just stop skipping and return to lexing whatever came after
1046 // the #if block.
1047 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001048}
1049
1050//===----------------------------------------------------------------------===//
1051// Preprocessor Directive Handling.
1052//===----------------------------------------------------------------------===//
1053
1054/// HandleDirective - This callback is invoked when the lexer sees a # token
1055/// at the start of a line. This consumes the directive, modifies the
1056/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1057/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001058void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001059 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001060
1061 // We just parsed a # character at the start of a line, so we're in directive
1062 // mode. Tell the lexer this so any newlines we see will be converted into an
1063 // EOM token (this terminates the macro).
1064 CurLexer->ParsingPreprocessorDirective = true;
1065
1066 ++NumDirectives;
1067
1068 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001069 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001070
1071 switch (Result.getKind()) {
1072 default: break;
1073 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001074 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001075
1076#if 0
1077 case tok::numeric_constant:
1078 // FIXME: implement # 7 line numbers!
1079 break;
1080#endif
1081 case tok::kw_else:
1082 return HandleElseDirective(Result);
1083 case tok::kw_if:
1084 return HandleIfDirective(Result);
1085 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001086 // Get the identifier name without trigraphs or embedded newlines.
1087 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001088 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001089 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001090 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001091 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001092 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001093 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 return HandleElifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001095 if (Directive[0] == 's' && !strcmp(Directive, "sccs")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001096 isExtension = true; // FIXME: implement #sccs
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 // SCCS is the same as #ident.
1098 }
1099 break;
1100 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001101 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001102 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001103 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001104 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001105 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001106 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001107 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001109 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001110 isExtension = true; // FIXME: implement #ident
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 break;
1112 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001113 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001115 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +00001117 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001119 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001120 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001121 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1122 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001123 break;
1124 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001125 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1126 return HandleIncludeDirective(Result); // Handle #include.
1127 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001128 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001129 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001130 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 break;
1132 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001133 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001134 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 }
1136 break;
1137 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001138 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1139 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001140 break;
1141 }
1142 break;
1143 }
1144
1145 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001146 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001147
1148 // Read the rest of the PP line.
1149 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001150 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 } while (Result.getKind() != tok::eom);
1152
1153 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001154}
1155
Chris Lattnercb283342006-06-18 06:48:37 +00001156void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +00001157 bool isWarning) {
1158 // Read the rest of the line raw. We do this because we don't want macros
1159 // to be expanded and we don't require that the tokens be valid preprocessing
1160 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1161 // collapse multiple consequtive white space between tokens, but this isn't
1162 // specified by the standard.
1163 std::string Message = CurLexer->ReadToEndOfLine();
1164
1165 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1166 return Diag(Result, DiagID, Message);
1167}
1168
Chris Lattnerb8761832006-06-24 21:31:03 +00001169//===----------------------------------------------------------------------===//
1170// Preprocessor Include Directive Handling.
1171//===----------------------------------------------------------------------===//
1172
Chris Lattner22eb9722006-06-18 05:43:12 +00001173/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1174/// file to be included from the lexer, then include it! This is a common
1175/// routine with functionality shared between #include, #include_next and
1176/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001177void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 const DirectoryLookup *LookupFrom,
1179 bool isImport) {
1180 ++NumIncluded;
1181 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001182 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001183
1184 // If the token kind is EOM, the error has already been diagnosed.
1185 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001186 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001187
1188 // Verify that there is nothing after the filename, other than EOM. Use the
1189 // preprocessor to lex this in case lexing the filename entered a macro.
1190 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001191
1192 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001193 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001194 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1195
Chris Lattner269c2322006-06-25 06:23:00 +00001196 // Find out whether the filename is <x> or "x".
1197 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001198
1199 // Remove the quotes.
1200 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1201
Chris Lattner22eb9722006-06-18 05:43:12 +00001202 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001203 const DirectoryLookup *CurDir;
1204 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001205 if (File == 0)
1206 return Diag(FilenameTok, diag::err_pp_file_not_found);
1207
1208 // Get information about this file.
1209 PerFileInfo &FileInfo = getFileInfo(File);
1210
1211 // If this is a #import directive, check that we have not already imported
1212 // this header.
1213 if (isImport) {
1214 // If this has already been imported, don't import it again.
1215 FileInfo.isImport = true;
1216
1217 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001218 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001219 } else {
1220 // Otherwise, if this is a #include of a file that was previously #import'd
1221 // or if this is the second #include of a #pragma once file, ignore it.
1222 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001223 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001224 }
1225
1226 // Look up the file, create a File ID for it.
1227 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +00001228 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001229 if (FileID == 0)
1230 return Diag(FilenameTok, diag::err_pp_file_not_found);
1231
1232 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001233 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001234
1235 // Increment the number of times this file has been included.
1236 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001237}
1238
1239/// HandleIncludeNextDirective - Implements #include_next.
1240///
Chris Lattnercb283342006-06-18 06:48:37 +00001241void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1242 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001243
1244 // #include_next is like #include, except that we start searching after
1245 // the current found directory. If we can't do this, issue a
1246 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001247 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001248 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001250 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001252 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001253 } else {
1254 // Start looking up in the next directory.
1255 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001256 }
1257
1258 return HandleIncludeDirective(IncludeNextTok, Lookup);
1259}
1260
1261/// HandleImportDirective - Implements #import.
1262///
Chris Lattnercb283342006-06-18 06:48:37 +00001263void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1264 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001265
1266 return HandleIncludeDirective(ImportTok, 0, true);
1267}
1268
Chris Lattnerb8761832006-06-24 21:31:03 +00001269//===----------------------------------------------------------------------===//
1270// Preprocessor Macro Directive Handling.
1271//===----------------------------------------------------------------------===//
1272
Chris Lattner22eb9722006-06-18 05:43:12 +00001273/// HandleDefineDirective - Implements #define. This consumes the entire macro
1274/// line then lets the caller lex the next real token.
1275///
Chris Lattnercb283342006-06-18 06:48:37 +00001276void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 ++NumDefined;
1278 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001279 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001280
1281 // Error reading macro name? If so, diagnostic already issued.
1282 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001283 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001284
Chris Lattner50b497e2006-06-18 16:32:35 +00001285 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001286
1287 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001288 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001289
1290 if (Tok.getKind() == tok::eom) {
1291 // If there is no body to this macro, we have no special handling here.
1292 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1293 // This is a function-like macro definition.
1294 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001295 return DiscardUntilEndOfDirective();
1296
1297 } else if (!Tok.hasLeadingSpace()) {
1298 // C99 requires whitespace between the macro definition and the body. Emit
1299 // a diagnostic for something like "#define X+".
1300 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001301 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001302 } else {
1303 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1304 // one in some cases!
1305 }
1306 } else {
1307 // This is a normal token with leading space. Clear the leading space
1308 // marker on the first token to get proper expansion.
1309 Tok.ClearFlag(LexerToken::LeadingSpace);
1310 }
1311
1312 // Read the rest of the macro body.
1313 while (Tok.getKind() != tok::eom) {
1314 MI->AddTokenToBody(Tok);
1315
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001316 // FIXME: Read macro body. See create_iso_definition.
Chris Lattner22eb9722006-06-18 05:43:12 +00001317
1318 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001319 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001320 }
1321
Chris Lattner13044d92006-07-03 05:16:44 +00001322 // If this is the primary source file, remember that this macro hasn't been
1323 // used yet.
1324 if (isInPrimaryFile())
1325 MI->setIsUsed(false);
1326
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 // Finally, if this identifier already had a macro defined for it, verify that
1328 // the macro bodies are identical and free the old definition.
1329 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001330 if (!OtherMI->isUsed())
1331 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1332
Chris Lattner22eb9722006-06-18 05:43:12 +00001333 // FIXME: Verify the definition is the same.
1334 // Macros must be identical. This means all tokes and whitespace separation
1335 // must be the same.
1336 delete OtherMI;
1337 }
1338
1339 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001340}
1341
1342
1343/// HandleUndefDirective - Implements #undef.
1344///
Chris Lattnercb283342006-06-18 06:48:37 +00001345void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 ++NumUndefined;
1347 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001348 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001349
1350 // Error reading macro name? If so, diagnostic already issued.
1351 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001352 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001353
1354 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001355 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001356
1357 // Okay, we finally have a valid identifier to undef.
1358 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1359
1360 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001361 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001362
Chris Lattner13044d92006-07-03 05:16:44 +00001363 if (!MI->isUsed())
1364 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001365
1366 // Free macro definition.
1367 delete MI;
1368 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001369}
1370
1371
Chris Lattnerb8761832006-06-24 21:31:03 +00001372//===----------------------------------------------------------------------===//
1373// Preprocessor Conditional Directive Handling.
1374//===----------------------------------------------------------------------===//
1375
Chris Lattner22eb9722006-06-18 05:43:12 +00001376/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1377/// true when this is a #ifndef directive.
1378///
Chris Lattnercb283342006-06-18 06:48:37 +00001379void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 ++NumIf;
1381 LexerToken DirectiveTok = Result;
1382
1383 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001384 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001385
1386 // Error reading macro name? If so, diagnostic already issued.
1387 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001388 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001389
1390 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001391 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001392
Chris Lattnera78a97e2006-07-03 05:42:18 +00001393 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1394
1395 // If there is a macro, mark it used.
1396 if (MI) MI->setIsUsed(true);
1397
Chris Lattner22eb9722006-06-18 05:43:12 +00001398 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001399 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001400 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001401 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001403 } else {
1404 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001405 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001406 /*Foundnonskip*/false,
1407 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001408 }
1409}
1410
1411/// HandleIfDirective - Implements the #if directive.
1412///
Chris Lattnercb283342006-06-18 06:48:37 +00001413void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001414 ++NumIf;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001415 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001416
1417 // Should we include the stuff contained by this directive?
1418 if (ConditionalTrue) {
1419 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001420 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001421 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001422 } else {
1423 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001424 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001425 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001426 }
1427}
1428
1429/// HandleEndifDirective - Implements the #endif directive.
1430///
Chris Lattnercb283342006-06-18 06:48:37 +00001431void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001432 ++NumEndif;
1433 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001434 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001435
1436 PPConditionalInfo CondInfo;
1437 if (CurLexer->popConditionalLevel(CondInfo)) {
1438 // No conditionals on the stack: this is an #endif without an #if.
1439 return Diag(EndifToken, diag::err_pp_endif_without_if);
1440 }
1441
1442 assert(!CondInfo.WasSkipping && !isSkipping() &&
1443 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001444}
1445
1446
Chris Lattnercb283342006-06-18 06:48:37 +00001447void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001448 ++NumElse;
1449 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001450 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001451
1452 PPConditionalInfo CI;
1453 if (CurLexer->popConditionalLevel(CI))
1454 return Diag(Result, diag::pp_err_else_without_if);
1455
1456 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001457 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001458
1459 // Finally, skip the rest of the contents of this block and return the first
1460 // token after it.
1461 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1462 /*FoundElse*/true);
1463}
1464
Chris Lattnercb283342006-06-18 06:48:37 +00001465void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001466 ++NumElse;
1467 // #elif directive in a non-skipping conditional... start skipping.
1468 // We don't care what the condition is, because we will always skip it (since
1469 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001470 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001471
1472 PPConditionalInfo CI;
1473 if (CurLexer->popConditionalLevel(CI))
1474 return Diag(ElifToken, diag::pp_err_elif_without_if);
1475
1476 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001477 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001478
1479 // Finally, skip the rest of the contents of this block and return the first
1480 // token after it.
1481 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1482 /*FoundElse*/CI.FoundElse);
1483}
Chris Lattnerb8761832006-06-24 21:31:03 +00001484