blob: 40fd3225501f9c70a7bb4b764b132a0cf4afcc9f [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
16// -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//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/MacroInfo.h"
31#include "clang/Lex/PPCallbacks.h"
32#include "clang/Lex/Pragma.h"
33#include "clang/Lex/ScratchBuffer.h"
34#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "llvm/ADT/SmallVector.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000039#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekbdd30c22008-01-14 16:44:48 +000040#include "llvm/Support/Streams.h"
Chris Lattner77034d32007-09-03 18:30:32 +000041#include <ctime>
Reid Spencer5f016e22007-07-11 17:01:13 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
45
46Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
47 TargetInfo &target, SourceManager &SM,
48 HeaderSearch &Headers)
49 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
51 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
52 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattner9594acf2007-07-15 00:25:26 +000053
Reid Spencer5f016e22007-07-11 17:01:13 +000054 // Clear stats.
55 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
56 NumIf = NumElse = NumEndif = 0;
57 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
59 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
60 MaxIncludeStackDepth = 0;
61 NumSkipped = 0;
62
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
67 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
69 InMacroArgs = false;
Chris Lattner9594acf2007-07-15 00:25:26 +000070 NumCachedMacroExpanders = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000071
72 // "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 Lattner53b0dab2007-10-09 22:10:18 +000076 Predefines = 0;
77
Reid Spencer5f016e22007-07-11 17:01:13 +000078 // Initialize the pragma handlers.
79 PragmaHandlers = new PragmaNamespace(0);
80 RegisterBuiltinPragmas();
81
82 // Initialize builtin macros like __LINE__ and friends.
83 RegisterBuiltinMacros();
84}
85
86Preprocessor::~Preprocessor() {
87 // Free any active lexers.
88 delete CurLexer;
89
90 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
92 delete IncludeMacroStack.back().TheMacroExpander;
93 IncludeMacroStack.pop_back();
94 }
Chris Lattnercc1a8752007-10-07 08:44:20 +000095
96 // Free any macro definitions.
97 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
98 Macros.begin(), E = Macros.end(); I != E; ++I) {
99 // Free the macro definition.
100 delete I->second;
101 I->second = 0;
102 I->first->setHasMacroDefinition(false);
103 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000104
Chris Lattner9594acf2007-07-15 00:25:26 +0000105 // Free any cached macro expanders.
106 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
107 delete MacroExpanderCache[i];
108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 // Release pragma information.
110 delete PragmaHandlers;
111
112 // Delete the scratch buffer info.
113 delete ScratchBuf;
114}
115
116PPCallbacks::~PPCallbacks() {
117}
118
119/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattnerd2177732007-07-20 16:59:19 +0000120/// the specified Token's location, translating the token's start
Reid Spencer5f016e22007-07-11 17:01:13 +0000121/// position in the current buffer into a SourcePosition object for rendering.
122void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000123 Diags.Report(getFullLoc(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000124}
125
126void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
127 const std::string &Msg) {
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000128 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
Chris Lattnerd2177732007-07-20 16:59:19 +0000131void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000132 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
133 << getSpelling(Tok) << "'";
Reid Spencer5f016e22007-07-11 17:01:13 +0000134
135 if (!DumpFlags) return;
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000136
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000137 llvm::cerr << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 if (Tok.isAtStartOfLine())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000139 llvm::cerr << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 if (Tok.hasLeadingSpace())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000141 llvm::cerr << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 if (Tok.isExpandDisabled())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000143 llvm::cerr << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 if (Tok.needsCleaning()) {
145 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000146 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
147 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 }
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000149
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000150 llvm::cerr << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000151 DumpLocation(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000152 llvm::cerr << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000153}
154
155void Preprocessor::DumpLocation(SourceLocation Loc) const {
156 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000157 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
158 << SourceMgr.getLineNumber(LogLoc) << ':'
159 << SourceMgr.getLineNumber(LogLoc);
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000160
161 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
162 if (PhysLoc != LogLoc) {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000163 llvm::cerr << " <PhysLoc=";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000164 DumpLocation(PhysLoc);
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000165 llvm::cerr << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000166 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000167}
168
169void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000170 llvm::cerr << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
172 DumpToken(MI.getReplacementToken(i));
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000173 llvm::cerr << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 }
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000175 llvm::cerr << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
178void Preprocessor::PrintStats() {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000179 llvm::cerr << "\n*** Preprocessor Stats:\n";
180 llvm::cerr << NumDirectives << " directives found:\n";
181 llvm::cerr << " " << NumDefined << " #define.\n";
182 llvm::cerr << " " << NumUndefined << " #undef.\n";
183 llvm::cerr << " #include/#include_next/#import:\n";
184 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
185 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
186 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
187 llvm::cerr << " " << NumElse << " #else/#elif.\n";
188 llvm::cerr << " " << NumEndif << " #endif.\n";
189 llvm::cerr << " " << NumPragma << " #pragma.\n";
190 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000191
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000192 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
193 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
194 << NumFastMacroExpanded << " on the fast path.\n";
195 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
196 << " token paste (##) operations performed, "
197 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000198}
199
200//===----------------------------------------------------------------------===//
201// Token Spelling
202//===----------------------------------------------------------------------===//
203
204
205/// getSpelling() - Return the 'spelling' of this token. The spelling of a
206/// token are the characters used to represent the token in the source file
207/// after trigraph expansion and escaped-newline folding. In particular, this
208/// wants to get the true, uncanonicalized, spelling of things like digraphs
209/// UCNs, etc.
Chris Lattnerd2177732007-07-20 16:59:19 +0000210std::string Preprocessor::getSpelling(const Token &Tok) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
212
213 // If this token contains nothing interesting, return it directly.
214 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
215 if (!Tok.needsCleaning())
216 return std::string(TokStart, TokStart+Tok.getLength());
217
218 std::string Result;
219 Result.reserve(Tok.getLength());
220
221 // Otherwise, hard case, relex the characters into the string.
222 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
223 Ptr != End; ) {
224 unsigned CharSize;
225 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
226 Ptr += CharSize;
227 }
228 assert(Result.size() != unsigned(Tok.getLength()) &&
229 "NeedsCleaning flag set on something that didn't need cleaning!");
230 return Result;
231}
232
233/// getSpelling - This method is used to get the spelling of a token into a
234/// preallocated buffer, instead of as an std::string. The caller is required
235/// to allocate enough space for the token, which is guaranteed to be at least
236/// Tok.getLength() bytes long. The actual length of the token is returned.
237///
238/// Note that this method may do two possible things: it may either fill in
239/// the buffer specified with characters, or it may *change the input pointer*
240/// to point to a constant buffer with the data already in it (avoiding a
241/// copy). The caller is not allowed to modify the returned buffer pointer
242/// if an internal buffer is returned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000243unsigned Preprocessor::getSpelling(const Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 const char *&Buffer) const {
245 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
246
247 // If this token is an identifier, just return the string from the identifier
248 // table, which is very quick.
249 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
250 Buffer = II->getName();
Chris Lattner0f670322007-07-22 22:50:09 +0000251
252 // Return the length of the token. If the token needed cleaning, don't
253 // include the size of the newlines or trigraphs in it.
254 if (!Tok.needsCleaning())
255 return Tok.getLength();
256 else
257 return strlen(Buffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 }
259
260 // Otherwise, compute the start of the token in the input lexer buffer.
261 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
262
263 // If this token contains nothing interesting, return it directly.
264 if (!Tok.needsCleaning()) {
265 Buffer = TokStart;
266 return Tok.getLength();
267 }
268 // Otherwise, hard case, relex the characters into the string.
269 char *OutBuf = const_cast<char*>(Buffer);
270 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
271 Ptr != End; ) {
272 unsigned CharSize;
273 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
274 Ptr += CharSize;
275 }
276 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
277 "NeedsCleaning flag set on something that didn't need cleaning!");
278
279 return OutBuf-Buffer;
280}
281
282
283/// CreateString - Plop the specified string into a scratch buffer and return a
284/// location for it. If specified, the source location provides a source
285/// location for the token.
286SourceLocation Preprocessor::
287CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
288 if (SLoc.isValid())
289 return ScratchBuf->getToken(Buf, Len, SLoc);
290 return ScratchBuf->getToken(Buf, Len);
291}
292
293
Chris Lattner97ba77c2007-07-16 06:48:38 +0000294/// AdvanceToTokenCharacter - Given a location that specifies the start of a
295/// token, return a new location that specifies a character within the token.
296SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
297 unsigned CharNo) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000298 // If they request the first char of the token, we're trivially done. If this
299 // is a macro expansion, it doesn't make sense to point to a character within
300 // the instantiation point (the name). We could point to the source
301 // character, but without also pointing to instantiation info, this is
302 // confusing.
303 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000304
305 // Figure out how many physical characters away the specified logical
306 // character is. This needs to take into consideration newlines and
307 // trigraphs.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000308 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
309 unsigned PhysOffset = 0;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000310
311 // The usual case is that tokens don't contain anything interesting. Skip
312 // over the uninteresting characters. If a token only consists of simple
313 // chars, this method is extremely fast.
314 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattner9dc1f532007-07-20 16:37:10 +0000315 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000316
317 // If we have a character that may be a trigraph or escaped newline, create a
318 // lexer to parse it correctly.
Chris Lattner97ba77c2007-07-16 06:48:38 +0000319 if (CharNo != 0) {
320 // Create a lexer starting at this token position.
Chris Lattner25bdb512007-07-20 16:52:03 +0000321 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattnerd2177732007-07-20 16:59:19 +0000322 Token Tok;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000323 // Skip over characters the remaining characters.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000324 const char *TokStartPtr = TokPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000325 for (; CharNo; --CharNo)
326 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattner9dc1f532007-07-20 16:37:10 +0000327
328 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000329 }
Chris Lattner9dc1f532007-07-20 16:37:10 +0000330
331 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner97ba77c2007-07-16 06:48:38 +0000332}
333
334
Chris Lattner53b0dab2007-10-09 22:10:18 +0000335//===----------------------------------------------------------------------===//
336// Preprocessor Initialization Methods
337//===----------------------------------------------------------------------===//
338
339// Append a #define line to Buf for Macro. Macro should be of the form XXX,
340// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
341// "#define XXX Y z W". To get a #define with no value, use "XXX=".
342static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
343 const char *Command = "#define ") {
344 Buf.insert(Buf.end(), Command, Command+strlen(Command));
345 if (const char *Equal = strchr(Macro, '=')) {
346 // Turn the = into ' '.
347 Buf.insert(Buf.end(), Macro, Equal);
348 Buf.push_back(' ');
349 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
350 } else {
351 // Push "macroname 1".
352 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
353 Buf.push_back(' ');
354 Buf.push_back('1');
355 }
356 Buf.push_back('\n');
357}
358
359
360static void InitializePredefinedMacros(Preprocessor &PP,
361 std::vector<char> &Buf) {
362 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
363 // and __DATE__ etc.
364#if 0
365 /* __STDC__ has the value 1 under normal circumstances.
366 However, if (a) we are in a system header, (b) the option
367 stdc_0_in_system_headers is true (set by target config), and
368 (c) we are not in strictly conforming mode, then it has the
369 value 0. (b) and (c) are already checked in cpp_init_builtins. */
370 //case BT_STDC:
371 if (cpp_in_system_header (pfile))
372 number = 0;
373 else
374 number = 1;
375 break;
376#endif
377 // These should all be defined in the preprocessor according to the
378 // current language configuration.
379 DefineBuiltinMacro(Buf, "__STDC__=1");
380 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
381 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
382 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
383 else if (0) // STDC94 ?
384 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
385
386 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
387 if (PP.getLangOptions().ObjC1)
388 DefineBuiltinMacro(Buf, "__OBJC__=1");
389 if (PP.getLangOptions().ObjC2)
390 DefineBuiltinMacro(Buf, "__OBJC2__=1");
Steve Naroff8ee529b2007-10-31 18:42:27 +0000391
Chris Lattnerd19144b2007-10-10 17:48:53 +0000392 // Add __builtin_va_list typedef.
393 {
394 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
395 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
396 Buf.push_back('\n');
397 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000398
399 // Get the target #defines.
400 PP.getTargetInfo().getTargetDefines(Buf);
401
402 // Compiler set macros.
403 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
Steve Naroff39d0a272007-11-10 18:06:36 +0000404 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1050");
Chris Lattner53b0dab2007-10-09 22:10:18 +0000405 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
406 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
407 DefineBuiltinMacro(Buf, "__GNUC__=4");
408 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
409 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
410 "build 5250)\"");
411
412 // Build configuration options.
413 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
414 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
415 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
416 DefineBuiltinMacro(Buf, "__PIC__=1");
417
418
419 if (PP.getLangOptions().CPlusPlus) {
420 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
421 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
422 DefineBuiltinMacro(Buf, "__GNUG__=4");
423 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
424 DefineBuiltinMacro(Buf, "__cplusplus=1");
425 DefineBuiltinMacro(Buf, "__private_extern__=extern");
426 }
Steve Naroffd62701b2008-02-07 03:50:06 +0000427 if (PP.getLangOptions().Microsoft) {
428 DefineBuiltinMacro(Buf, "__stdcall=");
429 DefineBuiltinMacro(Buf, "__cdecl=");
430 DefineBuiltinMacro(Buf, "_cdecl=");
431 DefineBuiltinMacro(Buf, "__ptr64=");
432 DefineBuiltinMacro(Buf, "__forceinline=");
433 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000434 // FIXME: Should emit a #line directive here.
435}
436
437
438/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000439/// which implicitly adds the builtin defines etc.
Ted Kremenek95041a22007-12-19 22:51:13 +0000440void Preprocessor::EnterMainSourceFile() {
441
442 unsigned MainFileID = SourceMgr.getMainFileID();
443
Chris Lattner53b0dab2007-10-09 22:10:18 +0000444 // Enter the main file source buffer.
445 EnterSourceFile(MainFileID, 0);
446
Chris Lattnerb2832982007-11-15 19:07:47 +0000447 // Tell the header info that the main file was entered. If the file is later
448 // #imported, it won't be re-entered.
449 if (const FileEntry *FE =
450 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
451 HeaderInfo.IncrementIncludeCount(FE);
452
Chris Lattner53b0dab2007-10-09 22:10:18 +0000453 std::vector<char> PrologFile;
454 PrologFile.reserve(4080);
455
456 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
457 InitializePredefinedMacros(*this, PrologFile);
458
459 // Add on the predefines from the driver.
460 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
461
462 // Memory buffer must end with a null byte!
463 PrologFile.push_back(0);
464
465 // Now that we have emitted the predefined macros, #includes, etc into
466 // PrologFile, preprocess it to populate the initial preprocessor state.
467 llvm::MemoryBuffer *SB =
468 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
469 "<predefines>");
470 assert(SB && "Cannot fail to create predefined source buffer");
471 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
472 assert(FileID && "Could not create FileID for predefines?");
473
474 // Start parsing the predefines.
475 EnterSourceFile(FileID, 0);
476}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000477
Reid Spencer5f016e22007-07-11 17:01:13 +0000478//===----------------------------------------------------------------------===//
479// Source File Location Methods.
480//===----------------------------------------------------------------------===//
481
482/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
483/// return null on failure. isAngled indicates whether the file reference is
484/// for system #include's or not (i.e. using <> instead of "").
485const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
486 const char *FilenameEnd,
487 bool isAngled,
488 const DirectoryLookup *FromDir,
489 const DirectoryLookup *&CurDir) {
490 // If the header lookup mechanism may be relative to the current file, pass in
491 // info about where the current file is.
492 const FileEntry *CurFileEnt = 0;
493 if (!FromDir) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000494 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
495 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 }
497
498 // Do a standard file entry lookup.
499 CurDir = CurDirLookup;
500 const FileEntry *FE =
501 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
502 isAngled, FromDir, CurDir, CurFileEnt);
503 if (FE) return FE;
504
505 // Otherwise, see if this is a subframework header. If so, this is relative
506 // to one of the headers on the #include stack. Walk the list of the current
507 // headers on the #include stack and pass them to HeaderInfo.
508 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000509 if ((CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc())))
510 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
511 CurFileEnt)))
512 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 }
514
515 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
516 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
517 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000518 if ((CurFileEnt =
519 SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc())))
520 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
521 FilenameEnd, CurFileEnt)))
522 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 }
524 }
525
526 // Otherwise, we really couldn't find the file.
527 return 0;
528}
529
530/// isInPrimaryFile - Return true if we're in the top-level file, not in a
531/// #include.
532bool Preprocessor::isInPrimaryFile() const {
533 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000534 return IncludeMacroStack.empty();
Reid Spencer5f016e22007-07-11 17:01:13 +0000535
536 // If there are any stacked lexers, we're in a #include.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000537 assert(IncludeMacroStack[0].TheLexer &&
538 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
539 "Top level include stack isn't our primary lexer?");
540 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Reid Spencer5f016e22007-07-11 17:01:13 +0000541 if (IncludeMacroStack[i].TheLexer &&
542 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000543 return false;
544 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000545}
546
547/// getCurrentLexer - Return the current file lexer being lexed from. Note
548/// that this ignores any potentially active macro expansions and _Pragma
549/// expansions going on at the time.
550Lexer *Preprocessor::getCurrentFileLexer() const {
551 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
552
553 // Look for a stacked lexer.
554 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
555 Lexer *L = IncludeMacroStack[i-1].TheLexer;
556 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
557 return L;
558 }
559 return 0;
560}
561
562
563/// EnterSourceFile - Add a source file to the top of the include stack and
564/// start lexing tokens from it instead of the current buffer. Return true
565/// on failure.
566void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000567 const DirectoryLookup *CurDir) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
569 ++NumEnteredSourceFiles;
570
571 if (MaxIncludeStackDepth < IncludeMacroStack.size())
572 MaxIncludeStackDepth = IncludeMacroStack.size();
573
Chris Lattner25bdb512007-07-20 16:52:03 +0000574 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 EnterSourceFileWithLexer(TheLexer, CurDir);
576}
577
578/// EnterSourceFile - Add a source file to the top of the include stack and
579/// start lexing tokens from it instead of the current buffer.
580void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
581 const DirectoryLookup *CurDir) {
582
583 // Add the current lexer to the include stack.
584 if (CurLexer || CurMacroExpander)
585 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
586 CurMacroExpander));
587
588 CurLexer = TheLexer;
589 CurDirLookup = CurDir;
590 CurMacroExpander = 0;
591
592 // Notify the client, if desired, that we are in a new source file.
593 if (Callbacks && !CurLexer->Is_PragmaLexer) {
594 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
595
596 // Get the file entry for the current file.
597 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +0000598 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 FileType = HeaderInfo.getFileDirFlavor(FE);
600
Chris Lattner9dc1f532007-07-20 16:37:10 +0000601 Callbacks->FileChanged(CurLexer->getFileLoc(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 PPCallbacks::EnterFile, FileType);
603 }
604}
605
606
607
608/// EnterMacro - Add a Macro to the top of the include stack and start lexing
609/// tokens from it instead of the current buffer.
Chris Lattnerd2177732007-07-20 16:59:19 +0000610void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
612 CurMacroExpander));
613 CurLexer = 0;
614 CurDirLookup = 0;
615
Chris Lattner9594acf2007-07-15 00:25:26 +0000616 if (NumCachedMacroExpanders == 0) {
617 CurMacroExpander = new MacroExpander(Tok, Args, *this);
618 } else {
619 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
620 CurMacroExpander->Init(Tok, Args);
621 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000622}
623
624/// EnterTokenStream - Add a "macro" context to the top of the include stack,
625/// which will cause the lexer to start returning the specified tokens. Note
626/// that these tokens will be re-macro-expanded when/if expansion is enabled.
627/// This method assumes that the specified stream of tokens has a permanent
628/// owner somewhere, so they do not need to be copied.
Chris Lattnerd2177732007-07-20 16:59:19 +0000629void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 // Save our current state.
631 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
632 CurMacroExpander));
633 CurLexer = 0;
634 CurDirLookup = 0;
635
636 // Create a macro expander to expand from the specified token stream.
Chris Lattner9594acf2007-07-15 00:25:26 +0000637 if (NumCachedMacroExpanders == 0) {
638 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
639 } else {
640 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
641 CurMacroExpander->Init(Toks, NumToks);
642 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000643}
644
645/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
646/// lexer stack. This should only be used in situations where the current
647/// state of the top-of-stack lexer is known.
648void Preprocessor::RemoveTopOfLexerStack() {
649 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattner9594acf2007-07-15 00:25:26 +0000650
651 if (CurMacroExpander) {
652 // Delete or cache the now-dead macro expander.
653 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
654 delete CurMacroExpander;
655 else
656 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
657 } else {
658 delete CurLexer;
659 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 CurLexer = IncludeMacroStack.back().TheLexer;
661 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
662 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
663 IncludeMacroStack.pop_back();
664}
665
666//===----------------------------------------------------------------------===//
667// Macro Expansion Handling.
668//===----------------------------------------------------------------------===//
669
Chris Lattnercc1a8752007-10-07 08:44:20 +0000670/// setMacroInfo - Specify a macro for this identifier.
671///
672void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
673 if (MI == 0) {
674 if (II->hasMacroDefinition()) {
675 Macros.erase(II);
676 II->setHasMacroDefinition(false);
677 }
678 } else {
679 Macros[II] = MI;
680 II->setHasMacroDefinition(true);
681 }
682}
683
Reid Spencer5f016e22007-07-11 17:01:13 +0000684/// RegisterBuiltinMacro - Register the specified identifier in the identifier
685/// table and mark it as a builtin macro to be expanded.
686IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
687 // Get the identifier.
688 IdentifierInfo *Id = getIdentifierInfo(Name);
689
690 // Mark it as being a macro that is builtin.
691 MacroInfo *MI = new MacroInfo(SourceLocation());
692 MI->setIsBuiltinMacro();
Chris Lattnercc1a8752007-10-07 08:44:20 +0000693 setMacroInfo(Id, MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 return Id;
695}
696
697
698/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
699/// identifier table.
700void Preprocessor::RegisterBuiltinMacros() {
701 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
702 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
703 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
704 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
705 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
706
707 // GCC Extensions.
708 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
709 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
710 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
711}
712
713/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
714/// in its expansion, currently expands to that token literally.
715static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnercc1a8752007-10-07 08:44:20 +0000716 const IdentifierInfo *MacroIdent,
717 Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
719
720 // If the token isn't an identifier, it's always literally expanded.
721 if (II == 0) return true;
722
723 // If the identifier is a macro, and if that macro is enabled, it may be
724 // expanded so it's not a trivial expansion.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000725 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // Fast expanding "#define X X" is ok, because X would be disabled.
727 II != MacroIdent)
728 return false;
729
730 // If this is an object-like macro invocation, it is safe to trivially expand
731 // it.
732 if (MI->isObjectLike()) return true;
733
734 // If this is a function-like macro invocation, it's safe to trivially expand
735 // as long as the identifier is not a macro argument.
736 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
737 I != E; ++I)
738 if (*I == II)
739 return false; // Identifier is a macro argument.
740
741 return true;
742}
743
744
745/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
746/// lexed is a '('. If so, consume the token and return true, if not, this
747/// method should have no observable side-effect on the lexed tokens.
748bool Preprocessor::isNextPPTokenLParen() {
749 // Do some quick tests for rejection cases.
750 unsigned Val;
751 if (CurLexer)
752 Val = CurLexer->isNextPPTokenLParen();
753 else
754 Val = CurMacroExpander->isNextTokenLParen();
755
756 if (Val == 2) {
Chris Lattner0ea793e2007-07-19 00:07:36 +0000757 // We have run off the end. If it's a source file we don't
758 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
759 // macro stack.
760 if (CurLexer)
761 return false;
762 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
764 if (Entry.TheLexer)
765 Val = Entry.TheLexer->isNextPPTokenLParen();
766 else
767 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner0ea793e2007-07-19 00:07:36 +0000768
769 if (Val != 2)
770 break;
771
772 // Ran off the end of a source file?
773 if (Entry.TheLexer)
774 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 }
776 }
777
778 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
779 // have found something that isn't a '(' or we found the end of the
780 // translation unit. In either case, return false.
781 if (Val != 1)
782 return false;
783
Chris Lattnerd2177732007-07-20 16:59:19 +0000784 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000786 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 return true;
788}
789
790/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
791/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000792bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 MacroInfo *MI) {
Chris Lattner4d730462008-01-07 19:50:27 +0000794 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
795 // then the macro could expand to different things in other contexts, we need
796 // to disable the optimization in this case.
797 if (CurLexer) CurLexer->MIOpt.ExpandedMacro();
Reid Spencer5f016e22007-07-11 17:01:13 +0000798
799 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
800 if (MI->isBuiltinMacro()) {
801 ExpandBuiltinMacro(Identifier);
802 return false;
803 }
804
805 // If this is the first use of a target-specific macro, warn about it.
806 if (MI->isTargetSpecific()) {
807 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000808 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 diag::port_target_macro_use);
810 }
811
812 /// Args - If this is a function-like macro expansion, this contains,
813 /// for each macro argument, the list of tokens that were provided to the
814 /// invocation.
815 MacroArgs *Args = 0;
816
817 // If this is a function-like macro, read the arguments.
818 if (MI->isFunctionLike()) {
819 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000820 // name isn't a '(', this macro should not be expanded. Otherwise, consume
821 // it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 if (!isNextPPTokenLParen())
823 return true;
824
825 // Remember that we are now parsing the arguments to a macro invocation.
826 // Preprocessor directives used inside macro arguments are not portable, and
827 // this enables the warning.
828 InMacroArgs = true;
829 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
830
831 // Finished parsing args.
832 InMacroArgs = false;
833
834 // If there was an error parsing the arguments, bail out.
835 if (Args == 0) return false;
836
837 ++NumFnMacroExpanded;
838 } else {
839 ++NumMacroExpanded;
840 }
841
842 // Notice that this macro has been used.
843 MI->setIsUsed(true);
844
845 // If we started lexing a macro, enter the macro expansion body.
846
847 // If this macro expands to no tokens, don't bother to push it onto the
848 // expansion stack, only to take it right back off.
849 if (MI->getNumTokens() == 0) {
850 // No need for arg info.
851 if (Args) Args->destroy();
852
853 // Ignore this macro use, just return the next token in the current
854 // buffer.
855 bool HadLeadingSpace = Identifier.hasLeadingSpace();
856 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
857
858 Lex(Identifier);
859
860 // If the identifier isn't on some OTHER line, inherit the leading
861 // whitespace/first-on-a-line property of this token. This handles
862 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
863 // empty.
864 if (!Identifier.isAtStartOfLine()) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000865 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
866 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 }
868 ++NumFastMacroExpanded;
869 return false;
870
871 } else if (MI->getNumTokens() == 1 &&
Chris Lattnercc1a8752007-10-07 08:44:20 +0000872 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
873 *this)){
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 // Otherwise, if this macro expands into a single trivially-expanded
875 // token: expand it now. This handles common cases like
876 // "#define VAL 42".
877
878 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
879 // identifier to the expanded token.
880 bool isAtStartOfLine = Identifier.isAtStartOfLine();
881 bool hasLeadingSpace = Identifier.hasLeadingSpace();
882
883 // Remember where the token is instantiated.
884 SourceLocation InstantiateLoc = Identifier.getLocation();
885
886 // Replace the result token.
887 Identifier = MI->getReplacementToken(0);
888
889 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattnerd2177732007-07-20 16:59:19 +0000890 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
891 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893 // Update the tokens location to include both its logical and physical
894 // locations.
895 SourceLocation Loc =
896 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
897 Identifier.setLocation(Loc);
898
899 // If this is #define X X, we must mark the result as unexpandible.
900 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnercc1a8752007-10-07 08:44:20 +0000901 if (getMacroInfo(NewII) == MI)
Chris Lattnerd2177732007-07-20 16:59:19 +0000902 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000903
904 // Since this is not an identifier token, it can't be macro expanded, so
905 // we're done.
906 ++NumFastMacroExpanded;
907 return false;
908 }
909
910 // Start expanding the macro.
911 EnterMacro(Identifier, Args);
912
913 // Now that the macro is at the top of the include stack, ask the
914 // preprocessor to read the next token from it.
915 Lex(Identifier);
916 return false;
917}
918
919/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
920/// invoked to read all of the actual arguments specified for the macro
921/// invocation. This returns null on error.
Chris Lattnerd2177732007-07-20 16:59:19 +0000922MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 MacroInfo *MI) {
924 // The number of fixed arguments to parse.
925 unsigned NumFixedArgsLeft = MI->getNumArgs();
926 bool isVariadic = MI->isVariadic();
927
928 // Outer loop, while there are more arguments, keep reading them.
Chris Lattnerd2177732007-07-20 16:59:19 +0000929 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 Tok.setKind(tok::comma);
931 --NumFixedArgsLeft; // Start reading the first arg.
932
933 // ArgTokens - Build up a list of tokens that make up each argument. Each
934 // argument is separated by an EOF token. Use a SmallVector so we can avoid
935 // heap allocations in the common case.
Chris Lattnerd2177732007-07-20 16:59:19 +0000936 llvm::SmallVector<Token, 64> ArgTokens;
Reid Spencer5f016e22007-07-11 17:01:13 +0000937
938 unsigned NumActuals = 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000939 while (Tok.is(tok::comma)) {
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000940 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
941 // that we already consumed the first one.
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 unsigned NumParens = 0;
943
944 while (1) {
945 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
946 // an argument value in a macro could expand to ',' or '(' or ')'.
947 LexUnexpandedToken(Tok);
948
Chris Lattnerc21d9e42008-01-22 19:34:51 +0000949 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 Diag(MacroName, diag::err_unterm_macro_invoc);
Chris Lattnerc21d9e42008-01-22 19:34:51 +0000951 // Do not lose the EOF/EOM. Return it to the client.
Reid Spencer5f016e22007-07-11 17:01:13 +0000952 MacroName = Tok;
953 return 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000954 } else if (Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 // If we found the ) token, the macro arg list is done.
956 if (NumParens-- == 0)
957 break;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000958 } else if (Tok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 ++NumParens;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000960 } else if (Tok.is(tok::comma) && NumParens == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 // Comma ends this argument if there are more fixed arguments expected.
962 if (NumFixedArgsLeft)
963 break;
964
965 // If this is not a variadic macro, too many args were specified.
966 if (!isVariadic) {
967 // Emit the diagnostic at the macro name in case there is a missing ).
968 // Emitting it at the , could be far away from the macro name.
969 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
970 return 0;
971 }
972 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000973 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 // If this is a comment token in the argument list and we're just in
975 // -C mode (not -CC mode), discard the comment.
976 continue;
Chris Lattner0c3eb292007-11-23 06:50:21 +0000977 } else if (Tok.is(tok::identifier)) {
978 // Reading macro arguments can cause macros that we are currently
979 // expanding from to be popped off the expansion stack. Doing so causes
980 // them to be reenabled for expansion. Here we record whether any
981 // identifiers we lex as macro arguments correspond to disabled macros.
982 // If so, we mark the token as noexpand. This is a subtle aspect of
983 // C99 6.10.3.4p2.
984 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
985 if (!MI->isEnabled())
986 Tok.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 }
988
989 ArgTokens.push_back(Tok);
990 }
991
992 // Empty arguments are standard in C99 and supported as an extension in
993 // other modes.
994 if (ArgTokens.empty() && !Features.C99)
995 Diag(Tok, diag::ext_empty_fnmacro_arg);
996
997 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattnerd2177732007-07-20 16:59:19 +0000998 Token EOFTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 EOFTok.startToken();
1000 EOFTok.setKind(tok::eof);
1001 EOFTok.setLocation(Tok.getLocation());
1002 EOFTok.setLength(0);
1003 ArgTokens.push_back(EOFTok);
1004 ++NumActuals;
1005 --NumFixedArgsLeft;
1006 };
1007
1008 // Okay, we either found the r_paren. Check to see if we parsed too few
1009 // arguments.
1010 unsigned MinArgsExpected = MI->getNumArgs();
1011
1012 // See MacroArgs instance var for description of this.
1013 bool isVarargsElided = false;
1014
1015 if (NumActuals < MinArgsExpected) {
1016 // There are several cases where too few arguments is ok, handle them now.
1017 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
1018 // Varargs where the named vararg parameter is missing: ok as extension.
1019 // #define A(x, ...)
1020 // A("blah")
1021 Diag(Tok, diag::ext_missing_varargs_arg);
1022
1023 // Remember this occurred if this is a C99 macro invocation with at least
1024 // one actual argument.
1025 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
1026 } else if (MI->getNumArgs() == 1) {
1027 // #define A(x)
1028 // A()
1029 // is ok because it is an empty argument.
1030
1031 // Empty arguments are standard in C99 and supported as an extension in
1032 // other modes.
1033 if (ArgTokens.empty() && !Features.C99)
1034 Diag(Tok, diag::ext_empty_fnmacro_arg);
1035 } else {
1036 // Otherwise, emit the error.
1037 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
1038 return 0;
1039 }
1040
1041 // Add a marker EOF token to the end of the token list for this argument.
1042 SourceLocation EndLoc = Tok.getLocation();
1043 Tok.startToken();
1044 Tok.setKind(tok::eof);
1045 Tok.setLocation(EndLoc);
1046 Tok.setLength(0);
1047 ArgTokens.push_back(Tok);
1048 }
1049
1050 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
1051}
1052
1053/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1054/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1055/// the identifier tokens inserted.
1056static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1057 Preprocessor &PP) {
1058 time_t TT = time(0);
1059 struct tm *TM = localtime(&TT);
1060
1061 static const char * const Months[] = {
1062 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1063 };
1064
1065 char TmpBuffer[100];
1066 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1067 TM->tm_year+1900);
1068 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1069
1070 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
1071 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1072}
1073
1074/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1075/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001076void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 // Figure out which token this is.
1078 IdentifierInfo *II = Tok.getIdentifierInfo();
1079 assert(II && "Can't be a macro without id info!");
1080
1081 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1082 // lex the token after it.
1083 if (II == Ident_Pragma)
1084 return Handle_Pragma(Tok);
1085
1086 ++NumBuiltinMacroExpanded;
1087
1088 char TmpBuffer[100];
1089
1090 // Set up the return result.
1091 Tok.setIdentifierInfo(0);
Chris Lattnerd2177732007-07-20 16:59:19 +00001092 Tok.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001093
1094 if (II == Ident__LINE__) {
1095 // __LINE__ expands to a simple numeric value.
Chris Lattner9dc1f532007-07-20 16:37:10 +00001096 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 unsigned Length = strlen(TmpBuffer);
1098 Tok.setKind(tok::numeric_constant);
1099 Tok.setLength(Length);
1100 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1101 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1102 SourceLocation Loc = Tok.getLocation();
1103 if (II == Ident__BASE_FILE__) {
1104 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner9dc1f532007-07-20 16:37:10 +00001105 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1106 while (NextLoc.isValid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 Loc = NextLoc;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001108 NextLoc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 }
1110 }
1111
1112 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner9dc1f532007-07-20 16:37:10 +00001113 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 FN = '"' + Lexer::Stringify(FN) + '"';
1115 Tok.setKind(tok::string_literal);
1116 Tok.setLength(FN.size());
1117 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
1118 } else if (II == Ident__DATE__) {
1119 if (!DATELoc.isValid())
1120 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1121 Tok.setKind(tok::string_literal);
1122 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1123 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
1124 } else if (II == Ident__TIME__) {
1125 if (!TIMELoc.isValid())
1126 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1127 Tok.setKind(tok::string_literal);
1128 Tok.setLength(strlen("\"hh:mm:ss\""));
1129 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
1130 } else if (II == Ident__INCLUDE_LEVEL__) {
1131 Diag(Tok, diag::ext_pp_include_level);
1132
1133 // Compute the include depth of this token.
1134 unsigned Depth = 0;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001135 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1136 for (; Loc.isValid(); ++Depth)
1137 Loc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001138
1139 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1140 sprintf(TmpBuffer, "%u", Depth);
1141 unsigned Length = strlen(TmpBuffer);
1142 Tok.setKind(tok::numeric_constant);
1143 Tok.setLength(Length);
1144 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1145 } else if (II == Ident__TIMESTAMP__) {
1146 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1147 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1148 Diag(Tok, diag::ext_pp_timestamp);
1149
1150 // Get the file that we are lexing out of. If we're currently lexing from
1151 // a macro, dig into the include stack.
1152 const FileEntry *CurFile = 0;
1153 Lexer *TheLexer = getCurrentFileLexer();
1154
1155 if (TheLexer)
Chris Lattner9dc1f532007-07-20 16:37:10 +00001156 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001157
1158 // If this file is older than the file it depends on, emit a diagnostic.
1159 const char *Result;
1160 if (CurFile) {
1161 time_t TT = CurFile->getModificationTime();
1162 struct tm *TM = localtime(&TT);
1163 Result = asctime(TM);
1164 } else {
1165 Result = "??? ??? ?? ??:??:?? ????\n";
1166 }
1167 TmpBuffer[0] = '"';
1168 strcpy(TmpBuffer+1, Result);
1169 unsigned Len = strlen(TmpBuffer);
1170 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
1171 Tok.setKind(tok::string_literal);
1172 Tok.setLength(Len);
1173 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
1174 } else {
1175 assert(0 && "Unknown identifier!");
Chris Lattnerc3d8d572007-12-09 20:31:55 +00001176 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001177}
1178
1179//===----------------------------------------------------------------------===//
1180// Lexer Event Handling.
1181//===----------------------------------------------------------------------===//
1182
1183/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1184/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +00001185IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001187 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1189
1190 // Look up this token, see if it is a macro, or if it is a language keyword.
1191 IdentifierInfo *II;
1192 if (BufPtr && !Identifier.needsCleaning()) {
1193 // No cleaning needed, just use the characters from the lexed buffer.
1194 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1195 } else {
1196 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +00001197 llvm::SmallVector<char, 64> IdentifierBuffer;
1198 IdentifierBuffer.resize(Identifier.getLength());
1199 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 unsigned Size = getSpelling(Identifier, TmpBuf);
1201 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1202 }
1203 Identifier.setIdentifierInfo(II);
1204 return II;
1205}
1206
1207
1208/// HandleIdentifier - This callback is invoked when the lexer reads an
1209/// identifier. This callback looks up the identifier in the map and/or
1210/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerd2177732007-07-20 16:59:19 +00001211void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 assert(Identifier.getIdentifierInfo() &&
1213 "Can't handle identifiers without identifier info!");
1214
1215 IdentifierInfo &II = *Identifier.getIdentifierInfo();
1216
1217 // If this identifier was poisoned, and if it was not produced from a macro
1218 // expansion, emit an error.
1219 if (II.isPoisoned() && CurLexer) {
1220 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1221 Diag(Identifier, diag::err_pp_used_poisoned_id);
1222 else
1223 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1224 }
1225
1226 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +00001227 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1229 if (MI->isEnabled()) {
1230 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1231 return;
1232 } else {
1233 // C99 6.10.3.4p2 says that a disabled macro may never again be
1234 // expanded, even if it's in a context where it could be expanded in the
1235 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +00001236 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 }
1238 }
1239 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1240 // If this identifier is a macro on some other target, emit a diagnostic.
1241 // This diagnosic is only emitted when macro expansion is enabled, because
1242 // the macro would not have been expanded for the other target either.
1243 II.setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001244 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 diag::port_target_macro_use);
1246
1247 }
1248
1249 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1250 // then we act as if it is the actual operator and not the textual
1251 // representation of it.
1252 if (II.isCPlusPlusOperatorKeyword())
1253 Identifier.setIdentifierInfo(0);
1254
1255 // Change the kind of this identifier to the appropriate token kind, e.g.
1256 // turning "for" into a keyword.
1257 Identifier.setKind(II.getTokenID());
1258
1259 // If this is an extension token, diagnose its use.
1260 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1261 // For now, I'm just commenting it out (while I work on attributes).
1262 if (II.isExtensionToken() && Features.C99)
1263 Diag(Identifier, diag::ext_token_used);
1264}
1265
1266/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1267/// the current file. This either returns the EOF token or pops a level off
1268/// the include stack and keeps going.
Chris Lattnerd2177732007-07-20 16:59:19 +00001269bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 assert(!CurMacroExpander &&
1271 "Ending a file when currently in a macro!");
1272
1273 // See if this file had a controlling macro.
1274 if (CurLexer) { // Not ending a macro, ignore it.
1275 if (const IdentifierInfo *ControllingMacro =
1276 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
1277 // Okay, this has a controlling macro, remember in PerFileInfo.
1278 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001279 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
1281 }
1282 }
1283
1284 // If this is a #include'd file, pop it off the include stack and continue
1285 // lexing the #includer file.
1286 if (!IncludeMacroStack.empty()) {
1287 // We're done with the #included file.
1288 RemoveTopOfLexerStack();
1289
1290 // Notify the client, if desired, that we are in a new source file.
1291 if (Callbacks && !isEndOfMacro && CurLexer) {
1292 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1293
1294 // Get the file entry for the current file.
1295 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001296 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 FileType = HeaderInfo.getFileDirFlavor(FE);
1298
1299 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1300 PPCallbacks::ExitFile, FileType);
1301 }
1302
1303 // Client should lex another token.
1304 return false;
1305 }
Chris Lattner09cf90f2008-01-25 00:00:30 +00001306
1307 // If the file ends with a newline, form the EOF token on the newline itself,
1308 // rather than "on the line following it", which doesn't exist. This makes
1309 // diagnostics relating to the end of file include the last file that the user
1310 // actually typed, which is goodness.
1311 const char *EndPos = CurLexer->BufferEnd;
1312 if (EndPos != CurLexer->BufferStart &&
1313 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
1314 --EndPos;
1315
1316 // Handle \n\r and \r\n:
1317 if (EndPos != CurLexer->BufferStart &&
1318 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
1319 EndPos[-1] != EndPos[0])
1320 --EndPos;
1321 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001322
1323 Result.startToken();
Chris Lattner09cf90f2008-01-25 00:00:30 +00001324 CurLexer->BufferPtr = EndPos;
1325 CurLexer->FormTokenWithChars(Result, EndPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 Result.setKind(tok::eof);
1327
1328 // We're done with the #included file.
1329 delete CurLexer;
1330 CurLexer = 0;
1331
1332 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnercc1a8752007-10-07 08:44:20 +00001333 // diagnostic is enabled, look for macros that have not been used.
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnercc1a8752007-10-07 08:44:20 +00001335 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1336 Macros.begin(), E = Macros.end(); I != E; ++I) {
1337 if (!I->second->isUsed())
1338 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 }
1340 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 return true;
1342}
1343
1344/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
1345/// the current macro expansion or token stream expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00001346bool Preprocessor::HandleEndOfMacro(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 assert(CurMacroExpander && !CurLexer &&
1348 "Ending a macro when currently in a #include file!");
1349
Chris Lattner9594acf2007-07-15 00:25:26 +00001350 // Delete or cache the now-dead macro expander.
1351 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1352 delete CurMacroExpander;
1353 else
1354 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Reid Spencer5f016e22007-07-11 17:01:13 +00001355
1356 // Handle this like a #include file being popped off the stack.
1357 CurMacroExpander = 0;
1358 return HandleEndOfFile(Result, true);
1359}
1360
1361
1362//===----------------------------------------------------------------------===//
1363// Utility Methods for Preprocessor Directive Handling.
1364//===----------------------------------------------------------------------===//
1365
1366/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1367/// current line until the tok::eom token is found.
1368void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattnerd2177732007-07-20 16:59:19 +00001369 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 do {
1371 LexUnexpandedToken(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001372 } while (Tmp.isNot(tok::eom));
Reid Spencer5f016e22007-07-11 17:01:13 +00001373}
1374
1375/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1376static bool isCXXNamedOperator(const std::string &Spelling) {
1377 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1378 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1379 Spelling == "or" || Spelling == "xor";
1380}
1381
1382/// ReadMacroName - Lex and validate a macro name, which occurs after a
1383/// #define or #undef. This sets the token kind to eom and discards the rest
1384/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1385/// this is due to a a #define, 2 if #undef directive, 0 if it is something
1386/// else (e.g. #ifdef).
Chris Lattnerd2177732007-07-20 16:59:19 +00001387void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 // Read the token, don't allow macro expansion on it.
1389 LexUnexpandedToken(MacroNameTok);
1390
1391 // Missing macro name?
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001392 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1394
1395 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1396 if (II == 0) {
1397 std::string Spelling = getSpelling(MacroNameTok);
1398 if (isCXXNamedOperator(Spelling))
1399 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1400 // except for their spellings.
1401 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1402 else
1403 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
1404 // Fall through on error.
1405 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
1406 // Error if defining "defined": C99 6.10.8.4.
1407 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner0edde552007-10-07 08:04:56 +00001408 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnercc1a8752007-10-07 08:44:20 +00001409 getMacroInfo(II)->isBuiltinMacro()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
1411 if (isDefineUndef == 1)
1412 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1413 else
1414 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
1415 } else {
1416 // Okay, we got a good identifier node. Return it.
1417 return;
1418 }
1419
1420 // Invalid macro name, read and discard the rest of the line. Then set the
1421 // token kind to tok::eom.
1422 MacroNameTok.setKind(tok::eom);
1423 return DiscardUntilEndOfDirective();
1424}
1425
1426/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1427/// not, emit a diagnostic and consume up until the eom.
1428void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001429 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 Lex(Tmp);
1431 // There should be no tokens after the directive, but we allow them as an
1432 // extension.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001433 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 Lex(Tmp);
1435
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001436 if (Tmp.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1438 DiscardUntilEndOfDirective();
1439 }
1440}
1441
1442
1443
1444/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1445/// decided that the subsequent tokens are in the #if'd out portion of the
1446/// file. Lex the rest of the file, until we see an #endif. If
1447/// FoundNonSkipPortion is true, then we have already emitted code for part of
1448/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1449/// is true, then #else directives are ok, if not, then we have already seen one
1450/// so a #else directive is a duplicate. When this returns, the caller can lex
1451/// the first valid token.
1452void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1453 bool FoundNonSkipPortion,
1454 bool FoundElse) {
1455 ++NumSkipped;
1456 assert(CurMacroExpander == 0 && CurLexer &&
1457 "Lexing a macro, not a file?");
1458
1459 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1460 FoundNonSkipPortion, FoundElse);
1461
1462 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1463 // disabling warnings, etc.
1464 CurLexer->LexingRawMode = true;
Chris Lattnerd2177732007-07-20 16:59:19 +00001465 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 while (1) {
1467 CurLexer->Lex(Tok);
1468
1469 // If this is the end of the buffer, we have an error.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001470 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 // Emit errors for each unterminated conditional on the stack, including
1472 // the current one.
1473 while (!CurLexer->ConditionalStack.empty()) {
1474 Diag(CurLexer->ConditionalStack.back().IfLoc,
1475 diag::err_pp_unterminated_conditional);
1476 CurLexer->ConditionalStack.pop_back();
1477 }
1478
1479 // Just return and let the caller lex after this #include.
1480 break;
1481 }
1482
1483 // If this token is not a preprocessor directive, just skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001484 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 continue;
1486
1487 // We just parsed a # character at the start of a line, so we're in
1488 // directive mode. Tell the lexer this so any newlines we see will be
1489 // converted into an EOM token (this terminates the macro).
1490 CurLexer->ParsingPreprocessorDirective = true;
1491 CurLexer->KeepCommentMode = false;
1492
1493
1494 // Read the next token, the directive flavor.
1495 LexUnexpandedToken(Tok);
1496
1497 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1498 // something bogus), skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001499 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 CurLexer->ParsingPreprocessorDirective = false;
1501 // Restore comment saving mode.
1502 CurLexer->KeepCommentMode = KeepComments;
1503 continue;
1504 }
1505
1506 // If the first letter isn't i or e, it isn't intesting to us. We know that
1507 // this is safe in the face of spelling differences, because there is no way
1508 // to spell an i/e in a strange way that is another letter. Skipping this
1509 // allows us to avoid looking up the identifier info for #define/#undef and
1510 // other common directives.
1511 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1512 char FirstChar = RawCharData[0];
1513 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1514 FirstChar != 'i' && FirstChar != 'e') {
1515 CurLexer->ParsingPreprocessorDirective = false;
1516 // Restore comment saving mode.
1517 CurLexer->KeepCommentMode = KeepComments;
1518 continue;
1519 }
1520
1521 // Get the identifier name without trigraphs or embedded newlines. Note
1522 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1523 // when skipping.
1524 // TODO: could do this with zero copies in the no-clean case by using
1525 // strncmp below.
1526 char Directive[20];
1527 unsigned IdLen;
1528 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1529 IdLen = Tok.getLength();
1530 memcpy(Directive, RawCharData, IdLen);
1531 Directive[IdLen] = 0;
1532 } else {
1533 std::string DirectiveStr = getSpelling(Tok);
1534 IdLen = DirectiveStr.size();
1535 if (IdLen >= 20) {
1536 CurLexer->ParsingPreprocessorDirective = false;
1537 // Restore comment saving mode.
1538 CurLexer->KeepCommentMode = KeepComments;
1539 continue;
1540 }
1541 memcpy(Directive, &DirectiveStr[0], IdLen);
1542 Directive[IdLen] = 0;
1543 }
1544
1545 if (FirstChar == 'i' && Directive[1] == 'f') {
1546 if ((IdLen == 2) || // "if"
1547 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1548 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
1549 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1550 // bother parsing the condition.
1551 DiscardUntilEndOfDirective();
1552 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
1553 /*foundnonskip*/false,
1554 /*fnddelse*/false);
1555 }
1556 } else if (FirstChar == 'e') {
1557 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
1558 CheckEndOfDirective("#endif");
1559 PPConditionalInfo CondInfo;
1560 CondInfo.WasSkipping = true; // Silence bogus warning.
1561 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1562 InCond = InCond; // Silence warning in no-asserts mode.
1563 assert(!InCond && "Can't be skipping if not in a conditional!");
1564
1565 // If we popped the outermost skipping block, we're done skipping!
1566 if (!CondInfo.WasSkipping)
1567 break;
1568 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
1569 // #else directive in a skipping conditional. If not in some other
1570 // skipping conditional, and if #else hasn't already been seen, enter it
1571 // as a non-skipping conditional.
1572 CheckEndOfDirective("#else");
1573 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1574
1575 // If this is a #else with a #else before it, report the error.
1576 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
1577
1578 // Note that we've seen a #else in this conditional.
1579 CondInfo.FoundElse = true;
1580
1581 // If the conditional is at the top level, and the #if block wasn't
1582 // entered, enter the #else block now.
1583 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1584 CondInfo.FoundNonSkip = true;
1585 break;
1586 }
1587 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
1588 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1589
1590 bool ShouldEnter;
1591 // If this is in a skipping block or if we're already handled this #if
1592 // block, don't bother parsing the condition.
1593 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
1594 DiscardUntilEndOfDirective();
1595 ShouldEnter = false;
1596 } else {
1597 // Restore the value of LexingRawMode so that identifiers are
1598 // looked up, etc, inside the #elif expression.
1599 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1600 CurLexer->LexingRawMode = false;
1601 IdentifierInfo *IfNDefMacro = 0;
1602 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
1603 CurLexer->LexingRawMode = true;
1604 }
1605
1606 // If this is a #elif with a #else before it, report the error.
1607 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
1608
1609 // If this condition is true, enter it!
1610 if (ShouldEnter) {
1611 CondInfo.FoundNonSkip = true;
1612 break;
1613 }
1614 }
1615 }
1616
1617 CurLexer->ParsingPreprocessorDirective = false;
1618 // Restore comment saving mode.
1619 CurLexer->KeepCommentMode = KeepComments;
1620 }
1621
1622 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1623 // of the file, just stop skipping and return to lexing whatever came after
1624 // the #if block.
1625 CurLexer->LexingRawMode = false;
1626}
1627
1628//===----------------------------------------------------------------------===//
1629// Preprocessor Directive Handling.
1630//===----------------------------------------------------------------------===//
1631
1632/// HandleDirective - This callback is invoked when the lexer sees a # token
1633/// at the start of a line. This consumes the directive, modifies the
1634/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1635/// read is the correct one.
Chris Lattnerd2177732007-07-20 16:59:19 +00001636void Preprocessor::HandleDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1638
1639 // We just parsed a # character at the start of a line, so we're in directive
1640 // mode. Tell the lexer this so any newlines we see will be converted into an
1641 // EOM token (which terminates the directive).
1642 CurLexer->ParsingPreprocessorDirective = true;
1643
1644 ++NumDirectives;
1645
1646 // We are about to read a token. For the multiple-include optimization FA to
1647 // work, we have to remember if we had read any tokens *before* this
1648 // pp-directive.
1649 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1650
1651 // Read the next token, the directive flavor. This isn't expanded due to
1652 // C99 6.10.3p8.
1653 LexUnexpandedToken(Result);
1654
1655 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1656 // #define A(x) #x
1657 // A(abc
1658 // #warning blah
1659 // def)
1660 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1661 if (InMacroArgs)
1662 Diag(Result, diag::ext_embedded_directive);
1663
1664TryAgain:
1665 switch (Result.getKind()) {
1666 case tok::eom:
1667 return; // null directive.
1668 case tok::comment:
1669 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1670 LexUnexpandedToken(Result);
1671 goto TryAgain;
1672
1673 case tok::numeric_constant:
1674 // FIXME: implement # 7 line numbers!
1675 DiscardUntilEndOfDirective();
1676 return;
1677 default:
1678 IdentifierInfo *II = Result.getIdentifierInfo();
1679 if (II == 0) break; // Not an identifier.
1680
1681 // Ask what the preprocessor keyword ID is.
1682 switch (II->getPPKeywordID()) {
1683 default: break;
1684 // C99 6.10.1 - Conditional Inclusion.
1685 case tok::pp_if:
1686 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1687 case tok::pp_ifdef:
1688 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1689 case tok::pp_ifndef:
1690 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1691 case tok::pp_elif:
1692 return HandleElifDirective(Result);
1693 case tok::pp_else:
1694 return HandleElseDirective(Result);
1695 case tok::pp_endif:
1696 return HandleEndifDirective(Result);
1697
1698 // C99 6.10.2 - Source File Inclusion.
1699 case tok::pp_include:
1700 return HandleIncludeDirective(Result); // Handle #include.
1701
1702 // C99 6.10.3 - Macro Replacement.
1703 case tok::pp_define:
1704 return HandleDefineDirective(Result, false);
1705 case tok::pp_undef:
1706 return HandleUndefDirective(Result);
1707
1708 // C99 6.10.4 - Line Control.
1709 case tok::pp_line:
1710 // FIXME: implement #line
1711 DiscardUntilEndOfDirective();
1712 return;
1713
1714 // C99 6.10.5 - Error Directive.
1715 case tok::pp_error:
1716 return HandleUserDiagnosticDirective(Result, false);
1717
1718 // C99 6.10.6 - Pragma Directive.
1719 case tok::pp_pragma:
1720 return HandlePragmaDirective();
1721
1722 // GNU Extensions.
1723 case tok::pp_import:
1724 return HandleImportDirective(Result);
1725 case tok::pp_include_next:
1726 return HandleIncludeNextDirective(Result);
1727
1728 case tok::pp_warning:
1729 Diag(Result, diag::ext_pp_warning_directive);
1730 return HandleUserDiagnosticDirective(Result, true);
1731 case tok::pp_ident:
1732 return HandleIdentSCCSDirective(Result);
1733 case tok::pp_sccs:
1734 return HandleIdentSCCSDirective(Result);
1735 case tok::pp_assert:
1736 //isExtension = true; // FIXME: implement #assert
1737 break;
1738 case tok::pp_unassert:
1739 //isExtension = true; // FIXME: implement #unassert
1740 break;
1741
1742 // clang extensions.
1743 case tok::pp_define_target:
1744 return HandleDefineDirective(Result, true);
1745 case tok::pp_define_other_target:
1746 return HandleDefineOtherTargetDirective(Result);
1747 }
1748 break;
1749 }
1750
1751 // If we reached here, the preprocessing token is not valid!
1752 Diag(Result, diag::err_pp_invalid_directive);
1753
1754 // Read the rest of the PP line.
1755 DiscardUntilEndOfDirective();
1756
1757 // Okay, we're done parsing the directive.
1758}
1759
Chris Lattnerd2177732007-07-20 16:59:19 +00001760void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 bool isWarning) {
1762 // Read the rest of the line raw. We do this because we don't want macros
1763 // to be expanded and we don't require that the tokens be valid preprocessing
1764 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1765 // collapse multiple consequtive white space between tokens, but this isn't
1766 // specified by the standard.
1767 std::string Message = CurLexer->ReadToEndOfLine();
1768
1769 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1770 return Diag(Tok, DiagID, Message);
1771}
1772
1773/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1774///
Chris Lattnerd2177732007-07-20 16:59:19 +00001775void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // Yes, this directive is an extension.
1777 Diag(Tok, diag::ext_pp_ident_directive);
1778
1779 // Read the string argument.
Chris Lattnerd2177732007-07-20 16:59:19 +00001780 Token StrTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 Lex(StrTok);
1782
1783 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001784 if (StrTok.isNot(tok::string_literal) &&
1785 StrTok.isNot(tok::wide_string_literal))
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 return Diag(StrTok, diag::err_pp_malformed_ident);
1787
1788 // Verify that there is nothing after the string, other than EOM.
1789 CheckEndOfDirective("#ident");
1790
1791 if (Callbacks)
1792 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
1793}
1794
1795//===----------------------------------------------------------------------===//
1796// Preprocessor Include Directive Handling.
1797//===----------------------------------------------------------------------===//
1798
1799/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1800/// checked and spelled filename, e.g. as an operand of #include. This returns
1801/// true if the input filename was in <>'s or false if it were in ""'s. The
1802/// caller is expected to provide a buffer that is large enough to hold the
1803/// spelling of the filename, but is also expected to handle the case when
1804/// this method decides to use a different buffer.
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001805bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 const char *&BufStart,
1807 const char *&BufEnd) {
1808 // Get the text form of the filename.
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1810
1811 // Make sure the filename is <x> or "x".
1812 bool isAngled;
1813 if (BufStart[0] == '<') {
1814 if (BufEnd[-1] != '>') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001815 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 BufStart = 0;
1817 return true;
1818 }
1819 isAngled = true;
1820 } else if (BufStart[0] == '"') {
1821 if (BufEnd[-1] != '"') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001822 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 BufStart = 0;
1824 return true;
1825 }
1826 isAngled = false;
1827 } else {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001828 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 BufStart = 0;
1830 return true;
1831 }
1832
1833 // Diagnose #include "" as invalid.
1834 if (BufEnd-BufStart <= 2) {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001835 Diag(Loc, diag::err_pp_empty_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 BufStart = 0;
1837 return "";
1838 }
1839
1840 // Skip the brackets.
1841 ++BufStart;
1842 --BufEnd;
1843 return isAngled;
1844}
1845
Chris Lattner706ab502007-07-23 04:56:47 +00001846/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1847/// from a macro as multiple tokens, which need to be glued together. This
1848/// occurs for code like:
1849/// #define FOO <a/b.h>
1850/// #include FOO
1851/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1852///
1853/// This code concatenates and consumes tokens up to the '>' token. It returns
1854/// false if the > was found, otherwise it returns true if it finds and consumes
1855/// the EOM marker.
1856static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1857 Preprocessor &PP) {
1858 Token CurTok;
1859
1860 PP.Lex(CurTok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001861 while (CurTok.isNot(tok::eom)) {
Chris Lattner706ab502007-07-23 04:56:47 +00001862 // Append the spelling of this token to the buffer. If there was a space
1863 // before it, add it now.
1864 if (CurTok.hasLeadingSpace())
1865 FilenameBuffer.push_back(' ');
1866
1867 // Get the spelling of the token, directly into FilenameBuffer if possible.
1868 unsigned PreAppendSize = FilenameBuffer.size();
1869 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1870
1871 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1872 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1873
1874 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1875 if (BufPtr != &FilenameBuffer[PreAppendSize])
1876 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1877
1878 // Resize FilenameBuffer to the correct size.
1879 if (CurTok.getLength() != ActualLen)
1880 FilenameBuffer.resize(PreAppendSize+ActualLen);
1881
1882 // If we found the '>' marker, return success.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001883 if (CurTok.is(tok::greater))
Chris Lattner706ab502007-07-23 04:56:47 +00001884 return false;
1885
1886 PP.Lex(CurTok);
1887 }
1888
1889 // If we hit the eom marker, emit an error and return true so that the caller
1890 // knows the EOM has been read.
1891 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1892 return true;
1893}
1894
Reid Spencer5f016e22007-07-11 17:01:13 +00001895/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1896/// file to be included from the lexer, then include it! This is a common
1897/// routine with functionality shared between #include, #include_next and
1898/// #import.
Chris Lattnerd2177732007-07-20 16:59:19 +00001899void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 const DirectoryLookup *LookupFrom,
1901 bool isImport) {
1902
Chris Lattnerd2177732007-07-20 16:59:19 +00001903 Token FilenameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 CurLexer->LexIncludeFilename(FilenameTok);
1905
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 // Reserve a buffer to get the spelling.
1907 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner706ab502007-07-23 04:56:47 +00001908 const char *FilenameStart, *FilenameEnd;
1909
1910 switch (FilenameTok.getKind()) {
1911 case tok::eom:
1912 // If the token kind is EOM, the error has already been diagnosed.
1913 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001914
Chris Lattner706ab502007-07-23 04:56:47 +00001915 case tok::angle_string_literal:
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001916 case tok::string_literal: {
Chris Lattner706ab502007-07-23 04:56:47 +00001917 FilenameBuffer.resize(FilenameTok.getLength());
1918 FilenameStart = &FilenameBuffer[0];
1919 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1920 FilenameEnd = FilenameStart+Len;
1921 break;
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001922 }
Chris Lattner706ab502007-07-23 04:56:47 +00001923
1924 case tok::less:
1925 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1926 // case, glue the tokens together into FilenameBuffer and interpret those.
1927 FilenameBuffer.push_back('<');
1928 if (ConcatenateIncludeName(FilenameBuffer, *this))
1929 return; // Found <eom> but no ">"? Diagnostic already emitted.
1930 FilenameStart = &FilenameBuffer[0];
1931 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1932 break;
1933 default:
1934 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1935 DiscardUntilEndOfDirective();
1936 return;
1937 }
1938
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001939 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 FilenameStart, FilenameEnd);
1941 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1942 // error.
Chris Lattner706ab502007-07-23 04:56:47 +00001943 if (FilenameStart == 0) {
1944 DiscardUntilEndOfDirective();
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 return;
Chris Lattner706ab502007-07-23 04:56:47 +00001946 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001947
1948 // Verify that there is nothing after the filename, other than EOM. Use the
1949 // preprocessor to lex this in case lexing the filename entered a macro.
1950 CheckEndOfDirective("#include");
1951
1952 // Check that we don't have infinite #include recursion.
1953 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
1954 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1955
1956 // Search include directories.
1957 const DirectoryLookup *CurDir;
1958 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1959 isAngled, LookupFrom, CurDir);
1960 if (File == 0)
1961 return Diag(FilenameTok, diag::err_pp_file_not_found,
1962 std::string(FilenameStart, FilenameEnd));
1963
1964 // Ask HeaderInfo if we should enter this #include file.
1965 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1966 // If it returns true, #including this file will have no effect.
1967 return;
1968 }
1969
1970 // Look up the file, create a File ID for it.
1971 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
1972 if (FileID == 0)
1973 return Diag(FilenameTok, diag::err_pp_file_not_found,
1974 std::string(FilenameStart, FilenameEnd));
1975
1976 // Finally, if all is good, enter the new file!
1977 EnterSourceFile(FileID, CurDir);
1978}
1979
1980/// HandleIncludeNextDirective - Implements #include_next.
1981///
Chris Lattnerd2177732007-07-20 16:59:19 +00001982void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1984
1985 // #include_next is like #include, except that we start searching after
1986 // the current found directory. If we can't do this, issue a
1987 // diagnostic.
1988 const DirectoryLookup *Lookup = CurDirLookup;
1989 if (isInPrimaryFile()) {
1990 Lookup = 0;
1991 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1992 } else if (Lookup == 0) {
1993 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1994 } else {
1995 // Start looking up in the next directory.
1996 ++Lookup;
1997 }
1998
1999 return HandleIncludeDirective(IncludeNextTok, Lookup);
2000}
2001
2002/// HandleImportDirective - Implements #import.
2003///
Chris Lattnerd2177732007-07-20 16:59:19 +00002004void Preprocessor::HandleImportDirective(Token &ImportTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 Diag(ImportTok, diag::ext_pp_import_directive);
2006
2007 return HandleIncludeDirective(ImportTok, 0, true);
2008}
2009
2010//===----------------------------------------------------------------------===//
2011// Preprocessor Macro Directive Handling.
2012//===----------------------------------------------------------------------===//
2013
2014/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2015/// definition has just been read. Lex the rest of the arguments and the
2016/// closing ), updating MI with what we learn. Return true if an error occurs
2017/// parsing the arg list.
2018bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner25c96482007-07-14 22:46:43 +00002019 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
2020
Chris Lattnerd2177732007-07-20 16:59:19 +00002021 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 while (1) {
2023 LexUnexpandedToken(Tok);
2024 switch (Tok.getKind()) {
2025 case tok::r_paren:
2026 // Found the end of the argument list.
Chris Lattner25c96482007-07-14 22:46:43 +00002027 if (Arguments.empty()) { // #define FOO()
2028 MI->setArgumentList(Arguments.begin(), Arguments.end());
2029 return false;
2030 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 // Otherwise we have #define FOO(A,)
2032 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2033 return true;
2034 case tok::ellipsis: // #define X(... -> C99 varargs
2035 // Warn if use of C99 feature in non-C99 mode.
2036 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
2037
2038 // Lex the token after the identifier.
2039 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002040 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002041 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2042 return true;
2043 }
2044 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner25c96482007-07-14 22:46:43 +00002045 Arguments.push_back(Ident__VA_ARGS__);
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 MI->setIsC99Varargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002047 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 return false;
2049 case tok::eom: // #define X(
2050 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2051 return true;
2052 default:
2053 // Handle keywords and identifiers here to accept things like
2054 // #define Foo(for) for.
2055 IdentifierInfo *II = Tok.getIdentifierInfo();
2056 if (II == 0) {
2057 // #define X(1
2058 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2059 return true;
2060 }
2061
2062 // If this is already used as an argument, it is used multiple times (e.g.
2063 // #define X(A,A.
Chris Lattner25c96482007-07-14 22:46:43 +00002064 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2065 Arguments.end()) { // C99 6.10.3p6
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2067 return true;
2068 }
2069
2070 // Add the argument to the macro info.
Chris Lattner25c96482007-07-14 22:46:43 +00002071 Arguments.push_back(II);
Reid Spencer5f016e22007-07-11 17:01:13 +00002072
2073 // Lex the token after the identifier.
2074 LexUnexpandedToken(Tok);
2075
2076 switch (Tok.getKind()) {
2077 default: // #define X(A B
2078 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2079 return true;
2080 case tok::r_paren: // #define X(A)
Chris Lattner25c96482007-07-14 22:46:43 +00002081 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 return false;
2083 case tok::comma: // #define X(A,
2084 break;
2085 case tok::ellipsis: // #define X(A... -> GCC extension
2086 // Diagnose extension.
2087 Diag(Tok, diag::ext_named_variadic_macro);
2088
2089 // Lex the token after the identifier.
2090 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002091 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2093 return true;
2094 }
2095
2096 MI->setIsGNUVarargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002097 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 return false;
2099 }
2100 }
2101 }
2102}
2103
2104/// HandleDefineDirective - Implements #define. This consumes the entire macro
2105/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2106/// true, then this is a "#define_target", otherwise this is a "#define".
2107///
Chris Lattnerd2177732007-07-20 16:59:19 +00002108void Preprocessor::HandleDefineDirective(Token &DefineTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 bool isTargetSpecific) {
2110 ++NumDefined;
2111
Chris Lattnerd2177732007-07-20 16:59:19 +00002112 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 ReadMacroName(MacroNameTok, 1);
2114
2115 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002116 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 return;
Chris Lattnerc215bd62007-07-14 22:11:41 +00002118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 // If we are supposed to keep comments in #defines, reenable comment saving
2120 // mode.
2121 CurLexer->KeepCommentMode = KeepMacroComments;
2122
2123 // Create the new macro.
2124 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
2125 if (isTargetSpecific) MI->setIsTargetSpecific();
2126
2127 // If the identifier is an 'other target' macro, clear this bit.
2128 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2129
2130
Chris Lattnerd2177732007-07-20 16:59:19 +00002131 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 LexUnexpandedToken(Tok);
2133
2134 // If this is a function-like macro definition, parse the argument list,
2135 // marking each of the identifiers as being used as macro arguments. Also,
2136 // check other constraints on the first token of the macro body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002137 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 // If there is no body to this macro, we have no special handling here.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002139 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 // This is a function-like macro definition. Read the argument list.
2141 MI->setIsFunctionLike();
2142 if (ReadMacroDefinitionArgList(MI)) {
2143 // Forget about MI.
2144 delete MI;
2145 // Throw away the rest of the line.
2146 if (CurLexer->ParsingPreprocessorDirective)
2147 DiscardUntilEndOfDirective();
2148 return;
2149 }
2150
2151 // Read the first token after the arg list for down below.
2152 LexUnexpandedToken(Tok);
2153 } else if (!Tok.hasLeadingSpace()) {
2154 // C99 requires whitespace between the macro definition and the body. Emit
2155 // a diagnostic for something like "#define X+".
2156 if (Features.C99) {
2157 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2158 } else {
2159 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2160 // one in some cases!
2161 }
2162 } else {
2163 // This is a normal token with leading space. Clear the leading space
2164 // marker on the first token to get proper expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00002165 Tok.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002166 }
2167
2168 // If this is a definition of a variadic C99 function-like macro, not using
2169 // the GNU named varargs extension, enabled __VA_ARGS__.
2170
2171 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2172 // This gets unpoisoned where it is allowed.
2173 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2174 if (MI->isC99Varargs())
2175 Ident__VA_ARGS__->setIsPoisoned(false);
2176
2177 // Read the rest of the macro body.
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002178 if (MI->isObjectLike()) {
2179 // Object-like macros are very simple, just read their body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002180 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002181 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 // Get the next token of the macro.
2183 LexUnexpandedToken(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 }
2185
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002186 } else {
2187 // Otherwise, read the body of a function-like macro. This has to validate
2188 // the # (stringize) operator.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002189 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002190 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002191
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002192 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2193 // parameters in function-like macro expansions.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002194 if (Tok.isNot(tok::hash)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002195 // Get the next token of the macro.
2196 LexUnexpandedToken(Tok);
2197 continue;
2198 }
2199
2200 // Get the next token of the macro.
2201 LexUnexpandedToken(Tok);
2202
2203 // Not a macro arg identifier?
2204 if (!Tok.getIdentifierInfo() ||
2205 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2206 Diag(Tok, diag::err_pp_stringize_not_parameter);
2207 delete MI;
2208
2209 // Disable __VA_ARGS__ again.
2210 Ident__VA_ARGS__->setIsPoisoned(true);
2211 return;
2212 }
2213
2214 // Things look ok, add the param name token to the macro.
2215 MI->AddTokenToBody(Tok);
2216
2217 // Get the next token of the macro.
2218 LexUnexpandedToken(Tok);
2219 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 }
2221
Chris Lattnerc215bd62007-07-14 22:11:41 +00002222
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 // Disable __VA_ARGS__ again.
2224 Ident__VA_ARGS__->setIsPoisoned(true);
2225
2226 // Check that there is no paste (##) operator at the begining or end of the
2227 // replacement list.
2228 unsigned NumTokens = MI->getNumTokens();
2229 if (NumTokens != 0) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002230 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002231 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2232 delete MI;
2233 return;
2234 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002235 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2237 delete MI;
2238 return;
2239 }
2240 }
2241
2242 // If this is the primary source file, remember that this macro hasn't been
2243 // used yet.
2244 if (isInPrimaryFile())
2245 MI->setIsUsed(false);
2246
2247 // Finally, if this identifier already had a macro defined for it, verify that
2248 // the macro bodies are identical and free the old definition.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002249 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 if (!OtherMI->isUsed())
2251 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2252
2253 // Macros must be identical. This means all tokes and whitespace separation
2254 // must be the same. C99 6.10.3.2.
2255 if (!MI->isIdenticalTo(*OtherMI, *this)) {
2256 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2257 MacroNameTok.getIdentifierInfo()->getName());
2258 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2259 }
2260 delete OtherMI;
2261 }
2262
Chris Lattnercc1a8752007-10-07 08:44:20 +00002263 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002264}
2265
2266/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattnerd2177732007-07-20 16:59:19 +00002267void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2268 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 ReadMacroName(MacroNameTok, 1);
2270
2271 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002272 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 return;
2274
2275 // Check to see if this is the last token on the #undef line.
2276 CheckEndOfDirective("#define_other_target");
2277
2278 // If there is already a macro defined by this name, turn it into a
2279 // target-specific define.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002280 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 MI->setIsTargetSpecific(true);
2282 return;
2283 }
2284
2285 // Mark the identifier as being a macro on some other target.
2286 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2287}
2288
2289
2290/// HandleUndefDirective - Implements #undef.
2291///
Chris Lattnerd2177732007-07-20 16:59:19 +00002292void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 ++NumUndefined;
2294
Chris Lattnerd2177732007-07-20 16:59:19 +00002295 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 ReadMacroName(MacroNameTok, 2);
2297
2298 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002299 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 return;
2301
2302 // Check to see if this is the last token on the #undef line.
2303 CheckEndOfDirective("#undef");
2304
2305 // Okay, we finally have a valid identifier to undef.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002306 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Reid Spencer5f016e22007-07-11 17:01:13 +00002307
2308 // #undef untaints an identifier if it were marked by define_other_target.
2309 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2310
2311 // If the macro is not defined, this is a noop undef, just return.
2312 if (MI == 0) return;
2313
2314 if (!MI->isUsed())
2315 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2316
2317 // Free macro definition.
2318 delete MI;
Chris Lattnercc1a8752007-10-07 08:44:20 +00002319 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002320}
2321
2322
2323//===----------------------------------------------------------------------===//
2324// Preprocessor Conditional Directive Handling.
2325//===----------------------------------------------------------------------===//
2326
2327/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
2328/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2329/// if any tokens have been returned or pp-directives activated before this
2330/// #ifndef has been lexed.
2331///
Chris Lattnerd2177732007-07-20 16:59:19 +00002332void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 bool ReadAnyTokensBeforeDirective) {
2334 ++NumIf;
Chris Lattnerd2177732007-07-20 16:59:19 +00002335 Token DirectiveTok = Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00002336
Chris Lattnerd2177732007-07-20 16:59:19 +00002337 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 ReadMacroName(MacroNameTok);
2339
2340 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002341 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerf37bb252007-09-24 05:14:57 +00002342 // Skip code until we get to #endif. This helps with recovery by not
2343 // emitting an error when the #endif is reached.
2344 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2345 /*Foundnonskip*/false, /*FoundElse*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 return;
Chris Lattnerf37bb252007-09-24 05:14:57 +00002347 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002348
2349 // Check to see if this is the last token on the #if[n]def line.
2350 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2351
2352 // If the start of a top-level #ifdef, inform MIOpt.
2353 if (!ReadAnyTokensBeforeDirective &&
2354 CurLexer->getConditionalStackDepth() == 0) {
2355 assert(isIfndef && "#ifdef shouldn't reach here");
2356 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2357 }
2358
2359 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnercc1a8752007-10-07 08:44:20 +00002360 MacroInfo *MI = getMacroInfo(MII);
Reid Spencer5f016e22007-07-11 17:01:13 +00002361
2362 // If there is a macro, process it.
2363 if (MI) {
2364 // Mark it used.
2365 MI->setIsUsed(true);
2366
2367 // If this is the first use of a target-specific macro, warn about it.
2368 if (MI->isTargetSpecific()) {
2369 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002370 getTargetInfo().DiagnoseNonPortability(
2371 getFullLoc(MacroNameTok.getLocation()),
2372 diag::port_target_macro_use);
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 }
2374 } else {
2375 // Use of a target-specific macro for some other target? If so, warn.
2376 if (MII->isOtherTargetMacro()) {
2377 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002378 getTargetInfo().DiagnoseNonPortability(
2379 getFullLoc(MacroNameTok.getLocation()),
2380 diag::port_target_macro_use);
Reid Spencer5f016e22007-07-11 17:01:13 +00002381 }
2382 }
2383
2384 // Should we include the stuff contained by this directive?
2385 if (!MI == isIfndef) {
2386 // Yes, remember that we are inside a conditional, then lex the next token.
2387 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
2388 /*foundnonskip*/true, /*foundelse*/false);
2389 } else {
2390 // No, skip the contents of this block and return the first token after it.
2391 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2392 /*Foundnonskip*/false,
2393 /*FoundElse*/false);
2394 }
2395}
2396
2397/// HandleIfDirective - Implements the #if directive.
2398///
Chris Lattnerd2177732007-07-20 16:59:19 +00002399void Preprocessor::HandleIfDirective(Token &IfToken,
Reid Spencer5f016e22007-07-11 17:01:13 +00002400 bool ReadAnyTokensBeforeDirective) {
2401 ++NumIf;
2402
2403 // Parse and evaluation the conditional expression.
2404 IdentifierInfo *IfNDefMacro = 0;
2405 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2406
2407 // Should we include the stuff contained by this directive?
2408 if (ConditionalTrue) {
2409 // If this condition is equivalent to #ifndef X, and if this is the first
2410 // directive seen, handle it for the multiple-include optimization.
2411 if (!ReadAnyTokensBeforeDirective &&
2412 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2413 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2414
2415 // Yes, remember that we are inside a conditional, then lex the next token.
2416 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2417 /*foundnonskip*/true, /*foundelse*/false);
2418 } else {
2419 // No, skip the contents of this block and return the first token after it.
2420 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2421 /*FoundElse*/false);
2422 }
2423}
2424
2425/// HandleEndifDirective - Implements the #endif directive.
2426///
Chris Lattnerd2177732007-07-20 16:59:19 +00002427void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002428 ++NumEndif;
2429
2430 // Check that this is the whole directive.
2431 CheckEndOfDirective("#endif");
2432
2433 PPConditionalInfo CondInfo;
2434 if (CurLexer->popConditionalLevel(CondInfo)) {
2435 // No conditionals on the stack: this is an #endif without an #if.
2436 return Diag(EndifToken, diag::err_pp_endif_without_if);
2437 }
2438
2439 // If this the end of a top-level #endif, inform MIOpt.
2440 if (CurLexer->getConditionalStackDepth() == 0)
2441 CurLexer->MIOpt.ExitTopLevelConditional();
2442
2443 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
2444 "This code should only be reachable in the non-skipping case!");
2445}
2446
2447
Chris Lattnerd2177732007-07-20 16:59:19 +00002448void Preprocessor::HandleElseDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002449 ++NumElse;
2450
2451 // #else directive in a non-skipping conditional... start skipping.
2452 CheckEndOfDirective("#else");
2453
2454 PPConditionalInfo CI;
2455 if (CurLexer->popConditionalLevel(CI))
2456 return Diag(Result, diag::pp_err_else_without_if);
2457
2458 // If this is a top-level #else, inform the MIOpt.
2459 if (CurLexer->getConditionalStackDepth() == 0)
2460 CurLexer->MIOpt.FoundTopLevelElse();
2461
2462 // If this is a #else with a #else before it, report the error.
2463 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2464
2465 // Finally, skip the rest of the contents of this block and return the first
2466 // token after it.
2467 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2468 /*FoundElse*/true);
2469}
2470
Chris Lattnerd2177732007-07-20 16:59:19 +00002471void Preprocessor::HandleElifDirective(Token &ElifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002472 ++NumElse;
2473
2474 // #elif directive in a non-skipping conditional... start skipping.
2475 // We don't care what the condition is, because we will always skip it (since
2476 // the block immediately before it was included).
2477 DiscardUntilEndOfDirective();
2478
2479 PPConditionalInfo CI;
2480 if (CurLexer->popConditionalLevel(CI))
2481 return Diag(ElifToken, diag::pp_err_elif_without_if);
2482
2483 // If this is a top-level #elif, inform the MIOpt.
2484 if (CurLexer->getConditionalStackDepth() == 0)
2485 CurLexer->MIOpt.FoundTopLevelElse();
2486
2487 // If this is a #elif with a #else before it, report the error.
2488 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2489
2490 // Finally, skip the rest of the contents of this block and return the first
2491 // token after it.
2492 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2493 /*FoundElse*/CI.FoundElse);
2494}
2495