blob: 94659cbb8d19fc15a24a1e9da3087482a1e4ded2 [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 Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Basic/Diagnostic.h"
40#include "clang/Basic/FileManager.h"
41#include "clang/Basic/SourceManager.h"
42#include <iostream>
43using namespace llvm;
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47
48Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
49 FileManager &FM, SourceManager &SM)
50 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
51 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000052 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner22eb9722006-06-18 05:43:12 +000053 // Clear stats.
54 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
55 NumIf = NumElse = NumEndif = 0;
56 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
57 MaxIncludeStackDepth = MaxMacroStackDepth = 0;
58 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000059
Chris Lattner22eb9722006-06-18 05:43:12 +000060 // Macro expansion is enabled.
61 DisableMacroExpansion = false;
62 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000063
64 // There is no file-change handler yet.
65 FileChangeHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000066
67 // Initialize the pragma handlers.
68 PragmaHandlers = new PragmaNamespace(0);
69 RegisterBuiltinPragmas();
Chris Lattner22eb9722006-06-18 05:43:12 +000070}
71
72Preprocessor::~Preprocessor() {
73 // Free any active lexers.
74 delete CurLexer;
75
76 while (!IncludeStack.empty()) {
77 delete IncludeStack.back().TheLexer;
78 IncludeStack.pop_back();
79 }
Chris Lattnerb8761832006-06-24 21:31:03 +000080
81 // Release pragma information.
82 delete PragmaHandlers;
Chris Lattner22eb9722006-06-18 05:43:12 +000083}
84
85/// getFileInfo - Return the PerFileInfo structure for the specified
86/// FileEntry.
87Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
88 if (FE->getUID() >= FileInfo.size())
89 FileInfo.resize(FE->getUID()+1);
90 return FileInfo[FE->getUID()];
91}
92
93
94/// AddKeywords - Add all keywords to the symbol table.
95///
96void Preprocessor::AddKeywords() {
97 enum {
98 C90Shift = 0,
99 EXTC90 = 1 << C90Shift,
100 NOTC90 = 2 << C90Shift,
101 C99Shift = 2,
102 EXTC99 = 1 << C99Shift,
103 NOTC99 = 2 << C99Shift,
104 CPPShift = 4,
105 EXTCPP = 1 << CPPShift,
106 NOTCPP = 2 << CPPShift,
107 Mask = 3
108 };
109
110 // Add keywords and tokens for the current language.
111#define KEYWORD(NAME, FLAGS) \
112 AddKeyword(#NAME+1, tok::kw##NAME, \
113 (FLAGS >> C90Shift) & Mask, \
114 (FLAGS >> C99Shift) & Mask, \
115 (FLAGS >> CPPShift) & Mask);
116#define ALIAS(NAME, TOK) \
117 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
118#include "clang/Basic/TokenKinds.def"
119}
120
121/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
122/// the specified LexerToken's location, translating the token's start
123/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000124void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000125 const std::string &Msg) {
126 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
127 // warnings or extensions.
128 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000129 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000130
Chris Lattnercb283342006-06-18 06:48:37 +0000131 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000132}
Chris Lattnercb283342006-06-18 06:48:37 +0000133void Preprocessor::Diag(const LexerToken &Tok, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000134 const std::string &Msg) {
135 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
136 // warnings or extensions.
137 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000138 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000139
Chris Lattner50b497e2006-06-18 16:32:35 +0000140 Diag(Tok.getLocation(), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000141}
142
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143
144void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
145 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
146 << getSpelling(Tok) << "'";
147
148 if (!DumpFlags) return;
149 std::cerr << "\t";
150 if (Tok.isAtStartOfLine())
151 std::cerr << " [StartOfLine]";
152 if (Tok.hasLeadingSpace())
153 std::cerr << " [LeadingSpace]";
154 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000155 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000156 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
157 << "']";
158 }
159}
160
161void Preprocessor::DumpMacro(const MacroInfo &MI) const {
162 std::cerr << "MACRO: ";
163 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
164 DumpToken(MI.getReplacementToken(i));
165 std::cerr << " ";
166 }
167 std::cerr << "\n";
168}
169
Chris Lattner22eb9722006-06-18 05:43:12 +0000170void Preprocessor::PrintStats() {
171 std::cerr << "\n*** Preprocessor Stats:\n";
172 std::cerr << FileInfo.size() << " files tracked.\n";
173 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
174 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
175 NumOnceOnlyFiles += FileInfo[i].isImport;
176 if (MaxNumIncludes < FileInfo[i].NumIncludes)
177 MaxNumIncludes = FileInfo[i].NumIncludes;
178 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
179 }
180 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
181 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
182 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
183
184 std::cerr << NumDirectives << " directives found:\n";
185 std::cerr << " " << NumDefined << " #define.\n";
186 std::cerr << " " << NumUndefined << " #undef.\n";
187 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
188 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
189 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
190 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
191 std::cerr << " " << NumElse << " #else/#elif.\n";
192 std::cerr << " " << NumEndif << " #endif.\n";
193 std::cerr << " " << NumPragma << " #pragma.\n";
194 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
195
196 std::cerr << NumMacroExpanded << " macros expanded, "
197 << NumFastMacroExpanded << " on the fast path.\n";
198 if (MaxMacroStackDepth > 1)
199 std::cerr << " " << MaxMacroStackDepth << " max macroexpand stack depth\n";
200}
201
202//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000203// Token Spelling
204//===----------------------------------------------------------------------===//
205
206
207/// getSpelling() - Return the 'spelling' of this token. The spelling of a
208/// token are the characters used to represent the token in the source file
209/// after trigraph expansion and escaped-newline folding. In particular, this
210/// wants to get the true, uncanonicalized, spelling of things like digraphs
211/// UCNs, etc.
212std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
213 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
214
215 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000216 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217 assert(TokStart && "Token has invalid location!");
218 if (!Tok.needsCleaning())
219 return std::string(TokStart, TokStart+Tok.getLength());
220
221 // Otherwise, hard case, relex the characters into the string.
222 std::string Result;
223 Result.reserve(Tok.getLength());
224
225 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
226 Ptr != End; ) {
227 unsigned CharSize;
228 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
229 Ptr += CharSize;
230 }
231 assert(Result.size() != unsigned(Tok.getLength()) &&
232 "NeedsCleaning flag set on something that didn't need cleaning!");
233 return Result;
234}
235
236/// getSpelling - This method is used to get the spelling of a token into a
237/// preallocated buffer, instead of as an std::string. The caller is required
238/// to allocate enough space for the token, which is guaranteed to be at least
239/// Tok.getLength() bytes long. The actual length of the token is returned.
240unsigned Preprocessor::getSpelling(const LexerToken &Tok, char *Buffer) const {
241 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
242
Chris Lattner50b497e2006-06-18 16:32:35 +0000243 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000244 assert(TokStart && "Token has invalid location!");
245
246 // If this token contains nothing interesting, return it directly.
247 if (!Tok.needsCleaning()) {
248 unsigned Size = Tok.getLength();
249 memcpy(Buffer, TokStart, Size);
250 return Size;
251 }
252 // Otherwise, hard case, relex the characters into the string.
253 std::string Result;
254 Result.reserve(Tok.getLength());
255
256 char *OutBuf = Buffer;
257 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
258 Ptr != End; ) {
259 unsigned CharSize;
260 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
261 Ptr += CharSize;
262 }
263 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
264 "NeedsCleaning flag set on something that didn't need cleaning!");
265
266 return OutBuf-Buffer;
267}
268
269//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000270// Source File Location Methods.
271//===----------------------------------------------------------------------===//
272
273
274/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
275/// return null on failure. isAngled indicates whether the file reference is
276/// for system #include's or not (i.e. using <> instead of "").
277const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000278 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000279 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000280 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000281 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000282 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000283
284 // If 'Filename' is absolute, check to see if it exists and no searching.
285 // FIXME: this should be a sys::Path interface, this doesn't handle things
286 // like C:\foo.txt right, nor win32 \\network\device\blah.
287 if (Filename[0] == '/') {
288 // If this was an #include_next "/absolute/file", fail.
289 if (FromDir) return 0;
290
291 // Otherwise, just return the file.
292 return FileMgr.getFile(Filename);
293 }
294
295 // Step #0, unless disabled, check to see if the file is in the #includer's
296 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000297 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000298 const FileEntry *CurFE =
299 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
300 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000301 // Concatenate the requested file onto the directory.
302 // FIXME: should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000303 if (const FileEntry *FE =
304 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000305 if (CurDirLookup)
306 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000307 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000308 CurDir = 0;
309
310 // This file is a system header or C++ unfriendly if the old file is.
311 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000312 return FE;
313 }
314 }
315 }
316
317 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000318 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000319
320 // If this is a #include_next request, start searching after the directory the
321 // file was found in.
322 if (FromDir)
323 i = FromDir-&SearchDirs[0];
324
325 // Check each directory in sequence to see if it contains this file.
326 for (; i != SearchDirs.size(); ++i) {
327 // Concatenate the requested file onto the directory.
328 // FIXME: should be in sys::Path.
329 if (const FileEntry *FE =
330 FileMgr.getFile(SearchDirs[i].getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000331 CurDir = &SearchDirs[i];
332
333 // This file is a system header or C++ unfriendly if the dir is.
334 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000335 return FE;
336 }
337 }
338
339 // Otherwise, didn't find it.
340 return 0;
341}
342
343/// EnterSourceFile - Add a source file to the top of the include stack and
344/// start lexing tokens from it instead of the current buffer. Return true
345/// on failure.
346void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattnerc8997182006-06-22 05:52:16 +0000347 const DirectoryLookup *CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000348 ++NumEnteredSourceFiles;
349
350 // Add the current lexer to the include stack.
351 if (CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000352 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup));
Chris Lattner22eb9722006-06-18 05:43:12 +0000353 } else {
354 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
355 }
356
357 if (MaxIncludeStackDepth < IncludeStack.size())
358 MaxIncludeStackDepth = IncludeStack.size();
359
360 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
361
Chris Lattnerc8997182006-06-22 05:52:16 +0000362 CurLexer = new Lexer(Buffer, FileID, *this);
363 CurDirLookup = CurDir;
Chris Lattner0c885f52006-06-21 06:50:18 +0000364
365 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerc8997182006-06-22 05:52:16 +0000366 if (FileChangeHandler) {
367 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
368
369 // Get the file entry for the current file.
370 if (const FileEntry *FE =
371 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
372 FileType = getFileInfo(FE).DirInfo;
373
Chris Lattner55a60952006-06-25 04:20:34 +0000374 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferStart),
375 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000376 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000377}
378
379/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000380/// tokens from it instead of the current buffer.
381void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000382 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
383 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000384 if (CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000385 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup));
386 CurLexer = 0;
387 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000388 } else if (CurMacroExpander) {
389 MacroStack.push_back(CurMacroExpander);
390 }
391
392 if (MaxMacroStackDepth < MacroStack.size())
393 MaxMacroStackDepth = MacroStack.size();
394
395 // TODO: Figure out arguments.
396
397 // Mark the macro as currently disabled, so that it is not recursively
398 // expanded.
399 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000400 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000401}
402
403
404//===----------------------------------------------------------------------===//
405// Lexer Event Handling.
406//===----------------------------------------------------------------------===//
407
408/// HandleIdentifier - This callback is invoked when the lexer reads an
409/// identifier. This callback looks up the identifier in the map and/or
410/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnercb283342006-06-18 06:48:37 +0000411void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000412 if (Identifier.getIdentifierInfo() == 0) {
413 // If we are skipping tokens (because we are in a #if 0 block), there will
414 // be no identifier info, just return the token.
415 assert(isSkipping() && "Token isn't an identifier?");
Chris Lattnercb283342006-06-18 06:48:37 +0000416 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000417 }
418 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
Chris Lattner17862172006-06-24 22:12:56 +0000419
Chris Lattnerba6df912006-06-25 05:41:00 +0000420 // If this identifier was poisoned, and if it was not produced from a macro
421 // expansion, emit an error.
422 if (ITI.isPoisoned() && CurLexer)
Chris Lattner17862172006-06-24 22:12:56 +0000423 Diag(Identifier, diag::err_pp_used_poisoned_id);
Chris Lattner22eb9722006-06-18 05:43:12 +0000424
425 if (MacroInfo *MI = ITI.getMacroInfo()) {
426 if (MI->isEnabled() && !DisableMacroExpansion) {
427 ++NumMacroExpanded;
428 // If we started lexing a macro, enter the macro expansion body.
429 // FIXME: Read/Validate the argument list here!
430
431 // If this macro expands to no tokens, don't bother to push it onto the
432 // expansion stack, only to take it right back off.
433 if (MI->getNumTokens() == 0) {
434 // Ignore this macro use, just return the next token in the current
435 // buffer.
436 bool HadLeadingSpace = Identifier.hasLeadingSpace();
437 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
438
Chris Lattnercb283342006-06-18 06:48:37 +0000439 Lex(Identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000440
441 // If the identifier isn't on some OTHER line, inherit the leading
442 // whitespace/first-on-a-line property of this token. This handles
443 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
444 // empty.
445 if (!Identifier.isAtStartOfLine()) {
446 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
447 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
448 }
449 ++NumFastMacroExpanded;
Chris Lattnercb283342006-06-18 06:48:37 +0000450 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000451
452 } else if (MI->getNumTokens() == 1 &&
453 // Don't handle identifiers, which might need recursive
454 // expansion.
455 MI->getReplacementToken(0).getIdentifierInfo() == 0) {
456 // FIXME: Function-style macros only if no arguments?
457
458 // Otherwise, if this macro expands into a single trivially-expanded
459 // token: expand it now. This handles common cases like
460 // "#define VAL 42".
461
462 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
463 // identifier to the expanded token.
464 bool isAtStartOfLine = Identifier.isAtStartOfLine();
465 bool hasLeadingSpace = Identifier.hasLeadingSpace();
466
467 // Replace the result token.
468 Identifier = MI->getReplacementToken(0);
469
470 // Restore the StartOfLine/LeadingSpace markers.
471 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
472 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
473
474 // FIXME: Get correct macro expansion stack location info!
475
476 // Since this is not an identifier token, it can't be macro expanded, so
477 // we're done.
478 ++NumFastMacroExpanded;
Chris Lattnercb283342006-06-18 06:48:37 +0000479 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000480 }
481
482 // Start expanding the macro (FIXME, pass arguments).
Chris Lattnercb283342006-06-18 06:48:37 +0000483 EnterMacro(Identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000484
485 // Now that the macro is at the top of the include stack, ask the
486 // preprocessor to read the next token from it.
487 return Lex(Identifier);
488 }
489 }
490
491 // Change the kind of this identifier to the appropriate token kind, e.g.
492 // turning "for" into a keyword.
493 Identifier.SetKind(ITI.getTokenID());
494
495 // If this is an extension token, diagnose its use.
Chris Lattnercb283342006-06-18 06:48:37 +0000496 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner22eb9722006-06-18 05:43:12 +0000497}
498
499/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
500/// the current file. This either returns the EOF token or pops a level off
501/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000502void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000503 assert(!CurMacroExpander &&
504 "Ending a file when currently in a macro!");
505
506 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
507 // this is an error condition. Just return the EOF token up to
508 // SkipExcludedConditionalBlock. The Lexer will have already have issued
509 // errors for the unterminated #if's on the conditional stack.
510 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000511 Result.StartToken();
512 CurLexer->BufferPtr = CurLexer->BufferEnd;
513 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000514 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000515 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000516 }
517
518 // If this is a #include'd file, pop it off the include stack and continue
519 // lexing the #includer file.
520 if (!IncludeStack.empty()) {
521 // We're done with the #included file.
522 delete CurLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000523 CurLexer = IncludeStack.back().TheLexer;
524 CurDirLookup = IncludeStack.back().TheDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000525 IncludeStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000526
527 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerc8997182006-06-22 05:52:16 +0000528 if (FileChangeHandler && !isEndOfMacro) {
529 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
530
531 // Get the file entry for the current file.
532 if (const FileEntry *FE =
533 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
534 FileType = getFileInfo(FE).DirInfo;
535
Chris Lattner0c885f52006-06-21 06:50:18 +0000536 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000537 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000538 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000539
Chris Lattner22eb9722006-06-18 05:43:12 +0000540 return Lex(Result);
541 }
542
Chris Lattnerd01e2912006-06-18 16:22:51 +0000543 Result.StartToken();
544 CurLexer->BufferPtr = CurLexer->BufferEnd;
545 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000546 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000547
548 // We're done with the #included file.
549 delete CurLexer;
550 CurLexer = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000551}
552
553/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000554/// the current macro line.
555void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000556 assert(CurMacroExpander && !CurLexer &&
557 "Ending a macro when currently in a #include file!");
558
559 // Mark macro not ignored now that it is no longer being expanded.
560 CurMacroExpander->getMacro().EnableMacro();
561 delete CurMacroExpander;
562
563 if (!MacroStack.empty()) {
564 // In a nested macro invocation, continue lexing from the macro.
565 CurMacroExpander = MacroStack.back();
566 MacroStack.pop_back();
567 return Lex(Result);
568 } else {
569 CurMacroExpander = 0;
570 // Handle this like a #include file being popped off the stack.
Chris Lattner0c885f52006-06-21 06:50:18 +0000571 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000572 }
573}
574
575
576//===----------------------------------------------------------------------===//
577// Utility Methods for Preprocessor Directive Handling.
578//===----------------------------------------------------------------------===//
579
580/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
581/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000582void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000583 LexerToken Tmp;
584 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000585 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000586 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000587}
588
589/// ReadMacroName - Lex and validate a macro name, which occurs after a
590/// #define or #undef. This sets the token kind to eom and discards the rest
591/// of the macro line if the macro name is invalid.
Chris Lattnercb283342006-06-18 06:48:37 +0000592void Preprocessor::ReadMacroName(LexerToken &MacroNameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000593 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000594 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000595
596 // Missing macro name?
597 if (MacroNameTok.getKind() == tok::eom)
598 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
599
600 if (MacroNameTok.getIdentifierInfo() == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000601 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000602 // Fall through on error.
603 } else if (0) {
604 // FIXME: Error if defining a C++ named operator.
605
606 } else if (0) {
607 // FIXME: Error if defining "defined", "__DATE__", and other predef macros
608 // in C99 6.10.8.4.
609 } else {
610 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000611 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000612 }
613
614
615 // Invalid macro name, read and discard the rest of the line. Then set the
616 // token kind to tok::eom.
617 MacroNameTok.SetKind(tok::eom);
618 return DiscardUntilEndOfDirective();
619}
620
621/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
622/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000623void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000624 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000625 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000626 // There should be no tokens after the directive, but we allow them as an
627 // extension.
628 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000629 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
630 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000631 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000632}
633
634
635
636/// SkipExcludedConditionalBlock - We just read a #if or related directive and
637/// decided that the subsequent tokens are in the #if'd out portion of the
638/// file. Lex the rest of the file, until we see an #endif. If
639/// FoundNonSkipPortion is true, then we have already emitted code for part of
640/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
641/// is true, then #else directives are ok, if not, then we have already seen one
642/// so a #else directive is a duplicate. When this returns, the caller can lex
643/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000644void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000645 bool FoundNonSkipPortion,
646 bool FoundElse) {
647 ++NumSkipped;
648 assert(MacroStack.empty() && CurMacroExpander == 0 && CurLexer &&
649 "Lexing a macro, not a file?");
650
651 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
652 FoundNonSkipPortion, FoundElse);
653
654 // Know that we are going to be skipping tokens. Set this flag to indicate
655 // this, which has a couple of effects:
656 // 1. If EOF of the current lexer is found, the include stack isn't popped.
657 // 2. Identifier information is not looked up for identifier tokens. As an
658 // effect of this, implicit macro expansion is naturally disabled.
659 // 3. "#" tokens at the start of a line are treated as normal tokens, not
660 // implicitly transformed by the lexer.
661 // 4. All notes, warnings, and extension messages are disabled.
662 //
663 SkippingContents = true;
664 LexerToken Tok;
665 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000666 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000667
668 // If this is the end of the buffer, we have an error. The lexer will have
669 // already handled this error condition, so just return and let the caller
670 // lex after this #include.
671 if (Tok.getKind() == tok::eof) break;
672
673 // If this token is not a preprocessor directive, just skip it.
674 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
675 continue;
676
677 // We just parsed a # character at the start of a line, so we're in
678 // directive mode. Tell the lexer this so any newlines we see will be
679 // converted into an EOM token (this terminates the macro).
680 CurLexer->ParsingPreprocessorDirective = true;
681
682 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000683 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000684
685 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
686 // something bogus), skip it.
687 if (Tok.getKind() != tok::identifier) {
688 CurLexer->ParsingPreprocessorDirective = false;
689 continue;
690 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000691
Chris Lattner22eb9722006-06-18 05:43:12 +0000692 // If the first letter isn't i or e, it isn't intesting to us. We know that
693 // this is safe in the face of spelling differences, because there is no way
694 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +0000695 // allows us to avoid looking up the identifier info for #define/#undef and
696 // other common directives.
697 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
698 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000699 if (FirstChar >= 'a' && FirstChar <= 'z' &&
700 FirstChar != 'i' && FirstChar != 'e') {
701 CurLexer->ParsingPreprocessorDirective = false;
702 continue;
703 }
704
Chris Lattnere60165f2006-06-22 06:36:29 +0000705 // Get the identifier name without trigraphs or embedded newlines. Note
706 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
707 // when skipping.
708 // TODO: could do this with zero copies in the no-clean case by using
709 // strncmp below.
710 char Directive[20];
711 unsigned IdLen;
712 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
713 IdLen = Tok.getLength();
714 memcpy(Directive, RawCharData, IdLen);
715 Directive[IdLen] = 0;
716 } else {
717 std::string DirectiveStr = getSpelling(Tok);
718 IdLen = DirectiveStr.size();
719 if (IdLen >= 20) {
720 CurLexer->ParsingPreprocessorDirective = false;
721 continue;
722 }
723 memcpy(Directive, &DirectiveStr[0], IdLen);
724 Directive[IdLen] = 0;
725 }
726
Chris Lattner22eb9722006-06-18 05:43:12 +0000727 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000728 if ((IdLen == 2) || // "if"
729 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
730 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +0000731 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
732 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000733 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000734 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000735 /*foundnonskip*/false,
736 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000737 }
738 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +0000739 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +0000740 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000741 PPConditionalInfo CondInfo;
742 CondInfo.WasSkipping = true; // Silence bogus warning.
743 bool InCond = CurLexer->popConditionalLevel(CondInfo);
744 assert(!InCond && "Can't be skipping if not in a conditional!");
745
746 // If we popped the outermost skipping block, we're done skipping!
747 if (!CondInfo.WasSkipping)
748 break;
Chris Lattnere60165f2006-06-22 06:36:29 +0000749 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +0000750 // #else directive in a skipping conditional. If not in some other
751 // skipping conditional, and if #else hasn't already been seen, enter it
752 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000753 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000754 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
755
756 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000757 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000758
759 // Note that we've seen a #else in this conditional.
760 CondInfo.FoundElse = true;
761
762 // If the conditional is at the top level, and the #if block wasn't
763 // entered, enter the #else block now.
764 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
765 CondInfo.FoundNonSkip = true;
766 break;
767 }
Chris Lattnere60165f2006-06-22 06:36:29 +0000768 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +0000769 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
770
771 bool ShouldEnter;
772 // If this is in a skipping block or if we're already handled this #if
773 // block, don't bother parsing the condition.
774 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +0000775 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000776 ShouldEnter = false;
777 } else {
778 // Evaluate the #elif condition!
779 const char *Start = CurLexer->BufferPtr;
780
781 // Restore the value of SkippingContents so that identifiers are
782 // looked up, etc, inside the #elif expression.
783 assert(SkippingContents && "We have to be skipping here!");
784 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +0000785 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +0000786 SkippingContents = true;
787 }
788
789 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000790 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000791
792 // If this condition is true, enter it!
793 if (ShouldEnter) {
794 CondInfo.FoundNonSkip = true;
795 break;
796 }
797 }
798 }
799
800 CurLexer->ParsingPreprocessorDirective = false;
801 }
802
803 // Finally, if we are out of the conditional (saw an #endif or ran off the end
804 // of the file, just stop skipping and return to lexing whatever came after
805 // the #if block.
806 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000807}
808
809//===----------------------------------------------------------------------===//
810// Preprocessor Directive Handling.
811//===----------------------------------------------------------------------===//
812
813/// HandleDirective - This callback is invoked when the lexer sees a # token
814/// at the start of a line. This consumes the directive, modifies the
815/// lexer/preprocessor state, and advances the lexer(s) so that the next token
816/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +0000817void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000818 // FIXME: TRADITIONAL: # with whitespace before it not recognized by K&R?
819
820 // We just parsed a # character at the start of a line, so we're in directive
821 // mode. Tell the lexer this so any newlines we see will be converted into an
822 // EOM token (this terminates the macro).
823 CurLexer->ParsingPreprocessorDirective = true;
824
825 ++NumDirectives;
826
827 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000828 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000829
830 switch (Result.getKind()) {
831 default: break;
832 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +0000833 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +0000834
835#if 0
836 case tok::numeric_constant:
837 // FIXME: implement # 7 line numbers!
838 break;
839#endif
840 case tok::kw_else:
841 return HandleElseDirective(Result);
842 case tok::kw_if:
843 return HandleIfDirective(Result);
844 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +0000845 // Get the identifier name without trigraphs or embedded newlines.
846 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +0000847 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +0000848 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000849 case 4:
Chris Lattner40931922006-06-22 06:14:04 +0000850 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattnerb8761832006-06-24 21:31:03 +0000851 ; // FIXME: implement #line
Chris Lattner40931922006-06-22 06:14:04 +0000852 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000853 return HandleElifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000854 if (Directive[0] == 's' && !strcmp(Directive, "sccs")) {
Chris Lattnerb8761832006-06-24 21:31:03 +0000855 isExtension = true; // FIXME: implement #sccs
Chris Lattner22eb9722006-06-18 05:43:12 +0000856 // SCCS is the same as #ident.
857 }
858 break;
859 case 5:
Chris Lattner40931922006-06-22 06:14:04 +0000860 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000861 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000862 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000863 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +0000864 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000865 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000866 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000867 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +0000868 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattnerb8761832006-06-24 21:31:03 +0000869 isExtension = true; // FIXME: implement #ident
Chris Lattner22eb9722006-06-18 05:43:12 +0000870 break;
871 case 6:
Chris Lattner40931922006-06-22 06:14:04 +0000872 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000873 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000874 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000875 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +0000876 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000877 return HandleImportDirective(Result);
Chris Lattnerb8761832006-06-24 21:31:03 +0000878 if (Directive[0] == 'p' && !strcmp(Directive, "pragma"))
879 return HandlePragmaDirective(Result);
880 if (Directive[0] == 'a' && !strcmp(Directive, "assert"))
881 isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +0000882 break;
883 case 7:
Chris Lattner40931922006-06-22 06:14:04 +0000884 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
885 return HandleIncludeDirective(Result); // Handle #include.
886 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +0000887 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +0000888 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +0000889 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000890 break;
891 case 8:
Chris Lattner40931922006-06-22 06:14:04 +0000892 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattnerb8761832006-06-24 21:31:03 +0000893 isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +0000894 }
895 break;
896 case 12:
Chris Lattner40931922006-06-22 06:14:04 +0000897 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
898 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +0000899 break;
900 }
901 break;
902 }
903
904 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +0000905 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +0000906
907 // Read the rest of the PP line.
908 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000909 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000910 } while (Result.getKind() != tok::eom);
911
912 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +0000913}
914
Chris Lattnercb283342006-06-18 06:48:37 +0000915void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +0000916 bool isWarning) {
917 // Read the rest of the line raw. We do this because we don't want macros
918 // to be expanded and we don't require that the tokens be valid preprocessing
919 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
920 // collapse multiple consequtive white space between tokens, but this isn't
921 // specified by the standard.
922 std::string Message = CurLexer->ReadToEndOfLine();
923
924 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
925 return Diag(Result, DiagID, Message);
926}
927
Chris Lattnerb8761832006-06-24 21:31:03 +0000928//===----------------------------------------------------------------------===//
929// Preprocessor Include Directive Handling.
930//===----------------------------------------------------------------------===//
931
Chris Lattner22eb9722006-06-18 05:43:12 +0000932/// HandleIncludeDirective - The "#include" tokens have just been read, read the
933/// file to be included from the lexer, then include it! This is a common
934/// routine with functionality shared between #include, #include_next and
935/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +0000936void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +0000937 const DirectoryLookup *LookupFrom,
938 bool isImport) {
939 ++NumIncluded;
940 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +0000941 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000942
943 // If the token kind is EOM, the error has already been diagnosed.
944 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +0000945 return;
Chris Lattner269c2322006-06-25 06:23:00 +0000946
947 // Verify that there is nothing after the filename, other than EOM. Use the
948 // preprocessor to lex this in case lexing the filename entered a macro.
949 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +0000950
951 // Check that we don't have infinite #include recursion.
952 if (IncludeStack.size() == MaxAllowedIncludeStackDepth-1)
953 return Diag(FilenameTok, diag::err_pp_include_too_deep);
954
Chris Lattner269c2322006-06-25 06:23:00 +0000955 // Find out whether the filename is <x> or "x".
956 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +0000957
958 // Remove the quotes.
959 Filename = std::string(Filename.begin()+1, Filename.end()-1);
960
Chris Lattner22eb9722006-06-18 05:43:12 +0000961 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +0000962 const DirectoryLookup *CurDir;
963 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +0000964 if (File == 0)
965 return Diag(FilenameTok, diag::err_pp_file_not_found);
966
967 // Get information about this file.
968 PerFileInfo &FileInfo = getFileInfo(File);
969
970 // If this is a #import directive, check that we have not already imported
971 // this header.
972 if (isImport) {
973 // If this has already been imported, don't import it again.
974 FileInfo.isImport = true;
975
976 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +0000977 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000978 } else {
979 // Otherwise, if this is a #include of a file that was previously #import'd
980 // or if this is the second #include of a #pragma once file, ignore it.
981 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +0000982 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000983 }
984
985 // Look up the file, create a File ID for it.
986 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +0000987 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +0000988 if (FileID == 0)
989 return Diag(FilenameTok, diag::err_pp_file_not_found);
990
991 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +0000992 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +0000993
994 // Increment the number of times this file has been included.
995 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +0000996}
997
998/// HandleIncludeNextDirective - Implements #include_next.
999///
Chris Lattnercb283342006-06-18 06:48:37 +00001000void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1001 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001002
1003 // #include_next is like #include, except that we start searching after
1004 // the current found directory. If we can't do this, issue a
1005 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001006 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001007 if (IncludeStack.empty()) {
1008 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001009 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001010 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001011 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001012 } else {
1013 // Start looking up in the next directory.
1014 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001015 }
1016
1017 return HandleIncludeDirective(IncludeNextTok, Lookup);
1018}
1019
1020/// HandleImportDirective - Implements #import.
1021///
Chris Lattnercb283342006-06-18 06:48:37 +00001022void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1023 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001024
1025 return HandleIncludeDirective(ImportTok, 0, true);
1026}
1027
Chris Lattnerb8761832006-06-24 21:31:03 +00001028//===----------------------------------------------------------------------===//
1029// Preprocessor Macro Directive Handling.
1030//===----------------------------------------------------------------------===//
1031
Chris Lattner22eb9722006-06-18 05:43:12 +00001032/// HandleDefineDirective - Implements #define. This consumes the entire macro
1033/// line then lets the caller lex the next real token.
1034///
Chris Lattnercb283342006-06-18 06:48:37 +00001035void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001036 ++NumDefined;
1037 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001038 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001039
1040 // Error reading macro name? If so, diagnostic already issued.
1041 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001042 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001043
Chris Lattner50b497e2006-06-18 16:32:35 +00001044 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001045
1046 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001047 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001048
1049 if (Tok.getKind() == tok::eom) {
1050 // If there is no body to this macro, we have no special handling here.
1051 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1052 // This is a function-like macro definition.
1053 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001054 return DiscardUntilEndOfDirective();
1055
1056 } else if (!Tok.hasLeadingSpace()) {
1057 // C99 requires whitespace between the macro definition and the body. Emit
1058 // a diagnostic for something like "#define X+".
1059 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001060 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001061 } else {
1062 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1063 // one in some cases!
1064 }
1065 } else {
1066 // This is a normal token with leading space. Clear the leading space
1067 // marker on the first token to get proper expansion.
1068 Tok.ClearFlag(LexerToken::LeadingSpace);
1069 }
1070
1071 // Read the rest of the macro body.
1072 while (Tok.getKind() != tok::eom) {
1073 MI->AddTokenToBody(Tok);
1074
1075 // FIXME: See create_iso_definition.
1076
1077 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001078 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001079 }
1080
1081 // Finally, if this identifier already had a macro defined for it, verify that
1082 // the macro bodies are identical and free the old definition.
1083 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1084 // FIXME: Verify the definition is the same.
1085 // Macros must be identical. This means all tokes and whitespace separation
1086 // must be the same.
1087 delete OtherMI;
1088 }
1089
1090 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001091}
1092
1093
1094/// HandleUndefDirective - Implements #undef.
1095///
Chris Lattnercb283342006-06-18 06:48:37 +00001096void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 ++NumUndefined;
1098 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001099 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001100
1101 // Error reading macro name? If so, diagnostic already issued.
1102 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001103 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001104
1105 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001106 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001107
1108 // Okay, we finally have a valid identifier to undef.
1109 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1110
1111 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001112 if (MI == 0) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001113
1114#if 0 // FIXME: implement warn_unused_macros.
1115 if (CPP_OPTION (pfile, warn_unused_macros))
1116 _cpp_warn_if_unused_macro (pfile, node, NULL);
1117#endif
1118
1119 // Free macro definition.
1120 delete MI;
1121 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001122}
1123
1124
Chris Lattnerb8761832006-06-24 21:31:03 +00001125//===----------------------------------------------------------------------===//
1126// Preprocessor Conditional Directive Handling.
1127//===----------------------------------------------------------------------===//
1128
Chris Lattner22eb9722006-06-18 05:43:12 +00001129/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1130/// true when this is a #ifndef directive.
1131///
Chris Lattnercb283342006-06-18 06:48:37 +00001132void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001133 ++NumIf;
1134 LexerToken DirectiveTok = Result;
1135
1136 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001137 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001138
1139 // Error reading macro name? If so, diagnostic already issued.
1140 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001141 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001142
1143 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001144 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001145
1146 // Should we include the stuff contained by this directive?
1147 if (!MacroNameTok.getIdentifierInfo()->getMacroInfo() == isIfndef) {
1148 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001149 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001150 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 } else {
1152 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001153 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001154 /*Foundnonskip*/false,
1155 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001156 }
1157}
1158
1159/// HandleIfDirective - Implements the #if directive.
1160///
Chris Lattnercb283342006-06-18 06:48:37 +00001161void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001162 ++NumIf;
1163 const char *Start = CurLexer->BufferPtr;
1164
Chris Lattner7966aaf2006-06-18 06:50:36 +00001165 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001166
1167 // Should we include the stuff contained by this directive?
1168 if (ConditionalTrue) {
1169 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001170 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001171 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001172 } else {
1173 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001174 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001175 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001176 }
1177}
1178
1179/// HandleEndifDirective - Implements the #endif directive.
1180///
Chris Lattnercb283342006-06-18 06:48:37 +00001181void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001182 ++NumEndif;
1183 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001184 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001185
1186 PPConditionalInfo CondInfo;
1187 if (CurLexer->popConditionalLevel(CondInfo)) {
1188 // No conditionals on the stack: this is an #endif without an #if.
1189 return Diag(EndifToken, diag::err_pp_endif_without_if);
1190 }
1191
1192 assert(!CondInfo.WasSkipping && !isSkipping() &&
1193 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001194}
1195
1196
Chris Lattnercb283342006-06-18 06:48:37 +00001197void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001198 ++NumElse;
1199 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001200 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001201
1202 PPConditionalInfo CI;
1203 if (CurLexer->popConditionalLevel(CI))
1204 return Diag(Result, diag::pp_err_else_without_if);
1205
1206 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001207 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001208
1209 // Finally, skip the rest of the contents of this block and return the first
1210 // token after it.
1211 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1212 /*FoundElse*/true);
1213}
1214
Chris Lattnercb283342006-06-18 06:48:37 +00001215void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001216 ++NumElse;
1217 // #elif directive in a non-skipping conditional... start skipping.
1218 // We don't care what the condition is, because we will always skip it (since
1219 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001220 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001221
1222 PPConditionalInfo CI;
1223 if (CurLexer->popConditionalLevel(CI))
1224 return Diag(ElifToken, diag::pp_err_elif_without_if);
1225
1226 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001227 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001228
1229 // Finally, skip the rest of the contents of this block and return the first
1230 // token after it.
1231 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1232 /*FoundElse*/CI.FoundElse);
1233}
Chris Lattnerb8761832006-06-24 21:31:03 +00001234
1235
1236//===----------------------------------------------------------------------===//
1237// Preprocessor Pragma Directive Handling.
1238//===----------------------------------------------------------------------===//
1239
1240/// HandlePragmaDirective - The "#pragma" directive has been parsed with
1241/// PragmaTok containing the "pragma" identifier. Lex the rest of the pragma,
1242/// passing it to the registered pragma handlers.
1243void Preprocessor::HandlePragmaDirective(LexerToken &PragmaTok) {
1244 ++NumPragma;
1245
1246 // Invoke the first level of pragma handlers which reads the namespace id.
1247 LexerToken Tok;
1248 PragmaHandlers->HandlePragma(*this, Tok);
1249
1250 // If the pragma handler didn't read the rest of the line, consume it now.
Chris Lattner17862172006-06-24 22:12:56 +00001251 if (CurLexer->ParsingPreprocessorDirective)
1252 DiscardUntilEndOfDirective();
Chris Lattnerb8761832006-06-24 21:31:03 +00001253}
1254
1255/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
Chris Lattner17862172006-06-24 22:12:56 +00001256///
Chris Lattnerb8761832006-06-24 21:31:03 +00001257void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
1258 if (IncludeStack.empty()) {
1259 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
1260 return;
1261 }
Chris Lattner17862172006-06-24 22:12:56 +00001262
1263 // FIXME: implement the _Pragma thing.
1264 assert(CurLexer && "Cannot have a pragma in a macro expansion yet!");
1265
1266 // Mark the file as a once-only file now.
1267 const FileEntry *File =
1268 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
1269 getFileInfo(File).isImport = true;
Chris Lattnerb8761832006-06-24 21:31:03 +00001270}
1271
Chris Lattner17862172006-06-24 22:12:56 +00001272/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
1273///
1274void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
1275 LexerToken Tok;
1276 assert(!SkippingContents && "Why are we handling pragmas while skipping?");
1277 while (1) {
1278 // Read the next token to poison. While doing this, pretend that we are
1279 // skipping while reading the identifier to poison.
1280 // This avoids errors on code like:
1281 // #pragma GCC poison X
1282 // #pragma GCC poison X
1283 SkippingContents = true;
1284 LexUnexpandedToken(Tok);
1285 SkippingContents = false;
1286
1287 // If we reached the end of line, we're done.
1288 if (Tok.getKind() == tok::eom) return;
1289
1290 // Can only poison identifiers.
1291 if (Tok.getKind() != tok::identifier) {
1292 Diag(Tok, diag::err_pp_invalid_poison);
1293 return;
1294 }
1295
1296 // Look up the identifier info for the token.
1297 std::string TokStr = getSpelling(Tok);
1298 IdentifierTokenInfo *II =
1299 getIdentifierInfo(&TokStr[0], &TokStr[0]+TokStr.size());
1300
1301 // Already poisoned.
1302 if (II->isPoisoned()) continue;
1303
1304 // If this is a macro identifier, emit a warning.
1305 if (II->getMacroInfo())
1306 Diag(Tok, diag::pp_poisoning_existing_macro);
1307
1308 // Finally, poison it!
1309 II->setIsPoisoned();
1310 }
1311}
Chris Lattnerb8761832006-06-24 21:31:03 +00001312
Chris Lattner269c2322006-06-25 06:23:00 +00001313/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
1314/// that the whole directive has been parsed.
Chris Lattner55a60952006-06-25 04:20:34 +00001315void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
1316 if (IncludeStack.empty()) {
1317 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
1318 return;
1319 }
1320
1321 // Mark the file as a system header.
1322 const FileEntry *File =
1323 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
1324 getFileInfo(File).DirInfo = DirectoryLookup::SystemHeaderDir;
1325
1326
1327 // Notify the client, if desired, that we are in a new source file.
1328 if (FileChangeHandler)
1329 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1330 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
1331}
1332
Chris Lattner269c2322006-06-25 06:23:00 +00001333/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
1334///
1335void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
1336 LexerToken FilenameTok;
1337 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
1338
1339 // If the token kind is EOM, the error has already been diagnosed.
1340 if (FilenameTok.getKind() == tok::eom)
1341 return;
1342
1343 // Find out whether the filename is <x> or "x".
1344 bool isAngled = Filename[0] == '<';
1345
1346 // Remove the quotes.
1347 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1348
1349 // Search include directories.
1350 const DirectoryLookup *CurDir;
1351 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
1352 if (File == 0)
1353 return Diag(FilenameTok, diag::err_pp_file_not_found);
1354
1355 Lexer *TheLexer = CurLexer;
1356 if (TheLexer == 0) {
1357 assert(!IncludeStack.empty() && "No current lexer?");
1358 TheLexer = IncludeStack.back().TheLexer;
1359 }
1360 const FileEntry *CurFile =
1361 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
1362
1363 // If this file is older than the file it depends on, emit a diagnostic.
1364 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
1365 // Lex tokens at the end of the message and include them in the message.
1366 std::string Message;
1367 Lex(DependencyTok);
1368 while (DependencyTok.getKind() != tok::eom) {
1369 Message += getSpelling(DependencyTok) + " ";
1370 Lex(DependencyTok);
1371 }
1372
1373 Message.erase(Message.end()-1);
1374 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
1375 }
1376}
1377
1378
Chris Lattnerb8761832006-06-24 21:31:03 +00001379/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
1380/// If 'Namespace' is non-null, then it is a token required to exist on the
1381/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
1382void Preprocessor::AddPragmaHandler(const char *Namespace,
1383 PragmaHandler *Handler) {
1384 PragmaNamespace *InsertNS = PragmaHandlers;
1385
1386 // If this is specified to be in a namespace, step down into it.
1387 if (Namespace) {
1388 IdentifierTokenInfo *NSID = getIdentifierInfo(Namespace);
1389
1390 // If there is already a pragma handler with the name of this namespace,
1391 // we either have an error (directive with the same name as a namespace) or
1392 // we already have the namespace to insert into.
1393 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
1394 InsertNS = Existing->getIfNamespace();
1395 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
1396 " handler with the same name!");
1397 } else {
1398 // Otherwise, this namespace doesn't exist yet, create and insert the
1399 // handler for it.
1400 InsertNS = new PragmaNamespace(NSID);
1401 PragmaHandlers->AddPragma(InsertNS);
1402 }
1403 }
1404
1405 // Check to make sure we don't already have a pragma for this identifier.
1406 assert(!InsertNS->FindHandler(Handler->getName()) &&
1407 "Pragma handler already exists for this identifier!");
1408 InsertNS->AddPragma(Handler);
1409}
1410
Chris Lattner17862172006-06-24 22:12:56 +00001411namespace {
Chris Lattner55a60952006-06-25 04:20:34 +00001412struct PragmaOnceHandler : public PragmaHandler {
Chris Lattnerb8761832006-06-24 21:31:03 +00001413 PragmaOnceHandler(const IdentifierTokenInfo *OnceID) : PragmaHandler(OnceID){}
1414 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
1415 PP.CheckEndOfDirective("#pragma once");
1416 PP.HandlePragmaOnce(OnceTok);
1417 }
1418};
1419
Chris Lattner55a60952006-06-25 04:20:34 +00001420struct PragmaPoisonHandler : public PragmaHandler {
Chris Lattner17862172006-06-24 22:12:56 +00001421 PragmaPoisonHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
1422 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
1423 PP.HandlePragmaPoison(PoisonTok);
1424 }
1425};
Chris Lattner55a60952006-06-25 04:20:34 +00001426
1427struct PragmaSystemHeaderHandler : public PragmaHandler {
1428 PragmaSystemHeaderHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID){}
1429 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
1430 PP.HandlePragmaSystemHeader(SHToken);
1431 PP.CheckEndOfDirective("#pragma");
1432 }
1433};
Chris Lattner269c2322006-06-25 06:23:00 +00001434struct PragmaDependencyHandler : public PragmaHandler {
1435 PragmaDependencyHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
1436 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
1437 PP.HandlePragmaDependency(DepToken);
1438 }
1439};
Chris Lattner17862172006-06-24 22:12:56 +00001440}
1441
Chris Lattnerb8761832006-06-24 21:31:03 +00001442
1443/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1444/// #pragma GCC poison/system_header/dependency and #pragma once.
1445void Preprocessor::RegisterBuiltinPragmas() {
1446 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
Chris Lattner17862172006-06-24 22:12:56 +00001447 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
Chris Lattner55a60952006-06-25 04:20:34 +00001448 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
1449 getIdentifierInfo("system_header")));
Chris Lattner269c2322006-06-25 06:23:00 +00001450 AddPragmaHandler("GCC", new PragmaDependencyHandler(
1451 getIdentifierInfo("dependency")));
Chris Lattnerb8761832006-06-24 21:31:03 +00001452}