blob: e5f581ef96fc1a37384d45da7e6bd504347aa176 [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//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000030#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000031#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000032#include "clang/Basic/Diagnostic.h"
33#include "clang/Basic/FileManager.h"
34#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000035#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000036#include "llvm/ADT/SmallVector.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000037#include <iostream>
38using namespace llvm;
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42
Chris Lattner02dffbd2006-10-14 07:50:21 +000043Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
44 TargetInfo &target,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000045 FileManager &FM, SourceManager &SM,
46 HeaderSearch &Headers)
Chris Lattner02dffbd2006-10-14 07:50:21 +000047 : Diags(diags), Features(opts), Target(target), FileMgr(FM), SourceMgr(SM),
Chris Lattner25e0d542006-10-18 06:07:05 +000048 HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerc8997182006-06-22 05:52:16 +000049 CurLexer(0), CurDirLookup(0), CurMacroExpander(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000050 ScratchBuf = new ScratchBuffer(SourceMgr);
51
Chris Lattner22eb9722006-06-18 05:43:12 +000052 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000053 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000054 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000055 NumEnteredSourceFiles = 0;
56 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000057 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000058 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000059 NumSkipped = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000060
Chris Lattner22eb9722006-06-18 05:43:12 +000061 // Macro expansion is enabled.
62 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000063 InMacroArgs = false;
Chris Lattner0c885f52006-06-21 06:50:18 +000064
65 // There is no file-change handler yet.
66 FileChangeHandler = 0;
Chris Lattner01d66cc2006-07-03 22:16:27 +000067 IdentHandler = 0;
Chris Lattnerb8761832006-06-24 21:31:03 +000068
Chris Lattner8ff71992006-07-06 05:17:39 +000069 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
70 // This gets unpoisoned where it is allowed.
71 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
72
Chris Lattnerb8761832006-06-24 21:31:03 +000073 // Initialize the pragma handlers.
74 PragmaHandlers = new PragmaNamespace(0);
75 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000076
77 // Initialize builtin macros like __LINE__ and friends.
78 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000079}
80
81Preprocessor::~Preprocessor() {
82 // Free any active lexers.
83 delete CurLexer;
84
Chris Lattner69772b02006-07-02 20:34:39 +000085 while (!IncludeMacroStack.empty()) {
86 delete IncludeMacroStack.back().TheLexer;
87 delete IncludeMacroStack.back().TheMacroExpander;
88 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000089 }
Chris Lattnerb8761832006-06-24 21:31:03 +000090
91 // Release pragma information.
92 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +000093
94 // Delete the scratch buffer info.
95 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +000096}
97
Chris Lattner87d3bec2006-10-17 03:44:32 +000098
99
Chris Lattner22eb9722006-06-18 05:43:12 +0000100/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
101/// the specified LexerToken's location, translating the token's start
102/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000103void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000104 const std::string &Msg) {
Chris Lattnercb283342006-06-18 06:48:37 +0000105 Diags.Report(Loc, DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000106}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000107
108void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
109 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
110 << getSpelling(Tok) << "'";
111
112 if (!DumpFlags) return;
113 std::cerr << "\t";
114 if (Tok.isAtStartOfLine())
115 std::cerr << " [StartOfLine]";
116 if (Tok.hasLeadingSpace())
117 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000118 if (Tok.isExpandDisabled())
119 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000120 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000121 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000122 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
123 << "']";
124 }
125}
126
127void Preprocessor::DumpMacro(const MacroInfo &MI) const {
128 std::cerr << "MACRO: ";
129 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
130 DumpToken(MI.getReplacementToken(i));
131 std::cerr << " ";
132 }
133 std::cerr << "\n";
134}
135
Chris Lattner22eb9722006-06-18 05:43:12 +0000136void Preprocessor::PrintStats() {
137 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000138 std::cerr << NumDirectives << " directives found:\n";
139 std::cerr << " " << NumDefined << " #define.\n";
140 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000141 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000142 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
143 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
144 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
145 std::cerr << " " << NumElse << " #else/#elif.\n";
146 std::cerr << " " << NumEndif << " #endif.\n";
147 std::cerr << " " << NumPragma << " #pragma.\n";
148 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
149
Chris Lattner78186052006-07-09 00:45:31 +0000150 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
151 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000152 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000153 std::cerr << (NumFastTokenPaste+NumTokenPaste)
154 << " token paste (##) operations performed, "
155 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000156}
157
158//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000159// Token Spelling
160//===----------------------------------------------------------------------===//
161
162
163/// getSpelling() - Return the 'spelling' of this token. The spelling of a
164/// token are the characters used to represent the token in the source file
165/// after trigraph expansion and escaped-newline folding. In particular, this
166/// wants to get the true, uncanonicalized, spelling of things like digraphs
167/// UCNs, etc.
168std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
169 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
170
171 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000172 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000173 if (!Tok.needsCleaning())
174 return std::string(TokStart, TokStart+Tok.getLength());
175
Chris Lattnerd01e2912006-06-18 16:22:51 +0000176 std::string Result;
177 Result.reserve(Tok.getLength());
178
Chris Lattneref9eae12006-07-04 22:33:12 +0000179 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000180 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
181 Ptr != End; ) {
182 unsigned CharSize;
183 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
184 Ptr += CharSize;
185 }
186 assert(Result.size() != unsigned(Tok.getLength()) &&
187 "NeedsCleaning flag set on something that didn't need cleaning!");
188 return Result;
189}
190
191/// getSpelling - This method is used to get the spelling of a token into a
192/// preallocated buffer, instead of as an std::string. The caller is required
193/// to allocate enough space for the token, which is guaranteed to be at least
194/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000195///
196/// Note that this method may do two possible things: it may either fill in
197/// the buffer specified with characters, or it may *change the input pointer*
198/// to point to a constant buffer with the data already in it (avoiding a
199/// copy). The caller is not allowed to modify the returned buffer pointer
200/// if an internal buffer is returned.
201unsigned Preprocessor::getSpelling(const LexerToken &Tok,
202 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000203 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
204
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000205 // If this token is an identifier, just return the string from the identifier
206 // table, which is very quick.
207 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
208 Buffer = II->getName();
209 return Tok.getLength();
210 }
211
212 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000213 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214
215 // If this token contains nothing interesting, return it directly.
216 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000217 Buffer = TokStart;
218 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000219 }
220 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000221 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
223 Ptr != End; ) {
224 unsigned CharSize;
225 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
226 Ptr += CharSize;
227 }
228 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
229 "NeedsCleaning flag set on something that didn't need cleaning!");
230
231 return OutBuf-Buffer;
232}
233
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000234
235/// CreateString - Plop the specified string into a scratch buffer and return a
236/// location for it. If specified, the source location provides a source
237/// location for the token.
238SourceLocation Preprocessor::
239CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
240 if (SLoc.isValid())
241 return ScratchBuf->getToken(Buf, Len, SLoc);
242 return ScratchBuf->getToken(Buf, Len);
243}
244
245
Chris Lattnerd01e2912006-06-18 16:22:51 +0000246//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000247// Source File Location Methods.
248//===----------------------------------------------------------------------===//
249
250
251/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
252/// return null on failure. isAngled indicates whether the file reference is
253/// for system #include's or not (i.e. using <> instead of "").
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000254const FileEntry *Preprocessor::LookupFile(const std::string &Filename,
Chris Lattnerc8997182006-06-22 05:52:16 +0000255 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000256 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000257 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000258 // If the header lookup mechanism may be relative to the current file, pass in
259 // info about where the current file is.
260 const FileEntry *CurFileEnt = 0;
261 if (!isAngled && !FromDir) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000262 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000263 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000264 }
265
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000266 CurDir = CurDirLookup;
267 return HeaderInfo.LookupFile(Filename, isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner22eb9722006-06-18 05:43:12 +0000268}
269
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000270/// isInPrimaryFile - Return true if we're in the top-level file, not in a
271/// #include.
272bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000273 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000274 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000275
Chris Lattner13044d92006-07-03 05:16:44 +0000276 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000277 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000278 if (IncludeMacroStack[i].TheLexer &&
279 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
280 return IncludeMacroStack[i].TheLexer->isMainFile();
281 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000282}
283
284/// getCurrentLexer - Return the current file lexer being lexed from. Note
285/// that this ignores any potentially active macro expansions and _Pragma
286/// expansions going on at the time.
287Lexer *Preprocessor::getCurrentFileLexer() const {
288 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
289
290 // Look for a stacked lexer.
291 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000292 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000293 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
294 return L;
295 }
296 return 0;
297}
298
299
Chris Lattner22eb9722006-06-18 05:43:12 +0000300/// EnterSourceFile - Add a source file to the top of the include stack and
301/// start lexing tokens from it instead of the current buffer. Return true
302/// on failure.
303void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000304 const DirectoryLookup *CurDir,
305 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000306 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000307 ++NumEnteredSourceFiles;
308
Chris Lattner69772b02006-07-02 20:34:39 +0000309 if (MaxIncludeStackDepth < IncludeMacroStack.size())
310 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000311
Chris Lattner22eb9722006-06-18 05:43:12 +0000312 const SourceBuffer *Buffer = SourceMgr.getBuffer(FileID);
Chris Lattner69772b02006-07-02 20:34:39 +0000313 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000314 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000315 EnterSourceFileWithLexer(TheLexer, CurDir);
316}
Chris Lattner22eb9722006-06-18 05:43:12 +0000317
Chris Lattner69772b02006-07-02 20:34:39 +0000318/// EnterSourceFile - Add a source file to the top of the include stack and
319/// start lexing tokens from it instead of the current buffer.
320void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
321 const DirectoryLookup *CurDir) {
322
323 // Add the current lexer to the include stack.
324 if (CurLexer || CurMacroExpander)
325 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
326 CurMacroExpander));
327
328 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000329 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000330 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000331
332 // Notify the client, if desired, that we are in a new source file.
Chris Lattner98a53122006-07-02 23:00:20 +0000333 if (FileChangeHandler && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000334 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
335
336 // Get the file entry for the current file.
337 if (const FileEntry *FE =
338 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000339 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000340
Chris Lattner1840e492006-07-02 22:30:01 +0000341 FileChangeHandler(SourceLocation(CurLexer->getCurFileID(), 0),
Chris Lattner55a60952006-06-25 04:20:34 +0000342 EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000343 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000344}
345
Chris Lattner69772b02006-07-02 20:34:39 +0000346
347
Chris Lattner22eb9722006-06-18 05:43:12 +0000348/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000349/// tokens from it instead of the current buffer.
Chris Lattneree8760b2006-07-15 07:42:55 +0000350void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000351 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
352 CurMacroExpander));
353 CurLexer = 0;
354 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000355
Chris Lattneree8760b2006-07-15 07:42:55 +0000356 CurMacroExpander = new MacroExpander(Tok, Args, *this);
Chris Lattner22eb9722006-06-18 05:43:12 +0000357}
358
Chris Lattner7667d0d2006-07-16 18:16:58 +0000359/// EnterTokenStream - Add a "macro" context to the top of the include stack,
360/// which will cause the lexer to start returning the specified tokens. Note
361/// that these tokens will be re-macro-expanded when/if expansion is enabled.
362/// This method assumes that the specified stream of tokens has a permanent
363/// owner somewhere, so they do not need to be copied.
Chris Lattner70216572006-07-26 03:50:40 +0000364void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000365 // Save our current state.
366 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
367 CurMacroExpander));
368 CurLexer = 0;
369 CurDirLookup = 0;
370
371 // Create a macro expander to expand from the specified token stream.
Chris Lattner70216572006-07-26 03:50:40 +0000372 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
Chris Lattner7667d0d2006-07-16 18:16:58 +0000373}
374
375/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
376/// lexer stack. This should only be used in situations where the current
377/// state of the top-of-stack lexer is known.
378void Preprocessor::RemoveTopOfLexerStack() {
379 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
380 delete CurLexer;
381 delete CurMacroExpander;
382 CurLexer = IncludeMacroStack.back().TheLexer;
383 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
384 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
385 IncludeMacroStack.pop_back();
386}
387
Chris Lattner22eb9722006-06-18 05:43:12 +0000388//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000389// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000390//===----------------------------------------------------------------------===//
391
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000392/// RegisterBuiltinMacro - Register the specified identifier in the identifier
393/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000394IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000395 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000396 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000397
398 // Mark it as being a macro that is builtin.
399 MacroInfo *MI = new MacroInfo(SourceLocation());
400 MI->setIsBuiltinMacro();
401 Id->setMacroInfo(MI);
402 return Id;
403}
404
405
Chris Lattner677757a2006-06-28 05:26:32 +0000406/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
407/// identifier table.
408void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000409 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000410 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000411 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
412 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000413 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000414
415 // GCC Extensions.
416 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
417 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000418 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000419}
420
Chris Lattnerc2395832006-07-09 00:57:04 +0000421/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
422/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000423static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
424 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000425 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
426
427 // If the token isn't an identifier, it's always literally expanded.
428 if (II == 0) return true;
429
430 // If the identifier is a macro, and if that macro is enabled, it may be
431 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000432 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
433 // Fast expanding "#define X X" is ok, because X would be disabled.
434 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000435 return false;
436
437 // If this is an object-like macro invocation, it is safe to trivially expand
438 // it.
439 if (MI->isObjectLike()) return true;
440
441 // If this is a function-like macro invocation, it's safe to trivially expand
442 // as long as the identifier is not a macro argument.
443 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
444 I != E; ++I)
445 if (*I == II)
446 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000447
Chris Lattnerc2395832006-07-09 00:57:04 +0000448 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000449}
450
Chris Lattnerc2395832006-07-09 00:57:04 +0000451
Chris Lattnerafe603f2006-07-11 04:02:46 +0000452/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
453/// lexed is a '('. If so, consume the token and return true, if not, this
454/// method should have no observable side-effect on the lexed tokens.
455bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000456 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000457 unsigned Val;
458 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000459 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000460 else
461 Val = CurMacroExpander->isNextTokenLParen();
462
463 if (Val == 2) {
464 // If we ran off the end of the lexer or macro expander, walk the include
465 // stack, looking for whatever will return the next token.
466 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
467 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
468 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000469 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000470 else
471 Val = Entry.TheMacroExpander->isNextTokenLParen();
472 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000473 }
474
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000475 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
476 // have found something that isn't a '(' or we found the end of the
477 // translation unit. In either case, return false.
478 if (Val != 1)
479 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000480
481 LexerToken Tok;
482 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000483 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
484 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000485}
Chris Lattner677757a2006-06-28 05:26:32 +0000486
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000487/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
488/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner78186052006-07-09 00:45:31 +0000489bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000490 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000491
492 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
493 if (MI->isBuiltinMacro()) {
494 ExpandBuiltinMacro(Identifier);
495 return false;
496 }
497
Chris Lattner81278c62006-10-14 19:03:49 +0000498 // If this is the first use of a target-specific macro, warn about it.
499 if (MI->isTargetSpecific()) {
500 MI->setIsTargetSpecific(false); // Don't warn on second use.
501 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
502 diag::port_target_macro_use);
503 }
504
Chris Lattneree8760b2006-07-15 07:42:55 +0000505 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000506 /// for each macro argument, the list of tokens that were provided to the
507 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000508 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000509
510 // If this is a function-like macro, read the arguments.
511 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000512 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
513 // name isn't a '(', this macro should not be expanded.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000514 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000515 return true;
516
Chris Lattner78186052006-07-09 00:45:31 +0000517 // Remember that we are now parsing the arguments to a macro invocation.
518 // Preprocessor directives used inside macro arguments are not portable, and
519 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000520 InMacroArgs = true;
521 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000522
523 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000524 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000525
526 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000527 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000528
529 ++NumFnMacroExpanded;
530 } else {
531 ++NumMacroExpanded;
532 }
Chris Lattner13044d92006-07-03 05:16:44 +0000533
534 // Notice that this macro has been used.
535 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000536
537 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000538
539 // If this macro expands to no tokens, don't bother to push it onto the
540 // expansion stack, only to take it right back off.
541 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000542 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000543 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000544
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000545 // Ignore this macro use, just return the next token in the current
546 // buffer.
547 bool HadLeadingSpace = Identifier.hasLeadingSpace();
548 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
549
550 Lex(Identifier);
551
552 // If the identifier isn't on some OTHER line, inherit the leading
553 // whitespace/first-on-a-line property of this token. This handles
554 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
555 // empty.
556 if (!Identifier.isAtStartOfLine()) {
Chris Lattner8c204872006-10-14 05:19:21 +0000557 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
558 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000559 }
560 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000561 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000562
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000563 } else if (MI->getNumTokens() == 1 &&
564 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000565 // Otherwise, if this macro expands into a single trivially-expanded
566 // token: expand it now. This handles common cases like
567 // "#define VAL 42".
568
569 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
570 // identifier to the expanded token.
571 bool isAtStartOfLine = Identifier.isAtStartOfLine();
572 bool hasLeadingSpace = Identifier.hasLeadingSpace();
573
574 // Remember where the token is instantiated.
575 SourceLocation InstantiateLoc = Identifier.getLocation();
576
577 // Replace the result token.
578 Identifier = MI->getReplacementToken(0);
579
580 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner8c204872006-10-14 05:19:21 +0000581 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
582 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000583
584 // Update the tokens location to include both its logical and physical
585 // locations.
586 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000587 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000588 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000589
Chris Lattner6e4bf522006-07-27 06:59:25 +0000590 // If this is #define X X, we must mark the result as unexpandible.
591 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
592 if (NewII->getMacroInfo() == MI)
Chris Lattner8c204872006-10-14 05:19:21 +0000593 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000594
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000595 // Since this is not an identifier token, it can't be macro expanded, so
596 // we're done.
597 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000598 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000599 }
600
Chris Lattner78186052006-07-09 00:45:31 +0000601 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000602 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000603
604 // Now that the macro is at the top of the include stack, ask the
605 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000606 Lex(Identifier);
607 return false;
608}
609
Chris Lattneree8760b2006-07-15 07:42:55 +0000610/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000611/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000612/// invocation. This returns null on error.
Chris Lattneree8760b2006-07-15 07:42:55 +0000613MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
614 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000615 // The number of fixed arguments to parse.
616 unsigned NumFixedArgsLeft = MI->getNumArgs();
617 bool isVariadic = MI->isVariadic();
618
Chris Lattner78186052006-07-09 00:45:31 +0000619 // Outer loop, while there are more arguments, keep reading them.
620 LexerToken Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000621 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000622 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000623
624 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000625 // argument is separated by an EOF token. Use a SmallVector so we can avoid
626 // heap allocations in the common case.
627 SmallVector<LexerToken, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000628
629 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000630 while (Tok.getKind() == tok::comma) {
Chris Lattner78186052006-07-09 00:45:31 +0000631 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
632 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000633
Chris Lattner78186052006-07-09 00:45:31 +0000634 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000635 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
636 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000637 LexUnexpandedToken(Tok);
638
639 if (Tok.getKind() == tok::eof) {
640 Diag(MacroName, diag::err_unterm_macro_invoc);
641 // Do not lose the EOF. Return it to the client.
642 MacroName = Tok;
643 return 0;
644 } else if (Tok.getKind() == tok::r_paren) {
645 // If we found the ) token, the macro arg list is done.
646 if (NumParens-- == 0)
647 break;
648 } else if (Tok.getKind() == tok::l_paren) {
649 ++NumParens;
650 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
651 // Comma ends this argument if there are more fixed arguments expected.
652 if (NumFixedArgsLeft)
653 break;
654
Chris Lattner2ada5d32006-07-15 07:51:24 +0000655 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000656 if (!isVariadic) {
657 // Emit the diagnostic at the macro name in case there is a missing ).
658 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000659 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000660 return 0;
661 }
662 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner457fc152006-07-29 06:30:25 +0000663 } else if (Tok.getKind() == tok::comment && !Features.KeepMacroComments) {
664 // If this is a comment token in the argument list and we're just in
665 // -C mode (not -CC mode), discard the comment.
666 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000667 }
668
669 ArgTokens.push_back(Tok);
670 }
671
Chris Lattnera12dd152006-07-11 04:09:02 +0000672 // Empty arguments are standard in C99 and supported as an extension in
673 // other modes.
674 if (ArgTokens.empty() && !Features.C99)
675 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000676
Chris Lattner36b6e812006-07-21 06:38:30 +0000677 // Add a marker EOF token to the end of the token list for this argument.
678 LexerToken EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000679 EOFTok.startToken();
680 EOFTok.setKind(tok::eof);
681 EOFTok.setLocation(Tok.getLocation());
682 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000683 ArgTokens.push_back(EOFTok);
684 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000685 --NumFixedArgsLeft;
686 };
687
688 // Okay, we either found the r_paren. Check to see if we parsed too few
689 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000690 unsigned MinArgsExpected = MI->getNumArgs();
691
Chris Lattner775d8322006-07-29 04:39:41 +0000692 // See MacroArgs instance var for description of this.
693 bool isVarargsElided = false;
694
Chris Lattner2ada5d32006-07-15 07:51:24 +0000695 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000696 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000697 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000698 // Varargs where the named vararg parameter is missing: ok as extension.
699 // #define A(x, ...)
700 // A("blah")
701 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000702
703 // Remember this occurred if this is a C99 macro invocation with at least
704 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000705 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000706 } else if (MI->getNumArgs() == 1) {
707 // #define A(x)
708 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000709 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000710
711 // Empty arguments are standard in C99 and supported as an extension in
712 // other modes.
713 if (ArgTokens.empty() && !Features.C99)
714 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000715 } else {
716 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000717 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000718 return 0;
719 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000720
721 // Add a marker EOF token to the end of the token list for this argument.
722 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000723 Tok.startToken();
724 Tok.setKind(tok::eof);
725 Tok.setLocation(EndLoc);
726 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000727 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000728 }
729
Chris Lattner775d8322006-07-29 04:39:41 +0000730 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000731}
732
Chris Lattnerc673f902006-06-30 06:10:41 +0000733/// ComputeDATE_TIME - Compute the current time, enter it into the specified
734/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
735/// the identifier tokens inserted.
736static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000737 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000738 time_t TT = time(0);
739 struct tm *TM = localtime(&TT);
740
741 static const char * const Months[] = {
742 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
743 };
744
745 char TmpBuffer[100];
746 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
747 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000748 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000749
750 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000751 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000752}
753
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000754/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
755/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner69772b02006-07-02 20:34:39 +0000756void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000757 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000758 IdentifierInfo *II = Tok.getIdentifierInfo();
759 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000760
761 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
762 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000763 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000764 return Handle_Pragma(Tok);
765
Chris Lattner78186052006-07-09 00:45:31 +0000766 ++NumBuiltinMacroExpanded;
767
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000768 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000769
770 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000771 Tok.setIdentifierInfo(0);
772 Tok.clearFlag(LexerToken::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000773
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000774 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000775 // __LINE__ expands to a simple numeric value.
776 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
777 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000778 Tok.setKind(tok::numeric_constant);
779 Tok.setLength(Length);
780 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000781 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000782 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000783 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000784 Diag(Tok, diag::ext_pp_base_file);
785 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
786 while (NextLoc.getFileID() != 0) {
787 Loc = NextLoc;
788 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
789 }
790 }
791
Chris Lattner0766e592006-07-03 01:07:01 +0000792 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
793 std::string FN = SourceMgr.getSourceName(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000794 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000795 Tok.setKind(tok::string_literal);
796 Tok.setLength(FN.size());
797 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000798 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000799 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000800 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000801 Tok.setKind(tok::string_literal);
802 Tok.setLength(strlen("\"Mmm dd yyyy\""));
803 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000804 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000805 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000806 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000807 Tok.setKind(tok::string_literal);
808 Tok.setLength(strlen("\"hh:mm:ss\""));
809 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000810 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000811 Diag(Tok, diag::ext_pp_include_level);
812
813 // Compute the include depth of this token.
814 unsigned Depth = 0;
815 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
816 for (; Loc.getFileID() != 0; ++Depth)
817 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
818
819 // __INCLUDE_LEVEL__ expands to a simple numeric value.
820 sprintf(TmpBuffer, "%u", Depth);
821 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000822 Tok.setKind(tok::numeric_constant);
823 Tok.setLength(Length);
824 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000825 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000826 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
827 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
828 Diag(Tok, diag::ext_pp_timestamp);
829
830 // Get the file that we are lexing out of. If we're currently lexing from
831 // a macro, dig into the include stack.
832 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000833 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000834
835 if (TheLexer)
836 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
837
838 // If this file is older than the file it depends on, emit a diagnostic.
839 const char *Result;
840 if (CurFile) {
841 time_t TT = CurFile->getModificationTime();
842 struct tm *TM = localtime(&TT);
843 Result = asctime(TM);
844 } else {
845 Result = "??? ??? ?? ??:??:?? ????\n";
846 }
847 TmpBuffer[0] = '"';
848 strcpy(TmpBuffer+1, Result);
849 unsigned Len = strlen(TmpBuffer);
850 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000851 Tok.setKind(tok::string_literal);
852 Tok.setLength(Len);
853 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000854 } else {
855 assert(0 && "Unknown identifier!");
856 }
857}
Chris Lattner677757a2006-06-28 05:26:32 +0000858
Chris Lattner13044d92006-07-03 05:16:44 +0000859namespace {
860struct UnusedIdentifierReporter : public IdentifierVisitor {
861 Preprocessor &PP;
862 UnusedIdentifierReporter(Preprocessor &pp) : PP(pp) {}
863
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000864 void VisitIdentifier(IdentifierInfo &II) const {
865 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
866 PP.Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner13044d92006-07-03 05:16:44 +0000867 }
868};
869}
870
Chris Lattner677757a2006-06-28 05:26:32 +0000871//===----------------------------------------------------------------------===//
872// Lexer Event Handling.
873//===----------------------------------------------------------------------===//
874
Chris Lattnercefc7682006-07-08 08:28:12 +0000875/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
876/// identifier information for the token and install it into the token.
877IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
878 const char *BufPtr) {
879 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
880 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
881
882 // Look up this token, see if it is a macro, or if it is a language keyword.
883 IdentifierInfo *II;
884 if (BufPtr && !Identifier.needsCleaning()) {
885 // No cleaning needed, just use the characters from the lexed buffer.
886 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
887 } else {
888 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
889 const char *TmpBuf = (char*)alloca(Identifier.getLength());
890 unsigned Size = getSpelling(Identifier, TmpBuf);
891 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
892 }
Chris Lattner8c204872006-10-14 05:19:21 +0000893 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000894 return II;
895}
896
897
Chris Lattner677757a2006-06-28 05:26:32 +0000898/// HandleIdentifier - This callback is invoked when the lexer reads an
899/// identifier. This callback looks up the identifier in the map and/or
900/// potentially macro expands it or turns it into a named token (like 'for').
901void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000902 assert(Identifier.getIdentifierInfo() &&
903 "Can't handle identifiers without identifier info!");
904
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000905 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000906
907 // If this identifier was poisoned, and if it was not produced from a macro
908 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +0000909 if (II.isPoisoned() && CurLexer) {
910 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
911 Diag(Identifier, diag::err_pp_used_poisoned_id);
912 else
913 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
914 }
Chris Lattner677757a2006-06-28 05:26:32 +0000915
Chris Lattner78186052006-07-09 00:45:31 +0000916 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +0000917 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000918 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
919 if (MI->isEnabled()) {
920 if (!HandleMacroExpandedIdentifier(Identifier, MI))
921 return;
922 } else {
923 // C99 6.10.3.4p2 says that a disabled macro may never again be
924 // expanded, even if it's in a context where it could be expanded in the
925 // future.
Chris Lattner8c204872006-10-14 05:19:21 +0000926 Identifier.setFlag(LexerToken::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000927 }
928 }
Chris Lattner063400e2006-10-14 19:54:15 +0000929 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
930 // If this identifier is a macro on some other target, emit a diagnostic.
931 // This diagnosic is only emitted when macro expansion is enabled, because
932 // the macro would not have been expanded for the other target either.
933 II.setIsOtherTargetMacro(false); // Don't warn on second use.
934 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
935 diag::port_target_macro_use);
936
937 }
Chris Lattner677757a2006-06-28 05:26:32 +0000938
939 // Change the kind of this identifier to the appropriate token kind, e.g.
940 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000941 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000942
943 // If this is an extension token, diagnose its use.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000944 if (II.isExtensionToken()) Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000945}
946
Chris Lattner22eb9722006-06-18 05:43:12 +0000947/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
948/// the current file. This either returns the EOF token or pops a level off
949/// the include stack and keeps going.
Chris Lattner2183a6e2006-07-18 06:36:12 +0000950bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000951 assert(!CurMacroExpander &&
952 "Ending a file when currently in a macro!");
953
Chris Lattner371ac8a2006-07-04 07:11:10 +0000954 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +0000955 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000956 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +0000957 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +0000958 // Okay, this has a controlling macro, remember in PerFileInfo.
959 if (const FileEntry *FE =
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000960 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
961 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +0000962 }
963 }
964
Chris Lattner22eb9722006-06-18 05:43:12 +0000965 // If this is a #include'd file, pop it off the include stack and continue
966 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +0000967 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000968 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +0000969 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +0000970
971 // Notify the client, if desired, that we are in a new source file.
Chris Lattner69772b02006-07-02 20:34:39 +0000972 if (FileChangeHandler && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000973 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
974
975 // Get the file entry for the current file.
976 if (const FileEntry *FE =
977 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000978 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000979
Chris Lattner0c885f52006-06-21 06:50:18 +0000980 FileChangeHandler(CurLexer->getSourceLocation(CurLexer->BufferPtr),
Chris Lattner55a60952006-06-25 04:20:34 +0000981 ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000982 }
Chris Lattner2183a6e2006-07-18 06:36:12 +0000983
984 // Client should lex another token.
985 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000986 }
987
Chris Lattner8c204872006-10-14 05:19:21 +0000988 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000989 CurLexer->BufferPtr = CurLexer->BufferEnd;
990 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +0000991 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000992
993 // We're done with the #included file.
994 delete CurLexer;
995 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +0000996
Chris Lattner03f83482006-07-10 06:16:26 +0000997 // This is the end of the top-level file. If the diag::pp_macro_not_used
998 // diagnostic is enabled, walk all of the identifiers, looking for macros that
999 // have not been used.
1000 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored)
1001 Identifiers.VisitIdentifiers(UnusedIdentifierReporter(*this));
Chris Lattner2183a6e2006-07-18 06:36:12 +00001002
1003 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001004}
1005
1006/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001007/// the current macro expansion or token stream expansion.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001008bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001009 assert(CurMacroExpander && !CurLexer &&
1010 "Ending a macro when currently in a #include file!");
1011
Chris Lattner22eb9722006-06-18 05:43:12 +00001012 delete CurMacroExpander;
1013
Chris Lattner69772b02006-07-02 20:34:39 +00001014 // Handle this like a #include file being popped off the stack.
1015 CurMacroExpander = 0;
1016 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001017}
1018
1019
1020//===----------------------------------------------------------------------===//
1021// Utility Methods for Preprocessor Directive Handling.
1022//===----------------------------------------------------------------------===//
1023
1024/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1025/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001026void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner22eb9722006-06-18 05:43:12 +00001027 LexerToken Tmp;
1028 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001029 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001030 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001031}
1032
1033/// ReadMacroName - Lex and validate a macro name, which occurs after a
1034/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001035/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1036/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001037/// else (e.g. #ifdef).
Chris Lattnere8eef322006-07-08 07:01:00 +00001038void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001039 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001040 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001041
1042 // Missing macro name?
1043 if (MacroNameTok.getKind() == tok::eom)
1044 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1045
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001046 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1047 if (II == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001048 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001049 // Fall through on error.
1050 } else if (0) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001051 // FIXME: C++. Error if defining a C++ named operator.
Chris Lattner22eb9722006-06-18 05:43:12 +00001052
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001053 } else if (isDefineUndef && II->getName()[0] == 'd' && // defined
1054 !strcmp(II->getName()+1, "efined")) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001055 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001056 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001057 } else if (isDefineUndef && II->getMacroInfo() &&
1058 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001059 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001060 if (isDefineUndef == 1)
1061 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1062 else
1063 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 } else {
1065 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001066 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001067 }
1068
Chris Lattner22eb9722006-06-18 05:43:12 +00001069 // Invalid macro name, read and discard the rest of the line. Then set the
1070 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001071 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001072 return DiscardUntilEndOfDirective();
1073}
1074
1075/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1076/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001077void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001078 LexerToken Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001079 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 // There should be no tokens after the directive, but we allow them as an
1081 // extension.
1082 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001083 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1084 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001085 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001086}
1087
1088
1089
1090/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1091/// decided that the subsequent tokens are in the #if'd out portion of the
1092/// file. Lex the rest of the file, until we see an #endif. If
1093/// FoundNonSkipPortion is true, then we have already emitted code for part of
1094/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1095/// is true, then #else directives are ok, if not, then we have already seen one
1096/// so a #else directive is a duplicate. When this returns, the caller can lex
1097/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001098void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 bool FoundNonSkipPortion,
1100 bool FoundElse) {
1101 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001102 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 "Lexing a macro, not a file?");
1104
1105 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1106 FoundNonSkipPortion, FoundElse);
1107
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001108 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1109 // disabling warnings, etc.
1110 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001111 LexerToken Tok;
1112 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001113 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001114
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001115 // If this is the end of the buffer, we have an error.
1116 if (Tok.getKind() == tok::eof) {
1117 // Emit errors for each unterminated conditional on the stack, including
1118 // the current one.
1119 while (!CurLexer->ConditionalStack.empty()) {
1120 Diag(CurLexer->ConditionalStack.back().IfLoc,
1121 diag::err_pp_unterminated_conditional);
1122 CurLexer->ConditionalStack.pop_back();
1123 }
1124
1125 // Just return and let the caller lex after this #include.
1126 break;
1127 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001128
1129 // If this token is not a preprocessor directive, just skip it.
1130 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1131 continue;
1132
1133 // We just parsed a # character at the start of a line, so we're in
1134 // directive mode. Tell the lexer this so any newlines we see will be
1135 // converted into an EOM token (this terminates the macro).
1136 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001137 CurLexer->KeepCommentMode = false;
1138
Chris Lattner22eb9722006-06-18 05:43:12 +00001139
1140 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001141 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001142
1143 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1144 // something bogus), skip it.
1145 if (Tok.getKind() != tok::identifier) {
1146 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001147 // Restore comment saving mode.
1148 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001149 continue;
1150 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001151
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 // If the first letter isn't i or e, it isn't intesting to us. We know that
1153 // this is safe in the face of spelling differences, because there is no way
1154 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001155 // allows us to avoid looking up the identifier info for #define/#undef and
1156 // other common directives.
1157 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1158 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001159 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1160 FirstChar != 'i' && FirstChar != 'e') {
1161 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001162 // Restore comment saving mode.
1163 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001164 continue;
1165 }
1166
Chris Lattnere60165f2006-06-22 06:36:29 +00001167 // Get the identifier name without trigraphs or embedded newlines. Note
1168 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1169 // when skipping.
1170 // TODO: could do this with zero copies in the no-clean case by using
1171 // strncmp below.
1172 char Directive[20];
1173 unsigned IdLen;
1174 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1175 IdLen = Tok.getLength();
1176 memcpy(Directive, RawCharData, IdLen);
1177 Directive[IdLen] = 0;
1178 } else {
1179 std::string DirectiveStr = getSpelling(Tok);
1180 IdLen = DirectiveStr.size();
1181 if (IdLen >= 20) {
1182 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001183 // Restore comment saving mode.
1184 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001185 continue;
1186 }
1187 memcpy(Directive, &DirectiveStr[0], IdLen);
1188 Directive[IdLen] = 0;
1189 }
1190
Chris Lattner22eb9722006-06-18 05:43:12 +00001191 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001192 if ((IdLen == 2) || // "if"
1193 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1194 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001195 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1196 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001197 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001198 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001199 /*foundnonskip*/false,
1200 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001201 }
1202 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001203 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001204 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001205 PPConditionalInfo CondInfo;
1206 CondInfo.WasSkipping = true; // Silence bogus warning.
1207 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1208 assert(!InCond && "Can't be skipping if not in a conditional!");
1209
1210 // If we popped the outermost skipping block, we're done skipping!
1211 if (!CondInfo.WasSkipping)
1212 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001213 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001214 // #else directive in a skipping conditional. If not in some other
1215 // skipping conditional, and if #else hasn't already been seen, enter it
1216 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001217 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001218 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1219
1220 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001221 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001222
1223 // Note that we've seen a #else in this conditional.
1224 CondInfo.FoundElse = true;
1225
1226 // If the conditional is at the top level, and the #if block wasn't
1227 // entered, enter the #else block now.
1228 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1229 CondInfo.FoundNonSkip = true;
1230 break;
1231 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001232 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001233 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1234
1235 bool ShouldEnter;
1236 // If this is in a skipping block or if we're already handled this #if
1237 // block, don't bother parsing the condition.
1238 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001239 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001240 ShouldEnter = false;
1241 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001242 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001243 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001244 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1245 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001246 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001247 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001248 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 }
1250
1251 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001252 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001253
1254 // If this condition is true, enter it!
1255 if (ShouldEnter) {
1256 CondInfo.FoundNonSkip = true;
1257 break;
1258 }
1259 }
1260 }
1261
1262 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001263 // Restore comment saving mode.
1264 CurLexer->KeepCommentMode = Features.KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 }
1266
1267 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1268 // of the file, just stop skipping and return to lexing whatever came after
1269 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001270 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001271}
1272
1273//===----------------------------------------------------------------------===//
1274// Preprocessor Directive Handling.
1275//===----------------------------------------------------------------------===//
1276
1277/// HandleDirective - This callback is invoked when the lexer sees a # token
1278/// at the start of a line. This consumes the directive, modifies the
1279/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1280/// read is the correct one.
Chris Lattnercb283342006-06-18 06:48:37 +00001281void Preprocessor::HandleDirective(LexerToken &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001282 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001283
1284 // We just parsed a # character at the start of a line, so we're in directive
1285 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001286 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 CurLexer->ParsingPreprocessorDirective = true;
1288
1289 ++NumDirectives;
1290
Chris Lattner371ac8a2006-07-04 07:11:10 +00001291 // We are about to read a token. For the multiple-include optimization FA to
1292 // work, we have to remember if we had read any tokens *before* this
1293 // pp-directive.
1294 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1295
Chris Lattner78186052006-07-09 00:45:31 +00001296 // Read the next token, the directive flavor. This isn't expanded due to
1297 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001298 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001299
Chris Lattner78186052006-07-09 00:45:31 +00001300 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1301 // #define A(x) #x
1302 // A(abc
1303 // #warning blah
1304 // def)
1305 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001306 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001307 Diag(Result, diag::ext_embedded_directive);
1308
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001311 return; // null directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001312
Chris Lattner22eb9722006-06-18 05:43:12 +00001313 case tok::numeric_constant:
1314 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001315 DiscardUntilEndOfDirective();
1316 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001317 default:
1318 IdentifierInfo *II = Result.getIdentifierInfo();
1319 if (II == 0) break; // Not an identifier.
1320
1321 // Ask what the preprocessor keyword ID is.
1322 switch (II->getPPKeywordID()) {
1323 default: break;
1324 // C99 6.10.1 - Conditional Inclusion.
1325 case tok::pp_if:
1326 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1327 case tok::pp_ifdef:
1328 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1329 case tok::pp_ifndef:
1330 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1331 case tok::pp_elif:
1332 return HandleElifDirective(Result);
1333 case tok::pp_else:
1334 return HandleElseDirective(Result);
1335 case tok::pp_endif:
1336 return HandleEndifDirective(Result);
1337
1338 // C99 6.10.2 - Source File Inclusion.
1339 case tok::pp_include:
1340 return HandleIncludeDirective(Result); // Handle #include.
1341
1342 // C99 6.10.3 - Macro Replacement.
1343 case tok::pp_define:
1344 return HandleDefineDirective(Result, false);
1345 case tok::pp_undef:
1346 return HandleUndefDirective(Result);
1347
1348 // C99 6.10.4 - Line Control.
1349 case tok::pp_line:
1350 // FIXME: implement #line
1351 DiscardUntilEndOfDirective();
1352 return;
1353
1354 // C99 6.10.5 - Error Directive.
1355 case tok::pp_error:
1356 return HandleUserDiagnosticDirective(Result, false);
1357
1358 // C99 6.10.6 - Pragma Directive.
1359 case tok::pp_pragma:
1360 return HandlePragmaDirective();
1361
1362 // GNU Extensions.
1363 case tok::pp_import:
1364 return HandleImportDirective(Result);
1365 case tok::pp_include_next:
1366 return HandleIncludeNextDirective(Result);
1367
1368 case tok::pp_warning:
1369 Diag(Result, diag::ext_pp_warning_directive);
1370 return HandleUserDiagnosticDirective(Result, true);
1371 case tok::pp_ident:
1372 return HandleIdentSCCSDirective(Result);
1373 case tok::pp_sccs:
1374 return HandleIdentSCCSDirective(Result);
1375 case tok::pp_assert:
1376 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001378 case tok::pp_unassert:
1379 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001381
1382 // clang extensions.
1383 case tok::pp_define_target:
1384 return HandleDefineDirective(Result, true);
1385 case tok::pp_define_other_target:
1386 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001387 }
1388 break;
1389 }
1390
1391 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001392 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001393
1394 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001395 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001396
1397 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001398}
1399
Chris Lattner01d66cc2006-07-03 22:16:27 +00001400void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001401 bool isWarning) {
1402 // Read the rest of the line raw. We do this because we don't want macros
1403 // to be expanded and we don't require that the tokens be valid preprocessing
1404 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1405 // collapse multiple consequtive white space between tokens, but this isn't
1406 // specified by the standard.
1407 std::string Message = CurLexer->ReadToEndOfLine();
1408
1409 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001410 return Diag(Tok, DiagID, Message);
1411}
1412
1413/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1414///
1415void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001416 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001417 Diag(Tok, diag::ext_pp_ident_directive);
1418
Chris Lattner371ac8a2006-07-04 07:11:10 +00001419 // Read the string argument.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001420 LexerToken StrTok;
1421 Lex(StrTok);
1422
1423 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001424 if (StrTok.getKind() != tok::string_literal &&
1425 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001426 return Diag(StrTok, diag::err_pp_malformed_ident);
1427
1428 // Verify that there is nothing after the string, other than EOM.
1429 CheckEndOfDirective("#ident");
1430
1431 if (IdentHandler)
1432 IdentHandler(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001433}
1434
Chris Lattnerb8761832006-06-24 21:31:03 +00001435//===----------------------------------------------------------------------===//
1436// Preprocessor Include Directive Handling.
1437//===----------------------------------------------------------------------===//
1438
Chris Lattner22eb9722006-06-18 05:43:12 +00001439/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1440/// file to be included from the lexer, then include it! This is a common
1441/// routine with functionality shared between #include, #include_next and
1442/// #import.
Chris Lattnercb283342006-06-18 06:48:37 +00001443void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001444 const DirectoryLookup *LookupFrom,
1445 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001446
Chris Lattner22eb9722006-06-18 05:43:12 +00001447 LexerToken FilenameTok;
Chris Lattner269c2322006-06-25 06:23:00 +00001448 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001449
1450 // If the token kind is EOM, the error has already been diagnosed.
1451 if (FilenameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001452 return;
Chris Lattner269c2322006-06-25 06:23:00 +00001453
1454 // Verify that there is nothing after the filename, other than EOM. Use the
1455 // preprocessor to lex this in case lexing the filename entered a macro.
1456 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001457
1458 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001459 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001460 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1461
Chris Lattner269c2322006-06-25 06:23:00 +00001462 // Find out whether the filename is <x> or "x".
1463 bool isAngled = Filename[0] == '<';
Chris Lattner22eb9722006-06-18 05:43:12 +00001464
1465 // Remove the quotes.
1466 Filename = std::string(Filename.begin()+1, Filename.end()-1);
1467
Chris Lattner22eb9722006-06-18 05:43:12 +00001468 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001469 const DirectoryLookup *CurDir;
1470 const FileEntry *File = LookupFile(Filename, isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001471 if (File == 0)
1472 return Diag(FilenameTok, diag::err_pp_file_not_found);
1473
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001474 // Ask HeaderInfo if we should enter this #include file.
1475 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1476 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001477 return;
1478 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001479
1480 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001481 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001482 if (FileID == 0)
1483 return Diag(FilenameTok, diag::err_pp_file_not_found);
1484
1485 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001486 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001487}
1488
1489/// HandleIncludeNextDirective - Implements #include_next.
1490///
Chris Lattnercb283342006-06-18 06:48:37 +00001491void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1492 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001493
1494 // #include_next is like #include, except that we start searching after
1495 // the current found directory. If we can't do this, issue a
1496 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001497 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001498 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001499 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001500 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001501 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001502 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001503 } else {
1504 // Start looking up in the next directory.
1505 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 }
1507
1508 return HandleIncludeDirective(IncludeNextTok, Lookup);
1509}
1510
1511/// HandleImportDirective - Implements #import.
1512///
Chris Lattnercb283342006-06-18 06:48:37 +00001513void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1514 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001515
1516 return HandleIncludeDirective(ImportTok, 0, true);
1517}
1518
Chris Lattnerb8761832006-06-24 21:31:03 +00001519//===----------------------------------------------------------------------===//
1520// Preprocessor Macro Directive Handling.
1521//===----------------------------------------------------------------------===//
1522
Chris Lattnercefc7682006-07-08 08:28:12 +00001523/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1524/// definition has just been read. Lex the rest of the arguments and the
1525/// closing ), updating MI with what we learn. Return true if an error occurs
1526/// parsing the arg list.
1527bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1528 LexerToken Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001529 while (1) {
1530 LexUnexpandedToken(Tok);
1531 switch (Tok.getKind()) {
1532 case tok::r_paren:
1533 // Found the end of the argument list.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001534 if (MI->arg_begin() == MI->arg_end()) return false; // #define FOO()
Chris Lattnercefc7682006-07-08 08:28:12 +00001535 // Otherwise we have #define FOO(A,)
1536 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1537 return true;
1538 case tok::ellipsis: // #define X(... -> C99 varargs
1539 // Warn if use of C99 feature in non-C99 mode.
1540 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1541
1542 // Lex the token after the identifier.
1543 LexUnexpandedToken(Tok);
1544 if (Tok.getKind() != tok::r_paren) {
1545 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1546 return true;
1547 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001548 // Add the __VA_ARGS__ identifier as an argument.
1549 MI->addArgument(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001550 MI->setIsC99Varargs();
1551 return false;
1552 case tok::eom: // #define X(
1553 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1554 return true;
1555 default: // #define X(1
1556 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1557 return true;
1558 case tok::identifier:
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001559 IdentifierInfo *II = Tok.getIdentifierInfo();
1560
1561 // If this is already used as an argument, it is used multiple times (e.g.
1562 // #define X(A,A.
Chris Lattnerc6532462006-07-15 06:55:18 +00001563 if (MI->getArgumentNum(II) != -1) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001564 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1565 return true;
1566 }
1567
1568 // Add the argument to the macro info.
1569 MI->addArgument(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001570
1571 // Lex the token after the identifier.
1572 LexUnexpandedToken(Tok);
1573
1574 switch (Tok.getKind()) {
1575 default: // #define X(A B
1576 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1577 return true;
1578 case tok::r_paren: // #define X(A)
1579 return false;
1580 case tok::comma: // #define X(A,
1581 break;
1582 case tok::ellipsis: // #define X(A... -> GCC extension
1583 // Diagnose extension.
1584 Diag(Tok, diag::ext_named_variadic_macro);
1585
1586 // Lex the token after the identifier.
1587 LexUnexpandedToken(Tok);
1588 if (Tok.getKind() != tok::r_paren) {
1589 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1590 return true;
1591 }
1592
1593 MI->setIsGNUVarargs();
1594 return false;
1595 }
1596 }
1597 }
1598}
1599
Chris Lattner22eb9722006-06-18 05:43:12 +00001600/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001601/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1602/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001603///
Chris Lattner81278c62006-10-14 19:03:49 +00001604void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1605 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001606 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001607
Chris Lattner22eb9722006-06-18 05:43:12 +00001608 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001609 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001610
1611 // Error reading macro name? If so, diagnostic already issued.
1612 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001613 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001614
Chris Lattner457fc152006-07-29 06:30:25 +00001615 // If we are supposed to keep comments in #defines, reenable comment saving
1616 // mode.
1617 CurLexer->KeepCommentMode = Features.KeepMacroComments;
1618
Chris Lattner063400e2006-10-14 19:54:15 +00001619 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001620 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001621 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001622
Chris Lattner063400e2006-10-14 19:54:15 +00001623 // If the identifier is an 'other target' macro, clear this bit.
1624 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1625
1626
Chris Lattner22eb9722006-06-18 05:43:12 +00001627 LexerToken Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001628 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001629
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001630 // If this is a function-like macro definition, parse the argument list,
1631 // marking each of the identifiers as being used as macro arguments. Also,
1632 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001633 if (Tok.getKind() == tok::eom) {
1634 // If there is no body to this macro, we have no special handling here.
1635 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001636 // This is a function-like macro definition. Read the argument list.
1637 MI->setIsFunctionLike();
1638 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001639 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001640 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001641 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001642 if (CurLexer->ParsingPreprocessorDirective)
1643 DiscardUntilEndOfDirective();
1644 return;
1645 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001646
Chris Lattner815a1f92006-07-08 20:48:04 +00001647 // Read the first token after the arg list for down below.
1648 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001649 } else if (!Tok.hasLeadingSpace()) {
1650 // C99 requires whitespace between the macro definition and the body. Emit
1651 // a diagnostic for something like "#define X+".
1652 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001653 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001654 } else {
1655 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1656 // one in some cases!
1657 }
1658 } else {
1659 // This is a normal token with leading space. Clear the leading space
1660 // marker on the first token to get proper expansion.
Chris Lattner8c204872006-10-14 05:19:21 +00001661 Tok.clearFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001662 }
1663
Chris Lattner7e374832006-07-29 03:46:57 +00001664 // If this is a definition of a variadic C99 function-like macro, not using
1665 // the GNU named varargs extension, enabled __VA_ARGS__.
1666
1667 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1668 // This gets unpoisoned where it is allowed.
1669 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1670 if (MI->isC99Varargs())
1671 Ident__VA_ARGS__->setIsPoisoned(false);
1672
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 // Read the rest of the macro body.
1674 while (Tok.getKind() != tok::eom) {
1675 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001676
1677 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
Chris Lattner69f88b82006-07-11 05:07:29 +00001678 // parameters in function-like macro expansions.
1679 if (Tok.getKind() != tok::hash || MI->isObjectLike()) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001680 // Get the next token of the macro.
1681 LexUnexpandedToken(Tok);
1682 continue;
1683 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001684
Chris Lattner815a1f92006-07-08 20:48:04 +00001685 // Get the next token of the macro.
1686 LexUnexpandedToken(Tok);
1687
1688 // Not a macro arg identifier?
Chris Lattnerc6532462006-07-15 06:55:18 +00001689 if (!Tok.getIdentifierInfo() ||
Chris Lattner95a06b32006-07-30 08:40:43 +00001690 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001691 Diag(Tok, diag::err_pp_stringize_not_parameter);
Chris Lattner815a1f92006-07-08 20:48:04 +00001692 delete MI;
Chris Lattner7e374832006-07-29 03:46:57 +00001693
1694 // Disable __VA_ARGS__ again.
1695 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattner815a1f92006-07-08 20:48:04 +00001696 return;
1697 }
1698
1699 // Things look ok, add the param name token to the macro.
1700 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001701
Chris Lattner22eb9722006-06-18 05:43:12 +00001702 // Get the next token of the macro.
Chris Lattnercb283342006-06-18 06:48:37 +00001703 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001704 }
Chris Lattner7e374832006-07-29 03:46:57 +00001705
1706 // Disable __VA_ARGS__ again.
1707 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001708
Chris Lattnerbff18d52006-07-06 04:49:18 +00001709 // Check that there is no paste (##) operator at the begining or end of the
1710 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00001711 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00001712 if (NumTokens != 0) {
1713 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001714 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001715 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001716 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001717 }
1718 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00001719 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001720 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00001721 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00001722 }
1723 }
1724
Chris Lattner13044d92006-07-03 05:16:44 +00001725 // If this is the primary source file, remember that this macro hasn't been
1726 // used yet.
1727 if (isInPrimaryFile())
1728 MI->setIsUsed(false);
1729
Chris Lattner22eb9722006-06-18 05:43:12 +00001730 // Finally, if this identifier already had a macro defined for it, verify that
1731 // the macro bodies are identical and free the old definition.
1732 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00001733 if (!OtherMI->isUsed())
1734 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1735
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00001737 // must be the same. C99 6.10.3.2.
1738 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00001739 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1740 MacroNameTok.getIdentifierInfo()->getName());
1741 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1742 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001743 delete OtherMI;
1744 }
1745
1746 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00001747}
1748
Chris Lattner063400e2006-10-14 19:54:15 +00001749/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1750void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1751 LexerToken MacroNameTok;
1752 ReadMacroName(MacroNameTok, 1);
1753
1754 // Error reading macro name? If so, diagnostic already issued.
1755 if (MacroNameTok.getKind() == tok::eom)
1756 return;
1757
1758 // Check to see if this is the last token on the #undef line.
1759 CheckEndOfDirective("#define_other_target");
1760
1761 // If there is already a macro defined by this name, turn it into a
1762 // target-specific define.
1763 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1764 MI->setIsTargetSpecific(true);
1765 return;
1766 }
1767
1768 // Mark the identifier as being a macro on some other target.
1769 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1770}
1771
Chris Lattner22eb9722006-06-18 05:43:12 +00001772
1773/// HandleUndefDirective - Implements #undef.
1774///
Chris Lattnercb283342006-06-18 06:48:37 +00001775void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001776 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001777
Chris Lattner22eb9722006-06-18 05:43:12 +00001778 LexerToken MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001779 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00001780
1781 // Error reading macro name? If so, diagnostic already issued.
1782 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001783 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001784
1785 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00001786 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00001787
1788 // Okay, we finally have a valid identifier to undef.
1789 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1790
Chris Lattner063400e2006-10-14 19:54:15 +00001791 // #undef untaints an identifier if it were marked by define_other_target.
1792 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1793
Chris Lattner22eb9722006-06-18 05:43:12 +00001794 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00001795 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00001796
Chris Lattner13044d92006-07-03 05:16:44 +00001797 if (!MI->isUsed())
1798 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00001799
1800 // Free macro definition.
1801 delete MI;
1802 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001803}
1804
1805
Chris Lattnerb8761832006-06-24 21:31:03 +00001806//===----------------------------------------------------------------------===//
1807// Preprocessor Conditional Directive Handling.
1808//===----------------------------------------------------------------------===//
1809
Chris Lattner22eb9722006-06-18 05:43:12 +00001810/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00001811/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1812/// if any tokens have been returned or pp-directives activated before this
1813/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00001814///
Chris Lattner371ac8a2006-07-04 07:11:10 +00001815void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1816 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001817 ++NumIf;
1818 LexerToken DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001819
Chris Lattner22eb9722006-06-18 05:43:12 +00001820 LexerToken MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00001821 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001822
1823 // Error reading macro name? If so, diagnostic already issued.
1824 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001825 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001826
1827 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001828 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1829
1830 // If the start of a top-level #ifdef, inform MIOpt.
1831 if (!ReadAnyTokensBeforeDirective &&
1832 CurLexer->getConditionalStackDepth() == 0) {
1833 assert(isIfndef && "#ifdef shouldn't reach here");
1834 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
1835 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001836
Chris Lattner063400e2006-10-14 19:54:15 +00001837 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1838 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00001839
Chris Lattner81278c62006-10-14 19:03:49 +00001840 // If there is a macro, process it.
1841 if (MI) {
1842 // Mark it used.
1843 MI->setIsUsed(true);
1844
1845 // If this is the first use of a target-specific macro, warn about it.
1846 if (MI->isTargetSpecific()) {
1847 MI->setIsTargetSpecific(false); // Don't warn on second use.
1848 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1849 diag::port_target_macro_use);
1850 }
Chris Lattner063400e2006-10-14 19:54:15 +00001851 } else {
1852 // Use of a target-specific macro for some other target? If so, warn.
1853 if (MII->isOtherTargetMacro()) {
1854 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
1855 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
1856 diag::port_target_macro_use);
1857 }
Chris Lattner81278c62006-10-14 19:03:49 +00001858 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00001859
Chris Lattner22eb9722006-06-18 05:43:12 +00001860 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00001861 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001862 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001863 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001864 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001865 } else {
1866 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001867 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00001868 /*Foundnonskip*/false,
1869 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001870 }
1871}
1872
1873/// HandleIfDirective - Implements the #if directive.
1874///
Chris Lattnera8654ca2006-07-04 17:42:08 +00001875void Preprocessor::HandleIfDirective(LexerToken &IfToken,
1876 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001877 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001878
Chris Lattner371ac8a2006-07-04 07:11:10 +00001879 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001880 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001881 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001882
1883 // Should we include the stuff contained by this directive?
1884 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00001885 // If this condition is equivalent to #ifndef X, and if this is the first
1886 // directive seen, handle it for the multiple-include optimization.
1887 if (!ReadAnyTokensBeforeDirective &&
1888 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
1889 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1890
Chris Lattner22eb9722006-06-18 05:43:12 +00001891 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00001892 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001894 } else {
1895 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00001896 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00001897 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001898 }
1899}
1900
1901/// HandleEndifDirective - Implements the #endif directive.
1902///
Chris Lattnercb283342006-06-18 06:48:37 +00001903void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001904 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001905
Chris Lattner22eb9722006-06-18 05:43:12 +00001906 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00001907 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001908
1909 PPConditionalInfo CondInfo;
1910 if (CurLexer->popConditionalLevel(CondInfo)) {
1911 // No conditionals on the stack: this is an #endif without an #if.
1912 return Diag(EndifToken, diag::err_pp_endif_without_if);
1913 }
1914
Chris Lattner371ac8a2006-07-04 07:11:10 +00001915 // If this the end of a top-level #endif, inform MIOpt.
1916 if (CurLexer->getConditionalStackDepth() == 0)
1917 CurLexer->MIOpt.ExitTopLevelConditional();
1918
Chris Lattner538d7f32006-07-20 04:31:52 +00001919 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001920 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001921}
1922
1923
Chris Lattnercb283342006-06-18 06:48:37 +00001924void Preprocessor::HandleElseDirective(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001925 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001926
Chris Lattner22eb9722006-06-18 05:43:12 +00001927 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00001928 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001929
1930 PPConditionalInfo CI;
1931 if (CurLexer->popConditionalLevel(CI))
1932 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001933
1934 // If this is a top-level #else, inform the MIOpt.
1935 if (CurLexer->getConditionalStackDepth() == 0)
1936 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00001937
1938 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001939 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001940
1941 // Finally, skip the rest of the contents of this block and return the first
1942 // token after it.
1943 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1944 /*FoundElse*/true);
1945}
1946
Chris Lattnercb283342006-06-18 06:48:37 +00001947void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001949
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 // #elif directive in a non-skipping conditional... start skipping.
1951 // We don't care what the condition is, because we will always skip it (since
1952 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00001953 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001954
1955 PPConditionalInfo CI;
1956 if (CurLexer->popConditionalLevel(CI))
1957 return Diag(ElifToken, diag::pp_err_elif_without_if);
1958
Chris Lattner371ac8a2006-07-04 07:11:10 +00001959 // If this is a top-level #elif, inform the MIOpt.
1960 if (CurLexer->getConditionalStackDepth() == 0)
1961 CurLexer->MIOpt.FoundTopLevelElse();
1962
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001964 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001965
1966 // Finally, skip the rest of the contents of this block and return the first
1967 // token after it.
1968 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1969 /*FoundElse*/CI.FoundElse);
1970}
Chris Lattnerb8761832006-06-24 21:31:03 +00001971