blob: c88907bf84416bb710d71e782dc6cebfda39750d [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 Lattner22eb9722006-06-18 05:43:12 +0000305 const FileEntry *CurFE =
306 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
307 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 {
353 unsigned NumLexersFound = 0;
354 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000355 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000356
Chris Lattner13044d92006-07-03 05:16:44 +0000357 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000358 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000359 if (IncludeMacroStack[i].TheLexer &&
360 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
361 return IncludeMacroStack[i].TheLexer->isMainFile();
362 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000363}
364
365/// getCurrentLexer - Return the current file lexer being lexed from. Note
366/// that this ignores any potentially active macro expansions and _Pragma
367/// expansions going on at the time.
368Lexer *Preprocessor::getCurrentFileLexer() const {
369 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
370
371 // Look for a stacked lexer.
372 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
373 Lexer *L = IncludeMacroStack[i].TheLexer;
374 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
375 return L;
376 }
377 return 0;
378}
379
380
Chris Lattner22eb9722006-06-18 05:43:12 +0000381/// EnterSourceFile - Add a source file to the top of the include stack and
382/// start lexing tokens from it instead of the current buffer. Return true
383/// on failure.
384void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000385 const DirectoryLookup *CurDir,
386 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000387 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000388 ++NumEnteredSourceFiles;
389
Chris Lattner69772b02006-07-02 20:34:39 +0000390 if (MaxIncludeStackDepth < IncludeMacroStack.size())
391 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000392
Chris Lattner22eb9722006-06-18 05:43:12 +0000393 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000394 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000395 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000396 EnterSourceFileWithLexer(TheLexer, CurDir);
397}
Chris Lattner22eb9722006-06-18 05:43:12 +0000398
Chris Lattner69772b02006-07-02 20:34:39 +0000399/// EnterSourceFile - Add a source file to the top of the include stack and
400/// start lexing tokens from it instead of the current buffer.
401void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
402 const DirectoryLookup *CurDir) {
403
404 // Add the current lexer to the include stack.
405 if (CurLexer || CurMacroExpander)
406 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
407 CurMacroExpander));
408
409 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000410 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000411 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000412
413 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000414 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000415 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
416
417 // Get the file entry for the current file.
418 if (const FileEntry *FE =
419 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
420 FileType = getFileInfo(FE).DirInfo;
421
Chris Lattner1840e492006-07-02 22:30:01 +0000422 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000423 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000424 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000425}
426
Chris Lattner69772b02006-07-02 20:34:39 +0000427
428
Chris Lattner22eb9722006-06-18 05:43:12 +0000429/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000430/// tokens from it instead of the current buffer.
431void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000432 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
433 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000434 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
435 CurMacroExpander));
436 CurLexer = 0;
437 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000438
439 // TODO: Figure out arguments.
440
441 // Mark the macro as currently disabled, so that it is not recursively
442 // expanded.
443 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000444 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000445}
446
Chris Lattner22eb9722006-06-18 05:43:12 +0000447//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000448// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000449//===----------------------------------------------------------------------===//
450
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000451/// RegisterBuiltinMacro - Register the specified identifier in the identifier
452/// table and mark it as a builtin macro to be expanded.
453IdentifierTokenInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
454 // Get the identifier.
455 IdentifierTokenInfo *Id = getIdentifierInfo(Name);
456
457 // Mark it as being a macro that is builtin.
458 MacroInfo *MI = new MacroInfo(SourceLocation());
459 MI->setIsBuiltinMacro();
460 Id->setMacroInfo(MI);
461 return Id;
462}
463
464
Chris Lattner677757a2006-06-28 05:26:32 +0000465/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
466/// identifier table.
467void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000468 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000469 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000470 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
471 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000472 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000473
474 // GCC Extensions.
475 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
476 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000477 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000478
Chris Lattner69772b02006-07-02 20:34:39 +0000479 // FIXME: implement them all:
Chris Lattnerc1283b92006-07-01 23:16:30 +0000480//Pseudo #defines.
481 // __STDC__ 1 if !stdc_0_in_system_headers and "std"
482 // __STDC_VERSION__
483 // __STDC_HOSTED__
484 // __OBJC__
Chris Lattner22eb9722006-06-18 05:43:12 +0000485}
486
Chris Lattner677757a2006-06-28 05:26:32 +0000487
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000488/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
489/// expanded as a macro, handle it and return the next token as 'Identifier'.
490void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
491 MacroInfo *MI) {
492 ++NumMacroExpanded;
Chris Lattner13044d92006-07-03 05:16:44 +0000493
494 // Notice that this macro has been used.
495 MI->setIsUsed(true);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000496
497 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
498 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000499 return ExpandBuiltinMacro(Identifier);
500
501 // If we started lexing a macro, enter the macro expansion body.
502 // FIXME: Read/Validate the argument list here!
503
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000504
505 // If this macro expands to no tokens, don't bother to push it onto the
506 // expansion stack, only to take it right back off.
507 if (MI->getNumTokens() == 0) {
508 // Ignore this macro use, just return the next token in the current
509 // buffer.
510 bool HadLeadingSpace = Identifier.hasLeadingSpace();
511 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
512
513 Lex(Identifier);
514
515 // If the identifier isn't on some OTHER line, inherit the leading
516 // whitespace/first-on-a-line property of this token. This handles
517 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
518 // empty.
519 if (!Identifier.isAtStartOfLine()) {
520 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
521 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
522 }
523 ++NumFastMacroExpanded;
524 return;
525
526 } else if (MI->getNumTokens() == 1 &&
527 // Don't handle identifiers if they need recursive expansion.
528 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
529 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
530 // FIXME: Function-style macros only if no arguments?
531
532 // Otherwise, if this macro expands into a single trivially-expanded
533 // token: expand it now. This handles common cases like
534 // "#define VAL 42".
535
536 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
537 // identifier to the expanded token.
538 bool isAtStartOfLine = Identifier.isAtStartOfLine();
539 bool hasLeadingSpace = Identifier.hasLeadingSpace();
540
541 // Remember where the token is instantiated.
542 SourceLocation InstantiateLoc = Identifier.getLocation();
543
544 // Replace the result token.
545 Identifier = MI->getReplacementToken(0);
546
547 // Restore the StartOfLine/LeadingSpace markers.
548 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
549 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
550
551 // Update the tokens location to include both its logical and physical
552 // locations.
553 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000554 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000555 Identifier.SetLocation(Loc);
556
557 // Since this is not an identifier token, it can't be macro expanded, so
558 // we're done.
559 ++NumFastMacroExpanded;
560 return;
561 }
562
563 // Start expanding the macro (FIXME, pass arguments).
564 EnterMacro(Identifier);
565
566 // Now that the macro is at the top of the include stack, ask the
567 // preprocessor to read the next token from it.
568 return Lex(Identifier);
569}
570
Chris Lattnerc673f902006-06-30 06:10:41 +0000571/// ComputeDATE_TIME - Compute the current time, enter it into the specified
572/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
573/// the identifier tokens inserted.
574static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
575 ScratchBuffer *ScratchBuf) {
576 time_t TT = time(0);
577 struct tm *TM = localtime(&TT);
578
579 static const char * const Months[] = {
580 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
581 };
582
583 char TmpBuffer[100];
584 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
585 TM->tm_year+1900);
586 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
587
588 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
589 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
590}
591
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000592/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
593/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000594void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000595 // Figure out which token this is.
596 IdentifierTokenInfo *ITI = Tok.getIdentifierInfo();
597 assert(ITI && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000598
599 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
600 // lex the token after it.
601 if (ITI == Ident_Pragma)
602 return Handle_Pragma(Tok);
603
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000604 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000605
606 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000607 Tok.SetIdentifierInfo(0);
608 Tok.ClearFlag(LexerToken::NeedsCleaning);
609
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000610 if (ITI == Ident__LINE__) {
611 // __LINE__ expands to a simple numeric value.
612 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
613 unsigned Length = strlen(TmpBuffer);
614 Tok.SetKind(tok::numeric_constant);
615 Tok.SetLength(Length);
616 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000617 } else if (ITI == Ident__FILE__ || ITI == Ident__BASE_FILE__) {
618 SourceLocation Loc = Tok.getLocation();
619 if (ITI == Ident__BASE_FILE__) {
620 Diag(Tok, diag::ext_pp_base_file);
621 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
622 while (NextLoc.getFileID() != 0) {
623 Loc = NextLoc;
624 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
625 }
626 }
627
Chris Lattner0766e592006-07-03 01:07:01 +0000628 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
629 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000630 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000631 Tok.SetKind(tok::string_literal);
632 Tok.SetLength(FN.size());
633 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000634 } else if (ITI == Ident__DATE__) {
635 if (!DATELoc.isValid())
636 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
637 Tok.SetKind(tok::string_literal);
638 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
639 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000640 } else if (ITI == Ident__TIME__) {
641 if (!TIMELoc.isValid())
642 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
643 Tok.SetKind(tok::string_literal);
644 Tok.SetLength(strlen("\"hh:mm:ss\""));
645 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000646 } else if (ITI == Ident__INCLUDE_LEVEL__) {
647 Diag(Tok, diag::ext_pp_include_level);
648
649 // Compute the include depth of this token.
650 unsigned Depth = 0;
651 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
652 for (; Loc.getFileID() != 0; ++Depth)
653 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
654
655 // __INCLUDE_LEVEL__ expands to a simple numeric value.
656 sprintf(TmpBuffer, "%u", Depth);
657 unsigned Length = strlen(TmpBuffer);
658 Tok.SetKind(tok::numeric_constant);
659 Tok.SetLength(Length);
660 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattner847e0e42006-07-01 23:49:16 +0000661 } else if (ITI == Ident__TIMESTAMP__) {
662 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
663 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
664 Diag(Tok, diag::ext_pp_timestamp);
665
666 // Get the file that we are lexing out of. If we're currently lexing from
667 // a macro, dig into the include stack.
668 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000669 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000670
671 if (TheLexer)
672 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
673
674 // If this file is older than the file it depends on, emit a diagnostic.
675 const char *Result;
676 if (CurFile) {
677 time_t TT = CurFile->getModificationTime();
678 struct tm *TM = localtime(&TT);
679 Result = asctime(TM);
680 } else {
681 Result = "??? ??? ?? ??:??:?? ????\n";
682 }
683 TmpBuffer[0] = '"';
684 strcpy(TmpBuffer+1, Result);
685 unsigned Len = strlen(TmpBuffer);
686 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
687 Tok.SetKind(tok::string_literal);
688 Tok.SetLength(Len);
689 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000690 } else {
691 assert(0 && "Unknown identifier!");
692 }
693}
Chris Lattner677757a2006-06-28 05:26:32 +0000694
Chris Lattner13044d92006-07-03 05:16:44 +0000695namespace {
696struct UnusedIdentifierReporter : public IdentifierVisitor {
697 Preprocessor &PP;
698 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
699
700 void VisitIdentifier(IdentifierTokenInfo &ITI) const {
701 if (ITI.getMacroInfo() && !ITI.getMacroInfo()->isUsed())
702 PP.Diag(ITI.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
703 }
704};
705}
706
Chris Lattner677757a2006-06-28 05:26:32 +0000707//===----------------------------------------------------------------------===//
708// Lexer Event Handling.
709//===----------------------------------------------------------------------===//
710
711/// HandleIdentifier - This callback is invoked when the lexer reads an
712/// identifier. This callback looks up the identifier in the map and/or
713/// potentially macro expands it or turns it into a named token (like 'for').
714void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
715 if (Identifier.getIdentifierInfo() == 0) {
716 // If we are skipping tokens (because we are in a #if 0 block), there will
717 // be no identifier info, just return the token.
718 assert(isSkipping() && "Token isn't an identifier?");
719 return;
720 }
721 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
722
723 // If this identifier was poisoned, and if it was not produced from a macro
724 // expansion, emit an error.
725 if (ITI.isPoisoned() && CurLexer)
726 Diag(Identifier, diag::err_pp_used_poisoned_id);
727
728 if (MacroInfo *MI = ITI.getMacroInfo())
729 if (MI->isEnabled() && !DisableMacroExpansion)
730 return HandleMacroExpandedIdentifier(Identifier, MI);
731
732 // Change the kind of this identifier to the appropriate token kind, e.g.
733 // turning "for" into a keyword.
734 Identifier.SetKind(ITI.getTokenID());
735
736 // If this is an extension token, diagnose its use.
737 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
738}
739
Chris Lattner22eb9722006-06-18 05:43:12 +0000740/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
741/// the current file. This either returns the EOF token or pops a level off
742/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000743void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000744 assert(!CurMacroExpander &&
745 "Ending a file when currently in a macro!");
746
747 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
748 // this is an error condition. Just return the EOF token up to
749 // SkipExcludedConditionalBlock. The Lexer will have already have issued
750 // errors for the unterminated #if's on the conditional stack.
751 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000752 Result.StartToken();
753 CurLexer->BufferPtr = CurLexer->BufferEnd;
754 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000755 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000756 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000757 }
758
759 // If this is a #include'd file, pop it off the include stack and continue
760 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000761 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000762 // We're done with the #included file.
763 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000764 CurLexer = IncludeMacroStack.back().TheLexer;
765 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
766 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
767 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000768
769 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000770 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000771 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
772
773 // Get the file entry for the current file.
774 if (const FileEntry *FE =
775 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
776 FileType = getFileInfo(FE).DirInfo;
777
Chris Lattner0c885f52006-06-21 06:50:18 +0000778 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000779 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000780 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000781
Chris Lattner22eb9722006-06-18 05:43:12 +0000782 return Lex(Result);
783 }
784
Chris Lattnerd01e2912006-06-18 16:22:51 +0000785 Result.StartToken();
786 CurLexer->BufferPtr = CurLexer->BufferEnd;
787 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000788 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000789
790 // We're done with the #included file.
791 delete CurLexer;
792 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000793
794 // This is the end of the top-level file.
795 IdentifierInfo.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +0000796}
797
798/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000799/// the current macro line.
800void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000801 assert(CurMacroExpander && !CurLexer &&
802 "Ending a macro when currently in a #include file!");
803
804 // Mark macro not ignored now that it is no longer being expanded.
805 CurMacroExpander->getMacro().EnableMacro();
806 delete CurMacroExpander;
807
Chris Lattner69772b02006-07-02 20:34:39 +0000808 // Handle this like a #include file being popped off the stack.
809 CurMacroExpander = 0;
810 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000811}
812
813
814//===----------------------------------------------------------------------===//
815// Utility Methods for Preprocessor Directive Handling.
816//===----------------------------------------------------------------------===//
817
818/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
819/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000820void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000821 LexerToken Tmp;
822 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000823 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000824 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000825}
826
827/// ReadMacroName - Lex and validate a macro name, which occurs after a
828/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattner44f8a662006-07-03 01:27:27 +0000829/// of the macro line if the macro name is invalid. isDefineUndef is true if
830/// this is due to a a #define or #undef directive, false if it is something
831/// else (e.g. #ifdef).
832void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, bool isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000833 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000834 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000835
836 // Missing macro name?
837 if (MacroNameTok.getKind() == tok::eom)
838 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
839
Chris Lattneraaf09112006-07-03 01:17:59 +0000840 IdentifierTokenInfo *ITI = MacroNameTok.getIdentifierInfo();
841 if (ITI == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000842 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000843 // Fall through on error.
844 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000845 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000846
Chris Lattner44f8a662006-07-03 01:27:27 +0000847 } else if (isDefineUndef && ITI->getName()[0] == 'd' && // defined
Chris Lattneraaf09112006-07-03 01:17:59 +0000848 !strcmp(ITI->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000849 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +0000850 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner44f8a662006-07-03 01:27:27 +0000851 } else if (isDefineUndef && ITI->getMacroInfo() &&
852 ITI->getMacroInfo()->isBuiltinMacro()) {
853 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
854 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +0000855 } else {
856 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000857 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000858 }
859
Chris Lattner22eb9722006-06-18 05:43:12 +0000860 // Invalid macro name, read and discard the rest of the line. Then set the
861 // token kind to tok::eom.
862 MacroNameTok.SetKind(tok::eom);
863 return DiscardUntilEndOfDirective();
864}
865
866/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
867/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000868void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000869 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000870 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000871 // There should be no tokens after the directive, but we allow them as an
872 // extension.
873 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000874 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
875 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000876 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000877}
878
879
880
881/// SkipExcludedConditionalBlock - We just read a #if or related directive and
882/// decided that the subsequent tokens are in the #if'd out portion of the
883/// file. Lex the rest of the file, until we see an #endif. If
884/// FoundNonSkipPortion is true, then we have already emitted code for part of
885/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
886/// is true, then #else directives are ok, if not, then we have already seen one
887/// so a #else directive is a duplicate. When this returns, the caller can lex
888/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000889void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000890 bool FoundNonSkipPortion,
891 bool FoundElse) {
892 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000893 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000894 "Lexing a macro, not a file?");
895
896 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
897 FoundNonSkipPortion, FoundElse);
898
899 // Know that we are going to be skipping tokens. Set this flag to indicate
900 // this, which has a couple of effects:
901 // 1. If EOF of the current lexer is found, the include stack isn't popped.
902 // 2. Identifier information is not looked up for identifier tokens. As an
903 // effect of this, implicit macro expansion is naturally disabled.
904 // 3. "#" tokens at the start of a line are treated as normal tokens, not
905 // implicitly transformed by the lexer.
906 // 4. All notes, warnings, and extension messages are disabled.
907 //
908 SkippingContents = true;
909 LexerToken Tok;
910 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000911 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000912
913 // If this is the end of the buffer, we have an error. The lexer will have
914 // already handled this error condition, so just return and let the caller
915 // lex after this #include.
916 if (Tok.getKind() == tok::eof) break;
917
918 // If this token is not a preprocessor directive, just skip it.
919 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
920 continue;
921
922 // We just parsed a # character at the start of a line, so we're in
923 // directive mode. Tell the lexer this so any newlines we see will be
924 // converted into an EOM token (this terminates the macro).
925 CurLexer->ParsingPreprocessorDirective = true;
926
927 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000928 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000929
930 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
931 // something bogus), skip it.
932 if (Tok.getKind() != tok::identifier) {
933 CurLexer->ParsingPreprocessorDirective = false;
934 continue;
935 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000936
Chris Lattner22eb9722006-06-18 05:43:12 +0000937 // If the first letter isn't i or e, it isn't intesting to us. We know that
938 // this is safe in the face of spelling differences, because there is no way
939 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000940 // allows us to avoid looking up the identifier info for #define/#undef and
941 // other common directives.
942 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
943 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000944 if (FirstChar >= 'a' && FirstChar <= 'z' &&
945 FirstChar != 'i' && FirstChar != 'e') {
946 CurLexer->ParsingPreprocessorDirective = false;
947 continue;
948 }
949
Chris Lattnere60165f2006-06-22 06:36:29 +0000950 // Get the identifier name without trigraphs or embedded newlines. Note
951 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
952 // when skipping.
953 // TODO: could do this with zero copies in the no-clean case by using
954 // strncmp below.
955 char Directive[20];
956 unsigned IdLen;
957 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
958 IdLen = Tok.getLength();
959 memcpy(Directive, RawCharData, IdLen);
960 Directive[IdLen] = 0;
961 } else {
962 std::string DirectiveStr = getSpelling(Tok);
963 IdLen = DirectiveStr.size();
964 if (IdLen >= 20) {
965 CurLexer->ParsingPreprocessorDirective = false;
966 continue;
967 }
968 memcpy(Directive, &DirectiveStr[0], IdLen);
969 Directive[IdLen] = 0;
970 }
971
Chris Lattner22eb9722006-06-18 05:43:12 +0000972 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000973 if ((IdLen == 2) || // "if"
974 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
975 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000976 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
977 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000978 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000979 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000980 /*foundnonskip*/false,
981 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000982 }
983 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000984 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000985 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000986 PPConditionalInfo CondInfo;
987 CondInfo.WasSkipping = true; // Silence bogus warning.
988 bool InCond = CurLexer->popConditionalLevel(CondInfo);
989 assert(!InCond && "Can't be skipping if not in a conditional!");
990
991 // If we popped the outermost skipping block, we're done skipping!
992 if (!CondInfo.WasSkipping)
993 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000994 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000995 // #else directive in a skipping conditional. If not in some other
996 // skipping conditional, and if #else hasn't already been seen, enter it
997 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000998 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000999 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1000
1001 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001002 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001003
1004 // Note that we've seen a #else in this conditional.
1005 CondInfo.FoundElse = true;
1006
1007 // If the conditional is at the top level, and the #if block wasn't
1008 // entered, enter the #else block now.
1009 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1010 CondInfo.FoundNonSkip = true;
1011 break;
1012 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001013 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001014 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1015
1016 bool ShouldEnter;
1017 // If this is in a skipping block or if we're already handled this #if
1018 // block, don't bother parsing the condition.
1019 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001020 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 ShouldEnter = false;
1022 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 // Restore the value of SkippingContents so that identifiers are
1024 // looked up, etc, inside the #elif expression.
1025 assert(SkippingContents && "We have to be skipping here!");
1026 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001027 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001028 SkippingContents = true;
1029 }
1030
1031 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001032 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001033
1034 // If this condition is true, enter it!
1035 if (ShouldEnter) {
1036 CondInfo.FoundNonSkip = true;
1037 break;
1038 }
1039 }
1040 }
1041
1042 CurLexer->ParsingPreprocessorDirective = false;
1043 }
1044
1045 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1046 // of the file, just stop skipping and return to lexing whatever came after
1047 // the #if block.
1048 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001049}
1050
1051//===----------------------------------------------------------------------===//
1052// Preprocessor Directive Handling.
1053//===----------------------------------------------------------------------===//
1054
1055/// HandleDirective - This callback is invoked when the lexer sees a # token
1056/// at the start of a line. This consumes the directive, modifies the
1057/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1058/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001059void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001060 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001061
1062 // We just parsed a # character at the start of a line, so we're in directive
1063 // mode. Tell the lexer this so any newlines we see will be converted into an
1064 // EOM token (this terminates the macro).
1065 CurLexer->ParsingPreprocessorDirective = true;
1066
1067 ++NumDirectives;
1068
1069 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001070 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001071
1072 switch (Result.getKind()) {
1073 default: break;
1074 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001075 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001076
1077#if 0
1078 case tok::numeric_constant:
1079 // FIXME: implement # 7 line numbers!
1080 break;
1081#endif
1082 case tok::kw_else:
1083 return HandleElseDirective(Result);
1084 case tok::kw_if:
1085 return HandleIfDirective(Result);
1086 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001087 // Get the identifier name without trigraphs or embedded newlines.
1088 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001089 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001090 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001092 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001093 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001094 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001095 return HandleElifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001096 if (Directive[0] == 's' && !strcmp(Directive, "sccs")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001097 isExtension = true; // FIXME: implement #sccs
Chris Lattner22eb9722006-06-18 05:43:12 +00001098 // SCCS is the same as #ident.
1099 }
1100 break;
1101 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001102 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001104 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001106 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001108 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001109 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001110 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001111 isExtension = true; // FIXME: implement #ident
Chris Lattner22eb9722006-06-18 05:43:12 +00001112 break;
1113 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001114 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001115 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001116 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +00001118 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001120 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001121 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001122 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1123 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001124 break;
1125 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001126 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1127 return HandleIncludeDirective(Result); // Handle #include.
1128 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001129 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001130 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001131 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 break;
1133 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001134 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001135 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001136 }
1137 break;
1138 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001139 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1140 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001141 break;
1142 }
1143 break;
1144 }
1145
1146 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001147 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001148
1149 // Read the rest of the PP line.
1150 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001151 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 } while (Result.getKind() != tok::eom);
1153
1154 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001155}
1156
Chris Lattnercb283342006-06-18 06:48:37 +00001157void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +00001158 bool isWarning) {
1159 // Read the rest of the line raw. We do this because we don't want macros
1160 // to be expanded and we don't require that the tokens be valid preprocessing
1161 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1162 // collapse multiple consequtive white space between tokens, but this isn't
1163 // specified by the standard.
1164 std::string Message = CurLexer->ReadToEndOfLine();
1165
1166 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1167 return Diag(Result, DiagID, Message);
1168}
1169
Chris Lattnerb8761832006-06-24 21:31:03 +00001170//===----------------------------------------------------------------------===//
1171// Preprocessor Include Directive Handling.
1172//===----------------------------------------------------------------------===//
1173
Chris Lattner22eb9722006-06-18 05:43:12 +00001174/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1175/// file to be included from the lexer, then include it! This is a common
1176/// routine with functionality shared between #include, #include_next and
1177/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001178void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 const DirectoryLookup *LookupFrom,
1180 bool isImport) {
1181 ++NumIncluded;
1182 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001183 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001184
1185 // If the token kind is EOM, the error has already been diagnosed.
1186 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001187 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001188
1189 // Verify that there is nothing after the filename, other than EOM. Use the
1190 // preprocessor to lex this in case lexing the filename entered a macro.
1191 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001192
1193 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001194 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001195 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1196
Chris Lattner269c2322006-06-25 06:23:00 +00001197 // Find out whether the filename is <x> or "x".
1198 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001199
1200 // Remove the quotes.
1201 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1202
Chris Lattner22eb9722006-06-18 05:43:12 +00001203 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001204 const DirectoryLookup *CurDir;
1205 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001206 if (File == 0)
1207 return Diag(FilenameTok, diag::err_pp_file_not_found);
1208
1209 // Get information about this file.
1210 PerFileInfo &FileInfo = getFileInfo(File);
1211
1212 // If this is a #import directive, check that we have not already imported
1213 // this header.
1214 if (isImport) {
1215 // If this has already been imported, don't import it again.
1216 FileInfo.isImport = true;
1217
1218 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001219 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001220 } else {
1221 // Otherwise, if this is a #include of a file that was previously #import'd
1222 // or if this is the second #include of a #pragma once file, ignore it.
1223 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001224 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001225 }
1226
1227 // Look up the file, create a File ID for it.
1228 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +00001229 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 if (FileID == 0)
1231 return Diag(FilenameTok, diag::err_pp_file_not_found);
1232
1233 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001234 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001235
1236 // Increment the number of times this file has been included.
1237 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001238}
1239
1240/// HandleIncludeNextDirective - Implements #include_next.
1241///
Chris Lattnercb283342006-06-18 06:48:37 +00001242void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1243 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001244
1245 // #include_next is like #include, except that we start searching after
1246 // the current found directory. If we can't do this, issue a
1247 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001248 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001249 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001250 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001251 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001252 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001253 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001254 } else {
1255 // Start looking up in the next directory.
1256 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 }
1258
1259 return HandleIncludeDirective(IncludeNextTok, Lookup);
1260}
1261
1262/// HandleImportDirective - Implements #import.
1263///
Chris Lattnercb283342006-06-18 06:48:37 +00001264void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1265 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001266
1267 return HandleIncludeDirective(ImportTok, 0, true);
1268}
1269
Chris Lattnerb8761832006-06-24 21:31:03 +00001270//===----------------------------------------------------------------------===//
1271// Preprocessor Macro Directive Handling.
1272//===----------------------------------------------------------------------===//
1273
Chris Lattner22eb9722006-06-18 05:43:12 +00001274/// HandleDefineDirective - Implements #define. This consumes the entire macro
1275/// line then lets the caller lex the next real token.
1276///
Chris Lattnercb283342006-06-18 06:48:37 +00001277void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 ++NumDefined;
1279 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001280 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001281
1282 // Error reading macro name? If so, diagnostic already issued.
1283 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001284 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001285
Chris Lattner50b497e2006-06-18 16:32:35 +00001286 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001287
1288 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001289 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001290
1291 if (Tok.getKind() == tok::eom) {
1292 // If there is no body to this macro, we have no special handling here.
1293 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1294 // This is a function-like macro definition.
1295 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 return DiscardUntilEndOfDirective();
1297
1298 } else if (!Tok.hasLeadingSpace()) {
1299 // C99 requires whitespace between the macro definition and the body. Emit
1300 // a diagnostic for something like "#define X+".
1301 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001302 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001303 } else {
1304 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1305 // one in some cases!
1306 }
1307 } else {
1308 // This is a normal token with leading space. Clear the leading space
1309 // marker on the first token to get proper expansion.
1310 Tok.ClearFlag(LexerToken::LeadingSpace);
1311 }
1312
1313 // Read the rest of the macro body.
1314 while (Tok.getKind() != tok::eom) {
1315 MI->AddTokenToBody(Tok);
1316
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001317 // FIXME: Read macro body. See create_iso_definition.
Chris Lattner22eb9722006-06-18 05:43:12 +00001318
1319 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001320 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 }
1322
Chris Lattner13044d92006-07-03 05:16:44 +00001323 // If this is the primary source file, remember that this macro hasn't been
1324 // used yet.
1325 if (isInPrimaryFile())
1326 MI->setIsUsed(false);
1327
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 // Finally, if this identifier already had a macro defined for it, verify that
1329 // the macro bodies are identical and free the old definition.
1330 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001331 if (!OtherMI->isUsed())
1332 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1333
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 // FIXME: Verify the definition is the same.
1335 // Macros must be identical. This means all tokes and whitespace separation
1336 // must be the same.
1337 delete OtherMI;
1338 }
1339
1340 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001341}
1342
1343
1344/// HandleUndefDirective - Implements #undef.
1345///
Chris Lattnercb283342006-06-18 06:48:37 +00001346void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001347 ++NumUndefined;
1348 LexerToken MacroNameTok;
Chris Lattner44f8a662006-07-03 01:27:27 +00001349 ReadMacroName(MacroNameTok, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001350
1351 // Error reading macro name? If so, diagnostic already issued.
1352 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001353 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001354
1355 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001356 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001357
1358 // Okay, we finally have a valid identifier to undef.
1359 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1360
1361 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001362 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001363
Chris Lattner13044d92006-07-03 05:16:44 +00001364 if (!MI->isUsed())
1365 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001366
1367 // Free macro definition.
1368 delete MI;
1369 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001370}
1371
1372
Chris Lattnerb8761832006-06-24 21:31:03 +00001373//===----------------------------------------------------------------------===//
1374// Preprocessor Conditional Directive Handling.
1375//===----------------------------------------------------------------------===//
1376
Chris Lattner22eb9722006-06-18 05:43:12 +00001377/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1378/// true when this is a #ifndef directive.
1379///
Chris Lattnercb283342006-06-18 06:48:37 +00001380void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001381 ++NumIf;
1382 LexerToken DirectiveTok = Result;
1383
1384 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001385 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001386
1387 // Error reading macro name? If so, diagnostic already issued.
1388 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001389 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001390
1391 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001392 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001393
1394 // Should we include the stuff contained by this directive?
1395 if (!MacroNameTok.getIdentifierInfo()->getMacroInfo() == isIfndef) {
1396 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001397 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001398 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001399 } else {
1400 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001401 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001402 /*Foundnonskip*/false,
1403 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 }
1405}
1406
1407/// HandleIfDirective - Implements the #if directive.
1408///
Chris Lattnercb283342006-06-18 06:48:37 +00001409void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001410 ++NumIf;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001411 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001412
1413 // Should we include the stuff contained by this directive?
1414 if (ConditionalTrue) {
1415 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001416 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001418 } else {
1419 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001420 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001421 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001422 }
1423}
1424
1425/// HandleEndifDirective - Implements the #endif directive.
1426///
Chris Lattnercb283342006-06-18 06:48:37 +00001427void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001428 ++NumEndif;
1429 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001430 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001431
1432 PPConditionalInfo CondInfo;
1433 if (CurLexer->popConditionalLevel(CondInfo)) {
1434 // No conditionals on the stack: this is an #endif without an #if.
1435 return Diag(EndifToken, diag::err_pp_endif_without_if);
1436 }
1437
1438 assert(!CondInfo.WasSkipping && !isSkipping() &&
1439 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001440}
1441
1442
Chris Lattnercb283342006-06-18 06:48:37 +00001443void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001444 ++NumElse;
1445 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001446 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001447
1448 PPConditionalInfo CI;
1449 if (CurLexer->popConditionalLevel(CI))
1450 return Diag(Result, diag::pp_err_else_without_if);
1451
1452 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001453 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001454
1455 // Finally, skip the rest of the contents of this block and return the first
1456 // token after it.
1457 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1458 /*FoundElse*/true);
1459}
1460
Chris Lattnercb283342006-06-18 06:48:37 +00001461void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001462 ++NumElse;
1463 // #elif directive in a non-skipping conditional... start skipping.
1464 // We don't care what the condition is, because we will always skip it (since
1465 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001466 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001467
1468 PPConditionalInfo CI;
1469 if (CurLexer->popConditionalLevel(CI))
1470 return Diag(ElifToken, diag::pp_err_elif_without_if);
1471
1472 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001473 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001474
1475 // Finally, skip the rest of the contents of this block and return the first
1476 // token after it.
1477 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1478 /*FoundElse*/CI.FoundElse);
1479}
Chris Lattnerb8761832006-06-24 21:31:03 +00001480