blob: c0dde238674fc33dffdba202f473e204c0255586 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include <iostream>
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 {
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
133 << getSpelling(Tok) << "'";
134
135 if (!DumpFlags) return;
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000136
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 std::cerr << "\t";
138 if (Tok.isAtStartOfLine())
139 std::cerr << " [StartOfLine]";
140 if (Tok.hasLeadingSpace())
141 std::cerr << " [LeadingSpace]";
142 if (Tok.isExpandDisabled())
143 std::cerr << " [ExpandDisabled]";
144 if (Tok.needsCleaning()) {
145 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
146 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
147 << "']";
148 }
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000149
150 std::cerr << "\tLoc=<";
151 DumpLocation(Tok.getLocation());
152 std::cerr << ">";
153}
154
155void Preprocessor::DumpLocation(SourceLocation Loc) const {
156 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
157 std::cerr << SourceMgr.getSourceName(LogLoc) << ':'
158 << SourceMgr.getLineNumber(LogLoc) << ':'
159 << SourceMgr.getLineNumber(LogLoc);
160
161 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
162 if (PhysLoc != LogLoc) {
163 std::cerr << " <PhysLoc=";
164 DumpLocation(PhysLoc);
165 std::cerr << ">";
166 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000167}
168
169void Preprocessor::DumpMacro(const MacroInfo &MI) const {
170 std::cerr << "MACRO: ";
171 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
172 DumpToken(MI.getReplacementToken(i));
173 std::cerr << " ";
174 }
175 std::cerr << "\n";
176}
177
178void Preprocessor::PrintStats() {
179 std::cerr << "\n*** Preprocessor Stats:\n";
180 std::cerr << NumDirectives << " directives found:\n";
181 std::cerr << " " << NumDefined << " #define.\n";
182 std::cerr << " " << NumUndefined << " #undef.\n";
183 std::cerr << " #include/#include_next/#import:\n";
184 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
185 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
186 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
187 std::cerr << " " << NumElse << " #else/#elif.\n";
188 std::cerr << " " << NumEndif << " #endif.\n";
189 std::cerr << " " << NumPragma << " #pragma.\n";
190 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
191
192 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
193 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
194 << NumFastMacroExpanded << " on the fast path.\n";
195 std::cerr << (NumFastTokenPaste+NumTokenPaste)
196 << " token paste (##) operations performed, "
197 << NumFastTokenPaste << " on the fast path.\n";
198}
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 }
427
428 // FIXME: Should emit a #line directive here.
429}
430
431
432/// EnterMainSourceFile - Enter the specified FileID as the main source file,
433/// which implicitly adds the builting defines etc.
Ted Kremenek95041a22007-12-19 22:51:13 +0000434void Preprocessor::EnterMainSourceFile() {
435
436 unsigned MainFileID = SourceMgr.getMainFileID();
437
Chris Lattner53b0dab2007-10-09 22:10:18 +0000438 // Enter the main file source buffer.
439 EnterSourceFile(MainFileID, 0);
440
Chris Lattnerb2832982007-11-15 19:07:47 +0000441 // Tell the header info that the main file was entered. If the file is later
442 // #imported, it won't be re-entered.
443 if (const FileEntry *FE =
444 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
445 HeaderInfo.IncrementIncludeCount(FE);
446
Chris Lattner53b0dab2007-10-09 22:10:18 +0000447 std::vector<char> PrologFile;
448 PrologFile.reserve(4080);
449
450 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
451 InitializePredefinedMacros(*this, PrologFile);
452
453 // Add on the predefines from the driver.
454 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
455
456 // Memory buffer must end with a null byte!
457 PrologFile.push_back(0);
458
459 // Now that we have emitted the predefined macros, #includes, etc into
460 // PrologFile, preprocess it to populate the initial preprocessor state.
461 llvm::MemoryBuffer *SB =
462 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
463 "<predefines>");
464 assert(SB && "Cannot fail to create predefined source buffer");
465 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
466 assert(FileID && "Could not create FileID for predefines?");
467
468 // Start parsing the predefines.
469 EnterSourceFile(FileID, 0);
470}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000471
Reid Spencer5f016e22007-07-11 17:01:13 +0000472//===----------------------------------------------------------------------===//
473// Source File Location Methods.
474//===----------------------------------------------------------------------===//
475
476/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
477/// return null on failure. isAngled indicates whether the file reference is
478/// for system #include's or not (i.e. using <> instead of "").
479const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
480 const char *FilenameEnd,
481 bool isAngled,
482 const DirectoryLookup *FromDir,
483 const DirectoryLookup *&CurDir) {
484 // If the header lookup mechanism may be relative to the current file, pass in
485 // info about where the current file is.
486 const FileEntry *CurFileEnt = 0;
487 if (!FromDir) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000488 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
489 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 }
491
492 // Do a standard file entry lookup.
493 CurDir = CurDirLookup;
494 const FileEntry *FE =
495 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
496 isAngled, FromDir, CurDir, CurFileEnt);
497 if (FE) return FE;
498
499 // Otherwise, see if this is a subframework header. If so, this is relative
500 // to one of the headers on the #include stack. Walk the list of the current
501 // headers on the #include stack and pass them to HeaderInfo.
502 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000503 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
505 CurFileEnt)))
506 return FE;
507 }
508
509 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
510 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
511 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000512 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
514 CurFileEnt)))
515 return FE;
516 }
517 }
518
519 // Otherwise, we really couldn't find the file.
520 return 0;
521}
522
523/// isInPrimaryFile - Return true if we're in the top-level file, not in a
524/// #include.
525bool Preprocessor::isInPrimaryFile() const {
526 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000527 return IncludeMacroStack.empty();
Reid Spencer5f016e22007-07-11 17:01:13 +0000528
529 // If there are any stacked lexers, we're in a #include.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000530 assert(IncludeMacroStack[0].TheLexer &&
531 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
532 "Top level include stack isn't our primary lexer?");
533 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 if (IncludeMacroStack[i].TheLexer &&
535 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000536 return false;
537 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000538}
539
540/// getCurrentLexer - Return the current file lexer being lexed from. Note
541/// that this ignores any potentially active macro expansions and _Pragma
542/// expansions going on at the time.
543Lexer *Preprocessor::getCurrentFileLexer() const {
544 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
545
546 // Look for a stacked lexer.
547 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
548 Lexer *L = IncludeMacroStack[i-1].TheLexer;
549 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
550 return L;
551 }
552 return 0;
553}
554
555
556/// EnterSourceFile - Add a source file to the top of the include stack and
557/// start lexing tokens from it instead of the current buffer. Return true
558/// on failure.
559void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000560 const DirectoryLookup *CurDir) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
562 ++NumEnteredSourceFiles;
563
564 if (MaxIncludeStackDepth < IncludeMacroStack.size())
565 MaxIncludeStackDepth = IncludeMacroStack.size();
566
Chris Lattner25bdb512007-07-20 16:52:03 +0000567 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 EnterSourceFileWithLexer(TheLexer, CurDir);
569}
570
571/// EnterSourceFile - Add a source file to the top of the include stack and
572/// start lexing tokens from it instead of the current buffer.
573void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
574 const DirectoryLookup *CurDir) {
575
576 // Add the current lexer to the include stack.
577 if (CurLexer || CurMacroExpander)
578 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
579 CurMacroExpander));
580
581 CurLexer = TheLexer;
582 CurDirLookup = CurDir;
583 CurMacroExpander = 0;
584
585 // Notify the client, if desired, that we are in a new source file.
586 if (Callbacks && !CurLexer->Is_PragmaLexer) {
587 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
588
589 // Get the file entry for the current file.
590 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +0000591 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 FileType = HeaderInfo.getFileDirFlavor(FE);
593
Chris Lattner9dc1f532007-07-20 16:37:10 +0000594 Callbacks->FileChanged(CurLexer->getFileLoc(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 PPCallbacks::EnterFile, FileType);
596 }
597}
598
599
600
601/// EnterMacro - Add a Macro to the top of the include stack and start lexing
602/// tokens from it instead of the current buffer.
Chris Lattnerd2177732007-07-20 16:59:19 +0000603void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
605 CurMacroExpander));
606 CurLexer = 0;
607 CurDirLookup = 0;
608
Chris Lattner9594acf2007-07-15 00:25:26 +0000609 if (NumCachedMacroExpanders == 0) {
610 CurMacroExpander = new MacroExpander(Tok, Args, *this);
611 } else {
612 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
613 CurMacroExpander->Init(Tok, Args);
614 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000615}
616
617/// EnterTokenStream - Add a "macro" context to the top of the include stack,
618/// which will cause the lexer to start returning the specified tokens. Note
619/// that these tokens will be re-macro-expanded when/if expansion is enabled.
620/// This method assumes that the specified stream of tokens has a permanent
621/// owner somewhere, so they do not need to be copied.
Chris Lattnerd2177732007-07-20 16:59:19 +0000622void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 // Save our current state.
624 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
625 CurMacroExpander));
626 CurLexer = 0;
627 CurDirLookup = 0;
628
629 // Create a macro expander to expand from the specified token stream.
Chris Lattner9594acf2007-07-15 00:25:26 +0000630 if (NumCachedMacroExpanders == 0) {
631 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
632 } else {
633 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
634 CurMacroExpander->Init(Toks, NumToks);
635 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000636}
637
638/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
639/// lexer stack. This should only be used in situations where the current
640/// state of the top-of-stack lexer is known.
641void Preprocessor::RemoveTopOfLexerStack() {
642 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattner9594acf2007-07-15 00:25:26 +0000643
644 if (CurMacroExpander) {
645 // Delete or cache the now-dead macro expander.
646 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
647 delete CurMacroExpander;
648 else
649 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
650 } else {
651 delete CurLexer;
652 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 CurLexer = IncludeMacroStack.back().TheLexer;
654 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
655 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
656 IncludeMacroStack.pop_back();
657}
658
659//===----------------------------------------------------------------------===//
660// Macro Expansion Handling.
661//===----------------------------------------------------------------------===//
662
Chris Lattnercc1a8752007-10-07 08:44:20 +0000663/// setMacroInfo - Specify a macro for this identifier.
664///
665void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
666 if (MI == 0) {
667 if (II->hasMacroDefinition()) {
668 Macros.erase(II);
669 II->setHasMacroDefinition(false);
670 }
671 } else {
672 Macros[II] = MI;
673 II->setHasMacroDefinition(true);
674 }
675}
676
Reid Spencer5f016e22007-07-11 17:01:13 +0000677/// RegisterBuiltinMacro - Register the specified identifier in the identifier
678/// table and mark it as a builtin macro to be expanded.
679IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
680 // Get the identifier.
681 IdentifierInfo *Id = getIdentifierInfo(Name);
682
683 // Mark it as being a macro that is builtin.
684 MacroInfo *MI = new MacroInfo(SourceLocation());
685 MI->setIsBuiltinMacro();
Chris Lattnercc1a8752007-10-07 08:44:20 +0000686 setMacroInfo(Id, MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 return Id;
688}
689
690
691/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
692/// identifier table.
693void Preprocessor::RegisterBuiltinMacros() {
694 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
695 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
696 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
697 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
698 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
699
700 // GCC Extensions.
701 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
702 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
703 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
704}
705
706/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
707/// in its expansion, currently expands to that token literally.
708static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnercc1a8752007-10-07 08:44:20 +0000709 const IdentifierInfo *MacroIdent,
710 Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
712
713 // If the token isn't an identifier, it's always literally expanded.
714 if (II == 0) return true;
715
716 // If the identifier is a macro, and if that macro is enabled, it may be
717 // expanded so it's not a trivial expansion.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000718 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 // Fast expanding "#define X X" is ok, because X would be disabled.
720 II != MacroIdent)
721 return false;
722
723 // If this is an object-like macro invocation, it is safe to trivially expand
724 // it.
725 if (MI->isObjectLike()) return true;
726
727 // If this is a function-like macro invocation, it's safe to trivially expand
728 // as long as the identifier is not a macro argument.
729 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
730 I != E; ++I)
731 if (*I == II)
732 return false; // Identifier is a macro argument.
733
734 return true;
735}
736
737
738/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
739/// lexed is a '('. If so, consume the token and return true, if not, this
740/// method should have no observable side-effect on the lexed tokens.
741bool Preprocessor::isNextPPTokenLParen() {
742 // Do some quick tests for rejection cases.
743 unsigned Val;
744 if (CurLexer)
745 Val = CurLexer->isNextPPTokenLParen();
746 else
747 Val = CurMacroExpander->isNextTokenLParen();
748
749 if (Val == 2) {
Chris Lattner0ea793e2007-07-19 00:07:36 +0000750 // We have run off the end. If it's a source file we don't
751 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
752 // macro stack.
753 if (CurLexer)
754 return false;
755 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
757 if (Entry.TheLexer)
758 Val = Entry.TheLexer->isNextPPTokenLParen();
759 else
760 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner0ea793e2007-07-19 00:07:36 +0000761
762 if (Val != 2)
763 break;
764
765 // Ran off the end of a source file?
766 if (Entry.TheLexer)
767 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000768 }
769 }
770
771 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
772 // have found something that isn't a '(' or we found the end of the
773 // translation unit. In either case, return false.
774 if (Val != 1)
775 return false;
776
Chris Lattnerd2177732007-07-20 16:59:19 +0000777 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000779 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 return true;
781}
782
783/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
784/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000785bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 MacroInfo *MI) {
787
788 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
789 if (MI->isBuiltinMacro()) {
790 ExpandBuiltinMacro(Identifier);
791 return false;
792 }
793
794 // If this is the first use of a target-specific macro, warn about it.
795 if (MI->isTargetSpecific()) {
796 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000797 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 diag::port_target_macro_use);
799 }
800
801 /// Args - If this is a function-like macro expansion, this contains,
802 /// for each macro argument, the list of tokens that were provided to the
803 /// invocation.
804 MacroArgs *Args = 0;
805
806 // If this is a function-like macro, read the arguments.
807 if (MI->isFunctionLike()) {
808 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000809 // name isn't a '(', this macro should not be expanded. Otherwise, consume
810 // it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 if (!isNextPPTokenLParen())
812 return true;
813
814 // Remember that we are now parsing the arguments to a macro invocation.
815 // Preprocessor directives used inside macro arguments are not portable, and
816 // this enables the warning.
817 InMacroArgs = true;
818 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
819
820 // Finished parsing args.
821 InMacroArgs = false;
822
823 // If there was an error parsing the arguments, bail out.
824 if (Args == 0) return false;
825
826 ++NumFnMacroExpanded;
827 } else {
828 ++NumMacroExpanded;
829 }
830
831 // Notice that this macro has been used.
832 MI->setIsUsed(true);
833
834 // If we started lexing a macro, enter the macro expansion body.
835
836 // If this macro expands to no tokens, don't bother to push it onto the
837 // expansion stack, only to take it right back off.
838 if (MI->getNumTokens() == 0) {
839 // No need for arg info.
840 if (Args) Args->destroy();
841
842 // Ignore this macro use, just return the next token in the current
843 // buffer.
844 bool HadLeadingSpace = Identifier.hasLeadingSpace();
845 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
846
847 Lex(Identifier);
848
849 // If the identifier isn't on some OTHER line, inherit the leading
850 // whitespace/first-on-a-line property of this token. This handles
851 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
852 // empty.
853 if (!Identifier.isAtStartOfLine()) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000854 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
855 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 }
857 ++NumFastMacroExpanded;
858 return false;
859
860 } else if (MI->getNumTokens() == 1 &&
Chris Lattnercc1a8752007-10-07 08:44:20 +0000861 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
862 *this)){
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 // Otherwise, if this macro expands into a single trivially-expanded
864 // token: expand it now. This handles common cases like
865 // "#define VAL 42".
866
867 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
868 // identifier to the expanded token.
869 bool isAtStartOfLine = Identifier.isAtStartOfLine();
870 bool hasLeadingSpace = Identifier.hasLeadingSpace();
871
872 // Remember where the token is instantiated.
873 SourceLocation InstantiateLoc = Identifier.getLocation();
874
875 // Replace the result token.
876 Identifier = MI->getReplacementToken(0);
877
878 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattnerd2177732007-07-20 16:59:19 +0000879 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
880 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000881
882 // Update the tokens location to include both its logical and physical
883 // locations.
884 SourceLocation Loc =
885 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
886 Identifier.setLocation(Loc);
887
888 // If this is #define X X, we must mark the result as unexpandible.
889 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnercc1a8752007-10-07 08:44:20 +0000890 if (getMacroInfo(NewII) == MI)
Chris Lattnerd2177732007-07-20 16:59:19 +0000891 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893 // Since this is not an identifier token, it can't be macro expanded, so
894 // we're done.
895 ++NumFastMacroExpanded;
896 return false;
897 }
898
899 // Start expanding the macro.
900 EnterMacro(Identifier, Args);
901
902 // Now that the macro is at the top of the include stack, ask the
903 // preprocessor to read the next token from it.
904 Lex(Identifier);
905 return false;
906}
907
908/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
909/// invoked to read all of the actual arguments specified for the macro
910/// invocation. This returns null on error.
Chris Lattnerd2177732007-07-20 16:59:19 +0000911MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 MacroInfo *MI) {
913 // The number of fixed arguments to parse.
914 unsigned NumFixedArgsLeft = MI->getNumArgs();
915 bool isVariadic = MI->isVariadic();
916
917 // Outer loop, while there are more arguments, keep reading them.
Chris Lattnerd2177732007-07-20 16:59:19 +0000918 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 Tok.setKind(tok::comma);
920 --NumFixedArgsLeft; // Start reading the first arg.
921
922 // ArgTokens - Build up a list of tokens that make up each argument. Each
923 // argument is separated by an EOF token. Use a SmallVector so we can avoid
924 // heap allocations in the common case.
Chris Lattnerd2177732007-07-20 16:59:19 +0000925 llvm::SmallVector<Token, 64> ArgTokens;
Reid Spencer5f016e22007-07-11 17:01:13 +0000926
927 unsigned NumActuals = 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000928 while (Tok.is(tok::comma)) {
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000929 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
930 // that we already consumed the first one.
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 unsigned NumParens = 0;
932
933 while (1) {
934 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
935 // an argument value in a macro could expand to ',' or '(' or ')'.
936 LexUnexpandedToken(Tok);
937
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000938 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 Diag(MacroName, diag::err_unterm_macro_invoc);
940 // Do not lose the EOF. Return it to the client.
941 MacroName = Tok;
942 return 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000943 } else if (Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 // If we found the ) token, the macro arg list is done.
945 if (NumParens-- == 0)
946 break;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000947 } else if (Tok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000948 ++NumParens;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000949 } else if (Tok.is(tok::comma) && NumParens == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 // Comma ends this argument if there are more fixed arguments expected.
951 if (NumFixedArgsLeft)
952 break;
953
954 // If this is not a variadic macro, too many args were specified.
955 if (!isVariadic) {
956 // Emit the diagnostic at the macro name in case there is a missing ).
957 // Emitting it at the , could be far away from the macro name.
958 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
959 return 0;
960 }
961 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000962 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000963 // If this is a comment token in the argument list and we're just in
964 // -C mode (not -CC mode), discard the comment.
965 continue;
Chris Lattner0c3eb292007-11-23 06:50:21 +0000966 } else if (Tok.is(tok::identifier)) {
967 // Reading macro arguments can cause macros that we are currently
968 // expanding from to be popped off the expansion stack. Doing so causes
969 // them to be reenabled for expansion. Here we record whether any
970 // identifiers we lex as macro arguments correspond to disabled macros.
971 // If so, we mark the token as noexpand. This is a subtle aspect of
972 // C99 6.10.3.4p2.
973 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
974 if (!MI->isEnabled())
975 Tok.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 }
977
978 ArgTokens.push_back(Tok);
979 }
980
981 // Empty arguments are standard in C99 and supported as an extension in
982 // other modes.
983 if (ArgTokens.empty() && !Features.C99)
984 Diag(Tok, diag::ext_empty_fnmacro_arg);
985
986 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattnerd2177732007-07-20 16:59:19 +0000987 Token EOFTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 EOFTok.startToken();
989 EOFTok.setKind(tok::eof);
990 EOFTok.setLocation(Tok.getLocation());
991 EOFTok.setLength(0);
992 ArgTokens.push_back(EOFTok);
993 ++NumActuals;
994 --NumFixedArgsLeft;
995 };
996
997 // Okay, we either found the r_paren. Check to see if we parsed too few
998 // arguments.
999 unsigned MinArgsExpected = MI->getNumArgs();
1000
1001 // See MacroArgs instance var for description of this.
1002 bool isVarargsElided = false;
1003
1004 if (NumActuals < MinArgsExpected) {
1005 // There are several cases where too few arguments is ok, handle them now.
1006 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
1007 // Varargs where the named vararg parameter is missing: ok as extension.
1008 // #define A(x, ...)
1009 // A("blah")
1010 Diag(Tok, diag::ext_missing_varargs_arg);
1011
1012 // Remember this occurred if this is a C99 macro invocation with at least
1013 // one actual argument.
1014 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
1015 } else if (MI->getNumArgs() == 1) {
1016 // #define A(x)
1017 // A()
1018 // is ok because it is an empty argument.
1019
1020 // Empty arguments are standard in C99 and supported as an extension in
1021 // other modes.
1022 if (ArgTokens.empty() && !Features.C99)
1023 Diag(Tok, diag::ext_empty_fnmacro_arg);
1024 } else {
1025 // Otherwise, emit the error.
1026 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
1027 return 0;
1028 }
1029
1030 // Add a marker EOF token to the end of the token list for this argument.
1031 SourceLocation EndLoc = Tok.getLocation();
1032 Tok.startToken();
1033 Tok.setKind(tok::eof);
1034 Tok.setLocation(EndLoc);
1035 Tok.setLength(0);
1036 ArgTokens.push_back(Tok);
1037 }
1038
1039 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
1040}
1041
1042/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1043/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1044/// the identifier tokens inserted.
1045static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1046 Preprocessor &PP) {
1047 time_t TT = time(0);
1048 struct tm *TM = localtime(&TT);
1049
1050 static const char * const Months[] = {
1051 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1052 };
1053
1054 char TmpBuffer[100];
1055 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1056 TM->tm_year+1900);
1057 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1058
1059 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
1060 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1061}
1062
1063/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1064/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001065void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001066 // Figure out which token this is.
1067 IdentifierInfo *II = Tok.getIdentifierInfo();
1068 assert(II && "Can't be a macro without id info!");
1069
1070 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1071 // lex the token after it.
1072 if (II == Ident_Pragma)
1073 return Handle_Pragma(Tok);
1074
1075 ++NumBuiltinMacroExpanded;
1076
1077 char TmpBuffer[100];
1078
1079 // Set up the return result.
1080 Tok.setIdentifierInfo(0);
Chris Lattnerd2177732007-07-20 16:59:19 +00001081 Tok.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001082
1083 if (II == Ident__LINE__) {
1084 // __LINE__ expands to a simple numeric value.
Chris Lattner9dc1f532007-07-20 16:37:10 +00001085 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 unsigned Length = strlen(TmpBuffer);
1087 Tok.setKind(tok::numeric_constant);
1088 Tok.setLength(Length);
1089 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1090 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1091 SourceLocation Loc = Tok.getLocation();
1092 if (II == Ident__BASE_FILE__) {
1093 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner9dc1f532007-07-20 16:37:10 +00001094 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1095 while (NextLoc.isValid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 Loc = NextLoc;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001097 NextLoc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 }
1099 }
1100
1101 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner9dc1f532007-07-20 16:37:10 +00001102 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 FN = '"' + Lexer::Stringify(FN) + '"';
1104 Tok.setKind(tok::string_literal);
1105 Tok.setLength(FN.size());
1106 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
1107 } else if (II == Ident__DATE__) {
1108 if (!DATELoc.isValid())
1109 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1110 Tok.setKind(tok::string_literal);
1111 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1112 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
1113 } else if (II == Ident__TIME__) {
1114 if (!TIMELoc.isValid())
1115 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1116 Tok.setKind(tok::string_literal);
1117 Tok.setLength(strlen("\"hh:mm:ss\""));
1118 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
1119 } else if (II == Ident__INCLUDE_LEVEL__) {
1120 Diag(Tok, diag::ext_pp_include_level);
1121
1122 // Compute the include depth of this token.
1123 unsigned Depth = 0;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001124 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1125 for (; Loc.isValid(); ++Depth)
1126 Loc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001127
1128 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1129 sprintf(TmpBuffer, "%u", Depth);
1130 unsigned Length = strlen(TmpBuffer);
1131 Tok.setKind(tok::numeric_constant);
1132 Tok.setLength(Length);
1133 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1134 } else if (II == Ident__TIMESTAMP__) {
1135 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1136 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1137 Diag(Tok, diag::ext_pp_timestamp);
1138
1139 // Get the file that we are lexing out of. If we're currently lexing from
1140 // a macro, dig into the include stack.
1141 const FileEntry *CurFile = 0;
1142 Lexer *TheLexer = getCurrentFileLexer();
1143
1144 if (TheLexer)
Chris Lattner9dc1f532007-07-20 16:37:10 +00001145 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001146
1147 // If this file is older than the file it depends on, emit a diagnostic.
1148 const char *Result;
1149 if (CurFile) {
1150 time_t TT = CurFile->getModificationTime();
1151 struct tm *TM = localtime(&TT);
1152 Result = asctime(TM);
1153 } else {
1154 Result = "??? ??? ?? ??:??:?? ????\n";
1155 }
1156 TmpBuffer[0] = '"';
1157 strcpy(TmpBuffer+1, Result);
1158 unsigned Len = strlen(TmpBuffer);
1159 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
1160 Tok.setKind(tok::string_literal);
1161 Tok.setLength(Len);
1162 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
1163 } else {
1164 assert(0 && "Unknown identifier!");
Chris Lattnerc3d8d572007-12-09 20:31:55 +00001165 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001166}
1167
1168//===----------------------------------------------------------------------===//
1169// Lexer Event Handling.
1170//===----------------------------------------------------------------------===//
1171
1172/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1173/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +00001174IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001176 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1178
1179 // Look up this token, see if it is a macro, or if it is a language keyword.
1180 IdentifierInfo *II;
1181 if (BufPtr && !Identifier.needsCleaning()) {
1182 // No cleaning needed, just use the characters from the lexed buffer.
1183 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1184 } else {
1185 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +00001186 llvm::SmallVector<char, 64> IdentifierBuffer;
1187 IdentifierBuffer.resize(Identifier.getLength());
1188 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 unsigned Size = getSpelling(Identifier, TmpBuf);
1190 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1191 }
1192 Identifier.setIdentifierInfo(II);
1193 return II;
1194}
1195
1196
1197/// HandleIdentifier - This callback is invoked when the lexer reads an
1198/// identifier. This callback looks up the identifier in the map and/or
1199/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerd2177732007-07-20 16:59:19 +00001200void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 assert(Identifier.getIdentifierInfo() &&
1202 "Can't handle identifiers without identifier info!");
1203
1204 IdentifierInfo &II = *Identifier.getIdentifierInfo();
1205
1206 // If this identifier was poisoned, and if it was not produced from a macro
1207 // expansion, emit an error.
1208 if (II.isPoisoned() && CurLexer) {
1209 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1210 Diag(Identifier, diag::err_pp_used_poisoned_id);
1211 else
1212 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1213 }
1214
1215 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +00001216 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1218 if (MI->isEnabled()) {
1219 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1220 return;
1221 } else {
1222 // C99 6.10.3.4p2 says that a disabled macro may never again be
1223 // expanded, even if it's in a context where it could be expanded in the
1224 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +00001225 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 }
1227 }
1228 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1229 // If this identifier is a macro on some other target, emit a diagnostic.
1230 // This diagnosic is only emitted when macro expansion is enabled, because
1231 // the macro would not have been expanded for the other target either.
1232 II.setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001233 getTargetInfo().DiagnoseNonPortability(getFullLoc(Identifier.getLocation()),
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 diag::port_target_macro_use);
1235
1236 }
1237
1238 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1239 // then we act as if it is the actual operator and not the textual
1240 // representation of it.
1241 if (II.isCPlusPlusOperatorKeyword())
1242 Identifier.setIdentifierInfo(0);
1243
1244 // Change the kind of this identifier to the appropriate token kind, e.g.
1245 // turning "for" into a keyword.
1246 Identifier.setKind(II.getTokenID());
1247
1248 // If this is an extension token, diagnose its use.
1249 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1250 // For now, I'm just commenting it out (while I work on attributes).
1251 if (II.isExtensionToken() && Features.C99)
1252 Diag(Identifier, diag::ext_token_used);
1253}
1254
1255/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1256/// the current file. This either returns the EOF token or pops a level off
1257/// the include stack and keeps going.
Chris Lattnerd2177732007-07-20 16:59:19 +00001258bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 assert(!CurMacroExpander &&
1260 "Ending a file when currently in a macro!");
1261
1262 // See if this file had a controlling macro.
1263 if (CurLexer) { // Not ending a macro, ignore it.
1264 if (const IdentifierInfo *ControllingMacro =
1265 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
1266 // Okay, this has a controlling macro, remember in PerFileInfo.
1267 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001268 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
1270 }
1271 }
1272
1273 // If this is a #include'd file, pop it off the include stack and continue
1274 // lexing the #includer file.
1275 if (!IncludeMacroStack.empty()) {
1276 // We're done with the #included file.
1277 RemoveTopOfLexerStack();
1278
1279 // Notify the client, if desired, that we are in a new source file.
1280 if (Callbacks && !isEndOfMacro && CurLexer) {
1281 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1282
1283 // Get the file entry for the current file.
1284 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001285 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 FileType = HeaderInfo.getFileDirFlavor(FE);
1287
1288 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1289 PPCallbacks::ExitFile, FileType);
1290 }
1291
1292 // Client should lex another token.
1293 return false;
1294 }
1295
1296 Result.startToken();
1297 CurLexer->BufferPtr = CurLexer->BufferEnd;
1298 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
1299 Result.setKind(tok::eof);
1300
1301 // We're done with the #included file.
1302 delete CurLexer;
1303 CurLexer = 0;
1304
1305 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnercc1a8752007-10-07 08:44:20 +00001306 // diagnostic is enabled, look for macros that have not been used.
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnercc1a8752007-10-07 08:44:20 +00001308 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1309 Macros.begin(), E = Macros.end(); I != E; ++I) {
1310 if (!I->second->isUsed())
1311 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 }
1313 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 return true;
1315}
1316
1317/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
1318/// the current macro expansion or token stream expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00001319bool Preprocessor::HandleEndOfMacro(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 assert(CurMacroExpander && !CurLexer &&
1321 "Ending a macro when currently in a #include file!");
1322
Chris Lattner9594acf2007-07-15 00:25:26 +00001323 // Delete or cache the now-dead macro expander.
1324 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1325 delete CurMacroExpander;
1326 else
1327 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Reid Spencer5f016e22007-07-11 17:01:13 +00001328
1329 // Handle this like a #include file being popped off the stack.
1330 CurMacroExpander = 0;
1331 return HandleEndOfFile(Result, true);
1332}
1333
1334
1335//===----------------------------------------------------------------------===//
1336// Utility Methods for Preprocessor Directive Handling.
1337//===----------------------------------------------------------------------===//
1338
1339/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1340/// current line until the tok::eom token is found.
1341void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattnerd2177732007-07-20 16:59:19 +00001342 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 do {
1344 LexUnexpandedToken(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001345 } while (Tmp.isNot(tok::eom));
Reid Spencer5f016e22007-07-11 17:01:13 +00001346}
1347
1348/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1349static bool isCXXNamedOperator(const std::string &Spelling) {
1350 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1351 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1352 Spelling == "or" || Spelling == "xor";
1353}
1354
1355/// ReadMacroName - Lex and validate a macro name, which occurs after a
1356/// #define or #undef. This sets the token kind to eom and discards the rest
1357/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1358/// this is due to a a #define, 2 if #undef directive, 0 if it is something
1359/// else (e.g. #ifdef).
Chris Lattnerd2177732007-07-20 16:59:19 +00001360void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // Read the token, don't allow macro expansion on it.
1362 LexUnexpandedToken(MacroNameTok);
1363
1364 // Missing macro name?
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001365 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1367
1368 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1369 if (II == 0) {
1370 std::string Spelling = getSpelling(MacroNameTok);
1371 if (isCXXNamedOperator(Spelling))
1372 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1373 // except for their spellings.
1374 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1375 else
1376 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
1377 // Fall through on error.
1378 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
1379 // Error if defining "defined": C99 6.10.8.4.
1380 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner0edde552007-10-07 08:04:56 +00001381 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnercc1a8752007-10-07 08:44:20 +00001382 getMacroInfo(II)->isBuiltinMacro()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
1384 if (isDefineUndef == 1)
1385 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1386 else
1387 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
1388 } else {
1389 // Okay, we got a good identifier node. Return it.
1390 return;
1391 }
1392
1393 // Invalid macro name, read and discard the rest of the line. Then set the
1394 // token kind to tok::eom.
1395 MacroNameTok.setKind(tok::eom);
1396 return DiscardUntilEndOfDirective();
1397}
1398
1399/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1400/// not, emit a diagnostic and consume up until the eom.
1401void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001402 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 Lex(Tmp);
1404 // There should be no tokens after the directive, but we allow them as an
1405 // extension.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001406 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 Lex(Tmp);
1408
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001409 if (Tmp.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1411 DiscardUntilEndOfDirective();
1412 }
1413}
1414
1415
1416
1417/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1418/// decided that the subsequent tokens are in the #if'd out portion of the
1419/// file. Lex the rest of the file, until we see an #endif. If
1420/// FoundNonSkipPortion is true, then we have already emitted code for part of
1421/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1422/// is true, then #else directives are ok, if not, then we have already seen one
1423/// so a #else directive is a duplicate. When this returns, the caller can lex
1424/// the first valid token.
1425void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1426 bool FoundNonSkipPortion,
1427 bool FoundElse) {
1428 ++NumSkipped;
1429 assert(CurMacroExpander == 0 && CurLexer &&
1430 "Lexing a macro, not a file?");
1431
1432 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1433 FoundNonSkipPortion, FoundElse);
1434
1435 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1436 // disabling warnings, etc.
1437 CurLexer->LexingRawMode = true;
Chris Lattnerd2177732007-07-20 16:59:19 +00001438 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 while (1) {
1440 CurLexer->Lex(Tok);
1441
1442 // If this is the end of the buffer, we have an error.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001443 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // Emit errors for each unterminated conditional on the stack, including
1445 // the current one.
1446 while (!CurLexer->ConditionalStack.empty()) {
1447 Diag(CurLexer->ConditionalStack.back().IfLoc,
1448 diag::err_pp_unterminated_conditional);
1449 CurLexer->ConditionalStack.pop_back();
1450 }
1451
1452 // Just return and let the caller lex after this #include.
1453 break;
1454 }
1455
1456 // If this token is not a preprocessor directive, just skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001457 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 continue;
1459
1460 // We just parsed a # character at the start of a line, so we're in
1461 // directive mode. Tell the lexer this so any newlines we see will be
1462 // converted into an EOM token (this terminates the macro).
1463 CurLexer->ParsingPreprocessorDirective = true;
1464 CurLexer->KeepCommentMode = false;
1465
1466
1467 // Read the next token, the directive flavor.
1468 LexUnexpandedToken(Tok);
1469
1470 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1471 // something bogus), skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001472 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 CurLexer->ParsingPreprocessorDirective = false;
1474 // Restore comment saving mode.
1475 CurLexer->KeepCommentMode = KeepComments;
1476 continue;
1477 }
1478
1479 // If the first letter isn't i or e, it isn't intesting to us. We know that
1480 // this is safe in the face of spelling differences, because there is no way
1481 // to spell an i/e in a strange way that is another letter. Skipping this
1482 // allows us to avoid looking up the identifier info for #define/#undef and
1483 // other common directives.
1484 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1485 char FirstChar = RawCharData[0];
1486 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1487 FirstChar != 'i' && FirstChar != 'e') {
1488 CurLexer->ParsingPreprocessorDirective = false;
1489 // Restore comment saving mode.
1490 CurLexer->KeepCommentMode = KeepComments;
1491 continue;
1492 }
1493
1494 // Get the identifier name without trigraphs or embedded newlines. Note
1495 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1496 // when skipping.
1497 // TODO: could do this with zero copies in the no-clean case by using
1498 // strncmp below.
1499 char Directive[20];
1500 unsigned IdLen;
1501 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1502 IdLen = Tok.getLength();
1503 memcpy(Directive, RawCharData, IdLen);
1504 Directive[IdLen] = 0;
1505 } else {
1506 std::string DirectiveStr = getSpelling(Tok);
1507 IdLen = DirectiveStr.size();
1508 if (IdLen >= 20) {
1509 CurLexer->ParsingPreprocessorDirective = false;
1510 // Restore comment saving mode.
1511 CurLexer->KeepCommentMode = KeepComments;
1512 continue;
1513 }
1514 memcpy(Directive, &DirectiveStr[0], IdLen);
1515 Directive[IdLen] = 0;
1516 }
1517
1518 if (FirstChar == 'i' && Directive[1] == 'f') {
1519 if ((IdLen == 2) || // "if"
1520 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1521 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
1522 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1523 // bother parsing the condition.
1524 DiscardUntilEndOfDirective();
1525 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
1526 /*foundnonskip*/false,
1527 /*fnddelse*/false);
1528 }
1529 } else if (FirstChar == 'e') {
1530 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
1531 CheckEndOfDirective("#endif");
1532 PPConditionalInfo CondInfo;
1533 CondInfo.WasSkipping = true; // Silence bogus warning.
1534 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1535 InCond = InCond; // Silence warning in no-asserts mode.
1536 assert(!InCond && "Can't be skipping if not in a conditional!");
1537
1538 // If we popped the outermost skipping block, we're done skipping!
1539 if (!CondInfo.WasSkipping)
1540 break;
1541 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
1542 // #else directive in a skipping conditional. If not in some other
1543 // skipping conditional, and if #else hasn't already been seen, enter it
1544 // as a non-skipping conditional.
1545 CheckEndOfDirective("#else");
1546 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1547
1548 // If this is a #else with a #else before it, report the error.
1549 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
1550
1551 // Note that we've seen a #else in this conditional.
1552 CondInfo.FoundElse = true;
1553
1554 // If the conditional is at the top level, and the #if block wasn't
1555 // entered, enter the #else block now.
1556 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1557 CondInfo.FoundNonSkip = true;
1558 break;
1559 }
1560 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
1561 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1562
1563 bool ShouldEnter;
1564 // If this is in a skipping block or if we're already handled this #if
1565 // block, don't bother parsing the condition.
1566 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
1567 DiscardUntilEndOfDirective();
1568 ShouldEnter = false;
1569 } else {
1570 // Restore the value of LexingRawMode so that identifiers are
1571 // looked up, etc, inside the #elif expression.
1572 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1573 CurLexer->LexingRawMode = false;
1574 IdentifierInfo *IfNDefMacro = 0;
1575 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
1576 CurLexer->LexingRawMode = true;
1577 }
1578
1579 // If this is a #elif with a #else before it, report the error.
1580 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
1581
1582 // If this condition is true, enter it!
1583 if (ShouldEnter) {
1584 CondInfo.FoundNonSkip = true;
1585 break;
1586 }
1587 }
1588 }
1589
1590 CurLexer->ParsingPreprocessorDirective = false;
1591 // Restore comment saving mode.
1592 CurLexer->KeepCommentMode = KeepComments;
1593 }
1594
1595 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1596 // of the file, just stop skipping and return to lexing whatever came after
1597 // the #if block.
1598 CurLexer->LexingRawMode = false;
1599}
1600
1601//===----------------------------------------------------------------------===//
1602// Preprocessor Directive Handling.
1603//===----------------------------------------------------------------------===//
1604
1605/// HandleDirective - This callback is invoked when the lexer sees a # token
1606/// at the start of a line. This consumes the directive, modifies the
1607/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1608/// read is the correct one.
Chris Lattnerd2177732007-07-20 16:59:19 +00001609void Preprocessor::HandleDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1611
1612 // We just parsed a # character at the start of a line, so we're in directive
1613 // mode. Tell the lexer this so any newlines we see will be converted into an
1614 // EOM token (which terminates the directive).
1615 CurLexer->ParsingPreprocessorDirective = true;
1616
1617 ++NumDirectives;
1618
1619 // We are about to read a token. For the multiple-include optimization FA to
1620 // work, we have to remember if we had read any tokens *before* this
1621 // pp-directive.
1622 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1623
1624 // Read the next token, the directive flavor. This isn't expanded due to
1625 // C99 6.10.3p8.
1626 LexUnexpandedToken(Result);
1627
1628 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1629 // #define A(x) #x
1630 // A(abc
1631 // #warning blah
1632 // def)
1633 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1634 if (InMacroArgs)
1635 Diag(Result, diag::ext_embedded_directive);
1636
1637TryAgain:
1638 switch (Result.getKind()) {
1639 case tok::eom:
1640 return; // null directive.
1641 case tok::comment:
1642 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1643 LexUnexpandedToken(Result);
1644 goto TryAgain;
1645
1646 case tok::numeric_constant:
1647 // FIXME: implement # 7 line numbers!
1648 DiscardUntilEndOfDirective();
1649 return;
1650 default:
1651 IdentifierInfo *II = Result.getIdentifierInfo();
1652 if (II == 0) break; // Not an identifier.
1653
1654 // Ask what the preprocessor keyword ID is.
1655 switch (II->getPPKeywordID()) {
1656 default: break;
1657 // C99 6.10.1 - Conditional Inclusion.
1658 case tok::pp_if:
1659 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1660 case tok::pp_ifdef:
1661 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1662 case tok::pp_ifndef:
1663 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1664 case tok::pp_elif:
1665 return HandleElifDirective(Result);
1666 case tok::pp_else:
1667 return HandleElseDirective(Result);
1668 case tok::pp_endif:
1669 return HandleEndifDirective(Result);
1670
1671 // C99 6.10.2 - Source File Inclusion.
1672 case tok::pp_include:
1673 return HandleIncludeDirective(Result); // Handle #include.
1674
1675 // C99 6.10.3 - Macro Replacement.
1676 case tok::pp_define:
1677 return HandleDefineDirective(Result, false);
1678 case tok::pp_undef:
1679 return HandleUndefDirective(Result);
1680
1681 // C99 6.10.4 - Line Control.
1682 case tok::pp_line:
1683 // FIXME: implement #line
1684 DiscardUntilEndOfDirective();
1685 return;
1686
1687 // C99 6.10.5 - Error Directive.
1688 case tok::pp_error:
1689 return HandleUserDiagnosticDirective(Result, false);
1690
1691 // C99 6.10.6 - Pragma Directive.
1692 case tok::pp_pragma:
1693 return HandlePragmaDirective();
1694
1695 // GNU Extensions.
1696 case tok::pp_import:
1697 return HandleImportDirective(Result);
1698 case tok::pp_include_next:
1699 return HandleIncludeNextDirective(Result);
1700
1701 case tok::pp_warning:
1702 Diag(Result, diag::ext_pp_warning_directive);
1703 return HandleUserDiagnosticDirective(Result, true);
1704 case tok::pp_ident:
1705 return HandleIdentSCCSDirective(Result);
1706 case tok::pp_sccs:
1707 return HandleIdentSCCSDirective(Result);
1708 case tok::pp_assert:
1709 //isExtension = true; // FIXME: implement #assert
1710 break;
1711 case tok::pp_unassert:
1712 //isExtension = true; // FIXME: implement #unassert
1713 break;
1714
1715 // clang extensions.
1716 case tok::pp_define_target:
1717 return HandleDefineDirective(Result, true);
1718 case tok::pp_define_other_target:
1719 return HandleDefineOtherTargetDirective(Result);
1720 }
1721 break;
1722 }
1723
1724 // If we reached here, the preprocessing token is not valid!
1725 Diag(Result, diag::err_pp_invalid_directive);
1726
1727 // Read the rest of the PP line.
1728 DiscardUntilEndOfDirective();
1729
1730 // Okay, we're done parsing the directive.
1731}
1732
Chris Lattnerd2177732007-07-20 16:59:19 +00001733void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 bool isWarning) {
1735 // Read the rest of the line raw. We do this because we don't want macros
1736 // to be expanded and we don't require that the tokens be valid preprocessing
1737 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1738 // collapse multiple consequtive white space between tokens, but this isn't
1739 // specified by the standard.
1740 std::string Message = CurLexer->ReadToEndOfLine();
1741
1742 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1743 return Diag(Tok, DiagID, Message);
1744}
1745
1746/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1747///
Chris Lattnerd2177732007-07-20 16:59:19 +00001748void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 // Yes, this directive is an extension.
1750 Diag(Tok, diag::ext_pp_ident_directive);
1751
1752 // Read the string argument.
Chris Lattnerd2177732007-07-20 16:59:19 +00001753 Token StrTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 Lex(StrTok);
1755
1756 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001757 if (StrTok.isNot(tok::string_literal) &&
1758 StrTok.isNot(tok::wide_string_literal))
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 return Diag(StrTok, diag::err_pp_malformed_ident);
1760
1761 // Verify that there is nothing after the string, other than EOM.
1762 CheckEndOfDirective("#ident");
1763
1764 if (Callbacks)
1765 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
1766}
1767
1768//===----------------------------------------------------------------------===//
1769// Preprocessor Include Directive Handling.
1770//===----------------------------------------------------------------------===//
1771
1772/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1773/// checked and spelled filename, e.g. as an operand of #include. This returns
1774/// true if the input filename was in <>'s or false if it were in ""'s. The
1775/// caller is expected to provide a buffer that is large enough to hold the
1776/// spelling of the filename, but is also expected to handle the case when
1777/// this method decides to use a different buffer.
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001778bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 const char *&BufStart,
1780 const char *&BufEnd) {
1781 // Get the text form of the filename.
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1783
1784 // Make sure the filename is <x> or "x".
1785 bool isAngled;
1786 if (BufStart[0] == '<') {
1787 if (BufEnd[-1] != '>') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001788 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 BufStart = 0;
1790 return true;
1791 }
1792 isAngled = true;
1793 } else if (BufStart[0] == '"') {
1794 if (BufEnd[-1] != '"') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001795 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 BufStart = 0;
1797 return true;
1798 }
1799 isAngled = false;
1800 } else {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001801 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 BufStart = 0;
1803 return true;
1804 }
1805
1806 // Diagnose #include "" as invalid.
1807 if (BufEnd-BufStart <= 2) {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001808 Diag(Loc, diag::err_pp_empty_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 BufStart = 0;
1810 return "";
1811 }
1812
1813 // Skip the brackets.
1814 ++BufStart;
1815 --BufEnd;
1816 return isAngled;
1817}
1818
Chris Lattner706ab502007-07-23 04:56:47 +00001819/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1820/// from a macro as multiple tokens, which need to be glued together. This
1821/// occurs for code like:
1822/// #define FOO <a/b.h>
1823/// #include FOO
1824/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1825///
1826/// This code concatenates and consumes tokens up to the '>' token. It returns
1827/// false if the > was found, otherwise it returns true if it finds and consumes
1828/// the EOM marker.
1829static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1830 Preprocessor &PP) {
1831 Token CurTok;
1832
1833 PP.Lex(CurTok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001834 while (CurTok.isNot(tok::eom)) {
Chris Lattner706ab502007-07-23 04:56:47 +00001835 // Append the spelling of this token to the buffer. If there was a space
1836 // before it, add it now.
1837 if (CurTok.hasLeadingSpace())
1838 FilenameBuffer.push_back(' ');
1839
1840 // Get the spelling of the token, directly into FilenameBuffer if possible.
1841 unsigned PreAppendSize = FilenameBuffer.size();
1842 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1843
1844 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1845 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1846
1847 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1848 if (BufPtr != &FilenameBuffer[PreAppendSize])
1849 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1850
1851 // Resize FilenameBuffer to the correct size.
1852 if (CurTok.getLength() != ActualLen)
1853 FilenameBuffer.resize(PreAppendSize+ActualLen);
1854
1855 // If we found the '>' marker, return success.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001856 if (CurTok.is(tok::greater))
Chris Lattner706ab502007-07-23 04:56:47 +00001857 return false;
1858
1859 PP.Lex(CurTok);
1860 }
1861
1862 // If we hit the eom marker, emit an error and return true so that the caller
1863 // knows the EOM has been read.
1864 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1865 return true;
1866}
1867
Reid Spencer5f016e22007-07-11 17:01:13 +00001868/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1869/// file to be included from the lexer, then include it! This is a common
1870/// routine with functionality shared between #include, #include_next and
1871/// #import.
Chris Lattnerd2177732007-07-20 16:59:19 +00001872void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 const DirectoryLookup *LookupFrom,
1874 bool isImport) {
1875
Chris Lattnerd2177732007-07-20 16:59:19 +00001876 Token FilenameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 CurLexer->LexIncludeFilename(FilenameTok);
1878
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 // Reserve a buffer to get the spelling.
1880 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner706ab502007-07-23 04:56:47 +00001881 const char *FilenameStart, *FilenameEnd;
1882
1883 switch (FilenameTok.getKind()) {
1884 case tok::eom:
1885 // If the token kind is EOM, the error has already been diagnosed.
1886 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001887
Chris Lattner706ab502007-07-23 04:56:47 +00001888 case tok::angle_string_literal:
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001889 case tok::string_literal: {
Chris Lattner706ab502007-07-23 04:56:47 +00001890 FilenameBuffer.resize(FilenameTok.getLength());
1891 FilenameStart = &FilenameBuffer[0];
1892 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1893 FilenameEnd = FilenameStart+Len;
1894 break;
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001895 }
Chris Lattner706ab502007-07-23 04:56:47 +00001896
1897 case tok::less:
1898 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1899 // case, glue the tokens together into FilenameBuffer and interpret those.
1900 FilenameBuffer.push_back('<');
1901 if (ConcatenateIncludeName(FilenameBuffer, *this))
1902 return; // Found <eom> but no ">"? Diagnostic already emitted.
1903 FilenameStart = &FilenameBuffer[0];
1904 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1905 break;
1906 default:
1907 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1908 DiscardUntilEndOfDirective();
1909 return;
1910 }
1911
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001912 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 FilenameStart, FilenameEnd);
1914 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1915 // error.
Chris Lattner706ab502007-07-23 04:56:47 +00001916 if (FilenameStart == 0) {
1917 DiscardUntilEndOfDirective();
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 return;
Chris Lattner706ab502007-07-23 04:56:47 +00001919 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001920
1921 // Verify that there is nothing after the filename, other than EOM. Use the
1922 // preprocessor to lex this in case lexing the filename entered a macro.
1923 CheckEndOfDirective("#include");
1924
1925 // Check that we don't have infinite #include recursion.
1926 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
1927 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1928
1929 // Search include directories.
1930 const DirectoryLookup *CurDir;
1931 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1932 isAngled, LookupFrom, CurDir);
1933 if (File == 0)
1934 return Diag(FilenameTok, diag::err_pp_file_not_found,
1935 std::string(FilenameStart, FilenameEnd));
1936
1937 // Ask HeaderInfo if we should enter this #include file.
1938 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1939 // If it returns true, #including this file will have no effect.
1940 return;
1941 }
1942
1943 // Look up the file, create a File ID for it.
1944 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
1945 if (FileID == 0)
1946 return Diag(FilenameTok, diag::err_pp_file_not_found,
1947 std::string(FilenameStart, FilenameEnd));
1948
1949 // Finally, if all is good, enter the new file!
1950 EnterSourceFile(FileID, CurDir);
1951}
1952
1953/// HandleIncludeNextDirective - Implements #include_next.
1954///
Chris Lattnerd2177732007-07-20 16:59:19 +00001955void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1957
1958 // #include_next is like #include, except that we start searching after
1959 // the current found directory. If we can't do this, issue a
1960 // diagnostic.
1961 const DirectoryLookup *Lookup = CurDirLookup;
1962 if (isInPrimaryFile()) {
1963 Lookup = 0;
1964 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1965 } else if (Lookup == 0) {
1966 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1967 } else {
1968 // Start looking up in the next directory.
1969 ++Lookup;
1970 }
1971
1972 return HandleIncludeDirective(IncludeNextTok, Lookup);
1973}
1974
1975/// HandleImportDirective - Implements #import.
1976///
Chris Lattnerd2177732007-07-20 16:59:19 +00001977void Preprocessor::HandleImportDirective(Token &ImportTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 Diag(ImportTok, diag::ext_pp_import_directive);
1979
1980 return HandleIncludeDirective(ImportTok, 0, true);
1981}
1982
1983//===----------------------------------------------------------------------===//
1984// Preprocessor Macro Directive Handling.
1985//===----------------------------------------------------------------------===//
1986
1987/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1988/// definition has just been read. Lex the rest of the arguments and the
1989/// closing ), updating MI with what we learn. Return true if an error occurs
1990/// parsing the arg list.
1991bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner25c96482007-07-14 22:46:43 +00001992 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1993
Chris Lattnerd2177732007-07-20 16:59:19 +00001994 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 while (1) {
1996 LexUnexpandedToken(Tok);
1997 switch (Tok.getKind()) {
1998 case tok::r_paren:
1999 // Found the end of the argument list.
Chris Lattner25c96482007-07-14 22:46:43 +00002000 if (Arguments.empty()) { // #define FOO()
2001 MI->setArgumentList(Arguments.begin(), Arguments.end());
2002 return false;
2003 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // Otherwise we have #define FOO(A,)
2005 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2006 return true;
2007 case tok::ellipsis: // #define X(... -> C99 varargs
2008 // Warn if use of C99 feature in non-C99 mode.
2009 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
2010
2011 // Lex the token after the identifier.
2012 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002013 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2015 return true;
2016 }
2017 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner25c96482007-07-14 22:46:43 +00002018 Arguments.push_back(Ident__VA_ARGS__);
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 MI->setIsC99Varargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002020 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 return false;
2022 case tok::eom: // #define X(
2023 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2024 return true;
2025 default:
2026 // Handle keywords and identifiers here to accept things like
2027 // #define Foo(for) for.
2028 IdentifierInfo *II = Tok.getIdentifierInfo();
2029 if (II == 0) {
2030 // #define X(1
2031 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2032 return true;
2033 }
2034
2035 // If this is already used as an argument, it is used multiple times (e.g.
2036 // #define X(A,A.
Chris Lattner25c96482007-07-14 22:46:43 +00002037 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2038 Arguments.end()) { // C99 6.10.3p6
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2040 return true;
2041 }
2042
2043 // Add the argument to the macro info.
Chris Lattner25c96482007-07-14 22:46:43 +00002044 Arguments.push_back(II);
Reid Spencer5f016e22007-07-11 17:01:13 +00002045
2046 // Lex the token after the identifier.
2047 LexUnexpandedToken(Tok);
2048
2049 switch (Tok.getKind()) {
2050 default: // #define X(A B
2051 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2052 return true;
2053 case tok::r_paren: // #define X(A)
Chris Lattner25c96482007-07-14 22:46:43 +00002054 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 return false;
2056 case tok::comma: // #define X(A,
2057 break;
2058 case tok::ellipsis: // #define X(A... -> GCC extension
2059 // Diagnose extension.
2060 Diag(Tok, diag::ext_named_variadic_macro);
2061
2062 // Lex the token after the identifier.
2063 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002064 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2066 return true;
2067 }
2068
2069 MI->setIsGNUVarargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002070 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 return false;
2072 }
2073 }
2074 }
2075}
2076
2077/// HandleDefineDirective - Implements #define. This consumes the entire macro
2078/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2079/// true, then this is a "#define_target", otherwise this is a "#define".
2080///
Chris Lattnerd2177732007-07-20 16:59:19 +00002081void Preprocessor::HandleDefineDirective(Token &DefineTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 bool isTargetSpecific) {
2083 ++NumDefined;
2084
Chris Lattnerd2177732007-07-20 16:59:19 +00002085 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 ReadMacroName(MacroNameTok, 1);
2087
2088 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002089 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 return;
Chris Lattnerc215bd62007-07-14 22:11:41 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 // If we are supposed to keep comments in #defines, reenable comment saving
2093 // mode.
2094 CurLexer->KeepCommentMode = KeepMacroComments;
2095
2096 // Create the new macro.
2097 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
2098 if (isTargetSpecific) MI->setIsTargetSpecific();
2099
2100 // If the identifier is an 'other target' macro, clear this bit.
2101 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2102
2103
Chris Lattnerd2177732007-07-20 16:59:19 +00002104 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 LexUnexpandedToken(Tok);
2106
2107 // If this is a function-like macro definition, parse the argument list,
2108 // marking each of the identifiers as being used as macro arguments. Also,
2109 // check other constraints on the first token of the macro body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002110 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // If there is no body to this macro, we have no special handling here.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002112 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 // This is a function-like macro definition. Read the argument list.
2114 MI->setIsFunctionLike();
2115 if (ReadMacroDefinitionArgList(MI)) {
2116 // Forget about MI.
2117 delete MI;
2118 // Throw away the rest of the line.
2119 if (CurLexer->ParsingPreprocessorDirective)
2120 DiscardUntilEndOfDirective();
2121 return;
2122 }
2123
2124 // Read the first token after the arg list for down below.
2125 LexUnexpandedToken(Tok);
2126 } else if (!Tok.hasLeadingSpace()) {
2127 // C99 requires whitespace between the macro definition and the body. Emit
2128 // a diagnostic for something like "#define X+".
2129 if (Features.C99) {
2130 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2131 } else {
2132 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2133 // one in some cases!
2134 }
2135 } else {
2136 // This is a normal token with leading space. Clear the leading space
2137 // marker on the first token to get proper expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00002138 Tok.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 }
2140
2141 // If this is a definition of a variadic C99 function-like macro, not using
2142 // the GNU named varargs extension, enabled __VA_ARGS__.
2143
2144 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2145 // This gets unpoisoned where it is allowed.
2146 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2147 if (MI->isC99Varargs())
2148 Ident__VA_ARGS__->setIsPoisoned(false);
2149
2150 // Read the rest of the macro body.
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002151 if (MI->isObjectLike()) {
2152 // Object-like macros are very simple, just read their body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002153 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002154 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 // Get the next token of the macro.
2156 LexUnexpandedToken(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002157 }
2158
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002159 } else {
2160 // Otherwise, read the body of a function-like macro. This has to validate
2161 // the # (stringize) operator.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002162 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002163 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002164
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002165 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2166 // parameters in function-like macro expansions.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002167 if (Tok.isNot(tok::hash)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002168 // Get the next token of the macro.
2169 LexUnexpandedToken(Tok);
2170 continue;
2171 }
2172
2173 // Get the next token of the macro.
2174 LexUnexpandedToken(Tok);
2175
2176 // Not a macro arg identifier?
2177 if (!Tok.getIdentifierInfo() ||
2178 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2179 Diag(Tok, diag::err_pp_stringize_not_parameter);
2180 delete MI;
2181
2182 // Disable __VA_ARGS__ again.
2183 Ident__VA_ARGS__->setIsPoisoned(true);
2184 return;
2185 }
2186
2187 // Things look ok, add the param name token to the macro.
2188 MI->AddTokenToBody(Tok);
2189
2190 // Get the next token of the macro.
2191 LexUnexpandedToken(Tok);
2192 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002193 }
2194
Chris Lattnerc215bd62007-07-14 22:11:41 +00002195
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 // Disable __VA_ARGS__ again.
2197 Ident__VA_ARGS__->setIsPoisoned(true);
2198
2199 // Check that there is no paste (##) operator at the begining or end of the
2200 // replacement list.
2201 unsigned NumTokens = MI->getNumTokens();
2202 if (NumTokens != 0) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002203 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2205 delete MI;
2206 return;
2207 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002208 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2210 delete MI;
2211 return;
2212 }
2213 }
2214
2215 // If this is the primary source file, remember that this macro hasn't been
2216 // used yet.
2217 if (isInPrimaryFile())
2218 MI->setIsUsed(false);
2219
2220 // Finally, if this identifier already had a macro defined for it, verify that
2221 // the macro bodies are identical and free the old definition.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002222 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 if (!OtherMI->isUsed())
2224 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2225
2226 // Macros must be identical. This means all tokes and whitespace separation
2227 // must be the same. C99 6.10.3.2.
2228 if (!MI->isIdenticalTo(*OtherMI, *this)) {
2229 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2230 MacroNameTok.getIdentifierInfo()->getName());
2231 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2232 }
2233 delete OtherMI;
2234 }
2235
Chris Lattnercc1a8752007-10-07 08:44:20 +00002236 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002237}
2238
2239/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattnerd2177732007-07-20 16:59:19 +00002240void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2241 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 ReadMacroName(MacroNameTok, 1);
2243
2244 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002245 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 return;
2247
2248 // Check to see if this is the last token on the #undef line.
2249 CheckEndOfDirective("#define_other_target");
2250
2251 // If there is already a macro defined by this name, turn it into a
2252 // target-specific define.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002253 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 MI->setIsTargetSpecific(true);
2255 return;
2256 }
2257
2258 // Mark the identifier as being a macro on some other target.
2259 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2260}
2261
2262
2263/// HandleUndefDirective - Implements #undef.
2264///
Chris Lattnerd2177732007-07-20 16:59:19 +00002265void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002266 ++NumUndefined;
2267
Chris Lattnerd2177732007-07-20 16:59:19 +00002268 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 ReadMacroName(MacroNameTok, 2);
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("#undef");
2277
2278 // Okay, we finally have a valid identifier to undef.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002279 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Reid Spencer5f016e22007-07-11 17:01:13 +00002280
2281 // #undef untaints an identifier if it were marked by define_other_target.
2282 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2283
2284 // If the macro is not defined, this is a noop undef, just return.
2285 if (MI == 0) return;
2286
2287 if (!MI->isUsed())
2288 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2289
2290 // Free macro definition.
2291 delete MI;
Chris Lattnercc1a8752007-10-07 08:44:20 +00002292 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002293}
2294
2295
2296//===----------------------------------------------------------------------===//
2297// Preprocessor Conditional Directive Handling.
2298//===----------------------------------------------------------------------===//
2299
2300/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
2301/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2302/// if any tokens have been returned or pp-directives activated before this
2303/// #ifndef has been lexed.
2304///
Chris Lattnerd2177732007-07-20 16:59:19 +00002305void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 bool ReadAnyTokensBeforeDirective) {
2307 ++NumIf;
Chris Lattnerd2177732007-07-20 16:59:19 +00002308 Token DirectiveTok = Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00002309
Chris Lattnerd2177732007-07-20 16:59:19 +00002310 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 ReadMacroName(MacroNameTok);
2312
2313 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002314 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerf37bb252007-09-24 05:14:57 +00002315 // Skip code until we get to #endif. This helps with recovery by not
2316 // emitting an error when the #endif is reached.
2317 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2318 /*Foundnonskip*/false, /*FoundElse*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 return;
Chris Lattnerf37bb252007-09-24 05:14:57 +00002320 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002321
2322 // Check to see if this is the last token on the #if[n]def line.
2323 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2324
2325 // If the start of a top-level #ifdef, inform MIOpt.
2326 if (!ReadAnyTokensBeforeDirective &&
2327 CurLexer->getConditionalStackDepth() == 0) {
2328 assert(isIfndef && "#ifdef shouldn't reach here");
2329 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2330 }
2331
2332 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnercc1a8752007-10-07 08:44:20 +00002333 MacroInfo *MI = getMacroInfo(MII);
Reid Spencer5f016e22007-07-11 17:01:13 +00002334
2335 // If there is a macro, process it.
2336 if (MI) {
2337 // Mark it used.
2338 MI->setIsUsed(true);
2339
2340 // If this is the first use of a target-specific macro, warn about it.
2341 if (MI->isTargetSpecific()) {
2342 MI->setIsTargetSpecific(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002343 getTargetInfo().DiagnoseNonPortability(
2344 getFullLoc(MacroNameTok.getLocation()),
2345 diag::port_target_macro_use);
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 }
2347 } else {
2348 // Use of a target-specific macro for some other target? If so, warn.
2349 if (MII->isOtherTargetMacro()) {
2350 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002351 getTargetInfo().DiagnoseNonPortability(
2352 getFullLoc(MacroNameTok.getLocation()),
2353 diag::port_target_macro_use);
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 }
2355 }
2356
2357 // Should we include the stuff contained by this directive?
2358 if (!MI == isIfndef) {
2359 // Yes, remember that we are inside a conditional, then lex the next token.
2360 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
2361 /*foundnonskip*/true, /*foundelse*/false);
2362 } else {
2363 // No, skip the contents of this block and return the first token after it.
2364 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2365 /*Foundnonskip*/false,
2366 /*FoundElse*/false);
2367 }
2368}
2369
2370/// HandleIfDirective - Implements the #if directive.
2371///
Chris Lattnerd2177732007-07-20 16:59:19 +00002372void Preprocessor::HandleIfDirective(Token &IfToken,
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 bool ReadAnyTokensBeforeDirective) {
2374 ++NumIf;
2375
2376 // Parse and evaluation the conditional expression.
2377 IdentifierInfo *IfNDefMacro = 0;
2378 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2379
2380 // Should we include the stuff contained by this directive?
2381 if (ConditionalTrue) {
2382 // If this condition is equivalent to #ifndef X, and if this is the first
2383 // directive seen, handle it for the multiple-include optimization.
2384 if (!ReadAnyTokensBeforeDirective &&
2385 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2386 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2387
2388 // Yes, remember that we are inside a conditional, then lex the next token.
2389 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2390 /*foundnonskip*/true, /*foundelse*/false);
2391 } else {
2392 // No, skip the contents of this block and return the first token after it.
2393 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2394 /*FoundElse*/false);
2395 }
2396}
2397
2398/// HandleEndifDirective - Implements the #endif directive.
2399///
Chris Lattnerd2177732007-07-20 16:59:19 +00002400void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002401 ++NumEndif;
2402
2403 // Check that this is the whole directive.
2404 CheckEndOfDirective("#endif");
2405
2406 PPConditionalInfo CondInfo;
2407 if (CurLexer->popConditionalLevel(CondInfo)) {
2408 // No conditionals on the stack: this is an #endif without an #if.
2409 return Diag(EndifToken, diag::err_pp_endif_without_if);
2410 }
2411
2412 // If this the end of a top-level #endif, inform MIOpt.
2413 if (CurLexer->getConditionalStackDepth() == 0)
2414 CurLexer->MIOpt.ExitTopLevelConditional();
2415
2416 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
2417 "This code should only be reachable in the non-skipping case!");
2418}
2419
2420
Chris Lattnerd2177732007-07-20 16:59:19 +00002421void Preprocessor::HandleElseDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 ++NumElse;
2423
2424 // #else directive in a non-skipping conditional... start skipping.
2425 CheckEndOfDirective("#else");
2426
2427 PPConditionalInfo CI;
2428 if (CurLexer->popConditionalLevel(CI))
2429 return Diag(Result, diag::pp_err_else_without_if);
2430
2431 // If this is a top-level #else, inform the MIOpt.
2432 if (CurLexer->getConditionalStackDepth() == 0)
2433 CurLexer->MIOpt.FoundTopLevelElse();
2434
2435 // If this is a #else with a #else before it, report the error.
2436 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2437
2438 // Finally, skip the rest of the contents of this block and return the first
2439 // token after it.
2440 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2441 /*FoundElse*/true);
2442}
2443
Chris Lattnerd2177732007-07-20 16:59:19 +00002444void Preprocessor::HandleElifDirective(Token &ElifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002445 ++NumElse;
2446
2447 // #elif directive in a non-skipping conditional... start skipping.
2448 // We don't care what the condition is, because we will always skip it (since
2449 // the block immediately before it was included).
2450 DiscardUntilEndOfDirective();
2451
2452 PPConditionalInfo CI;
2453 if (CurLexer->popConditionalLevel(CI))
2454 return Diag(ElifToken, diag::pp_err_elif_without_if);
2455
2456 // If this is a top-level #elif, inform the MIOpt.
2457 if (CurLexer->getConditionalStackDepth() == 0)
2458 CurLexer->MIOpt.FoundTopLevelElse();
2459
2460 // If this is a #elif with a #else before it, report the error.
2461 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2462
2463 // Finally, skip the rest of the contents of this block and return the first
2464 // token after it.
2465 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2466 /*FoundElse*/CI.FoundElse);
2467}
2468