blob: 83ae6f93b7f1d452e5a23bc02a8e62e5af7cedfe [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.
21// -P - Do not emit #line directives.
22// -d[MDNI] - Dump various things.
23// -fworking-directory - #line's with preprocessor's working dir.
24// -fpreprocessed
25// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
26// -W*
27// -w
28//
29// Messages to emit:
30// "Multiple include guards may be useful for:\n"
31//
32// TODO: Implement the include guard optimization.
33//
Chris Lattnerc1283b92006-07-01 23:16:30 +000034// Predefined Macros: _Pragma, __TIMESTAMP__, ...
Chris Lattner236ed522006-06-26 01:36:29 +000035//
Chris Lattner22eb9722006-06-18 05:43:12 +000036//===----------------------------------------------------------------------===//
37
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000040#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000041#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000042#include "clang/Basic/Diagnostic.h"
43#include "clang/Basic/FileManager.h"
44#include "clang/Basic/SourceManager.h"
45#include <iostream>
46using namespace llvm;
47using namespace clang;
48
49//===----------------------------------------------------------------------===//
50
51Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
52 FileManager &FM, SourceManager &SM)
53 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
54 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000055 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000056 ScratchBuf = new ScratchBuffer(SourceMgr);
57
Chris Lattner22eb9722006-06-18 05:43:12 +000058 // Clear stats.
59 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
60 NumIf = NumElse = NumEndif = 0;
61 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
62 MaxIncludeStackDepth = MaxMacroStackDepth = 0;
63 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000064
Chris Lattner22eb9722006-06-18 05:43:12 +000065 // Macro expansion is enabled.
66 DisableMacroExpansion = false;
67 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000068
69 // There is no file-change handler yet.
70 FileChangeHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000071
72 // Initialize the pragma handlers.
73 PragmaHandlers = new PragmaNamespace(0);
74 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000075
76 // Initialize builtin macros like __LINE__ and friends.
77 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000078}
79
80Preprocessor::~Preprocessor() {
81 // Free any active lexers.
82 delete CurLexer;
83
84 while (!IncludeStack.empty()) {
85 delete IncludeStack.back().TheLexer;
86 IncludeStack.pop_back();
87 }
Chris Lattnerb8761832006-06-24 21:31:03 +000088
89 // Release pragma information.
90 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000091
92 // Delete the scratch buffer info.
93 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000094}
95
96/// getFileInfo - Return the PerFileInfo structure for the specified
97/// FileEntry.
98Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
99 if (FE->getUID() >= FileInfo.size())
100 FileInfo.resize(FE->getUID()+1);
101 return FileInfo[FE->getUID()];
102}
103
104
105/// AddKeywords - Add all keywords to the symbol table.
106///
107void Preprocessor::AddKeywords() {
108 enum {
109 C90Shift = 0,
110 EXTC90 = 1 << C90Shift,
111 NOTC90 = 2 << C90Shift,
112 C99Shift = 2,
113 EXTC99 = 1 << C99Shift,
114 NOTC99 = 2 << C99Shift,
115 CPPShift = 4,
116 EXTCPP = 1 << CPPShift,
117 NOTCPP = 2 << CPPShift,
118 Mask = 3
119 };
120
121 // Add keywords and tokens for the current language.
122#define KEYWORD(NAME, FLAGS) \
123 AddKeyword(#NAME+1, tok::kw##NAME, \
124 (FLAGS >> C90Shift) & Mask, \
125 (FLAGS >> C99Shift) & Mask, \
126 (FLAGS >> CPPShift) & Mask);
127#define ALIAS(NAME, TOK) \
128 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
129#include "clang/Basic/TokenKinds.def"
130}
131
132/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
133/// the specified LexerToken's location, translating the token's start
134/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000135void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000136 const std::string &Msg) {
137 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
138 // warnings or extensions.
139 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000140 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000141
Chris Lattnercb283342006-06-18 06:48:37 +0000142 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000143}
Chris Lattnercb283342006-06-18 06:48:37 +0000144void Preprocessor::Diag(const LexerToken &Tok, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000145 const std::string &Msg) {
146 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
147 // warnings or extensions.
148 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000149 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000150
Chris Lattner50b497e2006-06-18 16:32:35 +0000151 Diag(Tok.getLocation(), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000152}
153
Chris Lattnerd01e2912006-06-18 16:22:51 +0000154
155void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
156 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
157 << getSpelling(Tok) << "'";
158
159 if (!DumpFlags) return;
160 std::cerr << "\t";
161 if (Tok.isAtStartOfLine())
162 std::cerr << " [StartOfLine]";
163 if (Tok.hasLeadingSpace())
164 std::cerr << " [LeadingSpace]";
165 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000166 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000167 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
168 << "']";
169 }
170}
171
172void Preprocessor::DumpMacro(const MacroInfo &MI) const {
173 std::cerr << "MACRO: ";
174 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
175 DumpToken(MI.getReplacementToken(i));
176 std::cerr << " ";
177 }
178 std::cerr << "\n";
179}
180
Chris Lattner22eb9722006-06-18 05:43:12 +0000181void Preprocessor::PrintStats() {
182 std::cerr << "\n*** Preprocessor Stats:\n";
183 std::cerr << FileInfo.size() << " files tracked.\n";
184 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
185 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
186 NumOnceOnlyFiles += FileInfo[i].isImport;
187 if (MaxNumIncludes < FileInfo[i].NumIncludes)
188 MaxNumIncludes = FileInfo[i].NumIncludes;
189 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
190 }
191 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
192 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
193 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
194
195 std::cerr << NumDirectives << " directives found:\n";
196 std::cerr << " " << NumDefined << " #define.\n";
197 std::cerr << " " << NumUndefined << " #undef.\n";
198 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
199 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
200 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
201 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
202 std::cerr << " " << NumElse << " #else/#elif.\n";
203 std::cerr << " " << NumEndif << " #endif.\n";
204 std::cerr << " " << NumPragma << " #pragma.\n";
205 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
206
207 std::cerr << NumMacroExpanded << " macros expanded, "
208 << NumFastMacroExpanded << " on the fast path.\n";
209 if (MaxMacroStackDepth > 1)
210 std::cerr << " " << MaxMacroStackDepth << " max macroexpand stack depth\n";
211}
212
213//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214// Token Spelling
215//===----------------------------------------------------------------------===//
216
217
218/// getSpelling() - Return the 'spelling' of this token. The spelling of a
219/// token are the characters used to represent the token in the source file
220/// after trigraph expansion and escaped-newline folding. In particular, this
221/// wants to get the true, uncanonicalized, spelling of things like digraphs
222/// UCNs, etc.
223std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
224 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
225
226 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000227 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228 assert(TokStart && "Token has invalid location!");
229 if (!Tok.needsCleaning())
230 return std::string(TokStart, TokStart+Tok.getLength());
231
232 // Otherwise, hard case, relex the characters into the string.
233 std::string Result;
234 Result.reserve(Tok.getLength());
235
236 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
237 Ptr != End; ) {
238 unsigned CharSize;
239 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
240 Ptr += CharSize;
241 }
242 assert(Result.size() != unsigned(Tok.getLength()) &&
243 "NeedsCleaning flag set on something that didn't need cleaning!");
244 return Result;
245}
246
247/// getSpelling - This method is used to get the spelling of a token into a
248/// preallocated buffer, instead of as an std::string. The caller is required
249/// to allocate enough space for the token, which is guaranteed to be at least
250/// Tok.getLength() bytes long. The actual length of the token is returned.
251unsigned Preprocessor::getSpelling(const LexerToken &Tok, char *Buffer) const {
252 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
253
Chris Lattner50b497e2006-06-18 16:32:35 +0000254 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000255 assert(TokStart && "Token has invalid location!");
256
257 // If this token contains nothing interesting, return it directly.
258 if (!Tok.needsCleaning()) {
259 unsigned Size = Tok.getLength();
260 memcpy(Buffer, TokStart, Size);
261 return Size;
262 }
263 // Otherwise, hard case, relex the characters into the string.
264 std::string Result;
265 Result.reserve(Tok.getLength());
266
267 char *OutBuf = Buffer;
268 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
269 Ptr != End; ) {
270 unsigned CharSize;
271 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
272 Ptr += CharSize;
273 }
274 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
275 "NeedsCleaning flag set on something that didn't need cleaning!");
276
277 return OutBuf-Buffer;
278}
279
280//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000281// Source File Location Methods.
282//===----------------------------------------------------------------------===//
283
284
285/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
286/// return null on failure. isAngled indicates whether the file reference is
287/// for system #include's or not (i.e. using <> instead of "").
288const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000289 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000290 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000291 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000292 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000293 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000294
295 // If 'Filename' is absolute, check to see if it exists and no searching.
296 // FIXME: this should be a sys::Path interface, this doesn't handle things
297 // like C:\foo.txt right, nor win32 \\network\device\blah.
298 if (Filename[0] == '/') {
299 // If this was an #include_next "/absolute/file", fail.
300 if (FromDir) return 0;
301
302 // Otherwise, just return the file.
303 return FileMgr.getFile(Filename);
304 }
305
306 // Step #0, unless disabled, check to see if the file is in the #includer's
307 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000308 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000309 const FileEntry *CurFE =
310 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
311 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000312 // Concatenate the requested file onto the directory.
313 // FIXME: should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000314 if (const FileEntry *FE =
315 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000316 if (CurDirLookup)
317 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000318 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000319 CurDir = 0;
320
321 // This file is a system header or C++ unfriendly if the old file is.
322 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000323 return FE;
324 }
325 }
326 }
327
328 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000329 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000330
331 // If this is a #include_next request, start searching after the directory the
332 // file was found in.
333 if (FromDir)
334 i = FromDir-&SearchDirs[0];
335
336 // Check each directory in sequence to see if it contains this file.
337 for (; i != SearchDirs.size(); ++i) {
338 // Concatenate the requested file onto the directory.
339 // FIXME: should be in sys::Path.
340 if (const FileEntry *FE =
341 FileMgr.getFile(SearchDirs[i].getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000342 CurDir = &SearchDirs[i];
343
344 // This file is a system header or C++ unfriendly if the dir is.
345 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000346 return FE;
347 }
348 }
349
350 // Otherwise, didn't find it.
351 return 0;
352}
353
354/// EnterSourceFile - Add a source file to the top of the include stack and
355/// start lexing tokens from it instead of the current buffer. Return true
356/// on failure.
357void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattnerc8997182006-06-22 05:52:16 +0000358 const DirectoryLookup *CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000359 ++NumEnteredSourceFiles;
360
361 // Add the current lexer to the include stack.
362 if (CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000363 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup));
Chris Lattner22eb9722006-06-18 05:43:12 +0000364 } else {
365 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
366 }
367
368 if (MaxIncludeStackDepth < IncludeStack.size())
369 MaxIncludeStackDepth = IncludeStack.size();
370
371 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
372
Chris Lattnerc8997182006-06-22 05:52:16 +0000373 CurLexer = new Lexer(Buffer, FileID, *this);
374 CurDirLookup = CurDir;
Chris Lattner0c885f52006-06-21 06:50:18 +0000375
376 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerc8997182006-06-22 05:52:16 +0000377 if (FileChangeHandler) {
378 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
379
380 // Get the file entry for the current file.
381 if (const FileEntry *FE =
382 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
383 FileType = getFileInfo(FE).DirInfo;
384
Chris Lattner55a60952006-06-25 04:20:34 +0000385 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferStart),
386 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000387 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000388}
389
390/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000391/// tokens from it instead of the current buffer.
392void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000393 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
394 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000395 if (CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000396 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup));
397 CurLexer = 0;
398 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000399 } else if (CurMacroExpander) {
400 MacroStack.push_back(CurMacroExpander);
401 }
402
403 if (MaxMacroStackDepth < MacroStack.size())
404 MaxMacroStackDepth = MacroStack.size();
405
406 // TODO: Figure out arguments.
407
408 // Mark the macro as currently disabled, so that it is not recursively
409 // expanded.
410 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000411 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000412}
413
Chris Lattner22eb9722006-06-18 05:43:12 +0000414//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000415// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000416//===----------------------------------------------------------------------===//
417
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000418/// RegisterBuiltinMacro - Register the specified identifier in the identifier
419/// table and mark it as a builtin macro to be expanded.
420IdentifierTokenInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
421 // Get the identifier.
422 IdentifierTokenInfo *Id = getIdentifierInfo(Name);
423
424 // Mark it as being a macro that is builtin.
425 MacroInfo *MI = new MacroInfo(SourceLocation());
426 MI->setIsBuiltinMacro();
427 Id->setMacroInfo(MI);
428 return Id;
429}
430
431
Chris Lattner677757a2006-06-28 05:26:32 +0000432/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
433/// identifier table.
434void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner677757a2006-06-28 05:26:32 +0000435 // FIXME: implement them all, including _Pragma.
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000436 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000437 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000438 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
439 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000440
441 // GCC Extensions.
442 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
443 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
444 // __TIMESTAMP__
445 // _Pragma
446
447//Pseudo #defines.
448 // __STDC__ 1 if !stdc_0_in_system_headers and "std"
449 // __STDC_VERSION__
450 // __STDC_HOSTED__
451 // __OBJC__
Chris Lattner22eb9722006-06-18 05:43:12 +0000452}
453
Chris Lattner677757a2006-06-28 05:26:32 +0000454
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000455/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
456/// expanded as a macro, handle it and return the next token as 'Identifier'.
457void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
458 MacroInfo *MI) {
459 ++NumMacroExpanded;
460 // If we started lexing a macro, enter the macro expansion body.
461 // FIXME: Read/Validate the argument list here!
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000462
463 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
464 if (MI->isBuiltinMacro())
465 return ExpandBuiltinMacro(Identifier, MI);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000466
467 // If this macro expands to no tokens, don't bother to push it onto the
468 // expansion stack, only to take it right back off.
469 if (MI->getNumTokens() == 0) {
470 // Ignore this macro use, just return the next token in the current
471 // buffer.
472 bool HadLeadingSpace = Identifier.hasLeadingSpace();
473 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
474
475 Lex(Identifier);
476
477 // If the identifier isn't on some OTHER line, inherit the leading
478 // whitespace/first-on-a-line property of this token. This handles
479 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
480 // empty.
481 if (!Identifier.isAtStartOfLine()) {
482 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
483 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
484 }
485 ++NumFastMacroExpanded;
486 return;
487
488 } else if (MI->getNumTokens() == 1 &&
489 // Don't handle identifiers if they need recursive expansion.
490 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
491 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
492 // FIXME: Function-style macros only if no arguments?
493
494 // Otherwise, if this macro expands into a single trivially-expanded
495 // token: expand it now. This handles common cases like
496 // "#define VAL 42".
497
498 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
499 // identifier to the expanded token.
500 bool isAtStartOfLine = Identifier.isAtStartOfLine();
501 bool hasLeadingSpace = Identifier.hasLeadingSpace();
502
503 // Remember where the token is instantiated.
504 SourceLocation InstantiateLoc = Identifier.getLocation();
505
506 // Replace the result token.
507 Identifier = MI->getReplacementToken(0);
508
509 // Restore the StartOfLine/LeadingSpace markers.
510 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
511 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
512
513 // Update the tokens location to include both its logical and physical
514 // locations.
515 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000516 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000517 Identifier.SetLocation(Loc);
518
519 // Since this is not an identifier token, it can't be macro expanded, so
520 // we're done.
521 ++NumFastMacroExpanded;
522 return;
523 }
524
525 // Start expanding the macro (FIXME, pass arguments).
526 EnterMacro(Identifier);
527
528 // Now that the macro is at the top of the include stack, ask the
529 // preprocessor to read the next token from it.
530 return Lex(Identifier);
531}
532
Chris Lattnerc673f902006-06-30 06:10:41 +0000533/// ComputeDATE_TIME - Compute the current time, enter it into the specified
534/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
535/// the identifier tokens inserted.
536static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
537 ScratchBuffer *ScratchBuf) {
538 time_t TT = time(0);
539 struct tm *TM = localtime(&TT);
540
541 static const char * const Months[] = {
542 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
543 };
544
545 char TmpBuffer[100];
546 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
547 TM->tm_year+1900);
548 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
549
550 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
551 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
552}
553
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000554/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
555/// as a builtin macro, handle it and return the next token as 'Tok'.
556void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok, MacroInfo *MI) {
557 // Figure out which token this is.
558 IdentifierTokenInfo *ITI = Tok.getIdentifierInfo();
559 assert(ITI && "Can't be a macro without id info!");
560 char TmpBuffer[100];
561
Chris Lattnerc673f902006-06-30 06:10:41 +0000562
Chris Lattner630b33c2006-07-01 22:46:53 +0000563 Tok.SetIdentifierInfo(0);
564 Tok.ClearFlag(LexerToken::NeedsCleaning);
565
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000566 if (ITI == Ident__LINE__) {
567 // __LINE__ expands to a simple numeric value.
568 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
569 unsigned Length = strlen(TmpBuffer);
570 Tok.SetKind(tok::numeric_constant);
571 Tok.SetLength(Length);
572 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000573 } else if (ITI == Ident__FILE__ || ITI == Ident__BASE_FILE__) {
574 SourceLocation Loc = Tok.getLocation();
575 if (ITI == Ident__BASE_FILE__) {
576 Diag(Tok, diag::ext_pp_base_file);
577 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
578 while (NextLoc.getFileID() != 0) {
579 Loc = NextLoc;
580 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
581 }
582 }
583
584 // FIXME: Escape this filename correctly.
585 std::string FN = '"' + SourceMgr.getSourceName(Loc) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000586 Tok.SetKind(tok::string_literal);
587 Tok.SetLength(FN.size());
588 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000589 } else if (ITI == Ident__DATE__) {
590 if (!DATELoc.isValid())
591 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
592 Tok.SetKind(tok::string_literal);
593 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
594 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000595 } else if (ITI == Ident__TIME__) {
596 if (!TIMELoc.isValid())
597 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
598 Tok.SetKind(tok::string_literal);
599 Tok.SetLength(strlen("\"hh:mm:ss\""));
600 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000601 } else if (ITI == Ident__INCLUDE_LEVEL__) {
602 Diag(Tok, diag::ext_pp_include_level);
603
604 // Compute the include depth of this token.
605 unsigned Depth = 0;
606 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
607 for (; Loc.getFileID() != 0; ++Depth)
608 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
609
610 // __INCLUDE_LEVEL__ expands to a simple numeric value.
611 sprintf(TmpBuffer, "%u", Depth);
612 unsigned Length = strlen(TmpBuffer);
613 Tok.SetKind(tok::numeric_constant);
614 Tok.SetLength(Length);
615 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000616 } else {
617 assert(0 && "Unknown identifier!");
618 }
619}
Chris Lattner677757a2006-06-28 05:26:32 +0000620
621//===----------------------------------------------------------------------===//
622// Lexer Event Handling.
623//===----------------------------------------------------------------------===//
624
625/// HandleIdentifier - This callback is invoked when the lexer reads an
626/// identifier. This callback looks up the identifier in the map and/or
627/// potentially macro expands it or turns it into a named token (like 'for').
628void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
629 if (Identifier.getIdentifierInfo() == 0) {
630 // If we are skipping tokens (because we are in a #if 0 block), there will
631 // be no identifier info, just return the token.
632 assert(isSkipping() && "Token isn't an identifier?");
633 return;
634 }
635 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
636
637 // If this identifier was poisoned, and if it was not produced from a macro
638 // expansion, emit an error.
639 if (ITI.isPoisoned() && CurLexer)
640 Diag(Identifier, diag::err_pp_used_poisoned_id);
641
642 if (MacroInfo *MI = ITI.getMacroInfo())
643 if (MI->isEnabled() && !DisableMacroExpansion)
644 return HandleMacroExpandedIdentifier(Identifier, MI);
645
646 // Change the kind of this identifier to the appropriate token kind, e.g.
647 // turning "for" into a keyword.
648 Identifier.SetKind(ITI.getTokenID());
649
650 // If this is an extension token, diagnose its use.
651 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
652}
653
Chris Lattner22eb9722006-06-18 05:43:12 +0000654/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
655/// the current file. This either returns the EOF token or pops a level off
656/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000657void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000658 assert(!CurMacroExpander &&
659 "Ending a file when currently in a macro!");
660
661 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
662 // this is an error condition. Just return the EOF token up to
663 // SkipExcludedConditionalBlock. The Lexer will have already have issued
664 // errors for the unterminated #if's on the conditional stack.
665 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000666 Result.StartToken();
667 CurLexer->BufferPtr = CurLexer->BufferEnd;
668 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000669 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000670 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000671 }
672
673 // If this is a #include'd file, pop it off the include stack and continue
674 // lexing the #includer file.
675 if (!IncludeStack.empty()) {
676 // We're done with the #included file.
677 delete CurLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000678 CurLexer = IncludeStack.back().TheLexer;
679 CurDirLookup = IncludeStack.back().TheDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000680 IncludeStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000681
682 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerc8997182006-06-22 05:52:16 +0000683 if (FileChangeHandler && !isEndOfMacro) {
684 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
685
686 // Get the file entry for the current file.
687 if (const FileEntry *FE =
688 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
689 FileType = getFileInfo(FE).DirInfo;
690
Chris Lattner0c885f52006-06-21 06:50:18 +0000691 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000692 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000693 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000694
Chris Lattner22eb9722006-06-18 05:43:12 +0000695 return Lex(Result);
696 }
697
Chris Lattnerd01e2912006-06-18 16:22:51 +0000698 Result.StartToken();
699 CurLexer->BufferPtr = CurLexer->BufferEnd;
700 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000701 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000702
703 // We're done with the #included file.
704 delete CurLexer;
705 CurLexer = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000706}
707
708/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000709/// the current macro line.
710void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000711 assert(CurMacroExpander && !CurLexer &&
712 "Ending a macro when currently in a #include file!");
713
714 // Mark macro not ignored now that it is no longer being expanded.
715 CurMacroExpander->getMacro().EnableMacro();
716 delete CurMacroExpander;
717
718 if (!MacroStack.empty()) {
719 // In a nested macro invocation, continue lexing from the macro.
720 CurMacroExpander = MacroStack.back();
721 MacroStack.pop_back();
722 return Lex(Result);
723 } else {
724 CurMacroExpander = 0;
725 // Handle this like a #include file being popped off the stack.
Chris Lattner0c885f52006-06-21 06:50:18 +0000726 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000727 }
728}
729
730
731//===----------------------------------------------------------------------===//
732// Utility Methods for Preprocessor Directive Handling.
733//===----------------------------------------------------------------------===//
734
735/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
736/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000737void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000738 LexerToken Tmp;
739 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000740 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000741 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000742}
743
744/// ReadMacroName - Lex and validate a macro name, which occurs after a
745/// #define or #undef. This sets the token kind to eom and discards the rest
746/// of the macro line if the macro name is invalid.
Chris Lattnercb283342006-06-18 06:48:37 +0000747void Preprocessor::ReadMacroName(LexerToken &MacroNameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000748 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000749 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000750
751 // Missing macro name?
752 if (MacroNameTok.getKind() == tok::eom)
753 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
754
755 if (MacroNameTok.getIdentifierInfo() == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000756 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000757 // Fall through on error.
758 } else if (0) {
759 // FIXME: Error if defining a C++ named operator.
760
761 } else if (0) {
762 // FIXME: Error if defining "defined", "__DATE__", and other predef macros
763 // in C99 6.10.8.4.
764 } else {
765 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000766 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000767 }
768
769
770 // Invalid macro name, read and discard the rest of the line. Then set the
771 // token kind to tok::eom.
772 MacroNameTok.SetKind(tok::eom);
773 return DiscardUntilEndOfDirective();
774}
775
776/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
777/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000778void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000779 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000780 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000781 // There should be no tokens after the directive, but we allow them as an
782 // extension.
783 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000784 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
785 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000786 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000787}
788
789
790
791/// SkipExcludedConditionalBlock - We just read a #if or related directive and
792/// decided that the subsequent tokens are in the #if'd out portion of the
793/// file. Lex the rest of the file, until we see an #endif. If
794/// FoundNonSkipPortion is true, then we have already emitted code for part of
795/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
796/// is true, then #else directives are ok, if not, then we have already seen one
797/// so a #else directive is a duplicate. When this returns, the caller can lex
798/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000799void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000800 bool FoundNonSkipPortion,
801 bool FoundElse) {
802 ++NumSkipped;
803 assert(MacroStack.empty() && CurMacroExpander == 0 && CurLexer &&
804 "Lexing a macro, not a file?");
805
806 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
807 FoundNonSkipPortion, FoundElse);
808
809 // Know that we are going to be skipping tokens. Set this flag to indicate
810 // this, which has a couple of effects:
811 // 1. If EOF of the current lexer is found, the include stack isn't popped.
812 // 2. Identifier information is not looked up for identifier tokens. As an
813 // effect of this, implicit macro expansion is naturally disabled.
814 // 3. "#" tokens at the start of a line are treated as normal tokens, not
815 // implicitly transformed by the lexer.
816 // 4. All notes, warnings, and extension messages are disabled.
817 //
818 SkippingContents = true;
819 LexerToken Tok;
820 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000821 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000822
823 // If this is the end of the buffer, we have an error. The lexer will have
824 // already handled this error condition, so just return and let the caller
825 // lex after this #include.
826 if (Tok.getKind() == tok::eof) break;
827
828 // If this token is not a preprocessor directive, just skip it.
829 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
830 continue;
831
832 // We just parsed a # character at the start of a line, so we're in
833 // directive mode. Tell the lexer this so any newlines we see will be
834 // converted into an EOM token (this terminates the macro).
835 CurLexer->ParsingPreprocessorDirective = true;
836
837 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000838 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000839
840 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
841 // something bogus), skip it.
842 if (Tok.getKind() != tok::identifier) {
843 CurLexer->ParsingPreprocessorDirective = false;
844 continue;
845 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000846
Chris Lattner22eb9722006-06-18 05:43:12 +0000847 // If the first letter isn't i or e, it isn't intesting to us. We know that
848 // this is safe in the face of spelling differences, because there is no way
849 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000850 // allows us to avoid looking up the identifier info for #define/#undef and
851 // other common directives.
852 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
853 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000854 if (FirstChar >= 'a' && FirstChar <= 'z' &&
855 FirstChar != 'i' && FirstChar != 'e') {
856 CurLexer->ParsingPreprocessorDirective = false;
857 continue;
858 }
859
Chris Lattnere60165f2006-06-22 06:36:29 +0000860 // Get the identifier name without trigraphs or embedded newlines. Note
861 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
862 // when skipping.
863 // TODO: could do this with zero copies in the no-clean case by using
864 // strncmp below.
865 char Directive[20];
866 unsigned IdLen;
867 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
868 IdLen = Tok.getLength();
869 memcpy(Directive, RawCharData, IdLen);
870 Directive[IdLen] = 0;
871 } else {
872 std::string DirectiveStr = getSpelling(Tok);
873 IdLen = DirectiveStr.size();
874 if (IdLen >= 20) {
875 CurLexer->ParsingPreprocessorDirective = false;
876 continue;
877 }
878 memcpy(Directive, &DirectiveStr[0], IdLen);
879 Directive[IdLen] = 0;
880 }
881
Chris Lattner22eb9722006-06-18 05:43:12 +0000882 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000883 if ((IdLen == 2) || // "if"
884 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
885 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000886 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
887 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000888 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000889 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000890 /*foundnonskip*/false,
891 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000892 }
893 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000894 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000895 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000896 PPConditionalInfo CondInfo;
897 CondInfo.WasSkipping = true; // Silence bogus warning.
898 bool InCond = CurLexer->popConditionalLevel(CondInfo);
899 assert(!InCond && "Can't be skipping if not in a conditional!");
900
901 // If we popped the outermost skipping block, we're done skipping!
902 if (!CondInfo.WasSkipping)
903 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000904 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000905 // #else directive in a skipping conditional. If not in some other
906 // skipping conditional, and if #else hasn't already been seen, enter it
907 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000908 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000909 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
910
911 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000912 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000913
914 // Note that we've seen a #else in this conditional.
915 CondInfo.FoundElse = true;
916
917 // If the conditional is at the top level, and the #if block wasn't
918 // entered, enter the #else block now.
919 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
920 CondInfo.FoundNonSkip = true;
921 break;
922 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000923 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +0000924 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
925
926 bool ShouldEnter;
927 // If this is in a skipping block or if we're already handled this #if
928 // block, don't bother parsing the condition.
929 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +0000930 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000931 ShouldEnter = false;
932 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +0000933 // Restore the value of SkippingContents so that identifiers are
934 // looked up, etc, inside the #elif expression.
935 assert(SkippingContents && "We have to be skipping here!");
936 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +0000937 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +0000938 SkippingContents = true;
939 }
940
941 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000942 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000943
944 // If this condition is true, enter it!
945 if (ShouldEnter) {
946 CondInfo.FoundNonSkip = true;
947 break;
948 }
949 }
950 }
951
952 CurLexer->ParsingPreprocessorDirective = false;
953 }
954
955 // Finally, if we are out of the conditional (saw an #endif or ran off the end
956 // of the file, just stop skipping and return to lexing whatever came after
957 // the #if block.
958 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000959}
960
961//===----------------------------------------------------------------------===//
962// Preprocessor Directive Handling.
963//===----------------------------------------------------------------------===//
964
965/// HandleDirective - This callback is invoked when the lexer sees a # token
966/// at the start of a line. This consumes the directive, modifies the
967/// lexer/preprocessor state, and advances the lexer(s) so that the next token
968/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +0000969void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000970 // FIXME: TRADITIONAL: # with whitespace before it not recognized by K&R?
971
972 // We just parsed a # character at the start of a line, so we're in directive
973 // mode. Tell the lexer this so any newlines we see will be converted into an
974 // EOM token (this terminates the macro).
975 CurLexer->ParsingPreprocessorDirective = true;
976
977 ++NumDirectives;
978
979 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000980 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000981
982 switch (Result.getKind()) {
983 default: break;
984 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +0000985 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +0000986
987#if 0
988 case tok::numeric_constant:
989 // FIXME: implement # 7 line numbers!
990 break;
991#endif
992 case tok::kw_else:
993 return HandleElseDirective(Result);
994 case tok::kw_if:
995 return HandleIfDirective(Result);
996 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +0000997 // Get the identifier name without trigraphs or embedded newlines.
998 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +0000999 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001000 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001001 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001002 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001003 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001004 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001005 return HandleElifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001006 if (Directive[0] == 's' && !strcmp(Directive, "sccs")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001007 isExtension = true; // FIXME: implement #sccs
Chris Lattner22eb9722006-06-18 05:43:12 +00001008 // SCCS is the same as #ident.
1009 }
1010 break;
1011 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001012 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001013 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001014 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001015 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001016 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001017 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001018 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001019 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001020 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001021 isExtension = true; // FIXME: implement #ident
Chris Lattner22eb9722006-06-18 05:43:12 +00001022 break;
1023 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001024 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001025 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001026 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001027 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +00001028 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001029 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001030 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
1031 return HandlePragmaDirective(Result);
1032 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1033 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001034 break;
1035 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001036 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1037 return HandleIncludeDirective(Result); // Handle #include.
1038 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001039 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001040 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001041 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001042 break;
1043 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001044 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001045 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001046 }
1047 break;
1048 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001049 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1050 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001051 break;
1052 }
1053 break;
1054 }
1055
1056 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001057 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001058
1059 // Read the rest of the PP line.
1060 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001061 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 } while (Result.getKind() != tok::eom);
1063
1064 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001065}
1066
Chris Lattnercb283342006-06-18 06:48:37 +00001067void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +00001068 bool isWarning) {
1069 // Read the rest of the line raw. We do this because we don't want macros
1070 // to be expanded and we don't require that the tokens be valid preprocessing
1071 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1072 // collapse multiple consequtive white space between tokens, but this isn't
1073 // specified by the standard.
1074 std::string Message = CurLexer->ReadToEndOfLine();
1075
1076 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1077 return Diag(Result, DiagID, Message);
1078}
1079
Chris Lattnerb8761832006-06-24 21:31:03 +00001080//===----------------------------------------------------------------------===//
1081// Preprocessor Include Directive Handling.
1082//===----------------------------------------------------------------------===//
1083
Chris Lattner22eb9722006-06-18 05:43:12 +00001084/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1085/// file to be included from the lexer, then include it! This is a common
1086/// routine with functionality shared between #include, #include_next and
1087/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001088void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001089 const DirectoryLookup *LookupFrom,
1090 bool isImport) {
1091 ++NumIncluded;
1092 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001093 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001094
1095 // If the token kind is EOM, the error has already been diagnosed.
1096 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001097 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001098
1099 // Verify that there is nothing after the filename, other than EOM. Use the
1100 // preprocessor to lex this in case lexing the filename entered a macro.
1101 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001102
1103 // Check that we don't have infinite #include recursion.
1104 if (IncludeStack.size() == MaxAllowedIncludeStackDepth-1)
1105 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1106
Chris Lattner269c2322006-06-25 06:23:00 +00001107 // Find out whether the filename is <x> or "x".
1108 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001109
1110 // Remove the quotes.
1111 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1112
Chris Lattner22eb9722006-06-18 05:43:12 +00001113 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001114 const DirectoryLookup *CurDir;
1115 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 if (File == 0)
1117 return Diag(FilenameTok, diag::err_pp_file_not_found);
1118
1119 // Get information about this file.
1120 PerFileInfo &FileInfo = getFileInfo(File);
1121
1122 // If this is a #import directive, check that we have not already imported
1123 // this header.
1124 if (isImport) {
1125 // If this has already been imported, don't import it again.
1126 FileInfo.isImport = true;
1127
1128 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001129 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001130 } else {
1131 // Otherwise, if this is a #include of a file that was previously #import'd
1132 // or if this is the second #include of a #pragma once file, ignore it.
1133 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001134 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001135 }
1136
1137 // Look up the file, create a File ID for it.
1138 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +00001139 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001140 if (FileID == 0)
1141 return Diag(FilenameTok, diag::err_pp_file_not_found);
1142
1143 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001144 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001145
1146 // Increment the number of times this file has been included.
1147 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001148}
1149
1150/// HandleIncludeNextDirective - Implements #include_next.
1151///
Chris Lattnercb283342006-06-18 06:48:37 +00001152void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1153 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001154
1155 // #include_next is like #include, except that we start searching after
1156 // the current found directory. If we can't do this, issue a
1157 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001158 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001159 if (IncludeStack.empty()) {
1160 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001161 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001162 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001163 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001164 } else {
1165 // Start looking up in the next directory.
1166 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001167 }
1168
1169 return HandleIncludeDirective(IncludeNextTok, Lookup);
1170}
1171
1172/// HandleImportDirective - Implements #import.
1173///
Chris Lattnercb283342006-06-18 06:48:37 +00001174void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1175 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001176
1177 return HandleIncludeDirective(ImportTok, 0, true);
1178}
1179
Chris Lattnerb8761832006-06-24 21:31:03 +00001180//===----------------------------------------------------------------------===//
1181// Preprocessor Macro Directive Handling.
1182//===----------------------------------------------------------------------===//
1183
Chris Lattner22eb9722006-06-18 05:43:12 +00001184/// HandleDefineDirective - Implements #define. This consumes the entire macro
1185/// line then lets the caller lex the next real token.
1186///
Chris Lattnercb283342006-06-18 06:48:37 +00001187void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001188 ++NumDefined;
1189 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001190 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001191
1192 // Error reading macro name? If so, diagnostic already issued.
1193 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001194 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001195
Chris Lattner50b497e2006-06-18 16:32:35 +00001196 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001197
1198 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001199 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001200
1201 if (Tok.getKind() == tok::eom) {
1202 // If there is no body to this macro, we have no special handling here.
1203 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1204 // This is a function-like macro definition.
1205 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001206 return DiscardUntilEndOfDirective();
1207
1208 } else if (!Tok.hasLeadingSpace()) {
1209 // C99 requires whitespace between the macro definition and the body. Emit
1210 // a diagnostic for something like "#define X+".
1211 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001212 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001213 } else {
1214 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1215 // one in some cases!
1216 }
1217 } else {
1218 // This is a normal token with leading space. Clear the leading space
1219 // marker on the first token to get proper expansion.
1220 Tok.ClearFlag(LexerToken::LeadingSpace);
1221 }
1222
1223 // Read the rest of the macro body.
1224 while (Tok.getKind() != tok::eom) {
1225 MI->AddTokenToBody(Tok);
1226
1227 // FIXME: See create_iso_definition.
1228
1229 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001230 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001231 }
1232
1233 // Finally, if this identifier already had a macro defined for it, verify that
1234 // the macro bodies are identical and free the old definition.
1235 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner677757a2006-06-28 05:26:32 +00001236 if (OtherMI->isBuiltinMacro())
1237 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1238
1239
Chris Lattner22eb9722006-06-18 05:43:12 +00001240 // FIXME: Verify the definition is the same.
1241 // Macros must be identical. This means all tokes and whitespace separation
1242 // must be the same.
1243 delete OtherMI;
1244 }
1245
1246 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001247}
1248
1249
1250/// HandleUndefDirective - Implements #undef.
1251///
Chris Lattnercb283342006-06-18 06:48:37 +00001252void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001253 ++NumUndefined;
1254 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001255 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001256
1257 // Error reading macro name? If so, diagnostic already issued.
1258 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001259 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001260
1261 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001262 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001263
1264 // Okay, we finally have a valid identifier to undef.
1265 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1266
1267 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001268 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001269
1270 if (MI->isBuiltinMacro())
1271 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001272
1273#if 0 // FIXME: implement warn_unused_macros.
1274 if (CPP_OPTION (pfile, warn_unused_macros))
1275 _cpp_warn_if_unused_macro (pfile, node, NULL);
1276#endif
1277
1278 // Free macro definition.
1279 delete MI;
1280 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001281}
1282
1283
Chris Lattnerb8761832006-06-24 21:31:03 +00001284//===----------------------------------------------------------------------===//
1285// Preprocessor Conditional Directive Handling.
1286//===----------------------------------------------------------------------===//
1287
Chris Lattner22eb9722006-06-18 05:43:12 +00001288/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1289/// true when this is a #ifndef directive.
1290///
Chris Lattnercb283342006-06-18 06:48:37 +00001291void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001292 ++NumIf;
1293 LexerToken DirectiveTok = Result;
1294
1295 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001296 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001297
1298 // Error reading macro name? If so, diagnostic already issued.
1299 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001300 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001301
1302 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001303 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001304
1305 // Should we include the stuff contained by this directive?
1306 if (!MacroNameTok.getIdentifierInfo()->getMacroInfo() == isIfndef) {
1307 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001308 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 } else {
1311 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001312 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001313 /*Foundnonskip*/false,
1314 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 }
1316}
1317
1318/// HandleIfDirective - Implements the #if directive.
1319///
Chris Lattnercb283342006-06-18 06:48:37 +00001320void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 ++NumIf;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001322 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001323
1324 // Should we include the stuff contained by this directive?
1325 if (ConditionalTrue) {
1326 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001327 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001329 } else {
1330 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001331 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001332 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001333 }
1334}
1335
1336/// HandleEndifDirective - Implements the #endif directive.
1337///
Chris Lattnercb283342006-06-18 06:48:37 +00001338void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 ++NumEndif;
1340 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001341 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001342
1343 PPConditionalInfo CondInfo;
1344 if (CurLexer->popConditionalLevel(CondInfo)) {
1345 // No conditionals on the stack: this is an #endif without an #if.
1346 return Diag(EndifToken, diag::err_pp_endif_without_if);
1347 }
1348
1349 assert(!CondInfo.WasSkipping && !isSkipping() &&
1350 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001351}
1352
1353
Chris Lattnercb283342006-06-18 06:48:37 +00001354void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 ++NumElse;
1356 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001357 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001358
1359 PPConditionalInfo CI;
1360 if (CurLexer->popConditionalLevel(CI))
1361 return Diag(Result, diag::pp_err_else_without_if);
1362
1363 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001364 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001365
1366 // Finally, skip the rest of the contents of this block and return the first
1367 // token after it.
1368 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1369 /*FoundElse*/true);
1370}
1371
Chris Lattnercb283342006-06-18 06:48:37 +00001372void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 ++NumElse;
1374 // #elif directive in a non-skipping conditional... start skipping.
1375 // We don't care what the condition is, because we will always skip it (since
1376 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001377 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001378
1379 PPConditionalInfo CI;
1380 if (CurLexer->popConditionalLevel(CI))
1381 return Diag(ElifToken, diag::pp_err_elif_without_if);
1382
1383 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001384 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001385
1386 // Finally, skip the rest of the contents of this block and return the first
1387 // token after it.
1388 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1389 /*FoundElse*/CI.FoundElse);
1390}
Chris Lattnerb8761832006-06-24 21:31:03 +00001391
1392
1393//===----------------------------------------------------------------------===//
1394// Preprocessor Pragma Directive Handling.
1395//===----------------------------------------------------------------------===//
1396
1397/// HandlePragmaDirective - The "#pragma" directive has been parsed with
1398/// PragmaTok containing the "pragma" identifier. Lex the rest of the pragma,
1399/// passing it to the registered pragma handlers.
1400void Preprocessor::HandlePragmaDirective(LexerToken &PragmaTok) {
1401 ++NumPragma;
1402
1403 // Invoke the first level of pragma handlers which reads the namespace id.
1404 LexerToken Tok;
1405 PragmaHandlers->HandlePragma(*this, Tok);
1406
1407 // If the pragma handler didn't read the rest of the line, consume it now.
Chris Lattner17862172006-06-24 22:12:56 +00001408 if (CurLexer->ParsingPreprocessorDirective)
1409 DiscardUntilEndOfDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001410}
1411
1412/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
Chris Lattner17862172006-06-24 22:12:56 +00001413///
Chris Lattnerb8761832006-06-24 21:31:03 +00001414void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
1415 if (IncludeStack.empty()) {
1416 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
1417 return;
1418 }
Chris Lattner17862172006-06-24 22:12:56 +00001419
1420 // FIXME: implement the _Pragma thing.
1421 assert(CurLexer && "Cannot have a pragma in a macro expansion yet!");
1422
1423 // Mark the file as a once-only file now.
1424 const FileEntry *File =
1425 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
1426 getFileInfo(File).isImport = true;
Chris Lattnerb8761832006-06-24 21:31:03 +00001427}
1428
Chris Lattner17862172006-06-24 22:12:56 +00001429/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
1430///
1431void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
1432 LexerToken Tok;
1433 assert(!SkippingContents && "Why are we handling pragmas while skipping?");
1434 while (1) {
1435 // Read the next token to poison. While doing this, pretend that we are
1436 // skipping while reading the identifier to poison.
1437 // This avoids errors on code like:
1438 // #pragma GCC poison X
1439 // #pragma GCC poison X
1440 SkippingContents = true;
1441 LexUnexpandedToken(Tok);
1442 SkippingContents = false;
1443
1444 // If we reached the end of line, we're done.
1445 if (Tok.getKind() == tok::eom) return;
1446
1447 // Can only poison identifiers.
1448 if (Tok.getKind() != tok::identifier) {
1449 Diag(Tok, diag::err_pp_invalid_poison);
1450 return;
1451 }
1452
1453 // Look up the identifier info for the token.
1454 std::string TokStr = getSpelling(Tok);
1455 IdentifierTokenInfo *II =
1456 getIdentifierInfo(&TokStr[0], &TokStr[0]+TokStr.size());
1457
1458 // Already poisoned.
1459 if (II->isPoisoned()) continue;
1460
1461 // If this is a macro identifier, emit a warning.
1462 if (II->getMacroInfo())
1463 Diag(Tok, diag::pp_poisoning_existing_macro);
1464
1465 // Finally, poison it!
1466 II->setIsPoisoned();
1467 }
1468}
Chris Lattnerb8761832006-06-24 21:31:03 +00001469
Chris Lattner269c2322006-06-25 06:23:00 +00001470/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
1471/// that the whole directive has been parsed.
Chris Lattner55a60952006-06-25 04:20:34 +00001472void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
1473 if (IncludeStack.empty()) {
1474 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
1475 return;
1476 }
1477
1478 // Mark the file as a system header.
1479 const FileEntry *File =
1480 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
1481 getFileInfo(File).DirInfo = DirectoryLookup::SystemHeaderDir;
1482
1483
1484 // Notify the client, if desired, that we are in a new source file.
1485 if (FileChangeHandler)
1486 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1487 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
1488}
1489
Chris Lattner269c2322006-06-25 06:23:00 +00001490/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
1491///
1492void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
1493 LexerToken FilenameTok;
1494 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
1495
1496 // If the token kind is EOM, the error has already been diagnosed.
1497 if (FilenameTok.getKind() == tok::eom)
1498 return;
1499
1500 // Find out whether the filename is <x> or "x".
1501 bool isAngled = Filename[0] == '<';
1502
1503 // Remove the quotes.
1504 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1505
1506 // Search include directories.
1507 const DirectoryLookup *CurDir;
1508 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
1509 if (File == 0)
1510 return Diag(FilenameTok, diag::err_pp_file_not_found);
1511
1512 Lexer *TheLexer = CurLexer;
1513 if (TheLexer == 0) {
1514 assert(!IncludeStack.empty() && "No current lexer?");
1515 TheLexer = IncludeStack.back().TheLexer;
1516 }
1517 const FileEntry *CurFile =
1518 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
1519
1520 // If this file is older than the file it depends on, emit a diagnostic.
1521 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
1522 // Lex tokens at the end of the message and include them in the message.
1523 std::string Message;
1524 Lex(DependencyTok);
1525 while (DependencyTok.getKind() != tok::eom) {
1526 Message += getSpelling(DependencyTok) + " ";
1527 Lex(DependencyTok);
1528 }
1529
1530 Message.erase(Message.end()-1);
1531 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
1532 }
1533}
1534
1535
Chris Lattnerb8761832006-06-24 21:31:03 +00001536/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
1537/// If 'Namespace' is non-null, then it is a token required to exist on the
1538/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
1539void Preprocessor::AddPragmaHandler(const char *Namespace,
1540 PragmaHandler *Handler) {
1541 PragmaNamespace *InsertNS = PragmaHandlers;
1542
1543 // If this is specified to be in a namespace, step down into it.
1544 if (Namespace) {
1545 IdentifierTokenInfo *NSID = getIdentifierInfo(Namespace);
1546
1547 // If there is already a pragma handler with the name of this namespace,
1548 // we either have an error (directive with the same name as a namespace) or
1549 // we already have the namespace to insert into.
1550 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
1551 InsertNS = Existing->getIfNamespace();
1552 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
1553 " handler with the same name!");
1554 } else {
1555 // Otherwise, this namespace doesn't exist yet, create and insert the
1556 // handler for it.
1557 InsertNS = new PragmaNamespace(NSID);
1558 PragmaHandlers->AddPragma(InsertNS);
1559 }
1560 }
1561
1562 // Check to make sure we don't already have a pragma for this identifier.
1563 assert(!InsertNS->FindHandler(Handler->getName()) &&
1564 "Pragma handler already exists for this identifier!");
1565 InsertNS->AddPragma(Handler);
1566}
1567
Chris Lattner17862172006-06-24 22:12:56 +00001568namespace {
Chris Lattner55a60952006-06-25 04:20:34 +00001569struct PragmaOnceHandler : public PragmaHandler {
Chris Lattnerb8761832006-06-24 21:31:03 +00001570 PragmaOnceHandler(const IdentifierTokenInfo *OnceID) : PragmaHandler(OnceID){}
1571 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
1572 PP.CheckEndOfDirective("#pragma once");
1573 PP.HandlePragmaOnce(OnceTok);
1574 }
1575};
1576
Chris Lattner55a60952006-06-25 04:20:34 +00001577struct PragmaPoisonHandler : public PragmaHandler {
Chris Lattner17862172006-06-24 22:12:56 +00001578 PragmaPoisonHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
1579 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
1580 PP.HandlePragmaPoison(PoisonTok);
1581 }
1582};
Chris Lattner55a60952006-06-25 04:20:34 +00001583
1584struct PragmaSystemHeaderHandler : public PragmaHandler {
1585 PragmaSystemHeaderHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID){}
1586 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
1587 PP.HandlePragmaSystemHeader(SHToken);
1588 PP.CheckEndOfDirective("#pragma");
1589 }
1590};
Chris Lattner269c2322006-06-25 06:23:00 +00001591struct PragmaDependencyHandler : public PragmaHandler {
1592 PragmaDependencyHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
1593 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
1594 PP.HandlePragmaDependency(DepToken);
1595 }
1596};
Chris Lattner17862172006-06-24 22:12:56 +00001597}
1598
Chris Lattnerb8761832006-06-24 21:31:03 +00001599
1600/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1601/// #pragma GCC poison/system_header/dependency and #pragma once.
1602void Preprocessor::RegisterBuiltinPragmas() {
1603 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
Chris Lattner17862172006-06-24 22:12:56 +00001604 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
Chris Lattner55a60952006-06-25 04:20:34 +00001605 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
1606 getIdentifierInfo("system_header")));
Chris Lattner269c2322006-06-25 06:23:00 +00001607 AddPragmaHandler("GCC", new PragmaDependencyHandler(
1608 getIdentifierInfo("dependency")));
Chris Lattnerb8761832006-06-24 21:31:03 +00001609}