blob: daee3ed715014e7847431928d56a6cf9711d60bc [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//
34//===----------------------------------------------------------------------===//
35
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000038#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000039#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000040#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/FileManager.h"
42#include "clang/Basic/SourceManager.h"
43#include <iostream>
44using namespace llvm;
45using namespace clang;
46
47//===----------------------------------------------------------------------===//
48
49Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
50 FileManager &FM, SourceManager &SM)
51 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
52 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000053 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000054 ScratchBuf = new ScratchBuffer(SourceMgr);
55
Chris Lattner22eb9722006-06-18 05:43:12 +000056 // Clear stats.
57 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
58 NumIf = NumElse = NumEndif = 0;
59 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
Chris Lattner69772b02006-07-02 20:34:39 +000060 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000061 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000062
Chris Lattner22eb9722006-06-18 05:43:12 +000063 // Macro expansion is enabled.
64 DisableMacroExpansion = false;
65 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000066
67 // There is no file-change handler yet.
68 FileChangeHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000069
70 // Initialize the pragma handlers.
71 PragmaHandlers = new PragmaNamespace(0);
72 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000073
74 // Initialize builtin macros like __LINE__ and friends.
75 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000076}
77
78Preprocessor::~Preprocessor() {
79 // Free any active lexers.
80 delete CurLexer;
81
Chris Lattner69772b02006-07-02 20:34:39 +000082 while (!IncludeMacroStack.empty()) {
83 delete IncludeMacroStack.back().TheLexer;
84 delete IncludeMacroStack.back().TheMacroExpander;
85 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000086 }
Chris Lattnerb8761832006-06-24 21:31:03 +000087
88 // Release pragma information.
89 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000090
91 // Delete the scratch buffer info.
92 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000093}
94
95/// getFileInfo - Return the PerFileInfo structure for the specified
96/// FileEntry.
97Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
98 if (FE->getUID() >= FileInfo.size())
99 FileInfo.resize(FE->getUID()+1);
100 return FileInfo[FE->getUID()];
101}
102
103
104/// AddKeywords - Add all keywords to the symbol table.
105///
106void Preprocessor::AddKeywords() {
107 enum {
108 C90Shift = 0,
109 EXTC90 = 1 << C90Shift,
110 NOTC90 = 2 << C90Shift,
111 C99Shift = 2,
112 EXTC99 = 1 << C99Shift,
113 NOTC99 = 2 << C99Shift,
114 CPPShift = 4,
115 EXTCPP = 1 << CPPShift,
116 NOTCPP = 2 << CPPShift,
117 Mask = 3
118 };
119
120 // Add keywords and tokens for the current language.
121#define KEYWORD(NAME, FLAGS) \
122 AddKeyword(#NAME+1, tok::kw##NAME, \
123 (FLAGS >> C90Shift) & Mask, \
124 (FLAGS >> C99Shift) & Mask, \
125 (FLAGS >> CPPShift) & Mask);
126#define ALIAS(NAME, TOK) \
127 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
128#include "clang/Basic/TokenKinds.def"
129}
130
131/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
132/// the specified LexerToken's location, translating the token's start
133/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000134void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000135 const std::string &Msg) {
136 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
137 // warnings or extensions.
138 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000139 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000140
Chris Lattnercb283342006-06-18 06:48:37 +0000141 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000142}
Chris Lattnercb283342006-06-18 06:48:37 +0000143void Preprocessor::Diag(const LexerToken &Tok, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000144 const std::string &Msg) {
145 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
146 // warnings or extensions.
147 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000148 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000149
Chris Lattner50b497e2006-06-18 16:32:35 +0000150 Diag(Tok.getLocation(), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000151}
152
Chris Lattnerd01e2912006-06-18 16:22:51 +0000153
154void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
155 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
156 << getSpelling(Tok) << "'";
157
158 if (!DumpFlags) return;
159 std::cerr << "\t";
160 if (Tok.isAtStartOfLine())
161 std::cerr << " [StartOfLine]";
162 if (Tok.hasLeadingSpace())
163 std::cerr << " [LeadingSpace]";
164 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000165 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000166 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
167 << "']";
168 }
169}
170
171void Preprocessor::DumpMacro(const MacroInfo &MI) const {
172 std::cerr << "MACRO: ";
173 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
174 DumpToken(MI.getReplacementToken(i));
175 std::cerr << " ";
176 }
177 std::cerr << "\n";
178}
179
Chris Lattner22eb9722006-06-18 05:43:12 +0000180void Preprocessor::PrintStats() {
181 std::cerr << "\n*** Preprocessor Stats:\n";
182 std::cerr << FileInfo.size() << " files tracked.\n";
183 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
184 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
185 NumOnceOnlyFiles += FileInfo[i].isImport;
186 if (MaxNumIncludes < FileInfo[i].NumIncludes)
187 MaxNumIncludes = FileInfo[i].NumIncludes;
188 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
189 }
190 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
191 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
192 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
193
194 std::cerr << NumDirectives << " directives found:\n";
195 std::cerr << " " << NumDefined << " #define.\n";
196 std::cerr << " " << NumUndefined << " #undef.\n";
197 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
198 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
199 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
200 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
201 std::cerr << " " << NumElse << " #else/#elif.\n";
202 std::cerr << " " << NumEndif << " #endif.\n";
203 std::cerr << " " << NumPragma << " #pragma.\n";
204 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
205
206 std::cerr << NumMacroExpanded << " macros expanded, "
207 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000208}
209
210//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000211// Token Spelling
212//===----------------------------------------------------------------------===//
213
214
215/// getSpelling() - Return the 'spelling' of this token. The spelling of a
216/// token are the characters used to represent the token in the source file
217/// after trigraph expansion and escaped-newline folding. In particular, this
218/// wants to get the true, uncanonicalized, spelling of things like digraphs
219/// UCNs, etc.
220std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
221 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
222
223 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000224 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 assert(TokStart && "Token has invalid location!");
226 if (!Tok.needsCleaning())
227 return std::string(TokStart, TokStart+Tok.getLength());
228
229 // Otherwise, hard case, relex the characters into the string.
230 std::string Result;
231 Result.reserve(Tok.getLength());
232
233 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
234 Ptr != End; ) {
235 unsigned CharSize;
236 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
237 Ptr += CharSize;
238 }
239 assert(Result.size() != unsigned(Tok.getLength()) &&
240 "NeedsCleaning flag set on something that didn't need cleaning!");
241 return Result;
242}
243
244/// getSpelling - This method is used to get the spelling of a token into a
245/// preallocated buffer, instead of as an std::string. The caller is required
246/// to allocate enough space for the token, which is guaranteed to be at least
247/// Tok.getLength() bytes long. The actual length of the token is returned.
248unsigned Preprocessor::getSpelling(const LexerToken &Tok, char *Buffer) const {
249 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
250
Chris Lattner50b497e2006-06-18 16:32:35 +0000251 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000252 assert(TokStart && "Token has invalid location!");
253
254 // If this token contains nothing interesting, return it directly.
255 if (!Tok.needsCleaning()) {
256 unsigned Size = Tok.getLength();
257 memcpy(Buffer, TokStart, Size);
258 return Size;
259 }
260 // Otherwise, hard case, relex the characters into the string.
261 std::string Result;
262 Result.reserve(Tok.getLength());
263
264 char *OutBuf = Buffer;
265 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
266 Ptr != End; ) {
267 unsigned CharSize;
268 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
269 Ptr += CharSize;
270 }
271 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
272 "NeedsCleaning flag set on something that didn't need cleaning!");
273
274 return OutBuf-Buffer;
275}
276
277//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000278// Source File Location Methods.
279//===----------------------------------------------------------------------===//
280
281
282/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
283/// return null on failure. isAngled indicates whether the file reference is
284/// for system #include's or not (i.e. using <> instead of "").
285const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000286 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000287 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000288 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000289 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000290 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000291
292 // If 'Filename' is absolute, check to see if it exists and no searching.
293 // FIXME: this should be a sys::Path interface, this doesn't handle things
294 // like C:\foo.txt right, nor win32 \\network\device\blah.
295 if (Filename[0] == '/') {
296 // If this was an #include_next "/absolute/file", fail.
297 if (FromDir) return 0;
298
299 // Otherwise, just return the file.
300 return FileMgr.getFile(Filename);
301 }
302
303 // Step #0, unless disabled, check to see if the file is in the #includer's
304 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000305 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000306 const FileEntry *CurFE =
307 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
308 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000309 // Concatenate the requested file onto the directory.
310 // FIXME: should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000311 if (const FileEntry *FE =
312 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000313 if (CurDirLookup)
314 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000315 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000316 CurDir = 0;
317
318 // This file is a system header or C++ unfriendly if the old file is.
319 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000320 return FE;
321 }
322 }
323 }
324
325 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000326 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000327
328 // If this is a #include_next request, start searching after the directory the
329 // file was found in.
330 if (FromDir)
331 i = FromDir-&SearchDirs[0];
332
333 // Check each directory in sequence to see if it contains this file.
334 for (; i != SearchDirs.size(); ++i) {
335 // Concatenate the requested file onto the directory.
336 // FIXME: should be in sys::Path.
337 if (const FileEntry *FE =
338 FileMgr.getFile(SearchDirs[i].getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000339 CurDir = &SearchDirs[i];
340
341 // This file is a system header or C++ unfriendly if the dir is.
342 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000343 return FE;
344 }
345 }
346
347 // Otherwise, didn't find it.
348 return 0;
349}
350
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000351/// isInPrimaryFile - Return true if we're in the top-level file, not in a
352/// #include.
353bool Preprocessor::isInPrimaryFile() const {
354 unsigned NumLexersFound = 0;
355 if (CurLexer && !CurLexer->Is_PragmaLexer)
356 ++NumLexersFound;
357
358 /// If there are any stacked lexers, we're in a #include.
359 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
360 if (IncludeMacroStack[i].TheLexer) {
361 if (!IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
362 if (++NumLexersFound > 1)
363 return false;
364 }
365 return NumLexersFound < 2;
366}
367
368/// getCurrentLexer - Return the current file lexer being lexed from. Note
369/// that this ignores any potentially active macro expansions and _Pragma
370/// expansions going on at the time.
371Lexer *Preprocessor::getCurrentFileLexer() const {
372 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
373
374 // Look for a stacked lexer.
375 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
376 Lexer *L = IncludeMacroStack[i].TheLexer;
377 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
378 return L;
379 }
380 return 0;
381}
382
383
Chris Lattner22eb9722006-06-18 05:43:12 +0000384/// EnterSourceFile - Add a source file to the top of the include stack and
385/// start lexing tokens from it instead of the current buffer. Return true
386/// on failure.
387void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattnerc8997182006-06-22 05:52:16 +0000388 const DirectoryLookup *CurDir) {
Chris Lattner69772b02006-07-02 20:34:39 +0000389 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000390 ++NumEnteredSourceFiles;
391
Chris Lattner69772b02006-07-02 20:34:39 +0000392 if (MaxIncludeStackDepth < IncludeMacroStack.size())
393 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000394
Chris Lattner22eb9722006-06-18 05:43:12 +0000395 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000396 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
397 EnterSourceFileWithLexer(TheLexer, CurDir);
398}
Chris Lattner22eb9722006-06-18 05:43:12 +0000399
Chris Lattner69772b02006-07-02 20:34:39 +0000400/// EnterSourceFile - Add a source file to the top of the include stack and
401/// start lexing tokens from it instead of the current buffer.
402void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
403 const DirectoryLookup *CurDir) {
404
405 // Add the current lexer to the include stack.
406 if (CurLexer || CurMacroExpander)
407 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
408 CurMacroExpander));
409
410 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000411 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000412 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000413
414 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerc8997182006-06-22 05:52:16 +0000415 if (FileChangeHandler) {
416 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
417
418 // Get the file entry for the current file.
419 if (const FileEntry *FE =
420 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
421 FileType = getFileInfo(FE).DirInfo;
422
Chris Lattner55a60952006-06-25 04:20:34 +0000423 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferStart),
424 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000425 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000426}
427
Chris Lattner69772b02006-07-02 20:34:39 +0000428
429
Chris Lattner22eb9722006-06-18 05:43:12 +0000430/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000431/// tokens from it instead of the current buffer.
432void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000433 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
434 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner69772b02006-07-02 20:34:39 +0000435 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
436 CurMacroExpander));
437 CurLexer = 0;
438 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000439
440 // TODO: Figure out arguments.
441
442 // Mark the macro as currently disabled, so that it is not recursively
443 // expanded.
444 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000445 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000446}
447
Chris Lattner22eb9722006-06-18 05:43:12 +0000448//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000449// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000450//===----------------------------------------------------------------------===//
451
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000452/// RegisterBuiltinMacro - Register the specified identifier in the identifier
453/// table and mark it as a builtin macro to be expanded.
454IdentifierTokenInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
455 // Get the identifier.
456 IdentifierTokenInfo *Id = getIdentifierInfo(Name);
457
458 // Mark it as being a macro that is builtin.
459 MacroInfo *MI = new MacroInfo(SourceLocation());
460 MI->setIsBuiltinMacro();
461 Id->setMacroInfo(MI);
462 return Id;
463}
464
465
Chris Lattner677757a2006-06-28 05:26:32 +0000466/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
467/// identifier table.
468void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000469 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000470 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000471 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
472 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000473 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000474
475 // GCC Extensions.
476 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
477 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000478 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000479
Chris Lattner69772b02006-07-02 20:34:39 +0000480 // FIXME: implement them all:
Chris Lattnerc1283b92006-07-01 23:16:30 +0000481//Pseudo #defines.
482 // __STDC__ 1 if !stdc_0_in_system_headers and "std"
483 // __STDC_VERSION__
484 // __STDC_HOSTED__
485 // __OBJC__
Chris Lattner22eb9722006-06-18 05:43:12 +0000486}
487
Chris Lattner677757a2006-06-28 05:26:32 +0000488
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000489/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
490/// expanded as a macro, handle it and return the next token as 'Identifier'.
491void Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
492 MacroInfo *MI) {
493 ++NumMacroExpanded;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000494
495 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
496 if (MI->isBuiltinMacro())
Chris Lattner69772b02006-07-02 20:34:39 +0000497 return ExpandBuiltinMacro(Identifier);
498
499 // If we started lexing a macro, enter the macro expansion body.
500 // FIXME: Read/Validate the argument list here!
501
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000502
503 // If this macro expands to no tokens, don't bother to push it onto the
504 // expansion stack, only to take it right back off.
505 if (MI->getNumTokens() == 0) {
506 // Ignore this macro use, just return the next token in the current
507 // buffer.
508 bool HadLeadingSpace = Identifier.hasLeadingSpace();
509 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
510
511 Lex(Identifier);
512
513 // If the identifier isn't on some OTHER line, inherit the leading
514 // whitespace/first-on-a-line property of this token. This handles
515 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
516 // empty.
517 if (!Identifier.isAtStartOfLine()) {
518 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
519 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
520 }
521 ++NumFastMacroExpanded;
522 return;
523
524 } else if (MI->getNumTokens() == 1 &&
525 // Don't handle identifiers if they need recursive expansion.
526 (MI->getReplacementToken(0).getIdentifierInfo() == 0 ||
527 !MI->getReplacementToken(0).getIdentifierInfo()->getMacroInfo())){
528 // FIXME: Function-style macros only if no arguments?
529
530 // Otherwise, if this macro expands into a single trivially-expanded
531 // token: expand it now. This handles common cases like
532 // "#define VAL 42".
533
534 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
535 // identifier to the expanded token.
536 bool isAtStartOfLine = Identifier.isAtStartOfLine();
537 bool hasLeadingSpace = Identifier.hasLeadingSpace();
538
539 // Remember where the token is instantiated.
540 SourceLocation InstantiateLoc = Identifier.getLocation();
541
542 // Replace the result token.
543 Identifier = MI->getReplacementToken(0);
544
545 // Restore the StartOfLine/LeadingSpace markers.
546 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
547 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
548
549 // Update the tokens location to include both its logical and physical
550 // locations.
551 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000552 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000553 Identifier.SetLocation(Loc);
554
555 // Since this is not an identifier token, it can't be macro expanded, so
556 // we're done.
557 ++NumFastMacroExpanded;
558 return;
559 }
560
561 // Start expanding the macro (FIXME, pass arguments).
562 EnterMacro(Identifier);
563
564 // Now that the macro is at the top of the include stack, ask the
565 // preprocessor to read the next token from it.
566 return Lex(Identifier);
567}
568
Chris Lattnerc673f902006-06-30 06:10:41 +0000569/// ComputeDATE_TIME - Compute the current time, enter it into the specified
570/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
571/// the identifier tokens inserted.
572static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
573 ScratchBuffer *ScratchBuf) {
574 time_t TT = time(0);
575 struct tm *TM = localtime(&TT);
576
577 static const char * const Months[] = {
578 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
579 };
580
581 char TmpBuffer[100];
582 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
583 TM->tm_year+1900);
584 DATELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
585
586 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
587 TIMELoc = ScratchBuf->getToken(TmpBuffer, strlen(TmpBuffer));
588}
589
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000590/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
591/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000592void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000593 // Figure out which token this is.
594 IdentifierTokenInfo *ITI = Tok.getIdentifierInfo();
595 assert(ITI && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000596
597 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
598 // lex the token after it.
599 if (ITI == Ident_Pragma)
600 return Handle_Pragma(Tok);
601
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000602 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000603
604 // Set up the return result.
Chris Lattner630b33c2006-07-01 22:46:53 +0000605 Tok.SetIdentifierInfo(0);
606 Tok.ClearFlag(LexerToken::NeedsCleaning);
607
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000608 if (ITI == Ident__LINE__) {
609 // __LINE__ expands to a simple numeric value.
610 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
611 unsigned Length = strlen(TmpBuffer);
612 Tok.SetKind(tok::numeric_constant);
613 Tok.SetLength(Length);
614 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000615 } else if (ITI == Ident__FILE__ || ITI == Ident__BASE_FILE__) {
616 SourceLocation Loc = Tok.getLocation();
617 if (ITI == Ident__BASE_FILE__) {
618 Diag(Tok, diag::ext_pp_base_file);
619 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
620 while (NextLoc.getFileID() != 0) {
621 Loc = NextLoc;
622 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
623 }
624 }
625
626 // FIXME: Escape this filename correctly.
627 std::string FN = '"' + SourceMgr.getSourceName(Loc) + '"';
Chris Lattner630b33c2006-07-01 22:46:53 +0000628 Tok.SetKind(tok::string_literal);
629 Tok.SetLength(FN.size());
630 Tok.SetLocation(ScratchBuf->getToken(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000631 } else if (ITI == Ident__DATE__) {
632 if (!DATELoc.isValid())
633 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
634 Tok.SetKind(tok::string_literal);
635 Tok.SetLength(strlen("\"Mmm dd yyyy\""));
636 Tok.SetLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc673f902006-06-30 06:10:41 +0000637 } else if (ITI == Ident__TIME__) {
638 if (!TIMELoc.isValid())
639 ComputeDATE_TIME(DATELoc, TIMELoc, ScratchBuf);
640 Tok.SetKind(tok::string_literal);
641 Tok.SetLength(strlen("\"hh:mm:ss\""));
642 Tok.SetLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc1283b92006-07-01 23:16:30 +0000643 } else if (ITI == Ident__INCLUDE_LEVEL__) {
644 Diag(Tok, diag::ext_pp_include_level);
645
646 // Compute the include depth of this token.
647 unsigned Depth = 0;
648 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
649 for (; Loc.getFileID() != 0; ++Depth)
650 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
651
652 // __INCLUDE_LEVEL__ expands to a simple numeric value.
653 sprintf(TmpBuffer, "%u", Depth);
654 unsigned Length = strlen(TmpBuffer);
655 Tok.SetKind(tok::numeric_constant);
656 Tok.SetLength(Length);
657 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Length, Tok.getLocation()));
Chris Lattner847e0e42006-07-01 23:49:16 +0000658 } else if (ITI == Ident__TIMESTAMP__) {
659 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
660 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
661 Diag(Tok, diag::ext_pp_timestamp);
662
663 // Get the file that we are lexing out of. If we're currently lexing from
664 // a macro, dig into the include stack.
665 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000666 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000667
668 if (TheLexer)
669 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
670
671 // If this file is older than the file it depends on, emit a diagnostic.
672 const char *Result;
673 if (CurFile) {
674 time_t TT = CurFile->getModificationTime();
675 struct tm *TM = localtime(&TT);
676 Result = asctime(TM);
677 } else {
678 Result = "??? ??? ?? ??:??:?? ????\n";
679 }
680 TmpBuffer[0] = '"';
681 strcpy(TmpBuffer+1, Result);
682 unsigned Len = strlen(TmpBuffer);
683 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
684 Tok.SetKind(tok::string_literal);
685 Tok.SetLength(Len);
686 Tok.SetLocation(ScratchBuf->getToken(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000687 } else {
688 assert(0 && "Unknown identifier!");
689 }
690}
Chris Lattner677757a2006-06-28 05:26:32 +0000691
692//===----------------------------------------------------------------------===//
693// Lexer Event Handling.
694//===----------------------------------------------------------------------===//
695
696/// HandleIdentifier - This callback is invoked when the lexer reads an
697/// identifier. This callback looks up the identifier in the map and/or
698/// potentially macro expands it or turns it into a named token (like 'for').
699void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
700 if (Identifier.getIdentifierInfo() == 0) {
701 // If we are skipping tokens (because we are in a #if 0 block), there will
702 // be no identifier info, just return the token.
703 assert(isSkipping() && "Token isn't an identifier?");
704 return;
705 }
706 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
707
708 // If this identifier was poisoned, and if it was not produced from a macro
709 // expansion, emit an error.
710 if (ITI.isPoisoned() && CurLexer)
711 Diag(Identifier, diag::err_pp_used_poisoned_id);
712
713 if (MacroInfo *MI = ITI.getMacroInfo())
714 if (MI->isEnabled() && !DisableMacroExpansion)
715 return HandleMacroExpandedIdentifier(Identifier, MI);
716
717 // Change the kind of this identifier to the appropriate token kind, e.g.
718 // turning "for" into a keyword.
719 Identifier.SetKind(ITI.getTokenID());
720
721 // If this is an extension token, diagnose its use.
722 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
723}
724
Chris Lattner22eb9722006-06-18 05:43:12 +0000725/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
726/// the current file. This either returns the EOF token or pops a level off
727/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000728void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000729 assert(!CurMacroExpander &&
730 "Ending a file when currently in a macro!");
731
732 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
733 // this is an error condition. Just return the EOF token up to
734 // SkipExcludedConditionalBlock. The Lexer will have already have issued
735 // errors for the unterminated #if's on the conditional stack.
736 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000737 Result.StartToken();
738 CurLexer->BufferPtr = CurLexer->BufferEnd;
739 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000740 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000741 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000742 }
743
744 // If this is a #include'd file, pop it off the include stack and continue
745 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000746 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000747 // We're done with the #included file.
748 delete CurLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000749 CurLexer = IncludeMacroStack.back().TheLexer;
750 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
751 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
752 IncludeMacroStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000753
754 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000755 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000756 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
757
758 // Get the file entry for the current file.
759 if (const FileEntry *FE =
760 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
761 FileType = getFileInfo(FE).DirInfo;
762
Chris Lattner0c885f52006-06-21 06:50:18 +0000763 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000764 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000765 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000766
Chris Lattner22eb9722006-06-18 05:43:12 +0000767 return Lex(Result);
768 }
769
Chris Lattnerd01e2912006-06-18 16:22:51 +0000770 Result.StartToken();
771 CurLexer->BufferPtr = CurLexer->BufferEnd;
772 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000773 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000774
775 // We're done with the #included file.
776 delete CurLexer;
777 CurLexer = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000778}
779
780/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000781/// the current macro line.
782void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000783 assert(CurMacroExpander && !CurLexer &&
784 "Ending a macro when currently in a #include file!");
785
786 // Mark macro not ignored now that it is no longer being expanded.
787 CurMacroExpander->getMacro().EnableMacro();
788 delete CurMacroExpander;
789
Chris Lattner69772b02006-07-02 20:34:39 +0000790 // Handle this like a #include file being popped off the stack.
791 CurMacroExpander = 0;
792 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000793}
794
795
796//===----------------------------------------------------------------------===//
797// Utility Methods for Preprocessor Directive Handling.
798//===----------------------------------------------------------------------===//
799
800/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
801/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000802void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000803 LexerToken Tmp;
804 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000805 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000806 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000807}
808
809/// ReadMacroName - Lex and validate a macro name, which occurs after a
810/// #define or #undef. This sets the token kind to eom and discards the rest
811/// of the macro line if the macro name is invalid.
Chris Lattnercb283342006-06-18 06:48:37 +0000812void Preprocessor::ReadMacroName(LexerToken &MacroNameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000813 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000814 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000815
816 // Missing macro name?
817 if (MacroNameTok.getKind() == tok::eom)
818 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
819
820 if (MacroNameTok.getIdentifierInfo() == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000821 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000822 // Fall through on error.
823 } else if (0) {
824 // FIXME: Error if defining a C++ named operator.
825
826 } else if (0) {
827 // FIXME: Error if defining "defined", "__DATE__", and other predef macros
828 // in C99 6.10.8.4.
829 } else {
830 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000831 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000832 }
833
834
835 // Invalid macro name, read and discard the rest of the line. Then set the
836 // token kind to tok::eom.
837 MacroNameTok.SetKind(tok::eom);
838 return DiscardUntilEndOfDirective();
839}
840
841/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
842/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000843void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000844 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000845 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000846 // There should be no tokens after the directive, but we allow them as an
847 // extension.
848 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000849 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
850 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000851 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000852}
853
854
855
856/// SkipExcludedConditionalBlock - We just read a #if or related directive and
857/// decided that the subsequent tokens are in the #if'd out portion of the
858/// file. Lex the rest of the file, until we see an #endif. If
859/// FoundNonSkipPortion is true, then we have already emitted code for part of
860/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
861/// is true, then #else directives are ok, if not, then we have already seen one
862/// so a #else directive is a duplicate. When this returns, the caller can lex
863/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000864void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000865 bool FoundNonSkipPortion,
866 bool FoundElse) {
867 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +0000868 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +0000869 "Lexing a macro, not a file?");
870
871 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
872 FoundNonSkipPortion, FoundElse);
873
874 // Know that we are going to be skipping tokens. Set this flag to indicate
875 // this, which has a couple of effects:
876 // 1. If EOF of the current lexer is found, the include stack isn't popped.
877 // 2. Identifier information is not looked up for identifier tokens. As an
878 // effect of this, implicit macro expansion is naturally disabled.
879 // 3. "#" tokens at the start of a line are treated as normal tokens, not
880 // implicitly transformed by the lexer.
881 // 4. All notes, warnings, and extension messages are disabled.
882 //
883 SkippingContents = true;
884 LexerToken Tok;
885 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000886 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000887
888 // If this is the end of the buffer, we have an error. The lexer will have
889 // already handled this error condition, so just return and let the caller
890 // lex after this #include.
891 if (Tok.getKind() == tok::eof) break;
892
893 // If this token is not a preprocessor directive, just skip it.
894 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
895 continue;
896
897 // We just parsed a # character at the start of a line, so we're in
898 // directive mode. Tell the lexer this so any newlines we see will be
899 // converted into an EOM token (this terminates the macro).
900 CurLexer->ParsingPreprocessorDirective = true;
901
902 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000903 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000904
905 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
906 // something bogus), skip it.
907 if (Tok.getKind() != tok::identifier) {
908 CurLexer->ParsingPreprocessorDirective = false;
909 continue;
910 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000911
Chris Lattner22eb9722006-06-18 05:43:12 +0000912 // If the first letter isn't i or e, it isn't intesting to us. We know that
913 // this is safe in the face of spelling differences, because there is no way
914 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000915 // allows us to avoid looking up the identifier info for #define/#undef and
916 // other common directives.
917 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
918 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000919 if (FirstChar >= 'a' && FirstChar <= 'z' &&
920 FirstChar != 'i' && FirstChar != 'e') {
921 CurLexer->ParsingPreprocessorDirective = false;
922 continue;
923 }
924
Chris Lattnere60165f2006-06-22 06:36:29 +0000925 // Get the identifier name without trigraphs or embedded newlines. Note
926 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
927 // when skipping.
928 // TODO: could do this with zero copies in the no-clean case by using
929 // strncmp below.
930 char Directive[20];
931 unsigned IdLen;
932 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
933 IdLen = Tok.getLength();
934 memcpy(Directive, RawCharData, IdLen);
935 Directive[IdLen] = 0;
936 } else {
937 std::string DirectiveStr = getSpelling(Tok);
938 IdLen = DirectiveStr.size();
939 if (IdLen >= 20) {
940 CurLexer->ParsingPreprocessorDirective = false;
941 continue;
942 }
943 memcpy(Directive, &DirectiveStr[0], IdLen);
944 Directive[IdLen] = 0;
945 }
946
Chris Lattner22eb9722006-06-18 05:43:12 +0000947 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000948 if ((IdLen == 2) || // "if"
949 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
950 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000951 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
952 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000953 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000954 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000955 /*foundnonskip*/false,
956 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000957 }
958 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000959 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000960 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000961 PPConditionalInfo CondInfo;
962 CondInfo.WasSkipping = true; // Silence bogus warning.
963 bool InCond = CurLexer->popConditionalLevel(CondInfo);
964 assert(!InCond && "Can't be skipping if not in a conditional!");
965
966 // If we popped the outermost skipping block, we're done skipping!
967 if (!CondInfo.WasSkipping)
968 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000969 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000970 // #else directive in a skipping conditional. If not in some other
971 // skipping conditional, and if #else hasn't already been seen, enter it
972 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000973 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000974 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
975
976 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000977 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000978
979 // Note that we've seen a #else in this conditional.
980 CondInfo.FoundElse = true;
981
982 // If the conditional is at the top level, and the #if block wasn't
983 // entered, enter the #else block now.
984 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
985 CondInfo.FoundNonSkip = true;
986 break;
987 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000988 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +0000989 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
990
991 bool ShouldEnter;
992 // If this is in a skipping block or if we're already handled this #if
993 // block, don't bother parsing the condition.
994 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +0000995 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000996 ShouldEnter = false;
997 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +0000998 // Restore the value of SkippingContents so that identifiers are
999 // looked up, etc, inside the #elif expression.
1000 assert(SkippingContents && "We have to be skipping here!");
1001 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001002 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001003 SkippingContents = true;
1004 }
1005
1006 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001007 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001008
1009 // If this condition is true, enter it!
1010 if (ShouldEnter) {
1011 CondInfo.FoundNonSkip = true;
1012 break;
1013 }
1014 }
1015 }
1016
1017 CurLexer->ParsingPreprocessorDirective = false;
1018 }
1019
1020 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1021 // of the file, just stop skipping and return to lexing whatever came after
1022 // the #if block.
1023 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001024}
1025
1026//===----------------------------------------------------------------------===//
1027// Preprocessor Directive Handling.
1028//===----------------------------------------------------------------------===//
1029
1030/// HandleDirective - This callback is invoked when the lexer sees a # token
1031/// at the start of a line. This consumes the directive, modifies the
1032/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1033/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001034void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001035 // FIXME: TRADITIONAL: # with whitespace before it not recognized by K&R?
1036
1037 // We just parsed a # character at the start of a line, so we're in directive
1038 // mode. Tell the lexer this so any newlines we see will be converted into an
1039 // EOM token (this terminates the macro).
1040 CurLexer->ParsingPreprocessorDirective = true;
1041
1042 ++NumDirectives;
1043
1044 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001045 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001046
1047 switch (Result.getKind()) {
1048 default: break;
1049 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001050 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001051
1052#if 0
1053 case tok::numeric_constant:
1054 // FIXME: implement # 7 line numbers!
1055 break;
1056#endif
1057 case tok::kw_else:
1058 return HandleElseDirective(Result);
1059 case tok::kw_if:
1060 return HandleIfDirective(Result);
1061 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +00001062 // Get the identifier name without trigraphs or embedded newlines.
1063 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +00001065 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 case 4:
Chris Lattner40931922006-06-22 06:14:04 +00001067 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001068 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +00001069 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001070 return HandleElifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001071 if (Directive[0] == 's' && !strcmp(Directive, "sccs")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001072 isExtension = true; // FIXME: implement #sccs
Chris Lattner22eb9722006-06-18 05:43:12 +00001073 // SCCS is the same as #ident.
1074 }
1075 break;
1076 case 5:
Chris Lattner40931922006-06-22 06:14:04 +00001077 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001078 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001079 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001081 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001082 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001083 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001084 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +00001085 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattnerb8761832006-06-24 21:31:03 +00001086 isExtension = true; // FIXME: implement #ident
Chris Lattner22eb9722006-06-18 05:43:12 +00001087 break;
1088 case 6:
Chris Lattner40931922006-06-22 06:14:04 +00001089 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001090 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +00001091 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001092 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +00001093 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +00001094 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +00001095 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
Chris Lattner69772b02006-07-02 20:34:39 +00001096 return HandlePragmaDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001097 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
1098 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 break;
1100 case 7:
Chris Lattner40931922006-06-22 06:14:04 +00001101 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
1102 return HandleIncludeDirective(Result); // Handle #include.
1103 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +00001104 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +00001105 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +00001106 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001107 break;
1108 case 8:
Chris Lattner40931922006-06-22 06:14:04 +00001109 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001110 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 }
1112 break;
1113 case 12:
Chris Lattner40931922006-06-22 06:14:04 +00001114 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
1115 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +00001116 break;
1117 }
1118 break;
1119 }
1120
1121 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001122 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001123
1124 // Read the rest of the PP line.
1125 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001126 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001127 } while (Result.getKind() != tok::eom);
1128
1129 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001130}
1131
Chris Lattnercb283342006-06-18 06:48:37 +00001132void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 bool isWarning) {
1134 // Read the rest of the line raw. We do this because we don't want macros
1135 // to be expanded and we don't require that the tokens be valid preprocessing
1136 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1137 // collapse multiple consequtive white space between tokens, but this isn't
1138 // specified by the standard.
1139 std::string Message = CurLexer->ReadToEndOfLine();
1140
1141 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1142 return Diag(Result, DiagID, Message);
1143}
1144
Chris Lattnerb8761832006-06-24 21:31:03 +00001145//===----------------------------------------------------------------------===//
1146// Preprocessor Include Directive Handling.
1147//===----------------------------------------------------------------------===//
1148
Chris Lattner22eb9722006-06-18 05:43:12 +00001149/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1150/// file to be included from the lexer, then include it! This is a common
1151/// routine with functionality shared between #include, #include_next and
1152/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001153void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001154 const DirectoryLookup *LookupFrom,
1155 bool isImport) {
1156 ++NumIncluded;
1157 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001158 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001159
1160 // If the token kind is EOM, the error has already been diagnosed.
1161 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001162 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001163
1164 // Verify that there is nothing after the filename, other than EOM. Use the
1165 // preprocessor to lex this in case lexing the filename entered a macro.
1166 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001167
1168 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001169 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001170 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1171
Chris Lattner269c2322006-06-25 06:23:00 +00001172 // Find out whether the filename is <x> or "x".
1173 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001174
1175 // Remove the quotes.
1176 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1177
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001179 const DirectoryLookup *CurDir;
1180 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001181 if (File == 0)
1182 return Diag(FilenameTok, diag::err_pp_file_not_found);
1183
1184 // Get information about this file.
1185 PerFileInfo &FileInfo = getFileInfo(File);
1186
1187 // If this is a #import directive, check that we have not already imported
1188 // this header.
1189 if (isImport) {
1190 // If this has already been imported, don't import it again.
1191 FileInfo.isImport = true;
1192
1193 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +00001194 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001195 } else {
1196 // Otherwise, if this is a #include of a file that was previously #import'd
1197 // or if this is the second #include of a #pragma once file, ignore it.
1198 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +00001199 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001200 }
1201
1202 // Look up the file, create a File ID for it.
1203 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +00001204 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001205 if (FileID == 0)
1206 return Diag(FilenameTok, diag::err_pp_file_not_found);
1207
1208 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001209 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001210
1211 // Increment the number of times this file has been included.
1212 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +00001213}
1214
1215/// HandleIncludeNextDirective - Implements #include_next.
1216///
Chris Lattnercb283342006-06-18 06:48:37 +00001217void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1218 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001219
1220 // #include_next is like #include, except that we start searching after
1221 // the current found directory. If we can't do this, issue a
1222 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001223 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001224 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001225 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001226 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001227 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001228 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001229 } else {
1230 // Start looking up in the next directory.
1231 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001232 }
1233
1234 return HandleIncludeDirective(IncludeNextTok, Lookup);
1235}
1236
1237/// HandleImportDirective - Implements #import.
1238///
Chris Lattnercb283342006-06-18 06:48:37 +00001239void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1240 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001241
1242 return HandleIncludeDirective(ImportTok, 0, true);
1243}
1244
Chris Lattnerb8761832006-06-24 21:31:03 +00001245//===----------------------------------------------------------------------===//
1246// Preprocessor Macro Directive Handling.
1247//===----------------------------------------------------------------------===//
1248
Chris Lattner22eb9722006-06-18 05:43:12 +00001249/// HandleDefineDirective - Implements #define. This consumes the entire macro
1250/// line then lets the caller lex the next real token.
1251///
Chris Lattnercb283342006-06-18 06:48:37 +00001252void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001253 ++NumDefined;
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
Chris Lattner50b497e2006-06-18 16:32:35 +00001261 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001262
1263 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001264 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001265
1266 if (Tok.getKind() == tok::eom) {
1267 // If there is no body to this macro, we have no special handling here.
1268 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1269 // This is a function-like macro definition.
1270 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001271 return DiscardUntilEndOfDirective();
1272
1273 } else if (!Tok.hasLeadingSpace()) {
1274 // C99 requires whitespace between the macro definition and the body. Emit
1275 // a diagnostic for something like "#define X+".
1276 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001277 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 } else {
1279 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1280 // one in some cases!
1281 }
1282 } else {
1283 // This is a normal token with leading space. Clear the leading space
1284 // marker on the first token to get proper expansion.
1285 Tok.ClearFlag(LexerToken::LeadingSpace);
1286 }
1287
1288 // Read the rest of the macro body.
1289 while (Tok.getKind() != tok::eom) {
1290 MI->AddTokenToBody(Tok);
1291
1292 // FIXME: See create_iso_definition.
1293
1294 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001295 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 }
1297
1298 // Finally, if this identifier already had a macro defined for it, verify that
1299 // the macro bodies are identical and free the old definition.
1300 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner677757a2006-06-28 05:26:32 +00001301 if (OtherMI->isBuiltinMacro())
1302 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1303
1304
Chris Lattner22eb9722006-06-18 05:43:12 +00001305 // FIXME: Verify the definition is the same.
1306 // Macros must be identical. This means all tokes and whitespace separation
1307 // must be the same.
1308 delete OtherMI;
1309 }
1310
1311 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001312}
1313
1314
1315/// HandleUndefDirective - Implements #undef.
1316///
Chris Lattnercb283342006-06-18 06:48:37 +00001317void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001318 ++NumUndefined;
1319 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001320 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001321
1322 // Error reading macro name? If so, diagnostic already issued.
1323 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001324 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001325
1326 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001327 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001328
1329 // Okay, we finally have a valid identifier to undef.
1330 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1331
1332 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001333 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001334
1335 if (MI->isBuiltinMacro())
1336 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001337
1338#if 0 // FIXME: implement warn_unused_macros.
1339 if (CPP_OPTION (pfile, warn_unused_macros))
1340 _cpp_warn_if_unused_macro (pfile, node, NULL);
1341#endif
1342
1343 // Free macro definition.
1344 delete MI;
1345 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001346}
1347
1348
Chris Lattnerb8761832006-06-24 21:31:03 +00001349//===----------------------------------------------------------------------===//
1350// Preprocessor Conditional Directive Handling.
1351//===----------------------------------------------------------------------===//
1352
Chris Lattner22eb9722006-06-18 05:43:12 +00001353/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1354/// true when this is a #ifndef directive.
1355///
Chris Lattnercb283342006-06-18 06:48:37 +00001356void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001357 ++NumIf;
1358 LexerToken DirectiveTok = Result;
1359
1360 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001361 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001362
1363 // Error reading macro name? If so, diagnostic already issued.
1364 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001365 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001366
1367 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001368 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001369
1370 // Should we include the stuff contained by this directive?
1371 if (!MacroNameTok.getIdentifierInfo()->getMacroInfo() == isIfndef) {
1372 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001373 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001374 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001375 } else {
1376 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001377 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001378 /*Foundnonskip*/false,
1379 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 }
1381}
1382
1383/// HandleIfDirective - Implements the #if directive.
1384///
Chris Lattnercb283342006-06-18 06:48:37 +00001385void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001386 ++NumIf;
Chris Lattner7966aaf2006-06-18 06:50:36 +00001387 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001388
1389 // Should we include the stuff contained by this directive?
1390 if (ConditionalTrue) {
1391 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001392 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001394 } else {
1395 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001396 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001397 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001398 }
1399}
1400
1401/// HandleEndifDirective - Implements the #endif directive.
1402///
Chris Lattnercb283342006-06-18 06:48:37 +00001403void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001404 ++NumEndif;
1405 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001406 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001407
1408 PPConditionalInfo CondInfo;
1409 if (CurLexer->popConditionalLevel(CondInfo)) {
1410 // No conditionals on the stack: this is an #endif without an #if.
1411 return Diag(EndifToken, diag::err_pp_endif_without_if);
1412 }
1413
1414 assert(!CondInfo.WasSkipping && !isSkipping() &&
1415 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001416}
1417
1418
Chris Lattnercb283342006-06-18 06:48:37 +00001419void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001420 ++NumElse;
1421 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001422 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001423
1424 PPConditionalInfo CI;
1425 if (CurLexer->popConditionalLevel(CI))
1426 return Diag(Result, diag::pp_err_else_without_if);
1427
1428 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001429 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001430
1431 // Finally, skip the rest of the contents of this block and return the first
1432 // token after it.
1433 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1434 /*FoundElse*/true);
1435}
1436
Chris Lattnercb283342006-06-18 06:48:37 +00001437void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001438 ++NumElse;
1439 // #elif directive in a non-skipping conditional... start skipping.
1440 // We don't care what the condition is, because we will always skip it (since
1441 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001442 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001443
1444 PPConditionalInfo CI;
1445 if (CurLexer->popConditionalLevel(CI))
1446 return Diag(ElifToken, diag::pp_err_elif_without_if);
1447
1448 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001449 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001450
1451 // Finally, skip the rest of the contents of this block and return the first
1452 // token after it.
1453 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1454 /*FoundElse*/CI.FoundElse);
1455}
Chris Lattnerb8761832006-06-24 21:31:03 +00001456
1457
1458//===----------------------------------------------------------------------===//
1459// Preprocessor Pragma Directive Handling.
1460//===----------------------------------------------------------------------===//
1461
Chris Lattner69772b02006-07-02 20:34:39 +00001462/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
1463/// rest of the pragma, passing it to the registered pragma handlers.
1464void Preprocessor::HandlePragmaDirective() {
Chris Lattnerb8761832006-06-24 21:31:03 +00001465 ++NumPragma;
1466
1467 // Invoke the first level of pragma handlers which reads the namespace id.
1468 LexerToken Tok;
1469 PragmaHandlers->HandlePragma(*this, Tok);
1470
1471 // If the pragma handler didn't read the rest of the line, consume it now.
Chris Lattner17862172006-06-24 22:12:56 +00001472 if (CurLexer->ParsingPreprocessorDirective)
1473 DiscardUntilEndOfDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001474}
1475
Chris Lattner69772b02006-07-02 20:34:39 +00001476/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
1477/// return the first token after the directive. The _Pragma token has just
1478/// been read into 'Tok'.
1479void Preprocessor::Handle_Pragma(LexerToken &Tok) {
1480 // Remember the pragma token location.
1481 SourceLocation PragmaLoc = Tok.getLocation();
1482
1483 // Read the '('.
1484 Lex(Tok);
1485 if (Tok.getKind() != tok::l_paren)
1486 return Diag(PragmaLoc, diag::err__Pragma_malformed);
1487
1488 // Read the '"..."'.
1489 Lex(Tok);
1490 if (Tok.getKind() != tok::string_literal)
1491 return Diag(PragmaLoc, diag::err__Pragma_malformed);
1492
1493 // Remember the string.
1494 std::string StrVal = getSpelling(Tok);
1495 SourceLocation StrLoc = Tok.getLocation();
1496
1497 // Read the ')'.
1498 Lex(Tok);
1499 if (Tok.getKind() != tok::r_paren)
1500 return Diag(PragmaLoc, diag::err__Pragma_malformed);
1501
1502 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
1503 if (StrVal[0] == 'L') // Remove L prefix.
1504 StrVal.erase(StrVal.begin());
1505 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
1506 "Invalid string token!");
1507
1508 // Remove the front quote, replacing it with a space, so that the pragma
1509 // contents appear to have a space before them.
1510 StrVal[0] = ' ';
1511
1512 // Replace the terminating quote with a \n\0.
1513 StrVal[StrVal.size()-1] = '\n';
1514 StrVal += '\0';
1515
1516 // Remove escaped quotes and escapes.
1517 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
1518 if (StrVal[i] == '\\' &&
1519 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
1520 // \\ -> '\' and \" -> '"'.
1521 StrVal.erase(StrVal.begin()+i);
1522 --e;
1523 }
1524 }
1525
1526 // Plop the string (including the trailing null) into a buffer where we can
1527 // lex it.
1528 SourceLocation TokLoc = ScratchBuf->getToken(&StrVal[0], StrVal.size());
1529 const char *StrData = SourceMgr.getCharacterData(TokLoc);
1530
1531 // FIXME: Create appropriate mapping info for this FileID, so that we know the
1532 // tokens are coming out of the input string (StrLoc).
1533 unsigned FileID = TokLoc.getFileID();
1534 assert(FileID && "Could not create FileID for predefines?");
1535
1536 // Make and enter a lexer object so that we lex and expand the tokens just
1537 // like any others.
1538 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, *this,
1539 StrData, StrData+StrVal.size()-1 /* no null */);
1540 EnterSourceFileWithLexer(TL, 0);
1541
1542 // Ensure that the lexer thinks it is inside a directive, so that end \n will
1543 // return an EOM token.
1544 TL->ParsingPreprocessorDirective = true;
1545
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001546 // This lexer really is for _Pragma.
1547 TL->Is_PragmaLexer = true;
1548
Chris Lattner69772b02006-07-02 20:34:39 +00001549 // With everything set up, lex this as a #pragma directive.
1550 HandlePragmaDirective();
1551
1552 // Finally, return whatever came after the pragma directive.
1553 return Lex(Tok);
1554}
1555
1556
1557
Chris Lattnerb8761832006-06-24 21:31:03 +00001558/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
Chris Lattner17862172006-06-24 22:12:56 +00001559///
Chris Lattnerb8761832006-06-24 21:31:03 +00001560void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
Chris Lattner69772b02006-07-02 20:34:39 +00001561 if (isInPrimaryFile()) {
Chris Lattnerb8761832006-06-24 21:31:03 +00001562 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
1563 return;
1564 }
Chris Lattner17862172006-06-24 22:12:56 +00001565
1566 // FIXME: implement the _Pragma thing.
1567 assert(CurLexer && "Cannot have a pragma in a macro expansion yet!");
1568
1569 // Mark the file as a once-only file now.
1570 const FileEntry *File =
1571 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
1572 getFileInfo(File).isImport = true;
Chris Lattnerb8761832006-06-24 21:31:03 +00001573}
1574
Chris Lattner17862172006-06-24 22:12:56 +00001575/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
1576///
1577void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
1578 LexerToken Tok;
1579 assert(!SkippingContents && "Why are we handling pragmas while skipping?");
1580 while (1) {
1581 // Read the next token to poison. While doing this, pretend that we are
1582 // skipping while reading the identifier to poison.
1583 // This avoids errors on code like:
1584 // #pragma GCC poison X
1585 // #pragma GCC poison X
1586 SkippingContents = true;
1587 LexUnexpandedToken(Tok);
1588 SkippingContents = false;
1589
1590 // If we reached the end of line, we're done.
1591 if (Tok.getKind() == tok::eom) return;
1592
1593 // Can only poison identifiers.
1594 if (Tok.getKind() != tok::identifier) {
1595 Diag(Tok, diag::err_pp_invalid_poison);
1596 return;
1597 }
1598
1599 // Look up the identifier info for the token.
1600 std::string TokStr = getSpelling(Tok);
1601 IdentifierTokenInfo *II =
1602 getIdentifierInfo(&TokStr[0], &TokStr[0]+TokStr.size());
1603
1604 // Already poisoned.
1605 if (II->isPoisoned()) continue;
1606
1607 // If this is a macro identifier, emit a warning.
1608 if (II->getMacroInfo())
1609 Diag(Tok, diag::pp_poisoning_existing_macro);
1610
1611 // Finally, poison it!
1612 II->setIsPoisoned();
1613 }
1614}
Chris Lattnerb8761832006-06-24 21:31:03 +00001615
Chris Lattner269c2322006-06-25 06:23:00 +00001616/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
1617/// that the whole directive has been parsed.
Chris Lattner55a60952006-06-25 04:20:34 +00001618void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
Chris Lattner69772b02006-07-02 20:34:39 +00001619 if (isInPrimaryFile()) {
Chris Lattner55a60952006-06-25 04:20:34 +00001620 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
1621 return;
1622 }
1623
1624 // Mark the file as a system header.
1625 const FileEntry *File =
1626 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
1627 getFileInfo(File).DirInfo = DirectoryLookup::SystemHeaderDir;
1628
1629
1630 // Notify the client, if desired, that we are in a new source file.
1631 if (FileChangeHandler)
1632 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1633 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
1634}
1635
Chris Lattner269c2322006-06-25 06:23:00 +00001636/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
1637///
1638void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
1639 LexerToken FilenameTok;
1640 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
1641
1642 // If the token kind is EOM, the error has already been diagnosed.
1643 if (FilenameTok.getKind() == tok::eom)
1644 return;
1645
1646 // Find out whether the filename is <x> or "x".
1647 bool isAngled = Filename[0] == '<';
1648
1649 // Remove the quotes.
1650 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1651
1652 // Search include directories.
1653 const DirectoryLookup *CurDir;
1654 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
1655 if (File == 0)
1656 return Diag(FilenameTok, diag::err_pp_file_not_found);
1657
Chris Lattnerecfeafe2006-07-02 21:26:45 +00001658 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner269c2322006-06-25 06:23:00 +00001659 const FileEntry *CurFile =
1660 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
1661
1662 // If this file is older than the file it depends on, emit a diagnostic.
1663 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
1664 // Lex tokens at the end of the message and include them in the message.
1665 std::string Message;
1666 Lex(DependencyTok);
1667 while (DependencyTok.getKind() != tok::eom) {
1668 Message += getSpelling(DependencyTok) + " ";
1669 Lex(DependencyTok);
1670 }
1671
1672 Message.erase(Message.end()-1);
1673 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
1674 }
1675}
1676
1677
Chris Lattnerb8761832006-06-24 21:31:03 +00001678/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
1679/// If 'Namespace' is non-null, then it is a token required to exist on the
1680/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
1681void Preprocessor::AddPragmaHandler(const char *Namespace,
1682 PragmaHandler *Handler) {
1683 PragmaNamespace *InsertNS = PragmaHandlers;
1684
1685 // If this is specified to be in a namespace, step down into it.
1686 if (Namespace) {
1687 IdentifierTokenInfo *NSID = getIdentifierInfo(Namespace);
1688
1689 // If there is already a pragma handler with the name of this namespace,
1690 // we either have an error (directive with the same name as a namespace) or
1691 // we already have the namespace to insert into.
1692 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
1693 InsertNS = Existing->getIfNamespace();
1694 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
1695 " handler with the same name!");
1696 } else {
1697 // Otherwise, this namespace doesn't exist yet, create and insert the
1698 // handler for it.
1699 InsertNS = new PragmaNamespace(NSID);
1700 PragmaHandlers->AddPragma(InsertNS);
1701 }
1702 }
1703
1704 // Check to make sure we don't already have a pragma for this identifier.
1705 assert(!InsertNS->FindHandler(Handler->getName()) &&
1706 "Pragma handler already exists for this identifier!");
1707 InsertNS->AddPragma(Handler);
1708}
1709
Chris Lattner17862172006-06-24 22:12:56 +00001710namespace {
Chris Lattner55a60952006-06-25 04:20:34 +00001711struct PragmaOnceHandler : public PragmaHandler {
Chris Lattnerb8761832006-06-24 21:31:03 +00001712 PragmaOnceHandler(const IdentifierTokenInfo *OnceID) : PragmaHandler(OnceID){}
1713 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
1714 PP.CheckEndOfDirective("#pragma once");
1715 PP.HandlePragmaOnce(OnceTok);
1716 }
1717};
1718
Chris Lattner55a60952006-06-25 04:20:34 +00001719struct PragmaPoisonHandler : public PragmaHandler {
Chris Lattner17862172006-06-24 22:12:56 +00001720 PragmaPoisonHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
1721 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
1722 PP.HandlePragmaPoison(PoisonTok);
1723 }
1724};
Chris Lattner55a60952006-06-25 04:20:34 +00001725
1726struct PragmaSystemHeaderHandler : public PragmaHandler {
1727 PragmaSystemHeaderHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID){}
1728 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
1729 PP.HandlePragmaSystemHeader(SHToken);
1730 PP.CheckEndOfDirective("#pragma");
1731 }
1732};
Chris Lattner269c2322006-06-25 06:23:00 +00001733struct PragmaDependencyHandler : public PragmaHandler {
1734 PragmaDependencyHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
1735 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
1736 PP.HandlePragmaDependency(DepToken);
1737 }
1738};
Chris Lattner17862172006-06-24 22:12:56 +00001739}
1740
Chris Lattnerb8761832006-06-24 21:31:03 +00001741
1742/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1743/// #pragma GCC poison/system_header/dependency and #pragma once.
1744void Preprocessor::RegisterBuiltinPragmas() {
1745 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
Chris Lattner17862172006-06-24 22:12:56 +00001746 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
Chris Lattner55a60952006-06-25 04:20:34 +00001747 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
1748 getIdentifierInfo("system_header")));
Chris Lattner269c2322006-06-25 06:23:00 +00001749 AddPragmaHandler("GCC", new PragmaDependencyHandler(
1750 getIdentifierInfo("dependency")));
Chris Lattnerb8761832006-06-24 21:31:03 +00001751}