blob: eafd3714f95f9426965ea72be3dc18895139e505 [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"
38#include "clang/Basic/Diagnostic.h"
39#include "clang/Basic/FileManager.h"
40#include "clang/Basic/SourceManager.h"
41#include <iostream>
42using namespace llvm;
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46
47Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
48 FileManager &FM, SourceManager &SM)
49 : Diags(diags), Features(opts), FileMgr(FM), SourceMgr(SM),
50 SystemDirIdx(0), NoCurDirSearch(false),
Chris Lattnerc8997182006-06-22 05:52:16 +000051 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner22eb9722006-06-18 05:43:12 +000052 // Clear stats.
53 NumDirectives = NumIncluded = NumDefined = NumUndefined = NumPragma = 0;
54 NumIf = NumElse = NumEndif = 0;
55 NumEnteredSourceFiles = NumMacroExpanded = NumFastMacroExpanded = 0;
56 MaxIncludeStackDepth = MaxMacroStackDepth = 0;
57 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000058
Chris Lattner22eb9722006-06-18 05:43:12 +000059 // Macro expansion is enabled.
60 DisableMacroExpansion = false;
61 SkippingContents = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000062
63 // There is no file-change handler yet.
64 FileChangeHandler = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000065}
66
67Preprocessor::~Preprocessor() {
68 // Free any active lexers.
69 delete CurLexer;
70
71 while (!IncludeStack.empty()) {
72 delete IncludeStack.back().TheLexer;
73 IncludeStack.pop_back();
74 }
75}
76
77/// getFileInfo - Return the PerFileInfo structure for the specified
78/// FileEntry.
79Preprocessor::PerFileInfo &Preprocessor::getFileInfo(const FileEntry *FE) {
80 if (FE->getUID() >= FileInfo.size())
81 FileInfo.resize(FE->getUID()+1);
82 return FileInfo[FE->getUID()];
83}
84
85
86/// AddKeywords - Add all keywords to the symbol table.
87///
88void Preprocessor::AddKeywords() {
89 enum {
90 C90Shift = 0,
91 EXTC90 = 1 << C90Shift,
92 NOTC90 = 2 << C90Shift,
93 C99Shift = 2,
94 EXTC99 = 1 << C99Shift,
95 NOTC99 = 2 << C99Shift,
96 CPPShift = 4,
97 EXTCPP = 1 << CPPShift,
98 NOTCPP = 2 << CPPShift,
99 Mask = 3
100 };
101
102 // Add keywords and tokens for the current language.
103#define KEYWORD(NAME, FLAGS) \
104 AddKeyword(#NAME+1, tok::kw##NAME, \
105 (FLAGS >> C90Shift) & Mask, \
106 (FLAGS >> C99Shift) & Mask, \
107 (FLAGS >> CPPShift) & Mask);
108#define ALIAS(NAME, TOK) \
109 AddKeyword(NAME, tok::kw_ ## TOK, 0, 0, 0);
110#include "clang/Basic/TokenKinds.def"
111}
112
113/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
114/// the specified LexerToken's location, translating the token's start
115/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000116void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000117 const std::string &Msg) {
118 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
119 // warnings or extensions.
120 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000121 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000122
Chris Lattnercb283342006-06-18 06:48:37 +0000123 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000124}
Chris Lattnercb283342006-06-18 06:48:37 +0000125void Preprocessor::Diag(const LexerToken &Tok, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000126 const std::string &Msg) {
127 // If we are in a '#if 0' block, don't emit any diagnostics for notes,
128 // warnings or extensions.
129 if (isSkipping() && Diagnostic::isNoteWarningOrExtension(DiagID))
Chris Lattnercb283342006-06-18 06:48:37 +0000130 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000131
Chris Lattner50b497e2006-06-18 16:32:35 +0000132 Diag(Tok.getLocation(), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000133}
134
Chris Lattnerd01e2912006-06-18 16:22:51 +0000135
136void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
137 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
138 << getSpelling(Tok) << "'";
139
140 if (!DumpFlags) return;
141 std::cerr << "\t";
142 if (Tok.isAtStartOfLine())
143 std::cerr << " [StartOfLine]";
144 if (Tok.hasLeadingSpace())
145 std::cerr << " [LeadingSpace]";
146 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000147 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000148 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
149 << "']";
150 }
151}
152
153void Preprocessor::DumpMacro(const MacroInfo &MI) const {
154 std::cerr << "MACRO: ";
155 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
156 DumpToken(MI.getReplacementToken(i));
157 std::cerr << " ";
158 }
159 std::cerr << "\n";
160}
161
Chris Lattner22eb9722006-06-18 05:43:12 +0000162void Preprocessor::PrintStats() {
163 std::cerr << "\n*** Preprocessor Stats:\n";
164 std::cerr << FileInfo.size() << " files tracked.\n";
165 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
166 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
167 NumOnceOnlyFiles += FileInfo[i].isImport;
168 if (MaxNumIncludes < FileInfo[i].NumIncludes)
169 MaxNumIncludes = FileInfo[i].NumIncludes;
170 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
171 }
172 std::cerr << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
173 std::cerr << " " << NumSingleIncludedFiles << " included exactly once.\n";
174 std::cerr << " " << MaxNumIncludes << " max times a file is included.\n";
175
176 std::cerr << NumDirectives << " directives found:\n";
177 std::cerr << " " << NumDefined << " #define.\n";
178 std::cerr << " " << NumUndefined << " #undef.\n";
179 std::cerr << " " << NumIncluded << " #include/#include_next/#import.\n";
180 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
181 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
182 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
183 std::cerr << " " << NumElse << " #else/#elif.\n";
184 std::cerr << " " << NumEndif << " #endif.\n";
185 std::cerr << " " << NumPragma << " #pragma.\n";
186 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
187
188 std::cerr << NumMacroExpanded << " macros expanded, "
189 << NumFastMacroExpanded << " on the fast path.\n";
190 if (MaxMacroStackDepth > 1)
191 std::cerr << " " << MaxMacroStackDepth << " max macroexpand stack depth\n";
192}
193
194//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000195// Token Spelling
196//===----------------------------------------------------------------------===//
197
198
199/// getSpelling() - Return the 'spelling' of this token. The spelling of a
200/// token are the characters used to represent the token in the source file
201/// after trigraph expansion and escaped-newline folding. In particular, this
202/// wants to get the true, uncanonicalized, spelling of things like digraphs
203/// UCNs, etc.
204std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
205 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
206
207 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000208 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000209 assert(TokStart && "Token has invalid location!");
210 if (!Tok.needsCleaning())
211 return std::string(TokStart, TokStart+Tok.getLength());
212
213 // Otherwise, hard case, relex the characters into the string.
214 std::string Result;
215 Result.reserve(Tok.getLength());
216
217 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
218 Ptr != End; ) {
219 unsigned CharSize;
220 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
221 Ptr += CharSize;
222 }
223 assert(Result.size() != unsigned(Tok.getLength()) &&
224 "NeedsCleaning flag set on something that didn't need cleaning!");
225 return Result;
226}
227
228/// getSpelling - This method is used to get the spelling of a token into a
229/// preallocated buffer, instead of as an std::string. The caller is required
230/// to allocate enough space for the token, which is guaranteed to be at least
231/// Tok.getLength() bytes long. The actual length of the token is returned.
232unsigned Preprocessor::getSpelling(const LexerToken &Tok, char *Buffer) const {
233 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
234
Chris Lattner50b497e2006-06-18 16:32:35 +0000235 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000236 assert(TokStart && "Token has invalid location!");
237
238 // If this token contains nothing interesting, return it directly.
239 if (!Tok.needsCleaning()) {
240 unsigned Size = Tok.getLength();
241 memcpy(Buffer, TokStart, Size);
242 return Size;
243 }
244 // Otherwise, hard case, relex the characters into the string.
245 std::string Result;
246 Result.reserve(Tok.getLength());
247
248 char *OutBuf = Buffer;
249 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
250 Ptr != End; ) {
251 unsigned CharSize;
252 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
253 Ptr += CharSize;
254 }
255 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
256 "NeedsCleaning flag set on something that didn't need cleaning!");
257
258 return OutBuf-Buffer;
259}
260
261//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000262// Source File Location Methods.
263//===----------------------------------------------------------------------===//
264
265
266/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
267/// return null on failure. isAngled indicates whether the file reference is
268/// for system #include's or not (i.e. using <> instead of "").
269const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000270 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000271 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000272 const DirectoryLookup *&CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000273 assert(CurLexer && "Cannot enter a #include inside a macro expansion!");
Chris Lattnerc8997182006-06-22 05:52:16 +0000274 CurDir = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000275
276 // If 'Filename' is absolute, check to see if it exists and no searching.
277 // FIXME: this should be a sys::Path interface, this doesn't handle things
278 // like C:\foo.txt right, nor win32 \\network\device\blah.
279 if (Filename[0] == '/') {
280 // If this was an #include_next "/absolute/file", fail.
281 if (FromDir) return 0;
282
283 // Otherwise, just return the file.
284 return FileMgr.getFile(Filename);
285 }
286
287 // Step #0, unless disabled, check to see if the file is in the #includer's
288 // directory. This search is not done for <> headers.
Chris Lattnerc8997182006-06-22 05:52:16 +0000289 if (!isAngled && !FromDir && !NoCurDirSearch) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000290 const FileEntry *CurFE =
291 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
292 if (CurFE) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000293 // Concatenate the requested file onto the directory.
294 // FIXME: should be in sys::Path.
Chris Lattner22eb9722006-06-18 05:43:12 +0000295 if (const FileEntry *FE =
296 FileMgr.getFile(CurFE->getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000297 if (CurDirLookup)
298 CurDir = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000299 else
Chris Lattnerc8997182006-06-22 05:52:16 +0000300 CurDir = 0;
301
302 // This file is a system header or C++ unfriendly if the old file is.
303 getFileInfo(FE).DirInfo = getFileInfo(CurFE).DirInfo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000304 return FE;
305 }
306 }
307 }
308
309 // If this is a system #include, ignore the user #include locs.
Chris Lattnerc8997182006-06-22 05:52:16 +0000310 unsigned i = isAngled ? SystemDirIdx : 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000311
312 // If this is a #include_next request, start searching after the directory the
313 // file was found in.
314 if (FromDir)
315 i = FromDir-&SearchDirs[0];
316
317 // Check each directory in sequence to see if it contains this file.
318 for (; i != SearchDirs.size(); ++i) {
319 // Concatenate the requested file onto the directory.
320 // FIXME: should be in sys::Path.
321 if (const FileEntry *FE =
322 FileMgr.getFile(SearchDirs[i].getDir()->getName()+"/"+Filename)) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000323 CurDir = &SearchDirs[i];
324
325 // This file is a system header or C++ unfriendly if the dir is.
326 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner22eb9722006-06-18 05:43:12 +0000327 return FE;
328 }
329 }
330
331 // Otherwise, didn't find it.
332 return 0;
333}
334
335/// EnterSourceFile - Add a source file to the top of the include stack and
336/// start lexing tokens from it instead of the current buffer. Return true
337/// on failure.
338void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattnerc8997182006-06-22 05:52:16 +0000339 const DirectoryLookup *CurDir) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000340 ++NumEnteredSourceFiles;
341
342 // Add the current lexer to the include stack.
343 if (CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000344 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup));
Chris Lattner22eb9722006-06-18 05:43:12 +0000345 } else {
346 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
347 }
348
349 if (MaxIncludeStackDepth < IncludeStack.size())
350 MaxIncludeStackDepth = IncludeStack.size();
351
352 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
353
Chris Lattnerc8997182006-06-22 05:52:16 +0000354 CurLexer = new Lexer(Buffer, FileID, *this);
355 CurDirLookup = CurDir;
Chris Lattner0c885f52006-06-21 06:50:18 +0000356
357 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerc8997182006-06-22 05:52:16 +0000358 if (FileChangeHandler) {
359 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
360
361 // Get the file entry for the current file.
362 if (const FileEntry *FE =
363 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
364 FileType = getFileInfo(FE).DirInfo;
365
366 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferStart), true,
367 FileType);
368 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000369}
370
371/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000372/// tokens from it instead of the current buffer.
373void Preprocessor::EnterMacro(LexerToken &Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000374 IdentifierTokenInfo *Identifier = Tok.getIdentifierInfo();
375 MacroInfo &MI = *Identifier->getMacroInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +0000376 if (CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000377 IncludeStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup));
378 CurLexer = 0;
379 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000380 } else if (CurMacroExpander) {
381 MacroStack.push_back(CurMacroExpander);
382 }
383
384 if (MaxMacroStackDepth < MacroStack.size())
385 MaxMacroStackDepth = MacroStack.size();
386
387 // TODO: Figure out arguments.
388
389 // Mark the macro as currently disabled, so that it is not recursively
390 // expanded.
391 MI.DisableMacro();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000392 CurMacroExpander = new MacroExpander(Tok, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000393}
394
395
396//===----------------------------------------------------------------------===//
397// Lexer Event Handling.
398//===----------------------------------------------------------------------===//
399
400/// HandleIdentifier - This callback is invoked when the lexer reads an
401/// identifier. This callback looks up the identifier in the map and/or
402/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnercb283342006-06-18 06:48:37 +0000403void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000404 if (Identifier.getIdentifierInfo() == 0) {
405 // If we are skipping tokens (because we are in a #if 0 block), there will
406 // be no identifier info, just return the token.
407 assert(isSkipping() && "Token isn't an identifier?");
Chris Lattnercb283342006-06-18 06:48:37 +0000408 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000409 }
410 IdentifierTokenInfo &ITI = *Identifier.getIdentifierInfo();
411
412 // FIXME: Check for poisoning in ITI?
413
414 if (MacroInfo *MI = ITI.getMacroInfo()) {
415 if (MI->isEnabled() && !DisableMacroExpansion) {
416 ++NumMacroExpanded;
417 // If we started lexing a macro, enter the macro expansion body.
418 // FIXME: Read/Validate the argument list here!
419
420 // If this macro expands to no tokens, don't bother to push it onto the
421 // expansion stack, only to take it right back off.
422 if (MI->getNumTokens() == 0) {
423 // Ignore this macro use, just return the next token in the current
424 // buffer.
425 bool HadLeadingSpace = Identifier.hasLeadingSpace();
426 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
427
Chris Lattnercb283342006-06-18 06:48:37 +0000428 Lex(Identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000429
430 // If the identifier isn't on some OTHER line, inherit the leading
431 // whitespace/first-on-a-line property of this token. This handles
432 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
433 // empty.
434 if (!Identifier.isAtStartOfLine()) {
435 if (IsAtStartOfLine) Identifier.SetFlag(LexerToken::StartOfLine);
436 if (HadLeadingSpace) Identifier.SetFlag(LexerToken::LeadingSpace);
437 }
438 ++NumFastMacroExpanded;
Chris Lattnercb283342006-06-18 06:48:37 +0000439 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000440
441 } else if (MI->getNumTokens() == 1 &&
442 // Don't handle identifiers, which might need recursive
443 // expansion.
444 MI->getReplacementToken(0).getIdentifierInfo() == 0) {
445 // FIXME: Function-style macros only if no arguments?
446
447 // Otherwise, if this macro expands into a single trivially-expanded
448 // token: expand it now. This handles common cases like
449 // "#define VAL 42".
450
451 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
452 // identifier to the expanded token.
453 bool isAtStartOfLine = Identifier.isAtStartOfLine();
454 bool hasLeadingSpace = Identifier.hasLeadingSpace();
455
456 // Replace the result token.
457 Identifier = MI->getReplacementToken(0);
458
459 // Restore the StartOfLine/LeadingSpace markers.
460 Identifier.SetFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
461 Identifier.SetFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
462
463 // FIXME: Get correct macro expansion stack location info!
464
465 // Since this is not an identifier token, it can't be macro expanded, so
466 // we're done.
467 ++NumFastMacroExpanded;
Chris Lattnercb283342006-06-18 06:48:37 +0000468 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000469 }
470
471 // Start expanding the macro (FIXME, pass arguments).
Chris Lattnercb283342006-06-18 06:48:37 +0000472 EnterMacro(Identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000473
474 // Now that the macro is at the top of the include stack, ask the
475 // preprocessor to read the next token from it.
476 return Lex(Identifier);
477 }
478 }
479
480 // Change the kind of this identifier to the appropriate token kind, e.g.
481 // turning "for" into a keyword.
482 Identifier.SetKind(ITI.getTokenID());
483
484 // If this is an extension token, diagnose its use.
Chris Lattnercb283342006-06-18 06:48:37 +0000485 if (ITI.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner22eb9722006-06-18 05:43:12 +0000486}
487
488/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
489/// the current file. This either returns the EOF token or pops a level off
490/// the include stack and keeps going.
Chris Lattner0c885f52006-06-21 06:50:18 +0000491void Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000492 assert(!CurMacroExpander &&
493 "Ending a file when currently in a macro!");
494
495 // If we are in a #if 0 block skipping tokens, and we see the end of the file,
496 // this is an error condition. Just return the EOF token up to
497 // SkipExcludedConditionalBlock. The Lexer will have already have issued
498 // errors for the unterminated #if's on the conditional stack.
499 if (isSkipping()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000500 Result.StartToken();
501 CurLexer->BufferPtr = CurLexer->BufferEnd;
502 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000503 Result.SetKind(tok::eof);
Chris Lattnercb283342006-06-18 06:48:37 +0000504 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000505 }
506
507 // If this is a #include'd file, pop it off the include stack and continue
508 // lexing the #includer file.
509 if (!IncludeStack.empty()) {
510 // We're done with the #included file.
511 delete CurLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000512 CurLexer = IncludeStack.back().TheLexer;
513 CurDirLookup = IncludeStack.back().TheDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000514 IncludeStack.pop_back();
Chris Lattner0c885f52006-06-21 06:50:18 +0000515
516 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerc8997182006-06-22 05:52:16 +0000517 if (FileChangeHandler && !isEndOfMacro) {
518 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
519
520 // Get the file entry for the current file.
521 if (const FileEntry *FE =
522 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
523 FileType = getFileInfo(FE).DirInfo;
524
Chris Lattner0c885f52006-06-21 06:50:18 +0000525 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattnerc8997182006-06-22 05:52:16 +0000526 false, FileType);
527 }
Chris Lattner0c885f52006-06-21 06:50:18 +0000528
Chris Lattner22eb9722006-06-18 05:43:12 +0000529 return Lex(Result);
530 }
531
Chris Lattnerd01e2912006-06-18 16:22:51 +0000532 Result.StartToken();
533 CurLexer->BufferPtr = CurLexer->BufferEnd;
534 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000535 Result.SetKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000536
537 // We're done with the #included file.
538 delete CurLexer;
539 CurLexer = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000540}
541
542/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattnercb283342006-06-18 06:48:37 +0000543/// the current macro line.
544void Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000545 assert(CurMacroExpander && !CurLexer &&
546 "Ending a macro when currently in a #include file!");
547
548 // Mark macro not ignored now that it is no longer being expanded.
549 CurMacroExpander->getMacro().EnableMacro();
550 delete CurMacroExpander;
551
552 if (!MacroStack.empty()) {
553 // In a nested macro invocation, continue lexing from the macro.
554 CurMacroExpander = MacroStack.back();
555 MacroStack.pop_back();
556 return Lex(Result);
557 } else {
558 CurMacroExpander = 0;
559 // Handle this like a #include file being popped off the stack.
Chris Lattner0c885f52006-06-21 06:50:18 +0000560 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +0000561 }
562}
563
564
565//===----------------------------------------------------------------------===//
566// Utility Methods for Preprocessor Directive Handling.
567//===----------------------------------------------------------------------===//
568
569/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
570/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +0000571void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000572 LexerToken Tmp;
573 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000574 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000575 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +0000576}
577
578/// ReadMacroName - Lex and validate a macro name, which occurs after a
579/// #define or #undef. This sets the token kind to eom and discards the rest
580/// of the macro line if the macro name is invalid.
Chris Lattnercb283342006-06-18 06:48:37 +0000581void Preprocessor::ReadMacroName(LexerToken &MacroNameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000582 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +0000583 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000584
585 // Missing macro name?
586 if (MacroNameTok.getKind() == tok::eom)
587 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
588
589 if (MacroNameTok.getIdentifierInfo() == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +0000590 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000591 // Fall through on error.
592 } else if (0) {
593 // FIXME: Error if defining a C++ named operator.
594
595 } else if (0) {
596 // FIXME: Error if defining "defined", "__DATE__", and other predef macros
597 // in C99 6.10.8.4.
598 } else {
599 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +0000600 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000601 }
602
603
604 // Invalid macro name, read and discard the rest of the line. Then set the
605 // token kind to tok::eom.
606 MacroNameTok.SetKind(tok::eom);
607 return DiscardUntilEndOfDirective();
608}
609
610/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
611/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +0000612void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000613 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +0000614 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000615 // There should be no tokens after the directive, but we allow them as an
616 // extension.
617 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +0000618 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
619 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000620 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000621}
622
623
624
625/// SkipExcludedConditionalBlock - We just read a #if or related directive and
626/// decided that the subsequent tokens are in the #if'd out portion of the
627/// file. Lex the rest of the file, until we see an #endif. If
628/// FoundNonSkipPortion is true, then we have already emitted code for part of
629/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
630/// is true, then #else directives are ok, if not, then we have already seen one
631/// so a #else directive is a duplicate. When this returns, the caller can lex
632/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000633void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +0000634 bool FoundNonSkipPortion,
635 bool FoundElse) {
636 ++NumSkipped;
637 assert(MacroStack.empty() && CurMacroExpander == 0 && CurLexer &&
638 "Lexing a macro, not a file?");
639
640 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
641 FoundNonSkipPortion, FoundElse);
642
643 // Know that we are going to be skipping tokens. Set this flag to indicate
644 // this, which has a couple of effects:
645 // 1. If EOF of the current lexer is found, the include stack isn't popped.
646 // 2. Identifier information is not looked up for identifier tokens. As an
647 // effect of this, implicit macro expansion is naturally disabled.
648 // 3. "#" tokens at the start of a line are treated as normal tokens, not
649 // implicitly transformed by the lexer.
650 // 4. All notes, warnings, and extension messages are disabled.
651 //
652 SkippingContents = true;
653 LexerToken Tok;
654 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +0000655 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000656
657 // If this is the end of the buffer, we have an error. The lexer will have
658 // already handled this error condition, so just return and let the caller
659 // lex after this #include.
660 if (Tok.getKind() == tok::eof) break;
661
662 // If this token is not a preprocessor directive, just skip it.
663 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
664 continue;
665
666 // We just parsed a # character at the start of a line, so we're in
667 // directive mode. Tell the lexer this so any newlines we see will be
668 // converted into an EOM token (this terminates the macro).
669 CurLexer->ParsingPreprocessorDirective = true;
670
671 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000672 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000673
674 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
675 // something bogus), skip it.
676 if (Tok.getKind() != tok::identifier) {
677 CurLexer->ParsingPreprocessorDirective = false;
678 continue;
679 }
680
681 // If the first letter isn't i or e, it isn't intesting to us. We know that
682 // this is safe in the face of spelling differences, because there is no way
683 // to spell an i/e in a strange way that is another letter. Skipping this
684 // allows us to avoid computing the spelling for #define/#undef and other
685 // common directives.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000686 // FIXME: This should use a bit in the identifier information!
Chris Lattner50b497e2006-06-18 16:32:35 +0000687 char FirstChar = SourceMgr.getCharacterData(Tok.getLocation())[0];
Chris Lattner22eb9722006-06-18 05:43:12 +0000688 if (FirstChar >= 'a' && FirstChar <= 'z' &&
689 FirstChar != 'i' && FirstChar != 'e') {
690 CurLexer->ParsingPreprocessorDirective = false;
691 continue;
692 }
693
694 // Strip out trigraphs and embedded newlines.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000695 std::string Directive = getSpelling(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000696 FirstChar = Directive[0];
697 if (FirstChar == 'i' && Directive[1] == 'f') {
698 if (Directive == "if" || Directive == "ifdef" || Directive == "ifndef") {
699 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
700 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +0000701 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +0000702 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +0000703 /*foundnonskip*/false,
704 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +0000705 }
706 } else if (FirstChar == 'e') {
707 if (Directive == "endif") {
Chris Lattnercb283342006-06-18 06:48:37 +0000708 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +0000709 PPConditionalInfo CondInfo;
710 CondInfo.WasSkipping = true; // Silence bogus warning.
711 bool InCond = CurLexer->popConditionalLevel(CondInfo);
712 assert(!InCond && "Can't be skipping if not in a conditional!");
713
714 // If we popped the outermost skipping block, we're done skipping!
715 if (!CondInfo.WasSkipping)
716 break;
717 } else if (Directive == "else") {
718 // #else directive in a skipping conditional. If not in some other
719 // skipping conditional, and if #else hasn't already been seen, enter it
720 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +0000721 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +0000722 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
723
724 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000725 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000726
727 // Note that we've seen a #else in this conditional.
728 CondInfo.FoundElse = true;
729
730 // If the conditional is at the top level, and the #if block wasn't
731 // entered, enter the #else block now.
732 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
733 CondInfo.FoundNonSkip = true;
734 break;
735 }
736 } else if (Directive == "elif") {
737 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
738
739 bool ShouldEnter;
740 // If this is in a skipping block or if we're already handled this #if
741 // block, don't bother parsing the condition.
742 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +0000743 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +0000744 ShouldEnter = false;
745 } else {
746 // Evaluate the #elif condition!
747 const char *Start = CurLexer->BufferPtr;
748
749 // Restore the value of SkippingContents so that identifiers are
750 // looked up, etc, inside the #elif expression.
751 assert(SkippingContents && "We have to be skipping here!");
752 SkippingContents = false;
Chris Lattner7966aaf2006-06-18 06:50:36 +0000753 ShouldEnter = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +0000754 SkippingContents = true;
755 }
756
757 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +0000758 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +0000759
760 // If this condition is true, enter it!
761 if (ShouldEnter) {
762 CondInfo.FoundNonSkip = true;
763 break;
764 }
765 }
766 }
767
768 CurLexer->ParsingPreprocessorDirective = false;
769 }
770
771 // Finally, if we are out of the conditional (saw an #endif or ran off the end
772 // of the file, just stop skipping and return to lexing whatever came after
773 // the #if block.
774 SkippingContents = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000775}
776
777//===----------------------------------------------------------------------===//
778// Preprocessor Directive Handling.
779//===----------------------------------------------------------------------===//
780
781/// HandleDirective - This callback is invoked when the lexer sees a # token
782/// at the start of a line. This consumes the directive, modifies the
783/// lexer/preprocessor state, and advances the lexer(s) so that the next token
784/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +0000785void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000786 // FIXME: TRADITIONAL: # with whitespace before it not recognized by K&R?
787
788 // We just parsed a # character at the start of a line, so we're in directive
789 // mode. Tell the lexer this so any newlines we see will be converted into an
790 // EOM token (this terminates the macro).
791 CurLexer->ParsingPreprocessorDirective = true;
792
793 ++NumDirectives;
794
795 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +0000796 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000797
798 switch (Result.getKind()) {
799 default: break;
800 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +0000801 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +0000802
803#if 0
804 case tok::numeric_constant:
805 // FIXME: implement # 7 line numbers!
806 break;
807#endif
808 case tok::kw_else:
809 return HandleElseDirective(Result);
810 case tok::kw_if:
811 return HandleIfDirective(Result);
812 case tok::identifier:
Chris Lattner40931922006-06-22 06:14:04 +0000813 // Get the identifier name without trigraphs or embedded newlines.
814 const char *Directive = Result.getIdentifierInfo()->getName();
Chris Lattner22eb9722006-06-18 05:43:12 +0000815 bool isExtension = false;
Chris Lattner40931922006-06-22 06:14:04 +0000816 switch (Result.getIdentifierInfo()->getNameLength()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000817 case 4:
Chris Lattner40931922006-06-22 06:14:04 +0000818 if (Directive[0] == 'l' && !strcmp(Directive, "line"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000819 ;
Chris Lattner40931922006-06-22 06:14:04 +0000820 if (Directive[0] == 'e' && !strcmp(Directive, "elif"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000821 return HandleElifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000822 if (Directive[0] == 's' && !strcmp(Directive, "sccs")) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000823 isExtension = true;
824 // SCCS is the same as #ident.
825 }
826 break;
827 case 5:
Chris Lattner40931922006-06-22 06:14:04 +0000828 if (Directive[0] == 'e' && !strcmp(Directive, "endif"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000829 return HandleEndifDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000830 if (Directive[0] == 'i' && !strcmp(Directive, "ifdef"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000831 return HandleIfdefDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +0000832 if (Directive[0] == 'u' && !strcmp(Directive, "undef"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000833 return HandleUndefDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000834 if (Directive[0] == 'e' && !strcmp(Directive, "error"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000835 return HandleUserDiagnosticDirective(Result, false);
Chris Lattner40931922006-06-22 06:14:04 +0000836 if (Directive[0] == 'i' && !strcmp(Directive, "ident"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000837 isExtension = true;
838 break;
839 case 6:
Chris Lattner40931922006-06-22 06:14:04 +0000840 if (Directive[0] == 'd' && !strcmp(Directive, "define"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000841 return HandleDefineDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000842 if (Directive[0] == 'i' && !strcmp(Directive, "ifndef"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000843 return HandleIfdefDirective(Result, true);
Chris Lattner40931922006-06-22 06:14:04 +0000844 if (Directive[0] == 'i' && !strcmp(Directive, "import"))
Chris Lattner22eb9722006-06-18 05:43:12 +0000845 return HandleImportDirective(Result);
Chris Lattner40931922006-06-22 06:14:04 +0000846 if (Directive[0] == 'p' && !strcmp(Directive, "pragma")) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000847 // FIXME: implement #pragma
848 ++NumPragma;
849#if 1
850 // Read the rest of the PP line.
851 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000852 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000853 } while (Result.getKind() != tok::eom);
854
Chris Lattnercb283342006-06-18 06:48:37 +0000855 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000856#endif
Chris Lattner40931922006-06-22 06:14:04 +0000857 } else if (Directive[0] == 'a' && !strcmp(Directive, "assert")) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000858 isExtension = true;
859 }
860 break;
861 case 7:
Chris Lattner40931922006-06-22 06:14:04 +0000862 if (Directive[0] == 'i' && !strcmp(Directive, "include"))
863 return HandleIncludeDirective(Result); // Handle #include.
864 if (Directive[0] == 'w' && !strcmp(Directive, "warning")) {
Chris Lattnercb283342006-06-18 06:48:37 +0000865 Diag(Result, diag::ext_pp_warning_directive);
Chris Lattner504f2eb2006-06-18 07:19:54 +0000866 return HandleUserDiagnosticDirective(Result, true);
Chris Lattnercb283342006-06-18 06:48:37 +0000867 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000868 break;
869 case 8:
Chris Lattner40931922006-06-22 06:14:04 +0000870 if (Directive[0] == 'u' && !strcmp(Directive, "unassert")) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000871 isExtension = true;
872 }
873 break;
874 case 12:
Chris Lattner40931922006-06-22 06:14:04 +0000875 if (Directive[0] == 'i' && !strcmp(Directive, "include_next"))
876 return HandleIncludeNextDirective(Result); // Handle #include_next.
Chris Lattner22eb9722006-06-18 05:43:12 +0000877 break;
878 }
879 break;
880 }
881
882 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +0000883 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +0000884
885 // Read the rest of the PP line.
886 do {
Chris Lattnercb283342006-06-18 06:48:37 +0000887 Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000888 } while (Result.getKind() != tok::eom);
889
890 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +0000891}
892
Chris Lattnercb283342006-06-18 06:48:37 +0000893void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Result,
Chris Lattner22eb9722006-06-18 05:43:12 +0000894 bool isWarning) {
895 // Read the rest of the line raw. We do this because we don't want macros
896 // to be expanded and we don't require that the tokens be valid preprocessing
897 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
898 // collapse multiple consequtive white space between tokens, but this isn't
899 // specified by the standard.
900 std::string Message = CurLexer->ReadToEndOfLine();
901
902 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
903 return Diag(Result, DiagID, Message);
904}
905
906/// HandleIncludeDirective - The "#include" tokens have just been read, read the
907/// file to be included from the lexer, then include it! This is a common
908/// routine with functionality shared between #include, #include_next and
909/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +0000910void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +0000911 const DirectoryLookup *LookupFrom,
912 bool isImport) {
913 ++NumIncluded;
914 LexerToken FilenameTok;
Chris Lattnercb283342006-06-18 06:48:37 +0000915 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000916
917 // If the token kind is EOM, the error has already been diagnosed.
918 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +0000919 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000920
921 // Check that we don't have infinite #include recursion.
922 if (IncludeStack.size() == MaxAllowedIncludeStackDepth-1)
923 return Diag(FilenameTok, diag::err_pp_include_too_deep);
924
925 // Get the text form of the filename.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000926 std::string Filename = getSpelling(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000927 assert(!Filename.empty() && "Can't have tokens with empty spellings!");
928
929 // Make sure the filename is <x> or "x".
930 bool isAngled;
931 if (Filename[0] == '<') {
932 isAngled = true;
933 if (Filename[Filename.size()-1] != '>')
934 return Diag(FilenameTok, diag::err_pp_expects_filename);
935 } else if (Filename[0] == '"') {
936 isAngled = false;
937 if (Filename[Filename.size()-1] != '"')
938 return Diag(FilenameTok, diag::err_pp_expects_filename);
939 } else {
940 return Diag(FilenameTok, diag::err_pp_expects_filename);
941 }
942
943 // Remove the quotes.
944 Filename = std::string(Filename.begin()+1, Filename.end()-1);
945
946 // Diagnose #include "" as invalid.
947 if (Filename.empty())
948 return Diag(FilenameTok, diag::err_pp_empty_filename);
949
950 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +0000951 const DirectoryLookup *CurDir;
952 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +0000953 if (File == 0)
954 return Diag(FilenameTok, diag::err_pp_file_not_found);
955
956 // Get information about this file.
957 PerFileInfo &FileInfo = getFileInfo(File);
958
959 // If this is a #import directive, check that we have not already imported
960 // this header.
961 if (isImport) {
962 // If this has already been imported, don't import it again.
963 FileInfo.isImport = true;
964
965 // Has this already been #import'ed or #include'd?
Chris Lattnercb283342006-06-18 06:48:37 +0000966 if (FileInfo.NumIncludes) return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000967 } else {
968 // Otherwise, if this is a #include of a file that was previously #import'd
969 // or if this is the second #include of a #pragma once file, ignore it.
970 if (FileInfo.isImport)
Chris Lattnercb283342006-06-18 06:48:37 +0000971 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000972 }
973
974 // Look up the file, create a File ID for it.
975 unsigned FileID =
Chris Lattner50b497e2006-06-18 16:32:35 +0000976 SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +0000977 if (FileID == 0)
978 return Diag(FilenameTok, diag::err_pp_file_not_found);
979
980 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +0000981 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +0000982
983 // Increment the number of times this file has been included.
984 ++FileInfo.NumIncludes;
Chris Lattner22eb9722006-06-18 05:43:12 +0000985}
986
987/// HandleIncludeNextDirective - Implements #include_next.
988///
Chris Lattnercb283342006-06-18 06:48:37 +0000989void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
990 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +0000991
992 // #include_next is like #include, except that we start searching after
993 // the current found directory. If we can't do this, issue a
994 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +0000995 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner22eb9722006-06-18 05:43:12 +0000996 if (IncludeStack.empty()) {
997 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +0000998 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +0000999 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001000 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001001 } else {
1002 // Start looking up in the next directory.
1003 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001004 }
1005
1006 return HandleIncludeDirective(IncludeNextTok, Lookup);
1007}
1008
1009/// HandleImportDirective - Implements #import.
1010///
Chris Lattnercb283342006-06-18 06:48:37 +00001011void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1012 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001013
1014 return HandleIncludeDirective(ImportTok, 0, true);
1015}
1016
1017/// HandleDefineDirective - Implements #define. This consumes the entire macro
1018/// line then lets the caller lex the next real token.
1019///
Chris Lattnercb283342006-06-18 06:48:37 +00001020void Preprocessor::HandleDefineDirective(LexerToken &DefineTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 ++NumDefined;
1022 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001023 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001024
1025 // Error reading macro name? If so, diagnostic already issued.
1026 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001027 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001028
Chris Lattner50b497e2006-06-18 16:32:35 +00001029 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001030
1031 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001032 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001033
1034 if (Tok.getKind() == tok::eom) {
1035 // If there is no body to this macro, we have no special handling here.
1036 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1037 // This is a function-like macro definition.
1038 //assert(0 && "Function-like macros not implemented!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 return DiscardUntilEndOfDirective();
1040
1041 } else if (!Tok.hasLeadingSpace()) {
1042 // C99 requires whitespace between the macro definition and the body. Emit
1043 // a diagnostic for something like "#define X+".
1044 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001045 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001046 } else {
1047 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1048 // one in some cases!
1049 }
1050 } else {
1051 // This is a normal token with leading space. Clear the leading space
1052 // marker on the first token to get proper expansion.
1053 Tok.ClearFlag(LexerToken::LeadingSpace);
1054 }
1055
1056 // Read the rest of the macro body.
1057 while (Tok.getKind() != tok::eom) {
1058 MI->AddTokenToBody(Tok);
1059
1060 // FIXME: See create_iso_definition.
1061
1062 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001063 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 }
1065
1066 // Finally, if this identifier already had a macro defined for it, verify that
1067 // the macro bodies are identical and free the old definition.
1068 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1069 // FIXME: Verify the definition is the same.
1070 // Macros must be identical. This means all tokes and whitespace separation
1071 // must be the same.
1072 delete OtherMI;
1073 }
1074
1075 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001076}
1077
1078
1079/// HandleUndefDirective - Implements #undef.
1080///
Chris Lattnercb283342006-06-18 06:48:37 +00001081void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001082 ++NumUndefined;
1083 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001084 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001085
1086 // Error reading macro name? If so, diagnostic already issued.
1087 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001088 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001089
1090 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001091 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001092
1093 // Okay, we finally have a valid identifier to undef.
1094 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1095
1096 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001097 if (MI == 0) return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001098
1099#if 0 // FIXME: implement warn_unused_macros.
1100 if (CPP_OPTION (pfile, warn_unused_macros))
1101 _cpp_warn_if_unused_macro (pfile, node, NULL);
1102#endif
1103
1104 // Free macro definition.
1105 delete MI;
1106 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001107}
1108
1109
1110/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1111/// true when this is a #ifndef directive.
1112///
Chris Lattnercb283342006-06-18 06:48:37 +00001113void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 ++NumIf;
1115 LexerToken DirectiveTok = Result;
1116
1117 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001118 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001119
1120 // Error reading macro name? If so, diagnostic already issued.
1121 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001122 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001123
1124 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnercb283342006-06-18 06:48:37 +00001125 CheckEndOfDirective("#ifdef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001126
1127 // Should we include the stuff contained by this directive?
1128 if (!MacroNameTok.getIdentifierInfo()->getMacroInfo() == isIfndef) {
1129 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001130 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001131 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 } else {
1133 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001134 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001135 /*Foundnonskip*/false,
1136 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001137 }
1138}
1139
1140/// HandleIfDirective - Implements the #if directive.
1141///
Chris Lattnercb283342006-06-18 06:48:37 +00001142void Preprocessor::HandleIfDirective(LexerToken &IfToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001143 ++NumIf;
1144 const char *Start = CurLexer->BufferPtr;
1145
Chris Lattner7966aaf2006-06-18 06:50:36 +00001146 bool ConditionalTrue = EvaluateDirectiveExpression();
Chris Lattner22eb9722006-06-18 05:43:12 +00001147
1148 // Should we include the stuff contained by this directive?
1149 if (ConditionalTrue) {
1150 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001151 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001153 } else {
1154 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001155 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001156 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001157 }
1158}
1159
1160/// HandleEndifDirective - Implements the #endif directive.
1161///
Chris Lattnercb283342006-06-18 06:48:37 +00001162void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001163 ++NumEndif;
1164 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001165 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001166
1167 PPConditionalInfo CondInfo;
1168 if (CurLexer->popConditionalLevel(CondInfo)) {
1169 // No conditionals on the stack: this is an #endif without an #if.
1170 return Diag(EndifToken, diag::err_pp_endif_without_if);
1171 }
1172
1173 assert(!CondInfo.WasSkipping && !isSkipping() &&
1174 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001175}
1176
1177
Chris Lattnercb283342006-06-18 06:48:37 +00001178void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 ++NumElse;
1180 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001181 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001182
1183 PPConditionalInfo CI;
1184 if (CurLexer->popConditionalLevel(CI))
1185 return Diag(Result, diag::pp_err_else_without_if);
1186
1187 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001188 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001189
1190 // Finally, skip the rest of the contents of this block and return the first
1191 // token after it.
1192 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1193 /*FoundElse*/true);
1194}
1195
Chris Lattnercb283342006-06-18 06:48:37 +00001196void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001197 ++NumElse;
1198 // #elif directive in a non-skipping conditional... start skipping.
1199 // We don't care what the condition is, because we will always skip it (since
1200 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001201 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001202
1203 PPConditionalInfo CI;
1204 if (CurLexer->popConditionalLevel(CI))
1205 return Diag(ElifToken, diag::pp_err_elif_without_if);
1206
1207 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001208 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001209
1210 // Finally, skip the rest of the contents of this block and return the first
1211 // token after it.
1212 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1213 /*FoundElse*/CI.FoundElse);
1214}