blob: a8890f0c92fe65f1d510cfb77f3e6841ccca295d [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)
355 ++NumLexersFound;
356
357 /// If there are any stacked lexers, we're in a #include.
358 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
359 if (IncludeMacroStack[i].TheLexer) {
360 if (!IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
361 if (++NumLexersFound > 1)
362 return false;
363 }
364 return NumLexersFound < 2;
365}
366
367/// getCurrentLexer - Return the current file lexer being lexed from. Note
368/// that this ignores any potentially active macro expansions and _Pragma
369/// expansions going on at the time.
370Lexer *Preprocessor::getCurrentFileLexer() const {
371 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
372
373 // Look for a stacked lexer.
374 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
375 Lexer *L = IncludeMacroStack[i].TheLexer;
376 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
377 return L;
378 }
379 return 0;
380}
381
382
Chris Lattner22eb9722006-06-18 05:43:12 +0000383/// EnterSourceFile - Add a source file to the top of the include stack and
384/// start lexing tokens from it instead of the current buffer. Return true
385/// on failure.
386void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattnerc8997182006-06-22 05:52:16 +0000387 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000388 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000389 ++NumEnteredSourceFiles;
390
Chris Lattner69772b02006-07-02 20:34:39 +0000391 if (MaxIncludeStackDepth < IncludeMacroStack.size())
392 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000393
Chris Lattner22eb9722006-06-18 05:43:12 +0000394 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000395 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
396 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 Lattner0b8cfc22006-06-28 06:49:17 +0000493
494 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
495 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000496 return ExpandBuiltinMacro(Identifier);
497
498 // If we started lexing a macro, enter the macro expansion body.
499 // FIXME: Read/Validate the argument list here!
500
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000501
502 // If this macro expands to no tokens, don't bother to push it onto the
503 // expansion stack, only to take it right back off.
504 if (MI->getNumTokens() == 0) {
505 // Ignore this macro use, just return the next token in the current
506 // buffer.
507 bool HadLeadingSpace = Identifier.hasLeadingSpace();
508 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
509
510 Lex(Identifier);
511
512 // If the identifier isn't on some OTHER line, inherit the leading
513 // whitespace/first-on-a-line property of this token. This handles
514 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
515 // empty.
516 if (!Identifier.isAtStartOfLine()) {
517 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
518 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
519 }
520 ++NumFastMacroExpanded;
521 return;
522
523 } else if (MI->getNumTokens() == 1 &&
524 // Don't handle identifiers if they need recursive expansion.
525 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
526 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
527 // FIXME: Function-style macros only if no arguments?
528
529 // Otherwise, if this macro expands into a single trivially-expanded
530 // token: expand it now. This handles common cases like
531 // "#define VAL 42".
532
533 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
534 // identifier to the expanded token.
535 bool isAtStartOfLine = Identifier.isAtStartOfLine();
536 bool hasLeadingSpace = Identifier.hasLeadingSpace();
537
538 // Remember where the token is instantiated.
539 SourceLocation InstantiateLoc = Identifier.getLocation();
540
541 // Replace the result token.
542 Identifier = MI->getReplacementToken(0);
543
544 // Restore the StartOfLine/LeadingSpace markers.
545 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
546 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
547
548 // Update the tokens location to include both its logical and physical
549 // locations.
550 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000551 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000552 Identifier.SetLocation(Loc);
553
554 // Since this is not an identifier token, it can't be macro expanded, so
555 // we're done.
556 ++NumFastMacroExpanded;
557 return;
558 }
559
560 // Start expanding the macro (FIXME, pass arguments).
561 EnterMacro(Identifier);
562
563 // Now that the macro is at the top of the include stack, ask the
564 // preprocessor to read the next token from it.
565 return Lex(Identifier);
566}
567
Chris Lattnerc673f902006-06-30 06:10:41 +0000568/// ComputeDATE_TIME - Compute the current time, enter it into the specified
569/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
570/// the identifier tokens inserted.
571static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
572 ScratchBuffer *ScratchBuf) {
573 time_t TT = time(0);
574 struct tm *TM = localtime(&TT);
575
576 static const char * const Months[] = {
577 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
578 };
579
580 char TmpBuffer[100];
581 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
582 TM->tm_year+1900);
583 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
584
585 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
586 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
587}
588
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000589/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
590/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000591void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000592 // Figure out which token this is.
593 IdentifierTokenInfo *ITI = Tok.getIdentifierInfo();
594 assert(ITI && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000595
596 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
597 // lex the token after it.
598 if (ITI == Ident_Pragma)
599 return Handle_Pragma(Tok);
600
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000601 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000602
603 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000604 Tok.SetIdentifierInfo(0);
605 Tok.ClearFlag(LexerToken::NeedsCleaning);
606
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000607 if (ITI == Ident__LINE__) {
608 // __LINE__ expands to a simple numeric value.
609 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
610 unsigned Length = strlen(TmpBuffer);
611 Tok.SetKind(tok::numeric_constant);
612 Tok.SetLength(Length);
613 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000614 } else if (ITI == Ident__FILE__ || ITI == Ident__BASE_FILE__) {
615 SourceLocation Loc = Tok.getLocation();
616 if (ITI == Ident__BASE_FILE__) {
617 Diag(Tok, diag::ext_pp_base_file);
618 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
619 while (NextLoc.getFileID() != 0) {
620 Loc = NextLoc;
621 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
622 }
623 }
624
625 // FIXME: Escape this filename correctly.
626 std::string FN = '"' + SourceMgr.getSourceName(Loc) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000627 Tok.SetKind(tok::string_literal);
628 Tok.SetLength(FN.size());
629 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000630 } else if (ITI == Ident__DATE__) {
631 if (!DATELoc.isValid())
632 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
633 Tok.SetKind(tok::string_literal);
634 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
635 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000636 } else if (ITI == Ident__TIME__) {
637 if (!TIMELoc.isValid())
638 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
639 Tok.SetKind(tok::string_literal);
640 Tok.SetLength(strlen("\"hh:mm:ss\""));
641 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000642 } else if (ITI == Ident__INCLUDE_LEVEL__) {
643 Diag(Tok, diag::ext_pp_include_level);
644
645 // Compute the include depth of this token.
646 unsigned Depth = 0;
647 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
648 for (; Loc.getFileID() != 0; ++Depth)
649 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
650
651 // __INCLUDE_LEVEL__ expands to a simple numeric value.
652 sprintf(TmpBuffer, "%u", Depth);
653 unsigned Length = strlen(TmpBuffer);
654 Tok.SetKind(tok::numeric_constant);
655 Tok.SetLength(Length);
656 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattner847e0e42006-07-01 23:49:16 +0000657 } else if (ITI == Ident__TIMESTAMP__) {
658 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
659 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
660 Diag(Tok, diag::ext_pp_timestamp);
661
662 // Get the file that we are lexing out of. If we're currently lexing from
663 // a macro, dig into the include stack.
664 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000665 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000666
667 if (TheLexer)
668 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
669
670 // If this file is older than the file it depends on, emit a diagnostic.
671 const char *Result;
672 if (CurFile) {
673 time_t TT = CurFile->getModificationTime();
674 struct tm *TM = localtime(&TT);
675 Result = asctime(TM);
676 } else {
677 Result = "??? ??? ?? ??:??:?? ????\n";
678 }
679 TmpBuffer[0] = '"';
680 strcpy(TmpBuffer+1, Result);
681 unsigned Len = strlen(TmpBuffer);
682 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
683 Tok.SetKind(tok::string_literal);
684 Tok.SetLength(Len);
685 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000686 } else {
687 assert(0 && "Unknown identifier!");
688 }
689}
Chris Lattner677757a2006-06-28 05:26:32 +0000690
691//===----------------------------------------------------------------------===//
692// Lexer Event Handling.
693//===----------------------------------------------------------------------===//
694
695/// HandleIdentifier - This callback is invoked when the lexer reads an
696/// identifier. This callback looks up the identifier in the map and/or
697/// potentially macro expands it or turns it into a named token (like 'for').
698void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
699 if (Identifier.getIdentifierInfo() == 0) {
700 // If we are skipping tokens (because we are in a #if 0 block), there will
701 // be no identifier info, just return the token.
702 assert(isSkipping() && "Token isn't an identifier?");
703 return;
704 }
705 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
706
707 // If this identifier was poisoned, and if it was not produced from a macro
708 // expansion, emit an error.
709 if (ITI.isPoisoned() && CurLexer)
710 Diag(Identifier, diag::err_pp_used_poisoned_id);
711
712 if (MacroInfo *MI = ITI.getMacroInfo())
713 if (MI->isEnabled() && !DisableMacroExpansion)
714 return HandleMacroExpandedIdentifier(Identifier, MI);
715
716 // Change the kind of this identifier to the appropriate token kind, e.g.
717 // turning "for" into a keyword.
718 Identifier.SetKind(ITI.getTokenID());
719
720 // If this is an extension token, diagnose its use.
721 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
722}
723
Chris Lattner22eb9722006-06-18 05:43:12 +0000724/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
725/// the current file. This either returns the EOF token or pops a level off
726/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000727void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000728 assert(!CurMacroExpander &&
729 "Ending a file when currently in a macro!");
730
731 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
732 // this is an error condition. Just return the EOF token up to
733 // SkipExcludedConditionalBlock. The Lexer will have already have issued
734 // errors for the unterminated #if's on the conditional stack.
735 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000736 Result.StartToken();
737 CurLexer->BufferPtr = CurLexer->BufferEnd;
738 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000739 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000740 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000741 }
742
743 // If this is a #include'd file, pop it off the include stack and continue
744 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000745 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000746 // We're done with the #included file.
747 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000748 CurLexer = IncludeMacroStack.back().TheLexer;
749 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
750 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
751 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000752
753 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000754 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000755 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
756
757 // Get the file entry for the current file.
758 if (const FileEntry *FE =
759 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
760 FileType = getFileInfo(FE).DirInfo;
761
Chris Lattner0c885f52006-06-21 06:50:18 +0000762 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000763 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000764 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000765
Chris Lattner22eb9722006-06-18 05:43:12 +0000766 return Lex(Result);
767 }
768
Chris Lattnerd01e2912006-06-18 16:22:51 +0000769 Result.StartToken();
770 CurLexer->BufferPtr = CurLexer->BufferEnd;
771 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000772 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000773
774 // We're done with the #included file.
775 delete CurLexer;
776 CurLexer = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000777}
778
779/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000780/// the current macro line.
781void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000782 assert(CurMacroExpander && !CurLexer &&
783 "Ending a macro when currently in a #include file!");
784
785 // Mark macro not ignored now that it is no longer being expanded.
786 CurMacroExpander->getMacro().EnableMacro();
787 delete CurMacroExpander;
788
Chris Lattner69772b02006-07-02 20:34:39 +0000789 // Handle this like a #include file being popped off the stack.
790 CurMacroExpander = 0;
791 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000792}
793
794
795//===----------------------------------------------------------------------===//
796// Utility Methods for Preprocessor Directive Handling.
797//===----------------------------------------------------------------------===//
798
799/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
800/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000801void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000802 LexerToken Tmp;
803 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000804 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000805 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000806}
807
808/// ReadMacroName - Lex and validate a macro name, which occurs after a
809/// #define or #undef. This sets the token kind to eom and discards the rest
810/// of the macro line if the macro name is invalid.
Chris Lattnercb283342006-06-18 06:48:37 +0000811void Preprocessor::ReadMacroName(LexerToken &MacroNameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000812 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000813 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000814
815 // Missing macro name?
816 if (MacroNameTok.getKind() == tok::eom)
817 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
818
819 if (MacroNameTok.getIdentifierInfo() == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000820 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000821 // Fall through on error.
822 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000823 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +0000824
825 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +0000826 // FIXME: Error if defining "defined" in C99 6.10.8.4.
Chris Lattner22eb9722006-06-18 05:43:12 +0000827 } else {
828 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000829 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000830 }
831
832
833 // Invalid macro name, read and discard the rest of the line. Then set the
834 // token kind to tok::eom.
835 MacroNameTok.SetKind(tok::eom);
836 return DiscardUntilEndOfDirective();
837}
838
839/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
840/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000841void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000842 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000843 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000844 // There should be no tokens after the directive, but we allow them as an
845 // extension.
846 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000847 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
848 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000849 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000850}
851
852
853
854/// SkipExcludedConditionalBlock - We just read a #if or related directive and
855/// decided that the subsequent tokens are in the #if'd out portion of the
856/// file. Lex the rest of the file, until we see an #endif. If
857/// FoundNonSkipPortion is true, then we have already emitted code for part of
858/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
859/// is true, then #else directives are ok, if not, then we have already seen one
860/// so a #else directive is a duplicate. When this returns, the caller can lex
861/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000862void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000863 bool FoundNonSkipPortion,
864 bool FoundElse) {
865 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000866 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000867 "Lexing a macro, not a file?");
868
869 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
870 FoundNonSkipPortion, FoundElse);
871
872 // Know that we are going to be skipping tokens. Set this flag to indicate
873 // this, which has a couple of effects:
874 // 1. If EOF of the current lexer is found, the include stack isn't popped.
875 // 2. Identifier information is not looked up for identifier tokens. As an
876 // effect of this, implicit macro expansion is naturally disabled.
877 // 3. "#" tokens at the start of a line are treated as normal tokens, not
878 // implicitly transformed by the lexer.
879 // 4. All notes, warnings, and extension messages are disabled.
880 //
881 SkippingContents = true;
882 LexerToken Tok;
883 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000884 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000885
886 // If this is the end of the buffer, we have an error. The lexer will have
887 // already handled this error condition, so just return and let the caller
888 // lex after this #include.
889 if (Tok.getKind() == tok::eof) break;
890
891 // If this token is not a preprocessor directive, just skip it.
892 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
893 continue;
894
895 // We just parsed a # character at the start of a line, so we're in
896 // directive mode. Tell the lexer this so any newlines we see will be
897 // converted into an EOM token (this terminates the macro).
898 CurLexer->ParsingPreprocessorDirective = true;
899
900 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000901 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000902
903 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
904 // something bogus), skip it.
905 if (Tok.getKind() != tok::identifier) {
906 CurLexer->ParsingPreprocessorDirective = false;
907 continue;
908 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000909
Chris Lattner22eb9722006-06-18 05:43:12 +0000910 // If the first letter isn't i or e, it isn't intesting to us. We know that
911 // this is safe in the face of spelling differences, because there is no way
912 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000913 // allows us to avoid looking up the identifier info for #define/#undef and
914 // other common directives.
915 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
916 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000917 if (FirstChar >= 'a' && FirstChar <= 'z' &&
918 FirstChar != 'i' && FirstChar != 'e') {
919 CurLexer->ParsingPreprocessorDirective = false;
920 continue;
921 }
922
Chris Lattnere60165f2006-06-22 06:36:29 +0000923 // Get the identifier name without trigraphs or embedded newlines. Note
924 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
925 // when skipping.
926 // TODO: could do this with zero copies in the no-clean case by using
927 // strncmp below.
928 char Directive[20];
929 unsigned IdLen;
930 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
931 IdLen = Tok.getLength();
932 memcpy(Directive, RawCharData, IdLen);
933 Directive[IdLen] = 0;
934 } else {
935 std::string DirectiveStr = getSpelling(Tok);
936 IdLen = DirectiveStr.size();
937 if (IdLen >= 20) {
938 CurLexer->ParsingPreprocessorDirective = false;
939 continue;
940 }
941 memcpy(Directive, &DirectiveStr[0], IdLen);
942 Directive[IdLen] = 0;
943 }
944
Chris Lattner22eb9722006-06-18 05:43:12 +0000945 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000946 if ((IdLen == 2) || // "if"
947 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
948 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000949 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
950 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000951 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000952 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000953 /*foundnonskip*/false,
954 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000955 }
956 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000957 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000958 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000959 PPConditionalInfo CondInfo;
960 CondInfo.WasSkipping = true; // Silence bogus warning.
961 bool InCond = CurLexer->popConditionalLevel(CondInfo);
962 assert(!InCond && "Can't be skipping if not in a conditional!");
963
964 // If we popped the outermost skipping block, we're done skipping!
965 if (!CondInfo.WasSkipping)
966 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000967 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000968 // #else directive in a skipping conditional. If not in some other
969 // skipping conditional, and if #else hasn't already been seen, enter it
970 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000971 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000972 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
973
974 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000975 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000976
977 // Note that we've seen a #else in this conditional.
978 CondInfo.FoundElse = true;
979
980 // If the conditional is at the top level, and the #if block wasn't
981 // entered, enter the #else block now.
982 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
983 CondInfo.FoundNonSkip = true;
984 break;
985 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000986 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +0000987 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
988
989 bool ShouldEnter;
990 // If this is in a skipping block or if we're already handled this #if
991 // block, don't bother parsing the condition.
992 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +0000993 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000994 ShouldEnter = false;
995 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +0000996 // Restore the value of SkippingContents so that identifiers are
997 // looked up, etc, inside the #elif expression.
998 assert(SkippingContents && "We have to be skipping here!");
999 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001000 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001001 SkippingContents = true;
1002 }
1003
1004 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001005 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001006
1007 // If this condition is true, enter it!
1008 if (ShouldEnter) {
1009 CondInfo.FoundNonSkip = true;
1010 break;
1011 }
1012 }
1013 }
1014
1015 CurLexer->ParsingPreprocessorDirective = false;
1016 }
1017
1018 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1019 // of the file, just stop skipping and return to lexing whatever came after
1020 // the #if block.
1021 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001022}
1023
1024//===----------------------------------------------------------------------===//
1025// Preprocessor Directive Handling.
1026//===----------------------------------------------------------------------===//
1027
1028/// HandleDirective - This callback is invoked when the lexer sees a # token
1029/// at the start of a line. This consumes the directive, modifies the
1030/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1031/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001032void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001033 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001034
1035 // We just parsed a # character at the start of a line, so we're in directive
1036 // mode. Tell the lexer this so any newlines we see will be converted into an
1037 // EOM token (this terminates the macro).
1038 CurLexer->ParsingPreprocessorDirective = true;
1039
1040 ++NumDirectives;
1041
1042 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001043 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001044
1045 switch (Result.getKind()) {
1046 default: break;
1047 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001048 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001049
1050#if 0
1051 case tok::numeric_constant:
1052 // FIXME: implement # 7 line numbers!
1053 break;
1054#endif
1055 case tok::kw_else:
1056 return HandleElseDirective(Result);
1057 case tok::kw_if:
1058 return HandleIfDirective(Result);
1059 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001060 // Get the identifier name without trigraphs or embedded newlines.
1061 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001063 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001065 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001066 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001067 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001068 return HandleElifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001069 if (Directive[0] == 's' && !strcmp(Directive, "sccs")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001070 isExtension = true; // FIXME: implement #sccs
Chris Lattner22eb9722006-06-18 05:43:12 +00001071 // SCCS is the same as #ident.
1072 }
1073 break;
1074 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001075 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001076 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001077 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001078 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001079 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001081 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001082 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001083 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001084 isExtension = true; // FIXME: implement #ident
Chris Lattner22eb9722006-06-18 05:43:12 +00001085 break;
1086 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001087 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001088 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001089 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001090 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +00001091 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001092 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001093 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001094 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001095 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1096 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 break;
1098 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001099 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1100 return HandleIncludeDirective(Result); // Handle #include.
1101 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001102 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001103 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001104 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 break;
1106 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001107 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001108 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001109 }
1110 break;
1111 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001112 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1113 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 break;
1115 }
1116 break;
1117 }
1118
1119 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001120 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001121
1122 // Read the rest of the PP line.
1123 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001124 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001125 } while (Result.getKind() != tok::eom);
1126
1127 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001128}
1129
Chris Lattnercb283342006-06-18 06:48:37 +00001130void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 bool isWarning) {
1132 // Read the rest of the line raw. We do this because we don't want macros
1133 // to be expanded and we don't require that the tokens be valid preprocessing
1134 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1135 // collapse multiple consequtive white space between tokens, but this isn't
1136 // specified by the standard.
1137 std::string Message = CurLexer->ReadToEndOfLine();
1138
1139 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1140 return Diag(Result, DiagID, Message);
1141}
1142
Chris Lattnerb8761832006-06-24 21:31:03 +00001143//===----------------------------------------------------------------------===//
1144// Preprocessor Include Directive Handling.
1145//===----------------------------------------------------------------------===//
1146
Chris Lattner22eb9722006-06-18 05:43:12 +00001147/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1148/// file to be included from the lexer, then include it! This is a common
1149/// routine with functionality shared between #include, #include_next and
1150/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001151void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 const DirectoryLookup *LookupFrom,
1153 bool isImport) {
1154 ++NumIncluded;
1155 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001156 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001157
1158 // If the token kind is EOM, the error has already been diagnosed.
1159 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001160 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001161
1162 // Verify that there is nothing after the filename, other than EOM. Use the
1163 // preprocessor to lex this in case lexing the filename entered a macro.
1164 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001165
1166 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001167 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001168 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1169
Chris Lattner269c2322006-06-25 06:23:00 +00001170 // Find out whether the filename is <x> or "x".
1171 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001172
1173 // Remove the quotes.
1174 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1175
Chris Lattner22eb9722006-06-18 05:43:12 +00001176 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001177 const DirectoryLookup *CurDir;
1178 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 if (File == 0)
1180 return Diag(FilenameTok, diag::err_pp_file_not_found);
1181
1182 // Get information about this file.
1183 PerFileInfo &FileInfo = getFileInfo(File);
1184
1185 // If this is a #import directive, check that we have not already imported
1186 // this header.
1187 if (isImport) {
1188 // If this has already been imported, don't import it again.
1189 FileInfo.isImport = true;
1190
1191 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001192 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001193 } else {
1194 // Otherwise, if this is a #include of a file that was previously #import'd
1195 // or if this is the second #include of a #pragma once file, ignore it.
1196 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001197 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001198 }
1199
1200 // Look up the file, create a File ID for it.
1201 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +00001202 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001203 if (FileID == 0)
1204 return Diag(FilenameTok, diag::err_pp_file_not_found);
1205
1206 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001207 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001208
1209 // Increment the number of times this file has been included.
1210 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001211}
1212
1213/// HandleIncludeNextDirective - Implements #include_next.
1214///
Chris Lattnercb283342006-06-18 06:48:37 +00001215void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1216 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001217
1218 // #include_next is like #include, except that we start searching after
1219 // the current found directory. If we can't do this, issue a
1220 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001221 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001222 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001223 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001224 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001225 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001226 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001227 } else {
1228 // Start looking up in the next directory.
1229 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 }
1231
1232 return HandleIncludeDirective(IncludeNextTok, Lookup);
1233}
1234
1235/// HandleImportDirective - Implements #import.
1236///
Chris Lattnercb283342006-06-18 06:48:37 +00001237void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1238 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001239
1240 return HandleIncludeDirective(ImportTok, 0, true);
1241}
1242
Chris Lattnerb8761832006-06-24 21:31:03 +00001243//===----------------------------------------------------------------------===//
1244// Preprocessor Macro Directive Handling.
1245//===----------------------------------------------------------------------===//
1246
Chris Lattner22eb9722006-06-18 05:43:12 +00001247/// HandleDefineDirective - Implements #define. This consumes the entire macro
1248/// line then lets the caller lex the next real token.
1249///
Chris Lattnercb283342006-06-18 06:48:37 +00001250void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001251 ++NumDefined;
1252 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001253 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001254
1255 // Error reading macro name? If so, diagnostic already issued.
1256 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001257 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001258
Chris Lattner50b497e2006-06-18 16:32:35 +00001259 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001260
1261 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001262 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001263
1264 if (Tok.getKind() == tok::eom) {
1265 // If there is no body to this macro, we have no special handling here.
1266 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1267 // This is a function-like macro definition.
1268 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001269 return DiscardUntilEndOfDirective();
1270
1271 } else if (!Tok.hasLeadingSpace()) {
1272 // C99 requires whitespace between the macro definition and the body. Emit
1273 // a diagnostic for something like "#define X+".
1274 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001275 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 } else {
1277 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1278 // one in some cases!
1279 }
1280 } else {
1281 // This is a normal token with leading space. Clear the leading space
1282 // marker on the first token to get proper expansion.
1283 Tok.ClearFlag(LexerToken::LeadingSpace);
1284 }
1285
1286 // Read the rest of the macro body.
1287 while (Tok.getKind() != tok::eom) {
1288 MI->AddTokenToBody(Tok);
1289
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001290 // FIXME: Read macro body. See create_iso_definition.
Chris Lattner22eb9722006-06-18 05:43:12 +00001291
1292 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001293 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001294 }
1295
1296 // Finally, if this identifier already had a macro defined for it, verify that
1297 // the macro bodies are identical and free the old definition.
1298 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001299 if (OtherMI->isBuiltinMacro()) // C99 6.10.8.4
Chris Lattner677757a2006-06-28 05:26:32 +00001300 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1301
1302
Chris Lattner22eb9722006-06-18 05:43:12 +00001303 // FIXME: Verify the definition is the same.
1304 // Macros must be identical. This means all tokes and whitespace separation
1305 // must be the same.
1306 delete OtherMI;
1307 }
1308
1309 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001310}
1311
1312
1313/// HandleUndefDirective - Implements #undef.
1314///
Chris Lattnercb283342006-06-18 06:48:37 +00001315void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001316 ++NumUndefined;
1317 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001318 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001319
1320 // Error reading macro name? If so, diagnostic already issued.
1321 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001322 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001323
1324 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001325 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001326
1327 // Okay, we finally have a valid identifier to undef.
1328 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1329
1330 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001331 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001332
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001333 if (MI->isBuiltinMacro()) // C99 6.10.8.4
Chris Lattner677757a2006-06-28 05:26:32 +00001334 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001335
1336#if 0 // FIXME: implement warn_unused_macros.
1337 if (CPP_OPTION (pfile, warn_unused_macros))
1338 _cpp_warn_if_unused_macro (pfile, node, NULL);
1339#endif
1340
1341 // Free macro definition.
1342 delete MI;
1343 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001344}
1345
1346
Chris Lattnerb8761832006-06-24 21:31:03 +00001347//===----------------------------------------------------------------------===//
1348// Preprocessor Conditional Directive Handling.
1349//===----------------------------------------------------------------------===//
1350
Chris Lattner22eb9722006-06-18 05:43:12 +00001351/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1352/// true when this is a #ifndef directive.
1353///
Chris Lattnercb283342006-06-18 06:48:37 +00001354void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 ++NumIf;
1356 LexerToken DirectiveTok = Result;
1357
1358 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001359 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001360
1361 // Error reading macro name? If so, diagnostic already issued.
1362 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001363 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001364
1365 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001366 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001367
1368 // Should we include the stuff contained by this directive?
1369 if (!MacroNameTok.getIdentifierInfo()->getMacroInfo() == isIfndef) {
1370 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001371 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001372 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 } else {
1374 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001375 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001376 /*Foundnonskip*/false,
1377 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001378 }
1379}
1380
1381/// HandleIfDirective - Implements the #if directive.
1382///
Chris Lattnercb283342006-06-18 06:48:37 +00001383void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001384 ++NumIf;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001385 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001386
1387 // Should we include the stuff contained by this directive?
1388 if (ConditionalTrue) {
1389 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001390 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001391 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001392 } else {
1393 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001394 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001395 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 }
1397}
1398
1399/// HandleEndifDirective - Implements the #endif directive.
1400///
Chris Lattnercb283342006-06-18 06:48:37 +00001401void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 ++NumEndif;
1403 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001404 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001405
1406 PPConditionalInfo CondInfo;
1407 if (CurLexer->popConditionalLevel(CondInfo)) {
1408 // No conditionals on the stack: this is an #endif without an #if.
1409 return Diag(EndifToken, diag::err_pp_endif_without_if);
1410 }
1411
1412 assert(!CondInfo.WasSkipping && !isSkipping() &&
1413 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001414}
1415
1416
Chris Lattnercb283342006-06-18 06:48:37 +00001417void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001418 ++NumElse;
1419 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001420 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001421
1422 PPConditionalInfo CI;
1423 if (CurLexer->popConditionalLevel(CI))
1424 return Diag(Result, diag::pp_err_else_without_if);
1425
1426 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001427 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001428
1429 // Finally, skip the rest of the contents of this block and return the first
1430 // token after it.
1431 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1432 /*FoundElse*/true);
1433}
1434
Chris Lattnercb283342006-06-18 06:48:37 +00001435void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001436 ++NumElse;
1437 // #elif directive in a non-skipping conditional... start skipping.
1438 // We don't care what the condition is, because we will always skip it (since
1439 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001440 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001441
1442 PPConditionalInfo CI;
1443 if (CurLexer->popConditionalLevel(CI))
1444 return Diag(ElifToken, diag::pp_err_elif_without_if);
1445
1446 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001447 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001448
1449 // Finally, skip the rest of the contents of this block and return the first
1450 // token after it.
1451 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1452 /*FoundElse*/CI.FoundElse);
1453}
Chris Lattnerb8761832006-06-24 21:31:03 +00001454