blob: f1e9b12efca96fc9fac61241eff837d336cce8d3 [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 Lattnerc43ddc82007-10-07 08:44:20 +000093
94 // Free any macro definitions.
95 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
96 Macros.begin(), E = Macros.end(); I != E; ++I) {
97 // Free the macro definition.
98 delete I->second;
99 I->second = 0;
100 I->first->setHasMacroDefinition(false);
101 }
Chris Lattnerb8761832006-06-24 21:31:03 +0000102
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000103 // Free any cached macro expanders.
104 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
105 delete MacroExpanderCache[i];
106
Chris Lattnerb8761832006-06-24 21:31:03 +0000107 // Release pragma information.
108 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000109
110 // Delete the scratch buffer info.
111 delete ScratchBuf;
Chris Lattner22eb9722006-06-18 05:43:12 +0000112}
113
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000114PPCallbacks::~PPCallbacks() {
115}
Chris Lattner87d3bec2006-10-17 03:44:32 +0000116
Chris Lattner22eb9722006-06-18 05:43:12 +0000117/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattner146762e2007-07-20 16:59:19 +0000118/// the specified Token's location, translating the token's start
Chris Lattner22eb9722006-06-18 05:43:12 +0000119/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner36982e42007-05-16 17:49:37 +0000120void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
121 Diags.Report(Loc, DiagID);
122}
123
Chris Lattnercb283342006-06-18 06:48:37 +0000124void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000125 const std::string &Msg) {
Chris Lattner36982e42007-05-16 17:49:37 +0000126 Diags.Report(Loc, DiagID, &Msg, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000127}
Chris Lattnerd01e2912006-06-18 16:22:51 +0000128
Chris Lattner146762e2007-07-20 16:59:19 +0000129void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000130 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
131 << getSpelling(Tok) << "'";
132
133 if (!DumpFlags) return;
134 std::cerr << "\t";
135 if (Tok.isAtStartOfLine())
136 std::cerr << " [StartOfLine]";
137 if (Tok.hasLeadingSpace())
138 std::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000139 if (Tok.isExpandDisabled())
140 std::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000141 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000142 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
144 << "']";
145 }
146}
147
148void Preprocessor::DumpMacro(const MacroInfo &MI) const {
149 std::cerr << "MACRO: ";
150 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
151 DumpToken(MI.getReplacementToken(i));
152 std::cerr << " ";
153 }
154 std::cerr << "\n";
155}
156
Chris Lattner22eb9722006-06-18 05:43:12 +0000157void Preprocessor::PrintStats() {
158 std::cerr << "\n*** Preprocessor Stats:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000159 std::cerr << NumDirectives << " directives found:\n";
160 std::cerr << " " << NumDefined << " #define.\n";
161 std::cerr << " " << NumUndefined << " #undef.\n";
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000162 std::cerr << " #include/#include_next/#import:\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000163 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
164 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
165 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
166 std::cerr << " " << NumElse << " #else/#elif.\n";
167 std::cerr << " " << NumEndif << " #endif.\n";
168 std::cerr << " " << NumPragma << " #pragma.\n";
169 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
170
Chris Lattner78186052006-07-09 00:45:31 +0000171 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
172 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
Chris Lattner22eb9722006-06-18 05:43:12 +0000173 << NumFastMacroExpanded << " on the fast path.\n";
Chris Lattner510ab612006-07-20 04:47:30 +0000174 std::cerr << (NumFastTokenPaste+NumTokenPaste)
175 << " token paste (##) operations performed, "
176 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000177}
178
179//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000180// Token Spelling
181//===----------------------------------------------------------------------===//
182
183
184/// getSpelling() - Return the 'spelling' of this token. The spelling of a
185/// token are the characters used to represent the token in the source file
186/// after trigraph expansion and escaped-newline folding. In particular, this
187/// wants to get the true, uncanonicalized, spelling of things like digraphs
188/// UCNs, etc.
Chris Lattner146762e2007-07-20 16:59:19 +0000189std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000190 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
191
192 // If this token contains nothing interesting, return it directly.
Chris Lattner50b497e2006-06-18 16:32:35 +0000193 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000194 if (!Tok.needsCleaning())
195 return std::string(TokStart, TokStart+Tok.getLength());
196
Chris Lattnerd01e2912006-06-18 16:22:51 +0000197 std::string Result;
198 Result.reserve(Tok.getLength());
199
Chris Lattneref9eae12006-07-04 22:33:12 +0000200 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000201 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
202 Ptr != End; ) {
203 unsigned CharSize;
204 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
205 Ptr += CharSize;
206 }
207 assert(Result.size() != unsigned(Tok.getLength()) &&
208 "NeedsCleaning flag set on something that didn't need cleaning!");
209 return Result;
210}
211
212/// getSpelling - This method is used to get the spelling of a token into a
213/// preallocated buffer, instead of as an std::string. The caller is required
214/// to allocate enough space for the token, which is guaranteed to be at least
215/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000216///
217/// Note that this method may do two possible things: it may either fill in
218/// the buffer specified with characters, or it may *change the input pointer*
219/// to point to a constant buffer with the data already in it (avoiding a
220/// copy). The caller is not allowed to modify the returned buffer pointer
221/// if an internal buffer is returned.
Chris Lattner146762e2007-07-20 16:59:19 +0000222unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000223 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
225
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000226 // If this token is an identifier, just return the string from the identifier
227 // table, which is very quick.
228 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
229 Buffer = II->getName();
Chris Lattner32e6d642007-07-22 22:50:09 +0000230
231 // Return the length of the token. If the token needed cleaning, don't
232 // include the size of the newlines or trigraphs in it.
233 if (!Tok.needsCleaning())
234 return Tok.getLength();
235 else
236 return strlen(Buffer);
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000237 }
238
239 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000240 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000241
242 // If this token contains nothing interesting, return it directly.
243 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000244 Buffer = TokStart;
245 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000246 }
247 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000248 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000249 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
250 Ptr != End; ) {
251 unsigned CharSize;
252 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
253 Ptr += CharSize;
254 }
255 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
256 "NeedsCleaning flag set on something that didn't need cleaning!");
257
258 return OutBuf-Buffer;
259}
260
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000261
262/// CreateString - Plop the specified string into a scratch buffer and return a
263/// location for it. If specified, the source location provides a source
264/// location for the token.
265SourceLocation Preprocessor::
266CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
267 if (SLoc.isValid())
268 return ScratchBuf->getToken(Buf, Len, SLoc);
269 return ScratchBuf->getToken(Buf, Len);
270}
271
272
Chris Lattner8a7003c2007-07-16 06:48:38 +0000273/// AdvanceToTokenCharacter - Given a location that specifies the start of a
274/// token, return a new location that specifies a character within the token.
275SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
276 unsigned CharNo) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000277 // If they request the first char of the token, we're trivially done. If this
278 // is a macro expansion, it doesn't make sense to point to a character within
279 // the instantiation point (the name). We could point to the source
280 // character, but without also pointing to instantiation info, this is
281 // confusing.
282 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000283
284 // Figure out how many physical characters away the specified logical
285 // character is. This needs to take into consideration newlines and
286 // trigraphs.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000287 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
288 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000289
290 // The usual case is that tokens don't contain anything interesting. Skip
291 // over the uninteresting characters. If a token only consists of simple
292 // chars, this method is extremely fast.
293 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000294 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000295
296 // If we have a character that may be a trigraph or escaped newline, create a
297 // lexer to parse it correctly.
Chris Lattner8a7003c2007-07-16 06:48:38 +0000298 if (CharNo != 0) {
299 // Create a lexer starting at this token position.
Chris Lattner77e9de52007-07-20 16:52:03 +0000300 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000301 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000302 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000303 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000304 for (; CharNo; --CharNo)
305 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000306
307 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000308 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000309
310 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000311}
312
313
314
Chris Lattnerd01e2912006-06-18 16:22:51 +0000315//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000316// Source File Location Methods.
317//===----------------------------------------------------------------------===//
318
Chris Lattner22eb9722006-06-18 05:43:12 +0000319/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
320/// return null on failure. isAngled indicates whether the file reference is
321/// for system #include's or not (i.e. using <> instead of "").
Chris Lattnerb8b94f12006-10-30 05:38:06 +0000322const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
323 const char *FilenameEnd,
Chris Lattnerc8997182006-06-22 05:52:16 +0000324 bool isAngled,
Chris Lattner22eb9722006-06-18 05:43:12 +0000325 const DirectoryLookup *FromDir,
Chris Lattnerc8997182006-06-22 05:52:16 +0000326 const DirectoryLookup *&CurDir) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000327 // If the header lookup mechanism may be relative to the current file, pass in
328 // info about where the current file is.
329 const FileEntry *CurFileEnt = 0;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000330 if (!FromDir) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000331 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
332 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000333 }
334
Chris Lattner63dd32b2006-10-20 04:42:40 +0000335 // Do a standard file entry lookup.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000336 CurDir = CurDirLookup;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000337 const FileEntry *FE =
Chris Lattner7cdbad92006-10-30 05:33:15 +0000338 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
339 isAngled, FromDir, CurDir, CurFileEnt);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000340 if (FE) return FE;
341
342 // Otherwise, see if this is a subframework header. If so, this is relative
343 // to one of the headers on the #include stack. Walk the list of the current
344 // headers on the #include stack and pass them to HeaderInfo.
Chris Lattner5c683b22006-10-20 05:12:14 +0000345 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000346 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->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 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
353 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Chris Lattner5c683b22006-10-20 05:12:14 +0000354 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000355 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Chris Lattner7cdbad92006-10-30 05:33:15 +0000356 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
357 CurFileEnt)))
Chris Lattner63dd32b2006-10-20 04:42:40 +0000358 return FE;
359 }
360 }
361
362 // Otherwise, we really couldn't find the file.
363 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000364}
365
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000366/// isInPrimaryFile - Return true if we're in the top-level file, not in a
367/// #include.
368bool Preprocessor::isInPrimaryFile() const {
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000369 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner13044d92006-07-03 05:16:44 +0000370 return CurLexer->isMainFile();
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000371
Chris Lattner13044d92006-07-03 05:16:44 +0000372 // If there are any stacked lexers, we're in a #include.
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000373 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
Chris Lattner13044d92006-07-03 05:16:44 +0000374 if (IncludeMacroStack[i].TheLexer &&
375 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
376 return IncludeMacroStack[i].TheLexer->isMainFile();
377 return false;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000378}
379
380/// getCurrentLexer - Return the current file lexer being lexed from. Note
381/// that this ignores any potentially active macro expansions and _Pragma
382/// expansions going on at the time.
383Lexer *Preprocessor::getCurrentFileLexer() const {
384 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
385
386 // Look for a stacked lexer.
387 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerf88c53a2006-07-03 05:26:05 +0000388 Lexer *L = IncludeMacroStack[i-1].TheLexer;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000389 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
390 return L;
391 }
392 return 0;
393}
394
395
Chris Lattner22eb9722006-06-18 05:43:12 +0000396/// EnterSourceFile - Add a source file to the top of the include stack and
397/// start lexing tokens from it instead of the current buffer. Return true
398/// on failure.
399void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner13044d92006-07-03 05:16:44 +0000400 const DirectoryLookup *CurDir,
401 bool isMainFile) {
Chris Lattner69772b02006-07-02 20:34:39 +0000402 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000403 ++NumEnteredSourceFiles;
404
Chris Lattner69772b02006-07-02 20:34:39 +0000405 if (MaxIncludeStackDepth < IncludeMacroStack.size())
406 MaxIncludeStackDepth = IncludeMacroStack.size();
Chris Lattner22eb9722006-06-18 05:43:12 +0000407
Chris Lattner77e9de52007-07-20 16:52:03 +0000408 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Chris Lattner13044d92006-07-03 05:16:44 +0000409 if (isMainFile) TheLexer->setIsMainFile();
Chris Lattner69772b02006-07-02 20:34:39 +0000410 EnterSourceFileWithLexer(TheLexer, CurDir);
411}
Chris Lattner22eb9722006-06-18 05:43:12 +0000412
Chris Lattner69772b02006-07-02 20:34:39 +0000413/// EnterSourceFile - Add a source file to the top of the include stack and
414/// start lexing tokens from it instead of the current buffer.
415void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
416 const DirectoryLookup *CurDir) {
417
418 // Add the current lexer to the include stack.
419 if (CurLexer || CurMacroExpander)
420 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
421 CurMacroExpander));
422
423 CurLexer = TheLexer;
Chris Lattnerc8997182006-06-22 05:52:16 +0000424 CurDirLookup = CurDir;
Chris Lattner69772b02006-07-02 20:34:39 +0000425 CurMacroExpander = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +0000426
427 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000428 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +0000429 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
430
431 // Get the file entry for the current file.
432 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000433 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000434 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +0000435
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000436 Callbacks->FileChanged(CurLexer->getFileLoc(),
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +0000437 PPCallbacks::EnterFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +0000438 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000439}
440
Chris Lattner69772b02006-07-02 20:34:39 +0000441
442
Chris Lattner22eb9722006-06-18 05:43:12 +0000443/// EnterMacro - Add a Macro to the top of the include stack and start lexing
Chris Lattnercb283342006-06-18 06:48:37 +0000444/// tokens from it instead of the current buffer.
Chris Lattner146762e2007-07-20 16:59:19 +0000445void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Chris Lattner69772b02006-07-02 20:34:39 +0000446 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
447 CurMacroExpander));
448 CurLexer = 0;
449 CurDirLookup = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000450
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000451 if (NumCachedMacroExpanders == 0) {
452 CurMacroExpander = new MacroExpander(Tok, Args, *this);
453 } else {
454 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
455 CurMacroExpander->Init(Tok, Args);
456 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000457}
458
Chris Lattner7667d0d2006-07-16 18:16:58 +0000459/// EnterTokenStream - Add a "macro" context to the top of the include stack,
460/// which will cause the lexer to start returning the specified tokens. Note
461/// that these tokens will be re-macro-expanded when/if expansion is enabled.
462/// This method assumes that the specified stream of tokens has a permanent
463/// owner somewhere, so they do not need to be copied.
Chris Lattner146762e2007-07-20 16:59:19 +0000464void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Chris Lattner7667d0d2006-07-16 18:16:58 +0000465 // Save our current state.
466 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
467 CurMacroExpander));
468 CurLexer = 0;
469 CurDirLookup = 0;
470
471 // Create a macro expander to expand from the specified token stream.
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000472 if (NumCachedMacroExpanders == 0) {
473 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
474 } else {
475 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
476 CurMacroExpander->Init(Toks, NumToks);
477 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000478}
479
480/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
481/// lexer stack. This should only be used in situations where the current
482/// state of the top-of-stack lexer is known.
483void Preprocessor::RemoveTopOfLexerStack() {
484 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000485
486 if (CurMacroExpander) {
487 // Delete or cache the now-dead macro expander.
488 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
489 delete CurMacroExpander;
490 else
491 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
492 } else {
493 delete CurLexer;
494 }
Chris Lattner7667d0d2006-07-16 18:16:58 +0000495 CurLexer = IncludeMacroStack.back().TheLexer;
496 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
497 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
498 IncludeMacroStack.pop_back();
499}
500
Chris Lattner22eb9722006-06-18 05:43:12 +0000501//===----------------------------------------------------------------------===//
Chris Lattner677757a2006-06-28 05:26:32 +0000502// Macro Expansion Handling.
Chris Lattner22eb9722006-06-18 05:43:12 +0000503//===----------------------------------------------------------------------===//
504
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000505/// setMacroInfo - Specify a macro for this identifier.
506///
507void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
508 if (MI == 0) {
509 if (II->hasMacroDefinition()) {
510 Macros.erase(II);
511 II->setHasMacroDefinition(false);
512 }
513 } else {
514 Macros[II] = MI;
515 II->setHasMacroDefinition(true);
516 }
517}
518
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000519/// RegisterBuiltinMacro - Register the specified identifier in the identifier
520/// table and mark it as a builtin macro to be expanded.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000521IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000522 // Get the identifier.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000523 IdentifierInfo *Id = getIdentifierInfo(Name);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000524
525 // Mark it as being a macro that is builtin.
526 MacroInfo *MI = new MacroInfo(SourceLocation());
527 MI->setIsBuiltinMacro();
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000528 setMacroInfo(Id, MI);
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000529 return Id;
530}
531
532
Chris Lattner677757a2006-06-28 05:26:32 +0000533/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
534/// identifier table.
535void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000536 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
Chris Lattner630b33c2006-07-01 22:46:53 +0000537 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
Chris Lattnerc673f902006-06-30 06:10:41 +0000538 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
539 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
Chris Lattner69772b02006-07-02 20:34:39 +0000540 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
Chris Lattnerc1283b92006-07-01 23:16:30 +0000541
542 // GCC Extensions.
543 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
544 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
Chris Lattner847e0e42006-07-01 23:49:16 +0000545 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
Chris Lattner22eb9722006-06-18 05:43:12 +0000546}
547
Chris Lattnerc2395832006-07-09 00:57:04 +0000548/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
549/// in its expansion, currently expands to that token literally.
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000550static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000551 const IdentifierInfo *MacroIdent,
552 Preprocessor &PP) {
Chris Lattnerc2395832006-07-09 00:57:04 +0000553 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
554
555 // If the token isn't an identifier, it's always literally expanded.
556 if (II == 0) return true;
557
558 // If the identifier is a macro, and if that macro is enabled, it may be
559 // expanded so it's not a trivial expansion.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000560 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000561 // Fast expanding "#define X X" is ok, because X would be disabled.
562 II != MacroIdent)
Chris Lattnerc2395832006-07-09 00:57:04 +0000563 return false;
564
565 // If this is an object-like macro invocation, it is safe to trivially expand
566 // it.
567 if (MI->isObjectLike()) return true;
568
569 // If this is a function-like macro invocation, it's safe to trivially expand
570 // as long as the identifier is not a macro argument.
571 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
572 I != E; ++I)
573 if (*I == II)
574 return false; // Identifier is a macro argument.
Chris Lattner273ddd52006-07-29 07:33:01 +0000575
Chris Lattnerc2395832006-07-09 00:57:04 +0000576 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000577}
578
Chris Lattnerc2395832006-07-09 00:57:04 +0000579
Chris Lattnerafe603f2006-07-11 04:02:46 +0000580/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
581/// lexed is a '('. If so, consume the token and return true, if not, this
582/// method should have no observable side-effect on the lexed tokens.
583bool Preprocessor::isNextPPTokenLParen() {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000584 // Do some quick tests for rejection cases.
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000585 unsigned Val;
586 if (CurLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000587 Val = CurLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000588 else
589 Val = CurMacroExpander->isNextTokenLParen();
590
591 if (Val == 2) {
Chris Lattner5c983792007-07-19 00:07:36 +0000592 // We have run off the end. If it's a source file we don't
593 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
594 // macro stack.
595 if (CurLexer)
596 return false;
597 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000598 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
599 if (Entry.TheLexer)
Chris Lattner678c8802006-07-11 05:46:12 +0000600 Val = Entry.TheLexer->isNextPPTokenLParen();
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000601 else
602 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner5c983792007-07-19 00:07:36 +0000603
604 if (Val != 2)
605 break;
606
607 // Ran off the end of a source file?
608 if (Entry.TheLexer)
609 return false;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000610 }
Chris Lattnerafe603f2006-07-11 04:02:46 +0000611 }
612
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000613 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
614 // have found something that isn't a '(' or we found the end of the
615 // translation unit. In either case, return false.
616 if (Val != 1)
617 return false;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000618
Chris Lattner146762e2007-07-20 16:59:19 +0000619 Token Tok;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000620 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000621 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000622 return true;
Chris Lattnerafe603f2006-07-11 04:02:46 +0000623}
Chris Lattner677757a2006-06-28 05:26:32 +0000624
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000625/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
626/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattner146762e2007-07-20 16:59:19 +0000627bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000628 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000629
630 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
631 if (MI->isBuiltinMacro()) {
632 ExpandBuiltinMacro(Identifier);
633 return false;
634 }
635
Chris Lattner81278c62006-10-14 19:03:49 +0000636 // If this is the first use of a target-specific macro, warn about it.
637 if (MI->isTargetSpecific()) {
638 MI->setIsTargetSpecific(false); // Don't warn on second use.
639 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
640 diag::port_target_macro_use);
641 }
642
Chris Lattneree8760b2006-07-15 07:42:55 +0000643 /// Args - If this is a function-like macro expansion, this contains,
Chris Lattner78186052006-07-09 00:45:31 +0000644 /// for each macro argument, the list of tokens that were provided to the
645 /// invocation.
Chris Lattneree8760b2006-07-15 07:42:55 +0000646 MacroArgs *Args = 0;
Chris Lattner78186052006-07-09 00:45:31 +0000647
648 // If this is a function-like macro, read the arguments.
649 if (MI->isFunctionLike()) {
Chris Lattner78186052006-07-09 00:45:31 +0000650 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner24dbee72007-07-19 16:11:58 +0000651 // name isn't a '(', this macro should not be expanded. Otherwise, consume
652 // it.
Chris Lattnerafe603f2006-07-11 04:02:46 +0000653 if (!isNextPPTokenLParen())
Chris Lattner78186052006-07-09 00:45:31 +0000654 return true;
655
Chris Lattner78186052006-07-09 00:45:31 +0000656 // Remember that we are now parsing the arguments to a macro invocation.
657 // Preprocessor directives used inside macro arguments are not portable, and
658 // this enables the warning.
Chris Lattneree8760b2006-07-15 07:42:55 +0000659 InMacroArgs = true;
660 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
Chris Lattner78186052006-07-09 00:45:31 +0000661
662 // Finished parsing args.
Chris Lattneree8760b2006-07-15 07:42:55 +0000663 InMacroArgs = false;
Chris Lattner78186052006-07-09 00:45:31 +0000664
665 // If there was an error parsing the arguments, bail out.
Chris Lattneree8760b2006-07-15 07:42:55 +0000666 if (Args == 0) return false;
Chris Lattner78186052006-07-09 00:45:31 +0000667
668 ++NumFnMacroExpanded;
669 } else {
670 ++NumMacroExpanded;
671 }
Chris Lattner13044d92006-07-03 05:16:44 +0000672
673 // Notice that this macro has been used.
674 MI->setIsUsed(true);
Chris Lattner69772b02006-07-02 20:34:39 +0000675
676 // If we started lexing a macro, enter the macro expansion body.
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000677
678 // If this macro expands to no tokens, don't bother to push it onto the
679 // expansion stack, only to take it right back off.
680 if (MI->getNumTokens() == 0) {
Chris Lattner2ada5d32006-07-15 07:51:24 +0000681 // No need for arg info.
Chris Lattnerc1410dc2006-07-26 05:22:49 +0000682 if (Args) Args->destroy();
Chris Lattner78186052006-07-09 00:45:31 +0000683
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000684 // Ignore this macro use, just return the next token in the current
685 // buffer.
686 bool HadLeadingSpace = Identifier.hasLeadingSpace();
687 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
688
689 Lex(Identifier);
690
691 // If the identifier isn't on some OTHER line, inherit the leading
692 // whitespace/first-on-a-line property of this token. This handles
693 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
694 // empty.
695 if (!Identifier.isAtStartOfLine()) {
Chris Lattner146762e2007-07-20 16:59:19 +0000696 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
697 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000698 }
699 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000700 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000701
Chris Lattner3ce1d1a2006-07-09 01:00:18 +0000702 } else if (MI->getNumTokens() == 1 &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000703 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
704 *this)){
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000705 // Otherwise, if this macro expands into a single trivially-expanded
706 // token: expand it now. This handles common cases like
707 // "#define VAL 42".
708
709 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
710 // identifier to the expanded token.
711 bool isAtStartOfLine = Identifier.isAtStartOfLine();
712 bool hasLeadingSpace = Identifier.hasLeadingSpace();
713
714 // Remember where the token is instantiated.
715 SourceLocation InstantiateLoc = Identifier.getLocation();
716
717 // Replace the result token.
718 Identifier = MI->getReplacementToken(0);
719
720 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattner146762e2007-07-20 16:59:19 +0000721 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
722 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000723
724 // Update the tokens location to include both its logical and physical
725 // locations.
726 SourceLocation Loc =
Chris Lattnerc673f902006-06-30 06:10:41 +0000727 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
Chris Lattner8c204872006-10-14 05:19:21 +0000728 Identifier.setLocation(Loc);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000729
Chris Lattner6e4bf522006-07-27 06:59:25 +0000730 // If this is #define X X, we must mark the result as unexpandible.
731 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000732 if (getMacroInfo(NewII) == MI)
Chris Lattner146762e2007-07-20 16:59:19 +0000733 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000734
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000735 // Since this is not an identifier token, it can't be macro expanded, so
736 // we're done.
737 ++NumFastMacroExpanded;
Chris Lattner78186052006-07-09 00:45:31 +0000738 return false;
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000739 }
740
Chris Lattner78186052006-07-09 00:45:31 +0000741 // Start expanding the macro.
Chris Lattneree8760b2006-07-15 07:42:55 +0000742 EnterMacro(Identifier, Args);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000743
744 // Now that the macro is at the top of the include stack, ask the
745 // preprocessor to read the next token from it.
Chris Lattner78186052006-07-09 00:45:31 +0000746 Lex(Identifier);
747 return false;
748}
749
Chris Lattneree8760b2006-07-15 07:42:55 +0000750/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
Chris Lattner2ada5d32006-07-15 07:51:24 +0000751/// invoked to read all of the actual arguments specified for the macro
Chris Lattner78186052006-07-09 00:45:31 +0000752/// invocation. This returns null on error.
Chris Lattner146762e2007-07-20 16:59:19 +0000753MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattneree8760b2006-07-15 07:42:55 +0000754 MacroInfo *MI) {
Chris Lattner78186052006-07-09 00:45:31 +0000755 // The number of fixed arguments to parse.
756 unsigned NumFixedArgsLeft = MI->getNumArgs();
757 bool isVariadic = MI->isVariadic();
758
Chris Lattner78186052006-07-09 00:45:31 +0000759 // Outer loop, while there are more arguments, keep reading them.
Chris Lattner146762e2007-07-20 16:59:19 +0000760 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +0000761 Tok.setKind(tok::comma);
Chris Lattner78186052006-07-09 00:45:31 +0000762 --NumFixedArgsLeft; // Start reading the first arg.
Chris Lattner36b6e812006-07-21 06:38:30 +0000763
764 // ArgTokens - Build up a list of tokens that make up each argument. Each
Chris Lattner7a4af3b2006-07-26 06:26:52 +0000765 // argument is separated by an EOF token. Use a SmallVector so we can avoid
766 // heap allocations in the common case.
Chris Lattner146762e2007-07-20 16:59:19 +0000767 llvm::SmallVector<Token, 64> ArgTokens;
Chris Lattner36b6e812006-07-21 06:38:30 +0000768
769 unsigned NumActuals = 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000770 while (Tok.is(tok::comma)) {
Chris Lattner24dbee72007-07-19 16:11:58 +0000771 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
772 // that we already consumed the first one.
Chris Lattner78186052006-07-09 00:45:31 +0000773 unsigned NumParens = 0;
Chris Lattner36b6e812006-07-21 06:38:30 +0000774
Chris Lattner78186052006-07-09 00:45:31 +0000775 while (1) {
Chris Lattnerafe603f2006-07-11 04:02:46 +0000776 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
777 // an argument value in a macro could expand to ',' or '(' or ')'.
Chris Lattner78186052006-07-09 00:45:31 +0000778 LexUnexpandedToken(Tok);
779
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000780 if (Tok.is(tok::eof)) {
Chris Lattner78186052006-07-09 00:45:31 +0000781 Diag(MacroName, diag::err_unterm_macro_invoc);
782 // Do not lose the EOF. Return it to the client.
783 MacroName = Tok;
784 return 0;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000785 } else if (Tok.is(tok::r_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000786 // If we found the ) token, the macro arg list is done.
787 if (NumParens-- == 0)
788 break;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000789 } else if (Tok.is(tok::l_paren)) {
Chris Lattner78186052006-07-09 00:45:31 +0000790 ++NumParens;
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000791 } else if (Tok.is(tok::comma) && NumParens == 0) {
Chris Lattner78186052006-07-09 00:45:31 +0000792 // Comma ends this argument if there are more fixed arguments expected.
793 if (NumFixedArgsLeft)
794 break;
795
Chris Lattner2ada5d32006-07-15 07:51:24 +0000796 // If this is not a variadic macro, too many args were specified.
Chris Lattner78186052006-07-09 00:45:31 +0000797 if (!isVariadic) {
798 // Emit the diagnostic at the macro name in case there is a missing ).
799 // Emitting it at the , could be far away from the macro name.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000800 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000801 return 0;
802 }
803 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000804 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Chris Lattner457fc152006-07-29 06:30:25 +0000805 // If this is a comment token in the argument list and we're just in
806 // -C mode (not -CC mode), discard the comment.
807 continue;
Chris Lattner78186052006-07-09 00:45:31 +0000808 }
809
810 ArgTokens.push_back(Tok);
811 }
812
Chris Lattnera12dd152006-07-11 04:09:02 +0000813 // Empty arguments are standard in C99 and supported as an extension in
814 // other modes.
815 if (ArgTokens.empty() && !Features.C99)
816 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattnerafe603f2006-07-11 04:02:46 +0000817
Chris Lattner36b6e812006-07-21 06:38:30 +0000818 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattner146762e2007-07-20 16:59:19 +0000819 Token EOFTok;
Chris Lattner8c204872006-10-14 05:19:21 +0000820 EOFTok.startToken();
821 EOFTok.setKind(tok::eof);
822 EOFTok.setLocation(Tok.getLocation());
823 EOFTok.setLength(0);
Chris Lattner36b6e812006-07-21 06:38:30 +0000824 ArgTokens.push_back(EOFTok);
825 ++NumActuals;
Chris Lattner78186052006-07-09 00:45:31 +0000826 --NumFixedArgsLeft;
827 };
828
829 // Okay, we either found the r_paren. Check to see if we parsed too few
830 // arguments.
Chris Lattner78186052006-07-09 00:45:31 +0000831 unsigned MinArgsExpected = MI->getNumArgs();
832
Chris Lattner775d8322006-07-29 04:39:41 +0000833 // See MacroArgs instance var for description of this.
834 bool isVarargsElided = false;
835
Chris Lattner2ada5d32006-07-15 07:51:24 +0000836 if (NumActuals < MinArgsExpected) {
Chris Lattner78186052006-07-09 00:45:31 +0000837 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000838 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
Chris Lattner78186052006-07-09 00:45:31 +0000839 // Varargs where the named vararg parameter is missing: ok as extension.
840 // #define A(x, ...)
841 // A("blah")
842 Diag(Tok, diag::ext_missing_varargs_arg);
Chris Lattner775d8322006-07-29 04:39:41 +0000843
844 // Remember this occurred if this is a C99 macro invocation with at least
845 // one actual argument.
Chris Lattner95a06b32006-07-30 08:40:43 +0000846 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
Chris Lattner78186052006-07-09 00:45:31 +0000847 } else if (MI->getNumArgs() == 1) {
848 // #define A(x)
849 // A()
Chris Lattnere7a51302006-07-29 01:25:12 +0000850 // is ok because it is an empty argument.
Chris Lattnera12dd152006-07-11 04:09:02 +0000851
852 // Empty arguments are standard in C99 and supported as an extension in
853 // other modes.
854 if (ArgTokens.empty() && !Features.C99)
855 Diag(Tok, diag::ext_empty_fnmacro_arg);
Chris Lattner78186052006-07-09 00:45:31 +0000856 } else {
857 // Otherwise, emit the error.
Chris Lattner2ada5d32006-07-15 07:51:24 +0000858 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Chris Lattner78186052006-07-09 00:45:31 +0000859 return 0;
860 }
Chris Lattnere7a51302006-07-29 01:25:12 +0000861
862 // Add a marker EOF token to the end of the token list for this argument.
863 SourceLocation EndLoc = Tok.getLocation();
Chris Lattner8c204872006-10-14 05:19:21 +0000864 Tok.startToken();
865 Tok.setKind(tok::eof);
866 Tok.setLocation(EndLoc);
867 Tok.setLength(0);
Chris Lattnere7a51302006-07-29 01:25:12 +0000868 ArgTokens.push_back(Tok);
Chris Lattner78186052006-07-09 00:45:31 +0000869 }
870
Chris Lattner775d8322006-07-29 04:39:41 +0000871 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
Chris Lattnerf373a4a2006-06-26 06:16:29 +0000872}
873
Chris Lattnerc673f902006-06-30 06:10:41 +0000874/// ComputeDATE_TIME - Compute the current time, enter it into the specified
875/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
876/// the identifier tokens inserted.
877static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000878 Preprocessor &PP) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000879 time_t TT = time(0);
880 struct tm *TM = localtime(&TT);
881
882 static const char * const Months[] = {
883 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
884 };
885
886 char TmpBuffer[100];
887 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
888 TM->tm_year+1900);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000889 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000890
891 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000892 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
Chris Lattnerc673f902006-06-30 06:10:41 +0000893}
894
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000895/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
896/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000897void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000898 // Figure out which token this is.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000899 IdentifierInfo *II = Tok.getIdentifierInfo();
900 assert(II && "Can't be a macro without id info!");
Chris Lattner69772b02006-07-02 20:34:39 +0000901
902 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
903 // lex the token after it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000904 if (II == Ident_Pragma)
Chris Lattner69772b02006-07-02 20:34:39 +0000905 return Handle_Pragma(Tok);
906
Chris Lattner78186052006-07-09 00:45:31 +0000907 ++NumBuiltinMacroExpanded;
908
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000909 char TmpBuffer[100];
Chris Lattner69772b02006-07-02 20:34:39 +0000910
911 // Set up the return result.
Chris Lattner8c204872006-10-14 05:19:21 +0000912 Tok.setIdentifierInfo(0);
Chris Lattner146762e2007-07-20 16:59:19 +0000913 Tok.clearFlag(Token::NeedsCleaning);
Chris Lattner630b33c2006-07-01 22:46:53 +0000914
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000915 if (II == Ident__LINE__) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000916 // __LINE__ expands to a simple numeric value.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000917 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000918 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000919 Tok.setKind(tok::numeric_constant);
920 Tok.setLength(Length);
921 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000922 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000923 SourceLocation Loc = Tok.getLocation();
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000924 if (II == Ident__BASE_FILE__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000925 Diag(Tok, diag::ext_pp_base_file);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000926 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
927 while (NextLoc.isValid()) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000928 Loc = NextLoc;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000929 NextLoc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000930 }
931 }
932
Chris Lattner0766e592006-07-03 01:07:01 +0000933 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000934 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Chris Lattnerecc39e92006-07-15 05:23:31 +0000935 FN = '"' + Lexer::Stringify(FN) + '"';
Chris Lattner8c204872006-10-14 05:19:21 +0000936 Tok.setKind(tok::string_literal);
937 Tok.setLength(FN.size());
938 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000939 } else if (II == Ident__DATE__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000940 if (!DATELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000941 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000942 Tok.setKind(tok::string_literal);
943 Tok.setLength(strlen("\"Mmm dd yyyy\""));
944 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000945 } else if (II == Ident__TIME__) {
Chris Lattnerc673f902006-06-30 06:10:41 +0000946 if (!TIMELoc.isValid())
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000947 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
Chris Lattner8c204872006-10-14 05:19:21 +0000948 Tok.setKind(tok::string_literal);
949 Tok.setLength(strlen("\"hh:mm:ss\""));
950 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000951 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerc1283b92006-07-01 23:16:30 +0000952 Diag(Tok, diag::ext_pp_include_level);
953
954 // Compute the include depth of this token.
955 unsigned Depth = 0;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000956 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
957 for (; Loc.isValid(); ++Depth)
958 Loc = SourceMgr.getIncludeLoc(Loc);
Chris Lattnerc1283b92006-07-01 23:16:30 +0000959
960 // __INCLUDE_LEVEL__ expands to a simple numeric value.
961 sprintf(TmpBuffer, "%u", Depth);
962 unsigned Length = strlen(TmpBuffer);
Chris Lattner8c204872006-10-14 05:19:21 +0000963 Tok.setKind(tok::numeric_constant);
964 Tok.setLength(Length);
965 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000966 } else if (II == Ident__TIMESTAMP__) {
Chris Lattner847e0e42006-07-01 23:49:16 +0000967 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
968 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
969 Diag(Tok, diag::ext_pp_timestamp);
970
971 // Get the file that we are lexing out of. If we're currently lexing from
972 // a macro, dig into the include stack.
973 const FileEntry *CurFile = 0;
Chris Lattnerecfeafe2006-07-02 21:26:45 +0000974 Lexer *TheLexer = getCurrentFileLexer();
Chris Lattner847e0e42006-07-01 23:49:16 +0000975
976 if (TheLexer)
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000977 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Chris Lattner847e0e42006-07-01 23:49:16 +0000978
979 // If this file is older than the file it depends on, emit a diagnostic.
980 const char *Result;
981 if (CurFile) {
982 time_t TT = CurFile->getModificationTime();
983 struct tm *TM = localtime(&TT);
984 Result = asctime(TM);
985 } else {
986 Result = "??? ??? ?? ??:??:?? ????\n";
987 }
988 TmpBuffer[0] = '"';
989 strcpy(TmpBuffer+1, Result);
990 unsigned Len = strlen(TmpBuffer);
991 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
Chris Lattner8c204872006-10-14 05:19:21 +0000992 Tok.setKind(tok::string_literal);
993 Tok.setLength(Len);
994 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000995 } else {
996 assert(0 && "Unknown identifier!");
997 }
998}
Chris Lattner677757a2006-06-28 05:26:32 +0000999
1000//===----------------------------------------------------------------------===//
1001// Lexer Event Handling.
1002//===----------------------------------------------------------------------===//
1003
Chris Lattnercefc7682006-07-08 08:28:12 +00001004/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1005/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +00001006IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +00001007 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001008 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +00001009 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1010
1011 // Look up this token, see if it is a macro, or if it is a language keyword.
1012 IdentifierInfo *II;
1013 if (BufPtr && !Identifier.needsCleaning()) {
1014 // No cleaning needed, just use the characters from the lexed buffer.
1015 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1016 } else {
1017 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +00001018 llvm::SmallVector<char, 64> IdentifierBuffer;
1019 IdentifierBuffer.resize(Identifier.getLength());
1020 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +00001021 unsigned Size = getSpelling(Identifier, TmpBuf);
1022 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1023 }
Chris Lattner8c204872006-10-14 05:19:21 +00001024 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001025 return II;
1026}
1027
1028
Chris Lattner677757a2006-06-28 05:26:32 +00001029/// HandleIdentifier - This callback is invoked when the lexer reads an
1030/// identifier. This callback looks up the identifier in the map and/or
1031/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +00001032void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +00001033 assert(Identifier.getIdentifierInfo() &&
1034 "Can't handle identifiers without identifier info!");
1035
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001036 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +00001037
1038 // If this identifier was poisoned, and if it was not produced from a macro
1039 // expansion, emit an error.
Chris Lattner8ff71992006-07-06 05:17:39 +00001040 if (II.isPoisoned() && CurLexer) {
1041 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1042 Diag(Identifier, diag::err_pp_used_poisoned_id);
1043 else
1044 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1045 }
Chris Lattner677757a2006-06-28 05:26:32 +00001046
Chris Lattner78186052006-07-09 00:45:31 +00001047 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001048 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +00001049 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1050 if (MI->isEnabled()) {
1051 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1052 return;
1053 } else {
1054 // C99 6.10.3.4p2 says that a disabled macro may never again be
1055 // expanded, even if it's in a context where it could be expanded in the
1056 // future.
Chris Lattner146762e2007-07-20 16:59:19 +00001057 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +00001058 }
1059 }
Chris Lattner063400e2006-10-14 19:54:15 +00001060 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1061 // If this identifier is a macro on some other target, emit a diagnostic.
1062 // This diagnosic is only emitted when macro expansion is enabled, because
1063 // the macro would not have been expanded for the other target either.
1064 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1065 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1066 diag::port_target_macro_use);
1067
1068 }
Chris Lattner677757a2006-06-28 05:26:32 +00001069
Chris Lattner5b9f4892006-11-21 17:23:33 +00001070 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1071 // then we act as if it is the actual operator and not the textual
1072 // representation of it.
1073 if (II.isCPlusPlusOperatorKeyword())
1074 Identifier.setIdentifierInfo(0);
1075
Chris Lattner677757a2006-06-28 05:26:32 +00001076 // Change the kind of this identifier to the appropriate token kind, e.g.
1077 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +00001078 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +00001079
1080 // If this is an extension token, diagnose its use.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001081 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1082 // For now, I'm just commenting it out (while I work on attributes).
Chris Lattner53621a52007-06-13 20:44:40 +00001083 if (II.isExtensionToken() && Features.C99)
1084 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +00001085}
1086
Chris Lattner22eb9722006-06-18 05:43:12 +00001087/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1088/// the current file. This either returns the EOF token or pops a level off
1089/// the include stack and keeps going.
Chris Lattner146762e2007-07-20 16:59:19 +00001090bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001091 assert(!CurMacroExpander &&
1092 "Ending a file when currently in a macro!");
1093
Chris Lattner371ac8a2006-07-04 07:11:10 +00001094 // See if this file had a controlling macro.
Chris Lattner3665f162006-07-04 07:26:10 +00001095 if (CurLexer) { // Not ending a macro, ignore it.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001096 if (const IdentifierInfo *ControllingMacro =
Chris Lattner371ac8a2006-07-04 07:11:10 +00001097 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner3665f162006-07-04 07:26:10 +00001098 // Okay, this has a controlling macro, remember in PerFileInfo.
1099 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001100 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001101 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001102 }
1103 }
1104
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 // If this is a #include'd file, pop it off the include stack and continue
1106 // lexing the #includer file.
Chris Lattner69772b02006-07-02 20:34:39 +00001107 if (!IncludeMacroStack.empty()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001108 // We're done with the #included file.
Chris Lattner7667d0d2006-07-16 18:16:58 +00001109 RemoveTopOfLexerStack();
Chris Lattner0c885f52006-06-21 06:50:18 +00001110
1111 // Notify the client, if desired, that we are in a new source file.
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001112 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattnerc8997182006-06-22 05:52:16 +00001113 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1114
1115 // Get the file entry for the current file.
1116 if (const FileEntry *FE =
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001117 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001118 FileType = HeaderInfo.getFileDirFlavor(FE);
Chris Lattnerc8997182006-06-22 05:52:16 +00001119
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001120 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1121 PPCallbacks::ExitFile, FileType);
Chris Lattnerc8997182006-06-22 05:52:16 +00001122 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001123
1124 // Client should lex another token.
1125 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001126 }
1127
Chris Lattner8c204872006-10-14 05:19:21 +00001128 Result.startToken();
Chris Lattnerd01e2912006-06-18 16:22:51 +00001129 CurLexer->BufferPtr = CurLexer->BufferEnd;
1130 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
Chris Lattner8c204872006-10-14 05:19:21 +00001131 Result.setKind(tok::eof);
Chris Lattner22eb9722006-06-18 05:43:12 +00001132
1133 // We're done with the #included file.
1134 delete CurLexer;
1135 CurLexer = 0;
Chris Lattner13044d92006-07-03 05:16:44 +00001136
Chris Lattner03f83482006-07-10 06:16:26 +00001137 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001138 // diagnostic is enabled, look for macros that have not been used.
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001139 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001140 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1141 Macros.begin(), E = Macros.end(); I != E; ++I) {
1142 if (!I->second->isUsed())
1143 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001144 }
1145 }
Chris Lattner2183a6e2006-07-18 06:36:12 +00001146 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001147}
1148
1149/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
Chris Lattner7667d0d2006-07-16 18:16:58 +00001150/// the current macro expansion or token stream expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001151bool Preprocessor::HandleEndOfMacro(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001152 assert(CurMacroExpander && !CurLexer &&
1153 "Ending a macro when currently in a #include file!");
1154
Chris Lattnerc02c4ab2007-07-15 00:25:26 +00001155 // Delete or cache the now-dead macro expander.
1156 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1157 delete CurMacroExpander;
1158 else
1159 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Chris Lattner22eb9722006-06-18 05:43:12 +00001160
Chris Lattner69772b02006-07-02 20:34:39 +00001161 // Handle this like a #include file being popped off the stack.
1162 CurMacroExpander = 0;
1163 return HandleEndOfFile(Result, true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001164}
1165
1166
1167//===----------------------------------------------------------------------===//
1168// Utility Methods for Preprocessor Directive Handling.
1169//===----------------------------------------------------------------------===//
1170
1171/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1172/// current line until the tok::eom token is found.
Chris Lattnercb283342006-06-18 06:48:37 +00001173void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattner146762e2007-07-20 16:59:19 +00001174 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001175 do {
Chris Lattnercb283342006-06-18 06:48:37 +00001176 LexUnexpandedToken(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001177 } while (Tmp.isNot(tok::eom));
Chris Lattner22eb9722006-06-18 05:43:12 +00001178}
1179
Chris Lattner652c1692006-11-21 23:47:30 +00001180/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1181static bool isCXXNamedOperator(const std::string &Spelling) {
1182 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1183 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1184 Spelling == "or" || Spelling == "xor";
1185}
1186
Chris Lattner22eb9722006-06-18 05:43:12 +00001187/// ReadMacroName - Lex and validate a macro name, which occurs after a
1188/// #define or #undef. This sets the token kind to eom and discards the rest
Chris Lattnere8eef322006-07-08 07:01:00 +00001189/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1190/// this is due to a a #define, 2 if #undef directive, 0 if it is something
Chris Lattner44f8a662006-07-03 01:27:27 +00001191/// else (e.g. #ifdef).
Chris Lattner146762e2007-07-20 16:59:19 +00001192void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001193 // Read the token, don't allow macro expansion on it.
Chris Lattnercb283342006-06-18 06:48:37 +00001194 LexUnexpandedToken(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001195
1196 // Missing macro name?
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001197 if (MacroNameTok.is(tok::eom))
Chris Lattner22eb9722006-06-18 05:43:12 +00001198 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1199
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001200 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1201 if (II == 0) {
Chris Lattner652c1692006-11-21 23:47:30 +00001202 std::string Spelling = getSpelling(MacroNameTok);
1203 if (isCXXNamedOperator(Spelling))
1204 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1205 // except for their spellings.
1206 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1207 else
1208 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001209 // Fall through on error.
Chris Lattner2bb8a952006-11-21 22:24:17 +00001210 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001211 // Error if defining "defined": C99 6.10.8.4.
Chris Lattneraaf09112006-07-03 01:17:59 +00001212 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner259716a2007-10-07 08:04:56 +00001213 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnerc43ddc82007-10-07 08:44:20 +00001214 getMacroInfo(II)->isBuiltinMacro()) {
Chris Lattner44f8a662006-07-03 01:27:27 +00001215 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
Chris Lattnere8eef322006-07-08 07:01:00 +00001216 if (isDefineUndef == 1)
1217 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1218 else
1219 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
Chris Lattner22eb9722006-06-18 05:43:12 +00001220 } else {
1221 // Okay, we got a good identifier node. Return it.
Chris Lattnercb283342006-06-18 06:48:37 +00001222 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001223 }
1224
Chris Lattner22eb9722006-06-18 05:43:12 +00001225 // Invalid macro name, read and discard the rest of the line. Then set the
1226 // token kind to tok::eom.
Chris Lattner8c204872006-10-14 05:19:21 +00001227 MacroNameTok.setKind(tok::eom);
Chris Lattner22eb9722006-06-18 05:43:12 +00001228 return DiscardUntilEndOfDirective();
1229}
1230
1231/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1232/// not, emit a diagnostic and consume up until the eom.
Chris Lattnercb283342006-06-18 06:48:37 +00001233void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattner146762e2007-07-20 16:59:19 +00001234 Token Tmp;
Chris Lattnercb283342006-06-18 06:48:37 +00001235 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 // There should be no tokens after the directive, but we allow them as an
1237 // extension.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001238 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001239 Lex(Tmp);
1240
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001241 if (Tmp.isNot(tok::eom)) {
Chris Lattnercb283342006-06-18 06:48:37 +00001242 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1243 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001244 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001245}
1246
1247
1248
1249/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1250/// decided that the subsequent tokens are in the #if'd out portion of the
1251/// file. Lex the rest of the file, until we see an #endif. If
1252/// FoundNonSkipPortion is true, then we have already emitted code for part of
1253/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1254/// is true, then #else directives are ok, if not, then we have already seen one
1255/// so a #else directive is a duplicate. When this returns, the caller can lex
1256/// the first valid token.
Chris Lattnerd01e2912006-06-18 16:22:51 +00001257void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
Chris Lattner22eb9722006-06-18 05:43:12 +00001258 bool FoundNonSkipPortion,
1259 bool FoundElse) {
1260 ++NumSkipped;
Chris Lattner69772b02006-07-02 20:34:39 +00001261 assert(CurMacroExpander == 0 && CurLexer &&
Chris Lattner22eb9722006-06-18 05:43:12 +00001262 "Lexing a macro, not a file?");
1263
1264 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1265 FoundNonSkipPortion, FoundElse);
1266
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001267 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1268 // disabling warnings, etc.
1269 CurLexer->LexingRawMode = true;
Chris Lattner146762e2007-07-20 16:59:19 +00001270 Token Tok;
Chris Lattner22eb9722006-06-18 05:43:12 +00001271 while (1) {
Chris Lattnercb283342006-06-18 06:48:37 +00001272 CurLexer->Lex(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001273
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001274 // If this is the end of the buffer, we have an error.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001275 if (Tok.is(tok::eof)) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001276 // Emit errors for each unterminated conditional on the stack, including
1277 // the current one.
1278 while (!CurLexer->ConditionalStack.empty()) {
1279 Diag(CurLexer->ConditionalStack.back().IfLoc,
1280 diag::err_pp_unterminated_conditional);
1281 CurLexer->ConditionalStack.pop_back();
1282 }
1283
1284 // Just return and let the caller lex after this #include.
1285 break;
1286 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001287
1288 // If this token is not a preprocessor directive, just skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001289 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Chris Lattner22eb9722006-06-18 05:43:12 +00001290 continue;
1291
1292 // We just parsed a # character at the start of a line, so we're in
1293 // directive mode. Tell the lexer this so any newlines we see will be
1294 // converted into an EOM token (this terminates the macro).
1295 CurLexer->ParsingPreprocessorDirective = true;
Chris Lattner457fc152006-07-29 06:30:25 +00001296 CurLexer->KeepCommentMode = false;
1297
Chris Lattner22eb9722006-06-18 05:43:12 +00001298
1299 // Read the next token, the directive flavor.
Chris Lattnercb283342006-06-18 06:48:37 +00001300 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001301
1302 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1303 // something bogus), skip it.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001304 if (Tok.isNot(tok::identifier)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001305 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001306 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001307 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001308 continue;
1309 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001310
Chris Lattner22eb9722006-06-18 05:43:12 +00001311 // If the first letter isn't i or e, it isn't intesting to us. We know that
1312 // this is safe in the face of spelling differences, because there is no way
1313 // to spell an i/e in a strange way that is another letter. Skipping this
Chris Lattnere60165f2006-06-22 06:36:29 +00001314 // allows us to avoid looking up the identifier info for #define/#undef and
1315 // other common directives.
1316 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1317 char FirstChar = RawCharData[0];
Chris Lattner22eb9722006-06-18 05:43:12 +00001318 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1319 FirstChar != 'i' && FirstChar != 'e') {
1320 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001321 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001322 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001323 continue;
1324 }
1325
Chris Lattnere60165f2006-06-22 06:36:29 +00001326 // Get the identifier name without trigraphs or embedded newlines. Note
1327 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1328 // when skipping.
1329 // TODO: could do this with zero copies in the no-clean case by using
1330 // strncmp below.
1331 char Directive[20];
1332 unsigned IdLen;
1333 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1334 IdLen = Tok.getLength();
1335 memcpy(Directive, RawCharData, IdLen);
1336 Directive[IdLen] = 0;
1337 } else {
1338 std::string DirectiveStr = getSpelling(Tok);
1339 IdLen = DirectiveStr.size();
1340 if (IdLen >= 20) {
1341 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001342 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001343 CurLexer->KeepCommentMode = KeepComments;
Chris Lattnere60165f2006-06-22 06:36:29 +00001344 continue;
1345 }
1346 memcpy(Directive, &DirectiveStr[0], IdLen);
1347 Directive[IdLen] = 0;
1348 }
1349
Chris Lattner22eb9722006-06-18 05:43:12 +00001350 if (FirstChar == 'i' && Directive[1] == 'f') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001351 if ((IdLen == 2) || // "if"
1352 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1353 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
Chris Lattner22eb9722006-06-18 05:43:12 +00001354 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1355 // bother parsing the condition.
Chris Lattnercb283342006-06-18 06:48:37 +00001356 DiscardUntilEndOfDirective();
Chris Lattner50b497e2006-06-18 16:32:35 +00001357 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerd01e2912006-06-18 16:22:51 +00001358 /*foundnonskip*/false,
1359 /*fnddelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001360 }
1361 } else if (FirstChar == 'e') {
Chris Lattnere60165f2006-06-22 06:36:29 +00001362 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
Chris Lattnercb283342006-06-18 06:48:37 +00001363 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00001364 PPConditionalInfo CondInfo;
1365 CondInfo.WasSkipping = true; // Silence bogus warning.
1366 bool InCond = CurLexer->popConditionalLevel(CondInfo);
Chris Lattnercf6bc662006-11-05 07:59:08 +00001367 InCond = InCond; // Silence warning in no-asserts mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001368 assert(!InCond && "Can't be skipping if not in a conditional!");
1369
1370 // If we popped the outermost skipping block, we're done skipping!
1371 if (!CondInfo.WasSkipping)
1372 break;
Chris Lattnere60165f2006-06-22 06:36:29 +00001373 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
Chris Lattner22eb9722006-06-18 05:43:12 +00001374 // #else directive in a skipping conditional. If not in some other
1375 // skipping conditional, and if #else hasn't already been seen, enter it
1376 // as a non-skipping conditional.
Chris Lattnercb283342006-06-18 06:48:37 +00001377 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00001378 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1379
1380 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001381 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001382
1383 // Note that we've seen a #else in this conditional.
1384 CondInfo.FoundElse = true;
1385
1386 // If the conditional is at the top level, and the #if block wasn't
1387 // entered, enter the #else block now.
1388 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1389 CondInfo.FoundNonSkip = true;
1390 break;
1391 }
Chris Lattnere60165f2006-06-22 06:36:29 +00001392 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1394
1395 bool ShouldEnter;
1396 // If this is in a skipping block or if we're already handled this #if
1397 // block, don't bother parsing the condition.
1398 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
Chris Lattnercb283342006-06-18 06:48:37 +00001399 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001400 ShouldEnter = false;
1401 } else {
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001402 // Restore the value of LexingRawMode so that identifiers are
Chris Lattner22eb9722006-06-18 05:43:12 +00001403 // looked up, etc, inside the #elif expression.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001404 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1405 CurLexer->LexingRawMode = false;
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00001406 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00001407 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001408 CurLexer->LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001409 }
1410
1411 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00001412 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00001413
1414 // If this condition is true, enter it!
1415 if (ShouldEnter) {
1416 CondInfo.FoundNonSkip = true;
1417 break;
1418 }
1419 }
1420 }
1421
1422 CurLexer->ParsingPreprocessorDirective = false;
Chris Lattner457fc152006-07-29 06:30:25 +00001423 // Restore comment saving mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001424 CurLexer->KeepCommentMode = KeepComments;
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 }
1426
1427 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1428 // of the file, just stop skipping and return to lexing whatever came after
1429 // the #if block.
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001430 CurLexer->LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001431}
1432
1433//===----------------------------------------------------------------------===//
1434// Preprocessor Directive Handling.
1435//===----------------------------------------------------------------------===//
1436
1437/// HandleDirective - This callback is invoked when the lexer sees a # token
1438/// at the start of a line. This consumes the directive, modifies the
1439/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1440/// read is the correct one.
Chris Lattner146762e2007-07-20 16:59:19 +00001441void Preprocessor::HandleDirective(Token &Result) {
Chris Lattner4d5e1a72006-07-03 01:01:29 +00001442 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Chris Lattner22eb9722006-06-18 05:43:12 +00001443
1444 // We just parsed a # character at the start of a line, so we're in directive
1445 // mode. Tell the lexer this so any newlines we see will be converted into an
Chris Lattner78186052006-07-09 00:45:31 +00001446 // EOM token (which terminates the directive).
Chris Lattner22eb9722006-06-18 05:43:12 +00001447 CurLexer->ParsingPreprocessorDirective = true;
1448
1449 ++NumDirectives;
1450
Chris Lattner371ac8a2006-07-04 07:11:10 +00001451 // We are about to read a token. For the multiple-include optimization FA to
1452 // work, we have to remember if we had read any tokens *before* this
1453 // pp-directive.
1454 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1455
Chris Lattner78186052006-07-09 00:45:31 +00001456 // Read the next token, the directive flavor. This isn't expanded due to
1457 // C99 6.10.3p8.
Chris Lattnercb283342006-06-18 06:48:37 +00001458 LexUnexpandedToken(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001459
Chris Lattner78186052006-07-09 00:45:31 +00001460 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1461 // #define A(x) #x
1462 // A(abc
1463 // #warning blah
1464 // def)
1465 // If so, the user is relying on non-portable behavior, emit a diagnostic.
Chris Lattneree8760b2006-07-15 07:42:55 +00001466 if (InMacroArgs)
Chris Lattner78186052006-07-09 00:45:31 +00001467 Diag(Result, diag::ext_embedded_directive);
1468
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001469TryAgain:
Chris Lattner22eb9722006-06-18 05:43:12 +00001470 switch (Result.getKind()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001471 case tok::eom:
Chris Lattnercb283342006-06-18 06:48:37 +00001472 return; // null directive.
Chris Lattnerbcb416b2006-10-27 05:43:50 +00001473 case tok::comment:
1474 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1475 LexUnexpandedToken(Result);
1476 goto TryAgain;
Chris Lattner22eb9722006-06-18 05:43:12 +00001477
Chris Lattner22eb9722006-06-18 05:43:12 +00001478 case tok::numeric_constant:
1479 // FIXME: implement # 7 line numbers!
Chris Lattner6e5b2a02006-10-17 02:53:32 +00001480 DiscardUntilEndOfDirective();
1481 return;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001482 default:
1483 IdentifierInfo *II = Result.getIdentifierInfo();
1484 if (II == 0) break; // Not an identifier.
1485
1486 // Ask what the preprocessor keyword ID is.
1487 switch (II->getPPKeywordID()) {
1488 default: break;
1489 // C99 6.10.1 - Conditional Inclusion.
1490 case tok::pp_if:
1491 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1492 case tok::pp_ifdef:
1493 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1494 case tok::pp_ifndef:
1495 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1496 case tok::pp_elif:
1497 return HandleElifDirective(Result);
1498 case tok::pp_else:
1499 return HandleElseDirective(Result);
1500 case tok::pp_endif:
1501 return HandleEndifDirective(Result);
1502
1503 // C99 6.10.2 - Source File Inclusion.
1504 case tok::pp_include:
1505 return HandleIncludeDirective(Result); // Handle #include.
1506
1507 // C99 6.10.3 - Macro Replacement.
1508 case tok::pp_define:
1509 return HandleDefineDirective(Result, false);
1510 case tok::pp_undef:
1511 return HandleUndefDirective(Result);
1512
1513 // C99 6.10.4 - Line Control.
1514 case tok::pp_line:
1515 // FIXME: implement #line
1516 DiscardUntilEndOfDirective();
1517 return;
1518
1519 // C99 6.10.5 - Error Directive.
1520 case tok::pp_error:
1521 return HandleUserDiagnosticDirective(Result, false);
1522
1523 // C99 6.10.6 - Pragma Directive.
1524 case tok::pp_pragma:
1525 return HandlePragmaDirective();
1526
1527 // GNU Extensions.
1528 case tok::pp_import:
1529 return HandleImportDirective(Result);
1530 case tok::pp_include_next:
1531 return HandleIncludeNextDirective(Result);
1532
1533 case tok::pp_warning:
1534 Diag(Result, diag::ext_pp_warning_directive);
1535 return HandleUserDiagnosticDirective(Result, true);
1536 case tok::pp_ident:
1537 return HandleIdentSCCSDirective(Result);
1538 case tok::pp_sccs:
1539 return HandleIdentSCCSDirective(Result);
1540 case tok::pp_assert:
1541 //isExtension = true; // FIXME: implement #assert
Chris Lattner22eb9722006-06-18 05:43:12 +00001542 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001543 case tok::pp_unassert:
1544 //isExtension = true; // FIXME: implement #unassert
Chris Lattner22eb9722006-06-18 05:43:12 +00001545 break;
Chris Lattner87d3bec2006-10-17 03:44:32 +00001546
1547 // clang extensions.
1548 case tok::pp_define_target:
1549 return HandleDefineDirective(Result, true);
1550 case tok::pp_define_other_target:
1551 return HandleDefineOtherTargetDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001552 }
1553 break;
1554 }
1555
1556 // If we reached here, the preprocessing token is not valid!
Chris Lattnercb283342006-06-18 06:48:37 +00001557 Diag(Result, diag::err_pp_invalid_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001558
1559 // Read the rest of the PP line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001560 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00001561
1562 // Okay, we're done parsing the directive.
Chris Lattner22eb9722006-06-18 05:43:12 +00001563}
1564
Chris Lattner146762e2007-07-20 16:59:19 +00001565void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001566 bool isWarning) {
1567 // Read the rest of the line raw. We do this because we don't want macros
1568 // to be expanded and we don't require that the tokens be valid preprocessing
1569 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1570 // collapse multiple consequtive white space between tokens, but this isn't
1571 // specified by the standard.
1572 std::string Message = CurLexer->ReadToEndOfLine();
1573
1574 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001575 return Diag(Tok, DiagID, Message);
1576}
1577
1578/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1579///
Chris Lattner146762e2007-07-20 16:59:19 +00001580void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001581 // Yes, this directive is an extension.
Chris Lattner01d66cc2006-07-03 22:16:27 +00001582 Diag(Tok, diag::ext_pp_ident_directive);
1583
Chris Lattner371ac8a2006-07-04 07:11:10 +00001584 // Read the string argument.
Chris Lattner146762e2007-07-20 16:59:19 +00001585 Token StrTok;
Chris Lattner01d66cc2006-07-03 22:16:27 +00001586 Lex(StrTok);
1587
1588 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001589 if (StrTok.isNot(tok::string_literal) &&
1590 StrTok.isNot(tok::wide_string_literal))
Chris Lattner01d66cc2006-07-03 22:16:27 +00001591 return Diag(StrTok, diag::err_pp_malformed_ident);
1592
1593 // Verify that there is nothing after the string, other than EOM.
1594 CheckEndOfDirective("#ident");
1595
Chris Lattnerb8d6d5a2006-11-21 04:09:30 +00001596 if (Callbacks)
1597 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
Chris Lattner22eb9722006-06-18 05:43:12 +00001598}
1599
Chris Lattnerb8761832006-06-24 21:31:03 +00001600//===----------------------------------------------------------------------===//
1601// Preprocessor Include Directive Handling.
1602//===----------------------------------------------------------------------===//
1603
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001604/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1605/// checked and spelled filename, e.g. as an operand of #include. This returns
1606/// true if the input filename was in <>'s or false if it were in ""'s. The
1607/// caller is expected to provide a buffer that is large enough to hold the
1608/// spelling of the filename, but is also expected to handle the case when
1609/// this method decides to use a different buffer.
Chris Lattner93ab9f12007-07-23 04:15:27 +00001610bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001611 const char *&BufStart,
1612 const char *&BufEnd) {
1613 // Get the text form of the filename.
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001614 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1615
1616 // Make sure the filename is <x> or "x".
1617 bool isAngled;
1618 if (BufStart[0] == '<') {
1619 if (BufEnd[-1] != '>') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001620 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001621 BufStart = 0;
1622 return true;
1623 }
1624 isAngled = true;
1625 } else if (BufStart[0] == '"') {
1626 if (BufEnd[-1] != '"') {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001627 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001628 BufStart = 0;
1629 return true;
1630 }
1631 isAngled = false;
1632 } else {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001633 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001634 BufStart = 0;
1635 return true;
1636 }
1637
1638 // Diagnose #include "" as invalid.
1639 if (BufEnd-BufStart <= 2) {
Chris Lattner93ab9f12007-07-23 04:15:27 +00001640 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001641 BufStart = 0;
1642 return "";
1643 }
1644
1645 // Skip the brackets.
1646 ++BufStart;
1647 --BufEnd;
1648 return isAngled;
1649}
1650
Chris Lattner43eafb42007-07-23 04:56:47 +00001651/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1652/// from a macro as multiple tokens, which need to be glued together. This
1653/// occurs for code like:
1654/// #define FOO <a/b.h>
1655/// #include FOO
1656/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1657///
1658/// This code concatenates and consumes tokens up to the '>' token. It returns
1659/// false if the > was found, otherwise it returns true if it finds and consumes
1660/// the EOM marker.
1661static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1662 Preprocessor &PP) {
1663 Token CurTok;
1664
1665 PP.Lex(CurTok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001666 while (CurTok.isNot(tok::eom)) {
Chris Lattner43eafb42007-07-23 04:56:47 +00001667 // Append the spelling of this token to the buffer. If there was a space
1668 // before it, add it now.
1669 if (CurTok.hasLeadingSpace())
1670 FilenameBuffer.push_back(' ');
1671
1672 // Get the spelling of the token, directly into FilenameBuffer if possible.
1673 unsigned PreAppendSize = FilenameBuffer.size();
1674 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1675
1676 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1677 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1678
1679 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1680 if (BufPtr != &FilenameBuffer[PreAppendSize])
1681 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1682
1683 // Resize FilenameBuffer to the correct size.
1684 if (CurTok.getLength() != ActualLen)
1685 FilenameBuffer.resize(PreAppendSize+ActualLen);
1686
1687 // If we found the '>' marker, return success.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001688 if (CurTok.is(tok::greater))
Chris Lattner43eafb42007-07-23 04:56:47 +00001689 return false;
1690
1691 PP.Lex(CurTok);
1692 }
1693
1694 // If we hit the eom marker, emit an error and return true so that the caller
1695 // knows the EOM has been read.
1696 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1697 return true;
1698}
1699
Chris Lattner22eb9722006-06-18 05:43:12 +00001700/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1701/// file to be included from the lexer, then include it! This is a common
1702/// routine with functionality shared between #include, #include_next and
1703/// #import.
Chris Lattner146762e2007-07-20 16:59:19 +00001704void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Chris Lattner22eb9722006-06-18 05:43:12 +00001705 const DirectoryLookup *LookupFrom,
1706 bool isImport) {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001707
Chris Lattner146762e2007-07-20 16:59:19 +00001708 Token FilenameTok;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001709 CurLexer->LexIncludeFilename(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001710
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001711 // Reserve a buffer to get the spelling.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001712 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner43eafb42007-07-23 04:56:47 +00001713 const char *FilenameStart, *FilenameEnd;
1714
1715 switch (FilenameTok.getKind()) {
1716 case tok::eom:
1717 // If the token kind is EOM, the error has already been diagnosed.
1718 return;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001719
Chris Lattner43eafb42007-07-23 04:56:47 +00001720 case tok::angle_string_literal:
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001721 case tok::string_literal: {
Chris Lattner43eafb42007-07-23 04:56:47 +00001722 FilenameBuffer.resize(FilenameTok.getLength());
1723 FilenameStart = &FilenameBuffer[0];
1724 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1725 FilenameEnd = FilenameStart+Len;
1726 break;
Chris Lattnerf97dbcb2007-07-23 22:23:52 +00001727 }
Chris Lattner43eafb42007-07-23 04:56:47 +00001728
1729 case tok::less:
1730 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1731 // case, glue the tokens together into FilenameBuffer and interpret those.
1732 FilenameBuffer.push_back('<');
1733 if (ConcatenateIncludeName(FilenameBuffer, *this))
1734 return; // Found <eom> but no ">"? Diagnostic already emitted.
1735 FilenameStart = &FilenameBuffer[0];
1736 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1737 break;
1738 default:
1739 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1740 DiscardUntilEndOfDirective();
1741 return;
1742 }
1743
Chris Lattner93ab9f12007-07-23 04:15:27 +00001744 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001745 FilenameStart, FilenameEnd);
1746 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1747 // error.
Chris Lattner43eafb42007-07-23 04:56:47 +00001748 if (FilenameStart == 0) {
1749 DiscardUntilEndOfDirective();
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001750 return;
Chris Lattner43eafb42007-07-23 04:56:47 +00001751 }
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001752
Chris Lattner269c2322006-06-25 06:23:00 +00001753 // Verify that there is nothing after the filename, other than EOM. Use the
1754 // preprocessor to lex this in case lexing the filename entered a macro.
1755 CheckEndOfDirective("#include");
Chris Lattner22eb9722006-06-18 05:43:12 +00001756
1757 // Check that we don't have infinite #include recursion.
Chris Lattner69772b02006-07-02 20:34:39 +00001758 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
Chris Lattner22eb9722006-06-18 05:43:12 +00001759 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1760
Chris Lattner22eb9722006-06-18 05:43:12 +00001761 // Search include directories.
Chris Lattnerc8997182006-06-22 05:52:16 +00001762 const DirectoryLookup *CurDir;
Chris Lattnerc07ba1f2006-10-30 05:58:32 +00001763 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
Chris Lattnerb8b94f12006-10-30 05:38:06 +00001764 isAngled, LookupFrom, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001765 if (File == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001766 return Diag(FilenameTok, diag::err_pp_file_not_found,
1767 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001768
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001769 // Ask HeaderInfo if we should enter this #include file.
1770 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1771 // If it returns true, #including this file will have no effect.
Chris Lattner3665f162006-07-04 07:26:10 +00001772 return;
1773 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001774
1775 // Look up the file, create a File ID for it.
Chris Lattner371ac8a2006-07-04 07:11:10 +00001776 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
Chris Lattner22eb9722006-06-18 05:43:12 +00001777 if (FileID == 0)
Chris Lattner7c718bd2007-04-10 06:02:46 +00001778 return Diag(FilenameTok, diag::err_pp_file_not_found,
1779 std::string(FilenameStart, FilenameEnd));
Chris Lattner22eb9722006-06-18 05:43:12 +00001780
1781 // Finally, if all is good, enter the new file!
Chris Lattnerc8997182006-06-22 05:52:16 +00001782 EnterSourceFile(FileID, CurDir);
Chris Lattner22eb9722006-06-18 05:43:12 +00001783}
1784
1785/// HandleIncludeNextDirective - Implements #include_next.
1786///
Chris Lattner146762e2007-07-20 16:59:19 +00001787void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001788 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001789
1790 // #include_next is like #include, except that we start searching after
1791 // the current found directory. If we can't do this, issue a
1792 // diagnostic.
Chris Lattnerc8997182006-06-22 05:52:16 +00001793 const DirectoryLookup *Lookup = CurDirLookup;
Chris Lattner69772b02006-07-02 20:34:39 +00001794 if (isInPrimaryFile()) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001795 Lookup = 0;
Chris Lattnercb283342006-06-18 06:48:37 +00001796 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Chris Lattner22eb9722006-06-18 05:43:12 +00001797 } else if (Lookup == 0) {
Chris Lattnercb283342006-06-18 06:48:37 +00001798 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
Chris Lattnerc8997182006-06-22 05:52:16 +00001799 } else {
1800 // Start looking up in the next directory.
1801 ++Lookup;
Chris Lattner22eb9722006-06-18 05:43:12 +00001802 }
1803
1804 return HandleIncludeDirective(IncludeNextTok, Lookup);
1805}
1806
1807/// HandleImportDirective - Implements #import.
1808///
Chris Lattner146762e2007-07-20 16:59:19 +00001809void Preprocessor::HandleImportDirective(Token &ImportTok) {
Chris Lattnercb283342006-06-18 06:48:37 +00001810 Diag(ImportTok, diag::ext_pp_import_directive);
Chris Lattner22eb9722006-06-18 05:43:12 +00001811
1812 return HandleIncludeDirective(ImportTok, 0, true);
1813}
1814
Chris Lattnerb8761832006-06-24 21:31:03 +00001815//===----------------------------------------------------------------------===//
1816// Preprocessor Macro Directive Handling.
1817//===----------------------------------------------------------------------===//
1818
Chris Lattnercefc7682006-07-08 08:28:12 +00001819/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1820/// definition has just been read. Lex the rest of the arguments and the
1821/// closing ), updating MI with what we learn. Return true if an error occurs
1822/// parsing the arg list.
1823bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner564f4782007-07-14 22:46:43 +00001824 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1825
Chris Lattner146762e2007-07-20 16:59:19 +00001826 Token Tok;
Chris Lattnercefc7682006-07-08 08:28:12 +00001827 while (1) {
1828 LexUnexpandedToken(Tok);
1829 switch (Tok.getKind()) {
1830 case tok::r_paren:
1831 // Found the end of the argument list.
Chris Lattner564f4782007-07-14 22:46:43 +00001832 if (Arguments.empty()) { // #define FOO()
1833 MI->setArgumentList(Arguments.begin(), Arguments.end());
1834 return false;
1835 }
Chris Lattnercefc7682006-07-08 08:28:12 +00001836 // Otherwise we have #define FOO(A,)
1837 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1838 return true;
1839 case tok::ellipsis: // #define X(... -> C99 varargs
1840 // Warn if use of C99 feature in non-C99 mode.
1841 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1842
1843 // Lex the token after the identifier.
1844 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001845 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001846 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1847 return true;
1848 }
Chris Lattner95a06b32006-07-30 08:40:43 +00001849 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner564f4782007-07-14 22:46:43 +00001850 Arguments.push_back(Ident__VA_ARGS__);
Chris Lattnercefc7682006-07-08 08:28:12 +00001851 MI->setIsC99Varargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001852 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001853 return false;
1854 case tok::eom: // #define X(
1855 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1856 return true;
Chris Lattner62aa0d42006-10-20 05:08:24 +00001857 default:
1858 // Handle keywords and identifiers here to accept things like
1859 // #define Foo(for) for.
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001860 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner62aa0d42006-10-20 05:08:24 +00001861 if (II == 0) {
1862 // #define X(1
1863 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1864 return true;
1865 }
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001866
1867 // If this is already used as an argument, it is used multiple times (e.g.
1868 // #define X(A,A.
Chris Lattner564f4782007-07-14 22:46:43 +00001869 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1870 Arguments.end()) { // C99 6.10.3p6
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001871 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1872 return true;
1873 }
1874
1875 // Add the argument to the macro info.
Chris Lattner564f4782007-07-14 22:46:43 +00001876 Arguments.push_back(II);
Chris Lattnercefc7682006-07-08 08:28:12 +00001877
1878 // Lex the token after the identifier.
1879 LexUnexpandedToken(Tok);
1880
1881 switch (Tok.getKind()) {
1882 default: // #define X(A B
1883 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1884 return true;
1885 case tok::r_paren: // #define X(A)
Chris Lattner564f4782007-07-14 22:46:43 +00001886 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001887 return false;
1888 case tok::comma: // #define X(A,
1889 break;
1890 case tok::ellipsis: // #define X(A... -> GCC extension
1891 // Diagnose extension.
1892 Diag(Tok, diag::ext_named_variadic_macro);
1893
1894 // Lex the token after the identifier.
1895 LexUnexpandedToken(Tok);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001896 if (Tok.isNot(tok::r_paren)) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001897 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1898 return true;
1899 }
1900
1901 MI->setIsGNUVarargs();
Chris Lattner564f4782007-07-14 22:46:43 +00001902 MI->setArgumentList(Arguments.begin(), Arguments.end());
Chris Lattnercefc7682006-07-08 08:28:12 +00001903 return false;
1904 }
1905 }
1906 }
1907}
1908
Chris Lattner22eb9722006-06-18 05:43:12 +00001909/// HandleDefineDirective - Implements #define. This consumes the entire macro
Chris Lattner81278c62006-10-14 19:03:49 +00001910/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1911/// true, then this is a "#define_target", otherwise this is a "#define".
Chris Lattner22eb9722006-06-18 05:43:12 +00001912///
Chris Lattner146762e2007-07-20 16:59:19 +00001913void Preprocessor::HandleDefineDirective(Token &DefineTok,
Chris Lattner81278c62006-10-14 19:03:49 +00001914 bool isTargetSpecific) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001915 ++NumDefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00001916
Chris Lattner146762e2007-07-20 16:59:19 +00001917 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00001918 ReadMacroName(MacroNameTok, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001919
1920 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001921 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00001922 return;
Chris Lattnerf40fe992007-07-14 22:11:41 +00001923
Chris Lattner457fc152006-07-29 06:30:25 +00001924 // If we are supposed to keep comments in #defines, reenable comment saving
1925 // mode.
Chris Lattnerb352e3e2006-11-21 06:17:10 +00001926 CurLexer->KeepCommentMode = KeepMacroComments;
Chris Lattner457fc152006-07-29 06:30:25 +00001927
Chris Lattner063400e2006-10-14 19:54:15 +00001928 // Create the new macro.
Chris Lattner50b497e2006-06-18 16:32:35 +00001929 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
Chris Lattner81278c62006-10-14 19:03:49 +00001930 if (isTargetSpecific) MI->setIsTargetSpecific();
Chris Lattner22eb9722006-06-18 05:43:12 +00001931
Chris Lattner063400e2006-10-14 19:54:15 +00001932 // If the identifier is an 'other target' macro, clear this bit.
1933 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1934
1935
Chris Lattner146762e2007-07-20 16:59:19 +00001936 Token Tok;
Chris Lattnercb283342006-06-18 06:48:37 +00001937 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001938
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001939 // If this is a function-like macro definition, parse the argument list,
1940 // marking each of the identifiers as being used as macro arguments. Also,
1941 // check other constraints on the first token of the macro body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001942 if (Tok.is(tok::eom)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001943 // If there is no body to this macro, we have no special handling here.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001944 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Chris Lattnercefc7682006-07-08 08:28:12 +00001945 // This is a function-like macro definition. Read the argument list.
1946 MI->setIsFunctionLike();
1947 if (ReadMacroDefinitionArgList(MI)) {
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001948 // Forget about MI.
Chris Lattnercefc7682006-07-08 08:28:12 +00001949 delete MI;
Chris Lattner6e0d42c2006-07-08 20:32:52 +00001950 // Throw away the rest of the line.
Chris Lattnercefc7682006-07-08 08:28:12 +00001951 if (CurLexer->ParsingPreprocessorDirective)
1952 DiscardUntilEndOfDirective();
1953 return;
1954 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001955
Chris Lattner815a1f92006-07-08 20:48:04 +00001956 // Read the first token after the arg list for down below.
1957 LexUnexpandedToken(Tok);
Chris Lattner22eb9722006-06-18 05:43:12 +00001958 } else if (!Tok.hasLeadingSpace()) {
1959 // C99 requires whitespace between the macro definition and the body. Emit
1960 // a diagnostic for something like "#define X+".
1961 if (Features.C99) {
Chris Lattnercb283342006-06-18 06:48:37 +00001962 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 } else {
1964 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1965 // one in some cases!
1966 }
1967 } else {
1968 // This is a normal token with leading space. Clear the leading space
1969 // marker on the first token to get proper expansion.
Chris Lattner146762e2007-07-20 16:59:19 +00001970 Tok.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001971 }
1972
Chris Lattner7e374832006-07-29 03:46:57 +00001973 // If this is a definition of a variadic C99 function-like macro, not using
1974 // the GNU named varargs extension, enabled __VA_ARGS__.
1975
1976 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1977 // This gets unpoisoned where it is allowed.
1978 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1979 if (MI->isC99Varargs())
1980 Ident__VA_ARGS__->setIsPoisoned(false);
1981
Chris Lattner22eb9722006-06-18 05:43:12 +00001982 // Read the rest of the macro body.
Chris Lattnera3834342007-07-14 21:54:03 +00001983 if (MI->isObjectLike()) {
1984 // Object-like macros are very simple, just read their body.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001985 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00001986 MI->AddTokenToBody(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001987 // Get the next token of the macro.
1988 LexUnexpandedToken(Tok);
Chris Lattner815a1f92006-07-08 20:48:04 +00001989 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001990
Chris Lattnera3834342007-07-14 21:54:03 +00001991 } else {
1992 // Otherwise, read the body of a function-like macro. This has to validate
1993 // the # (stringize) operator.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001994 while (Tok.isNot(tok::eom)) {
Chris Lattnera3834342007-07-14 21:54:03 +00001995 MI->AddTokenToBody(Tok);
Chris Lattnerbff18d52006-07-06 04:49:18 +00001996
Chris Lattnera3834342007-07-14 21:54:03 +00001997 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1998 // parameters in function-like macro expansions.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001999 if (Tok.isNot(tok::hash)) {
Chris Lattnera3834342007-07-14 21:54:03 +00002000 // Get the next token of the macro.
2001 LexUnexpandedToken(Tok);
2002 continue;
2003 }
2004
2005 // Get the next token of the macro.
2006 LexUnexpandedToken(Tok);
2007
2008 // Not a macro arg identifier?
2009 if (!Tok.getIdentifierInfo() ||
2010 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2011 Diag(Tok, diag::err_pp_stringize_not_parameter);
2012 delete MI;
2013
2014 // Disable __VA_ARGS__ again.
2015 Ident__VA_ARGS__->setIsPoisoned(true);
2016 return;
2017 }
2018
2019 // Things look ok, add the param name token to the macro.
2020 MI->AddTokenToBody(Tok);
2021
2022 // Get the next token of the macro.
2023 LexUnexpandedToken(Tok);
2024 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002025 }
Chris Lattner7e374832006-07-29 03:46:57 +00002026
Chris Lattnerf40fe992007-07-14 22:11:41 +00002027
Chris Lattner7e374832006-07-29 03:46:57 +00002028 // Disable __VA_ARGS__ again.
2029 Ident__VA_ARGS__->setIsPoisoned(true);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002030
Chris Lattnerbff18d52006-07-06 04:49:18 +00002031 // Check that there is no paste (##) operator at the begining or end of the
2032 // replacement list.
Chris Lattner78186052006-07-09 00:45:31 +00002033 unsigned NumTokens = MI->getNumTokens();
Chris Lattnerbff18d52006-07-06 04:49:18 +00002034 if (NumTokens != 0) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002035 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002036 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002037 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002038 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002039 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002040 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Chris Lattner815a1f92006-07-08 20:48:04 +00002041 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerbff18d52006-07-06 04:49:18 +00002042 delete MI;
Chris Lattner815a1f92006-07-08 20:48:04 +00002043 return;
Chris Lattnerbff18d52006-07-06 04:49:18 +00002044 }
2045 }
2046
Chris Lattner13044d92006-07-03 05:16:44 +00002047 // If this is the primary source file, remember that this macro hasn't been
2048 // used yet.
2049 if (isInPrimaryFile())
2050 MI->setIsUsed(false);
2051
Chris Lattner22eb9722006-06-18 05:43:12 +00002052 // Finally, if this identifier already had a macro defined for it, verify that
2053 // the macro bodies are identical and free the old definition.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002054 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner13044d92006-07-03 05:16:44 +00002055 if (!OtherMI->isUsed())
2056 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2057
Chris Lattner22eb9722006-06-18 05:43:12 +00002058 // Macros must be identical. This means all tokes and whitespace separation
Chris Lattner21284df2006-07-08 07:16:08 +00002059 // must be the same. C99 6.10.3.2.
2060 if (!MI->isIdenticalTo(*OtherMI, *this)) {
Chris Lattnere8eef322006-07-08 07:01:00 +00002061 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2062 MacroNameTok.getIdentifierInfo()->getName());
2063 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2064 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002065 delete OtherMI;
2066 }
2067
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002068 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Chris Lattner22eb9722006-06-18 05:43:12 +00002069}
2070
Chris Lattner063400e2006-10-14 19:54:15 +00002071/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattner146762e2007-07-20 16:59:19 +00002072void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2073 Token MacroNameTok;
Chris Lattner063400e2006-10-14 19:54:15 +00002074 ReadMacroName(MacroNameTok, 1);
2075
2076 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002077 if (MacroNameTok.is(tok::eom))
Chris Lattner063400e2006-10-14 19:54:15 +00002078 return;
2079
2080 // Check to see if this is the last token on the #undef line.
2081 CheckEndOfDirective("#define_other_target");
2082
2083 // If there is already a macro defined by this name, turn it into a
2084 // target-specific define.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002085 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner063400e2006-10-14 19:54:15 +00002086 MI->setIsTargetSpecific(true);
2087 return;
2088 }
2089
2090 // Mark the identifier as being a macro on some other target.
2091 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2092}
2093
Chris Lattner22eb9722006-06-18 05:43:12 +00002094
2095/// HandleUndefDirective - Implements #undef.
2096///
Chris Lattner146762e2007-07-20 16:59:19 +00002097void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002098 ++NumUndefined;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002099
Chris Lattner146762e2007-07-20 16:59:19 +00002100 Token MacroNameTok;
Chris Lattnere8eef322006-07-08 07:01:00 +00002101 ReadMacroName(MacroNameTok, 2);
Chris Lattner22eb9722006-06-18 05:43:12 +00002102
2103 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002104 if (MacroNameTok.is(tok::eom))
Chris Lattnercb283342006-06-18 06:48:37 +00002105 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002106
2107 // Check to see if this is the last token on the #undef line.
Chris Lattnercb283342006-06-18 06:48:37 +00002108 CheckEndOfDirective("#undef");
Chris Lattner22eb9722006-06-18 05:43:12 +00002109
2110 // Okay, we finally have a valid identifier to undef.
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002111 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Chris Lattner22eb9722006-06-18 05:43:12 +00002112
Chris Lattner063400e2006-10-14 19:54:15 +00002113 // #undef untaints an identifier if it were marked by define_other_target.
2114 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2115
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 // If the macro is not defined, this is a noop undef, just return.
Chris Lattnercb283342006-06-18 06:48:37 +00002117 if (MI == 0) return;
Chris Lattner677757a2006-06-28 05:26:32 +00002118
Chris Lattner13044d92006-07-03 05:16:44 +00002119 if (!MI->isUsed())
2120 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner22eb9722006-06-18 05:43:12 +00002121
2122 // Free macro definition.
2123 delete MI;
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002124 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002125}
2126
2127
Chris Lattnerb8761832006-06-24 21:31:03 +00002128//===----------------------------------------------------------------------===//
2129// Preprocessor Conditional Directive Handling.
2130//===----------------------------------------------------------------------===//
2131
Chris Lattner22eb9722006-06-18 05:43:12 +00002132/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
Chris Lattner371ac8a2006-07-04 07:11:10 +00002133/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2134/// if any tokens have been returned or pp-directives activated before this
2135/// #ifndef has been lexed.
Chris Lattner22eb9722006-06-18 05:43:12 +00002136///
Chris Lattner146762e2007-07-20 16:59:19 +00002137void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Chris Lattner371ac8a2006-07-04 07:11:10 +00002138 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002139 ++NumIf;
Chris Lattner146762e2007-07-20 16:59:19 +00002140 Token DirectiveTok = Result;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002141
Chris Lattner146762e2007-07-20 16:59:19 +00002142 Token MacroNameTok;
Chris Lattnercb283342006-06-18 06:48:37 +00002143 ReadMacroName(MacroNameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +00002144
2145 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002146 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002147 // Skip code until we get to #endif. This helps with recovery by not
2148 // emitting an error when the #endif is reached.
2149 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2150 /*Foundnonskip*/false, /*FoundElse*/false);
Chris Lattnercb283342006-06-18 06:48:37 +00002151 return;
Chris Lattnerd05e44e2007-09-24 05:14:57 +00002152 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002153
2154 // Check to see if this is the last token on the #if[n]def line.
Chris Lattner371ac8a2006-07-04 07:11:10 +00002155 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2156
2157 // If the start of a top-level #ifdef, inform MIOpt.
2158 if (!ReadAnyTokensBeforeDirective &&
2159 CurLexer->getConditionalStackDepth() == 0) {
2160 assert(isIfndef && "#ifdef shouldn't reach here");
2161 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2162 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002163
Chris Lattner063400e2006-10-14 19:54:15 +00002164 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnerc43ddc82007-10-07 08:44:20 +00002165 MacroInfo *MI = getMacroInfo(MII);
Chris Lattnera78a97e2006-07-03 05:42:18 +00002166
Chris Lattner81278c62006-10-14 19:03:49 +00002167 // If there is a macro, process it.
2168 if (MI) {
2169 // Mark it used.
2170 MI->setIsUsed(true);
2171
2172 // If this is the first use of a target-specific macro, warn about it.
2173 if (MI->isTargetSpecific()) {
2174 MI->setIsTargetSpecific(false); // Don't warn on second use.
2175 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2176 diag::port_target_macro_use);
2177 }
Chris Lattner063400e2006-10-14 19:54:15 +00002178 } else {
2179 // Use of a target-specific macro for some other target? If so, warn.
2180 if (MII->isOtherTargetMacro()) {
2181 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2182 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2183 diag::port_target_macro_use);
2184 }
Chris Lattner81278c62006-10-14 19:03:49 +00002185 }
Chris Lattnera78a97e2006-07-03 05:42:18 +00002186
Chris Lattner22eb9722006-06-18 05:43:12 +00002187 // Should we include the stuff contained by this directive?
Chris Lattnera78a97e2006-07-03 05:42:18 +00002188 if (!MI == isIfndef) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002189 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002190 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002191 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002192 } else {
2193 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002194 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Chris Lattnercb283342006-06-18 06:48:37 +00002195 /*Foundnonskip*/false,
2196 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002197 }
2198}
2199
2200/// HandleIfDirective - Implements the #if directive.
2201///
Chris Lattner146762e2007-07-20 16:59:19 +00002202void Preprocessor::HandleIfDirective(Token &IfToken,
Chris Lattnera8654ca2006-07-04 17:42:08 +00002203 bool ReadAnyTokensBeforeDirective) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002204 ++NumIf;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002205
Chris Lattner371ac8a2006-07-04 07:11:10 +00002206 // Parse and evaluation the conditional expression.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +00002207 IdentifierInfo *IfNDefMacro = 0;
Chris Lattnera8654ca2006-07-04 17:42:08 +00002208 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
Chris Lattner22eb9722006-06-18 05:43:12 +00002209
2210 // Should we include the stuff contained by this directive?
2211 if (ConditionalTrue) {
Chris Lattnera8654ca2006-07-04 17:42:08 +00002212 // If this condition is equivalent to #ifndef X, and if this is the first
2213 // directive seen, handle it for the multiple-include optimization.
2214 if (!ReadAnyTokensBeforeDirective &&
2215 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2216 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2217
Chris Lattner22eb9722006-06-18 05:43:12 +00002218 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner50b497e2006-06-18 16:32:35 +00002219 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattner22eb9722006-06-18 05:43:12 +00002220 /*foundnonskip*/true, /*foundelse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002221 } else {
2222 // No, skip the contents of this block and return the first token after it.
Chris Lattner50b497e2006-06-18 16:32:35 +00002223 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnercb283342006-06-18 06:48:37 +00002224 /*FoundElse*/false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002225 }
2226}
2227
2228/// HandleEndifDirective - Implements the #endif directive.
2229///
Chris Lattner146762e2007-07-20 16:59:19 +00002230void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002231 ++NumEndif;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002232
Chris Lattner22eb9722006-06-18 05:43:12 +00002233 // Check that this is the whole directive.
Chris Lattnercb283342006-06-18 06:48:37 +00002234 CheckEndOfDirective("#endif");
Chris Lattner22eb9722006-06-18 05:43:12 +00002235
2236 PPConditionalInfo CondInfo;
2237 if (CurLexer->popConditionalLevel(CondInfo)) {
2238 // No conditionals on the stack: this is an #endif without an #if.
2239 return Diag(EndifToken, diag::err_pp_endif_without_if);
2240 }
2241
Chris Lattner371ac8a2006-07-04 07:11:10 +00002242 // If this the end of a top-level #endif, inform MIOpt.
2243 if (CurLexer->getConditionalStackDepth() == 0)
2244 CurLexer->MIOpt.ExitTopLevelConditional();
2245
Chris Lattner538d7f32006-07-20 04:31:52 +00002246 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 "This code should only be reachable in the non-skipping case!");
Chris Lattner22eb9722006-06-18 05:43:12 +00002248}
2249
2250
Chris Lattner146762e2007-07-20 16:59:19 +00002251void Preprocessor::HandleElseDirective(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002252 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002253
Chris Lattner22eb9722006-06-18 05:43:12 +00002254 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnercb283342006-06-18 06:48:37 +00002255 CheckEndOfDirective("#else");
Chris Lattner22eb9722006-06-18 05:43:12 +00002256
2257 PPConditionalInfo CI;
2258 if (CurLexer->popConditionalLevel(CI))
2259 return Diag(Result, diag::pp_err_else_without_if);
Chris Lattner371ac8a2006-07-04 07:11:10 +00002260
2261 // If this is a top-level #else, inform the MIOpt.
2262 if (CurLexer->getConditionalStackDepth() == 0)
2263 CurLexer->MIOpt.FoundTopLevelElse();
Chris Lattner22eb9722006-06-18 05:43:12 +00002264
2265 // If this is a #else with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002266 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002267
2268 // Finally, skip the rest of the contents of this block and return the first
2269 // token after it.
2270 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2271 /*FoundElse*/true);
2272}
2273
Chris Lattner146762e2007-07-20 16:59:19 +00002274void Preprocessor::HandleElifDirective(Token &ElifToken) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002275 ++NumElse;
Chris Lattner371ac8a2006-07-04 07:11:10 +00002276
Chris Lattner22eb9722006-06-18 05:43:12 +00002277 // #elif directive in a non-skipping conditional... start skipping.
2278 // We don't care what the condition is, because we will always skip it (since
2279 // the block immediately before it was included).
Chris Lattnercb283342006-06-18 06:48:37 +00002280 DiscardUntilEndOfDirective();
Chris Lattner22eb9722006-06-18 05:43:12 +00002281
2282 PPConditionalInfo CI;
2283 if (CurLexer->popConditionalLevel(CI))
2284 return Diag(ElifToken, diag::pp_err_elif_without_if);
2285
Chris Lattner371ac8a2006-07-04 07:11:10 +00002286 // If this is a top-level #elif, inform the MIOpt.
2287 if (CurLexer->getConditionalStackDepth() == 0)
2288 CurLexer->MIOpt.FoundTopLevelElse();
2289
Chris Lattner22eb9722006-06-18 05:43:12 +00002290 // If this is a #elif with a #else before it, report the error.
Chris Lattnercb283342006-06-18 06:48:37 +00002291 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Chris Lattner22eb9722006-06-18 05:43:12 +00002292
2293 // Finally, skip the rest of the contents of this block and return the first
2294 // token after it.
2295 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2296 /*FoundElse*/CI.FoundElse);
2297}
Chris Lattnerb8761832006-06-24 21:31:03 +00002298