blob: 258815175780f416e239bd626e7305b41c09520e [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 Lattner3665f162006-07-04 07:26:10 +000059 MaxIncludeStackDepth = 0; NumMultiIncludeFileOptzn = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000060 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000061
Chris Lattner22eb9722006-06-18 05:43:12 +000062 // Macro expansion is enabled.
63 DisableMacroExpansion = false;
64 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000065
66 // There is no file-change handler yet.
67 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000068 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000069
Chris Lattner8ff71992006-07-06 05:17:39 +000070 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
71 // This gets unpoisoned where it is allowed.
72 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
73
Chris Lattnerb8761832006-06-24 21:31:03 +000074 // Initialize the pragma handlers.
75 PragmaHandlers = new PragmaNamespace(0);
76 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000077
78 // Initialize builtin macros like __LINE__ and friends.
79 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000080}
81
82Preprocessor::~Preprocessor() {
83 // Free any active lexers.
84 delete CurLexer;
85
Chris Lattner69772b02006-07-02 20:34:39 +000086 while (!IncludeMacroStack.empty()) {
87 delete IncludeMacroStack.back().TheLexer;
88 delete IncludeMacroStack.back().TheMacroExpander;
89 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000090 }
Chris Lattnerb8761832006-06-24 21:31:03 +000091
92 // Release pragma information.
93 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000094
95 // Delete the scratch buffer info.
96 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000097}
98
99/// getFileInfo - Return the PerFileInfo structure for the specified
100/// FileEntry.
101Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
102 if (FE->getUID() >= FileInfo.size())
103 FileInfo.resize(FE->getUID()+1);
104 return FileInfo[FE->getUID()];
105}
106
107
108/// AddKeywords - Add all keywords to the symbol table.
109///
110void Preprocessor::AddKeywords() {
111 enum {
112 C90Shift = 0,
113 EXTC90 = 1 << C90Shift,
114 NOTC90 = 2 << C90Shift,
115 C99Shift = 2,
116 EXTC99 = 1 << C99Shift,
117 NOTC99 = 2 << C99Shift,
118 CPPShift = 4,
119 EXTCPP = 1 << CPPShift,
120 NOTCPP = 2 << CPPShift,
121 Mask = 3
122 };
123
124 // Add keywords and tokens for the current language.
125#define KEYWORD(NAME, FLAGS) \
126 AddKeyword(#NAME+1, tok::kw##NAME, \
127 (FLAGS >> C90Shift) & Mask, \
128 (FLAGS >> C99Shift) & Mask, \
129 (FLAGS >> CPPShift) & Mask);
130#define ALIAS(NAME, TOK) \
131 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
132#include "clang/Basic/TokenKinds.def"
133}
134
135/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
136/// the specified LexerToken's location, translating the token's start
137/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000138void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000139 const std::string &Msg) {
140 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
141 // warnings or extensions.
142 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000143 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000144
Chris Lattnercb283342006-06-18 06:48:37 +0000145 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000146}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000147
148void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
149 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
150 << getSpelling(Tok) << "'";
151
152 if (!DumpFlags) return;
153 std::cerr << "\t";
154 if (Tok.isAtStartOfLine())
155 std::cerr << " [StartOfLine]";
156 if (Tok.hasLeadingSpace())
157 std::cerr << " [LeadingSpace]";
158 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000159 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000160 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
161 << "']";
162 }
163}
164
165void Preprocessor::DumpMacro(const MacroInfo &MI) const {
166 std::cerr << "MACRO: ";
167 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
168 DumpToken(MI.getReplacementToken(i));
169 std::cerr << " ";
170 }
171 std::cerr << "\n";
172}
173
Chris Lattner22eb9722006-06-18 05:43:12 +0000174void Preprocessor::PrintStats() {
175 std::cerr << "\n*** Preprocessor Stats:\n";
176 std::cerr << FileInfo.size() << " files tracked.\n";
177 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
178 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
179 NumOnceOnlyFiles += FileInfo[i].isImport;
180 if (MaxNumIncludes < FileInfo[i].NumIncludes)
181 MaxNumIncludes = FileInfo[i].NumIncludes;
182 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
183 }
184 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
185 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
186 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
187
188 std::cerr << NumDirectives << " directives found:\n";
189 std::cerr << " " << NumDefined << " #define.\n";
190 std::cerr << " " << NumUndefined << " #undef.\n";
191 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
Chris Lattner3665f162006-07-04 07:26:10 +0000192 std::cerr << " " << NumMultiIncludeFileOptzn << " #includes skipped due to"
193 << " the multi-include optimization.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000194 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
195 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
196 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
197 std::cerr << " " << NumElse << " #else/#elif.\n";
198 std::cerr << " " << NumEndif << " #endif.\n";
199 std::cerr << " " << NumPragma << " #pragma.\n";
200 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
201
202 std::cerr << NumMacroExpanded << " macros expanded, "
203 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000204}
205
206//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000207// Token Spelling
208//===----------------------------------------------------------------------===//
209
210
211/// getSpelling() - Return the 'spelling' of this token. The spelling of a
212/// token are the characters used to represent the token in the source file
213/// after trigraph expansion and escaped-newline folding. In particular, this
214/// wants to get the true, uncanonicalized, spelling of things like digraphs
215/// UCNs, etc.
216std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
217 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
218
219 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000220 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 if (!Tok.needsCleaning())
222 return std::string(TokStart, TokStart+Tok.getLength());
223
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 std::string Result;
225 Result.reserve(Tok.getLength());
226
Chris Lattneref9eae12006-07-04 22:33:12 +0000227 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
229 Ptr != End; ) {
230 unsigned CharSize;
231 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
232 Ptr += CharSize;
233 }
234 assert(Result.size() != unsigned(Tok.getLength()) &&
235 "NeedsCleaning flag set on something that didn't need cleaning!");
236 return Result;
237}
238
239/// getSpelling - This method is used to get the spelling of a token into a
240/// preallocated buffer, instead of as an std::string. The caller is required
241/// to allocate enough space for the token, which is guaranteed to be at least
242/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000243///
244/// Note that this method may do two possible things: it may either fill in
245/// the buffer specified with characters, or it may *change the input pointer*
246/// to point to a constant buffer with the data already in it (avoiding a
247/// copy). The caller is not allowed to modify the returned buffer pointer
248/// if an internal buffer is returned.
249unsigned Preprocessor::getSpelling(const LexerToken &Tok,
250 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
252
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000253 // If this token is an identifier, just return the string from the identifier
254 // table, which is very quick.
255 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
256 Buffer = II->getName();
257 return Tok.getLength();
258 }
259
260 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000261 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000262
263 // If this token contains nothing interesting, return it directly.
264 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000265 Buffer = TokStart;
266 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000267 }
268 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000269 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000270 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
271 Ptr != End; ) {
272 unsigned CharSize;
273 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
274 Ptr += CharSize;
275 }
276 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
277 "NeedsCleaning flag set on something that didn't need cleaning!");
278
279 return OutBuf-Buffer;
280}
281
282//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000283// Source File Location Methods.
284//===----------------------------------------------------------------------===//
285
286
287/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
288/// return null on failure. isAngled indicates whether the file reference is
289/// for system #include's or not (i.e. using <> instead of "").
290const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000291 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000292 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000293 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000294 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000295 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000296
297 // If 'Filename' is absolute, check to see if it exists and no searching.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000298 // FIXME: Portability. This should be a sys::Path interface, this doesn't
299 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
Chris Lattner22eb9722006-06-18 05:43:12 +0000300 if (Filename[0] == '/') {
301 // If this was an #include_next "/absolute/file", fail.
302 if (FromDir) return 0;
303
304 // Otherwise, just return the file.
305 return FileMgr.getFile(Filename);
306 }
307
308 // Step #0, unless disabled, check to see if the file is in the #includer's
309 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000310 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000311 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
312 const FileEntry *CurFE = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000313 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000314 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000315 // FIXME: Portability. Should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000316 if (const FileEntry *FE =
317 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000318 if (CurDirLookup)
319 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000320 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000321 CurDir = 0;
322
323 // This file is a system header or C++ unfriendly if the old file is.
324 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000325 return FE;
326 }
327 }
328 }
329
330 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000331 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000332
333 // If this is a #include_next request, start searching after the directory the
334 // file was found in.
335 if (FromDir)
336 i = FromDir-&SearchDirs[0];
337
338 // Check each directory in sequence to see if it contains this file.
339 for (; i != SearchDirs.size(); ++i) {
340 // Concatenate the requested file onto the directory.
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000341 // FIXME: Portability. Adding file to dir should be in sys::Path.
342 std::string SearchDir = SearchDirs[i].getDir()->getName()+"/"+Filename;
343 if (const FileEntry *FE = FileMgr.getFile(SearchDir)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000344 CurDir = &SearchDirs[i];
345
346 // This file is a system header or C++ unfriendly if the dir is.
347 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000348 return FE;
349 }
350 }
351
352 // Otherwise, didn't find it.
353 return 0;
354}
355
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000356/// isInPrimaryFile - Return true if we're in the top-level file, not in a
357/// #include.
358bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000359 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000360 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000361
Chris Lattner13044d92006-07-03 05:16:44 +0000362 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000363 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000364 if (IncludeMacroStack[i].TheLexer &&
365 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
366 return IncludeMacroStack[i].TheLexer->isMainFile();
367 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000368}
369
370/// getCurrentLexer - Return the current file lexer being lexed from. Note
371/// that this ignores any potentially active macro expansions and _Pragma
372/// expansions going on at the time.
373Lexer *Preprocessor::getCurrentFileLexer() const {
374 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
375
376 // Look for a stacked lexer.
377 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000378 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000379 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
380 return L;
381 }
382 return 0;
383}
384
385
Chris Lattner22eb9722006-06-18 05:43:12 +0000386/// EnterSourceFile - Add a source file to the top of the include stack and
387/// start lexing tokens from it instead of the current buffer. Return true
388/// on failure.
389void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000390 const DirectoryLookup *CurDir,
391 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000392 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000393 ++NumEnteredSourceFiles;
394
Chris Lattner69772b02006-07-02 20:34:39 +0000395 if (MaxIncludeStackDepth < IncludeMacroStack.size())
396 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000397
Chris Lattner22eb9722006-06-18 05:43:12 +0000398 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000399 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000400 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000401 EnterSourceFileWithLexer(TheLexer, CurDir);
402}
Chris Lattner22eb9722006-06-18 05:43:12 +0000403
Chris Lattner69772b02006-07-02 20:34:39 +0000404/// EnterSourceFile - Add a source file to the top of the include stack and
405/// start lexing tokens from it instead of the current buffer.
406void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
407 const DirectoryLookup *CurDir) {
408
409 // Add the current lexer to the include stack.
410 if (CurLexer || CurMacroExpander)
411 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
412 CurMacroExpander));
413
414 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000415 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000416 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000417
418 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000419 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000420 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
421
422 // Get the file entry for the current file.
423 if (const FileEntry *FE =
424 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
425 FileType = getFileInfo(FE).DirInfo;
426
Chris Lattner1840e492006-07-02 22:30:01 +0000427 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000428 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000429 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000430}
431
Chris Lattner69772b02006-07-02 20:34:39 +0000432
433
Chris Lattner22eb9722006-06-18 05:43:12 +0000434/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000435/// tokens from it instead of the current buffer.
436void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000437 IdentifierInfo *Identifier = Tok.getIdentifierInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000438 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000439 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
440 CurMacroExpander));
441 CurLexer = 0;
442 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000443
444 // TODO: Figure out arguments.
445
446 // Mark the macro as currently disabled, so that it is not recursively
447 // expanded.
448 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000449 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000450}
451
Chris Lattner22eb9722006-06-18 05:43:12 +0000452//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000453// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000454//===----------------------------------------------------------------------===//
455
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000456/// RegisterBuiltinMacro - Register the specified identifier in the identifier
457/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000458IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000459 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000460 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000461
462 // Mark it as being a macro that is builtin.
463 MacroInfo *MI = new MacroInfo(SourceLocation());
464 MI->setIsBuiltinMacro();
465 Id->setMacroInfo(MI);
466 return Id;
467}
468
469
Chris Lattner677757a2006-06-28 05:26:32 +0000470/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
471/// identifier table.
472void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000473 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000474 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000475 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
476 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000477 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000478
479 // GCC Extensions.
480 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
481 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000482 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000483}
484
Chris Lattner677757a2006-06-28 05:26:32 +0000485
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000486/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
487/// expanded as a macro, handle it and return the next token as 'Identifier'.
488void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
489 MacroInfo *MI) {
490 ++NumMacroExpanded;
Chris Lattner13044d92006-07-03 05:16:44 +0000491
492 // Notice that this macro has been used.
493 MI->setIsUsed(true);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000494
495 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
496 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000497 return ExpandBuiltinMacro(Identifier);
498
499 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000500 // FIXME: Fn-Like Macros: Read/Validate the argument list here!
Chris Lattner69772b02006-07-02 20:34:39 +0000501
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000502
503 // If this macro expands to no tokens, don't bother to push it onto the
504 // expansion stack, only to take it right back off.
505 if (MI->getNumTokens() == 0) {
506 // Ignore this macro use, just return the next token in the current
507 // buffer.
508 bool HadLeadingSpace = Identifier.hasLeadingSpace();
509 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
510
511 Lex(Identifier);
512
513 // If the identifier isn't on some OTHER line, inherit the leading
514 // whitespace/first-on-a-line property of this token. This handles
515 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
516 // empty.
517 if (!Identifier.isAtStartOfLine()) {
518 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
519 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
520 }
521 ++NumFastMacroExpanded;
522 return;
523
524 } else if (MI->getNumTokens() == 1 &&
525 // Don't handle identifiers if they need recursive expansion.
526 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
527 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000528 // FIXME: Fn-Like Macros: Function-style macros only if no arguments?
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000529
530 // Otherwise, if this macro expands into a single trivially-expanded
531 // token: expand it now. This handles common cases like
532 // "#define VAL 42".
533
534 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
535 // identifier to the expanded token.
536 bool isAtStartOfLine = Identifier.isAtStartOfLine();
537 bool hasLeadingSpace = Identifier.hasLeadingSpace();
538
539 // Remember where the token is instantiated.
540 SourceLocation InstantiateLoc = Identifier.getLocation();
541
542 // Replace the result token.
543 Identifier = MI->getReplacementToken(0);
544
545 // Restore the StartOfLine/LeadingSpace markers.
546 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
547 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
548
549 // Update the tokens location to include both its logical and physical
550 // locations.
551 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000552 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000553 Identifier.SetLocation(Loc);
554
555 // Since this is not an identifier token, it can't be macro expanded, so
556 // we're done.
557 ++NumFastMacroExpanded;
558 return;
559 }
560
Chris Lattnerd7dfa572006-07-04 04:50:35 +0000561 // Start expanding the macro (FIXME: Fn-Like Macros: pass arguments).
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000562 EnterMacro(Identifier);
563
564 // Now that the macro is at the top of the include stack, ask the
565 // preprocessor to read the next token from it.
566 return Lex(Identifier);
567}
568
Chris Lattnerc673f902006-06-30 06:10:41 +0000569/// ComputeDATE_TIME - Compute the current time, enter it into the specified
570/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
571/// the identifier tokens inserted.
572static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
573 ScratchBuffer *ScratchBuf) {
574 time_t TT = time(0);
575 struct tm *TM = localtime(&TT);
576
577 static const char * const Months[] = {
578 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
579 };
580
581 char TmpBuffer[100];
582 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
583 TM->tm_year+1900);
584 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
585
586 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
587 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
588}
589
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000590/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
591/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000592void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000593 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000594 IdentifierInfo *II = Tok.getIdentifierInfo();
595 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000596
597 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
598 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000599 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000600 return Handle_Pragma(Tok);
601
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000602 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000603
604 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000605 Tok.SetIdentifierInfo(0);
606 Tok.ClearFlag(LexerToken::NeedsCleaning);
607
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000608 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000609 // __LINE__ expands to a simple numeric value.
610 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
611 unsigned Length = strlen(TmpBuffer);
612 Tok.SetKind(tok::numeric_constant);
613 Tok.SetLength(Length);
614 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000615 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000616 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000617 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000618 Diag(Tok, diag::ext_pp_base_file);
619 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
620 while (NextLoc.getFileID() != 0) {
621 Loc = NextLoc;
622 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
623 }
624 }
625
Chris Lattner0766e592006-07-03 01:07:01 +0000626 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
627 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000628 FN = Lexer::Stringify(FN);
Chris Lattner630b33c2006-07-01 22:46:53 +0000629 Tok.SetKind(tok::string_literal);
630 Tok.SetLength(FN.size());
631 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000632 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000633 if (!DATELoc.isValid())
634 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
635 Tok.SetKind(tok::string_literal);
636 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
637 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000638 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000639 if (!TIMELoc.isValid())
640 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
641 Tok.SetKind(tok::string_literal);
642 Tok.SetLength(strlen("\"hh:mm:ss\""));
643 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000644 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000645 Diag(Tok, diag::ext_pp_include_level);
646
647 // Compute the include depth of this token.
648 unsigned Depth = 0;
649 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
650 for (; Loc.getFileID() != 0; ++Depth)
651 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
652
653 // __INCLUDE_LEVEL__ expands to a simple numeric value.
654 sprintf(TmpBuffer, "%u", Depth);
655 unsigned Length = strlen(TmpBuffer);
656 Tok.SetKind(tok::numeric_constant);
657 Tok.SetLength(Length);
658 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000659 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000660 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
661 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
662 Diag(Tok, diag::ext_pp_timestamp);
663
664 // Get the file that we are lexing out of. If we're currently lexing from
665 // a macro, dig into the include stack.
666 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000667 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000668
669 if (TheLexer)
670 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
671
672 // If this file is older than the file it depends on, emit a diagnostic.
673 const char *Result;
674 if (CurFile) {
675 time_t TT = CurFile->getModificationTime();
676 struct tm *TM = localtime(&TT);
677 Result = asctime(TM);
678 } else {
679 Result = "??? ??? ?? ??:??:?? ????\n";
680 }
681 TmpBuffer[0] = '"';
682 strcpy(TmpBuffer+1, Result);
683 unsigned Len = strlen(TmpBuffer);
684 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
685 Tok.SetKind(tok::string_literal);
686 Tok.SetLength(Len);
687 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000688 } else {
689 assert(0 && "Unknown identifier!");
690 }
691}
Chris Lattner677757a2006-06-28 05:26:32 +0000692
Chris Lattner13044d92006-07-03 05:16:44 +0000693namespace {
694struct UnusedIdentifierReporter : public IdentifierVisitor {
695 Preprocessor &PP;
696 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
697
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000698 void VisitIdentifier(IdentifierInfo &II) const {
699 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
700 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000701 }
702};
703}
704
Chris Lattner677757a2006-06-28 05:26:32 +0000705//===----------------------------------------------------------------------===//
706// Lexer Event Handling.
707//===----------------------------------------------------------------------===//
708
Chris Lattnercefc7682006-07-08 08:28:12 +0000709/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
710/// identifier information for the token and install it into the token.
711IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
712 const char *BufPtr) {
713 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
714 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
715
716 // Look up this token, see if it is a macro, or if it is a language keyword.
717 IdentifierInfo *II;
718 if (BufPtr && !Identifier.needsCleaning()) {
719 // No cleaning needed, just use the characters from the lexed buffer.
720 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
721 } else {
722 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
723 const char *TmpBuf = (char*)alloca(Identifier.getLength());
724 unsigned Size = getSpelling(Identifier, TmpBuf);
725 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
726 }
727 Identifier.SetIdentifierInfo(II);
728 return II;
729}
730
731
Chris Lattner677757a2006-06-28 05:26:32 +0000732/// HandleIdentifier - This callback is invoked when the lexer reads an
733/// identifier. This callback looks up the identifier in the map and/or
734/// potentially macro expands it or turns it into a named token (like 'for').
735void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
736 if (Identifier.getIdentifierInfo() == 0) {
737 // If we are skipping tokens (because we are in a #if 0 block), there will
738 // be no identifier info, just return the token.
739 assert(isSkipping() && "Token isn't an identifier?");
740 return;
741 }
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000742 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000743
744 // If this identifier was poisoned, and if it was not produced from a macro
745 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000746 if (II.isPoisoned() && CurLexer) {
747 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
748 Diag(Identifier, diag::err_pp_used_poisoned_id);
749 else
750 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
751 }
Chris Lattner677757a2006-06-28 05:26:32 +0000752
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000753 if (MacroInfo *MI = II.getMacroInfo())
Chris Lattner677757a2006-06-28 05:26:32 +0000754 if (MI->isEnabled() && !DisableMacroExpansion)
755 return HandleMacroExpandedIdentifier(Identifier, MI);
756
757 // Change the kind of this identifier to the appropriate token kind, e.g.
758 // turning "for" into a keyword.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000759 Identifier.SetKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000760
761 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000762 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000763}
764
Chris Lattner22eb9722006-06-18 05:43:12 +0000765/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
766/// the current file. This either returns the EOF token or pops a level off
767/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000768void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000769 assert(!CurMacroExpander &&
770 "Ending a file when currently in a macro!");
771
772 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
773 // this is an error condition. Just return the EOF token up to
774 // SkipExcludedConditionalBlock. The Lexer will have already have issued
775 // errors for the unterminated #if's on the conditional stack.
776 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000777 Result.StartToken();
778 CurLexer->BufferPtr = CurLexer->BufferEnd;
779 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000780 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000781 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000782 }
783
Chris Lattner371ac8a2006-07-04 07:11:10 +0000784 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000785 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000786 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000787 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000788 // Okay, this has a controlling macro, remember in PerFileInfo.
789 if (const FileEntry *FE =
790 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
791 getFileInfo(FE).ControllingMacro = ControllingMacro;
Chris Lattner371ac8a2006-07-04 07:11:10 +0000792 }
793 }
794
Chris Lattner22eb9722006-06-18 05:43:12 +0000795 // If this is a #include'd file, pop it off the include stack and continue
796 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000797 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000798 // We're done with the #included file.
799 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000800 CurLexer = IncludeMacroStack.back().TheLexer;
801 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
802 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
803 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000804
805 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000806 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000807 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
808
809 // Get the file entry for the current file.
810 if (const FileEntry *FE =
811 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
812 FileType = getFileInfo(FE).DirInfo;
813
Chris Lattner0c885f52006-06-21 06:50:18 +0000814 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000815 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000816 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000817
Chris Lattner22eb9722006-06-18 05:43:12 +0000818 return Lex(Result);
819 }
820
Chris Lattnerd01e2912006-06-18 16:22:51 +0000821 Result.StartToken();
822 CurLexer->BufferPtr = CurLexer->BufferEnd;
823 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000824 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000825
826 // We're done with the #included file.
827 delete CurLexer;
828 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000829
830 // This is the end of the top-level file.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000831 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner22eb9722006-06-18 05:43:12 +0000832}
833
834/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000835/// the current macro line.
836void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000837 assert(CurMacroExpander && !CurLexer &&
838 "Ending a macro when currently in a #include file!");
839
840 // Mark macro not ignored now that it is no longer being expanded.
841 CurMacroExpander->getMacro().EnableMacro();
842 delete CurMacroExpander;
843
Chris Lattner69772b02006-07-02 20:34:39 +0000844 // Handle this like a #include file being popped off the stack.
845 CurMacroExpander = 0;
846 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000847}
848
849
850//===----------------------------------------------------------------------===//
851// Utility Methods for Preprocessor Directive Handling.
852//===----------------------------------------------------------------------===//
853
854/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
855/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000856void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000857 LexerToken Tmp;
858 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000859 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000860 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000861}
862
863/// ReadMacroName - Lex and validate a macro name, which occurs after a
864/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +0000865/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
866/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +0000867/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +0000868void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000869 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000870 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000871
872 // Missing macro name?
873 if (MacroNameTok.getKind() == tok::eom)
874 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
875
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000876 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
877 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000878 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000879 // Fall through on error.
880 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000881 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000882
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000883 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
884 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000885 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +0000886 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000887 } else if (isDefineUndef && II->getMacroInfo() &&
888 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +0000889 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +0000890 if (isDefineUndef == 1)
891 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
892 else
893 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +0000894 } else {
895 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000896 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000897 }
898
Chris Lattner22eb9722006-06-18 05:43:12 +0000899 // Invalid macro name, read and discard the rest of the line. Then set the
900 // token kind to tok::eom.
901 MacroNameTok.SetKind(tok::eom);
902 return DiscardUntilEndOfDirective();
903}
904
905/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
906/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000907void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000908 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000909 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000910 // There should be no tokens after the directive, but we allow them as an
911 // extension.
912 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000913 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
914 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000915 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000916}
917
918
919
920/// SkipExcludedConditionalBlock - We just read a #if or related directive and
921/// decided that the subsequent tokens are in the #if'd out portion of the
922/// file. Lex the rest of the file, until we see an #endif. If
923/// FoundNonSkipPortion is true, then we have already emitted code for part of
924/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
925/// is true, then #else directives are ok, if not, then we have already seen one
926/// so a #else directive is a duplicate. When this returns, the caller can lex
927/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000928void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000929 bool FoundNonSkipPortion,
930 bool FoundElse) {
931 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000932 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000933 "Lexing a macro, not a file?");
934
935 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
936 FoundNonSkipPortion, FoundElse);
937
938 // Know that we are going to be skipping tokens. Set this flag to indicate
939 // this, which has a couple of effects:
940 // 1. If EOF of the current lexer is found, the include stack isn't popped.
941 // 2. Identifier information is not looked up for identifier tokens. As an
942 // effect of this, implicit macro expansion is naturally disabled.
943 // 3. "#" tokens at the start of a line are treated as normal tokens, not
944 // implicitly transformed by the lexer.
945 // 4. All notes, warnings, and extension messages are disabled.
946 //
947 SkippingContents = true;
948 LexerToken Tok;
949 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000950 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000951
952 // If this is the end of the buffer, we have an error. The lexer will have
953 // already handled this error condition, so just return and let the caller
954 // lex after this #include.
955 if (Tok.getKind() == tok::eof) break;
956
957 // If this token is not a preprocessor directive, just skip it.
958 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
959 continue;
960
961 // We just parsed a # character at the start of a line, so we're in
962 // directive mode. Tell the lexer this so any newlines we see will be
963 // converted into an EOM token (this terminates the macro).
964 CurLexer->ParsingPreprocessorDirective = true;
965
966 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000967 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000968
969 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
970 // something bogus), skip it.
971 if (Tok.getKind() != tok::identifier) {
972 CurLexer->ParsingPreprocessorDirective = false;
973 continue;
974 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000975
Chris Lattner22eb9722006-06-18 05:43:12 +0000976 // If the first letter isn't i or e, it isn't intesting to us. We know that
977 // this is safe in the face of spelling differences, because there is no way
978 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000979 // allows us to avoid looking up the identifier info for #define/#undef and
980 // other common directives.
981 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
982 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000983 if (FirstChar >= 'a' && FirstChar <= 'z' &&
984 FirstChar != 'i' && FirstChar != 'e') {
985 CurLexer->ParsingPreprocessorDirective = false;
986 continue;
987 }
988
Chris Lattnere60165f2006-06-22 06:36:29 +0000989 // Get the identifier name without trigraphs or embedded newlines. Note
990 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
991 // when skipping.
992 // TODO: could do this with zero copies in the no-clean case by using
993 // strncmp below.
994 char Directive[20];
995 unsigned IdLen;
996 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
997 IdLen = Tok.getLength();
998 memcpy(Directive, RawCharData, IdLen);
999 Directive[IdLen] = 0;
1000 } else {
1001 std::string DirectiveStr = getSpelling(Tok);
1002 IdLen = DirectiveStr.size();
1003 if (IdLen >= 20) {
1004 CurLexer->ParsingPreprocessorDirective = false;
1005 continue;
1006 }
1007 memcpy(Directive, &DirectiveStr[0], IdLen);
1008 Directive[IdLen] = 0;
1009 }
1010
Chris Lattner22eb9722006-06-18 05:43:12 +00001011 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001012 if ((IdLen == 2) || // "if"
1013 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1014 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001015 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1016 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001017 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001018 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001019 /*foundnonskip*/false,
1020 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 }
1022 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001023 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001024 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001025 PPConditionalInfo CondInfo;
1026 CondInfo.WasSkipping = true; // Silence bogus warning.
1027 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1028 assert(!InCond && "Can't be skipping if not in a conditional!");
1029
1030 // If we popped the outermost skipping block, we're done skipping!
1031 if (!CondInfo.WasSkipping)
1032 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001033 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001034 // #else directive in a skipping conditional. If not in some other
1035 // skipping conditional, and if #else hasn't already been seen, enter it
1036 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001037 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001038 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1039
1040 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001041 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001042
1043 // Note that we've seen a #else in this conditional.
1044 CondInfo.FoundElse = true;
1045
1046 // If the conditional is at the top level, and the #if block wasn't
1047 // entered, enter the #else block now.
1048 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1049 CondInfo.FoundNonSkip = true;
1050 break;
1051 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001052 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001053 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1054
1055 bool ShouldEnter;
1056 // If this is in a skipping block or if we're already handled this #if
1057 // block, don't bother parsing the condition.
1058 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001059 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001060 ShouldEnter = false;
1061 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 // Restore the value of SkippingContents so that identifiers are
1063 // looked up, etc, inside the #elif expression.
1064 assert(SkippingContents && "We have to be skipping here!");
1065 SkippingContents = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001066 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001067 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001068 SkippingContents = true;
1069 }
1070
1071 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001072 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001073
1074 // If this condition is true, enter it!
1075 if (ShouldEnter) {
1076 CondInfo.FoundNonSkip = true;
1077 break;
1078 }
1079 }
1080 }
1081
1082 CurLexer->ParsingPreprocessorDirective = false;
1083 }
1084
1085 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1086 // of the file, just stop skipping and return to lexing whatever came after
1087 // the #if block.
1088 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001089}
1090
1091//===----------------------------------------------------------------------===//
1092// Preprocessor Directive Handling.
1093//===----------------------------------------------------------------------===//
1094
1095/// HandleDirective - This callback is invoked when the lexer sees a # token
1096/// at the start of a line. This consumes the directive, modifies the
1097/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1098/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001099void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001100 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001101
1102 // We just parsed a # character at the start of a line, so we're in directive
1103 // mode. Tell the lexer this so any newlines we see will be converted into an
1104 // EOM token (this terminates the macro).
1105 CurLexer->ParsingPreprocessorDirective = true;
1106
1107 ++NumDirectives;
1108
Chris Lattner371ac8a2006-07-04 07:11:10 +00001109 // We are about to read a token. For the multiple-include optimization FA to
1110 // work, we have to remember if we had read any tokens *before* this
1111 // pp-directive.
1112 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1113
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001115 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001116
1117 switch (Result.getKind()) {
1118 default: break;
1119 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001120 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001121
1122#if 0
1123 case tok::numeric_constant:
1124 // FIXME: implement # 7 line numbers!
1125 break;
1126#endif
1127 case tok::kw_else:
1128 return HandleElseDirective(Result);
1129 case tok::kw_if:
Chris Lattnera8654ca2006-07-04 17:42:08 +00001130 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001132 // Get the identifier name without trigraphs or embedded newlines.
1133 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001134 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001135 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001136 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001137 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnera8654ca2006-07-04 17:42:08 +00001138 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001139 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001140 return HandleElifDirective(Result);
Chris Lattner01d66cc2006-07-03 22:16:27 +00001141 if (Directive[0] == 's' && !strcmp(Directive, "sccs"))
1142 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001143 break;
1144 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001145 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001147 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001148 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
Chris Lattner40931922006-06-22 06:14:04 +00001149 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001150 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001151 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001153 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001154 return HandleIdentSCCSDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001155 break;
1156 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001157 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001158 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001159 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner371ac8a2006-07-04 07:11:10 +00001160 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
Chris Lattner40931922006-06-22 06:14:04 +00001161 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001162 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001163 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001164 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001165 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1166 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001167 break;
1168 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001169 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1170 return HandleIncludeDirective(Result); // Handle #include.
1171 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001172 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001173 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001174 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001175 break;
1176 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001177 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001178 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 }
1180 break;
1181 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001182 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1183 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001184 break;
1185 }
1186 break;
1187 }
1188
1189 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001190 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001191
1192 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001193 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001194
1195 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001196}
1197
Chris Lattner01d66cc2006-07-03 22:16:27 +00001198void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 bool isWarning) {
1200 // Read the rest of the line raw. We do this because we don't want macros
1201 // to be expanded and we don't require that the tokens be valid preprocessing
1202 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1203 // collapse multiple consequtive white space between tokens, but this isn't
1204 // specified by the standard.
1205 std::string Message = CurLexer->ReadToEndOfLine();
1206
1207 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001208 return Diag(Tok, DiagID, Message);
1209}
1210
1211/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1212///
1213void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001214 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001215 Diag(Tok, diag::ext_pp_ident_directive);
1216
Chris Lattner371ac8a2006-07-04 07:11:10 +00001217 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001218 LexerToken StrTok;
1219 Lex(StrTok);
1220
1221 // If the token kind isn't a string, it's a malformed directive.
1222 if (StrTok.getKind() != tok::string_literal)
1223 return Diag(StrTok, diag::err_pp_malformed_ident);
1224
1225 // Verify that there is nothing after the string, other than EOM.
1226 CheckEndOfDirective("#ident");
1227
1228 if (IdentHandler)
1229 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001230}
1231
Chris Lattnerb8761832006-06-24 21:31:03 +00001232//===----------------------------------------------------------------------===//
1233// Preprocessor Include Directive Handling.
1234//===----------------------------------------------------------------------===//
1235
Chris Lattner22eb9722006-06-18 05:43:12 +00001236/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1237/// file to be included from the lexer, then include it! This is a common
1238/// routine with functionality shared between #include, #include_next and
1239/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001240void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001241 const DirectoryLookup *LookupFrom,
1242 bool isImport) {
1243 ++NumIncluded;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001244
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001246 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001247
1248 // If the token kind is EOM, the error has already been diagnosed.
1249 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001250 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001251
1252 // Verify that there is nothing after the filename, other than EOM. Use the
1253 // preprocessor to lex this in case lexing the filename entered a macro.
1254 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001255
1256 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001257 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001258 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1259
Chris Lattner269c2322006-06-25 06:23:00 +00001260 // Find out whether the filename is <x> or "x".
1261 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001262
1263 // Remove the quotes.
1264 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1265
Chris Lattner22eb9722006-06-18 05:43:12 +00001266 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001267 const DirectoryLookup *CurDir;
1268 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001269 if (File == 0)
1270 return Diag(FilenameTok, diag::err_pp_file_not_found);
1271
1272 // Get information about this file.
1273 PerFileInfo &FileInfo = getFileInfo(File);
1274
1275 // If this is a #import directive, check that we have not already imported
1276 // this header.
1277 if (isImport) {
1278 // If this has already been imported, don't import it again.
1279 FileInfo.isImport = true;
1280
1281 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001282 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001283 } else {
1284 // Otherwise, if this is a #include of a file that was previously #import'd
1285 // or if this is the second #include of a #pragma once file, ignore it.
1286 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001287 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001288 }
Chris Lattner3665f162006-07-04 07:26:10 +00001289
1290 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1291 // if the macro that guards it is defined, we know the #include has no effect.
1292 if (FileInfo.ControllingMacro && FileInfo.ControllingMacro->getMacroInfo()) {
1293 ++NumMultiIncludeFileOptzn;
1294 return;
1295 }
1296
Chris Lattner22eb9722006-06-18 05:43:12 +00001297
1298 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001299 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001300 if (FileID == 0)
1301 return Diag(FilenameTok, diag::err_pp_file_not_found);
1302
1303 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001304 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001305
1306 // Increment the number of times this file has been included.
1307 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001308}
1309
1310/// HandleIncludeNextDirective - Implements #include_next.
1311///
Chris Lattnercb283342006-06-18 06:48:37 +00001312void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1313 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001314
1315 // #include_next is like #include, except that we start searching after
1316 // the current found directory. If we can't do this, issue a
1317 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001318 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001319 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001320 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001321 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001322 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001323 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001324 } else {
1325 // Start looking up in the next directory.
1326 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 }
1328
1329 return HandleIncludeDirective(IncludeNextTok, Lookup);
1330}
1331
1332/// HandleImportDirective - Implements #import.
1333///
Chris Lattnercb283342006-06-18 06:48:37 +00001334void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1335 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001336
1337 return HandleIncludeDirective(ImportTok, 0, true);
1338}
1339
Chris Lattnerb8761832006-06-24 21:31:03 +00001340//===----------------------------------------------------------------------===//
1341// Preprocessor Macro Directive Handling.
1342//===----------------------------------------------------------------------===//
1343
Chris Lattnercefc7682006-07-08 08:28:12 +00001344/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1345/// definition has just been read. Lex the rest of the arguments and the
1346/// closing ), updating MI with what we learn. Return true if an error occurs
1347/// parsing the arg list.
1348bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1349 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001350 while (1) {
1351 LexUnexpandedToken(Tok);
1352 switch (Tok.getKind()) {
1353 case tok::r_paren:
1354 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001355 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001356 // Otherwise we have #define FOO(A,)
1357 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1358 return true;
1359 case tok::ellipsis: // #define X(... -> C99 varargs
1360 // Warn if use of C99 feature in non-C99 mode.
1361 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1362
1363 // Lex the token after the identifier.
1364 LexUnexpandedToken(Tok);
1365 if (Tok.getKind() != tok::r_paren) {
1366 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1367 return true;
1368 }
1369 MI->setIsC99Varargs();
1370 return false;
1371 case tok::eom: // #define X(
1372 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1373 return true;
1374 default: // #define X(1
1375 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1376 return true;
1377 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001378 IdentifierInfo *II = Tok.getIdentifierInfo();
1379
1380 // If this is already used as an argument, it is used multiple times (e.g.
1381 // #define X(A,A.
1382 if (II->isMacroArg()) { // C99 6.10.3p6
1383 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1384 return true;
1385 }
1386
1387 // Add the argument to the macro info.
1388 MI->addArgument(II);
1389 // Remember it is an argument now.
1390 II->setIsMacroArg(true);
Chris Lattnercefc7682006-07-08 08:28:12 +00001391
1392 // Lex the token after the identifier.
1393 LexUnexpandedToken(Tok);
1394
1395 switch (Tok.getKind()) {
1396 default: // #define X(A B
1397 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1398 return true;
1399 case tok::r_paren: // #define X(A)
1400 return false;
1401 case tok::comma: // #define X(A,
1402 break;
1403 case tok::ellipsis: // #define X(A... -> GCC extension
1404 // Diagnose extension.
1405 Diag(Tok, diag::ext_named_variadic_macro);
1406
1407 // Lex the token after the identifier.
1408 LexUnexpandedToken(Tok);
1409 if (Tok.getKind() != tok::r_paren) {
1410 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1411 return true;
1412 }
1413
1414 MI->setIsGNUVarargs();
1415 return false;
1416 }
1417 }
1418 }
1419}
1420
Chris Lattner22eb9722006-06-18 05:43:12 +00001421/// HandleDefineDirective - Implements #define. This consumes the entire macro
1422/// line then lets the caller lex the next real token.
1423///
Chris Lattnercb283342006-06-18 06:48:37 +00001424void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001426
Chris Lattner22eb9722006-06-18 05:43:12 +00001427 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001428 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001429
1430 // Error reading macro name? If so, diagnostic already issued.
1431 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001432 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001433
Chris Lattner50b497e2006-06-18 16:32:35 +00001434 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001435
1436 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001437 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001438
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001439 // If this is a function-like macro definition, parse the argument list,
1440 // marking each of the identifiers as being used as macro arguments. Also,
1441 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 if (Tok.getKind() == tok::eom) {
1443 // If there is no body to this macro, we have no special handling here.
1444 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001445 // This is a function-like macro definition. Read the argument list.
1446 MI->setIsFunctionLike();
1447 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001448 // Clear the "isMacroArg" flags from all the macro arguments parsed.
1449 MI->SetIdentifierIsMacroArgFlags(false);
1450 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001451 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001452 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001453 if (CurLexer->ParsingPreprocessorDirective)
1454 DiscardUntilEndOfDirective();
1455 return;
1456 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001457
Chris Lattner815a1f92006-07-08 20:48:04 +00001458 // Read the first token after the arg list for down below.
1459 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001460 } else if (!Tok.hasLeadingSpace()) {
1461 // C99 requires whitespace between the macro definition and the body. Emit
1462 // a diagnostic for something like "#define X+".
1463 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001464 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001465 } else {
1466 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1467 // one in some cases!
1468 }
1469 } else {
1470 // This is a normal token with leading space. Clear the leading space
1471 // marker on the first token to get proper expansion.
1472 Tok.ClearFlag(LexerToken::LeadingSpace);
1473 }
1474
1475 // Read the rest of the macro body.
1476 while (Tok.getKind() != tok::eom) {
1477 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001478
1479 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1480 // parameters.
1481 if (Tok.getKind() != tok::hash) {
1482 // Get the next token of the macro.
1483 LexUnexpandedToken(Tok);
1484 continue;
1485 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001486
Chris Lattner815a1f92006-07-08 20:48:04 +00001487 // Get the next token of the macro.
1488 LexUnexpandedToken(Tok);
1489
1490 // Not a macro arg identifier?
1491 if (!Tok.getIdentifierInfo() || !Tok.getIdentifierInfo()->isMacroArg()) {
1492 Diag(Tok, diag::err_pp_stringize_not_parameter);
1493 // Clear the "isMacroArg" flags from all the macro arguments.
1494 MI->SetIdentifierIsMacroArgFlags(false);
1495 delete MI;
1496 return;
1497 }
1498
1499 // Things look ok, add the param name token to the macro.
1500 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001501
Chris Lattner22eb9722006-06-18 05:43:12 +00001502 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001503 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001504 }
Chris Lattnerbff18d52006-07-06 04:49:18 +00001505
1506 unsigned NumTokens = MI->getNumTokens();
1507
1508 // Check that there is no paste (##) operator at the begining or end of the
1509 // replacement list.
1510 if (NumTokens != 0) {
1511 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001512 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001513 // Clear the "isMacroArg" flags from all the macro arguments.
1514 MI->SetIdentifierIsMacroArgFlags(false);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001515 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001516 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001517 }
1518 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001519 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001520 // Clear the "isMacroArg" flags from all the macro arguments.
1521 MI->SetIdentifierIsMacroArgFlags(false);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001522 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001523 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001524 }
1525 }
1526
Chris Lattner13044d92006-07-03 05:16:44 +00001527 // If this is the primary source file, remember that this macro hasn't been
1528 // used yet.
1529 if (isInPrimaryFile())
1530 MI->setIsUsed(false);
1531
Chris Lattner22eb9722006-06-18 05:43:12 +00001532 // Finally, if this identifier already had a macro defined for it, verify that
1533 // the macro bodies are identical and free the old definition.
1534 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001535 if (!OtherMI->isUsed())
1536 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1537
Chris Lattner22eb9722006-06-18 05:43:12 +00001538 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001539 // must be the same. C99 6.10.3.2.
1540 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001541 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1542 MacroNameTok.getIdentifierInfo()->getName());
1543 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1544 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001545 delete OtherMI;
1546 }
1547
1548 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001549
1550 // Clear the "isMacroArg" flags from all the macro arguments.
1551 MI->SetIdentifierIsMacroArgFlags(false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001552}
1553
1554
1555/// HandleUndefDirective - Implements #undef.
1556///
Chris Lattnercb283342006-06-18 06:48:37 +00001557void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001558 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001559
Chris Lattner22eb9722006-06-18 05:43:12 +00001560 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001561 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001562
1563 // Error reading macro name? If so, diagnostic already issued.
1564 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001565 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001566
1567 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001568 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001569
1570 // Okay, we finally have a valid identifier to undef.
1571 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1572
1573 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001574 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001575
Chris Lattner13044d92006-07-03 05:16:44 +00001576 if (!MI->isUsed())
1577 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001578
1579 // Free macro definition.
1580 delete MI;
1581 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001582}
1583
1584
Chris Lattnerb8761832006-06-24 21:31:03 +00001585//===----------------------------------------------------------------------===//
1586// Preprocessor Conditional Directive Handling.
1587//===----------------------------------------------------------------------===//
1588
Chris Lattner22eb9722006-06-18 05:43:12 +00001589/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001590/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1591/// if any tokens have been returned or pp-directives activated before this
1592/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001593///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001594void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1595 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001596 ++NumIf;
1597 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001598
Chris Lattner22eb9722006-06-18 05:43:12 +00001599 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001600 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001601
1602 // Error reading macro name? If so, diagnostic already issued.
1603 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001604 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001605
1606 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001607 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1608
1609 // If the start of a top-level #ifdef, inform MIOpt.
1610 if (!ReadAnyTokensBeforeDirective &&
1611 CurLexer->getConditionalStackDepth() == 0) {
1612 assert(isIfndef && "#ifdef shouldn't reach here");
1613 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1614 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001615
Chris Lattnera78a97e2006-07-03 05:42:18 +00001616 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1617
1618 // If there is a macro, mark it used.
1619 if (MI) MI->setIsUsed(true);
1620
Chris Lattner22eb9722006-06-18 05:43:12 +00001621 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001622 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001623 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001624 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001625 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001626 } else {
1627 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001628 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001629 /*Foundnonskip*/false,
1630 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001631 }
1632}
1633
1634/// HandleIfDirective - Implements the #if directive.
1635///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001636void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1637 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001638 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001639
Chris Lattner371ac8a2006-07-04 07:11:10 +00001640 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001641 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001642 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001643
1644 // Should we include the stuff contained by this directive?
1645 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001646 // If this condition is equivalent to #ifndef X, and if this is the first
1647 // directive seen, handle it for the multiple-include optimization.
1648 if (!ReadAnyTokensBeforeDirective &&
1649 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1650 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1651
Chris Lattner22eb9722006-06-18 05:43:12 +00001652 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001653 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001654 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001655 } else {
1656 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001657 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001658 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001659 }
1660}
1661
1662/// HandleEndifDirective - Implements the #endif directive.
1663///
Chris Lattnercb283342006-06-18 06:48:37 +00001664void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001665 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001666
Chris Lattner22eb9722006-06-18 05:43:12 +00001667 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001668 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001669
1670 PPConditionalInfo CondInfo;
1671 if (CurLexer->popConditionalLevel(CondInfo)) {
1672 // No conditionals on the stack: this is an #endif without an #if.
1673 return Diag(EndifToken, diag::err_pp_endif_without_if);
1674 }
1675
Chris Lattner371ac8a2006-07-04 07:11:10 +00001676 // If this the end of a top-level #endif, inform MIOpt.
1677 if (CurLexer->getConditionalStackDepth() == 0)
1678 CurLexer->MIOpt.ExitTopLevelConditional();
1679
Chris Lattner22eb9722006-06-18 05:43:12 +00001680 assert(!CondInfo.WasSkipping && !isSkipping() &&
1681 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001682}
1683
1684
Chris Lattnercb283342006-06-18 06:48:37 +00001685void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001686 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001687
Chris Lattner22eb9722006-06-18 05:43:12 +00001688 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001689 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001690
1691 PPConditionalInfo CI;
1692 if (CurLexer->popConditionalLevel(CI))
1693 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001694
1695 // If this is a top-level #else, inform the MIOpt.
1696 if (CurLexer->getConditionalStackDepth() == 0)
1697 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001698
1699 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001700 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001701
1702 // Finally, skip the rest of the contents of this block and return the first
1703 // token after it.
1704 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1705 /*FoundElse*/true);
1706}
1707
Chris Lattnercb283342006-06-18 06:48:37 +00001708void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001709 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001710
Chris Lattner22eb9722006-06-18 05:43:12 +00001711 // #elif directive in a non-skipping conditional... start skipping.
1712 // We don't care what the condition is, because we will always skip it (since
1713 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001714 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001715
1716 PPConditionalInfo CI;
1717 if (CurLexer->popConditionalLevel(CI))
1718 return Diag(ElifToken, diag::pp_err_elif_without_if);
1719
Chris Lattner371ac8a2006-07-04 07:11:10 +00001720 // If this is a top-level #elif, inform the MIOpt.
1721 if (CurLexer->getConditionalStackDepth() == 0)
1722 CurLexer->MIOpt.FoundTopLevelElse();
1723
Chris Lattner22eb9722006-06-18 05:43:12 +00001724 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001725 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001726
1727 // Finally, skip the rest of the contents of this block and return the first
1728 // token after it.
1729 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1730 /*FoundElse*/CI.FoundElse);
1731}
Chris Lattnerb8761832006-06-24 21:31:03 +00001732