blob: 0970590afe9d44b65f790277b4edf6890e3dd84f [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");
Steve Naroff8ee529b2007-10-31 18:42:27 +0000372
Chris Lattnerd19144b2007-10-10 17:48:53 +0000373 // Add __builtin_va_list typedef.
374 {
375 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
376 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
377 Buf.push_back('\n');
378 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000379
380 // Get the target #defines.
381 PP.getTargetInfo().getTargetDefines(Buf);
382
383 // Compiler set macros.
384 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
Steve Naroff39d0a272007-11-10 18:06:36 +0000385 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1050");
Chris Lattner53b0dab2007-10-09 22:10:18 +0000386 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
387 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
388 DefineBuiltinMacro(Buf, "__GNUC__=4");
389 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
390 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
391 "build 5250)\"");
392
393 // Build configuration options.
394 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
395 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
396 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
397 DefineBuiltinMacro(Buf, "__PIC__=1");
398
399
400 if (PP.getLangOptions().CPlusPlus) {
401 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
402 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
403 DefineBuiltinMacro(Buf, "__GNUG__=4");
404 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
405 DefineBuiltinMacro(Buf, "__cplusplus=1");
406 DefineBuiltinMacro(Buf, "__private_extern__=extern");
407 }
408
409 // FIXME: Should emit a #line directive here.
410}
411
412
413/// EnterMainSourceFile - Enter the specified FileID as the main source file,
414/// which implicitly adds the builting defines etc.
415void Preprocessor::EnterMainSourceFile(unsigned MainFileID) {
416 // Enter the main file source buffer.
417 EnterSourceFile(MainFileID, 0);
418
Chris Lattnerb2832982007-11-15 19:07:47 +0000419 // Tell the header info that the main file was entered. If the file is later
420 // #imported, it won't be re-entered.
421 if (const FileEntry *FE =
422 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
423 HeaderInfo.IncrementIncludeCount(FE);
424
Chris Lattner53b0dab2007-10-09 22:10:18 +0000425 std::vector<char> PrologFile;
426 PrologFile.reserve(4080);
427
428 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
429 InitializePredefinedMacros(*this, PrologFile);
430
431 // Add on the predefines from the driver.
432 PrologFile.insert(PrologFile.end(), Predefines,Predefines+strlen(Predefines));
433
434 // Memory buffer must end with a null byte!
435 PrologFile.push_back(0);
436
437 // Now that we have emitted the predefined macros, #includes, etc into
438 // PrologFile, preprocess it to populate the initial preprocessor state.
439 llvm::MemoryBuffer *SB =
440 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
441 "<predefines>");
442 assert(SB && "Cannot fail to create predefined source buffer");
443 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
444 assert(FileID && "Could not create FileID for predefines?");
445
446 // Start parsing the predefines.
447 EnterSourceFile(FileID, 0);
448}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000449
Reid Spencer5f016e22007-07-11 17:01:13 +0000450//===----------------------------------------------------------------------===//
451// Source File Location Methods.
452//===----------------------------------------------------------------------===//
453
454/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
455/// return null on failure. isAngled indicates whether the file reference is
456/// for system #include's or not (i.e. using <> instead of "").
457const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
458 const char *FilenameEnd,
459 bool isAngled,
460 const DirectoryLookup *FromDir,
461 const DirectoryLookup *&CurDir) {
462 // If the header lookup mechanism may be relative to the current file, pass in
463 // info about where the current file is.
464 const FileEntry *CurFileEnt = 0;
465 if (!FromDir) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000466 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
467 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 }
469
470 // Do a standard file entry lookup.
471 CurDir = CurDirLookup;
472 const FileEntry *FE =
473 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
474 isAngled, FromDir, CurDir, CurFileEnt);
475 if (FE) return FE;
476
477 // Otherwise, see if this is a subframework header. If so, this is relative
478 // to one of the headers on the #include stack. Walk the list of the current
479 // headers on the #include stack and pass them to HeaderInfo.
480 if (CurLexer && !CurLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000481 CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
483 CurFileEnt)))
484 return FE;
485 }
486
487 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
488 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
489 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000490 CurFileEnt = SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
492 CurFileEnt)))
493 return FE;
494 }
495 }
496
497 // Otherwise, we really couldn't find the file.
498 return 0;
499}
500
501/// isInPrimaryFile - Return true if we're in the top-level file, not in a
502/// #include.
503bool Preprocessor::isInPrimaryFile() const {
504 if (CurLexer && !CurLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000505 return IncludeMacroStack.empty();
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
507 // If there are any stacked lexers, we're in a #include.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000508 assert(IncludeMacroStack[0].TheLexer &&
509 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
510 "Top level include stack isn't our primary lexer?");
511 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Reid Spencer5f016e22007-07-11 17:01:13 +0000512 if (IncludeMacroStack[i].TheLexer &&
513 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000514 return false;
515 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000516}
517
518/// getCurrentLexer - Return the current file lexer being lexed from. Note
519/// that this ignores any potentially active macro expansions and _Pragma
520/// expansions going on at the time.
521Lexer *Preprocessor::getCurrentFileLexer() const {
522 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
523
524 // Look for a stacked lexer.
525 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
526 Lexer *L = IncludeMacroStack[i-1].TheLexer;
527 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
528 return L;
529 }
530 return 0;
531}
532
533
534/// EnterSourceFile - Add a source file to the top of the include stack and
535/// start lexing tokens from it instead of the current buffer. Return true
536/// on failure.
537void Preprocessor::EnterSourceFile(unsigned FileID,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000538 const DirectoryLookup *CurDir) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
540 ++NumEnteredSourceFiles;
541
542 if (MaxIncludeStackDepth < IncludeMacroStack.size())
543 MaxIncludeStackDepth = IncludeMacroStack.size();
544
Chris Lattner25bdb512007-07-20 16:52:03 +0000545 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 EnterSourceFileWithLexer(TheLexer, CurDir);
547}
548
549/// EnterSourceFile - Add a source file to the top of the include stack and
550/// start lexing tokens from it instead of the current buffer.
551void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
552 const DirectoryLookup *CurDir) {
553
554 // Add the current lexer to the include stack.
555 if (CurLexer || CurMacroExpander)
556 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
557 CurMacroExpander));
558
559 CurLexer = TheLexer;
560 CurDirLookup = CurDir;
561 CurMacroExpander = 0;
562
563 // Notify the client, if desired, that we are in a new source file.
564 if (Callbacks && !CurLexer->Is_PragmaLexer) {
565 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
566
567 // Get the file entry for the current file.
568 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +0000569 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 FileType = HeaderInfo.getFileDirFlavor(FE);
571
Chris Lattner9dc1f532007-07-20 16:37:10 +0000572 Callbacks->FileChanged(CurLexer->getFileLoc(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 PPCallbacks::EnterFile, FileType);
574 }
575}
576
577
578
579/// EnterMacro - Add a Macro to the top of the include stack and start lexing
580/// tokens from it instead of the current buffer.
Chris Lattnerd2177732007-07-20 16:59:19 +0000581void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
583 CurMacroExpander));
584 CurLexer = 0;
585 CurDirLookup = 0;
586
Chris Lattner9594acf2007-07-15 00:25:26 +0000587 if (NumCachedMacroExpanders == 0) {
588 CurMacroExpander = new MacroExpander(Tok, Args, *this);
589 } else {
590 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
591 CurMacroExpander->Init(Tok, Args);
592 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000593}
594
595/// EnterTokenStream - Add a "macro" context to the top of the include stack,
596/// which will cause the lexer to start returning the specified tokens. Note
597/// that these tokens will be re-macro-expanded when/if expansion is enabled.
598/// This method assumes that the specified stream of tokens has a permanent
599/// owner somewhere, so they do not need to be copied.
Chris Lattnerd2177732007-07-20 16:59:19 +0000600void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 // Save our current state.
602 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
603 CurMacroExpander));
604 CurLexer = 0;
605 CurDirLookup = 0;
606
607 // Create a macro expander to expand from the specified token stream.
Chris Lattner9594acf2007-07-15 00:25:26 +0000608 if (NumCachedMacroExpanders == 0) {
609 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
610 } else {
611 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
612 CurMacroExpander->Init(Toks, NumToks);
613 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000614}
615
616/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
617/// lexer stack. This should only be used in situations where the current
618/// state of the top-of-stack lexer is known.
619void Preprocessor::RemoveTopOfLexerStack() {
620 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattner9594acf2007-07-15 00:25:26 +0000621
622 if (CurMacroExpander) {
623 // Delete or cache the now-dead macro expander.
624 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
625 delete CurMacroExpander;
626 else
627 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
628 } else {
629 delete CurLexer;
630 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 CurLexer = IncludeMacroStack.back().TheLexer;
632 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
633 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
634 IncludeMacroStack.pop_back();
635}
636
637//===----------------------------------------------------------------------===//
638// Macro Expansion Handling.
639//===----------------------------------------------------------------------===//
640
Chris Lattnercc1a8752007-10-07 08:44:20 +0000641/// setMacroInfo - Specify a macro for this identifier.
642///
643void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
644 if (MI == 0) {
645 if (II->hasMacroDefinition()) {
646 Macros.erase(II);
647 II->setHasMacroDefinition(false);
648 }
649 } else {
650 Macros[II] = MI;
651 II->setHasMacroDefinition(true);
652 }
653}
654
Reid Spencer5f016e22007-07-11 17:01:13 +0000655/// RegisterBuiltinMacro - Register the specified identifier in the identifier
656/// table and mark it as a builtin macro to be expanded.
657IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
658 // Get the identifier.
659 IdentifierInfo *Id = getIdentifierInfo(Name);
660
661 // Mark it as being a macro that is builtin.
662 MacroInfo *MI = new MacroInfo(SourceLocation());
663 MI->setIsBuiltinMacro();
Chris Lattnercc1a8752007-10-07 08:44:20 +0000664 setMacroInfo(Id, MI);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 return Id;
666}
667
668
669/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
670/// identifier table.
671void Preprocessor::RegisterBuiltinMacros() {
672 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
673 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
674 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
675 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
676 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
677
678 // GCC Extensions.
679 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
680 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
681 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
682}
683
684/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
685/// in its expansion, currently expands to that token literally.
686static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
Chris Lattnercc1a8752007-10-07 08:44:20 +0000687 const IdentifierInfo *MacroIdent,
688 Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
690
691 // If the token isn't an identifier, it's always literally expanded.
692 if (II == 0) return true;
693
694 // If the identifier is a macro, and if that macro is enabled, it may be
695 // expanded so it's not a trivial expansion.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000696 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 // Fast expanding "#define X X" is ok, because X would be disabled.
698 II != MacroIdent)
699 return false;
700
701 // If this is an object-like macro invocation, it is safe to trivially expand
702 // it.
703 if (MI->isObjectLike()) return true;
704
705 // If this is a function-like macro invocation, it's safe to trivially expand
706 // as long as the identifier is not a macro argument.
707 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
708 I != E; ++I)
709 if (*I == II)
710 return false; // Identifier is a macro argument.
711
712 return true;
713}
714
715
716/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
717/// lexed is a '('. If so, consume the token and return true, if not, this
718/// method should have no observable side-effect on the lexed tokens.
719bool Preprocessor::isNextPPTokenLParen() {
720 // Do some quick tests for rejection cases.
721 unsigned Val;
722 if (CurLexer)
723 Val = CurLexer->isNextPPTokenLParen();
724 else
725 Val = CurMacroExpander->isNextTokenLParen();
726
727 if (Val == 2) {
Chris Lattner0ea793e2007-07-19 00:07:36 +0000728 // We have run off the end. If it's a source file we don't
729 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
730 // macro stack.
731 if (CurLexer)
732 return false;
733 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
735 if (Entry.TheLexer)
736 Val = Entry.TheLexer->isNextPPTokenLParen();
737 else
738 Val = Entry.TheMacroExpander->isNextTokenLParen();
Chris Lattner0ea793e2007-07-19 00:07:36 +0000739
740 if (Val != 2)
741 break;
742
743 // Ran off the end of a source file?
744 if (Entry.TheLexer)
745 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 }
747 }
748
749 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
750 // have found something that isn't a '(' or we found the end of the
751 // translation unit. In either case, return false.
752 if (Val != 1)
753 return false;
754
Chris Lattnerd2177732007-07-20 16:59:19 +0000755 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000757 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 return true;
759}
760
761/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
762/// expanded as a macro, handle it and return the next token as 'Identifier'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000763bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 MacroInfo *MI) {
765
766 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
767 if (MI->isBuiltinMacro()) {
768 ExpandBuiltinMacro(Identifier);
769 return false;
770 }
771
772 // If this is the first use of a target-specific macro, warn about it.
773 if (MI->isTargetSpecific()) {
774 MI->setIsTargetSpecific(false); // Don't warn on second use.
775 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
776 diag::port_target_macro_use);
777 }
778
779 /// Args - If this is a function-like macro expansion, this contains,
780 /// for each macro argument, the list of tokens that were provided to the
781 /// invocation.
782 MacroArgs *Args = 0;
783
784 // If this is a function-like macro, read the arguments.
785 if (MI->isFunctionLike()) {
786 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000787 // name isn't a '(', this macro should not be expanded. Otherwise, consume
788 // it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 if (!isNextPPTokenLParen())
790 return true;
791
792 // Remember that we are now parsing the arguments to a macro invocation.
793 // Preprocessor directives used inside macro arguments are not portable, and
794 // this enables the warning.
795 InMacroArgs = true;
796 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
797
798 // Finished parsing args.
799 InMacroArgs = false;
800
801 // If there was an error parsing the arguments, bail out.
802 if (Args == 0) return false;
803
804 ++NumFnMacroExpanded;
805 } else {
806 ++NumMacroExpanded;
807 }
808
809 // Notice that this macro has been used.
810 MI->setIsUsed(true);
811
812 // If we started lexing a macro, enter the macro expansion body.
813
814 // If this macro expands to no tokens, don't bother to push it onto the
815 // expansion stack, only to take it right back off.
816 if (MI->getNumTokens() == 0) {
817 // No need for arg info.
818 if (Args) Args->destroy();
819
820 // Ignore this macro use, just return the next token in the current
821 // buffer.
822 bool HadLeadingSpace = Identifier.hasLeadingSpace();
823 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
824
825 Lex(Identifier);
826
827 // If the identifier isn't on some OTHER line, inherit the leading
828 // whitespace/first-on-a-line property of this token. This handles
829 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
830 // empty.
831 if (!Identifier.isAtStartOfLine()) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000832 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
833 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 }
835 ++NumFastMacroExpanded;
836 return false;
837
838 } else if (MI->getNumTokens() == 1 &&
Chris Lattnercc1a8752007-10-07 08:44:20 +0000839 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
840 *this)){
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 // Otherwise, if this macro expands into a single trivially-expanded
842 // token: expand it now. This handles common cases like
843 // "#define VAL 42".
844
845 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
846 // identifier to the expanded token.
847 bool isAtStartOfLine = Identifier.isAtStartOfLine();
848 bool hasLeadingSpace = Identifier.hasLeadingSpace();
849
850 // Remember where the token is instantiated.
851 SourceLocation InstantiateLoc = Identifier.getLocation();
852
853 // Replace the result token.
854 Identifier = MI->getReplacementToken(0);
855
856 // Restore the StartOfLine/LeadingSpace markers.
Chris Lattnerd2177732007-07-20 16:59:19 +0000857 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
858 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
860 // Update the tokens location to include both its logical and physical
861 // locations.
862 SourceLocation Loc =
863 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
864 Identifier.setLocation(Loc);
865
866 // If this is #define X X, we must mark the result as unexpandible.
867 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
Chris Lattnercc1a8752007-10-07 08:44:20 +0000868 if (getMacroInfo(NewII) == MI)
Chris Lattnerd2177732007-07-20 16:59:19 +0000869 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000870
871 // Since this is not an identifier token, it can't be macro expanded, so
872 // we're done.
873 ++NumFastMacroExpanded;
874 return false;
875 }
876
877 // Start expanding the macro.
878 EnterMacro(Identifier, Args);
879
880 // Now that the macro is at the top of the include stack, ask the
881 // preprocessor to read the next token from it.
882 Lex(Identifier);
883 return false;
884}
885
886/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
887/// invoked to read all of the actual arguments specified for the macro
888/// invocation. This returns null on error.
Chris Lattnerd2177732007-07-20 16:59:19 +0000889MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 MacroInfo *MI) {
891 // The number of fixed arguments to parse.
892 unsigned NumFixedArgsLeft = MI->getNumArgs();
893 bool isVariadic = MI->isVariadic();
894
895 // Outer loop, while there are more arguments, keep reading them.
Chris Lattnerd2177732007-07-20 16:59:19 +0000896 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 Tok.setKind(tok::comma);
898 --NumFixedArgsLeft; // Start reading the first arg.
899
900 // ArgTokens - Build up a list of tokens that make up each argument. Each
901 // argument is separated by an EOF token. Use a SmallVector so we can avoid
902 // heap allocations in the common case.
Chris Lattnerd2177732007-07-20 16:59:19 +0000903 llvm::SmallVector<Token, 64> ArgTokens;
Reid Spencer5f016e22007-07-11 17:01:13 +0000904
905 unsigned NumActuals = 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000906 while (Tok.is(tok::comma)) {
Chris Lattner2b64fdc2007-07-19 16:11:58 +0000907 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
908 // that we already consumed the first one.
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 unsigned NumParens = 0;
910
911 while (1) {
912 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
913 // an argument value in a macro could expand to ',' or '(' or ')'.
914 LexUnexpandedToken(Tok);
915
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000916 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 Diag(MacroName, diag::err_unterm_macro_invoc);
918 // Do not lose the EOF. Return it to the client.
919 MacroName = Tok;
920 return 0;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000921 } else if (Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 // If we found the ) token, the macro arg list is done.
923 if (NumParens-- == 0)
924 break;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000925 } else if (Tok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 ++NumParens;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000927 } else if (Tok.is(tok::comma) && NumParens == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 // Comma ends this argument if there are more fixed arguments expected.
929 if (NumFixedArgsLeft)
930 break;
931
932 // If this is not a variadic macro, too many args were specified.
933 if (!isVariadic) {
934 // Emit the diagnostic at the macro name in case there is a missing ).
935 // Emitting it at the , could be far away from the macro name.
936 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
937 return 0;
938 }
939 // Otherwise, continue to add the tokens to this variable argument.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000940 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 // If this is a comment token in the argument list and we're just in
942 // -C mode (not -CC mode), discard the comment.
943 continue;
944 }
945
946 ArgTokens.push_back(Tok);
947 }
948
949 // Empty arguments are standard in C99 and supported as an extension in
950 // other modes.
951 if (ArgTokens.empty() && !Features.C99)
952 Diag(Tok, diag::ext_empty_fnmacro_arg);
953
954 // Add a marker EOF token to the end of the token list for this argument.
Chris Lattnerd2177732007-07-20 16:59:19 +0000955 Token EOFTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 EOFTok.startToken();
957 EOFTok.setKind(tok::eof);
958 EOFTok.setLocation(Tok.getLocation());
959 EOFTok.setLength(0);
960 ArgTokens.push_back(EOFTok);
961 ++NumActuals;
962 --NumFixedArgsLeft;
963 };
964
965 // Okay, we either found the r_paren. Check to see if we parsed too few
966 // arguments.
967 unsigned MinArgsExpected = MI->getNumArgs();
968
969 // See MacroArgs instance var for description of this.
970 bool isVarargsElided = false;
971
972 if (NumActuals < MinArgsExpected) {
973 // There are several cases where too few arguments is ok, handle them now.
974 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
975 // Varargs where the named vararg parameter is missing: ok as extension.
976 // #define A(x, ...)
977 // A("blah")
978 Diag(Tok, diag::ext_missing_varargs_arg);
979
980 // Remember this occurred if this is a C99 macro invocation with at least
981 // one actual argument.
982 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
983 } else if (MI->getNumArgs() == 1) {
984 // #define A(x)
985 // A()
986 // is ok because it is an empty argument.
987
988 // Empty arguments are standard in C99 and supported as an extension in
989 // other modes.
990 if (ArgTokens.empty() && !Features.C99)
991 Diag(Tok, diag::ext_empty_fnmacro_arg);
992 } else {
993 // Otherwise, emit the error.
994 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
995 return 0;
996 }
997
998 // Add a marker EOF token to the end of the token list for this argument.
999 SourceLocation EndLoc = Tok.getLocation();
1000 Tok.startToken();
1001 Tok.setKind(tok::eof);
1002 Tok.setLocation(EndLoc);
1003 Tok.setLength(0);
1004 ArgTokens.push_back(Tok);
1005 }
1006
1007 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
1008}
1009
1010/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1011/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1012/// the identifier tokens inserted.
1013static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1014 Preprocessor &PP) {
1015 time_t TT = time(0);
1016 struct tm *TM = localtime(&TT);
1017
1018 static const char * const Months[] = {
1019 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1020 };
1021
1022 char TmpBuffer[100];
1023 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
1024 TM->tm_year+1900);
1025 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1026
1027 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
1028 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
1029}
1030
1031/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1032/// as a builtin macro, handle it and return the next token as 'Tok'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001033void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 // Figure out which token this is.
1035 IdentifierInfo *II = Tok.getIdentifierInfo();
1036 assert(II && "Can't be a macro without id info!");
1037
1038 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
1039 // lex the token after it.
1040 if (II == Ident_Pragma)
1041 return Handle_Pragma(Tok);
1042
1043 ++NumBuiltinMacroExpanded;
1044
1045 char TmpBuffer[100];
1046
1047 // Set up the return result.
1048 Tok.setIdentifierInfo(0);
Chris Lattnerd2177732007-07-20 16:59:19 +00001049 Tok.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001050
1051 if (II == Ident__LINE__) {
1052 // __LINE__ expands to a simple numeric value.
Chris Lattner9dc1f532007-07-20 16:37:10 +00001053 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 unsigned Length = strlen(TmpBuffer);
1055 Tok.setKind(tok::numeric_constant);
1056 Tok.setLength(Length);
1057 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1058 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1059 SourceLocation Loc = Tok.getLocation();
1060 if (II == Ident__BASE_FILE__) {
1061 Diag(Tok, diag::ext_pp_base_file);
Chris Lattner9dc1f532007-07-20 16:37:10 +00001062 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
1063 while (NextLoc.isValid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 Loc = NextLoc;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001065 NextLoc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001066 }
1067 }
1068
1069 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Chris Lattner9dc1f532007-07-20 16:37:10 +00001070 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 FN = '"' + Lexer::Stringify(FN) + '"';
1072 Tok.setKind(tok::string_literal);
1073 Tok.setLength(FN.size());
1074 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
1075 } else if (II == Ident__DATE__) {
1076 if (!DATELoc.isValid())
1077 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1078 Tok.setKind(tok::string_literal);
1079 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1080 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
1081 } else if (II == Ident__TIME__) {
1082 if (!TIMELoc.isValid())
1083 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1084 Tok.setKind(tok::string_literal);
1085 Tok.setLength(strlen("\"hh:mm:ss\""));
1086 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
1087 } else if (II == Ident__INCLUDE_LEVEL__) {
1088 Diag(Tok, diag::ext_pp_include_level);
1089
1090 // Compute the include depth of this token.
1091 unsigned Depth = 0;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001092 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
1093 for (; Loc.isValid(); ++Depth)
1094 Loc = SourceMgr.getIncludeLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001095
1096 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1097 sprintf(TmpBuffer, "%u", Depth);
1098 unsigned Length = strlen(TmpBuffer);
1099 Tok.setKind(tok::numeric_constant);
1100 Tok.setLength(Length);
1101 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
1102 } else if (II == Ident__TIMESTAMP__) {
1103 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1104 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1105 Diag(Tok, diag::ext_pp_timestamp);
1106
1107 // Get the file that we are lexing out of. If we're currently lexing from
1108 // a macro, dig into the include stack.
1109 const FileEntry *CurFile = 0;
1110 Lexer *TheLexer = getCurrentFileLexer();
1111
1112 if (TheLexer)
Chris Lattner9dc1f532007-07-20 16:37:10 +00001113 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001114
1115 // If this file is older than the file it depends on, emit a diagnostic.
1116 const char *Result;
1117 if (CurFile) {
1118 time_t TT = CurFile->getModificationTime();
1119 struct tm *TM = localtime(&TT);
1120 Result = asctime(TM);
1121 } else {
1122 Result = "??? ??? ?? ??:??:?? ????\n";
1123 }
1124 TmpBuffer[0] = '"';
1125 strcpy(TmpBuffer+1, Result);
1126 unsigned Len = strlen(TmpBuffer);
1127 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
1128 Tok.setKind(tok::string_literal);
1129 Tok.setLength(Len);
1130 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
1131 } else {
1132 assert(0 && "Unknown identifier!");
1133 }
1134}
1135
1136//===----------------------------------------------------------------------===//
1137// Lexer Event Handling.
1138//===----------------------------------------------------------------------===//
1139
1140/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
1141/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +00001142IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001144 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
1146
1147 // Look up this token, see if it is a macro, or if it is a language keyword.
1148 IdentifierInfo *II;
1149 if (BufPtr && !Identifier.needsCleaning()) {
1150 // No cleaning needed, just use the characters from the lexed buffer.
1151 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
1152 } else {
1153 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +00001154 llvm::SmallVector<char, 64> IdentifierBuffer;
1155 IdentifierBuffer.resize(Identifier.getLength());
1156 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 unsigned Size = getSpelling(Identifier, TmpBuf);
1158 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
1159 }
1160 Identifier.setIdentifierInfo(II);
1161 return II;
1162}
1163
1164
1165/// HandleIdentifier - This callback is invoked when the lexer reads an
1166/// identifier. This callback looks up the identifier in the map and/or
1167/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerd2177732007-07-20 16:59:19 +00001168void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 assert(Identifier.getIdentifierInfo() &&
1170 "Can't handle identifiers without identifier info!");
1171
1172 IdentifierInfo &II = *Identifier.getIdentifierInfo();
1173
1174 // If this identifier was poisoned, and if it was not produced from a macro
1175 // expansion, emit an error.
1176 if (II.isPoisoned() && CurLexer) {
1177 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
1178 Diag(Identifier, diag::err_pp_used_poisoned_id);
1179 else
1180 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
1181 }
1182
1183 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +00001184 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
1186 if (MI->isEnabled()) {
1187 if (!HandleMacroExpandedIdentifier(Identifier, MI))
1188 return;
1189 } else {
1190 // C99 6.10.3.4p2 says that a disabled macro may never again be
1191 // expanded, even if it's in a context where it could be expanded in the
1192 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +00001193 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 }
1195 }
1196 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
1197 // If this identifier is a macro on some other target, emit a diagnostic.
1198 // This diagnosic is only emitted when macro expansion is enabled, because
1199 // the macro would not have been expanded for the other target either.
1200 II.setIsOtherTargetMacro(false); // Don't warn on second use.
1201 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
1202 diag::port_target_macro_use);
1203
1204 }
1205
1206 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
1207 // then we act as if it is the actual operator and not the textual
1208 // representation of it.
1209 if (II.isCPlusPlusOperatorKeyword())
1210 Identifier.setIdentifierInfo(0);
1211
1212 // Change the kind of this identifier to the appropriate token kind, e.g.
1213 // turning "for" into a keyword.
1214 Identifier.setKind(II.getTokenID());
1215
1216 // If this is an extension token, diagnose its use.
1217 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
1218 // For now, I'm just commenting it out (while I work on attributes).
1219 if (II.isExtensionToken() && Features.C99)
1220 Diag(Identifier, diag::ext_token_used);
1221}
1222
1223/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1224/// the current file. This either returns the EOF token or pops a level off
1225/// the include stack and keeps going.
Chris Lattnerd2177732007-07-20 16:59:19 +00001226bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 assert(!CurMacroExpander &&
1228 "Ending a file when currently in a macro!");
1229
1230 // See if this file had a controlling macro.
1231 if (CurLexer) { // Not ending a macro, ignore it.
1232 if (const IdentifierInfo *ControllingMacro =
1233 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
1234 // Okay, this has a controlling macro, remember in PerFileInfo.
1235 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001236 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
1238 }
1239 }
1240
1241 // If this is a #include'd file, pop it off the include stack and continue
1242 // lexing the #includer file.
1243 if (!IncludeMacroStack.empty()) {
1244 // We're done with the #included file.
1245 RemoveTopOfLexerStack();
1246
1247 // Notify the client, if desired, that we are in a new source file.
1248 if (Callbacks && !isEndOfMacro && CurLexer) {
1249 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1250
1251 // Get the file entry for the current file.
1252 if (const FileEntry *FE =
Chris Lattner9dc1f532007-07-20 16:37:10 +00001253 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 FileType = HeaderInfo.getFileDirFlavor(FE);
1255
1256 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1257 PPCallbacks::ExitFile, FileType);
1258 }
1259
1260 // Client should lex another token.
1261 return false;
1262 }
1263
1264 Result.startToken();
1265 CurLexer->BufferPtr = CurLexer->BufferEnd;
1266 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
1267 Result.setKind(tok::eof);
1268
1269 // We're done with the #included file.
1270 delete CurLexer;
1271 CurLexer = 0;
1272
1273 // This is the end of the top-level file. If the diag::pp_macro_not_used
Chris Lattnercc1a8752007-10-07 08:44:20 +00001274 // diagnostic is enabled, look for macros that have not been used.
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
Chris Lattnercc1a8752007-10-07 08:44:20 +00001276 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
1277 Macros.begin(), E = Macros.end(); I != E; ++I) {
1278 if (!I->second->isUsed())
1279 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 }
1281 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 return true;
1283}
1284
1285/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
1286/// the current macro expansion or token stream expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00001287bool Preprocessor::HandleEndOfMacro(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 assert(CurMacroExpander && !CurLexer &&
1289 "Ending a macro when currently in a #include file!");
1290
Chris Lattner9594acf2007-07-15 00:25:26 +00001291 // Delete or cache the now-dead macro expander.
1292 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1293 delete CurMacroExpander;
1294 else
1295 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Reid Spencer5f016e22007-07-11 17:01:13 +00001296
1297 // Handle this like a #include file being popped off the stack.
1298 CurMacroExpander = 0;
1299 return HandleEndOfFile(Result, true);
1300}
1301
1302
1303//===----------------------------------------------------------------------===//
1304// Utility Methods for Preprocessor Directive Handling.
1305//===----------------------------------------------------------------------===//
1306
1307/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1308/// current line until the tok::eom token is found.
1309void Preprocessor::DiscardUntilEndOfDirective() {
Chris Lattnerd2177732007-07-20 16:59:19 +00001310 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 do {
1312 LexUnexpandedToken(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001313 } while (Tmp.isNot(tok::eom));
Reid Spencer5f016e22007-07-11 17:01:13 +00001314}
1315
1316/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1317static bool isCXXNamedOperator(const std::string &Spelling) {
1318 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1319 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1320 Spelling == "or" || Spelling == "xor";
1321}
1322
1323/// ReadMacroName - Lex and validate a macro name, which occurs after a
1324/// #define or #undef. This sets the token kind to eom and discards the rest
1325/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1326/// this is due to a a #define, 2 if #undef directive, 0 if it is something
1327/// else (e.g. #ifdef).
Chris Lattnerd2177732007-07-20 16:59:19 +00001328void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 // Read the token, don't allow macro expansion on it.
1330 LexUnexpandedToken(MacroNameTok);
1331
1332 // Missing macro name?
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001333 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1335
1336 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1337 if (II == 0) {
1338 std::string Spelling = getSpelling(MacroNameTok);
1339 if (isCXXNamedOperator(Spelling))
1340 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1341 // except for their spellings.
1342 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1343 else
1344 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
1345 // Fall through on error.
1346 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
1347 // Error if defining "defined": C99 6.10.8.4.
1348 Diag(MacroNameTok, diag::err_defined_macro_name);
Chris Lattner0edde552007-10-07 08:04:56 +00001349 } else if (isDefineUndef && II->hasMacroDefinition() &&
Chris Lattnercc1a8752007-10-07 08:44:20 +00001350 getMacroInfo(II)->isBuiltinMacro()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
1352 if (isDefineUndef == 1)
1353 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1354 else
1355 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
1356 } else {
1357 // Okay, we got a good identifier node. Return it.
1358 return;
1359 }
1360
1361 // Invalid macro name, read and discard the rest of the line. Then set the
1362 // token kind to tok::eom.
1363 MacroNameTok.setKind(tok::eom);
1364 return DiscardUntilEndOfDirective();
1365}
1366
1367/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1368/// not, emit a diagnostic and consume up until the eom.
1369void Preprocessor::CheckEndOfDirective(const char *DirType) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001370 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 Lex(Tmp);
1372 // There should be no tokens after the directive, but we allow them as an
1373 // extension.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001374 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 Lex(Tmp);
1376
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001377 if (Tmp.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1379 DiscardUntilEndOfDirective();
1380 }
1381}
1382
1383
1384
1385/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1386/// decided that the subsequent tokens are in the #if'd out portion of the
1387/// file. Lex the rest of the file, until we see an #endif. If
1388/// FoundNonSkipPortion is true, then we have already emitted code for part of
1389/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1390/// is true, then #else directives are ok, if not, then we have already seen one
1391/// so a #else directive is a duplicate. When this returns, the caller can lex
1392/// the first valid token.
1393void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1394 bool FoundNonSkipPortion,
1395 bool FoundElse) {
1396 ++NumSkipped;
1397 assert(CurMacroExpander == 0 && CurLexer &&
1398 "Lexing a macro, not a file?");
1399
1400 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1401 FoundNonSkipPortion, FoundElse);
1402
1403 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1404 // disabling warnings, etc.
1405 CurLexer->LexingRawMode = true;
Chris Lattnerd2177732007-07-20 16:59:19 +00001406 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 while (1) {
1408 CurLexer->Lex(Tok);
1409
1410 // If this is the end of the buffer, we have an error.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001411 if (Tok.is(tok::eof)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 // Emit errors for each unterminated conditional on the stack, including
1413 // the current one.
1414 while (!CurLexer->ConditionalStack.empty()) {
1415 Diag(CurLexer->ConditionalStack.back().IfLoc,
1416 diag::err_pp_unterminated_conditional);
1417 CurLexer->ConditionalStack.pop_back();
1418 }
1419
1420 // Just return and let the caller lex after this #include.
1421 break;
1422 }
1423
1424 // If this token is not a preprocessor directive, just skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001425 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 continue;
1427
1428 // We just parsed a # character at the start of a line, so we're in
1429 // directive mode. Tell the lexer this so any newlines we see will be
1430 // converted into an EOM token (this terminates the macro).
1431 CurLexer->ParsingPreprocessorDirective = true;
1432 CurLexer->KeepCommentMode = false;
1433
1434
1435 // Read the next token, the directive flavor.
1436 LexUnexpandedToken(Tok);
1437
1438 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1439 // something bogus), skip it.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001440 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 CurLexer->ParsingPreprocessorDirective = false;
1442 // Restore comment saving mode.
1443 CurLexer->KeepCommentMode = KeepComments;
1444 continue;
1445 }
1446
1447 // If the first letter isn't i or e, it isn't intesting to us. We know that
1448 // this is safe in the face of spelling differences, because there is no way
1449 // to spell an i/e in a strange way that is another letter. Skipping this
1450 // allows us to avoid looking up the identifier info for #define/#undef and
1451 // other common directives.
1452 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1453 char FirstChar = RawCharData[0];
1454 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1455 FirstChar != 'i' && FirstChar != 'e') {
1456 CurLexer->ParsingPreprocessorDirective = false;
1457 // Restore comment saving mode.
1458 CurLexer->KeepCommentMode = KeepComments;
1459 continue;
1460 }
1461
1462 // Get the identifier name without trigraphs or embedded newlines. Note
1463 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1464 // when skipping.
1465 // TODO: could do this with zero copies in the no-clean case by using
1466 // strncmp below.
1467 char Directive[20];
1468 unsigned IdLen;
1469 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1470 IdLen = Tok.getLength();
1471 memcpy(Directive, RawCharData, IdLen);
1472 Directive[IdLen] = 0;
1473 } else {
1474 std::string DirectiveStr = getSpelling(Tok);
1475 IdLen = DirectiveStr.size();
1476 if (IdLen >= 20) {
1477 CurLexer->ParsingPreprocessorDirective = false;
1478 // Restore comment saving mode.
1479 CurLexer->KeepCommentMode = KeepComments;
1480 continue;
1481 }
1482 memcpy(Directive, &DirectiveStr[0], IdLen);
1483 Directive[IdLen] = 0;
1484 }
1485
1486 if (FirstChar == 'i' && Directive[1] == 'f') {
1487 if ((IdLen == 2) || // "if"
1488 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1489 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
1490 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1491 // bother parsing the condition.
1492 DiscardUntilEndOfDirective();
1493 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
1494 /*foundnonskip*/false,
1495 /*fnddelse*/false);
1496 }
1497 } else if (FirstChar == 'e') {
1498 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
1499 CheckEndOfDirective("#endif");
1500 PPConditionalInfo CondInfo;
1501 CondInfo.WasSkipping = true; // Silence bogus warning.
1502 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1503 InCond = InCond; // Silence warning in no-asserts mode.
1504 assert(!InCond && "Can't be skipping if not in a conditional!");
1505
1506 // If we popped the outermost skipping block, we're done skipping!
1507 if (!CondInfo.WasSkipping)
1508 break;
1509 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
1510 // #else directive in a skipping conditional. If not in some other
1511 // skipping conditional, and if #else hasn't already been seen, enter it
1512 // as a non-skipping conditional.
1513 CheckEndOfDirective("#else");
1514 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1515
1516 // If this is a #else with a #else before it, report the error.
1517 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
1518
1519 // Note that we've seen a #else in this conditional.
1520 CondInfo.FoundElse = true;
1521
1522 // If the conditional is at the top level, and the #if block wasn't
1523 // entered, enter the #else block now.
1524 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1525 CondInfo.FoundNonSkip = true;
1526 break;
1527 }
1528 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
1529 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1530
1531 bool ShouldEnter;
1532 // If this is in a skipping block or if we're already handled this #if
1533 // block, don't bother parsing the condition.
1534 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
1535 DiscardUntilEndOfDirective();
1536 ShouldEnter = false;
1537 } else {
1538 // Restore the value of LexingRawMode so that identifiers are
1539 // looked up, etc, inside the #elif expression.
1540 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1541 CurLexer->LexingRawMode = false;
1542 IdentifierInfo *IfNDefMacro = 0;
1543 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
1544 CurLexer->LexingRawMode = true;
1545 }
1546
1547 // If this is a #elif with a #else before it, report the error.
1548 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
1549
1550 // If this condition is true, enter it!
1551 if (ShouldEnter) {
1552 CondInfo.FoundNonSkip = true;
1553 break;
1554 }
1555 }
1556 }
1557
1558 CurLexer->ParsingPreprocessorDirective = false;
1559 // Restore comment saving mode.
1560 CurLexer->KeepCommentMode = KeepComments;
1561 }
1562
1563 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1564 // of the file, just stop skipping and return to lexing whatever came after
1565 // the #if block.
1566 CurLexer->LexingRawMode = false;
1567}
1568
1569//===----------------------------------------------------------------------===//
1570// Preprocessor Directive Handling.
1571//===----------------------------------------------------------------------===//
1572
1573/// HandleDirective - This callback is invoked when the lexer sees a # token
1574/// at the start of a line. This consumes the directive, modifies the
1575/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1576/// read is the correct one.
Chris Lattnerd2177732007-07-20 16:59:19 +00001577void Preprocessor::HandleDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1579
1580 // We just parsed a # character at the start of a line, so we're in directive
1581 // mode. Tell the lexer this so any newlines we see will be converted into an
1582 // EOM token (which terminates the directive).
1583 CurLexer->ParsingPreprocessorDirective = true;
1584
1585 ++NumDirectives;
1586
1587 // We are about to read a token. For the multiple-include optimization FA to
1588 // work, we have to remember if we had read any tokens *before* this
1589 // pp-directive.
1590 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1591
1592 // Read the next token, the directive flavor. This isn't expanded due to
1593 // C99 6.10.3p8.
1594 LexUnexpandedToken(Result);
1595
1596 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1597 // #define A(x) #x
1598 // A(abc
1599 // #warning blah
1600 // def)
1601 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1602 if (InMacroArgs)
1603 Diag(Result, diag::ext_embedded_directive);
1604
1605TryAgain:
1606 switch (Result.getKind()) {
1607 case tok::eom:
1608 return; // null directive.
1609 case tok::comment:
1610 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1611 LexUnexpandedToken(Result);
1612 goto TryAgain;
1613
1614 case tok::numeric_constant:
1615 // FIXME: implement # 7 line numbers!
1616 DiscardUntilEndOfDirective();
1617 return;
1618 default:
1619 IdentifierInfo *II = Result.getIdentifierInfo();
1620 if (II == 0) break; // Not an identifier.
1621
1622 // Ask what the preprocessor keyword ID is.
1623 switch (II->getPPKeywordID()) {
1624 default: break;
1625 // C99 6.10.1 - Conditional Inclusion.
1626 case tok::pp_if:
1627 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1628 case tok::pp_ifdef:
1629 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1630 case tok::pp_ifndef:
1631 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1632 case tok::pp_elif:
1633 return HandleElifDirective(Result);
1634 case tok::pp_else:
1635 return HandleElseDirective(Result);
1636 case tok::pp_endif:
1637 return HandleEndifDirective(Result);
1638
1639 // C99 6.10.2 - Source File Inclusion.
1640 case tok::pp_include:
1641 return HandleIncludeDirective(Result); // Handle #include.
1642
1643 // C99 6.10.3 - Macro Replacement.
1644 case tok::pp_define:
1645 return HandleDefineDirective(Result, false);
1646 case tok::pp_undef:
1647 return HandleUndefDirective(Result);
1648
1649 // C99 6.10.4 - Line Control.
1650 case tok::pp_line:
1651 // FIXME: implement #line
1652 DiscardUntilEndOfDirective();
1653 return;
1654
1655 // C99 6.10.5 - Error Directive.
1656 case tok::pp_error:
1657 return HandleUserDiagnosticDirective(Result, false);
1658
1659 // C99 6.10.6 - Pragma Directive.
1660 case tok::pp_pragma:
1661 return HandlePragmaDirective();
1662
1663 // GNU Extensions.
1664 case tok::pp_import:
1665 return HandleImportDirective(Result);
1666 case tok::pp_include_next:
1667 return HandleIncludeNextDirective(Result);
1668
1669 case tok::pp_warning:
1670 Diag(Result, diag::ext_pp_warning_directive);
1671 return HandleUserDiagnosticDirective(Result, true);
1672 case tok::pp_ident:
1673 return HandleIdentSCCSDirective(Result);
1674 case tok::pp_sccs:
1675 return HandleIdentSCCSDirective(Result);
1676 case tok::pp_assert:
1677 //isExtension = true; // FIXME: implement #assert
1678 break;
1679 case tok::pp_unassert:
1680 //isExtension = true; // FIXME: implement #unassert
1681 break;
1682
1683 // clang extensions.
1684 case tok::pp_define_target:
1685 return HandleDefineDirective(Result, true);
1686 case tok::pp_define_other_target:
1687 return HandleDefineOtherTargetDirective(Result);
1688 }
1689 break;
1690 }
1691
1692 // If we reached here, the preprocessing token is not valid!
1693 Diag(Result, diag::err_pp_invalid_directive);
1694
1695 // Read the rest of the PP line.
1696 DiscardUntilEndOfDirective();
1697
1698 // Okay, we're done parsing the directive.
1699}
1700
Chris Lattnerd2177732007-07-20 16:59:19 +00001701void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 bool isWarning) {
1703 // Read the rest of the line raw. We do this because we don't want macros
1704 // to be expanded and we don't require that the tokens be valid preprocessing
1705 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1706 // collapse multiple consequtive white space between tokens, but this isn't
1707 // specified by the standard.
1708 std::string Message = CurLexer->ReadToEndOfLine();
1709
1710 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1711 return Diag(Tok, DiagID, Message);
1712}
1713
1714/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1715///
Chris Lattnerd2177732007-07-20 16:59:19 +00001716void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // Yes, this directive is an extension.
1718 Diag(Tok, diag::ext_pp_ident_directive);
1719
1720 // Read the string argument.
Chris Lattnerd2177732007-07-20 16:59:19 +00001721 Token StrTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 Lex(StrTok);
1723
1724 // If the token kind isn't a string, it's a malformed directive.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001725 if (StrTok.isNot(tok::string_literal) &&
1726 StrTok.isNot(tok::wide_string_literal))
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 return Diag(StrTok, diag::err_pp_malformed_ident);
1728
1729 // Verify that there is nothing after the string, other than EOM.
1730 CheckEndOfDirective("#ident");
1731
1732 if (Callbacks)
1733 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
1734}
1735
1736//===----------------------------------------------------------------------===//
1737// Preprocessor Include Directive Handling.
1738//===----------------------------------------------------------------------===//
1739
1740/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1741/// checked and spelled filename, e.g. as an operand of #include. This returns
1742/// true if the input filename was in <>'s or false if it were in ""'s. The
1743/// caller is expected to provide a buffer that is large enough to hold the
1744/// spelling of the filename, but is also expected to handle the case when
1745/// this method decides to use a different buffer.
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001746bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 const char *&BufStart,
1748 const char *&BufEnd) {
1749 // Get the text form of the filename.
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1751
1752 // Make sure the filename is <x> or "x".
1753 bool isAngled;
1754 if (BufStart[0] == '<') {
1755 if (BufEnd[-1] != '>') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001756 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 BufStart = 0;
1758 return true;
1759 }
1760 isAngled = true;
1761 } else if (BufStart[0] == '"') {
1762 if (BufEnd[-1] != '"') {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001763 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 BufStart = 0;
1765 return true;
1766 }
1767 isAngled = false;
1768 } else {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001769 Diag(Loc, diag::err_pp_expects_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 BufStart = 0;
1771 return true;
1772 }
1773
1774 // Diagnose #include "" as invalid.
1775 if (BufEnd-BufStart <= 2) {
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001776 Diag(Loc, diag::err_pp_empty_filename);
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 BufStart = 0;
1778 return "";
1779 }
1780
1781 // Skip the brackets.
1782 ++BufStart;
1783 --BufEnd;
1784 return isAngled;
1785}
1786
Chris Lattner706ab502007-07-23 04:56:47 +00001787/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1788/// from a macro as multiple tokens, which need to be glued together. This
1789/// occurs for code like:
1790/// #define FOO <a/b.h>
1791/// #include FOO
1792/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1793///
1794/// This code concatenates and consumes tokens up to the '>' token. It returns
1795/// false if the > was found, otherwise it returns true if it finds and consumes
1796/// the EOM marker.
1797static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer,
1798 Preprocessor &PP) {
1799 Token CurTok;
1800
1801 PP.Lex(CurTok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001802 while (CurTok.isNot(tok::eom)) {
Chris Lattner706ab502007-07-23 04:56:47 +00001803 // Append the spelling of this token to the buffer. If there was a space
1804 // before it, add it now.
1805 if (CurTok.hasLeadingSpace())
1806 FilenameBuffer.push_back(' ');
1807
1808 // Get the spelling of the token, directly into FilenameBuffer if possible.
1809 unsigned PreAppendSize = FilenameBuffer.size();
1810 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1811
1812 const char *BufPtr = &FilenameBuffer[PreAppendSize];
1813 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr);
1814
1815 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1816 if (BufPtr != &FilenameBuffer[PreAppendSize])
1817 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1818
1819 // Resize FilenameBuffer to the correct size.
1820 if (CurTok.getLength() != ActualLen)
1821 FilenameBuffer.resize(PreAppendSize+ActualLen);
1822
1823 // If we found the '>' marker, return success.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001824 if (CurTok.is(tok::greater))
Chris Lattner706ab502007-07-23 04:56:47 +00001825 return false;
1826
1827 PP.Lex(CurTok);
1828 }
1829
1830 // If we hit the eom marker, emit an error and return true so that the caller
1831 // knows the EOM has been read.
1832 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1833 return true;
1834}
1835
Reid Spencer5f016e22007-07-11 17:01:13 +00001836/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1837/// file to be included from the lexer, then include it! This is a common
1838/// routine with functionality shared between #include, #include_next and
1839/// #import.
Chris Lattnerd2177732007-07-20 16:59:19 +00001840void Preprocessor::HandleIncludeDirective(Token &IncludeTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 const DirectoryLookup *LookupFrom,
1842 bool isImport) {
1843
Chris Lattnerd2177732007-07-20 16:59:19 +00001844 Token FilenameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 CurLexer->LexIncludeFilename(FilenameTok);
1846
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 // Reserve a buffer to get the spelling.
1848 llvm::SmallVector<char, 128> FilenameBuffer;
Chris Lattner706ab502007-07-23 04:56:47 +00001849 const char *FilenameStart, *FilenameEnd;
1850
1851 switch (FilenameTok.getKind()) {
1852 case tok::eom:
1853 // If the token kind is EOM, the error has already been diagnosed.
1854 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001855
Chris Lattner706ab502007-07-23 04:56:47 +00001856 case tok::angle_string_literal:
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001857 case tok::string_literal: {
Chris Lattner706ab502007-07-23 04:56:47 +00001858 FilenameBuffer.resize(FilenameTok.getLength());
1859 FilenameStart = &FilenameBuffer[0];
1860 unsigned Len = getSpelling(FilenameTok, FilenameStart);
1861 FilenameEnd = FilenameStart+Len;
1862 break;
Chris Lattnerf11ccfc2007-07-23 22:23:52 +00001863 }
Chris Lattner706ab502007-07-23 04:56:47 +00001864
1865 case tok::less:
1866 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1867 // case, glue the tokens together into FilenameBuffer and interpret those.
1868 FilenameBuffer.push_back('<');
1869 if (ConcatenateIncludeName(FilenameBuffer, *this))
1870 return; // Found <eom> but no ">"? Diagnostic already emitted.
1871 FilenameStart = &FilenameBuffer[0];
1872 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()];
1873 break;
1874 default:
1875 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1876 DiscardUntilEndOfDirective();
1877 return;
1878 }
1879
Chris Lattnerf1c99ac2007-07-23 04:15:27 +00001880 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 FilenameStart, FilenameEnd);
1882 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1883 // error.
Chris Lattner706ab502007-07-23 04:56:47 +00001884 if (FilenameStart == 0) {
1885 DiscardUntilEndOfDirective();
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 return;
Chris Lattner706ab502007-07-23 04:56:47 +00001887 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001888
1889 // Verify that there is nothing after the filename, other than EOM. Use the
1890 // preprocessor to lex this in case lexing the filename entered a macro.
1891 CheckEndOfDirective("#include");
1892
1893 // Check that we don't have infinite #include recursion.
1894 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
1895 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1896
1897 // Search include directories.
1898 const DirectoryLookup *CurDir;
1899 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1900 isAngled, LookupFrom, CurDir);
1901 if (File == 0)
1902 return Diag(FilenameTok, diag::err_pp_file_not_found,
1903 std::string(FilenameStart, FilenameEnd));
1904
1905 // Ask HeaderInfo if we should enter this #include file.
1906 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1907 // If it returns true, #including this file will have no effect.
1908 return;
1909 }
1910
1911 // Look up the file, create a File ID for it.
1912 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
1913 if (FileID == 0)
1914 return Diag(FilenameTok, diag::err_pp_file_not_found,
1915 std::string(FilenameStart, FilenameEnd));
1916
1917 // Finally, if all is good, enter the new file!
1918 EnterSourceFile(FileID, CurDir);
1919}
1920
1921/// HandleIncludeNextDirective - Implements #include_next.
1922///
Chris Lattnerd2177732007-07-20 16:59:19 +00001923void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1925
1926 // #include_next is like #include, except that we start searching after
1927 // the current found directory. If we can't do this, issue a
1928 // diagnostic.
1929 const DirectoryLookup *Lookup = CurDirLookup;
1930 if (isInPrimaryFile()) {
1931 Lookup = 0;
1932 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1933 } else if (Lookup == 0) {
1934 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1935 } else {
1936 // Start looking up in the next directory.
1937 ++Lookup;
1938 }
1939
1940 return HandleIncludeDirective(IncludeNextTok, Lookup);
1941}
1942
1943/// HandleImportDirective - Implements #import.
1944///
Chris Lattnerd2177732007-07-20 16:59:19 +00001945void Preprocessor::HandleImportDirective(Token &ImportTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 Diag(ImportTok, diag::ext_pp_import_directive);
1947
1948 return HandleIncludeDirective(ImportTok, 0, true);
1949}
1950
1951//===----------------------------------------------------------------------===//
1952// Preprocessor Macro Directive Handling.
1953//===----------------------------------------------------------------------===//
1954
1955/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1956/// definition has just been read. Lex the rest of the arguments and the
1957/// closing ), updating MI with what we learn. Return true if an error occurs
1958/// parsing the arg list.
1959bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner25c96482007-07-14 22:46:43 +00001960 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1961
Chris Lattnerd2177732007-07-20 16:59:19 +00001962 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 while (1) {
1964 LexUnexpandedToken(Tok);
1965 switch (Tok.getKind()) {
1966 case tok::r_paren:
1967 // Found the end of the argument list.
Chris Lattner25c96482007-07-14 22:46:43 +00001968 if (Arguments.empty()) { // #define FOO()
1969 MI->setArgumentList(Arguments.begin(), Arguments.end());
1970 return false;
1971 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 // Otherwise we have #define FOO(A,)
1973 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1974 return true;
1975 case tok::ellipsis: // #define X(... -> C99 varargs
1976 // Warn if use of C99 feature in non-C99 mode.
1977 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1978
1979 // Lex the token after the identifier.
1980 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001981 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1983 return true;
1984 }
1985 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner25c96482007-07-14 22:46:43 +00001986 Arguments.push_back(Ident__VA_ARGS__);
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 MI->setIsC99Varargs();
Chris Lattner25c96482007-07-14 22:46:43 +00001988 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 return false;
1990 case tok::eom: // #define X(
1991 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1992 return true;
1993 default:
1994 // Handle keywords and identifiers here to accept things like
1995 // #define Foo(for) for.
1996 IdentifierInfo *II = Tok.getIdentifierInfo();
1997 if (II == 0) {
1998 // #define X(1
1999 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2000 return true;
2001 }
2002
2003 // If this is already used as an argument, it is used multiple times (e.g.
2004 // #define X(A,A.
Chris Lattner25c96482007-07-14 22:46:43 +00002005 if (std::find(Arguments.begin(), Arguments.end(), II) !=
2006 Arguments.end()) { // C99 6.10.3p6
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
2008 return true;
2009 }
2010
2011 // Add the argument to the macro info.
Chris Lattner25c96482007-07-14 22:46:43 +00002012 Arguments.push_back(II);
Reid Spencer5f016e22007-07-11 17:01:13 +00002013
2014 // Lex the token after the identifier.
2015 LexUnexpandedToken(Tok);
2016
2017 switch (Tok.getKind()) {
2018 default: // #define X(A B
2019 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2020 return true;
2021 case tok::r_paren: // #define X(A)
Chris Lattner25c96482007-07-14 22:46:43 +00002022 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 return false;
2024 case tok::comma: // #define X(A,
2025 break;
2026 case tok::ellipsis: // #define X(A... -> GCC extension
2027 // Diagnose extension.
2028 Diag(Tok, diag::ext_named_variadic_macro);
2029
2030 // Lex the token after the identifier.
2031 LexUnexpandedToken(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002032 if (Tok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2034 return true;
2035 }
2036
2037 MI->setIsGNUVarargs();
Chris Lattner25c96482007-07-14 22:46:43 +00002038 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 return false;
2040 }
2041 }
2042 }
2043}
2044
2045/// HandleDefineDirective - Implements #define. This consumes the entire macro
2046/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
2047/// true, then this is a "#define_target", otherwise this is a "#define".
2048///
Chris Lattnerd2177732007-07-20 16:59:19 +00002049void Preprocessor::HandleDefineDirective(Token &DefineTok,
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 bool isTargetSpecific) {
2051 ++NumDefined;
2052
Chris Lattnerd2177732007-07-20 16:59:19 +00002053 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 ReadMacroName(MacroNameTok, 1);
2055
2056 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002057 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 return;
Chris Lattnerc215bd62007-07-14 22:11:41 +00002059
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 // If we are supposed to keep comments in #defines, reenable comment saving
2061 // mode.
2062 CurLexer->KeepCommentMode = KeepMacroComments;
2063
2064 // Create the new macro.
2065 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
2066 if (isTargetSpecific) MI->setIsTargetSpecific();
2067
2068 // If the identifier is an 'other target' macro, clear this bit.
2069 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2070
2071
Chris Lattnerd2177732007-07-20 16:59:19 +00002072 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 LexUnexpandedToken(Tok);
2074
2075 // If this is a function-like macro definition, parse the argument list,
2076 // marking each of the identifiers as being used as macro arguments. Also,
2077 // check other constraints on the first token of the macro body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002078 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // If there is no body to this macro, we have no special handling here.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002080 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 // This is a function-like macro definition. Read the argument list.
2082 MI->setIsFunctionLike();
2083 if (ReadMacroDefinitionArgList(MI)) {
2084 // Forget about MI.
2085 delete MI;
2086 // Throw away the rest of the line.
2087 if (CurLexer->ParsingPreprocessorDirective)
2088 DiscardUntilEndOfDirective();
2089 return;
2090 }
2091
2092 // Read the first token after the arg list for down below.
2093 LexUnexpandedToken(Tok);
2094 } else if (!Tok.hasLeadingSpace()) {
2095 // C99 requires whitespace between the macro definition and the body. Emit
2096 // a diagnostic for something like "#define X+".
2097 if (Features.C99) {
2098 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2099 } else {
2100 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
2101 // one in some cases!
2102 }
2103 } else {
2104 // This is a normal token with leading space. Clear the leading space
2105 // marker on the first token to get proper expansion.
Chris Lattnerd2177732007-07-20 16:59:19 +00002106 Tok.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 }
2108
2109 // If this is a definition of a variadic C99 function-like macro, not using
2110 // the GNU named varargs extension, enabled __VA_ARGS__.
2111
2112 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2113 // This gets unpoisoned where it is allowed.
2114 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2115 if (MI->isC99Varargs())
2116 Ident__VA_ARGS__->setIsPoisoned(false);
2117
2118 // Read the rest of the macro body.
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002119 if (MI->isObjectLike()) {
2120 // Object-like macros are very simple, just read their body.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002121 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002122 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 // Get the next token of the macro.
2124 LexUnexpandedToken(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 }
2126
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002127 } else {
2128 // Otherwise, read the body of a function-like macro. This has to validate
2129 // the # (stringize) operator.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002130 while (Tok.isNot(tok::eom)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002131 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00002132
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002133 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
2134 // parameters in function-like macro expansions.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002135 if (Tok.isNot(tok::hash)) {
Chris Lattnerb5e240f2007-07-14 21:54:03 +00002136 // Get the next token of the macro.
2137 LexUnexpandedToken(Tok);
2138 continue;
2139 }
2140
2141 // Get the next token of the macro.
2142 LexUnexpandedToken(Tok);
2143
2144 // Not a macro arg identifier?
2145 if (!Tok.getIdentifierInfo() ||
2146 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2147 Diag(Tok, diag::err_pp_stringize_not_parameter);
2148 delete MI;
2149
2150 // Disable __VA_ARGS__ again.
2151 Ident__VA_ARGS__->setIsPoisoned(true);
2152 return;
2153 }
2154
2155 // Things look ok, add the param name token to the macro.
2156 MI->AddTokenToBody(Tok);
2157
2158 // Get the next token of the macro.
2159 LexUnexpandedToken(Tok);
2160 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 }
2162
Chris Lattnerc215bd62007-07-14 22:11:41 +00002163
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 // Disable __VA_ARGS__ again.
2165 Ident__VA_ARGS__->setIsPoisoned(true);
2166
2167 // Check that there is no paste (##) operator at the begining or end of the
2168 // replacement list.
2169 unsigned NumTokens = MI->getNumTokens();
2170 if (NumTokens != 0) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002171 if (MI->getReplacementToken(0).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002172 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2173 delete MI;
2174 return;
2175 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002176 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002177 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2178 delete MI;
2179 return;
2180 }
2181 }
2182
2183 // If this is the primary source file, remember that this macro hasn't been
2184 // used yet.
2185 if (isInPrimaryFile())
2186 MI->setIsUsed(false);
2187
2188 // Finally, if this identifier already had a macro defined for it, verify that
2189 // the macro bodies are identical and free the old definition.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002190 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 if (!OtherMI->isUsed())
2192 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2193
2194 // Macros must be identical. This means all tokes and whitespace separation
2195 // must be the same. C99 6.10.3.2.
2196 if (!MI->isIdenticalTo(*OtherMI, *this)) {
2197 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
2198 MacroNameTok.getIdentifierInfo()->getName());
2199 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
2200 }
2201 delete OtherMI;
2202 }
2203
Chris Lattnercc1a8752007-10-07 08:44:20 +00002204 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002205}
2206
2207/// HandleDefineOtherTargetDirective - Implements #define_other_target.
Chris Lattnerd2177732007-07-20 16:59:19 +00002208void Preprocessor::HandleDefineOtherTargetDirective(Token &Tok) {
2209 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 ReadMacroName(MacroNameTok, 1);
2211
2212 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002213 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 return;
2215
2216 // Check to see if this is the last token on the #undef line.
2217 CheckEndOfDirective("#define_other_target");
2218
2219 // If there is already a macro defined by this name, turn it into a
2220 // target-specific define.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002221 if (MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 MI->setIsTargetSpecific(true);
2223 return;
2224 }
2225
2226 // Mark the identifier as being a macro on some other target.
2227 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
2228}
2229
2230
2231/// HandleUndefDirective - Implements #undef.
2232///
Chris Lattnerd2177732007-07-20 16:59:19 +00002233void Preprocessor::HandleUndefDirective(Token &UndefTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 ++NumUndefined;
2235
Chris Lattnerd2177732007-07-20 16:59:19 +00002236 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 ReadMacroName(MacroNameTok, 2);
2238
2239 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002240 if (MacroNameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 return;
2242
2243 // Check to see if this is the last token on the #undef line.
2244 CheckEndOfDirective("#undef");
2245
2246 // Okay, we finally have a valid identifier to undef.
Chris Lattnercc1a8752007-10-07 08:44:20 +00002247 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
Reid Spencer5f016e22007-07-11 17:01:13 +00002248
2249 // #undef untaints an identifier if it were marked by define_other_target.
2250 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
2251
2252 // If the macro is not defined, this is a noop undef, just return.
2253 if (MI == 0) return;
2254
2255 if (!MI->isUsed())
2256 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
2257
2258 // Free macro definition.
2259 delete MI;
Chris Lattnercc1a8752007-10-07 08:44:20 +00002260 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002261}
2262
2263
2264//===----------------------------------------------------------------------===//
2265// Preprocessor Conditional Directive Handling.
2266//===----------------------------------------------------------------------===//
2267
2268/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
2269/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
2270/// if any tokens have been returned or pp-directives activated before this
2271/// #ifndef has been lexed.
2272///
Chris Lattnerd2177732007-07-20 16:59:19 +00002273void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
Reid Spencer5f016e22007-07-11 17:01:13 +00002274 bool ReadAnyTokensBeforeDirective) {
2275 ++NumIf;
Chris Lattnerd2177732007-07-20 16:59:19 +00002276 Token DirectiveTok = Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00002277
Chris Lattnerd2177732007-07-20 16:59:19 +00002278 Token MacroNameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002279 ReadMacroName(MacroNameTok);
2280
2281 // Error reading macro name? If so, diagnostic already issued.
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002282 if (MacroNameTok.is(tok::eom)) {
Chris Lattnerf37bb252007-09-24 05:14:57 +00002283 // Skip code until we get to #endif. This helps with recovery by not
2284 // emitting an error when the #endif is reached.
2285 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2286 /*Foundnonskip*/false, /*FoundElse*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 return;
Chris Lattnerf37bb252007-09-24 05:14:57 +00002288 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002289
2290 // Check to see if this is the last token on the #if[n]def line.
2291 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
2292
2293 // If the start of a top-level #ifdef, inform MIOpt.
2294 if (!ReadAnyTokensBeforeDirective &&
2295 CurLexer->getConditionalStackDepth() == 0) {
2296 assert(isIfndef && "#ifdef shouldn't reach here");
2297 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2298 }
2299
2300 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Chris Lattnercc1a8752007-10-07 08:44:20 +00002301 MacroInfo *MI = getMacroInfo(MII);
Reid Spencer5f016e22007-07-11 17:01:13 +00002302
2303 // If there is a macro, process it.
2304 if (MI) {
2305 // Mark it used.
2306 MI->setIsUsed(true);
2307
2308 // If this is the first use of a target-specific macro, warn about it.
2309 if (MI->isTargetSpecific()) {
2310 MI->setIsTargetSpecific(false); // Don't warn on second use.
2311 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2312 diag::port_target_macro_use);
2313 }
2314 } else {
2315 // Use of a target-specific macro for some other target? If so, warn.
2316 if (MII->isOtherTargetMacro()) {
2317 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2318 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2319 diag::port_target_macro_use);
2320 }
2321 }
2322
2323 // Should we include the stuff contained by this directive?
2324 if (!MI == isIfndef) {
2325 // Yes, remember that we are inside a conditional, then lex the next token.
2326 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
2327 /*foundnonskip*/true, /*foundelse*/false);
2328 } else {
2329 // No, skip the contents of this block and return the first token after it.
2330 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2331 /*Foundnonskip*/false,
2332 /*FoundElse*/false);
2333 }
2334}
2335
2336/// HandleIfDirective - Implements the #if directive.
2337///
Chris Lattnerd2177732007-07-20 16:59:19 +00002338void Preprocessor::HandleIfDirective(Token &IfToken,
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 bool ReadAnyTokensBeforeDirective) {
2340 ++NumIf;
2341
2342 // Parse and evaluation the conditional expression.
2343 IdentifierInfo *IfNDefMacro = 0;
2344 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2345
2346 // Should we include the stuff contained by this directive?
2347 if (ConditionalTrue) {
2348 // If this condition is equivalent to #ifndef X, and if this is the first
2349 // directive seen, handle it for the multiple-include optimization.
2350 if (!ReadAnyTokensBeforeDirective &&
2351 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2352 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2353
2354 // Yes, remember that we are inside a conditional, then lex the next token.
2355 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2356 /*foundnonskip*/true, /*foundelse*/false);
2357 } else {
2358 // No, skip the contents of this block and return the first token after it.
2359 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2360 /*FoundElse*/false);
2361 }
2362}
2363
2364/// HandleEndifDirective - Implements the #endif directive.
2365///
Chris Lattnerd2177732007-07-20 16:59:19 +00002366void Preprocessor::HandleEndifDirective(Token &EndifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 ++NumEndif;
2368
2369 // Check that this is the whole directive.
2370 CheckEndOfDirective("#endif");
2371
2372 PPConditionalInfo CondInfo;
2373 if (CurLexer->popConditionalLevel(CondInfo)) {
2374 // No conditionals on the stack: this is an #endif without an #if.
2375 return Diag(EndifToken, diag::err_pp_endif_without_if);
2376 }
2377
2378 // If this the end of a top-level #endif, inform MIOpt.
2379 if (CurLexer->getConditionalStackDepth() == 0)
2380 CurLexer->MIOpt.ExitTopLevelConditional();
2381
2382 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
2383 "This code should only be reachable in the non-skipping case!");
2384}
2385
2386
Chris Lattnerd2177732007-07-20 16:59:19 +00002387void Preprocessor::HandleElseDirective(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002388 ++NumElse;
2389
2390 // #else directive in a non-skipping conditional... start skipping.
2391 CheckEndOfDirective("#else");
2392
2393 PPConditionalInfo CI;
2394 if (CurLexer->popConditionalLevel(CI))
2395 return Diag(Result, diag::pp_err_else_without_if);
2396
2397 // If this is a top-level #else, inform the MIOpt.
2398 if (CurLexer->getConditionalStackDepth() == 0)
2399 CurLexer->MIOpt.FoundTopLevelElse();
2400
2401 // If this is a #else with a #else before it, report the error.
2402 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2403
2404 // Finally, skip the rest of the contents of this block and return the first
2405 // token after it.
2406 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2407 /*FoundElse*/true);
2408}
2409
Chris Lattnerd2177732007-07-20 16:59:19 +00002410void Preprocessor::HandleElifDirective(Token &ElifToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 ++NumElse;
2412
2413 // #elif directive in a non-skipping conditional... start skipping.
2414 // We don't care what the condition is, because we will always skip it (since
2415 // the block immediately before it was included).
2416 DiscardUntilEndOfDirective();
2417
2418 PPConditionalInfo CI;
2419 if (CurLexer->popConditionalLevel(CI))
2420 return Diag(ElifToken, diag::pp_err_elif_without_if);
2421
2422 // If this is a top-level #elif, inform the MIOpt.
2423 if (CurLexer->getConditionalStackDepth() == 0)
2424 CurLexer->MIOpt.FoundTopLevelElse();
2425
2426 // If this is a #elif with a #else before it, report the error.
2427 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2428
2429 // Finally, skip the rest of the contents of this block and return the first
2430 // token after it.
2431 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2432 /*FoundElse*/CI.FoundElse);
2433}
2434