blob: b51222cefd3bdcb9c1dbe822f2f7463d3b9221d6 [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"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000031#include "clang/Lex/PPCallbacks.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000032#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000033#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000037#include "clang/Basic/TargetInfo.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000039#include "llvm/Support/MemoryBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000040#include <iostream>
Chris Lattnera2633932007-09-03 18:30:32 +000041#include <ctime>
Chris Lattner22eb9722006-06-18 05:43:12 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
45
Chris Lattner02dffbd2006-10-14 07:50:21 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000047 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000048 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000049 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +000051 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000053
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000055 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000057 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000059 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000060 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000061 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000062
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
Chris Lattner22eb9722006-06-18 05:43:12 +000067 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000069 InMacroArgs = false;
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000070 NumCachedMacroExpanders = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000071
Chris Lattner8ff71992006-07-06 05:17:39 +000072 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
73 // This gets unpoisoned where it is allowed.
74 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
75
Chris Lattnerb8761832006-06-24 21:31:03 +000076 // Initialize the pragma handlers.
77 PragmaHandlers = new PragmaNamespace(0);
78 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000079
80 // Initialize builtin macros like __LINE__ and friends.
81 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000082}
83
84Preprocessor::~Preprocessor() {
85 // Free any active lexers.
86 delete CurLexer;
87
Chris Lattner69772b02006-07-02 20:34:39 +000088 while (!IncludeMacroStack.empty()) {
89 delete IncludeMacroStack.back().TheLexer;
90 delete IncludeMacroStack.back().TheMacroExpander;
91 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000092 }
Chris Lattnerb8761832006-06-24 21:31:03 +000093
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000094 // Free any cached macro expanders.
95 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
96 delete MacroExpanderCache[i];
97
Chris Lattnerb8761832006-06-24 21:31:03 +000098 // Release pragma information.
99 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000100
101 // Delete the scratch buffer info.
102 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000103}
104
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000105PPCallbacks::~PPCallbacks() {
106}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000107
Chris Lattner22eb9722006-06-18 05:43:12 +0000108/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattner146762e2007-07-20 16:59:19 +0000109/// the specified Token's location, translating the token's start
Chris Lattner22eb9722006-06-18 05:43:12 +0000110/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000111void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
112 Diags.Report(Loc, DiagID);
113}
114
Chris Lattnercb283342006-06-18 06:48:37 +0000115void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000116 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +0000117 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000118}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000119
Chris Lattner146762e2007-07-20 16:59:19 +0000120void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000121 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
122 << getSpelling(Tok) << "'";
123
124 if (!DumpFlags) return;
125 std::cerr << "\t";
126 if (Tok.isAtStartOfLine())
127 std::cerr << " [StartOfLine]";
128 if (Tok.hasLeadingSpace())
129 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000130 if (Tok.isExpandDisabled())
131 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000132 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000133 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000134 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
135 << "']";
136 }
137}
138
139void Preprocessor::DumpMacro(const MacroInfo &MI) const {
140 std::cerr << "MACRO: ";
141 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
142 DumpToken(MI.getReplacementToken(i));
143 std::cerr << " ";
144 }
145 std::cerr << "\n";
146}
147
Chris Lattner22eb9722006-06-18 05:43:12 +0000148void Preprocessor::PrintStats() {
149 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000150 std::cerr << NumDirectives << " directives found:\n";
151 std::cerr << " " << NumDefined << " #define.\n";
152 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000153 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000154 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
155 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
156 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
157 std::cerr << " " << NumElse << " #else/#elif.\n";
158 std::cerr << " " << NumEndif << " #endif.\n";
159 std::cerr << " " << NumPragma << " #pragma.\n";
160 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
161
Chris Lattner78186052006-07-09 00:45:31 +0000162 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
163 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000164 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000165 std::cerr << (NumFastTokenPaste+NumTokenPaste)
166 << " token paste (##) operations performed, "
167 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000168}
169
170//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000171// Token Spelling
172//===----------------------------------------------------------------------===//
173
174
175/// getSpelling() - Return the 'spelling' of this token. The spelling of a
176/// token are the characters used to represent the token in the source file
177/// after trigraph expansion and escaped-newline folding. In particular, this
178/// wants to get the true, uncanonicalized, spelling of things like digraphs
179/// UCNs, etc.
Chris Lattner146762e2007-07-20 16:59:19 +0000180std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000181 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
182
183 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000184 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000185 if (!Tok.needsCleaning())
186 return std::string(TokStart, TokStart+Tok.getLength());
187
Chris Lattnerd01e2912006-06-18 16:22:51 +0000188 std::string Result;
189 Result.reserve(Tok.getLength());
190
Chris Lattneref9eae12006-07-04 22:33:12 +0000191 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000192 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
193 Ptr != End; ) {
194 unsigned CharSize;
195 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
196 Ptr += CharSize;
197 }
198 assert(Result.size() != unsigned(Tok.getLength()) &&
199 "NeedsCleaning flag set on something that didn't need cleaning!");
200 return Result;
201}
202
203/// getSpelling - This method is used to get the spelling of a token into a
204/// preallocated buffer, instead of as an std::string. The caller is required
205/// to allocate enough space for the token, which is guaranteed to be at least
206/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000207///
208/// Note that this method may do two possible things: it may either fill in
209/// the buffer specified with characters, or it may *change the input pointer*
210/// to point to a constant buffer with the data already in it (avoiding a
211/// copy). The caller is not allowed to modify the returned buffer pointer
212/// if an internal buffer is returned.
Chris Lattner146762e2007-07-20 16:59:19 +0000213unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000214 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
216
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000217 // If this token is an identifier, just return the string from the identifier
218 // table, which is very quick.
219 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
220 Buffer = II->getName();
Chris Lattner32e6d642007-07-22 22:50:09 +0000221
222 // Return the length of the token. If the token needed cleaning, don't
223 // include the size of the newlines or trigraphs in it.
224 if (!Tok.needsCleaning())
225 return Tok.getLength();
226 else
227 return strlen(Buffer);
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000228 }
229
230 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000231 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000232
233 // If this token contains nothing interesting, return it directly.
234 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000235 Buffer = TokStart;
236 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000237 }
238 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000239 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000240 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
241 Ptr != End; ) {
242 unsigned CharSize;
243 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
244 Ptr += CharSize;
245 }
246 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
247 "NeedsCleaning flag set on something that didn't need cleaning!");
248
249 return OutBuf-Buffer;
250}
251
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000252
253/// CreateString - Plop the specified string into a scratch buffer and return a
254/// location for it. If specified, the source location provides a source
255/// location for the token.
256SourceLocation Preprocessor::
257CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
258 if (SLoc.isValid())
259 return ScratchBuf->getToken(Buf, Len, SLoc);
260 return ScratchBuf->getToken(Buf, Len);
261}
262
263
Chris Lattner8a7003c2007-07-16 06:48:38 +0000264/// AdvanceToTokenCharacter - Given a location that specifies the start of a
265/// token, return a new location that specifies a character within the token.
266SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
267 unsigned CharNo) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000268 // If they request the first char of the token, we're trivially done. If this
269 // is a macro expansion, it doesn't make sense to point to a character within
270 // the instantiation point (the name). We could point to the source
271 // character, but without also pointing to instantiation info, this is
272 // confusing.
273 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000274
275 // Figure out how many physical characters away the specified logical
276 // character is. This needs to take into consideration newlines and
277 // trigraphs.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000278 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
279 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000280
281 // The usual case is that tokens don't contain anything interesting. Skip
282 // over the uninteresting characters. If a token only consists of simple
283 // chars, this method is extremely fast.
284 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000285 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000286
287 // If we have a character that may be a trigraph or escaped newline, create a
288 // lexer to parse it correctly.
Chris Lattner8a7003c2007-07-16 06:48:38 +0000289 if (CharNo != 0) {
290 // Create a lexer starting at this token position.
Chris Lattner77e9de52007-07-20 16:52:03 +0000291 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000292 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000293 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000294 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000295 for (; CharNo; --CharNo)
296 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000297
298 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000299 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000300
301 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000302}
303
304
305
Chris Lattnerd01e2912006-06-18 16:22:51 +0000306//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000307// Source File Location Methods.
308//===----------------------------------------------------------------------===//
309
Chris Lattner22eb9722006-06-18 05:43:12 +0000310/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
311/// return null on failure. isAngled indicates whether the file reference is
312/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000313const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
314 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000315 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000316 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000317 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000318 // If the header lookup mechanism may be relative to the current file, pass in
319 // info about where the current file is.
320 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000321 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000322 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
323 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000324 }
325
Chris Lattner63dd32b2006-10-20 04:42:40 +0000326 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000327 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000328 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000329 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
330 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000331 if (FE) return FE;
332
333 // Otherwise, see if this is a subframework header. If so, this is relative
334 // to one of the headers on the #include stack. Walk the list of the current
335 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000336 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000337 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000338 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
339 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000340 return FE;
341 }
342
343 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
344 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000345 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000346 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000347 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
348 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000349 return FE;
350 }
351 }
352
353 // Otherwise, we really couldn't find the file.
354 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000355}
356
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000357/// isInPrimaryFile - Return true if we're in the top-level file, not in a
358/// #include.
359bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000360 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000361 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000362
Chris Lattner13044d92006-07-03 05:16:44 +0000363 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000364 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000365 if (IncludeMacroStack[i].TheLexer &&
366 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
367 return IncludeMacroStack[i].TheLexer->isMainFile();
368 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000369}
370
371/// getCurrentLexer - Return the current file lexer being lexed from. Note
372/// that this ignores any potentially active macro expansions and _Pragma
373/// expansions going on at the time.
374Lexer *Preprocessor::getCurrentFileLexer() const {
375 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
376
377 // Look for a stacked lexer.
378 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000379 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000380 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
381 return L;
382 }
383 return 0;
384}
385
386
Chris Lattner22eb9722006-06-18 05:43:12 +0000387/// EnterSourceFile - Add a source file to the top of the include stack and
388/// start lexing tokens from it instead of the current buffer. Return true
389/// on failure.
390void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000391 const DirectoryLookup *CurDir,
392 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000393 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000394 ++NumEnteredSourceFiles;
395
Chris Lattner69772b02006-07-02 20:34:39 +0000396 if (MaxIncludeStackDepth < IncludeMacroStack.size())
397 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000398
Chris Lattner77e9de52007-07-20 16:52:03 +0000399 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000400 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000401 EnterSourceFileWithLexer(TheLexer, CurDir);
402}
Chris Lattner22eb9722006-06-18 05:43:12 +0000403
Chris Lattner69772b02006-07-02 20:34:39 +0000404/// EnterSourceFile - Add a source file to the top of the include stack and
405/// start lexing tokens from it instead of the current buffer.
406void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
407 const DirectoryLookup *CurDir) {
408
409 // Add the current lexer to the include stack.
410 if (CurLexer || CurMacroExpander)
411 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
412 CurMacroExpander));
413
414 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000415 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000416 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000417
418 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000419 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000420 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
421
422 // Get the file entry for the current file.
423 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000424 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000425 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000426
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000427 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000428 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000429 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000430}
431
Chris Lattner69772b02006-07-02 20:34:39 +0000432
433
Chris Lattner22eb9722006-06-18 05:43:12 +0000434/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000435/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000436void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000437 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
438 CurMacroExpander));
439 CurLexer = 0;
440 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000441
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000442 if (NumCachedMacroExpanders == 0) {
443 CurMacroExpander = new MacroExpander(Tok, Args, *this);
444 } else {
445 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
446 CurMacroExpander->Init(Tok, Args);
447 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000448}
449
Chris Lattner7667d0d2006-07-16 18:16:58 +0000450/// EnterTokenStream - Add a "macro" context to the top of the include stack,
451/// which will cause the lexer to start returning the specified tokens. Note
452/// that these tokens will be re-macro-expanded when/if expansion is enabled.
453/// This method assumes that the specified stream of tokens has a permanent
454/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000455void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000456 // Save our current state.
457 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
458 CurMacroExpander));
459 CurLexer = 0;
460 CurDirLookup = 0;
461
462 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000463 if (NumCachedMacroExpanders == 0) {
464 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
465 } else {
466 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
467 CurMacroExpander->Init(Toks, NumToks);
468 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000469}
470
471/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
472/// lexer stack. This should only be used in situations where the current
473/// state of the top-of-stack lexer is known.
474void Preprocessor::RemoveTopOfLexerStack() {
475 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000476
477 if (CurMacroExpander) {
478 // Delete or cache the now-dead macro expander.
479 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
480 delete CurMacroExpander;
481 else
482 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
483 } else {
484 delete CurLexer;
485 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000486 CurLexer = IncludeMacroStack.back().TheLexer;
487 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
488 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
489 IncludeMacroStack.pop_back();
490}
491
Chris Lattner22eb9722006-06-18 05:43:12 +0000492//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000493// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000494//===----------------------------------------------------------------------===//
495
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000496/// RegisterBuiltinMacro - Register the specified identifier in the identifier
497/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000498IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000499 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000500 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000501
502 // Mark it as being a macro that is builtin.
503 MacroInfo *MI = new MacroInfo(SourceLocation());
504 MI->setIsBuiltinMacro();
505 Id->setMacroInfo(MI);
506 return Id;
507}
508
509
Chris Lattner677757a2006-06-28 05:26:32 +0000510/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
511/// identifier table.
512void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000513 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000514 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000515 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
516 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000517 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000518
519 // GCC Extensions.
520 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
521 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000522 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000523}
524
Chris Lattnerc2395832006-07-09 00:57:04 +0000525/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
526/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000527static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
528 const IdentifierInfo *MacroIdent) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000529 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
530
531 // If the token isn't an identifier, it's always literally expanded.
532 if (II == 0) return true;
533
534 // If the identifier is a macro, and if that macro is enabled, it may be
535 // expanded so it's not a trivial expansion.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000536 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
537 // Fast expanding "#define X X" is ok, because X would be disabled.
538 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000539 return false;
540
541 // If this is an object-like macro invocation, it is safe to trivially expand
542 // it.
543 if (MI->isObjectLike()) return true;
544
545 // If this is a function-like macro invocation, it's safe to trivially expand
546 // as long as the identifier is not a macro argument.
547 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
548 I != E; ++I)
549 if (*I == II)
550 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000551
Chris Lattnerc2395832006-07-09 00:57:04 +0000552 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000553}
554
Chris Lattnerc2395832006-07-09 00:57:04 +0000555
Chris Lattnerafe603f2006-07-11 04:02:46 +0000556/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
557/// lexed is a '('. If so, consume the token and return true, if not, this
558/// method should have no observable side-effect on the lexed tokens.
559bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000560 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000561 unsigned Val;
562 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000563 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000564 else
565 Val = CurMacroExpander->isNextTokenLParen();
566
567 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000568 // We have run off the end. If it's a source file we don't
569 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
570 // macro stack.
571 if (CurLexer)
572 return false;
573 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000574 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
575 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000576 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000577 else
578 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000579
580 if (Val != 2)
581 break;
582
583 // Ran off the end of a source file?
584 if (Entry.TheLexer)
585 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000586 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000587 }
588
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000589 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
590 // have found something that isn't a '(' or we found the end of the
591 // translation unit. In either case, return false.
592 if (Val != 1)
593 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000594
Chris Lattner146762e2007-07-20 16:59:19 +0000595 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000596 LexUnexpandedToken(Tok);
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000597 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
598 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000599}
Chris Lattner677757a2006-06-28 05:26:32 +0000600
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000601/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
602/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000603bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000604 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000605
606 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
607 if (MI->isBuiltinMacro()) {
608 ExpandBuiltinMacro(Identifier);
609 return false;
610 }
611
Chris Lattner81278c62006-10-14 19:03:49 +0000612 // If this is the first use of a target-specific macro, warn about it.
613 if (MI->isTargetSpecific()) {
614 MI->setIsTargetSpecific(false); // Don't warn on second use.
615 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
616 diag::port_target_macro_use);
617 }
618
Chris Lattneree8760b2006-07-15 07:42:55 +0000619 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000620 /// for each macro argument, the list of tokens that were provided to the
621 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000622 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000623
624 // If this is a function-like macro, read the arguments.
625 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000626 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000627 // name isn't a '(', this macro should not be expanded. Otherwise, consume
628 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000629 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000630 return true;
631
Chris Lattner78186052006-07-09 00:45:31 +0000632 // Remember that we are now parsing the arguments to a macro invocation.
633 // Preprocessor directives used inside macro arguments are not portable, and
634 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000635 InMacroArgs = true;
636 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000637
638 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000639 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000640
641 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000642 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000643
644 ++NumFnMacroExpanded;
645 } else {
646 ++NumMacroExpanded;
647 }
Chris Lattner13044d92006-07-03 05:16:44 +0000648
649 // Notice that this macro has been used.
650 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000651
652 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000653
654 // If this macro expands to no tokens, don't bother to push it onto the
655 // expansion stack, only to take it right back off.
656 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000657 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000658 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000659
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000660 // Ignore this macro use, just return the next token in the current
661 // buffer.
662 bool HadLeadingSpace = Identifier.hasLeadingSpace();
663 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
664
665 Lex(Identifier);
666
667 // If the identifier isn't on some OTHER line, inherit the leading
668 // whitespace/first-on-a-line property of this token. This handles
669 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
670 // empty.
671 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000672 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
673 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000674 }
675 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000676 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000677
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000678 } else if (MI->getNumTokens() == 1 &&
679 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000680 // Otherwise, if this macro expands into a single trivially-expanded
681 // token: expand it now. This handles common cases like
682 // "#define VAL 42".
683
684 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
685 // identifier to the expanded token.
686 bool isAtStartOfLine = Identifier.isAtStartOfLine();
687 bool hasLeadingSpace = Identifier.hasLeadingSpace();
688
689 // Remember where the token is instantiated.
690 SourceLocation InstantiateLoc = Identifier.getLocation();
691
692 // Replace the result token.
693 Identifier = MI->getReplacementToken(0);
694
695 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000696 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
697 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000698
699 // Update the tokens location to include both its logical and physical
700 // locations.
701 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000702 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000703 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000704
Chris Lattner6e4bf522006-07-27 06:59:25 +0000705 // If this is #define X X, we must mark the result as unexpandible.
706 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
707 if (NewII->getMacroInfo() == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000708 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000709
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000710 // Since this is not an identifier token, it can't be macro expanded, so
711 // we're done.
712 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000713 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000714 }
715
Chris Lattner78186052006-07-09 00:45:31 +0000716 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000717 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000718
719 // Now that the macro is at the top of the include stack, ask the
720 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000721 Lex(Identifier);
722 return false;
723}
724
Chris Lattneree8760b2006-07-15 07:42:55 +0000725/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000726/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000727/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000728MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000729 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000730 // The number of fixed arguments to parse.
731 unsigned NumFixedArgsLeft = MI->getNumArgs();
732 bool isVariadic = MI->isVariadic();
733
Chris Lattner78186052006-07-09 00:45:31 +0000734 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000735 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000736 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000737 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000738
739 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000740 // argument is separated by an EOF token. Use a SmallVector so we can avoid
741 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000742 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000743
744 unsigned NumActuals = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000745 while (Tok.getKind() == tok::comma) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000746 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
747 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000748 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000749
Chris Lattner78186052006-07-09 00:45:31 +0000750 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000751 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
752 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000753 LexUnexpandedToken(Tok);
754
755 if (Tok.getKind() == tok::eof) {
756 Diag(MacroName, diag::err_unterm_macro_invoc);
757 // Do not lose the EOF. Return it to the client.
758 MacroName = Tok;
759 return 0;
760 } else if (Tok.getKind() == tok::r_paren) {
761 // If we found the ) token, the macro arg list is done.
762 if (NumParens-- == 0)
763 break;
764 } else if (Tok.getKind() == tok::l_paren) {
765 ++NumParens;
766 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
767 // Comma ends this argument if there are more fixed arguments expected.
768 if (NumFixedArgsLeft)
769 break;
770
Chris Lattner2ada5d32006-07-15 07:51:24 +0000771 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000772 if (!isVariadic) {
773 // Emit the diagnostic at the macro name in case there is a missing ).
774 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000775 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000776 return 0;
777 }
778 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattnerb352e3e2006-11-21 06:17:10 +0000779 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000780 // If this is a comment token in the argument list and we're just in
781 // -C mode (not -CC mode), discard the comment.
782 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000783 }
784
785 ArgTokens.push_back(Tok);
786 }
787
Chris Lattnera12dd152006-07-11 04:09:02 +0000788 // Empty arguments are standard in C99 and supported as an extension in
789 // other modes.
790 if (ArgTokens.empty() && !Features.C99)
791 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000792
Chris Lattner36b6e812006-07-21 06:38:30 +0000793 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000794 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000795 EOFTok.startToken();
796 EOFTok.setKind(tok::eof);
797 EOFTok.setLocation(Tok.getLocation());
798 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000799 ArgTokens.push_back(EOFTok);
800 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000801 --NumFixedArgsLeft;
802 };
803
804 // Okay, we either found the r_paren. Check to see if we parsed too few
805 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000806 unsigned MinArgsExpected = MI->getNumArgs();
807
Chris Lattner775d8322006-07-29 04:39:41 +0000808 // See MacroArgs instance var for description of this.
809 bool isVarargsElided = false;
810
Chris Lattner2ada5d32006-07-15 07:51:24 +0000811 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000812 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000813 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000814 // Varargs where the named vararg parameter is missing: ok as extension.
815 // #define A(x, ...)
816 // A("blah")
817 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000818
819 // Remember this occurred if this is a C99 macro invocation with at least
820 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000821 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000822 } else if (MI->getNumArgs() == 1) {
823 // #define A(x)
824 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000825 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000826
827 // Empty arguments are standard in C99 and supported as an extension in
828 // other modes.
829 if (ArgTokens.empty() && !Features.C99)
830 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000831 } else {
832 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000833 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000834 return 0;
835 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000836
837 // Add a marker EOF token to the end of the token list for this argument.
838 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000839 Tok.startToken();
840 Tok.setKind(tok::eof);
841 Tok.setLocation(EndLoc);
842 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000843 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000844 }
845
Chris Lattner775d8322006-07-29 04:39:41 +0000846 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000847}
848
Chris Lattnerc673f902006-06-30 06:10:41 +0000849/// ComputeDATE_TIME - Compute the current time, enter it into the specified
850/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
851/// the identifier tokens inserted.
852static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000853 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000854 time_t TT = time(0);
855 struct tm *TM = localtime(&TT);
856
857 static const char * const Months[] = {
858 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
859 };
860
861 char TmpBuffer[100];
862 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
863 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000864 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000865
866 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000867 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000868}
869
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000870/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
871/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000872void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000873 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000874 IdentifierInfo *II = Tok.getIdentifierInfo();
875 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000876
877 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
878 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000879 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000880 return Handle_Pragma(Tok);
881
Chris Lattner78186052006-07-09 00:45:31 +0000882 ++NumBuiltinMacroExpanded;
883
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000884 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000885
886 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000887 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +0000888 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000889
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000890 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000891 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000892 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000893 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000894 Tok.setKind(tok::numeric_constant);
895 Tok.setLength(Length);
896 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000897 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000898 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000899 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000900 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000901 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
902 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000903 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000904 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000905 }
906 }
907
Chris Lattner0766e592006-07-03 01:07:01 +0000908 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000909 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +0000910 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000911 Tok.setKind(tok::string_literal);
912 Tok.setLength(FN.size());
913 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000914 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000915 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000916 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000917 Tok.setKind(tok::string_literal);
918 Tok.setLength(strlen("\"Mmm dd yyyy\""));
919 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000920 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000921 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000922 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000923 Tok.setKind(tok::string_literal);
924 Tok.setLength(strlen("\"hh:mm:ss\""));
925 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000926 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000927 Diag(Tok, diag::ext_pp_include_level);
928
929 // Compute the include depth of this token.
930 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000931 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
932 for (; Loc.isValid(); ++Depth)
933 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000934
935 // __INCLUDE_LEVEL__ expands to a simple numeric value.
936 sprintf(TmpBuffer, "%u", Depth);
937 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000938 Tok.setKind(tok::numeric_constant);
939 Tok.setLength(Length);
940 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000941 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000942 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
943 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
944 Diag(Tok, diag::ext_pp_timestamp);
945
946 // Get the file that we are lexing out of. If we're currently lexing from
947 // a macro, dig into the include stack.
948 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000949 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000950
951 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000952 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +0000953
954 // If this file is older than the file it depends on, emit a diagnostic.
955 const char *Result;
956 if (CurFile) {
957 time_t TT = CurFile->getModificationTime();
958 struct tm *TM = localtime(&TT);
959 Result = asctime(TM);
960 } else {
961 Result = "??? ??? ?? ??:??:?? ????\n";
962 }
963 TmpBuffer[0] = '"';
964 strcpy(TmpBuffer+1, Result);
965 unsigned Len = strlen(TmpBuffer);
966 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000967 Tok.setKind(tok::string_literal);
968 Tok.setLength(Len);
969 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000970 } else {
971 assert(0 && "Unknown identifier!");
972 }
973}
Chris Lattner677757a2006-06-28 05:26:32 +0000974
975//===----------------------------------------------------------------------===//
976// Lexer Event Handling.
977//===----------------------------------------------------------------------===//
978
Chris Lattnercefc7682006-07-08 08:28:12 +0000979/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
980/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +0000981IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +0000982 const char *BufPtr) {
983 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
984 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
985
986 // Look up this token, see if it is a macro, or if it is a language keyword.
987 IdentifierInfo *II;
988 if (BufPtr && !Identifier.needsCleaning()) {
989 // No cleaning needed, just use the characters from the lexed buffer.
990 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
991 } else {
992 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000993 llvm::SmallVector<char, 64> IdentifierBuffer;
994 IdentifierBuffer.resize(Identifier.getLength());
995 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000996 unsigned Size = getSpelling(Identifier, TmpBuf);
997 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
998 }
Chris Lattner8c204872006-10-14 05:19:21 +0000999 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001000 return II;
1001}
1002
1003
Chris Lattner677757a2006-06-28 05:26:32 +00001004/// HandleIdentifier - This callback is invoked when the lexer reads an
1005/// identifier. This callback looks up the identifier in the map and/or
1006/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001007void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001008 assert(Identifier.getIdentifierInfo() &&
1009 "Can't handle identifiers without identifier info!");
1010
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001011 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001012
1013 // If this identifier was poisoned, and if it was not produced from a macro
1014 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001015 if (II.isPoisoned() && CurLexer) {
1016 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1017 Diag(Identifier, diag::err_pp_used_poisoned_id);
1018 else
1019 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1020 }
Chris Lattner677757a2006-06-28 05:26:32 +00001021
Chris Lattner78186052006-07-09 00:45:31 +00001022 // If this is a macro to be expanded, do it.
Chris Lattner063400e2006-10-14 19:54:15 +00001023 if (MacroInfo *MI = II.getMacroInfo()) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001024 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1025 if (MI->isEnabled()) {
1026 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1027 return;
1028 } else {
1029 // C99 6.10.3.4p2 says that a disabled macro may never again be
1030 // expanded, even if it's in a context where it could be expanded in the
1031 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001032 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001033 }
1034 }
Chris Lattner063400e2006-10-14 19:54:15 +00001035 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1036 // If this identifier is a macro on some other target, emit a diagnostic.
1037 // This diagnosic is only emitted when macro expansion is enabled, because
1038 // the macro would not have been expanded for the other target either.
1039 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1040 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1041 diag::port_target_macro_use);
1042
1043 }
Chris Lattner677757a2006-06-28 05:26:32 +00001044
Chris Lattner5b9f4892006-11-21 17:23:33 +00001045 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1046 // then we act as if it is the actual operator and not the textual
1047 // representation of it.
1048 if (II.isCPlusPlusOperatorKeyword())
1049 Identifier.setIdentifierInfo(0);
1050
Chris Lattner677757a2006-06-28 05:26:32 +00001051 // Change the kind of this identifier to the appropriate token kind, e.g.
1052 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001053 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001054
1055 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001056 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1057 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001058 if (II.isExtensionToken() && Features.C99)
1059 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001060}
1061
Chris Lattner22eb9722006-06-18 05:43:12 +00001062/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1063/// the current file. This either returns the EOF token or pops a level off
1064/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001065bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 assert(!CurMacroExpander &&
1067 "Ending a file when currently in a macro!");
1068
Chris Lattner371ac8a2006-07-04 07:11:10 +00001069 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001070 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001071 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001072 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001073 // Okay, this has a controlling macro, remember in PerFileInfo.
1074 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001075 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001076 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001077 }
1078 }
1079
Chris Lattner22eb9722006-06-18 05:43:12 +00001080 // If this is a #include'd file, pop it off the include stack and continue
1081 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001082 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001083 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001084 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001085
1086 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001087 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001088 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1089
1090 // Get the file entry for the current file.
1091 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001092 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001093 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001094
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001095 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1096 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001097 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001098
1099 // Client should lex another token.
1100 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001101 }
1102
Chris Lattner8c204872006-10-14 05:19:21 +00001103 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001104 CurLexer->BufferPtr = CurLexer->BufferEnd;
1105 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001106 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001107
1108 // We're done with the #included file.
1109 delete CurLexer;
1110 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001111
Chris Lattner03f83482006-07-10 06:16:26 +00001112 // This is the end of the top-level file. If the diag::pp_macro_not_used
1113 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1114 // have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001115 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1116 for (IdentifierTable::iterator I = Identifiers.begin(),
1117 E = Identifiers.end(); I != E; ++I) {
1118 const IdentifierInfo &II = I->getValue();
1119 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1120 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1121 }
1122 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001123
1124 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001125}
1126
1127/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001128/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001129bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001130 assert(CurMacroExpander && !CurLexer &&
1131 "Ending a macro when currently in a #include file!");
1132
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001133 // Delete or cache the now-dead macro expander.
1134 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1135 delete CurMacroExpander;
1136 else
1137 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001138
Chris Lattner69772b02006-07-02 20:34:39 +00001139 // Handle this like a #include file being popped off the stack.
1140 CurMacroExpander = 0;
1141 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001142}
1143
1144
1145//===----------------------------------------------------------------------===//
1146// Utility Methods for Preprocessor Directive Handling.
1147//===----------------------------------------------------------------------===//
1148
1149/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1150/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001151void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001152 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001153 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001154 LexUnexpandedToken(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001155 } while (Tmp.getKind() != tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001156}
1157
Chris Lattner652c1692006-11-21 23:47:30 +00001158/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1159static bool isCXXNamedOperator(const std::string &Spelling) {
1160 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1161 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1162 Spelling == "or" || Spelling == "xor";
1163}
1164
Chris Lattner22eb9722006-06-18 05:43:12 +00001165/// ReadMacroName - Lex and validate a macro name, which occurs after a
1166/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001167/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1168/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001169/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001170void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001171 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001172 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001173
1174 // Missing macro name?
1175 if (MacroNameTok.getKind() == tok::eom)
1176 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1177
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001178 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1179 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001180 std::string Spelling = getSpelling(MacroNameTok);
1181 if (isCXXNamedOperator(Spelling))
1182 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1183 // except for their spellings.
1184 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1185 else
1186 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001187 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001188 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001189 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001190 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001191 } else if (isDefineUndef && II->getMacroInfo() &&
1192 II->getMacroInfo()->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001193 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001194 if (isDefineUndef == 1)
1195 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1196 else
1197 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001198 } else {
1199 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001200 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001201 }
1202
Chris Lattner22eb9722006-06-18 05:43:12 +00001203 // Invalid macro name, read and discard the rest of the line. Then set the
1204 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001205 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001206 return DiscardUntilEndOfDirective();
1207}
1208
1209/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1210/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001211void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001212 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001213 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001214 // There should be no tokens after the directive, but we allow them as an
1215 // extension.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001216 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1217 Lex(Tmp);
1218
Chris Lattner22eb9722006-06-18 05:43:12 +00001219 if (Tmp.getKind() != tok::eom) {
Chris Lattnercb283342006-06-18 06:48:37 +00001220 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1221 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001222 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001223}
1224
1225
1226
1227/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1228/// decided that the subsequent tokens are in the #if'd out portion of the
1229/// file. Lex the rest of the file, until we see an #endif. If
1230/// FoundNonSkipPortion is true, then we have already emitted code for part of
1231/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1232/// is true, then #else directives are ok, if not, then we have already seen one
1233/// so a #else directive is a duplicate. When this returns, the caller can lex
1234/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001235void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 bool FoundNonSkipPortion,
1237 bool FoundElse) {
1238 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001239 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001240 "Lexing a macro, not a file?");
1241
1242 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1243 FoundNonSkipPortion, FoundElse);
1244
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001245 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1246 // disabling warnings, etc.
1247 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001248 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001250 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001251
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001252 // If this is the end of the buffer, we have an error.
1253 if (Tok.getKind() == tok::eof) {
1254 // Emit errors for each unterminated conditional on the stack, including
1255 // the current one.
1256 while (!CurLexer->ConditionalStack.empty()) {
1257 Diag(CurLexer->ConditionalStack.back().IfLoc,
1258 diag::err_pp_unterminated_conditional);
1259 CurLexer->ConditionalStack.pop_back();
1260 }
1261
1262 // Just return and let the caller lex after this #include.
1263 break;
1264 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001265
1266 // If this token is not a preprocessor directive, just skip it.
1267 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1268 continue;
1269
1270 // We just parsed a # character at the start of a line, so we're in
1271 // directive mode. Tell the lexer this so any newlines we see will be
1272 // converted into an EOM token (this terminates the macro).
1273 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001274 CurLexer->KeepCommentMode = false;
1275
Chris Lattner22eb9722006-06-18 05:43:12 +00001276
1277 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001278 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001279
1280 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1281 // something bogus), skip it.
1282 if (Tok.getKind() != tok::identifier) {
1283 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001284 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001285 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001286 continue;
1287 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001288
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 // If the first letter isn't i or e, it isn't intesting to us. We know that
1290 // this is safe in the face of spelling differences, because there is no way
1291 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001292 // allows us to avoid looking up the identifier info for #define/#undef and
1293 // other common directives.
1294 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1295 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1297 FirstChar != 'i' && FirstChar != 'e') {
1298 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001299 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001300 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001301 continue;
1302 }
1303
Chris Lattnere60165f2006-06-22 06:36:29 +00001304 // Get the identifier name without trigraphs or embedded newlines. Note
1305 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1306 // when skipping.
1307 // TODO: could do this with zero copies in the no-clean case by using
1308 // strncmp below.
1309 char Directive[20];
1310 unsigned IdLen;
1311 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1312 IdLen = Tok.getLength();
1313 memcpy(Directive, RawCharData, IdLen);
1314 Directive[IdLen] = 0;
1315 } else {
1316 std::string DirectiveStr = getSpelling(Tok);
1317 IdLen = DirectiveStr.size();
1318 if (IdLen >= 20) {
1319 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001320 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001321 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001322 continue;
1323 }
1324 memcpy(Directive, &DirectiveStr[0], IdLen);
1325 Directive[IdLen] = 0;
1326 }
1327
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001329 if ((IdLen == 2) || // "if"
1330 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1331 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001332 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1333 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001334 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001335 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001336 /*foundnonskip*/false,
1337 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 }
1339 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001340 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001341 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001342 PPConditionalInfo CondInfo;
1343 CondInfo.WasSkipping = true; // Silence bogus warning.
1344 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001345 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 assert(!InCond && "Can't be skipping if not in a conditional!");
1347
1348 // If we popped the outermost skipping block, we're done skipping!
1349 if (!CondInfo.WasSkipping)
1350 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001351 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 // #else directive in a skipping conditional. If not in some other
1353 // skipping conditional, and if #else hasn't already been seen, enter it
1354 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001355 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001356 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1357
1358 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001359 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001360
1361 // Note that we've seen a #else in this conditional.
1362 CondInfo.FoundElse = true;
1363
1364 // If the conditional is at the top level, and the #if block wasn't
1365 // entered, enter the #else block now.
1366 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1367 CondInfo.FoundNonSkip = true;
1368 break;
1369 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001370 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001371 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1372
1373 bool ShouldEnter;
1374 // If this is in a skipping block or if we're already handled this #if
1375 // block, don't bother parsing the condition.
1376 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001377 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001378 ShouldEnter = false;
1379 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001380 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001381 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001382 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1383 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001384 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001385 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001386 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001387 }
1388
1389 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001390 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001391
1392 // If this condition is true, enter it!
1393 if (ShouldEnter) {
1394 CondInfo.FoundNonSkip = true;
1395 break;
1396 }
1397 }
1398 }
1399
1400 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001401 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001402 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001403 }
1404
1405 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1406 // of the file, just stop skipping and return to lexing whatever came after
1407 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001408 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001409}
1410
1411//===----------------------------------------------------------------------===//
1412// Preprocessor Directive Handling.
1413//===----------------------------------------------------------------------===//
1414
1415/// HandleDirective - This callback is invoked when the lexer sees a # token
1416/// at the start of a line. This consumes the directive, modifies the
1417/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1418/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001419void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001420 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001421
1422 // We just parsed a # character at the start of a line, so we're in directive
1423 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001424 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 CurLexer->ParsingPreprocessorDirective = true;
1426
1427 ++NumDirectives;
1428
Chris Lattner371ac8a2006-07-04 07:11:10 +00001429 // We are about to read a token. For the multiple-include optimization FA to
1430 // work, we have to remember if we had read any tokens *before* this
1431 // pp-directive.
1432 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1433
Chris Lattner78186052006-07-09 00:45:31 +00001434 // Read the next token, the directive flavor. This isn't expanded due to
1435 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001436 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001437
Chris Lattner78186052006-07-09 00:45:31 +00001438 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1439 // #define A(x) #x
1440 // A(abc
1441 // #warning blah
1442 // def)
1443 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001444 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001445 Diag(Result, diag::ext_embedded_directive);
1446
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001447TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001448 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001449 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001450 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001451 case tok::comment:
1452 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1453 LexUnexpandedToken(Result);
1454 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001455
Chris Lattner22eb9722006-06-18 05:43:12 +00001456 case tok::numeric_constant:
1457 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001458 DiscardUntilEndOfDirective();
1459 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001460 default:
1461 IdentifierInfo *II = Result.getIdentifierInfo();
1462 if (II == 0) break; // Not an identifier.
1463
1464 // Ask what the preprocessor keyword ID is.
1465 switch (II->getPPKeywordID()) {
1466 default: break;
1467 // C99 6.10.1 - Conditional Inclusion.
1468 case tok::pp_if:
1469 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1470 case tok::pp_ifdef:
1471 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1472 case tok::pp_ifndef:
1473 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1474 case tok::pp_elif:
1475 return HandleElifDirective(Result);
1476 case tok::pp_else:
1477 return HandleElseDirective(Result);
1478 case tok::pp_endif:
1479 return HandleEndifDirective(Result);
1480
1481 // C99 6.10.2 - Source File Inclusion.
1482 case tok::pp_include:
1483 return HandleIncludeDirective(Result); // Handle #include.
1484
1485 // C99 6.10.3 - Macro Replacement.
1486 case tok::pp_define:
1487 return HandleDefineDirective(Result, false);
1488 case tok::pp_undef:
1489 return HandleUndefDirective(Result);
1490
1491 // C99 6.10.4 - Line Control.
1492 case tok::pp_line:
1493 // FIXME: implement #line
1494 DiscardUntilEndOfDirective();
1495 return;
1496
1497 // C99 6.10.5 - Error Directive.
1498 case tok::pp_error:
1499 return HandleUserDiagnosticDirective(Result, false);
1500
1501 // C99 6.10.6 - Pragma Directive.
1502 case tok::pp_pragma:
1503 return HandlePragmaDirective();
1504
1505 // GNU Extensions.
1506 case tok::pp_import:
1507 return HandleImportDirective(Result);
1508 case tok::pp_include_next:
1509 return HandleIncludeNextDirective(Result);
1510
1511 case tok::pp_warning:
1512 Diag(Result, diag::ext_pp_warning_directive);
1513 return HandleUserDiagnosticDirective(Result, true);
1514 case tok::pp_ident:
1515 return HandleIdentSCCSDirective(Result);
1516 case tok::pp_sccs:
1517 return HandleIdentSCCSDirective(Result);
1518 case tok::pp_assert:
1519 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001521 case tok::pp_unassert:
1522 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001523 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001524
1525 // clang extensions.
1526 case tok::pp_define_target:
1527 return HandleDefineDirective(Result, true);
1528 case tok::pp_define_other_target:
1529 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 }
1531 break;
1532 }
1533
1534 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001535 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001536
1537 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001538 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001539
1540 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001541}
1542
Chris Lattner146762e2007-07-20 16:59:19 +00001543void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001544 bool isWarning) {
1545 // Read the rest of the line raw. We do this because we don't want macros
1546 // to be expanded and we don't require that the tokens be valid preprocessing
1547 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1548 // collapse multiple consequtive white space between tokens, but this isn't
1549 // specified by the standard.
1550 std::string Message = CurLexer->ReadToEndOfLine();
1551
1552 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001553 return Diag(Tok, DiagID, Message);
1554}
1555
1556/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1557///
Chris Lattner146762e2007-07-20 16:59:19 +00001558void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001559 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001560 Diag(Tok, diag::ext_pp_ident_directive);
1561
Chris Lattner371ac8a2006-07-04 07:11:10 +00001562 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001563 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001564 Lex(StrTok);
1565
1566 // If the token kind isn't a string, it's a malformed directive.
Chris Lattnerd3e98952006-10-06 05:22:26 +00001567 if (StrTok.getKind() != tok::string_literal &&
1568 StrTok.getKind() != tok::wide_string_literal)
Chris Lattner01d66cc2006-07-03 22:16:27 +00001569 return Diag(StrTok, diag::err_pp_malformed_ident);
1570
1571 // Verify that there is nothing after the string, other than EOM.
1572 CheckEndOfDirective("#ident");
1573
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001574 if (Callbacks)
1575 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001576}
1577
Chris Lattnerb8761832006-06-24 21:31:03 +00001578//===----------------------------------------------------------------------===//
1579// Preprocessor Include Directive Handling.
1580//===----------------------------------------------------------------------===//
1581
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001582/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1583/// checked and spelled filename, e.g. as an operand of #include. This returns
1584/// true if the input filename was in <>'s or false if it were in ""'s. The
1585/// caller is expected to provide a buffer that is large enough to hold the
1586/// spelling of the filename, but is also expected to handle the case when
1587/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001588bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001589 const char *&BufStart,
1590 const char *&BufEnd) {
1591 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001592 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1593
1594 // Make sure the filename is <x> or "x".
1595 bool isAngled;
1596 if (BufStart[0] == '<') {
1597 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001598 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001599 BufStart = 0;
1600 return true;
1601 }
1602 isAngled = true;
1603 } else if (BufStart[0] == '"') {
1604 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001605 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001606 BufStart = 0;
1607 return true;
1608 }
1609 isAngled = false;
1610 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001611 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001612 BufStart = 0;
1613 return true;
1614 }
1615
1616 // Diagnose #include "" as invalid.
1617 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001618 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001619 BufStart = 0;
1620 return "";
1621 }
1622
1623 // Skip the brackets.
1624 ++BufStart;
1625 --BufEnd;
1626 return isAngled;
1627}
1628
Chris Lattner43eafb42007-07-23 04:56:47 +00001629/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1630/// from a macro as multiple tokens, which need to be glued together. This
1631/// occurs for code like:
1632/// #define FOO <a/b.h>
1633/// #include FOO
1634/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1635///
1636/// This code concatenates and consumes tokens up to the '>' token. It returns
1637/// false if the > was found, otherwise it returns true if it finds and consumes
1638/// the EOM marker.
1639static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1640 Preprocessor &PP) {
1641 Token CurTok;
1642
1643 PP.Lex(CurTok);
1644 while (CurTok.getKind() != tok::eom) {
1645 // Append the spelling of this token to the buffer. If there was a space
1646 // before it, add it now.
1647 if (CurTok.hasLeadingSpace())
1648 FilenameBuffer.push_back(' ');
1649
1650 // Get the spelling of the token, directly into FilenameBuffer if possible.
1651 unsigned PreAppendSize = FilenameBuffer.size();
1652 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1653
1654 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1655 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1656
1657 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1658 if (BufPtr != &FilenameBuffer[PreAppendSize])
1659 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1660
1661 // Resize FilenameBuffer to the correct size.
1662 if (CurTok.getLength() != ActualLen)
1663 FilenameBuffer.resize(PreAppendSize+ActualLen);
1664
1665 // If we found the '>' marker, return success.
1666 if (CurTok.getKind() == tok::greater)
1667 return false;
1668
1669 PP.Lex(CurTok);
1670 }
1671
1672 // If we hit the eom marker, emit an error and return true so that the caller
1673 // knows the EOM has been read.
1674 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1675 return true;
1676}
1677
Chris Lattner22eb9722006-06-18 05:43:12 +00001678/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1679/// file to be included from the lexer, then include it! This is a common
1680/// routine with functionality shared between #include, #include_next and
1681/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001682void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001683 const DirectoryLookup *LookupFrom,
1684 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001685
Chris Lattner146762e2007-07-20 16:59:19 +00001686 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001687 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001688
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001689 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001690 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001691 const char *FilenameStart, *FilenameEnd;
1692
1693 switch (FilenameTok.getKind()) {
1694 case tok::eom:
1695 // If the token kind is EOM, the error has already been diagnosed.
1696 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001697
Chris Lattner43eafb42007-07-23 04:56:47 +00001698 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001699 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001700 FilenameBuffer.resize(FilenameTok.getLength());
1701 FilenameStart = &FilenameBuffer[0];
1702 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1703 FilenameEnd = FilenameStart+Len;
1704 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001705 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001706
1707 case tok::less:
1708 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1709 // case, glue the tokens together into FilenameBuffer and interpret those.
1710 FilenameBuffer.push_back('<');
1711 if (ConcatenateIncludeName(FilenameBuffer, *this))
1712 return; // Found <eom> but no ">"? Diagnostic already emitted.
1713 FilenameStart = &FilenameBuffer[0];
1714 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1715 break;
1716 default:
1717 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1718 DiscardUntilEndOfDirective();
1719 return;
1720 }
1721
Chris Lattner93ab9f12007-07-23 04:15:27 +00001722 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001723 FilenameStart, FilenameEnd);
1724 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1725 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00001726 if (FilenameStart == 0) {
1727 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001728 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00001729 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001730
Chris Lattner269c2322006-06-25 06:23:00 +00001731 // Verify that there is nothing after the filename, other than EOM. Use the
1732 // preprocessor to lex this in case lexing the filename entered a macro.
1733 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001734
1735 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001736 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001737 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1738
Chris Lattner22eb9722006-06-18 05:43:12 +00001739 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001740 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001741 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001742 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001743 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001744 return Diag(FilenameTok, diag::err_pp_file_not_found,
1745 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001746
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001747 // Ask HeaderInfo if we should enter this #include file.
1748 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1749 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001750 return;
1751 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001752
1753 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001754 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001755 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001756 return Diag(FilenameTok, diag::err_pp_file_not_found,
1757 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001758
1759 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001760 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001761}
1762
1763/// HandleIncludeNextDirective - Implements #include_next.
1764///
Chris Lattner146762e2007-07-20 16:59:19 +00001765void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001766 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001767
1768 // #include_next is like #include, except that we start searching after
1769 // the current found directory. If we can't do this, issue a
1770 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001771 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001772 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001773 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001774 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001775 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001776 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001777 } else {
1778 // Start looking up in the next directory.
1779 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001780 }
1781
1782 return HandleIncludeDirective(IncludeNextTok, Lookup);
1783}
1784
1785/// HandleImportDirective - Implements #import.
1786///
Chris Lattner146762e2007-07-20 16:59:19 +00001787void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001788 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001789
1790 return HandleIncludeDirective(ImportTok, 0, true);
1791}
1792
Chris Lattnerb8761832006-06-24 21:31:03 +00001793//===----------------------------------------------------------------------===//
1794// Preprocessor Macro Directive Handling.
1795//===----------------------------------------------------------------------===//
1796
Chris Lattnercefc7682006-07-08 08:28:12 +00001797/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1798/// definition has just been read. Lex the rest of the arguments and the
1799/// closing ), updating MI with what we learn. Return true if an error occurs
1800/// parsing the arg list.
1801bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001802 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1803
Chris Lattner146762e2007-07-20 16:59:19 +00001804 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001805 while (1) {
1806 LexUnexpandedToken(Tok);
1807 switch (Tok.getKind()) {
1808 case tok::r_paren:
1809 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001810 if (Arguments.empty()) { // #define FOO()
1811 MI->setArgumentList(Arguments.begin(), Arguments.end());
1812 return false;
1813 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001814 // Otherwise we have #define FOO(A,)
1815 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1816 return true;
1817 case tok::ellipsis: // #define X(... -> C99 varargs
1818 // Warn if use of C99 feature in non-C99 mode.
1819 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1820
1821 // Lex the token after the identifier.
1822 LexUnexpandedToken(Tok);
1823 if (Tok.getKind() != tok::r_paren) {
1824 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1825 return true;
1826 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001827 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001828 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001829 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001830 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001831 return false;
1832 case tok::eom: // #define X(
1833 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1834 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001835 default:
1836 // Handle keywords and identifiers here to accept things like
1837 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001838 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001839 if (II == 0) {
1840 // #define X(1
1841 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1842 return true;
1843 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001844
1845 // If this is already used as an argument, it is used multiple times (e.g.
1846 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001847 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1848 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001849 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1850 return true;
1851 }
1852
1853 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001854 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001855
1856 // Lex the token after the identifier.
1857 LexUnexpandedToken(Tok);
1858
1859 switch (Tok.getKind()) {
1860 default: // #define X(A B
1861 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1862 return true;
1863 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001864 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001865 return false;
1866 case tok::comma: // #define X(A,
1867 break;
1868 case tok::ellipsis: // #define X(A... -> GCC extension
1869 // Diagnose extension.
1870 Diag(Tok, diag::ext_named_variadic_macro);
1871
1872 // Lex the token after the identifier.
1873 LexUnexpandedToken(Tok);
1874 if (Tok.getKind() != tok::r_paren) {
1875 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1876 return true;
1877 }
1878
1879 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001880 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001881 return false;
1882 }
1883 }
1884 }
1885}
1886
Chris Lattner22eb9722006-06-18 05:43:12 +00001887/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001888/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1889/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001890///
Chris Lattner146762e2007-07-20 16:59:19 +00001891void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00001892 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001894
Chris Lattner146762e2007-07-20 16:59:19 +00001895 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001896 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001897
1898 // Error reading macro name? If so, diagnostic already issued.
1899 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00001900 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001901
Chris Lattner457fc152006-07-29 06:30:25 +00001902 // If we are supposed to keep comments in #defines, reenable comment saving
1903 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001904 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001905
Chris Lattner063400e2006-10-14 19:54:15 +00001906 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001907 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001908 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001909
Chris Lattner063400e2006-10-14 19:54:15 +00001910 // If the identifier is an 'other target' macro, clear this bit.
1911 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1912
1913
Chris Lattner146762e2007-07-20 16:59:19 +00001914 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001915 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001916
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001917 // If this is a function-like macro definition, parse the argument list,
1918 // marking each of the identifiers as being used as macro arguments. Also,
1919 // check other constraints on the first token of the macro body.
Chris Lattner22eb9722006-06-18 05:43:12 +00001920 if (Tok.getKind() == tok::eom) {
1921 // If there is no body to this macro, we have no special handling here.
1922 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001923 // This is a function-like macro definition. Read the argument list.
1924 MI->setIsFunctionLike();
1925 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001926 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001927 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001928 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001929 if (CurLexer->ParsingPreprocessorDirective)
1930 DiscardUntilEndOfDirective();
1931 return;
1932 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001933
Chris Lattner815a1f92006-07-08 20:48:04 +00001934 // Read the first token after the arg list for down below.
1935 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001936 } else if (!Tok.hasLeadingSpace()) {
1937 // C99 requires whitespace between the macro definition and the body. Emit
1938 // a diagnostic for something like "#define X+".
1939 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001940 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001941 } else {
1942 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1943 // one in some cases!
1944 }
1945 } else {
1946 // This is a normal token with leading space. Clear the leading space
1947 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001948 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001949 }
1950
Chris Lattner7e374832006-07-29 03:46:57 +00001951 // If this is a definition of a variadic C99 function-like macro, not using
1952 // the GNU named varargs extension, enabled __VA_ARGS__.
1953
1954 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1955 // This gets unpoisoned where it is allowed.
1956 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1957 if (MI->isC99Varargs())
1958 Ident__VA_ARGS__->setIsPoisoned(false);
1959
Chris Lattner22eb9722006-06-18 05:43:12 +00001960 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001961 if (MI->isObjectLike()) {
1962 // Object-like macros are very simple, just read their body.
1963 while (Tok.getKind() != tok::eom) {
1964 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001965 // Get the next token of the macro.
1966 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001967 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001968
Chris Lattnera3834342007-07-14 21:54:03 +00001969 } else {
1970 // Otherwise, read the body of a function-like macro. This has to validate
1971 // the # (stringize) operator.
1972 while (Tok.getKind() != tok::eom) {
1973 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001974
Chris Lattnera3834342007-07-14 21:54:03 +00001975 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1976 // parameters in function-like macro expansions.
1977 if (Tok.getKind() != tok::hash) {
1978 // Get the next token of the macro.
1979 LexUnexpandedToken(Tok);
1980 continue;
1981 }
1982
1983 // Get the next token of the macro.
1984 LexUnexpandedToken(Tok);
1985
1986 // Not a macro arg identifier?
1987 if (!Tok.getIdentifierInfo() ||
1988 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1989 Diag(Tok, diag::err_pp_stringize_not_parameter);
1990 delete MI;
1991
1992 // Disable __VA_ARGS__ again.
1993 Ident__VA_ARGS__->setIsPoisoned(true);
1994 return;
1995 }
1996
1997 // Things look ok, add the param name token to the macro.
1998 MI->AddTokenToBody(Tok);
1999
2000 // Get the next token of the macro.
2001 LexUnexpandedToken(Tok);
2002 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002003 }
Chris Lattner7e374832006-07-29 03:46:57 +00002004
Chris Lattnerf40fe992007-07-14 22:11:41 +00002005
Chris Lattner7e374832006-07-29 03:46:57 +00002006 // Disable __VA_ARGS__ again.
2007 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002008
Chris Lattnerbff18d52006-07-06 04:49:18 +00002009 // Check that there is no paste (##) operator at the begining or end of the
2010 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002011 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002012 if (NumTokens != 0) {
2013 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002014 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002015 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002016 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002017 }
2018 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002019 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002020 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002021 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002022 }
2023 }
2024
Chris Lattner13044d92006-07-03 05:16:44 +00002025 // If this is the primary source file, remember that this macro hasn't been
2026 // used yet.
2027 if (isInPrimaryFile())
2028 MI->setIsUsed(false);
2029
Chris Lattner22eb9722006-06-18 05:43:12 +00002030 // Finally, if this identifier already had a macro defined for it, verify that
2031 // the macro bodies are identical and free the old definition.
2032 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
Chris Lattner13044d92006-07-03 05:16:44 +00002033 if (!OtherMI->isUsed())
2034 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2035
Chris Lattner22eb9722006-06-18 05:43:12 +00002036 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002037 // must be the same. C99 6.10.3.2.
2038 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002039 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2040 MacroNameTok.getIdentifierInfo()->getName());
2041 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2042 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002043 delete OtherMI;
2044 }
2045
2046 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002047}
2048
Chris Lattner063400e2006-10-14 19:54:15 +00002049/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002050void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2051 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002052 ReadMacroName(MacroNameTok, 1);
2053
2054 // Error reading macro name? If so, diagnostic already issued.
2055 if (MacroNameTok.getKind() == tok::eom)
2056 return;
2057
2058 // Check to see if this is the last token on the #undef line.
2059 CheckEndOfDirective("#define_other_target");
2060
2061 // If there is already a macro defined by this name, turn it into a
2062 // target-specific define.
2063 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
2064 MI->setIsTargetSpecific(true);
2065 return;
2066 }
2067
2068 // Mark the identifier as being a macro on some other target.
2069 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2070}
2071
Chris Lattner22eb9722006-06-18 05:43:12 +00002072
2073/// HandleUndefDirective - Implements #undef.
2074///
Chris Lattner146762e2007-07-20 16:59:19 +00002075void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002076 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002077
Chris Lattner146762e2007-07-20 16:59:19 +00002078 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002079 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002080
2081 // Error reading macro name? If so, diagnostic already issued.
2082 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002083 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002084
2085 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002086 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002087
2088 // Okay, we finally have a valid identifier to undef.
2089 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
2090
Chris Lattner063400e2006-10-14 19:54:15 +00002091 // #undef untaints an identifier if it were marked by define_other_target.
2092 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2093
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002095 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002096
Chris Lattner13044d92006-07-03 05:16:44 +00002097 if (!MI->isUsed())
2098 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002099
2100 // Free macro definition.
2101 delete MI;
2102 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002103}
2104
2105
Chris Lattnerb8761832006-06-24 21:31:03 +00002106//===----------------------------------------------------------------------===//
2107// Preprocessor Conditional Directive Handling.
2108//===----------------------------------------------------------------------===//
2109
Chris Lattner22eb9722006-06-18 05:43:12 +00002110/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002111/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2112/// if any tokens have been returned or pp-directives activated before this
2113/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002114///
Chris Lattner146762e2007-07-20 16:59:19 +00002115void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002116 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002117 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002118 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002119
Chris Lattner146762e2007-07-20 16:59:19 +00002120 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002121 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002122
2123 // Error reading macro name? If so, diagnostic already issued.
2124 if (MacroNameTok.getKind() == tok::eom)
Chris Lattnercb283342006-06-18 06:48:37 +00002125 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002126
2127 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002128 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2129
2130 // If the start of a top-level #ifdef, inform MIOpt.
2131 if (!ReadAnyTokensBeforeDirective &&
2132 CurLexer->getConditionalStackDepth() == 0) {
2133 assert(isIfndef && "#ifdef shouldn't reach here");
2134 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2135 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002136
Chris Lattner063400e2006-10-14 19:54:15 +00002137 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2138 MacroInfo *MI = MII->getMacroInfo();
Chris Lattnera78a97e2006-07-03 05:42:18 +00002139
Chris Lattner81278c62006-10-14 19:03:49 +00002140 // If there is a macro, process it.
2141 if (MI) {
2142 // Mark it used.
2143 MI->setIsUsed(true);
2144
2145 // If this is the first use of a target-specific macro, warn about it.
2146 if (MI->isTargetSpecific()) {
2147 MI->setIsTargetSpecific(false); // Don't warn on second use.
2148 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2149 diag::port_target_macro_use);
2150 }
Chris Lattner063400e2006-10-14 19:54:15 +00002151 } else {
2152 // Use of a target-specific macro for some other target? If so, warn.
2153 if (MII->isOtherTargetMacro()) {
2154 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2155 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2156 diag::port_target_macro_use);
2157 }
Chris Lattner81278c62006-10-14 19:03:49 +00002158 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002159
Chris Lattner22eb9722006-06-18 05:43:12 +00002160 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002161 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002162 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002163 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002164 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002165 } else {
2166 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002167 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002168 /*Foundnonskip*/false,
2169 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002170 }
2171}
2172
2173/// HandleIfDirective - Implements the #if directive.
2174///
Chris Lattner146762e2007-07-20 16:59:19 +00002175void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002176 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002177 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002178
Chris Lattner371ac8a2006-07-04 07:11:10 +00002179 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002180 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002181 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002182
2183 // Should we include the stuff contained by this directive?
2184 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002185 // If this condition is equivalent to #ifndef X, and if this is the first
2186 // directive seen, handle it for the multiple-include optimization.
2187 if (!ReadAnyTokensBeforeDirective &&
2188 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2189 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2190
Chris Lattner22eb9722006-06-18 05:43:12 +00002191 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002192 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002193 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002194 } else {
2195 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002196 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002197 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002198 }
2199}
2200
2201/// HandleEndifDirective - Implements the #endif directive.
2202///
Chris Lattner146762e2007-07-20 16:59:19 +00002203void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002204 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002205
Chris Lattner22eb9722006-06-18 05:43:12 +00002206 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002207 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002208
2209 PPConditionalInfo CondInfo;
2210 if (CurLexer->popConditionalLevel(CondInfo)) {
2211 // No conditionals on the stack: this is an #endif without an #if.
2212 return Diag(EndifToken, diag::err_pp_endif_without_if);
2213 }
2214
Chris Lattner371ac8a2006-07-04 07:11:10 +00002215 // If this the end of a top-level #endif, inform MIOpt.
2216 if (CurLexer->getConditionalStackDepth() == 0)
2217 CurLexer->MIOpt.ExitTopLevelConditional();
2218
Chris Lattner538d7f32006-07-20 04:31:52 +00002219 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002220 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002221}
2222
2223
Chris Lattner146762e2007-07-20 16:59:19 +00002224void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002225 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002226
Chris Lattner22eb9722006-06-18 05:43:12 +00002227 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002228 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002229
2230 PPConditionalInfo CI;
2231 if (CurLexer->popConditionalLevel(CI))
2232 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002233
2234 // If this is a top-level #else, inform the MIOpt.
2235 if (CurLexer->getConditionalStackDepth() == 0)
2236 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002237
2238 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002239 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002240
2241 // Finally, skip the rest of the contents of this block and return the first
2242 // token after it.
2243 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2244 /*FoundElse*/true);
2245}
2246
Chris Lattner146762e2007-07-20 16:59:19 +00002247void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002248 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002249
Chris Lattner22eb9722006-06-18 05:43:12 +00002250 // #elif directive in a non-skipping conditional... start skipping.
2251 // We don't care what the condition is, because we will always skip it (since
2252 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002253 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002254
2255 PPConditionalInfo CI;
2256 if (CurLexer->popConditionalLevel(CI))
2257 return Diag(ElifToken, diag::pp_err_elif_without_if);
2258
Chris Lattner371ac8a2006-07-04 07:11:10 +00002259 // If this is a top-level #elif, inform the MIOpt.
2260 if (CurLexer->getConditionalStackDepth() == 0)
2261 CurLexer->MIOpt.FoundTopLevelElse();
2262
Chris Lattner22eb9722006-06-18 05:43:12 +00002263 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002264 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002265
2266 // Finally, skip the rest of the contents of this block and return the first
2267 // token after it.
2268 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2269 /*FoundElse*/CI.FoundElse);
2270}
Chris Lattnerb8761832006-06-24 21:31:03 +00002271