blob: ba96fad92cf41c200844452a68d6ebb8f9a35b32 [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
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) {
123 Diags.Report(Loc, DiagID);
124}
125
126void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
127 const std::string &Msg) {
128 Diags.Report(Loc, DiagID, &Msg, 1);
129}
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;
136 std::cerr << "\t";
137 if (Tok.isAtStartOfLine())
138 std::cerr << " [StartOfLine]";
139 if (Tok.hasLeadingSpace())
140 std::cerr << " [LeadingSpace]";
141 if (Tok.isExpandDisabled())
142 std::cerr << " [ExpandDisabled]";
143 if (Tok.needsCleaning()) {
144 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
145 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
146 << "']";
147 }
148}
149
150void Preprocessor::DumpMacro(const MacroInfo &MI) const {
151 std::cerr << "MACRO: ";
152 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
153 DumpToken(MI.getReplacementToken(i));
154 std::cerr << " ";
155 }
156 std::cerr << "\n";
157}
158
159void Preprocessor::PrintStats() {
160 std::cerr << "\n*** Preprocessor Stats:\n";
161 std::cerr << NumDirectives << " directives found:\n";
162 std::cerr << " " << NumDefined << " #define.\n";
163 std::cerr << " " << NumUndefined << " #undef.\n";
164 std::cerr << " #include/#include_next/#import:\n";
165 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
166 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
167 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
168 std::cerr << " " << NumElse << " #else/#elif.\n";
169 std::cerr << " " << NumEndif << " #endif.\n";
170 std::cerr << " " << NumPragma << " #pragma.\n";
171 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
172
173 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
174 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
175 << NumFastMacroExpanded << " on the fast path.\n";
176 std::cerr << (NumFastTokenPaste+NumTokenPaste)
177 << " token paste (##) operations performed, "
178 << NumFastTokenPaste << " on the fast path.\n";
179}
180
181//===----------------------------------------------------------------------===//
182// Token Spelling
183//===----------------------------------------------------------------------===//
184
185
186/// getSpelling() - Return the 'spelling' of this token. The spelling of a
187/// token are the characters used to represent the token in the source file
188/// after trigraph expansion and escaped-newline folding. In particular, this
189/// wants to get the true, uncanonicalized, spelling of things like digraphs
190/// UCNs, etc.
Chris Lattnerd2177732007-07-20 16:59:19 +0000191std::string Preprocessor::getSpelling(const Token &Tok) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
193
194 // If this token contains nothing interesting, return it directly.
195 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
196 if (!Tok.needsCleaning())
197 return std::string(TokStart, TokStart+Tok.getLength());
198
199 std::string Result;
200 Result.reserve(Tok.getLength());
201
202 // Otherwise, hard case, relex the characters into the string.
203 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
204 Ptr != End; ) {
205 unsigned CharSize;
206 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
207 Ptr += CharSize;
208 }
209 assert(Result.size() != unsigned(Tok.getLength()) &&
210 "NeedsCleaning flag set on something that didn't need cleaning!");
211 return Result;
212}
213
214/// getSpelling - This method is used to get the spelling of a token into a
215/// preallocated buffer, instead of as an std::string. The caller is required
216/// to allocate enough space for the token, which is guaranteed to be at least
217/// Tok.getLength() bytes long. The actual length of the token is returned.
218///
219/// Note that this method may do two possible things: it may either fill in
220/// the buffer specified with characters, or it may *change the input pointer*
221/// to point to a constant buffer with the data already in it (avoiding a
222/// copy). The caller is not allowed to modify the returned buffer pointer
223/// if an internal buffer is returned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000224unsigned Preprocessor::getSpelling(const Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 const char *&Buffer) const {
226 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
227
228 // If this token is an identifier, just return the string from the identifier
229 // table, which is very quick.
230 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
231 Buffer = II->getName();
Chris Lattner0f670322007-07-22 22:50:09 +0000232
233 // Return the length of the token. If the token needed cleaning, don't
234 // include the size of the newlines or trigraphs in it.
235 if (!Tok.needsCleaning())
236 return Tok.getLength();
237 else
238 return strlen(Buffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 }
240
241 // Otherwise, compute the start of the token in the input lexer buffer.
242 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
243
244 // If this token contains nothing interesting, return it directly.
245 if (!Tok.needsCleaning()) {
246 Buffer = TokStart;
247 return Tok.getLength();
248 }
249 // Otherwise, hard case, relex the characters into the string.
250 char *OutBuf = const_cast<char*>(Buffer);
251 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
252 Ptr != End; ) {
253 unsigned CharSize;
254 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
255 Ptr += CharSize;
256 }
257 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
258 "NeedsCleaning flag set on something that didn't need cleaning!");
259
260 return OutBuf-Buffer;
261}
262
263
264/// CreateString - Plop the specified string into a scratch buffer and return a
265/// location for it. If specified, the source location provides a source
266/// location for the token.
267SourceLocation Preprocessor::
268CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
269 if (SLoc.isValid())
270 return ScratchBuf->getToken(Buf, Len, SLoc);
271 return ScratchBuf->getToken(Buf, Len);
272}
273
274
Chris Lattner97ba77c2007-07-16 06:48:38 +0000275/// AdvanceToTokenCharacter - Given a location that specifies the start of a
276/// token, return a new location that specifies a character within the token.
277SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
278 unsigned CharNo) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000279 // If they request the first char of the token, we're trivially done. If this
280 // is a macro expansion, it doesn't make sense to point to a character within
281 // the instantiation point (the name). We could point to the source
282 // character, but without also pointing to instantiation info, this is
283 // confusing.
284 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000285
286 // Figure out how many physical characters away the specified logical
287 // character is. This needs to take into consideration newlines and
288 // trigraphs.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000289 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
290 unsigned PhysOffset = 0;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000291
292 // The usual case is that tokens don't contain anything interesting. Skip
293 // over the uninteresting characters. If a token only consists of simple
294 // chars, this method is extremely fast.
295 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattner9dc1f532007-07-20 16:37:10 +0000296 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000297
298 // If we have a character that may be a trigraph or escaped newline, create a
299 // lexer to parse it correctly.
Chris Lattner97ba77c2007-07-16 06:48:38 +0000300 if (CharNo != 0) {
301 // Create a lexer starting at this token position.
Chris Lattner25bdb512007-07-20 16:52:03 +0000302 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattnerd2177732007-07-20 16:59:19 +0000303 Token Tok;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000304 // Skip over characters the remaining characters.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000305 const char *TokStartPtr = TokPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000306 for (; CharNo; --CharNo)
307 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattner9dc1f532007-07-20 16:37:10 +0000308
309 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000310 }
Chris Lattner9dc1f532007-07-20 16:37:10 +0000311
312 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner97ba77c2007-07-16 06:48:38 +0000313}
314
315
Chris Lattner53b0dab2007-10-09 22:10:18 +0000316//===----------------------------------------------------------------------===//
317// Preprocessor Initialization Methods
318//===----------------------------------------------------------------------===//
319
320// Append a #define line to Buf for Macro. Macro should be of the form XXX,
321// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
322// "#define XXX Y z W". To get a #define with no value, use "XXX=".
323static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
324 const char *Command = "#define ") {
325 Buf.insert(Buf.end(), Command, Command+strlen(Command));
326 if (const char *Equal = strchr(Macro, '=')) {
327 // Turn the = into ' '.
328 Buf.insert(Buf.end(), Macro, Equal);
329 Buf.push_back(' ');
330 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
331 } else {
332 // Push "macroname 1".
333 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
334 Buf.push_back(' ');
335 Buf.push_back('1');
336 }
337 Buf.push_back('\n');
338}
339
340
341static void InitializePredefinedMacros(Preprocessor &PP,
342 std::vector<char> &Buf) {
343 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
344 // and __DATE__ etc.
345#if 0
346 /* __STDC__ has the value 1 under normal circumstances.
347 However, if (a) we are in a system header, (b) the option
348 stdc_0_in_system_headers is true (set by target config), and
349 (c) we are not in strictly conforming mode, then it has the
350 value 0. (b) and (c) are already checked in cpp_init_builtins. */
351 //case BT_STDC:
352 if (cpp_in_system_header (pfile))
353 number = 0;
354 else
355 number = 1;
356 break;
357#endif
358 // These should all be defined in the preprocessor according to the
359 // current language configuration.
360 DefineBuiltinMacro(Buf, "__STDC__=1");
361 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
362 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
363 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
364 else if (0) // STDC94 ?
365 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
366
367 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
368 if (PP.getLangOptions().ObjC1)
369 DefineBuiltinMacro(Buf, "__OBJC__=1");
370 if (PP.getLangOptions().ObjC2)
371 DefineBuiltinMacro(Buf, "__OBJC2__=1");
372
373 // Get the target #defines.
374 PP.getTargetInfo().getTargetDefines(Buf);
375
376 // Compiler set macros.
377 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
378 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1030");
379 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
380 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
381 DefineBuiltinMacro(Buf, "__GNUC__=4");
382 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
383 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
384 "build 5250)\"");
385
386 // Build configuration options.
387 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
388 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
389 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
390 DefineBuiltinMacro(Buf, "__PIC__=1");
391
392
393 if (PP.getLangOptions().CPlusPlus) {
394 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
395 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
396 DefineBuiltinMacro(Buf, "__GNUG__=4");
397 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
398 DefineBuiltinMacro(Buf, "__cplusplus=1");
399 DefineBuiltinMacro(Buf, "__private_extern__=extern");
400 }
401
402 // FIXME: Should emit a #line directive here.
403}
404
405
406/// EnterMainSourceFile - Enter the specified FileID as the main source file,
407/// which implicitly adds the builting defines etc.
408void Preprocessor::EnterMainSourceFile(unsigned MainFileID) {
409 // Enter the main file source buffer.
410 EnterSourceFile(MainFileID, 0);
411
412
413 std::vector<char> PrologFile;
414 PrologFile.reserve(4080);
415
416 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
417 InitializePredefinedMacros(*this, PrologFile);
418
419 // Add on the predefines from the driver.
420 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
421
422 // Memory buffer must end with a null byte!
423 PrologFile.push_back(0);
424
425 // Now that we have emitted the predefined macros, #includes, etc into
426 // PrologFile, preprocess it to populate the initial preprocessor state.
427 llvm::MemoryBuffer *SB =
428 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
429 "<predefines>");
430 assert(SB && "Cannot fail to create predefined source buffer");
431 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
432 assert(FileID && "Could not create FileID for predefines?");
433
434 // Start parsing the predefines.
435 EnterSourceFile(FileID, 0);
436}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000437
Reid Spencer5f016e22007-07-11 17:01:13 +0000438//===----------------------------------------------------------------------===//
439// Source File Location Methods.
440//===----------------------------------------------------------------------===//
441
442/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
443/// return null on failure. isAngled indicates whether the file reference is
444/// for system #include's or not (i.e. using <> instead of "").
445const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
446 const char *FilenameEnd,
447 bool isAngled,
448 const DirectoryLookup *FromDir,
449 const DirectoryLookup *&CurDir) {
450 // If the header lookup mechanism may be relative to the current file, pass in
451 // info about where the current file is.
452 const FileEntry *CurFileEnt = 0;
453 if (!FromDir) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000454 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
455 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 }
457
458 // Do a standard file entry lookup.
459 CurDir = CurDirLookup;
460 const FileEntry *FE =
461 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
462 isAngled, FromDir, CurDir, CurFileEnt);
463 if (FE) return FE;
464
465 // Otherwise, see if this is a subframework header. If so, this is relative
466 // to one of the headers on the #include stack. Walk the list of the current
467 // headers on the #include stack and pass them to HeaderInfo.
468 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000469 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
471 CurFileEnt)))
472 return FE;
473 }
474
475 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
476 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
477 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000478 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
480 CurFileEnt)))
481 return FE;
482 }
483 }
484
485 // Otherwise, we really couldn't find the file.
486 return 0;
487}
488
489/// isInPrimaryFile - Return true if we're in the top-level file, not in a
490/// #include.
491bool Preprocessor::isInPrimaryFile() const {
492 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000493 return IncludeMacroStack.empty();
Reid Spencer5f016e22007-07-11 17:01:13 +0000494
495 // If there are any stacked lexers, we're in a #include.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000496 assert(IncludeMacroStack[0].TheLexer &&
497 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
498 "Top level include stack isn't our primary lexer?");
499 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 if (IncludeMacroStack[i].TheLexer &&
501 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000502 return false;
503 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000504}
505
506/// getCurrentLexer - Return the current file lexer being lexed from. Note
507/// that this ignores any potentially active macro expansions and _Pragma
508/// expansions going on at the time.
509Lexer *Preprocessor::getCurrentFileLexer() const {
510 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
511
512 // Look for a stacked lexer.
513 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
514 Lexer *L = IncludeMacroStack[i-1].TheLexer;
515 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
516 return L;
517 }
518 return 0;
519}
520
521
522/// EnterSourceFile - Add a source file to the top of the include stack and
523/// start lexing tokens from it instead of the current buffer. Return true
524/// on failure.
525void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000526 const DirectoryLookup *CurDir) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
528 ++NumEnteredSourceFiles;
529
530 if (MaxIncludeStackDepth < IncludeMacroStack.size())
531 MaxIncludeStackDepth = IncludeMacroStack.size();
532
Chris Lattner25bdb512007-07-20 16:52:03 +0000533 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 EnterSourceFileWithLexer(TheLexer, CurDir);
535}
536
537/// EnterSourceFile - Add a source file to the top of the include stack and
538/// start lexing tokens from it instead of the current buffer.
539void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
540 const DirectoryLookup *CurDir) {
541
542 // Add the current lexer to the include stack.
543 if (CurLexer || CurMacroExpander)
544 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
545 CurMacroExpander));
546
547 CurLexer = TheLexer;
548 CurDirLookup = CurDir;
549 CurMacroExpander = 0;
550
551 // Notify the client, if desired, that we are in a new source file.
552 if (Callbacks && !CurLexer->Is_PragmaLexer) {
553 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
554
555 // Get the file entry for the current file.
556 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +0000557 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 FileType = HeaderInfo.getFileDirFlavor(FE);
559
Chris Lattner9dc1f532007-07-20 16:37:10 +0000560 Callbacks->FileChanged(CurLexer->getFileLoc(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 PPCallbacks::EnterFile, FileType);
562 }
563}
564
565
566
567/// EnterMacro - Add a Macro to the top of the include stack and start lexing
568/// tokens from it instead of the current buffer.
Chris Lattnerd2177732007-07-20 16:59:19 +0000569void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
571 CurMacroExpander));
572 CurLexer = 0;
573 CurDirLookup = 0;
574
Chris Lattner9594acf2007-07-15 00:25:26 +0000575 if (NumCachedMacroExpanders == 0) {
576 CurMacroExpander = new MacroExpander(Tok, Args, *this);
577 } else {
578 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
579 CurMacroExpander->Init(Tok, Args);
580 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000581}
582
583/// EnterTokenStream - Add a "macro" context to the top of the include stack,
584/// which will cause the lexer to start returning the specified tokens. Note
585/// that these tokens will be re-macro-expanded when/if expansion is enabled.
586/// This method assumes that the specified stream of tokens has a permanent
587/// owner somewhere, so they do not need to be copied.
Chris Lattnerd2177732007-07-20 16:59:19 +0000588void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 // Save our current state.
590 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
591 CurMacroExpander));
592 CurLexer = 0;
593 CurDirLookup = 0;
594
595 // Create a macro expander to expand from the specified token stream.
Chris Lattner9594acf2007-07-15 00:25:26 +0000596 if (NumCachedMacroExpanders == 0) {
597 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
598 } else {
599 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
600 CurMacroExpander->Init(Toks, NumToks);
601 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000602}
603
604/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
605/// lexer stack. This should only be used in situations where the current
606/// state of the top-of-stack lexer is known.
607void Preprocessor::RemoveTopOfLexerStack() {
608 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattner9594acf2007-07-15 00:25:26 +0000609
610 if (CurMacroExpander) {
611 // Delete or cache the now-dead macro expander.
612 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
613 delete CurMacroExpander;
614 else
615 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
616 } else {
617 delete CurLexer;
618 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 CurLexer = IncludeMacroStack.back().TheLexer;
620 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
621 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
622 IncludeMacroStack.pop_back();
623}
624
625//===----------------------------------------------------------------------===//
626// Macro Expansion Handling.
627//===----------------------------------------------------------------------===//
628
Chris Lattnercc1a8752007-10-07 08:44:20 +0000629/// setMacroInfo - Specify a macro for this identifier.
630///
631void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
632 if (MI == 0) {
633 if (II->hasMacroDefinition()) {
634 Macros.erase(II);
635 II->setHasMacroDefinition(false);
636 }
637 } else {
638 Macros[II] = MI;
639 II->setHasMacroDefinition(true);
640 }
641}
642
Reid Spencer5f016e22007-07-11 17:01:13 +0000643/// RegisterBuiltinMacro - Register the specified identifier in the identifier
644/// table and mark it as a builtin macro to be expanded.
645IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
646 // Get the identifier.
647 IdentifierInfo *Id = getIdentifierInfo(Name);
648
649 // Mark it as being a macro that is builtin.
650 MacroInfo *MI = new MacroInfo(SourceLocation());
651 MI->setIsBuiltinMacro();
Chris Lattnercc1a8752007-10-07 08:44:20 +0000652 setMacroInfo(Id, MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 return Id;
654}
655
656
657/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
658/// identifier table.
659void Preprocessor::RegisterBuiltinMacros() {
660 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
661 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
662 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
663 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
664 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
665
666 // GCC Extensions.
667 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
668 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
669 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
670}
671
672/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
673/// in its expansion, currently expands to that token literally.
674static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnercc1a8752007-10-07 08:44:20 +0000675 const IdentifierInfo *MacroIdent,
676 Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
678
679 // If the token isn't an identifier, it's always literally expanded.
680 if (II == 0) return true;
681
682 // If the identifier is a macro, and if that macro is enabled, it may be
683 // expanded so it's not a trivial expansion.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000684 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000685 // Fast expanding "#define X X" is ok, because X would be disabled.
686 II != MacroIdent)
687 return false;
688
689 // If this is an object-like macro invocation, it is safe to trivially expand
690 // it.
691 if (MI->isObjectLike()) return true;
692
693 // If this is a function-like macro invocation, it's safe to trivially expand
694 // as long as the identifier is not a macro argument.
695 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
696 I != E; ++I)
697 if (*I == II)
698 return false; // Identifier is a macro argument.
699
700 return true;
701}
702
703
704/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
705/// lexed is a '('. If so, consume the token and return true, if not, this
706/// method should have no observable side-effect on the lexed tokens.
707bool Preprocessor::isNextPPTokenLParen() {
708 // Do some quick tests for rejection cases.
709 unsigned Val;
710 if (CurLexer)
711 Val = CurLexer->isNextPPTokenLParen();
712 else
713 Val = CurMacroExpander->isNextTokenLParen();
714
715 if (Val == 2) {
Chris Lattner0ea793e2007-07-19 00:07:36 +0000716 // We have run off the end. If it's a source file we don't
717 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
718 // macro stack.
719 if (CurLexer)
720 return false;
721 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
723 if (Entry.TheLexer)
724 Val = Entry.TheLexer->isNextPPTokenLParen();
725 else
726 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner0ea793e2007-07-19 00:07:36 +0000727
728 if (Val != 2)
729 break;
730
731 // Ran off the end of a source file?
732 if (Entry.TheLexer)
733 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 }
735 }
736
737 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
738 // have found something that isn't a '(' or we found the end of the
739 // translation unit. In either case, return false.
740 if (Val != 1)
741 return false;
742
Chris Lattnerd2177732007-07-20 16:59:19 +0000743 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000745 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 return true;
747}
748
749/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
750/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000751bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 MacroInfo *MI) {
753
754 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
755 if (MI->isBuiltinMacro()) {
756 ExpandBuiltinMacro(Identifier);
757 return false;
758 }
759
760 // If this is the first use of a target-specific macro, warn about it.
761 if (MI->isTargetSpecific()) {
762 MI->setIsTargetSpecific(false); // Don't warn on second use.
763 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
764 diag::port_target_macro_use);
765 }
766
767 /// Args - If this is a function-like macro expansion, this contains,
768 /// for each macro argument, the list of tokens that were provided to the
769 /// invocation.
770 MacroArgs *Args = 0;
771
772 // If this is a function-like macro, read the arguments.
773 if (MI->isFunctionLike()) {
774 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000775 // name isn't a '(', this macro should not be expanded. Otherwise, consume
776 // it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 if (!isNextPPTokenLParen())
778 return true;
779
780 // Remember that we are now parsing the arguments to a macro invocation.
781 // Preprocessor directives used inside macro arguments are not portable, and
782 // this enables the warning.
783 InMacroArgs = true;
784 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
785
786 // Finished parsing args.
787 InMacroArgs = false;
788
789 // If there was an error parsing the arguments, bail out.
790 if (Args == 0) return false;
791
792 ++NumFnMacroExpanded;
793 } else {
794 ++NumMacroExpanded;
795 }
796
797 // Notice that this macro has been used.
798 MI->setIsUsed(true);
799
800 // If we started lexing a macro, enter the macro expansion body.
801
802 // If this macro expands to no tokens, don't bother to push it onto the
803 // expansion stack, only to take it right back off.
804 if (MI->getNumTokens() == 0) {
805 // No need for arg info.
806 if (Args) Args->destroy();
807
808 // Ignore this macro use, just return the next token in the current
809 // buffer.
810 bool HadLeadingSpace = Identifier.hasLeadingSpace();
811 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
812
813 Lex(Identifier);
814
815 // If the identifier isn't on some OTHER line, inherit the leading
816 // whitespace/first-on-a-line property of this token. This handles
817 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
818 // empty.
819 if (!Identifier.isAtStartOfLine()) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000820 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
821 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 }
823 ++NumFastMacroExpanded;
824 return false;
825
826 } else if (MI->getNumTokens() == 1 &&
Chris Lattnercc1a8752007-10-07 08:44:20 +0000827 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
828 *this)){
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 // Otherwise, if this macro expands into a single trivially-expanded
830 // token: expand it now. This handles common cases like
831 // "#define VAL 42".
832
833 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
834 // identifier to the expanded token.
835 bool isAtStartOfLine = Identifier.isAtStartOfLine();
836 bool hasLeadingSpace = Identifier.hasLeadingSpace();
837
838 // Remember where the token is instantiated.
839 SourceLocation InstantiateLoc = Identifier.getLocation();
840
841 // Replace the result token.
842 Identifier = MI->getReplacementToken(0);
843
844 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattnerd2177732007-07-20 16:59:19 +0000845 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
846 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000847
848 // Update the tokens location to include both its logical and physical
849 // locations.
850 SourceLocation Loc =
851 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
852 Identifier.setLocation(Loc);
853
854 // If this is #define X X, we must mark the result as unexpandible.
855 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnercc1a8752007-10-07 08:44:20 +0000856 if (getMacroInfo(NewII) == MI)
Chris Lattnerd2177732007-07-20 16:59:19 +0000857 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000858
859 // Since this is not an identifier token, it can't be macro expanded, so
860 // we're done.
861 ++NumFastMacroExpanded;
862 return false;
863 }
864
865 // Start expanding the macro.
866 EnterMacro(Identifier, Args);
867
868 // Now that the macro is at the top of the include stack, ask the
869 // preprocessor to read the next token from it.
870 Lex(Identifier);
871 return false;
872}
873
874/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
875/// invoked to read all of the actual arguments specified for the macro
876/// invocation. This returns null on error.
Chris Lattnerd2177732007-07-20 16:59:19 +0000877MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 MacroInfo *MI) {
879 // The number of fixed arguments to parse.
880 unsigned NumFixedArgsLeft = MI->getNumArgs();
881 bool isVariadic = MI->isVariadic();
882
883 // Outer loop, while there are more arguments, keep reading them.
Chris Lattnerd2177732007-07-20 16:59:19 +0000884 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 Tok.setKind(tok::comma);
886 --NumFixedArgsLeft; // Start reading the first arg.
887
888 // ArgTokens - Build up a list of tokens that make up each argument. Each
889 // argument is separated by an EOF token. Use a SmallVector so we can avoid
890 // heap allocations in the common case.
Chris Lattnerd2177732007-07-20 16:59:19 +0000891 llvm::SmallVector<Token, 64> ArgTokens;
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893 unsigned NumActuals = 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000894 while (Tok.is(tok::comma)) {
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000895 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
896 // that we already consumed the first one.
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 unsigned NumParens = 0;
898
899 while (1) {
900 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
901 // an argument value in a macro could expand to ',' or '(' or ')'.
902 LexUnexpandedToken(Tok);
903
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000904 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 Diag(MacroName, diag::err_unterm_macro_invoc);
906 // Do not lose the EOF. Return it to the client.
907 MacroName = Tok;
908 return 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000909 } else if (Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 // If we found the ) token, the macro arg list is done.
911 if (NumParens-- == 0)
912 break;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000913 } else if (Tok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 ++NumParens;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000915 } else if (Tok.is(tok::comma) && NumParens == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 // Comma ends this argument if there are more fixed arguments expected.
917 if (NumFixedArgsLeft)
918 break;
919
920 // If this is not a variadic macro, too many args were specified.
921 if (!isVariadic) {
922 // Emit the diagnostic at the macro name in case there is a missing ).
923 // Emitting it at the , could be far away from the macro name.
924 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
925 return 0;
926 }
927 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000928 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 // If this is a comment token in the argument list and we're just in
930 // -C mode (not -CC mode), discard the comment.
931 continue;
932 }
933
934 ArgTokens.push_back(Tok);
935 }
936
937 // Empty arguments are standard in C99 and supported as an extension in
938 // other modes.
939 if (ArgTokens.empty() && !Features.C99)
940 Diag(Tok, diag::ext_empty_fnmacro_arg);
941
942 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattnerd2177732007-07-20 16:59:19 +0000943 Token EOFTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 EOFTok.startToken();
945 EOFTok.setKind(tok::eof);
946 EOFTok.setLocation(Tok.getLocation());
947 EOFTok.setLength(0);
948 ArgTokens.push_back(EOFTok);
949 ++NumActuals;
950 --NumFixedArgsLeft;
951 };
952
953 // Okay, we either found the r_paren. Check to see if we parsed too few
954 // arguments.
955 unsigned MinArgsExpected = MI->getNumArgs();
956
957 // See MacroArgs instance var for description of this.
958 bool isVarargsElided = false;
959
960 if (NumActuals < MinArgsExpected) {
961 // There are several cases where too few arguments is ok, handle them now.
962 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
963 // Varargs where the named vararg parameter is missing: ok as extension.
964 // #define A(x, ...)
965 // A("blah")
966 Diag(Tok, diag::ext_missing_varargs_arg);
967
968 // Remember this occurred if this is a C99 macro invocation with at least
969 // one actual argument.
970 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
971 } else if (MI->getNumArgs() == 1) {
972 // #define A(x)
973 // A()
974 // is ok because it is an empty argument.
975
976 // Empty arguments are standard in C99 and supported as an extension in
977 // other modes.
978 if (ArgTokens.empty() && !Features.C99)
979 Diag(Tok, diag::ext_empty_fnmacro_arg);
980 } else {
981 // Otherwise, emit the error.
982 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
983 return 0;
984 }
985
986 // Add a marker EOF token to the end of the token list for this argument.
987 SourceLocation EndLoc = Tok.getLocation();
988 Tok.startToken();
989 Tok.setKind(tok::eof);
990 Tok.setLocation(EndLoc);
991 Tok.setLength(0);
992 ArgTokens.push_back(Tok);
993 }
994
995 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
996}
997
998/// ComputeDATE_TIME - Compute the current time, enter it into the specified
999/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1000/// the identifier tokens inserted.
1001static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1002 Preprocessor &PP) {
1003 time_t TT = time(0);
1004 struct tm *TM = localtime(&TT);
1005
1006 static const char * const Months[] = {
1007 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1008 };
1009
1010 char TmpBuffer[100];
1011 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1012 TM->tm_year+1900);
1013 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1014
1015 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
1016 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1017}
1018
1019/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1020/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001021void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 // Figure out which token this is.
1023 IdentifierInfo *II = Tok.getIdentifierInfo();
1024 assert(II && "Can't be a macro without id info!");
1025
1026 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1027 // lex the token after it.
1028 if (II == Ident_Pragma)
1029 return Handle_Pragma(Tok);
1030
1031 ++NumBuiltinMacroExpanded;
1032
1033 char TmpBuffer[100];
1034
1035 // Set up the return result.
1036 Tok.setIdentifierInfo(0);
Chris Lattnerd2177732007-07-20 16:59:19 +00001037 Tok.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038
1039 if (II == Ident__LINE__) {
1040 // __LINE__ expands to a simple numeric value.
Chris Lattner9dc1f532007-07-20 16:37:10 +00001041 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 unsigned Length = strlen(TmpBuffer);
1043 Tok.setKind(tok::numeric_constant);
1044 Tok.setLength(Length);
1045 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1046 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1047 SourceLocation Loc = Tok.getLocation();
1048 if (II == Ident__BASE_FILE__) {
1049 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner9dc1f532007-07-20 16:37:10 +00001050 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1051 while (NextLoc.isValid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 Loc = NextLoc;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001053 NextLoc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 }
1055 }
1056
1057 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner9dc1f532007-07-20 16:37:10 +00001058 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 FN = '"' + Lexer::Stringify(FN) + '"';
1060 Tok.setKind(tok::string_literal);
1061 Tok.setLength(FN.size());
1062 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
1063 } else if (II == Ident__DATE__) {
1064 if (!DATELoc.isValid())
1065 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1066 Tok.setKind(tok::string_literal);
1067 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1068 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
1069 } else if (II == Ident__TIME__) {
1070 if (!TIMELoc.isValid())
1071 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1072 Tok.setKind(tok::string_literal);
1073 Tok.setLength(strlen("\"hh:mm:ss\""));
1074 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
1075 } else if (II == Ident__INCLUDE_LEVEL__) {
1076 Diag(Tok, diag::ext_pp_include_level);
1077
1078 // Compute the include depth of this token.
1079 unsigned Depth = 0;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001080 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1081 for (; Loc.isValid(); ++Depth)
1082 Loc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001083
1084 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1085 sprintf(TmpBuffer, "%u", Depth);
1086 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__TIMESTAMP__) {
1091 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1092 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1093 Diag(Tok, diag::ext_pp_timestamp);
1094
1095 // Get the file that we are lexing out of. If we're currently lexing from
1096 // a macro, dig into the include stack.
1097 const FileEntry *CurFile = 0;
1098 Lexer *TheLexer = getCurrentFileLexer();
1099
1100 if (TheLexer)
Chris Lattner9dc1f532007-07-20 16:37:10 +00001101 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001102
1103 // If this file is older than the file it depends on, emit a diagnostic.
1104 const char *Result;
1105 if (CurFile) {
1106 time_t TT = CurFile->getModificationTime();
1107 struct tm *TM = localtime(&TT);
1108 Result = asctime(TM);
1109 } else {
1110 Result = "??? ??? ?? ??:??:?? ????\n";
1111 }
1112 TmpBuffer[0] = '"';
1113 strcpy(TmpBuffer+1, Result);
1114 unsigned Len = strlen(TmpBuffer);
1115 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
1116 Tok.setKind(tok::string_literal);
1117 Tok.setLength(Len);
1118 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
1119 } else {
1120 assert(0 && "Unknown identifier!");
1121 }
1122}
1123
1124//===----------------------------------------------------------------------===//
1125// Lexer Event Handling.
1126//===----------------------------------------------------------------------===//
1127
1128/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1129/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +00001130IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001132 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1134
1135 // Look up this token, see if it is a macro, or if it is a language keyword.
1136 IdentifierInfo *II;
1137 if (BufPtr && !Identifier.needsCleaning()) {
1138 // No cleaning needed, just use the characters from the lexed buffer.
1139 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1140 } else {
1141 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +00001142 llvm::SmallVector<char, 64> IdentifierBuffer;
1143 IdentifierBuffer.resize(Identifier.getLength());
1144 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 unsigned Size = getSpelling(Identifier, TmpBuf);
1146 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1147 }
1148 Identifier.setIdentifierInfo(II);
1149 return II;
1150}
1151
1152
1153/// HandleIdentifier - This callback is invoked when the lexer reads an
1154/// identifier. This callback looks up the identifier in the map and/or
1155/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerd2177732007-07-20 16:59:19 +00001156void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 assert(Identifier.getIdentifierInfo() &&
1158 "Can't handle identifiers without identifier info!");
1159
1160 IdentifierInfo &II = *Identifier.getIdentifierInfo();
1161
1162 // If this identifier was poisoned, and if it was not produced from a macro
1163 // expansion, emit an error.
1164 if (II.isPoisoned() && CurLexer) {
1165 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1166 Diag(Identifier, diag::err_pp_used_poisoned_id);
1167 else
1168 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1169 }
1170
1171 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +00001172 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1174 if (MI->isEnabled()) {
1175 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1176 return;
1177 } else {
1178 // C99 6.10.3.4p2 says that a disabled macro may never again be
1179 // expanded, even if it's in a context where it could be expanded in the
1180 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +00001181 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 }
1183 }
1184 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1185 // If this identifier is a macro on some other target, emit a diagnostic.
1186 // This diagnosic is only emitted when macro expansion is enabled, because
1187 // the macro would not have been expanded for the other target either.
1188 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1189 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1190 diag::port_target_macro_use);
1191
1192 }
1193
1194 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1195 // then we act as if it is the actual operator and not the textual
1196 // representation of it.
1197 if (II.isCPlusPlusOperatorKeyword())
1198 Identifier.setIdentifierInfo(0);
1199
1200 // Change the kind of this identifier to the appropriate token kind, e.g.
1201 // turning "for" into a keyword.
1202 Identifier.setKind(II.getTokenID());
1203
1204 // If this is an extension token, diagnose its use.
1205 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1206 // For now, I'm just commenting it out (while I work on attributes).
1207 if (II.isExtensionToken() && Features.C99)
1208 Diag(Identifier, diag::ext_token_used);
1209}
1210
1211/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1212/// the current file. This either returns the EOF token or pops a level off
1213/// the include stack and keeps going.
Chris Lattnerd2177732007-07-20 16:59:19 +00001214bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 assert(!CurMacroExpander &&
1216 "Ending a file when currently in a macro!");
1217
1218 // See if this file had a controlling macro.
1219 if (CurLexer) { // Not ending a macro, ignore it.
1220 if (const IdentifierInfo *ControllingMacro =
1221 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
1222 // Okay, this has a controlling macro, remember in PerFileInfo.
1223 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001224 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
1226 }
1227 }
1228
1229 // If this is a #include'd file, pop it off the include stack and continue
1230 // lexing the #includer file.
1231 if (!IncludeMacroStack.empty()) {
1232 // We're done with the #included file.
1233 RemoveTopOfLexerStack();
1234
1235 // Notify the client, if desired, that we are in a new source file.
1236 if (Callbacks && !isEndOfMacro && CurLexer) {
1237 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1238
1239 // Get the file entry for the current file.
1240 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001241 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 FileType = HeaderInfo.getFileDirFlavor(FE);
1243
1244 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1245 PPCallbacks::ExitFile, FileType);
1246 }
1247
1248 // Client should lex another token.
1249 return false;
1250 }
1251
1252 Result.startToken();
1253 CurLexer->BufferPtr = CurLexer->BufferEnd;
1254 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
1255 Result.setKind(tok::eof);
1256
1257 // We're done with the #included file.
1258 delete CurLexer;
1259 CurLexer = 0;
1260
1261 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnercc1a8752007-10-07 08:44:20 +00001262 // diagnostic is enabled, look for macros that have not been used.
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnercc1a8752007-10-07 08:44:20 +00001264 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1265 Macros.begin(), E = Macros.end(); I != E; ++I) {
1266 if (!I->second->isUsed())
1267 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 }
1269 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 return true;
1271}
1272
1273/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
1274/// the current macro expansion or token stream expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00001275bool Preprocessor::HandleEndOfMacro(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 assert(CurMacroExpander && !CurLexer &&
1277 "Ending a macro when currently in a #include file!");
1278
Chris Lattner9594acf2007-07-15 00:25:26 +00001279 // Delete or cache the now-dead macro expander.
1280 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1281 delete CurMacroExpander;
1282 else
1283 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Reid Spencer5f016e22007-07-11 17:01:13 +00001284
1285 // Handle this like a #include file being popped off the stack.
1286 CurMacroExpander = 0;
1287 return HandleEndOfFile(Result, true);
1288}
1289
1290
1291//===----------------------------------------------------------------------===//
1292// Utility Methods for Preprocessor Directive Handling.
1293//===----------------------------------------------------------------------===//
1294
1295/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1296/// current line until the tok::eom token is found.
1297void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattnerd2177732007-07-20 16:59:19 +00001298 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 do {
1300 LexUnexpandedToken(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001301 } while (Tmp.isNot(tok::eom));
Reid Spencer5f016e22007-07-11 17:01:13 +00001302}
1303
1304/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1305static bool isCXXNamedOperator(const std::string &Spelling) {
1306 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1307 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1308 Spelling == "or" || Spelling == "xor";
1309}
1310
1311/// ReadMacroName - Lex and validate a macro name, which occurs after a
1312/// #define or #undef. This sets the token kind to eom and discards the rest
1313/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1314/// this is due to a a #define, 2 if #undef directive, 0 if it is something
1315/// else (e.g. #ifdef).
Chris Lattnerd2177732007-07-20 16:59:19 +00001316void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // Read the token, don't allow macro expansion on it.
1318 LexUnexpandedToken(MacroNameTok);
1319
1320 // Missing macro name?
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001321 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1323
1324 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1325 if (II == 0) {
1326 std::string Spelling = getSpelling(MacroNameTok);
1327 if (isCXXNamedOperator(Spelling))
1328 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1329 // except for their spellings.
1330 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1331 else
1332 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
1333 // Fall through on error.
1334 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
1335 // Error if defining "defined": C99 6.10.8.4.
1336 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner0edde552007-10-07 08:04:56 +00001337 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnercc1a8752007-10-07 08:44:20 +00001338 getMacroInfo(II)->isBuiltinMacro()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
1340 if (isDefineUndef == 1)
1341 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1342 else
1343 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
1344 } else {
1345 // Okay, we got a good identifier node. Return it.
1346 return;
1347 }
1348
1349 // Invalid macro name, read and discard the rest of the line. Then set the
1350 // token kind to tok::eom.
1351 MacroNameTok.setKind(tok::eom);
1352 return DiscardUntilEndOfDirective();
1353}
1354
1355/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1356/// not, emit a diagnostic and consume up until the eom.
1357void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001358 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 Lex(Tmp);
1360 // There should be no tokens after the directive, but we allow them as an
1361 // extension.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001362 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 Lex(Tmp);
1364
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001365 if (Tmp.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1367 DiscardUntilEndOfDirective();
1368 }
1369}
1370
1371
1372
1373/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1374/// decided that the subsequent tokens are in the #if'd out portion of the
1375/// file. Lex the rest of the file, until we see an #endif. If
1376/// FoundNonSkipPortion is true, then we have already emitted code for part of
1377/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1378/// is true, then #else directives are ok, if not, then we have already seen one
1379/// so a #else directive is a duplicate. When this returns, the caller can lex
1380/// the first valid token.
1381void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1382 bool FoundNonSkipPortion,
1383 bool FoundElse) {
1384 ++NumSkipped;
1385 assert(CurMacroExpander == 0 && CurLexer &&
1386 "Lexing a macro, not a file?");
1387
1388 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1389 FoundNonSkipPortion, FoundElse);
1390
1391 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1392 // disabling warnings, etc.
1393 CurLexer->LexingRawMode = true;
Chris Lattnerd2177732007-07-20 16:59:19 +00001394 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 while (1) {
1396 CurLexer->Lex(Tok);
1397
1398 // If this is the end of the buffer, we have an error.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001399 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // Emit errors for each unterminated conditional on the stack, including
1401 // the current one.
1402 while (!CurLexer->ConditionalStack.empty()) {
1403 Diag(CurLexer->ConditionalStack.back().IfLoc,
1404 diag::err_pp_unterminated_conditional);
1405 CurLexer->ConditionalStack.pop_back();
1406 }
1407
1408 // Just return and let the caller lex after this #include.
1409 break;
1410 }
1411
1412 // If this token is not a preprocessor directive, just skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001413 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 continue;
1415
1416 // We just parsed a # character at the start of a line, so we're in
1417 // directive mode. Tell the lexer this so any newlines we see will be
1418 // converted into an EOM token (this terminates the macro).
1419 CurLexer->ParsingPreprocessorDirective = true;
1420 CurLexer->KeepCommentMode = false;
1421
1422
1423 // Read the next token, the directive flavor.
1424 LexUnexpandedToken(Tok);
1425
1426 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1427 // something bogus), skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001428 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 CurLexer->ParsingPreprocessorDirective = false;
1430 // Restore comment saving mode.
1431 CurLexer->KeepCommentMode = KeepComments;
1432 continue;
1433 }
1434
1435 // If the first letter isn't i or e, it isn't intesting to us. We know that
1436 // this is safe in the face of spelling differences, because there is no way
1437 // to spell an i/e in a strange way that is another letter. Skipping this
1438 // allows us to avoid looking up the identifier info for #define/#undef and
1439 // other common directives.
1440 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1441 char FirstChar = RawCharData[0];
1442 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1443 FirstChar != 'i' && FirstChar != 'e') {
1444 CurLexer->ParsingPreprocessorDirective = false;
1445 // Restore comment saving mode.
1446 CurLexer->KeepCommentMode = KeepComments;
1447 continue;
1448 }
1449
1450 // Get the identifier name without trigraphs or embedded newlines. Note
1451 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1452 // when skipping.
1453 // TODO: could do this with zero copies in the no-clean case by using
1454 // strncmp below.
1455 char Directive[20];
1456 unsigned IdLen;
1457 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1458 IdLen = Tok.getLength();
1459 memcpy(Directive, RawCharData, IdLen);
1460 Directive[IdLen] = 0;
1461 } else {
1462 std::string DirectiveStr = getSpelling(Tok);
1463 IdLen = DirectiveStr.size();
1464 if (IdLen >= 20) {
1465 CurLexer->ParsingPreprocessorDirective = false;
1466 // Restore comment saving mode.
1467 CurLexer->KeepCommentMode = KeepComments;
1468 continue;
1469 }
1470 memcpy(Directive, &DirectiveStr[0], IdLen);
1471 Directive[IdLen] = 0;
1472 }
1473
1474 if (FirstChar == 'i' && Directive[1] == 'f') {
1475 if ((IdLen == 2) || // "if"
1476 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1477 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
1478 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1479 // bother parsing the condition.
1480 DiscardUntilEndOfDirective();
1481 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
1482 /*foundnonskip*/false,
1483 /*fnddelse*/false);
1484 }
1485 } else if (FirstChar == 'e') {
1486 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
1487 CheckEndOfDirective("#endif");
1488 PPConditionalInfo CondInfo;
1489 CondInfo.WasSkipping = true; // Silence bogus warning.
1490 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1491 InCond = InCond; // Silence warning in no-asserts mode.
1492 assert(!InCond && "Can't be skipping if not in a conditional!");
1493
1494 // If we popped the outermost skipping block, we're done skipping!
1495 if (!CondInfo.WasSkipping)
1496 break;
1497 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
1498 // #else directive in a skipping conditional. If not in some other
1499 // skipping conditional, and if #else hasn't already been seen, enter it
1500 // as a non-skipping conditional.
1501 CheckEndOfDirective("#else");
1502 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1503
1504 // If this is a #else with a #else before it, report the error.
1505 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
1506
1507 // Note that we've seen a #else in this conditional.
1508 CondInfo.FoundElse = true;
1509
1510 // If the conditional is at the top level, and the #if block wasn't
1511 // entered, enter the #else block now.
1512 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1513 CondInfo.FoundNonSkip = true;
1514 break;
1515 }
1516 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
1517 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1518
1519 bool ShouldEnter;
1520 // If this is in a skipping block or if we're already handled this #if
1521 // block, don't bother parsing the condition.
1522 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
1523 DiscardUntilEndOfDirective();
1524 ShouldEnter = false;
1525 } else {
1526 // Restore the value of LexingRawMode so that identifiers are
1527 // looked up, etc, inside the #elif expression.
1528 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1529 CurLexer->LexingRawMode = false;
1530 IdentifierInfo *IfNDefMacro = 0;
1531 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
1532 CurLexer->LexingRawMode = true;
1533 }
1534
1535 // If this is a #elif with a #else before it, report the error.
1536 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
1537
1538 // If this condition is true, enter it!
1539 if (ShouldEnter) {
1540 CondInfo.FoundNonSkip = true;
1541 break;
1542 }
1543 }
1544 }
1545
1546 CurLexer->ParsingPreprocessorDirective = false;
1547 // Restore comment saving mode.
1548 CurLexer->KeepCommentMode = KeepComments;
1549 }
1550
1551 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1552 // of the file, just stop skipping and return to lexing whatever came after
1553 // the #if block.
1554 CurLexer->LexingRawMode = false;
1555}
1556
1557//===----------------------------------------------------------------------===//
1558// Preprocessor Directive Handling.
1559//===----------------------------------------------------------------------===//
1560
1561/// HandleDirective - This callback is invoked when the lexer sees a # token
1562/// at the start of a line. This consumes the directive, modifies the
1563/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1564/// read is the correct one.
Chris Lattnerd2177732007-07-20 16:59:19 +00001565void Preprocessor::HandleDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1567
1568 // We just parsed a # character at the start of a line, so we're in directive
1569 // mode. Tell the lexer this so any newlines we see will be converted into an
1570 // EOM token (which terminates the directive).
1571 CurLexer->ParsingPreprocessorDirective = true;
1572
1573 ++NumDirectives;
1574
1575 // We are about to read a token. For the multiple-include optimization FA to
1576 // work, we have to remember if we had read any tokens *before* this
1577 // pp-directive.
1578 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1579
1580 // Read the next token, the directive flavor. This isn't expanded due to
1581 // C99 6.10.3p8.
1582 LexUnexpandedToken(Result);
1583
1584 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1585 // #define A(x) #x
1586 // A(abc
1587 // #warning blah
1588 // def)
1589 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1590 if (InMacroArgs)
1591 Diag(Result, diag::ext_embedded_directive);
1592
1593TryAgain:
1594 switch (Result.getKind()) {
1595 case tok::eom:
1596 return; // null directive.
1597 case tok::comment:
1598 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1599 LexUnexpandedToken(Result);
1600 goto TryAgain;
1601
1602 case tok::numeric_constant:
1603 // FIXME: implement # 7 line numbers!
1604 DiscardUntilEndOfDirective();
1605 return;
1606 default:
1607 IdentifierInfo *II = Result.getIdentifierInfo();
1608 if (II == 0) break; // Not an identifier.
1609
1610 // Ask what the preprocessor keyword ID is.
1611 switch (II->getPPKeywordID()) {
1612 default: break;
1613 // C99 6.10.1 - Conditional Inclusion.
1614 case tok::pp_if:
1615 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1616 case tok::pp_ifdef:
1617 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1618 case tok::pp_ifndef:
1619 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1620 case tok::pp_elif:
1621 return HandleElifDirective(Result);
1622 case tok::pp_else:
1623 return HandleElseDirective(Result);
1624 case tok::pp_endif:
1625 return HandleEndifDirective(Result);
1626
1627 // C99 6.10.2 - Source File Inclusion.
1628 case tok::pp_include:
1629 return HandleIncludeDirective(Result); // Handle #include.
1630
1631 // C99 6.10.3 - Macro Replacement.
1632 case tok::pp_define:
1633 return HandleDefineDirective(Result, false);
1634 case tok::pp_undef:
1635 return HandleUndefDirective(Result);
1636
1637 // C99 6.10.4 - Line Control.
1638 case tok::pp_line:
1639 // FIXME: implement #line
1640 DiscardUntilEndOfDirective();
1641 return;
1642
1643 // C99 6.10.5 - Error Directive.
1644 case tok::pp_error:
1645 return HandleUserDiagnosticDirective(Result, false);
1646
1647 // C99 6.10.6 - Pragma Directive.
1648 case tok::pp_pragma:
1649 return HandlePragmaDirective();
1650
1651 // GNU Extensions.
1652 case tok::pp_import:
1653 return HandleImportDirective(Result);
1654 case tok::pp_include_next:
1655 return HandleIncludeNextDirective(Result);
1656
1657 case tok::pp_warning:
1658 Diag(Result, diag::ext_pp_warning_directive);
1659 return HandleUserDiagnosticDirective(Result, true);
1660 case tok::pp_ident:
1661 return HandleIdentSCCSDirective(Result);
1662 case tok::pp_sccs:
1663 return HandleIdentSCCSDirective(Result);
1664 case tok::pp_assert:
1665 //isExtension = true; // FIXME: implement #assert
1666 break;
1667 case tok::pp_unassert:
1668 //isExtension = true; // FIXME: implement #unassert
1669 break;
1670
1671 // clang extensions.
1672 case tok::pp_define_target:
1673 return HandleDefineDirective(Result, true);
1674 case tok::pp_define_other_target:
1675 return HandleDefineOtherTargetDirective(Result);
1676 }
1677 break;
1678 }
1679
1680 // If we reached here, the preprocessing token is not valid!
1681 Diag(Result, diag::err_pp_invalid_directive);
1682
1683 // Read the rest of the PP line.
1684 DiscardUntilEndOfDirective();
1685
1686 // Okay, we're done parsing the directive.
1687}
1688
Chris Lattnerd2177732007-07-20 16:59:19 +00001689void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 bool isWarning) {
1691 // Read the rest of the line raw. We do this because we don't want macros
1692 // to be expanded and we don't require that the tokens be valid preprocessing
1693 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1694 // collapse multiple consequtive white space between tokens, but this isn't
1695 // specified by the standard.
1696 std::string Message = CurLexer->ReadToEndOfLine();
1697
1698 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1699 return Diag(Tok, DiagID, Message);
1700}
1701
1702/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1703///
Chris Lattnerd2177732007-07-20 16:59:19 +00001704void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 // Yes, this directive is an extension.
1706 Diag(Tok, diag::ext_pp_ident_directive);
1707
1708 // Read the string argument.
Chris Lattnerd2177732007-07-20 16:59:19 +00001709 Token StrTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 Lex(StrTok);
1711
1712 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001713 if (StrTok.isNot(tok::string_literal) &&
1714 StrTok.isNot(tok::wide_string_literal))
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 return Diag(StrTok, diag::err_pp_malformed_ident);
1716
1717 // Verify that there is nothing after the string, other than EOM.
1718 CheckEndOfDirective("#ident");
1719
1720 if (Callbacks)
1721 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
1722}
1723
1724//===----------------------------------------------------------------------===//
1725// Preprocessor Include Directive Handling.
1726//===----------------------------------------------------------------------===//
1727
1728/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1729/// checked and spelled filename, e.g. as an operand of #include. This returns
1730/// true if the input filename was in <>'s or false if it were in ""'s. The
1731/// caller is expected to provide a buffer that is large enough to hold the
1732/// spelling of the filename, but is also expected to handle the case when
1733/// this method decides to use a different buffer.
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001734bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 const char *&BufStart,
1736 const char *&BufEnd) {
1737 // Get the text form of the filename.
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1739
1740 // Make sure the filename is <x> or "x".
1741 bool isAngled;
1742 if (BufStart[0] == '<') {
1743 if (BufEnd[-1] != '>') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001744 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 BufStart = 0;
1746 return true;
1747 }
1748 isAngled = true;
1749 } else if (BufStart[0] == '"') {
1750 if (BufEnd[-1] != '"') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001751 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 BufStart = 0;
1753 return true;
1754 }
1755 isAngled = false;
1756 } else {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001757 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 BufStart = 0;
1759 return true;
1760 }
1761
1762 // Diagnose #include "" as invalid.
1763 if (BufEnd-BufStart <= 2) {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001764 Diag(Loc, diag::err_pp_empty_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 BufStart = 0;
1766 return "";
1767 }
1768
1769 // Skip the brackets.
1770 ++BufStart;
1771 --BufEnd;
1772 return isAngled;
1773}
1774
Chris Lattner706ab502007-07-23 04:56:47 +00001775/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1776/// from a macro as multiple tokens, which need to be glued together. This
1777/// occurs for code like:
1778/// #define FOO <a/b.h>
1779/// #include FOO
1780/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1781///
1782/// This code concatenates and consumes tokens up to the '>' token. It returns
1783/// false if the > was found, otherwise it returns true if it finds and consumes
1784/// the EOM marker.
1785static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1786 Preprocessor &PP) {
1787 Token CurTok;
1788
1789 PP.Lex(CurTok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001790 while (CurTok.isNot(tok::eom)) {
Chris Lattner706ab502007-07-23 04:56:47 +00001791 // Append the spelling of this token to the buffer. If there was a space
1792 // before it, add it now.
1793 if (CurTok.hasLeadingSpace())
1794 FilenameBuffer.push_back(' ');
1795
1796 // Get the spelling of the token, directly into FilenameBuffer if possible.
1797 unsigned PreAppendSize = FilenameBuffer.size();
1798 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1799
1800 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1801 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1802
1803 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1804 if (BufPtr != &FilenameBuffer[PreAppendSize])
1805 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1806
1807 // Resize FilenameBuffer to the correct size.
1808 if (CurTok.getLength() != ActualLen)
1809 FilenameBuffer.resize(PreAppendSize+ActualLen);
1810
1811 // If we found the '>' marker, return success.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001812 if (CurTok.is(tok::greater))
Chris Lattner706ab502007-07-23 04:56:47 +00001813 return false;
1814
1815 PP.Lex(CurTok);
1816 }
1817
1818 // If we hit the eom marker, emit an error and return true so that the caller
1819 // knows the EOM has been read.
1820 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1821 return true;
1822}
1823
Reid Spencer5f016e22007-07-11 17:01:13 +00001824/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1825/// file to be included from the lexer, then include it! This is a common
1826/// routine with functionality shared between #include, #include_next and
1827/// #import.
Chris Lattnerd2177732007-07-20 16:59:19 +00001828void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 const DirectoryLookup *LookupFrom,
1830 bool isImport) {
1831
Chris Lattnerd2177732007-07-20 16:59:19 +00001832 Token FilenameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 CurLexer->LexIncludeFilename(FilenameTok);
1834
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 // Reserve a buffer to get the spelling.
1836 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner706ab502007-07-23 04:56:47 +00001837 const char *FilenameStart, *FilenameEnd;
1838
1839 switch (FilenameTok.getKind()) {
1840 case tok::eom:
1841 // If the token kind is EOM, the error has already been diagnosed.
1842 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001843
Chris Lattner706ab502007-07-23 04:56:47 +00001844 case tok::angle_string_literal:
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001845 case tok::string_literal: {
Chris Lattner706ab502007-07-23 04:56:47 +00001846 FilenameBuffer.resize(FilenameTok.getLength());
1847 FilenameStart = &FilenameBuffer[0];
1848 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1849 FilenameEnd = FilenameStart+Len;
1850 break;
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001851 }
Chris Lattner706ab502007-07-23 04:56:47 +00001852
1853 case tok::less:
1854 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1855 // case, glue the tokens together into FilenameBuffer and interpret those.
1856 FilenameBuffer.push_back('<');
1857 if (ConcatenateIncludeName(FilenameBuffer, *this))
1858 return; // Found <eom> but no ">"? Diagnostic already emitted.
1859 FilenameStart = &FilenameBuffer[0];
1860 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1861 break;
1862 default:
1863 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1864 DiscardUntilEndOfDirective();
1865 return;
1866 }
1867
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001868 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 FilenameStart, FilenameEnd);
1870 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1871 // error.
Chris Lattner706ab502007-07-23 04:56:47 +00001872 if (FilenameStart == 0) {
1873 DiscardUntilEndOfDirective();
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 return;
Chris Lattner706ab502007-07-23 04:56:47 +00001875 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001876
1877 // Verify that there is nothing after the filename, other than EOM. Use the
1878 // preprocessor to lex this in case lexing the filename entered a macro.
1879 CheckEndOfDirective("#include");
1880
1881 // Check that we don't have infinite #include recursion.
1882 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
1883 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1884
1885 // Search include directories.
1886 const DirectoryLookup *CurDir;
1887 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1888 isAngled, LookupFrom, CurDir);
1889 if (File == 0)
1890 return Diag(FilenameTok, diag::err_pp_file_not_found,
1891 std::string(FilenameStart, FilenameEnd));
1892
1893 // Ask HeaderInfo if we should enter this #include file.
1894 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1895 // If it returns true, #including this file will have no effect.
1896 return;
1897 }
1898
1899 // Look up the file, create a File ID for it.
1900 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
1901 if (FileID == 0)
1902 return Diag(FilenameTok, diag::err_pp_file_not_found,
1903 std::string(FilenameStart, FilenameEnd));
1904
1905 // Finally, if all is good, enter the new file!
1906 EnterSourceFile(FileID, CurDir);
1907}
1908
1909/// HandleIncludeNextDirective - Implements #include_next.
1910///
Chris Lattnerd2177732007-07-20 16:59:19 +00001911void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1913
1914 // #include_next is like #include, except that we start searching after
1915 // the current found directory. If we can't do this, issue a
1916 // diagnostic.
1917 const DirectoryLookup *Lookup = CurDirLookup;
1918 if (isInPrimaryFile()) {
1919 Lookup = 0;
1920 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1921 } else if (Lookup == 0) {
1922 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1923 } else {
1924 // Start looking up in the next directory.
1925 ++Lookup;
1926 }
1927
1928 return HandleIncludeDirective(IncludeNextTok, Lookup);
1929}
1930
1931/// HandleImportDirective - Implements #import.
1932///
Chris Lattnerd2177732007-07-20 16:59:19 +00001933void Preprocessor::HandleImportDirective(Token &ImportTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 Diag(ImportTok, diag::ext_pp_import_directive);
1935
1936 return HandleIncludeDirective(ImportTok, 0, true);
1937}
1938
1939//===----------------------------------------------------------------------===//
1940// Preprocessor Macro Directive Handling.
1941//===----------------------------------------------------------------------===//
1942
1943/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1944/// definition has just been read. Lex the rest of the arguments and the
1945/// closing ), updating MI with what we learn. Return true if an error occurs
1946/// parsing the arg list.
1947bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner25c96482007-07-14 22:46:43 +00001948 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1949
Chris Lattnerd2177732007-07-20 16:59:19 +00001950 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 while (1) {
1952 LexUnexpandedToken(Tok);
1953 switch (Tok.getKind()) {
1954 case tok::r_paren:
1955 // Found the end of the argument list.
Chris Lattner25c96482007-07-14 22:46:43 +00001956 if (Arguments.empty()) { // #define FOO()
1957 MI->setArgumentList(Arguments.begin(), Arguments.end());
1958 return false;
1959 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 // Otherwise we have #define FOO(A,)
1961 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1962 return true;
1963 case tok::ellipsis: // #define X(... -> C99 varargs
1964 // Warn if use of C99 feature in non-C99 mode.
1965 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1966
1967 // Lex the token after the identifier.
1968 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001969 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1971 return true;
1972 }
1973 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner25c96482007-07-14 22:46:43 +00001974 Arguments.push_back(Ident__VA_ARGS__);
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 MI->setIsC99Varargs();
Chris Lattner25c96482007-07-14 22:46:43 +00001976 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 return false;
1978 case tok::eom: // #define X(
1979 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1980 return true;
1981 default:
1982 // Handle keywords and identifiers here to accept things like
1983 // #define Foo(for) for.
1984 IdentifierInfo *II = Tok.getIdentifierInfo();
1985 if (II == 0) {
1986 // #define X(1
1987 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1988 return true;
1989 }
1990
1991 // If this is already used as an argument, it is used multiple times (e.g.
1992 // #define X(A,A.
Chris Lattner25c96482007-07-14 22:46:43 +00001993 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1994 Arguments.end()) { // C99 6.10.3p6
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1996 return true;
1997 }
1998
1999 // Add the argument to the macro info.
Chris Lattner25c96482007-07-14 22:46:43 +00002000 Arguments.push_back(II);
Reid Spencer5f016e22007-07-11 17:01:13 +00002001
2002 // Lex the token after the identifier.
2003 LexUnexpandedToken(Tok);
2004
2005 switch (Tok.getKind()) {
2006 default: // #define X(A B
2007 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2008 return true;
2009 case tok::r_paren: // #define X(A)
Chris Lattner25c96482007-07-14 22:46:43 +00002010 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 return false;
2012 case tok::comma: // #define X(A,
2013 break;
2014 case tok::ellipsis: // #define X(A... -> GCC extension
2015 // Diagnose extension.
2016 Diag(Tok, diag::ext_named_variadic_macro);
2017
2018 // Lex the token after the identifier.
2019 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002020 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2022 return true;
2023 }
2024
2025 MI->setIsGNUVarargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002026 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 return false;
2028 }
2029 }
2030 }
2031}
2032
2033/// HandleDefineDirective - Implements #define. This consumes the entire macro
2034/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2035/// true, then this is a "#define_target", otherwise this is a "#define".
2036///
Chris Lattnerd2177732007-07-20 16:59:19 +00002037void Preprocessor::HandleDefineDirective(Token &DefineTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 bool isTargetSpecific) {
2039 ++NumDefined;
2040
Chris Lattnerd2177732007-07-20 16:59:19 +00002041 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 ReadMacroName(MacroNameTok, 1);
2043
2044 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002045 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 return;
Chris Lattnerc215bd62007-07-14 22:11:41 +00002047
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 // If we are supposed to keep comments in #defines, reenable comment saving
2049 // mode.
2050 CurLexer->KeepCommentMode = KeepMacroComments;
2051
2052 // Create the new macro.
2053 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
2054 if (isTargetSpecific) MI->setIsTargetSpecific();
2055
2056 // If the identifier is an 'other target' macro, clear this bit.
2057 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2058
2059
Chris Lattnerd2177732007-07-20 16:59:19 +00002060 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 LexUnexpandedToken(Tok);
2062
2063 // If this is a function-like macro definition, parse the argument list,
2064 // marking each of the identifiers as being used as macro arguments. Also,
2065 // check other constraints on the first token of the macro body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002066 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 // If there is no body to this macro, we have no special handling here.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002068 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 // This is a function-like macro definition. Read the argument list.
2070 MI->setIsFunctionLike();
2071 if (ReadMacroDefinitionArgList(MI)) {
2072 // Forget about MI.
2073 delete MI;
2074 // Throw away the rest of the line.
2075 if (CurLexer->ParsingPreprocessorDirective)
2076 DiscardUntilEndOfDirective();
2077 return;
2078 }
2079
2080 // Read the first token after the arg list for down below.
2081 LexUnexpandedToken(Tok);
2082 } else if (!Tok.hasLeadingSpace()) {
2083 // C99 requires whitespace between the macro definition and the body. Emit
2084 // a diagnostic for something like "#define X+".
2085 if (Features.C99) {
2086 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2087 } else {
2088 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2089 // one in some cases!
2090 }
2091 } else {
2092 // This is a normal token with leading space. Clear the leading space
2093 // marker on the first token to get proper expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00002094 Tok.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 }
2096
2097 // If this is a definition of a variadic C99 function-like macro, not using
2098 // the GNU named varargs extension, enabled __VA_ARGS__.
2099
2100 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2101 // This gets unpoisoned where it is allowed.
2102 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2103 if (MI->isC99Varargs())
2104 Ident__VA_ARGS__->setIsPoisoned(false);
2105
2106 // Read the rest of the macro body.
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002107 if (MI->isObjectLike()) {
2108 // Object-like macros are very simple, just read their body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002109 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002110 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // Get the next token of the macro.
2112 LexUnexpandedToken(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 }
2114
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002115 } else {
2116 // Otherwise, read the body of a function-like macro. This has to validate
2117 // the # (stringize) operator.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002118 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002119 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002120
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002121 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2122 // parameters in function-like macro expansions.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002123 if (Tok.isNot(tok::hash)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002124 // Get the next token of the macro.
2125 LexUnexpandedToken(Tok);
2126 continue;
2127 }
2128
2129 // Get the next token of the macro.
2130 LexUnexpandedToken(Tok);
2131
2132 // Not a macro arg identifier?
2133 if (!Tok.getIdentifierInfo() ||
2134 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2135 Diag(Tok, diag::err_pp_stringize_not_parameter);
2136 delete MI;
2137
2138 // Disable __VA_ARGS__ again.
2139 Ident__VA_ARGS__->setIsPoisoned(true);
2140 return;
2141 }
2142
2143 // Things look ok, add the param name token to the macro.
2144 MI->AddTokenToBody(Tok);
2145
2146 // Get the next token of the macro.
2147 LexUnexpandedToken(Tok);
2148 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 }
2150
Chris Lattnerc215bd62007-07-14 22:11:41 +00002151
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 // Disable __VA_ARGS__ again.
2153 Ident__VA_ARGS__->setIsPoisoned(true);
2154
2155 // Check that there is no paste (##) operator at the begining or end of the
2156 // replacement list.
2157 unsigned NumTokens = MI->getNumTokens();
2158 if (NumTokens != 0) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002159 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2161 delete MI;
2162 return;
2163 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002164 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2166 delete MI;
2167 return;
2168 }
2169 }
2170
2171 // If this is the primary source file, remember that this macro hasn't been
2172 // used yet.
2173 if (isInPrimaryFile())
2174 MI->setIsUsed(false);
2175
2176 // Finally, if this identifier already had a macro defined for it, verify that
2177 // the macro bodies are identical and free the old definition.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002178 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 if (!OtherMI->isUsed())
2180 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2181
2182 // Macros must be identical. This means all tokes and whitespace separation
2183 // must be the same. C99 6.10.3.2.
2184 if (!MI->isIdenticalTo(*OtherMI, *this)) {
2185 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2186 MacroNameTok.getIdentifierInfo()->getName());
2187 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2188 }
2189 delete OtherMI;
2190 }
2191
Chris Lattnercc1a8752007-10-07 08:44:20 +00002192 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002193}
2194
2195/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattnerd2177732007-07-20 16:59:19 +00002196void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2197 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 ReadMacroName(MacroNameTok, 1);
2199
2200 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002201 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 return;
2203
2204 // Check to see if this is the last token on the #undef line.
2205 CheckEndOfDirective("#define_other_target");
2206
2207 // If there is already a macro defined by this name, turn it into a
2208 // target-specific define.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002209 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 MI->setIsTargetSpecific(true);
2211 return;
2212 }
2213
2214 // Mark the identifier as being a macro on some other target.
2215 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2216}
2217
2218
2219/// HandleUndefDirective - Implements #undef.
2220///
Chris Lattnerd2177732007-07-20 16:59:19 +00002221void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 ++NumUndefined;
2223
Chris Lattnerd2177732007-07-20 16:59:19 +00002224 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 ReadMacroName(MacroNameTok, 2);
2226
2227 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002228 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 return;
2230
2231 // Check to see if this is the last token on the #undef line.
2232 CheckEndOfDirective("#undef");
2233
2234 // Okay, we finally have a valid identifier to undef.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002235 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Reid Spencer5f016e22007-07-11 17:01:13 +00002236
2237 // #undef untaints an identifier if it were marked by define_other_target.
2238 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2239
2240 // If the macro is not defined, this is a noop undef, just return.
2241 if (MI == 0) return;
2242
2243 if (!MI->isUsed())
2244 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2245
2246 // Free macro definition.
2247 delete MI;
Chris Lattnercc1a8752007-10-07 08:44:20 +00002248 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002249}
2250
2251
2252//===----------------------------------------------------------------------===//
2253// Preprocessor Conditional Directive Handling.
2254//===----------------------------------------------------------------------===//
2255
2256/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
2257/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2258/// if any tokens have been returned or pp-directives activated before this
2259/// #ifndef has been lexed.
2260///
Chris Lattnerd2177732007-07-20 16:59:19 +00002261void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 bool ReadAnyTokensBeforeDirective) {
2263 ++NumIf;
Chris Lattnerd2177732007-07-20 16:59:19 +00002264 Token DirectiveTok = Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00002265
Chris Lattnerd2177732007-07-20 16:59:19 +00002266 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 ReadMacroName(MacroNameTok);
2268
2269 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002270 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerf37bb252007-09-24 05:14:57 +00002271 // Skip code until we get to #endif. This helps with recovery by not
2272 // emitting an error when the #endif is reached.
2273 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2274 /*Foundnonskip*/false, /*FoundElse*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 return;
Chris Lattnerf37bb252007-09-24 05:14:57 +00002276 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002277
2278 // Check to see if this is the last token on the #if[n]def line.
2279 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2280
2281 // If the start of a top-level #ifdef, inform MIOpt.
2282 if (!ReadAnyTokensBeforeDirective &&
2283 CurLexer->getConditionalStackDepth() == 0) {
2284 assert(isIfndef && "#ifdef shouldn't reach here");
2285 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2286 }
2287
2288 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnercc1a8752007-10-07 08:44:20 +00002289 MacroInfo *MI = getMacroInfo(MII);
Reid Spencer5f016e22007-07-11 17:01:13 +00002290
2291 // If there is a macro, process it.
2292 if (MI) {
2293 // Mark it used.
2294 MI->setIsUsed(true);
2295
2296 // If this is the first use of a target-specific macro, warn about it.
2297 if (MI->isTargetSpecific()) {
2298 MI->setIsTargetSpecific(false); // Don't warn on second use.
2299 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2300 diag::port_target_macro_use);
2301 }
2302 } else {
2303 // Use of a target-specific macro for some other target? If so, warn.
2304 if (MII->isOtherTargetMacro()) {
2305 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2306 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2307 diag::port_target_macro_use);
2308 }
2309 }
2310
2311 // Should we include the stuff contained by this directive?
2312 if (!MI == isIfndef) {
2313 // Yes, remember that we are inside a conditional, then lex the next token.
2314 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
2315 /*foundnonskip*/true, /*foundelse*/false);
2316 } else {
2317 // No, skip the contents of this block and return the first token after it.
2318 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2319 /*Foundnonskip*/false,
2320 /*FoundElse*/false);
2321 }
2322}
2323
2324/// HandleIfDirective - Implements the #if directive.
2325///
Chris Lattnerd2177732007-07-20 16:59:19 +00002326void Preprocessor::HandleIfDirective(Token &IfToken,
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 bool ReadAnyTokensBeforeDirective) {
2328 ++NumIf;
2329
2330 // Parse and evaluation the conditional expression.
2331 IdentifierInfo *IfNDefMacro = 0;
2332 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2333
2334 // Should we include the stuff contained by this directive?
2335 if (ConditionalTrue) {
2336 // If this condition is equivalent to #ifndef X, and if this is the first
2337 // directive seen, handle it for the multiple-include optimization.
2338 if (!ReadAnyTokensBeforeDirective &&
2339 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2340 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2341
2342 // Yes, remember that we are inside a conditional, then lex the next token.
2343 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2344 /*foundnonskip*/true, /*foundelse*/false);
2345 } else {
2346 // No, skip the contents of this block and return the first token after it.
2347 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2348 /*FoundElse*/false);
2349 }
2350}
2351
2352/// HandleEndifDirective - Implements the #endif directive.
2353///
Chris Lattnerd2177732007-07-20 16:59:19 +00002354void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 ++NumEndif;
2356
2357 // Check that this is the whole directive.
2358 CheckEndOfDirective("#endif");
2359
2360 PPConditionalInfo CondInfo;
2361 if (CurLexer->popConditionalLevel(CondInfo)) {
2362 // No conditionals on the stack: this is an #endif without an #if.
2363 return Diag(EndifToken, diag::err_pp_endif_without_if);
2364 }
2365
2366 // If this the end of a top-level #endif, inform MIOpt.
2367 if (CurLexer->getConditionalStackDepth() == 0)
2368 CurLexer->MIOpt.ExitTopLevelConditional();
2369
2370 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
2371 "This code should only be reachable in the non-skipping case!");
2372}
2373
2374
Chris Lattnerd2177732007-07-20 16:59:19 +00002375void Preprocessor::HandleElseDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 ++NumElse;
2377
2378 // #else directive in a non-skipping conditional... start skipping.
2379 CheckEndOfDirective("#else");
2380
2381 PPConditionalInfo CI;
2382 if (CurLexer->popConditionalLevel(CI))
2383 return Diag(Result, diag::pp_err_else_without_if);
2384
2385 // If this is a top-level #else, inform the MIOpt.
2386 if (CurLexer->getConditionalStackDepth() == 0)
2387 CurLexer->MIOpt.FoundTopLevelElse();
2388
2389 // If this is a #else with a #else before it, report the error.
2390 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2391
2392 // Finally, skip the rest of the contents of this block and return the first
2393 // token after it.
2394 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2395 /*FoundElse*/true);
2396}
2397
Chris Lattnerd2177732007-07-20 16:59:19 +00002398void Preprocessor::HandleElifDirective(Token &ElifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 ++NumElse;
2400
2401 // #elif directive in a non-skipping conditional... start skipping.
2402 // We don't care what the condition is, because we will always skip it (since
2403 // the block immediately before it was included).
2404 DiscardUntilEndOfDirective();
2405
2406 PPConditionalInfo CI;
2407 if (CurLexer->popConditionalLevel(CI))
2408 return Diag(ElifToken, diag::pp_err_elif_without_if);
2409
2410 // If this is a top-level #elif, inform the MIOpt.
2411 if (CurLexer->getConditionalStackDepth() == 0)
2412 CurLexer->MIOpt.FoundTopLevelElse();
2413
2414 // If this is a #elif with a #else before it, report the error.
2415 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2416
2417 // Finally, skip the rest of the contents of this block and return the first
2418 // token after it.
2419 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2420 /*FoundElse*/CI.FoundElse);
2421}
2422